@tradejs/node 1.0.6 → 1.0.8
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/dist/ai.js +274 -126
- package/dist/ai.mjs +3 -3
- package/dist/backtest.js +345 -42
- package/dist/backtest.mjs +98 -16
- package/dist/chunk-2JKX3DM7.mjs +619 -0
- package/dist/{chunk-XW5L327F.mjs → chunk-JMDYEKIO.mjs} +1 -1
- package/dist/chunk-JRRG3YQG.mjs +154 -0
- package/dist/{chunk-CGJ2UU6H.mjs → chunk-JU77QVJ3.mjs} +8 -1
- package/dist/{chunk-SCMBUEGK.mjs → chunk-KMJQQ53K.mjs} +1 -1
- package/dist/{chunk-GKDBAF3A.mjs → chunk-KZDHZ56N.mjs} +25 -7
- package/dist/{chunk-EOZSJKUM.mjs → chunk-WGOYR6AB.mjs} +1 -1
- package/dist/cli.d.mts +20 -2
- package/dist/cli.d.ts +20 -2
- package/dist/cli.js +456 -183
- package/dist/cli.mjs +155 -49
- package/dist/connectors.js +6 -1
- package/dist/connectors.mjs +2 -2
- package/dist/constants.js +1 -1
- package/dist/constants.mjs +1 -1
- package/dist/registry.js +6 -1
- package/dist/registry.mjs +2 -2
- package/dist/strategies.d.mts +24 -9
- package/dist/strategies.d.ts +24 -9
- package/dist/strategies.js +7465 -6467
- package/dist/strategies.mjs +865 -140
- package/package.json +6 -6
- package/dist/chunk-72FKXJ2I.mjs +0 -473
- package/dist/chunk-PQH5PAFC.mjs +0 -49
package/dist/ai.js
CHANGED
|
@@ -46,6 +46,7 @@ __export(ai_exports, {
|
|
|
46
46
|
trimSeriesDeep: () => trimSeriesDeep
|
|
47
47
|
});
|
|
48
48
|
module.exports = __toCommonJS(ai_exports);
|
|
49
|
+
var import_aiLanguages = require("@tradejs/infra/aiLanguages");
|
|
49
50
|
var import_redis = require("@tradejs/infra/redis");
|
|
50
51
|
var import_userSettings = require("@tradejs/infra/userSettings");
|
|
51
52
|
|
|
@@ -73,6 +74,109 @@ var trimSeriesDeep = (value) => {
|
|
|
73
74
|
return value;
|
|
74
75
|
};
|
|
75
76
|
|
|
77
|
+
// src/aiMarketContext.ts
|
|
78
|
+
var SESSION_WINDOWS = [
|
|
79
|
+
{ name: "asia", startMinuteUtc: 0, endMinuteUtc: 8 * 60 },
|
|
80
|
+
{ name: "europe", startMinuteUtc: 7 * 60, endMinuteUtc: 16 * 60 },
|
|
81
|
+
{ name: "us", startMinuteUtc: 13 * 60, endMinuteUtc: 22 * 60 }
|
|
82
|
+
];
|
|
83
|
+
var toRecord = (value) => {
|
|
84
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
return value;
|
|
88
|
+
};
|
|
89
|
+
var toFiniteNumber = (value) => {
|
|
90
|
+
const numeric = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : Number.NaN;
|
|
91
|
+
return Number.isFinite(numeric) ? numeric : null;
|
|
92
|
+
};
|
|
93
|
+
var getLastFiniteNumber = (value) => {
|
|
94
|
+
const numeric = toFiniteNumber(value);
|
|
95
|
+
if (numeric != null) {
|
|
96
|
+
return numeric;
|
|
97
|
+
}
|
|
98
|
+
if (!Array.isArray(value)) {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
for (let i = value.length - 1; i >= 0; i -= 1) {
|
|
102
|
+
const nested = getLastFiniteNumber(value[i]);
|
|
103
|
+
if (nested != null) {
|
|
104
|
+
return nested;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return null;
|
|
108
|
+
};
|
|
109
|
+
var roundTo = (value, decimals) => {
|
|
110
|
+
const factor = 10 ** decimals;
|
|
111
|
+
return Math.round(value * factor) / factor;
|
|
112
|
+
};
|
|
113
|
+
var isInsideSession = (minuteUtc, startMinuteUtc, endMinuteUtc) => startMinuteUtc <= endMinuteUtc ? minuteUtc >= startMinuteUtc && minuteUtc < endMinuteUtc : minuteUtc >= startMinuteUtc || minuteUtc < endMinuteUtc;
|
|
114
|
+
var buildTradingSessionContext = (timestamp) => {
|
|
115
|
+
const date = new Date(timestamp);
|
|
116
|
+
const utcHour = date.getUTCHours();
|
|
117
|
+
const utcMinute = date.getUTCMinutes();
|
|
118
|
+
const minuteUtc = utcHour * 60 + utcMinute;
|
|
119
|
+
const activeSessions = SESSION_WINDOWS.filter(
|
|
120
|
+
(session) => isInsideSession(minuteUtc, session.startMinuteUtc, session.endMinuteUtc)
|
|
121
|
+
).map((session) => session.name);
|
|
122
|
+
const primarySession = activeSessions.includes("us") ? "us" : activeSessions.includes("europe") ? "europe" : activeSessions.includes("asia") ? "asia" : "off_hours";
|
|
123
|
+
return {
|
|
124
|
+
timezone: "UTC",
|
|
125
|
+
utcHour,
|
|
126
|
+
utcMinute,
|
|
127
|
+
primarySession,
|
|
128
|
+
activeSessions,
|
|
129
|
+
isOverlap: activeSessions.length > 1,
|
|
130
|
+
overlap: activeSessions.length > 1 ? `${activeSessions.join("_")}_overlap` : null
|
|
131
|
+
};
|
|
132
|
+
};
|
|
133
|
+
var buildMissingSpreadContext = () => ({
|
|
134
|
+
source: "binance_coinbase_btc",
|
|
135
|
+
indicatorKey: "payload.indicators.spread",
|
|
136
|
+
available: false,
|
|
137
|
+
value: null,
|
|
138
|
+
bps: null,
|
|
139
|
+
absBps: null,
|
|
140
|
+
bias: null,
|
|
141
|
+
severity: null
|
|
142
|
+
});
|
|
143
|
+
var buildSpreadContextFromValue = (spread) => {
|
|
144
|
+
const value = roundTo(spread, 8);
|
|
145
|
+
const bps = roundTo(value * 1e4, 2);
|
|
146
|
+
const absBps = Math.abs(bps);
|
|
147
|
+
const bias = Math.abs(bps) < 1 ? "flat" : bps > 0 ? "coinbase_premium" : "binance_premium";
|
|
148
|
+
const severity = absBps >= 20 ? "wide" : absBps >= 5 ? "elevated" : "normal";
|
|
149
|
+
return {
|
|
150
|
+
source: "binance_coinbase_btc",
|
|
151
|
+
indicatorKey: "payload.indicators.spread",
|
|
152
|
+
available: true,
|
|
153
|
+
value,
|
|
154
|
+
bps,
|
|
155
|
+
absBps,
|
|
156
|
+
bias,
|
|
157
|
+
severity
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
var readSpreadFromSignal = (signal) => {
|
|
161
|
+
const indicatorSpread = getLastFiniteNumber(signal.indicators?.spread);
|
|
162
|
+
if (indicatorSpread != null) {
|
|
163
|
+
return indicatorSpread;
|
|
164
|
+
}
|
|
165
|
+
return getLastFiniteNumber(signal.additionalIndicators?.spread);
|
|
166
|
+
};
|
|
167
|
+
var buildAiMarketContext = (signal) => {
|
|
168
|
+
const existingMarketContext = toRecord(
|
|
169
|
+
signal.additionalIndicators?.marketContext
|
|
170
|
+
);
|
|
171
|
+
const existingSpread = toRecord(existingMarketContext?.binanceCoinbaseSpread);
|
|
172
|
+
const spread = readSpreadFromSignal(signal);
|
|
173
|
+
return {
|
|
174
|
+
...existingMarketContext ?? {},
|
|
175
|
+
tradingSession: buildTradingSessionContext(signal.timestamp),
|
|
176
|
+
binanceCoinbaseSpread: spread != null ? buildSpreadContextFromValue(spread) : existingSpread ?? buildMissingSpreadContext()
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
|
|
76
180
|
// src/strategy/manifests.ts
|
|
77
181
|
var import_indicators = require("@tradejs/core/indicators");
|
|
78
182
|
var import_logger2 = require("@tradejs/infra/logger");
|
|
@@ -82,6 +186,7 @@ var import_fs = __toESM(require("fs"));
|
|
|
82
186
|
var import_path = __toESM(require("path"));
|
|
83
187
|
var import_module = require("module");
|
|
84
188
|
var import_url = require("url");
|
|
189
|
+
var import_config = require("@tradejs/core/config");
|
|
85
190
|
var import_logger = require("@tradejs/infra/logger");
|
|
86
191
|
var CONFIG_FILE_NAMES = [
|
|
87
192
|
"tradejs.config.ts",
|
|
@@ -114,10 +219,14 @@ var normalizeConfig = (rawConfig) => {
|
|
|
114
219
|
const strategies2 = Array.isArray(config.strategies) ? config.strategies.map((value) => String(value || "").trim()).filter(Boolean) : [];
|
|
115
220
|
const indicators = Array.isArray(config.indicators) ? config.indicators.map((value) => String(value || "").trim()).filter(Boolean) : [];
|
|
116
221
|
const connectors = Array.isArray(config.connectors) ? config.connectors.map((value) => String(value || "").trim()).filter(Boolean) : [];
|
|
222
|
+
const hooks = (0, import_config.normalizeTradejsConfigHooks)(
|
|
223
|
+
config.hooks
|
|
224
|
+
);
|
|
117
225
|
return {
|
|
118
226
|
strategies: strategies2,
|
|
119
227
|
indicators,
|
|
120
|
-
connectors
|
|
228
|
+
connectors,
|
|
229
|
+
...hooks ? { hooks } : {}
|
|
121
230
|
};
|
|
122
231
|
};
|
|
123
232
|
var getRequireFn = (cwd = getTradejsProjectCwd()) => (0, import_module.createRequire)(import_path.default.join(import_path.default.resolve(cwd), "__tradejs_loader__.js"));
|
|
@@ -487,24 +596,36 @@ var strategies = new Proxy(
|
|
|
487
596
|
);
|
|
488
597
|
|
|
489
598
|
// src/strategyAdapters/ai.ts
|
|
490
|
-
var
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
599
|
+
var toRecord2 = (value) => {
|
|
600
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
601
|
+
return {};
|
|
602
|
+
}
|
|
603
|
+
return value;
|
|
604
|
+
};
|
|
605
|
+
var buildBaseAiPayload = (signal) => {
|
|
606
|
+
const additionalIndicators = {
|
|
607
|
+
...toRecord2(signal.additionalIndicators),
|
|
608
|
+
marketContext: buildAiMarketContext(signal)
|
|
609
|
+
};
|
|
610
|
+
return {
|
|
611
|
+
signal: {
|
|
612
|
+
symbol: signal.symbol,
|
|
613
|
+
signalId: signal.signalId,
|
|
614
|
+
interval: signal.interval,
|
|
615
|
+
direction: signal.direction,
|
|
616
|
+
timestamp: signal.timestamp,
|
|
617
|
+
strategy: signal.strategy,
|
|
618
|
+
prices: {
|
|
619
|
+
currentPrice: signal.prices.currentPrice,
|
|
620
|
+
takeProfitPrice: signal.prices.takeProfitPrice,
|
|
621
|
+
stopLossPrice: signal.prices.stopLossPrice
|
|
622
|
+
}
|
|
623
|
+
},
|
|
624
|
+
figures: trimSeriesDeep(signal.figures ?? {}),
|
|
625
|
+
indicators: trimSeriesDeep(signal.indicators),
|
|
626
|
+
additionalIndicators: trimSeriesDeep(additionalIndicators)
|
|
627
|
+
};
|
|
628
|
+
};
|
|
508
629
|
var defaultAiAdapter = {};
|
|
509
630
|
var getStrategyAiAdapter = (strategy) => getStrategyManifest(strategy)?.aiAdapter ?? defaultAiAdapter;
|
|
510
631
|
var getSignalAiAdapter = (signal) => getStrategyAiAdapter(signal.strategy);
|
|
@@ -532,8 +653,8 @@ var parseAIResponse = (input) => {
|
|
|
532
653
|
if (!match) throw new Error("JSON block not found");
|
|
533
654
|
return JSON.parse(match[0]);
|
|
534
655
|
} catch (err) {
|
|
535
|
-
console.error("
|
|
536
|
-
console.log("
|
|
656
|
+
console.error("Failed to parse AI response:", err);
|
|
657
|
+
console.log("Raw AI response:", input);
|
|
537
658
|
return {};
|
|
538
659
|
}
|
|
539
660
|
};
|
|
@@ -597,22 +718,22 @@ var getDeterministicQuality = (gateContext) => {
|
|
|
597
718
|
return Array.isArray(gateContext?.structuralHardBlockReasons) && gateContext.structuralHardBlockReasons.length > 0 ? 2 : 3;
|
|
598
719
|
};
|
|
599
720
|
var buildAiSystemPrompt = (signal) => `
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
721
|
+
You are an internal market-structure classifier for an already computed system signal.
|
|
722
|
+
Analyze the provided JSON containing the trade, candles, indicators (for the coin and BTC across multiple timeframes), and strategy figures/context.
|
|
723
|
+
Series data is already trimmed to the latest 5 values.
|
|
603
724
|
|
|
604
|
-
|
|
605
|
-
-
|
|
606
|
-
-
|
|
607
|
-
-
|
|
608
|
-
-
|
|
609
|
-
-
|
|
610
|
-
-
|
|
611
|
-
-
|
|
612
|
-
-
|
|
613
|
-
-
|
|
725
|
+
Important:
|
|
726
|
+
- Do not invent missing data.
|
|
727
|
+
- This is an internal audit/classification task, not user-facing trading advice.
|
|
728
|
+
- Do not generate execution instructions, do not replace the original thesis with a new one, and do not provide personalized investment advice.
|
|
729
|
+
- Use the original signal direction and levels as the anchor, but you may state that the current structure does not support them.
|
|
730
|
+
- Respect the source strategy specified in \`signal.strategy\`.
|
|
731
|
+
- Your goal is to explain how well the observed structure matches the existing signal and how structurally confirmed it is right now.
|
|
732
|
+
- Do not write vague statements like "there is momentum/slope" without tying them to the decision.
|
|
733
|
+
- Write all user-visible text fields in the requested response language. If no explicit language instruction is provided later, default to English.
|
|
734
|
+
- If confidence is incomplete, prefer cautious wording such as "likely", "not confirmed yet", or "probably" instead of categorical claims.
|
|
614
735
|
|
|
615
|
-
|
|
736
|
+
Return exactly one JSON object and nothing else:
|
|
616
737
|
|
|
617
738
|
{
|
|
618
739
|
"direction": payload.signal.direction | null,
|
|
@@ -630,95 +751,106 @@ var buildAiSystemPrompt = (signal) => `
|
|
|
630
751
|
"triggerInvalidation": string
|
|
631
752
|
}
|
|
632
753
|
|
|
633
|
-
-
|
|
634
|
-
-
|
|
635
|
-
-
|
|
636
|
-
-
|
|
637
|
-
-
|
|
638
|
-
-
|
|
639
|
-
-
|
|
640
|
-
-
|
|
641
|
-
-
|
|
642
|
-
-
|
|
643
|
-
-
|
|
644
|
-
-
|
|
645
|
-
-
|
|
646
|
-
-
|
|
647
|
-
-
|
|
648
|
-
-
|
|
649
|
-
-
|
|
754
|
+
- Do not add any other fields.
|
|
755
|
+
- All numbers must be finite, with no \`NaN\` or \`Infinity\`.
|
|
756
|
+
- All text fields must be short strings with no line breaks and no markdown lists.
|
|
757
|
+
- \`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.
|
|
758
|
+
- \`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.
|
|
759
|
+
- \`needRetest\` indicates whether an additional confirmation level is required before the current signal can be treated as structurally confirmed.
|
|
760
|
+
- \`retestPrice\` is the key level that would confirm or invalidate the structure, or \`null\` if no extra level is needed or available.
|
|
761
|
+
- \`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\`.
|
|
762
|
+
- Use these fields as separate parts of the analysis:
|
|
763
|
+
- \`setup\`: the current structural setup or trendline state.
|
|
764
|
+
- \`confirmations\`: 2-4 concrete confirmations or conflicts from the coin indicators.
|
|
765
|
+
- \`btcContext\`: whether BTC supports the idea, is neutral, or conflicts with it.
|
|
766
|
+
- \`retestPlan\`: what must happen at the key level to confirm the structure, or why no extra level is needed.
|
|
767
|
+
- \`riskLevels\`: a short note on whether the existing levels and risk structure are internally coherent, without creating a new trade plan.
|
|
768
|
+
- \`qualityReason\`: why the quality score is what it is.
|
|
769
|
+
- \`triggerInvalidation\`: what must happen to confirm the signal or what invalidates the current structural thesis.
|
|
770
|
+
- \`comment\` is optional. If you include it, do not just duplicate the structured fields.
|
|
650
771
|
|
|
651
|
-
|
|
772
|
+
If the data is insufficient or the setup is weak, return \`"direction": null\`, \`quality <= 2\`, and explain why.
|
|
652
773
|
|
|
653
|
-
|
|
774
|
+
Input payload structure:
|
|
654
775
|
- payload.signal:
|
|
655
776
|
symbol, signalId, interval, direction, timestamp, strategy, prices
|
|
656
777
|
- payload.signal.prices:
|
|
657
778
|
currentPrice, takeProfitPrice, stopLossPrice
|
|
658
779
|
- payload.figures:
|
|
659
|
-
|
|
780
|
+
strategy-specific figures or geometry when available. Fields vary by strategy.
|
|
660
781
|
- payload.indicators:
|
|
661
|
-
|
|
782
|
+
indicator dictionaries and series for the coin and BTC; all series are already trimmed to the latest 5 values.
|
|
662
783
|
- payload.additionalIndicators:
|
|
663
|
-
strategy-specific summary/context fields.
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
\
|
|
667
|
-
\u2022
|
|
668
|
-
|
|
669
|
-
|
|
784
|
+
strategy-specific summary/context fields. This is not noise; it contains derived fields deliberately passed by the strategy to help the decision.
|
|
785
|
+
Examples: helperFlags, structureContext, spread, correlation, volatilitySummary.
|
|
786
|
+
Always inspect \`payload.additionalIndicators.marketContext\` when present:
|
|
787
|
+
\u2022 \`marketContext.tradingSession\`: UTC session at signal time: asia / europe / us / overlap / off_hours.
|
|
788
|
+
\u2022 \`marketContext.binanceCoinbaseSpread\`: BTC spread between Coinbase and Binance from \`payload.indicators.spread\`; \`value=(Coinbase-Binance)/Binance\`, \`bps=value*10000\`.
|
|
789
|
+
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.
|
|
790
|
+
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.
|
|
791
|
+
Key patterns:
|
|
792
|
+
\u2022 coin: \`maFast\`, \`atrPct\`, \`macd...\`, \`candles15m/candles1h/candles4h/candles1d\`, and \`*1h/*4h/*1d\`
|
|
793
|
+
\u2022 BTC: \`btcMaFast\`, \`btcAtr\`, \`btcMacd...\`, \`btcCandles*\`, and \`btc*1h/*4h/*1d\`
|
|
794
|
+
\u2022 strategy service keys are possible as well, for example \`correlation\`, \`spread\`, \`touches\`, \`distance\`
|
|
670
795
|
|
|
671
|
-
|
|
672
|
-
1
|
|
673
|
-
2
|
|
674
|
-
3
|
|
675
|
-
4
|
|
676
|
-
5
|
|
677
|
-
6
|
|
796
|
+
How to analyze, in order:
|
|
797
|
+
1. Start with price structure and the setup geometry or context in \`payload.figures\`. This has higher priority than indicators.
|
|
798
|
+
2. Then use \`payload.additionalIndicators\` when it contains explicit strategy-specific context such as line state, spread, correlation, and similar fields.
|
|
799
|
+
3. Then assess confirmation or conflict from the current coin indicators.
|
|
800
|
+
4. Then evaluate BTC context.
|
|
801
|
+
5. Only after that choose \`direction\`, \`quality\`, and whether an extra confirmation level is required.
|
|
802
|
+
6. If strong conflicts exist, reduce quality or set direction to \`null\`.
|
|
678
803
|
|
|
679
|
-
|
|
680
|
-
-
|
|
681
|
-
-
|
|
682
|
-
-
|
|
683
|
-
-
|
|
684
|
-
|
|
804
|
+
Explicit conflict rules:
|
|
805
|
+
- If the figure or price structure is invalid or doubtful, indicators must not rescue the setup.
|
|
806
|
+
- If strategy-specific helper fields explicitly say the signal is not confirmed yet, lacks margin, or requires waiting, do not overstate quality.
|
|
807
|
+
- If the structure is acceptable but BTC or key indicators noticeably conflict, quality is usually \`<= 3\`.
|
|
808
|
+
- 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\`.
|
|
809
|
+
- 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.
|
|
810
|
+
- If \`derivativesContext.summary.directionAligned=false\`, explicitly mention the derivatives conflict in \`confirmations\` or \`qualityReason\`.
|
|
811
|
+
- 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.
|
|
812
|
+
- 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\`.
|
|
813
|
+
- 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.
|
|
814
|
+
- 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.
|
|
815
|
+
- If the current signal is not confirmed (\`direction=null\`), name the main reason briefly in \`comment\`.
|
|
816
|
+
If you use the structured fields, include the main reason in \`qualityReason\` or \`triggerInvalidation\`.
|
|
685
817
|
|
|
686
|
-
|
|
687
|
-
- direction = LONG
|
|
688
|
-
-
|
|
689
|
-
-
|
|
690
|
-
-
|
|
691
|
-
-
|
|
692
|
-
-
|
|
693
|
-
-
|
|
694
|
-
-
|
|
818
|
+
Rules for \`direction\` / TP / SL:
|
|
819
|
+
- \`direction = LONG\` only if the data confirms the existing LONG signal; \`SHORT\` only if the data confirms the existing SHORT signal; otherwise \`null\`.
|
|
820
|
+
- For LONG, the expected relation is usually \`stopLossPrice < currentPrice < takeProfitPrice\`.
|
|
821
|
+
- For SHORT, the expected relation is usually \`takeProfitPrice < currentPrice < stopLossPrice\`.
|
|
822
|
+
- Do not optimize or recalculate TP/SL for a "better trade"; only assess whether the already supplied levels are coherent.
|
|
823
|
+
- If \`direction = null\`, then \`takeProfitPrice = null\` and \`stopLossPrice = null\`.
|
|
824
|
+
- If \`needRetest = false\`, then \`retestPrice = null\`.
|
|
825
|
+
- If \`needRetest = true\`, \`retestPrice\` must be a finite number tied to a meaningful retest or breakout level.
|
|
826
|
+
- Before responding, sanity-check the consistency of \`direction\`, TP/SL, and the current price.
|
|
695
827
|
|
|
696
|
-
|
|
697
|
-
- 1:
|
|
698
|
-
- 2:
|
|
699
|
-
- 3:
|
|
700
|
-
- 4:
|
|
701
|
-
- 5:
|
|
828
|
+
Quality scale:
|
|
829
|
+
- 1: poor or chaotic setup, strong conflicts, signal not structurally confirmed
|
|
830
|
+
- 2: weak setup, few confirmations, more of a watch or reject
|
|
831
|
+
- 3: average setup, some structure exists, but notable conflicts remain
|
|
832
|
+
- 4: good setup, several confirmations, structure is mostly coherent
|
|
833
|
+
- 5: very strong setup, clean structure, confirmations, and internally coherent levels
|
|
702
834
|
|
|
703
|
-
|
|
704
|
-
-
|
|
705
|
-
-
|
|
706
|
-
-
|
|
707
|
-
-
|
|
708
|
-
-
|
|
709
|
-
-
|
|
710
|
-
-
|
|
835
|
+
Requirements for useful structured analysis:
|
|
836
|
+
- Include 2-4 concrete factors for or against confirmation in \`confirmations\`.
|
|
837
|
+
- Explicitly mention the role of the key figure or structural state, for example breakout, retest, false break, touch, or lack of confirmation.
|
|
838
|
+
- Explicitly mention BTC context as supportive, neutral, or conflicting.
|
|
839
|
+
- Explain why the quality score is what it is.
|
|
840
|
+
- If the signal is not confirmed (\`direction=null\`), state clearly what must change for confirmation.
|
|
841
|
+
- In \`retestPlan\`, avoid technical placeholders like \`needRetest=false @ null\`; write a human explanation.
|
|
842
|
+
- Do not simply restate JSON fields; add interpretation and decision logic.
|
|
711
843
|
|
|
712
|
-
|
|
713
|
-
-
|
|
714
|
-
-
|
|
715
|
-
-
|
|
844
|
+
Rules for using trimmed series (last 5 values):
|
|
845
|
+
- Do not make strong long-term conclusions from only 5 points.
|
|
846
|
+
- Use 4h and 1d series as brief context, not full history.
|
|
847
|
+
- If the data is too limited for confidence, reduce quality and use cautious wording.
|
|
716
848
|
|
|
717
|
-
|
|
718
|
-
{"direction":"LONG","quality":4,"needRetest":true,"retestPrice":100.2,"takeProfitPrice":101.5,"stopLossPrice":98.9,"setup":"
|
|
719
|
-
{"direction":null,"quality":2,"needRetest":false,"retestPrice":null,"takeProfitPrice":null,"stopLossPrice":null,"setup":"
|
|
849
|
+
Short few-shot examples:
|
|
850
|
+
{"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."}
|
|
851
|
+
{"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."}
|
|
720
852
|
|
|
721
|
-
|
|
853
|
+
Return only the JSON object, with no extra characters.
|
|
722
854
|
${signal ? buildAiSystemPromptAddonByStrategy(signal) : ""}
|
|
723
855
|
`;
|
|
724
856
|
var buildAiPayload = (signal) => buildAiPayloadByStrategy(signal);
|
|
@@ -733,10 +865,10 @@ var getDeterministicAiGateContext = (payload) => {
|
|
|
733
865
|
) ?? null;
|
|
734
866
|
};
|
|
735
867
|
var buildAiHumanPrompt = (signal, payload = buildAiPayload(signal)) => `
|
|
736
|
-
|
|
737
|
-
|
|
868
|
+
Analyze the already computed internal signal for ${signal.symbol}. The original signal direction is ${signal.direction}.
|
|
869
|
+
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.
|
|
738
870
|
|
|
739
|
-
|
|
871
|
+
Trade payload:
|
|
740
872
|
${JSON.stringify(payload)}
|
|
741
873
|
${buildAiHumanPromptAddonByStrategy(signal, payload)}
|
|
742
874
|
`;
|
|
@@ -744,6 +876,14 @@ var DEFAULT_AI_MODEL = "openai/gpt-5-mini";
|
|
|
744
876
|
var userSettingsCache = /* @__PURE__ */ new Map();
|
|
745
877
|
var aiModelCache = /* @__PURE__ */ new Map();
|
|
746
878
|
var getAiModelCacheKey = (userName, modelName) => `${userName}::${modelName}`;
|
|
879
|
+
var resolveAiModelName = (settings, requestedModelName) => {
|
|
880
|
+
const explicitModelName = typeof requestedModelName === "string" ? requestedModelName.trim() : "";
|
|
881
|
+
if (explicitModelName) {
|
|
882
|
+
return explicitModelName;
|
|
883
|
+
}
|
|
884
|
+
const settingsModelName = typeof settings.AI_MODEL === "string" ? settings.AI_MODEL.trim() : "";
|
|
885
|
+
return settingsModelName || DEFAULT_AI_MODEL;
|
|
886
|
+
};
|
|
747
887
|
var getOpenRouterModelKwargs = (apiEndpoint) => {
|
|
748
888
|
const endpoint = String(apiEndpoint ?? "").trim();
|
|
749
889
|
if (!endpoint) {
|
|
@@ -774,30 +914,27 @@ var getAiSettings = async (userName = "root") => {
|
|
|
774
914
|
userSettingsCache.set(userName, settingsPromise);
|
|
775
915
|
}
|
|
776
916
|
const settings = await settingsPromise;
|
|
777
|
-
if (!settings.
|
|
917
|
+
if (!settings.AI_API_KEY || !settings.AI_API_ENDPOINT) {
|
|
778
918
|
throw new Error(`AI settings are incomplete for user ${userName}`);
|
|
779
919
|
}
|
|
780
920
|
return settings;
|
|
781
921
|
};
|
|
782
|
-
var createAiModel = async (userName = "root",
|
|
922
|
+
var createAiModel = async (userName = "root", requestedModelName) => {
|
|
923
|
+
const settings = await getAiSettings(userName);
|
|
924
|
+
const modelName = resolveAiModelName(settings, requestedModelName);
|
|
783
925
|
const cacheKey = getAiModelCacheKey(userName, modelName);
|
|
784
926
|
let modelPromise = aiModelCache.get(cacheKey);
|
|
785
927
|
if (!modelPromise) {
|
|
786
928
|
modelPromise = (async () => {
|
|
787
|
-
const
|
|
788
|
-
|
|
789
|
-
getAiSettings(userName)
|
|
790
|
-
]);
|
|
791
|
-
const modelKwargs = getOpenRouterModelKwargs(
|
|
792
|
-
settings.OPENAI_API_ENDPOINT
|
|
793
|
-
);
|
|
929
|
+
const { ChatOpenAI } = await import("@langchain/openai");
|
|
930
|
+
const modelKwargs = getOpenRouterModelKwargs(settings.AI_API_ENDPOINT);
|
|
794
931
|
return new ChatOpenAI({
|
|
795
932
|
temperature: 0.2,
|
|
796
933
|
modelName,
|
|
797
|
-
apiKey: settings.
|
|
934
|
+
apiKey: settings.AI_API_KEY,
|
|
798
935
|
...Object.keys(modelKwargs).length ? { modelKwargs } : {},
|
|
799
936
|
configuration: {
|
|
800
|
-
baseURL: settings.
|
|
937
|
+
baseURL: settings.AI_API_ENDPOINT,
|
|
801
938
|
defaultHeaders: {
|
|
802
939
|
"HTTP-Referer": "https://tradejs.dev",
|
|
803
940
|
"X-Title": "Inv"
|
|
@@ -812,11 +949,13 @@ var createAiModel = async (userName = "root", modelName = DEFAULT_AI_MODEL) => {
|
|
|
812
949
|
}
|
|
813
950
|
return modelPromise;
|
|
814
951
|
};
|
|
815
|
-
var getAiModel = async (userName = "root",
|
|
952
|
+
var getAiModel = async (userName = "root", requestedModelName) => {
|
|
953
|
+
const settings = await getAiSettings(userName);
|
|
954
|
+
const resolvedModelName = resolveAiModelName(settings, requestedModelName);
|
|
816
955
|
try {
|
|
817
|
-
return await createAiModel(userName,
|
|
956
|
+
return await createAiModel(userName, resolvedModelName);
|
|
818
957
|
} catch (error) {
|
|
819
|
-
aiModelCache.delete(getAiModelCacheKey(userName,
|
|
958
|
+
aiModelCache.delete(getAiModelCacheKey(userName, resolvedModelName));
|
|
820
959
|
userSettingsCache.delete(userName);
|
|
821
960
|
throw error;
|
|
822
961
|
}
|
|
@@ -839,12 +978,21 @@ var runAiPrompt = async ({ systemPrompt, humanPrompt }, options = {}) => {
|
|
|
839
978
|
if (options.signal) {
|
|
840
979
|
await ensureAiStrategyPluginsLoaded();
|
|
841
980
|
}
|
|
842
|
-
const [{ HumanMessage, SystemMessage }, model] = await Promise.all([
|
|
981
|
+
const [{ HumanMessage, SystemMessage }, model, settings] = await Promise.all([
|
|
843
982
|
import("@langchain/core/messages"),
|
|
844
|
-
getAiModel(options.userName, options.model)
|
|
983
|
+
getAiModel(options.userName, options.model),
|
|
984
|
+
getAiSettings(options.userName)
|
|
845
985
|
]);
|
|
846
986
|
const messages = [];
|
|
987
|
+
const responseLanguage = (0, import_aiLanguages.getAiResponseLanguagePromptName)(
|
|
988
|
+
settings.AI_RESPONSE_LANGUAGE || import_aiLanguages.DEFAULT_AI_RESPONSE_LANGUAGE
|
|
989
|
+
);
|
|
847
990
|
messages.push(new SystemMessage(systemPrompt));
|
|
991
|
+
messages.push(
|
|
992
|
+
new SystemMessage(
|
|
993
|
+
`Write all user-visible text fields in ${responseLanguage}. Keep field names and JSON syntax unchanged.`
|
|
994
|
+
)
|
|
995
|
+
);
|
|
848
996
|
messages.push(
|
|
849
997
|
new HumanMessage({
|
|
850
998
|
content: [
|