@tradejs/node 1.0.8 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tradejs/node",
3
- "version": "1.0.8",
3
+ "version": "1.0.10",
4
4
  "description": "Node-only runtime for the TradeJS open-source framework: strategies, backtests, Pine loading, and plugin registries.",
5
5
  "keywords": [
6
6
  "tradejs",
@@ -13,7 +13,7 @@
13
13
  ],
14
14
  "repository": {
15
15
  "type": "git",
16
- "url": "git+https://github.com/tradejs-dev/tradejs.git",
16
+ "url": "https://github.com/TradeJS-Dev/TradeJS",
17
17
  "directory": "packages/node"
18
18
  },
19
19
  "bugs": {
@@ -67,9 +67,9 @@
67
67
  "dependencies": {
68
68
  "@langchain/core": "^1.1.42",
69
69
  "@langchain/openai": "^1.4.5",
70
- "@tradejs/core": "^1.0.8",
71
- "@tradejs/infra": "^1.0.8",
72
- "@tradejs/types": "^1.0.8",
70
+ "@tradejs/core": "^1.0.10",
71
+ "@tradejs/infra": "^1.0.10",
72
+ "@tradejs/types": "^1.0.10",
73
73
  "chalk": "4.1.2",
74
74
  "ioredis": "5.8.0",
75
75
  "pinets": "0.8.12",
@@ -79,7 +79,7 @@
79
79
  "tsconfig-paths": "^4.2.0"
80
80
  },
81
81
  "devDependencies": {
82
- "@types/node": "^20",
82
+ "@types/node": "^24",
83
83
  "tsup": "^8.5.1",
84
84
  "typescript": "^5.1"
85
85
  },
@@ -1,619 +0,0 @@
1
- import {
2
- ensureStrategyPluginsLoaded,
3
- getStrategyManifest
4
- } from "./chunk-WGOYR6AB.mjs";
5
-
6
- // src/ai.ts
7
- import {
8
- DEFAULT_AI_RESPONSE_LANGUAGE,
9
- getAiResponseLanguagePromptName
10
- } from "@tradejs/infra/aiLanguages";
11
- import { setData, redisKeys } from "@tradejs/infra/redis";
12
- import {
13
- getUserSettings
14
- } from "@tradejs/infra/userSettings";
15
-
16
- // src/aiShared.ts
17
- var MAX_AI_SERIES_POINTS = 5;
18
- var trimSeriesDeep = (value) => {
19
- if (Array.isArray(value)) {
20
- const trimmed = value.slice(-MAX_AI_SERIES_POINTS);
21
- const isMatrix = trimmed.every((item) => Array.isArray(item));
22
- if (isMatrix) {
23
- return trimmed;
24
- }
25
- return trimmed.map(
26
- (item) => item && typeof item === "object" ? trimSeriesDeep(item) : item
27
- );
28
- }
29
- if (value && typeof value === "object") {
30
- return Object.fromEntries(
31
- Object.entries(value).map(([key, nested]) => [
32
- key,
33
- trimSeriesDeep(nested)
34
- ])
35
- );
36
- }
37
- return value;
38
- };
39
-
40
- // src/aiMarketContext.ts
41
- var SESSION_WINDOWS = [
42
- { name: "asia", startMinuteUtc: 0, endMinuteUtc: 8 * 60 },
43
- { name: "europe", startMinuteUtc: 7 * 60, endMinuteUtc: 16 * 60 },
44
- { name: "us", startMinuteUtc: 13 * 60, endMinuteUtc: 22 * 60 }
45
- ];
46
- var toRecord = (value) => {
47
- if (!value || typeof value !== "object" || Array.isArray(value)) {
48
- return null;
49
- }
50
- return value;
51
- };
52
- var toFiniteNumber = (value) => {
53
- const numeric = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : Number.NaN;
54
- return Number.isFinite(numeric) ? numeric : null;
55
- };
56
- var getLastFiniteNumber = (value) => {
57
- const numeric = toFiniteNumber(value);
58
- if (numeric != null) {
59
- return numeric;
60
- }
61
- if (!Array.isArray(value)) {
62
- return null;
63
- }
64
- for (let i = value.length - 1; i >= 0; i -= 1) {
65
- const nested = getLastFiniteNumber(value[i]);
66
- if (nested != null) {
67
- return nested;
68
- }
69
- }
70
- return null;
71
- };
72
- var roundTo = (value, decimals) => {
73
- const factor = 10 ** decimals;
74
- return Math.round(value * factor) / factor;
75
- };
76
- var isInsideSession = (minuteUtc, startMinuteUtc, endMinuteUtc) => startMinuteUtc <= endMinuteUtc ? minuteUtc >= startMinuteUtc && minuteUtc < endMinuteUtc : minuteUtc >= startMinuteUtc || minuteUtc < endMinuteUtc;
77
- var buildTradingSessionContext = (timestamp) => {
78
- const date = new Date(timestamp);
79
- const utcHour = date.getUTCHours();
80
- const utcMinute = date.getUTCMinutes();
81
- const minuteUtc = utcHour * 60 + utcMinute;
82
- const activeSessions = SESSION_WINDOWS.filter(
83
- (session) => isInsideSession(minuteUtc, session.startMinuteUtc, session.endMinuteUtc)
84
- ).map((session) => session.name);
85
- const primarySession = activeSessions.includes("us") ? "us" : activeSessions.includes("europe") ? "europe" : activeSessions.includes("asia") ? "asia" : "off_hours";
86
- return {
87
- timezone: "UTC",
88
- utcHour,
89
- utcMinute,
90
- primarySession,
91
- activeSessions,
92
- isOverlap: activeSessions.length > 1,
93
- overlap: activeSessions.length > 1 ? `${activeSessions.join("_")}_overlap` : null
94
- };
95
- };
96
- var buildMissingSpreadContext = () => ({
97
- source: "binance_coinbase_btc",
98
- indicatorKey: "payload.indicators.spread",
99
- available: false,
100
- value: null,
101
- bps: null,
102
- absBps: null,
103
- bias: null,
104
- severity: null
105
- });
106
- var buildSpreadContextFromValue = (spread) => {
107
- const value = roundTo(spread, 8);
108
- const bps = roundTo(value * 1e4, 2);
109
- const absBps = Math.abs(bps);
110
- const bias = Math.abs(bps) < 1 ? "flat" : bps > 0 ? "coinbase_premium" : "binance_premium";
111
- const severity = absBps >= 20 ? "wide" : absBps >= 5 ? "elevated" : "normal";
112
- return {
113
- source: "binance_coinbase_btc",
114
- indicatorKey: "payload.indicators.spread",
115
- available: true,
116
- value,
117
- bps,
118
- absBps,
119
- bias,
120
- severity
121
- };
122
- };
123
- var readSpreadFromSignal = (signal) => {
124
- const indicatorSpread = getLastFiniteNumber(signal.indicators?.spread);
125
- if (indicatorSpread != null) {
126
- return indicatorSpread;
127
- }
128
- return getLastFiniteNumber(signal.additionalIndicators?.spread);
129
- };
130
- var buildAiMarketContext = (signal) => {
131
- const existingMarketContext = toRecord(
132
- signal.additionalIndicators?.marketContext
133
- );
134
- const existingSpread = toRecord(existingMarketContext?.binanceCoinbaseSpread);
135
- const spread = readSpreadFromSignal(signal);
136
- return {
137
- ...existingMarketContext ?? {},
138
- tradingSession: buildTradingSessionContext(signal.timestamp),
139
- binanceCoinbaseSpread: spread != null ? buildSpreadContextFromValue(spread) : existingSpread ?? buildMissingSpreadContext()
140
- };
141
- };
142
-
143
- // src/strategyAdapters/ai.ts
144
- var toRecord2 = (value) => {
145
- if (!value || typeof value !== "object" || Array.isArray(value)) {
146
- return {};
147
- }
148
- return value;
149
- };
150
- var buildBaseAiPayload = (signal) => {
151
- const additionalIndicators = {
152
- ...toRecord2(signal.additionalIndicators),
153
- marketContext: buildAiMarketContext(signal)
154
- };
155
- return {
156
- signal: {
157
- symbol: signal.symbol,
158
- signalId: signal.signalId,
159
- interval: signal.interval,
160
- direction: signal.direction,
161
- timestamp: signal.timestamp,
162
- strategy: signal.strategy,
163
- prices: {
164
- currentPrice: signal.prices.currentPrice,
165
- takeProfitPrice: signal.prices.takeProfitPrice,
166
- stopLossPrice: signal.prices.stopLossPrice
167
- }
168
- },
169
- figures: trimSeriesDeep(signal.figures ?? {}),
170
- indicators: trimSeriesDeep(signal.indicators),
171
- additionalIndicators: trimSeriesDeep(additionalIndicators)
172
- };
173
- };
174
- var defaultAiAdapter = {};
175
- var getStrategyAiAdapter = (strategy) => getStrategyManifest(strategy)?.aiAdapter ?? defaultAiAdapter;
176
- var getSignalAiAdapter = (signal) => getStrategyAiAdapter(signal.strategy);
177
- var buildAiPayloadByStrategy = (signal) => {
178
- const basePayload = buildBaseAiPayload(signal);
179
- const adapter = getSignalAiAdapter(signal);
180
- return adapter.buildPayload?.({ signal, basePayload }) ?? basePayload;
181
- };
182
- var buildAiSystemPromptAddonByStrategy = (signal) => getSignalAiAdapter(signal).buildSystemPromptAddon?.({ signal }) ?? "";
183
- var buildAiHumanPromptAddonByStrategy = (signal, payload) => getSignalAiAdapter(signal).buildHumanPromptAddon?.({
184
- signal,
185
- payload
186
- }) ?? "";
187
- var postProcessAiAnalysisByStrategy = (signal, analysis, payload = buildAiPayloadByStrategy(signal)) => getSignalAiAdapter(signal).postProcessAnalysis?.({
188
- signal,
189
- payload,
190
- analysis
191
- }) ?? analysis;
192
-
193
- // src/ai.ts
194
- var parseAIResponse = (input) => {
195
- try {
196
- if (typeof input === "object" && input !== null) return input;
197
- const match = input.match(/\{[\s\S]*\}/);
198
- if (!match) throw new Error("JSON block not found");
199
- return JSON.parse(match[0]);
200
- } catch (err) {
201
- console.error("Failed to parse AI response:", err);
202
- console.log("Raw AI response:", input);
203
- return {};
204
- }
205
- };
206
- var normalizeResponseContent = (content) => {
207
- if (typeof content === "string" || content && typeof content === "object") {
208
- if (typeof content !== "object" || !Array.isArray(content)) {
209
- return content;
210
- }
211
- }
212
- if (Array.isArray(content)) {
213
- const text = content.map((part) => typeof part?.text === "string" ? part.text : "").join("\n").trim();
214
- return text;
215
- }
216
- return String(content ?? "");
217
- };
218
- var normalizeAnalysis = (raw) => {
219
- const direction = raw?.direction === "LONG" || raw?.direction === "SHORT" ? raw.direction : null;
220
- const qualityNum = typeof raw?.quality === "number" ? Math.max(1, Math.min(5, Math.round(raw.quality))) : void 0;
221
- const toNumberOrNull = (value) => {
222
- if (typeof value === "number" && Number.isFinite(value)) return value;
223
- if (typeof value === "string" && value.trim()) {
224
- const parsed = Number(value);
225
- if (Number.isFinite(parsed)) return parsed;
226
- }
227
- return null;
228
- };
229
- const toText = (value) => typeof value === "string" ? value.slice(0, 400) : void 0;
230
- return {
231
- direction,
232
- quality: qualityNum,
233
- needRetest: Boolean(raw?.needRetest),
234
- retestPrice: toNumberOrNull(raw?.retestPrice),
235
- takeProfitPrice: toNumberOrNull(raw?.takeProfitPrice),
236
- stopLossPrice: toNumberOrNull(raw?.stopLossPrice),
237
- setup: toText(raw?.setup),
238
- confirmations: toText(raw?.confirmations),
239
- btcContext: toText(raw?.btcContext),
240
- retestPlan: toText(raw?.retestPlan),
241
- riskLevels: toText(raw?.riskLevels),
242
- qualityReason: toText(raw?.qualityReason),
243
- triggerInvalidation: toText(raw?.triggerInvalidation),
244
- comment: typeof raw?.comment === "string" ? raw.comment.slice(0, 1024) : ""
245
- };
246
- };
247
- var asRecord = (value) => {
248
- if (!value || typeof value !== "object" || Array.isArray(value)) {
249
- return null;
250
- }
251
- return value;
252
- };
253
- var getSignalDirection = (signal) => signal.direction === "LONG" || signal.direction === "SHORT" ? signal.direction : null;
254
- var getDeterministicQuality = (gateContext) => {
255
- const deterministicQuality = Number(gateContext?.deterministicQuality);
256
- if (Number.isFinite(deterministicQuality)) {
257
- return Math.max(1, Math.min(5, Math.round(deterministicQuality)));
258
- }
259
- const maxAllowedQuality = Number(gateContext?.maxAllowedQuality);
260
- if (Number.isFinite(maxAllowedQuality)) {
261
- return Math.max(1, Math.min(5, Math.round(maxAllowedQuality)));
262
- }
263
- return Array.isArray(gateContext?.structuralHardBlockReasons) && gateContext.structuralHardBlockReasons.length > 0 ? 2 : 3;
264
- };
265
- var buildAiSystemPrompt = (signal) => `
266
- You are an internal market-structure classifier for an already computed system signal.
267
- Analyze the provided JSON containing the trade, candles, indicators (for the coin and BTC across multiple timeframes), and strategy figures/context.
268
- Series data is already trimmed to the latest 5 values.
269
-
270
- Important:
271
- - Do not invent missing data.
272
- - This is an internal audit/classification task, not user-facing trading advice.
273
- - Do not generate execution instructions, do not replace the original thesis with a new one, and do not provide personalized investment advice.
274
- - Use the original signal direction and levels as the anchor, but you may state that the current structure does not support them.
275
- - Respect the source strategy specified in \`signal.strategy\`.
276
- - Your goal is to explain how well the observed structure matches the existing signal and how structurally confirmed it is right now.
277
- - Do not write vague statements like "there is momentum/slope" without tying them to the decision.
278
- - Write all user-visible text fields in the requested response language. If no explicit language instruction is provided later, default to English.
279
- - If confidence is incomplete, prefer cautious wording such as "likely", "not confirmed yet", or "probably" instead of categorical claims.
280
-
281
- Return exactly one JSON object and nothing else:
282
-
283
- {
284
- "direction": payload.signal.direction | null,
285
- "quality": 1 | 2 | 3 | 4 | 5,
286
- "needRetest": boolean,
287
- "retestPrice": number | null,
288
- "takeProfitPrice": number | null,
289
- "stopLossPrice": number | null,
290
- "setup": string,
291
- "confirmations": string,
292
- "btcContext": string,
293
- "retestPlan": string,
294
- "riskLevels": string,
295
- "qualityReason": string,
296
- "triggerInvalidation": string
297
- }
298
-
299
- - Do not add any other fields.
300
- - All numbers must be finite, with no \`NaN\` or \`Infinity\`.
301
- - All text fields must be short strings with no line breaks and no markdown lists.
302
- - \`direction\` is not a new trade idea. It is only a compatibility flag for the existing signal: either exactly \`payload.signal.direction\` or \`null\` if the current structure does not confirm that signal. Never propose the opposite direction.
303
- - \`quality\` is the structural confirmation level of the current signal right now, including timing and confirmations. It is not a general attractiveness score and not investment advice.
304
- - \`needRetest\` indicates whether an additional confirmation level is required before the current signal can be treated as structurally confirmed.
305
- - \`retestPrice\` is the key level that would confirm or invalidate the structure, or \`null\` if no extra level is needed or available.
306
- - \`takeProfitPrice\` and \`stopLossPrice\` must not be newly invented levels. If the levels already supplied in \`payload.signal.prices\` still look internally coherent relative to the current price and the confirmed signal, you may return them as an audit of existing levels; otherwise return \`null\`.
307
- - Use these fields as separate parts of the analysis:
308
- - \`setup\`: the current structural setup or trendline state.
309
- - \`confirmations\`: 2-4 concrete confirmations or conflicts from the coin indicators.
310
- - \`btcContext\`: whether BTC supports the idea, is neutral, or conflicts with it.
311
- - \`retestPlan\`: what must happen at the key level to confirm the structure, or why no extra level is needed.
312
- - \`riskLevels\`: a short note on whether the existing levels and risk structure are internally coherent, without creating a new trade plan.
313
- - \`qualityReason\`: why the quality score is what it is.
314
- - \`triggerInvalidation\`: what must happen to confirm the signal or what invalidates the current structural thesis.
315
- - \`comment\` is optional. If you include it, do not just duplicate the structured fields.
316
-
317
- If the data is insufficient or the setup is weak, return \`"direction": null\`, \`quality <= 2\`, and explain why.
318
-
319
- Input payload structure:
320
- - payload.signal:
321
- symbol, signalId, interval, direction, timestamp, strategy, prices
322
- - payload.signal.prices:
323
- currentPrice, takeProfitPrice, stopLossPrice
324
- - payload.figures:
325
- strategy-specific figures or geometry when available. Fields vary by strategy.
326
- - payload.indicators:
327
- indicator dictionaries and series for the coin and BTC; all series are already trimmed to the latest 5 values.
328
- - payload.additionalIndicators:
329
- strategy-specific summary/context fields. This is not noise; it contains derived fields deliberately passed by the strategy to help the decision.
330
- Examples: helperFlags, structureContext, spread, correlation, volatilitySummary.
331
- Always inspect \`payload.additionalIndicators.marketContext\` when present:
332
- \u2022 \`marketContext.tradingSession\`: UTC session at signal time: asia / europe / us / overlap / off_hours.
333
- \u2022 \`marketContext.binanceCoinbaseSpread\`: BTC spread between Coinbase and Binance from \`payload.indicators.spread\`; \`value=(Coinbase-Binance)/Binance\`, \`bps=value*10000\`.
334
- If those fields exist, use them as a more explicit hint instead of trying to re-derive the same idea from raw lines or points.
335
- If \`derivativesContext\` exists, it is a derived Coinalyze summary for the time of the signal. Coinalyze context is built only from \`BTCUSDT\` and \`ETHUSDT\` reference symbols, not for every target coin. \`targetSymbol\` is just the source signal coin. Use BTC/ETH open interest, funding, liquidations, and pressure/riskFlags as positioning context, not as an independent trade idea.
336
- Key patterns:
337
- \u2022 coin: \`maFast\`, \`atrPct\`, \`macd...\`, \`candles15m/candles1h/candles4h/candles1d\`, and \`*1h/*4h/*1d\`
338
- \u2022 BTC: \`btcMaFast\`, \`btcAtr\`, \`btcMacd...\`, \`btcCandles*\`, and \`btc*1h/*4h/*1d\`
339
- \u2022 strategy service keys are possible as well, for example \`correlation\`, \`spread\`, \`touches\`, \`distance\`
340
-
341
- How to analyze, in order:
342
- 1. Start with price structure and the setup geometry or context in \`payload.figures\`. This has higher priority than indicators.
343
- 2. Then use \`payload.additionalIndicators\` when it contains explicit strategy-specific context such as line state, spread, correlation, and similar fields.
344
- 3. Then assess confirmation or conflict from the current coin indicators.
345
- 4. Then evaluate BTC context.
346
- 5. Only after that choose \`direction\`, \`quality\`, and whether an extra confirmation level is required.
347
- 6. If strong conflicts exist, reduce quality or set direction to \`null\`.
348
-
349
- Explicit conflict rules:
350
- - If the figure or price structure is invalid or doubtful, indicators must not rescue the setup.
351
- - If strategy-specific helper fields explicitly say the signal is not confirmed yet, lacks margin, or requires waiting, do not overstate quality.
352
- - If the structure is acceptable but BTC or key indicators noticeably conflict, quality is usually \`<= 3\`.
353
- - If \`derivativesContext.referenceContexts\` exists, check \`primaryReferenceSymbol\` first, then compare \`BTCUSDT\` and \`ETHUSDT\` as broad-market derivatives context. Do not search for Coinalyze data for \`targetSymbol\` unless \`targetSymbol\` itself is \`BTCUSDT\` or \`ETHUSDT\`.
354
- - If \`derivativesContext.summary.riskFlags\` contains \`crowded_long\` for a LONG or \`crowded_short\` for a SHORT, treat that as crowded positioning and do not overstate quality without strong structural confirmation.
355
- - If \`derivativesContext.summary.directionAligned=false\`, explicitly mention the derivatives conflict in \`confirmations\` or \`qualityReason\`.
356
- - If \`derivativesContext\` is absent, stale, or \`missing_derivatives\`, do not infer Coinalyze conclusions and do not penalize the signal just because that data is missing.
357
- - If \`marketContext.tradingSession\` exists, treat the session as a liquidity and volatility regime: asia is often thinner, europe/us are more active, and overlaps can amplify both momentum and noise. Do not reject a signal solely because of session, but mention clear session support or conflict in \`confirmations\` or \`qualityReason\`.
358
- - If \`marketContext.binanceCoinbaseSpread.available=true\` and \`severity=elevated/wide\`, treat it as cross-exchange divergence or BTC liquidity risk. Do not use the spread as a standalone long/short signal, but reduce confidence or require more confirmation when the rest of the structure is weak or BTC context conflicts.
359
- - If \`marketContext.binanceCoinbaseSpread\` is missing or \`available=false\`, do not infer anything from Binance/Coinbase spread and do not penalize the signal just because it is absent.
360
- - If the current signal is not confirmed (\`direction=null\`), name the main reason briefly in \`comment\`.
361
- If you use the structured fields, include the main reason in \`qualityReason\` or \`triggerInvalidation\`.
362
-
363
- Rules for \`direction\` / TP / SL:
364
- - \`direction = LONG\` only if the data confirms the existing LONG signal; \`SHORT\` only if the data confirms the existing SHORT signal; otherwise \`null\`.
365
- - For LONG, the expected relation is usually \`stopLossPrice < currentPrice < takeProfitPrice\`.
366
- - For SHORT, the expected relation is usually \`takeProfitPrice < currentPrice < stopLossPrice\`.
367
- - Do not optimize or recalculate TP/SL for a "better trade"; only assess whether the already supplied levels are coherent.
368
- - If \`direction = null\`, then \`takeProfitPrice = null\` and \`stopLossPrice = null\`.
369
- - If \`needRetest = false\`, then \`retestPrice = null\`.
370
- - If \`needRetest = true\`, \`retestPrice\` must be a finite number tied to a meaningful retest or breakout level.
371
- - Before responding, sanity-check the consistency of \`direction\`, TP/SL, and the current price.
372
-
373
- Quality scale:
374
- - 1: poor or chaotic setup, strong conflicts, signal not structurally confirmed
375
- - 2: weak setup, few confirmations, more of a watch or reject
376
- - 3: average setup, some structure exists, but notable conflicts remain
377
- - 4: good setup, several confirmations, structure is mostly coherent
378
- - 5: very strong setup, clean structure, confirmations, and internally coherent levels
379
-
380
- Requirements for useful structured analysis:
381
- - Include 2-4 concrete factors for or against confirmation in \`confirmations\`.
382
- - Explicitly mention the role of the key figure or structural state, for example breakout, retest, false break, touch, or lack of confirmation.
383
- - Explicitly mention BTC context as supportive, neutral, or conflicting.
384
- - Explain why the quality score is what it is.
385
- - If the signal is not confirmed (\`direction=null\`), state clearly what must change for confirmation.
386
- - In \`retestPlan\`, avoid technical placeholders like \`needRetest=false @ null\`; write a human explanation.
387
- - Do not simply restate JSON fields; add interpretation and decision logic.
388
-
389
- Rules for using trimmed series (last 5 values):
390
- - Do not make strong long-term conclusions from only 5 points.
391
- - Use 4h and 1d series as brief context, not full history.
392
- - If the data is too limited for confidence, reduce quality and use cautious wording.
393
-
394
- Short few-shot examples:
395
- {"direction":"LONG","quality":4,"needRetest":true,"retestPrice":100.2,"takeProfitPrice":101.5,"stopLossPrice":98.9,"setup":"Likely trendline breakout upward, but the signal still needs a level check for confirmation.","confirmations":"The coin shows momentum support without obvious overheating, but confirmation is not fully clean yet.","btcContext":"BTC is neutral-to-supportive and does not conflict with the current LONG signal.","retestPlan":"The key level is 100.2; holding above it would confirm the signal structure.","riskLevels":"The supplied TP and SL remain on the correct sides of the current price and still look internally coherent.","qualityReason":"Quality=4 because the structure is solid, but an extra level confirmation is still preferable.","triggerInvalidation":"The structure confirms on a hold above the level and weakens on a move back under the line."}
396
- {"direction":null,"quality":2,"needRetest":false,"retestPrice":null,"takeProfitPrice":null,"stopLossPrice":null,"setup":"Touch or noise around the trendline without a convincing breakout.","confirmations":"Indicators are mixed and do not provide strong structural support.","btcContext":"BTC is either conflicting or not supportive of the current thesis.","retestPlan":"It is too early to define an extra level because a quality breakout is not present yet.","riskLevels":"The supplied levels should not be treated as confirmed while the structure remains weak.","qualityReason":"Quality=2 because timing is weak and confirmations are limited.","triggerInvalidation":"Wait for a clear breakout and confirmation from both the coin and BTC."}
397
-
398
- Return only the JSON object, with no extra characters.
399
- ${signal ? buildAiSystemPromptAddonByStrategy(signal) : ""}
400
- `;
401
- var buildAiPayload = (signal) => buildAiPayloadByStrategy(signal);
402
- var getDeterministicAiGateContext = (payload) => {
403
- const additionalIndicators = asRecord(payload.additionalIndicators);
404
- const candidates = [
405
- additionalIndicators,
406
- ...Object.values(additionalIndicators ?? {}).map(asRecord)
407
- ].filter((value) => Boolean(value));
408
- return candidates.find(
409
- (candidate) => Array.isArray(candidate.structuralHardBlockReasons) || typeof candidate.approvalAllowedNow === "boolean"
410
- ) ?? null;
411
- };
412
- var buildAiHumanPrompt = (signal, payload = buildAiPayload(signal)) => `
413
- Analyze the already computed internal signal for ${signal.symbol}. The original signal direction is ${signal.direction}.
414
- This is a structure-classification and audit task, not execution advice. Determine whether the current structure confirms the existing signal, how structurally coherent it is right now, whether an extra confirmation level is needed, and whether the already supplied levels in \`payload.signal.prices\` still look internally coherent. Do not replace the original thesis with a new one and do not invent new levels; return only the requested JSON.
415
-
416
- Trade payload:
417
- ${JSON.stringify(payload)}
418
- ${buildAiHumanPromptAddonByStrategy(signal, payload)}
419
- `;
420
- var DEFAULT_AI_MODEL = "openai/gpt-5-mini";
421
- var userSettingsCache = /* @__PURE__ */ new Map();
422
- var aiModelCache = /* @__PURE__ */ new Map();
423
- var getAiModelCacheKey = (userName, modelName) => `${userName}::${modelName}`;
424
- var resolveAiModelName = (settings, requestedModelName) => {
425
- const explicitModelName = typeof requestedModelName === "string" ? requestedModelName.trim() : "";
426
- if (explicitModelName) {
427
- return explicitModelName;
428
- }
429
- const settingsModelName = typeof settings.AI_MODEL === "string" ? settings.AI_MODEL.trim() : "";
430
- return settingsModelName || DEFAULT_AI_MODEL;
431
- };
432
- var getOpenRouterModelKwargs = (apiEndpoint) => {
433
- const endpoint = String(apiEndpoint ?? "").trim();
434
- if (!endpoint) {
435
- return {};
436
- }
437
- let hostname = "";
438
- try {
439
- hostname = new URL(endpoint).hostname;
440
- } catch {
441
- hostname = endpoint;
442
- }
443
- if (!hostname.toLowerCase().includes("openrouter")) {
444
- return {};
445
- }
446
- return {
447
- provider: {
448
- ignore: ["azure"]
449
- }
450
- };
451
- };
452
- var getAiSettings = async (userName = "root") => {
453
- let settingsPromise = userSettingsCache.get(userName);
454
- if (!settingsPromise) {
455
- settingsPromise = getUserSettings(userName);
456
- settingsPromise.catch(() => {
457
- userSettingsCache.delete(userName);
458
- });
459
- userSettingsCache.set(userName, settingsPromise);
460
- }
461
- const settings = await settingsPromise;
462
- if (!settings.AI_API_KEY || !settings.AI_API_ENDPOINT) {
463
- throw new Error(`AI settings are incomplete for user ${userName}`);
464
- }
465
- return settings;
466
- };
467
- var createAiModel = async (userName = "root", requestedModelName) => {
468
- const settings = await getAiSettings(userName);
469
- const modelName = resolveAiModelName(settings, requestedModelName);
470
- const cacheKey = getAiModelCacheKey(userName, modelName);
471
- let modelPromise = aiModelCache.get(cacheKey);
472
- if (!modelPromise) {
473
- modelPromise = (async () => {
474
- const { ChatOpenAI } = await import("@langchain/openai");
475
- const modelKwargs = getOpenRouterModelKwargs(settings.AI_API_ENDPOINT);
476
- return new ChatOpenAI({
477
- temperature: 0.2,
478
- modelName,
479
- apiKey: settings.AI_API_KEY,
480
- ...Object.keys(modelKwargs).length ? { modelKwargs } : {},
481
- configuration: {
482
- baseURL: settings.AI_API_ENDPOINT,
483
- defaultHeaders: {
484
- "HTTP-Referer": "https://tradejs.dev",
485
- "X-Title": "Inv"
486
- }
487
- }
488
- });
489
- })();
490
- modelPromise.catch(() => {
491
- aiModelCache.delete(cacheKey);
492
- });
493
- aiModelCache.set(cacheKey, modelPromise);
494
- }
495
- return modelPromise;
496
- };
497
- var getAiModel = async (userName = "root", requestedModelName) => {
498
- const settings = await getAiSettings(userName);
499
- const resolvedModelName = resolveAiModelName(settings, requestedModelName);
500
- try {
501
- return await createAiModel(userName, resolvedModelName);
502
- } catch (error) {
503
- aiModelCache.delete(getAiModelCacheKey(userName, resolvedModelName));
504
- userSettingsCache.delete(userName);
505
- throw error;
506
- }
507
- };
508
- var resetAiRuntimeCache = () => {
509
- aiModelCache.clear();
510
- userSettingsCache.clear();
511
- };
512
- var ensureAiStrategyPluginsLoaded = async () => {
513
- await ensureStrategyPluginsLoaded();
514
- };
515
- var buildAiPrompts = (signal) => {
516
- const payload = buildAiPayload(signal);
517
- return {
518
- systemPrompt: buildAiSystemPrompt(signal),
519
- humanPrompt: buildAiHumanPrompt(signal, payload)
520
- };
521
- };
522
- var runAiPrompt = async ({ systemPrompt, humanPrompt }, options = {}) => {
523
- if (options.signal) {
524
- await ensureAiStrategyPluginsLoaded();
525
- }
526
- const [{ HumanMessage, SystemMessage }, model, settings] = await Promise.all([
527
- import("@langchain/core/messages"),
528
- getAiModel(options.userName, options.model),
529
- getAiSettings(options.userName)
530
- ]);
531
- const messages = [];
532
- const responseLanguage = getAiResponseLanguagePromptName(
533
- settings.AI_RESPONSE_LANGUAGE || DEFAULT_AI_RESPONSE_LANGUAGE
534
- );
535
- messages.push(new SystemMessage(systemPrompt));
536
- messages.push(
537
- new SystemMessage(
538
- `Write all user-visible text fields in ${responseLanguage}. Keep field names and JSON syntax unchanged.`
539
- )
540
- );
541
- messages.push(
542
- new HumanMessage({
543
- content: [
544
- {
545
- type: "text",
546
- text: humanPrompt
547
- }
548
- ]
549
- })
550
- );
551
- const response = await model.invoke(messages);
552
- const parsed = parseAIResponse(
553
- normalizeResponseContent(response.content)
554
- );
555
- const normalized = normalizeAnalysis(parsed);
556
- if (!options.signal) {
557
- return normalized;
558
- }
559
- return postProcessAiAnalysisByStrategy(
560
- options.signal,
561
- normalized,
562
- options.payload
563
- );
564
- };
565
- var runAiPromptLocal = async (signal, options = {}) => {
566
- await ensureAiStrategyPluginsLoaded();
567
- const payload = options.payload ?? buildAiPayload(signal);
568
- const gateContext = getDeterministicAiGateContext(payload);
569
- const signalDirection = getSignalDirection(signal);
570
- const deterministicQuality = getDeterministicQuality(gateContext);
571
- const approvalAllowedNow = typeof gateContext?.approvalAllowedNow === "boolean" ? gateContext.approvalAllowedNow : deterministicQuality >= 4;
572
- return postProcessAiAnalysisByStrategy(
573
- signal,
574
- {
575
- direction: approvalAllowedNow ? signalDirection : null,
576
- quality: deterministicQuality,
577
- needRetest: !approvalAllowedNow,
578
- retestPrice: null,
579
- takeProfitPrice: approvalAllowedNow ? signal.prices?.takeProfitPrice ?? null : null,
580
- stopLossPrice: approvalAllowedNow ? signal.prices?.stopLossPrice ?? null : null
581
- },
582
- payload
583
- );
584
- };
585
- var askAI = async (signal, options = {}) => {
586
- const { symbol } = signal;
587
- await ensureAiStrategyPluginsLoaded();
588
- const payload = buildAiPayload(signal);
589
- const content = await runAiPrompt(
590
- {
591
- systemPrompt: buildAiSystemPrompt(signal),
592
- humanPrompt: buildAiHumanPrompt(signal, payload)
593
- },
594
- {
595
- ...options,
596
- signal,
597
- payload
598
- }
599
- );
600
- await setData(redisKeys.analysis(symbol, signal.signalId), content);
601
- return content;
602
- };
603
-
604
- export {
605
- MAX_AI_SERIES_POINTS,
606
- trimSeriesDeep,
607
- buildAiSystemPrompt,
608
- buildAiPayload,
609
- getDeterministicAiGateContext,
610
- buildAiHumanPrompt,
611
- DEFAULT_AI_MODEL,
612
- getOpenRouterModelKwargs,
613
- resetAiRuntimeCache,
614
- ensureAiStrategyPluginsLoaded,
615
- buildAiPrompts,
616
- runAiPrompt,
617
- runAiPromptLocal,
618
- askAI
619
- };