@tradejs/node 1.0.5 → 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.d.mts +31 -0
- package/dist/ai.d.ts +31 -0
- package/dist/ai.js +1074 -0
- package/dist/ai.mjs +35 -0
- package/dist/backtest.js +713 -5689
- package/dist/backtest.mjs +418 -180
- package/dist/chunk-2JKX3DM7.mjs +619 -0
- package/dist/{chunk-7ICOZAKA.mjs → chunk-H6LIYHU4.mjs} +29 -11
- package/dist/{chunk-CIY64D57.mjs → chunk-JMDYEKIO.mjs} +1 -1
- package/dist/chunk-JRRG3YQG.mjs +154 -0
- package/dist/{chunk-P2ZUWONT.mjs → chunk-JU77QVJ3.mjs} +9 -2
- package/dist/{chunk-SCMBUEGK.mjs → chunk-KMJQQ53K.mjs} +1 -1
- package/dist/{chunk-GKDBAF3A.mjs → chunk-KZDHZ56N.mjs} +25 -7
- package/dist/{chunk-ZY6ULOWK.mjs → chunk-WGOYR6AB.mjs} +1 -1
- package/dist/cli.d.mts +23 -5
- package/dist/cli.d.ts +23 -5
- package/dist/cli.js +1091 -232
- package/dist/cli.mjs +342 -108
- package/dist/connectors.js +7 -2
- package/dist/connectors.mjs +2 -2
- package/dist/constants.js +1 -1
- package/dist/constants.mjs +1 -1
- package/dist/pine.d.mts +10 -6
- package/dist/pine.d.ts +10 -6
- package/dist/pine.js +40 -18
- package/dist/pine.mjs +21 -13
- package/dist/registry.js +7 -2
- package/dist/registry.mjs +2 -2
- package/dist/strategies.d.mts +28 -19
- package/dist/strategies.d.ts +28 -19
- package/dist/strategies.js +7690 -6349
- package/dist/strategies.mjs +1060 -169
- package/package.json +11 -6
- package/dist/ai-G7ATN4YL.mjs +0 -19
- package/dist/chunk-LMAKIC3C.mjs +0 -294
- package/dist/chunk-RBE4PZER.mjs +0 -49
package/dist/ai.js
ADDED
|
@@ -0,0 +1,1074 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/ai.ts
|
|
31
|
+
var ai_exports = {};
|
|
32
|
+
__export(ai_exports, {
|
|
33
|
+
DEFAULT_AI_MODEL: () => DEFAULT_AI_MODEL,
|
|
34
|
+
MAX_AI_SERIES_POINTS: () => MAX_AI_SERIES_POINTS,
|
|
35
|
+
askAI: () => askAI,
|
|
36
|
+
buildAiHumanPrompt: () => buildAiHumanPrompt,
|
|
37
|
+
buildAiPayload: () => buildAiPayload,
|
|
38
|
+
buildAiPrompts: () => buildAiPrompts,
|
|
39
|
+
buildAiSystemPrompt: () => buildAiSystemPrompt,
|
|
40
|
+
ensureAiStrategyPluginsLoaded: () => ensureAiStrategyPluginsLoaded,
|
|
41
|
+
getDeterministicAiGateContext: () => getDeterministicAiGateContext,
|
|
42
|
+
getOpenRouterModelKwargs: () => getOpenRouterModelKwargs,
|
|
43
|
+
resetAiRuntimeCache: () => resetAiRuntimeCache,
|
|
44
|
+
runAiPrompt: () => runAiPrompt,
|
|
45
|
+
runAiPromptLocal: () => runAiPromptLocal,
|
|
46
|
+
trimSeriesDeep: () => trimSeriesDeep
|
|
47
|
+
});
|
|
48
|
+
module.exports = __toCommonJS(ai_exports);
|
|
49
|
+
var import_aiLanguages = require("@tradejs/infra/aiLanguages");
|
|
50
|
+
var import_redis = require("@tradejs/infra/redis");
|
|
51
|
+
var import_userSettings = require("@tradejs/infra/userSettings");
|
|
52
|
+
|
|
53
|
+
// src/aiShared.ts
|
|
54
|
+
var MAX_AI_SERIES_POINTS = 5;
|
|
55
|
+
var trimSeriesDeep = (value) => {
|
|
56
|
+
if (Array.isArray(value)) {
|
|
57
|
+
const trimmed = value.slice(-MAX_AI_SERIES_POINTS);
|
|
58
|
+
const isMatrix = trimmed.every((item) => Array.isArray(item));
|
|
59
|
+
if (isMatrix) {
|
|
60
|
+
return trimmed;
|
|
61
|
+
}
|
|
62
|
+
return trimmed.map(
|
|
63
|
+
(item) => item && typeof item === "object" ? trimSeriesDeep(item) : item
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
if (value && typeof value === "object") {
|
|
67
|
+
return Object.fromEntries(
|
|
68
|
+
Object.entries(value).map(([key, nested]) => [
|
|
69
|
+
key,
|
|
70
|
+
trimSeriesDeep(nested)
|
|
71
|
+
])
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
return value;
|
|
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
|
+
|
|
180
|
+
// src/strategy/manifests.ts
|
|
181
|
+
var import_indicators = require("@tradejs/core/indicators");
|
|
182
|
+
var import_logger2 = require("@tradejs/infra/logger");
|
|
183
|
+
|
|
184
|
+
// src/tradejsConfig.ts
|
|
185
|
+
var import_fs = __toESM(require("fs"));
|
|
186
|
+
var import_path = __toESM(require("path"));
|
|
187
|
+
var import_module = require("module");
|
|
188
|
+
var import_url = require("url");
|
|
189
|
+
var import_config = require("@tradejs/core/config");
|
|
190
|
+
var import_logger = require("@tradejs/infra/logger");
|
|
191
|
+
var CONFIG_FILE_NAMES = [
|
|
192
|
+
"tradejs.config.ts",
|
|
193
|
+
"tradejs.config.mts",
|
|
194
|
+
"tradejs.config.js",
|
|
195
|
+
"tradejs.config.mjs",
|
|
196
|
+
"tradejs.config.cjs"
|
|
197
|
+
];
|
|
198
|
+
var TS_MODULE_RE = /\.(cts|mts|ts)$/i;
|
|
199
|
+
var cachedByCwd = /* @__PURE__ */ new Map();
|
|
200
|
+
var announcedConfigFile = /* @__PURE__ */ new Set();
|
|
201
|
+
var tsNodeRegistered = false;
|
|
202
|
+
var tsconfigPathsRegisteredByCwd = /* @__PURE__ */ new Set();
|
|
203
|
+
var getTradejsProjectCwd = (cwd) => {
|
|
204
|
+
const explicit = String(cwd ?? "").trim();
|
|
205
|
+
if (explicit) {
|
|
206
|
+
return import_path.default.resolve(explicit);
|
|
207
|
+
}
|
|
208
|
+
const fromEnv = String(process.env.PROJECT_CWD || "").trim();
|
|
209
|
+
if (fromEnv) {
|
|
210
|
+
return import_path.default.resolve(fromEnv);
|
|
211
|
+
}
|
|
212
|
+
return process.cwd();
|
|
213
|
+
};
|
|
214
|
+
var normalizeConfig = (rawConfig) => {
|
|
215
|
+
if (!rawConfig || typeof rawConfig !== "object") {
|
|
216
|
+
return {};
|
|
217
|
+
}
|
|
218
|
+
const config = rawConfig;
|
|
219
|
+
const strategies2 = Array.isArray(config.strategies) ? config.strategies.map((value) => String(value || "").trim()).filter(Boolean) : [];
|
|
220
|
+
const indicators = Array.isArray(config.indicators) ? config.indicators.map((value) => String(value || "").trim()).filter(Boolean) : [];
|
|
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
|
+
);
|
|
225
|
+
return {
|
|
226
|
+
strategies: strategies2,
|
|
227
|
+
indicators,
|
|
228
|
+
connectors,
|
|
229
|
+
...hooks ? { hooks } : {}
|
|
230
|
+
};
|
|
231
|
+
};
|
|
232
|
+
var getRequireFn = (cwd = getTradejsProjectCwd()) => (0, import_module.createRequire)(import_path.default.join(import_path.default.resolve(cwd), "__tradejs_loader__.js"));
|
|
233
|
+
var ensureTsNodeRegistered = async () => {
|
|
234
|
+
if (tsNodeRegistered) {
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const tsNodeModule = await import("ts-node");
|
|
238
|
+
const tsNode = tsNodeModule.default ?? tsNodeModule;
|
|
239
|
+
tsNode.register?.({
|
|
240
|
+
transpileOnly: true,
|
|
241
|
+
compilerOptions: {
|
|
242
|
+
module: "commonjs",
|
|
243
|
+
moduleResolution: "node"
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
tsNodeRegistered = true;
|
|
247
|
+
};
|
|
248
|
+
var ensureTsconfigPathsRegistered = async (cwd = getTradejsProjectCwd()) => {
|
|
249
|
+
const projectRoot = getTradejsProjectCwd(cwd);
|
|
250
|
+
if (tsconfigPathsRegisteredByCwd.has(projectRoot)) {
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
const tsconfigPathsModule = await import("tsconfig-paths");
|
|
254
|
+
const loadConfig = tsconfigPathsModule.loadConfig;
|
|
255
|
+
const register = tsconfigPathsModule.register;
|
|
256
|
+
if (typeof loadConfig !== "function" || typeof register !== "function") {
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
const loadedConfig = loadConfig(projectRoot);
|
|
260
|
+
if (loadedConfig.resultType !== "success") {
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
register({
|
|
264
|
+
baseUrl: loadedConfig.absoluteBaseUrl,
|
|
265
|
+
paths: loadedConfig.paths,
|
|
266
|
+
addMatchAll: false
|
|
267
|
+
});
|
|
268
|
+
tsconfigPathsRegisteredByCwd.add(projectRoot);
|
|
269
|
+
};
|
|
270
|
+
var toImportSpecifier = (moduleName) => {
|
|
271
|
+
if (moduleName.startsWith("file://")) {
|
|
272
|
+
return moduleName;
|
|
273
|
+
}
|
|
274
|
+
if (import_path.default.isAbsolute(moduleName)) {
|
|
275
|
+
return (0, import_url.pathToFileURL)(moduleName).href;
|
|
276
|
+
}
|
|
277
|
+
return moduleName;
|
|
278
|
+
};
|
|
279
|
+
var isTsModulePath = (moduleName) => TS_MODULE_RE.test(moduleName.split("?")[0]);
|
|
280
|
+
var isRelativeModulePath = (moduleName) => moduleName.startsWith("./") || moduleName.startsWith("../");
|
|
281
|
+
var isBareModuleSpecifier = (moduleName) => {
|
|
282
|
+
const normalized = String(moduleName ?? "").trim();
|
|
283
|
+
if (!normalized) {
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
if (normalized.startsWith("file://") || import_path.default.isAbsolute(normalized) || isRelativeModulePath(normalized)) {
|
|
287
|
+
return false;
|
|
288
|
+
}
|
|
289
|
+
return true;
|
|
290
|
+
};
|
|
291
|
+
var importConfigFile = async (configFilePath) => {
|
|
292
|
+
const ext = import_path.default.extname(configFilePath).toLowerCase();
|
|
293
|
+
const configFileUrl = `${toImportSpecifier(configFilePath)}?t=${Date.now()}`;
|
|
294
|
+
if (ext === ".ts" || ext === ".mts") {
|
|
295
|
+
const requireFn = getRequireFn(import_path.default.dirname(configFilePath));
|
|
296
|
+
await ensureTsNodeRegistered();
|
|
297
|
+
await ensureTsconfigPathsRegistered(import_path.default.dirname(configFilePath));
|
|
298
|
+
return requireFn(configFilePath);
|
|
299
|
+
}
|
|
300
|
+
return import(
|
|
301
|
+
/* webpackIgnore: true */
|
|
302
|
+
configFileUrl
|
|
303
|
+
);
|
|
304
|
+
};
|
|
305
|
+
var importTradejsModule = async (moduleName, cwd = getTradejsProjectCwd()) => {
|
|
306
|
+
const normalized = String(moduleName ?? "").trim();
|
|
307
|
+
if (!normalized) {
|
|
308
|
+
return {};
|
|
309
|
+
}
|
|
310
|
+
let modulePath = normalized;
|
|
311
|
+
if (normalized.startsWith("file://")) {
|
|
312
|
+
try {
|
|
313
|
+
modulePath = (0, import_url.fileURLToPath)(normalized);
|
|
314
|
+
} catch {
|
|
315
|
+
modulePath = normalized;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
const requireFn = getRequireFn(
|
|
319
|
+
import_path.default.isAbsolute(modulePath) ? import_path.default.dirname(modulePath) : cwd
|
|
320
|
+
);
|
|
321
|
+
if (isTsModulePath(modulePath)) {
|
|
322
|
+
await ensureTsNodeRegistered();
|
|
323
|
+
await ensureTsconfigPathsRegistered(cwd);
|
|
324
|
+
return requireFn(modulePath);
|
|
325
|
+
}
|
|
326
|
+
if (isBareModuleSpecifier(normalized)) {
|
|
327
|
+
await ensureTsconfigPathsRegistered(cwd);
|
|
328
|
+
return requireFn(normalized);
|
|
329
|
+
}
|
|
330
|
+
try {
|
|
331
|
+
return await import(
|
|
332
|
+
/* webpackIgnore: true */
|
|
333
|
+
toImportSpecifier(normalized)
|
|
334
|
+
);
|
|
335
|
+
} catch (error) {
|
|
336
|
+
if (isTsModulePath(modulePath)) {
|
|
337
|
+
await ensureTsNodeRegistered();
|
|
338
|
+
await ensureTsconfigPathsRegistered(cwd);
|
|
339
|
+
return requireFn(modulePath);
|
|
340
|
+
}
|
|
341
|
+
throw error;
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
var resolveExportedConfig = (moduleExports) => {
|
|
345
|
+
const candidate = moduleExports && typeof moduleExports === "object" && "default" in moduleExports ? moduleExports.default : moduleExports;
|
|
346
|
+
return normalizeConfig(candidate);
|
|
347
|
+
};
|
|
348
|
+
var findConfigFilePath = (cwd) => {
|
|
349
|
+
let currentDir = import_path.default.resolve(cwd);
|
|
350
|
+
while (true) {
|
|
351
|
+
for (const fileName of CONFIG_FILE_NAMES) {
|
|
352
|
+
const fullPath = import_path.default.join(currentDir, fileName);
|
|
353
|
+
if (import_fs.default.existsSync(fullPath) && import_fs.default.statSync(fullPath).isFile()) {
|
|
354
|
+
return fullPath;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
const parentDir = import_path.default.dirname(currentDir);
|
|
358
|
+
if (parentDir === currentDir) {
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
currentDir = parentDir;
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
var resolvePluginModuleSpecifier = (moduleName, cwd = getTradejsProjectCwd()) => {
|
|
365
|
+
const normalized = String(moduleName ?? "").trim();
|
|
366
|
+
if (!normalized) {
|
|
367
|
+
return "";
|
|
368
|
+
}
|
|
369
|
+
if (normalized.startsWith("file://")) {
|
|
370
|
+
try {
|
|
371
|
+
return (0, import_url.fileURLToPath)(normalized);
|
|
372
|
+
} catch {
|
|
373
|
+
return normalized;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
if (import_path.default.isAbsolute(normalized)) {
|
|
377
|
+
return normalized;
|
|
378
|
+
}
|
|
379
|
+
if (isRelativeModulePath(normalized)) {
|
|
380
|
+
return import_path.default.resolve(cwd, normalized);
|
|
381
|
+
}
|
|
382
|
+
return normalized;
|
|
383
|
+
};
|
|
384
|
+
var loadTradejsConfig = async (cwd = getTradejsProjectCwd()) => {
|
|
385
|
+
const cached = cachedByCwd.get(cwd);
|
|
386
|
+
if (cached) {
|
|
387
|
+
return cached;
|
|
388
|
+
}
|
|
389
|
+
const configFilePath = findConfigFilePath(cwd);
|
|
390
|
+
if (!configFilePath) {
|
|
391
|
+
cachedByCwd.set(cwd, {});
|
|
392
|
+
return {};
|
|
393
|
+
}
|
|
394
|
+
try {
|
|
395
|
+
const moduleExports = await importConfigFile(configFilePath);
|
|
396
|
+
const config = resolveExportedConfig(moduleExports);
|
|
397
|
+
cachedByCwd.set(cwd, config);
|
|
398
|
+
if (!announcedConfigFile.has(configFilePath)) {
|
|
399
|
+
announcedConfigFile.add(configFilePath);
|
|
400
|
+
import_logger.logger.log("debug", "Loaded TradeJS config: %s", configFilePath);
|
|
401
|
+
}
|
|
402
|
+
return config;
|
|
403
|
+
} catch (error) {
|
|
404
|
+
import_logger.logger.log(
|
|
405
|
+
"warn",
|
|
406
|
+
"Failed to load TradeJS config from %s: %s",
|
|
407
|
+
configFilePath,
|
|
408
|
+
String(error)
|
|
409
|
+
);
|
|
410
|
+
cachedByCwd.set(cwd, {});
|
|
411
|
+
return {};
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
// src/strategy/manifests.ts
|
|
416
|
+
var createStrategyRegistryState = () => ({
|
|
417
|
+
strategyCreators: /* @__PURE__ */ new Map(),
|
|
418
|
+
strategyManifestsMap: /* @__PURE__ */ new Map(),
|
|
419
|
+
pluginsLoadPromise: null
|
|
420
|
+
});
|
|
421
|
+
var registryStateByProjectRoot = /* @__PURE__ */ new Map();
|
|
422
|
+
var getStrategyRegistryState = (cwd = getTradejsProjectCwd()) => {
|
|
423
|
+
const projectRoot = getTradejsProjectCwd(cwd);
|
|
424
|
+
let state = registryStateByProjectRoot.get(projectRoot);
|
|
425
|
+
if (!state) {
|
|
426
|
+
state = createStrategyRegistryState();
|
|
427
|
+
registryStateByProjectRoot.set(projectRoot, state);
|
|
428
|
+
}
|
|
429
|
+
return {
|
|
430
|
+
projectRoot,
|
|
431
|
+
state
|
|
432
|
+
};
|
|
433
|
+
};
|
|
434
|
+
var toUniqueModules = (modules = []) => [
|
|
435
|
+
...new Set(modules.map((moduleName) => moduleName.trim()).filter(Boolean))
|
|
436
|
+
];
|
|
437
|
+
var getConfiguredPluginModuleNames = async (cwd = getTradejsProjectCwd()) => {
|
|
438
|
+
const config = await loadTradejsConfig(cwd);
|
|
439
|
+
return {
|
|
440
|
+
strategyModules: toUniqueModules(config.strategies),
|
|
441
|
+
indicatorModules: toUniqueModules(config.indicators)
|
|
442
|
+
};
|
|
443
|
+
};
|
|
444
|
+
var extractModuleEntries = (moduleExport, key) => {
|
|
445
|
+
if (!moduleExport || typeof moduleExport !== "object") {
|
|
446
|
+
return null;
|
|
447
|
+
}
|
|
448
|
+
const candidate = moduleExport;
|
|
449
|
+
if (Array.isArray(candidate[key])) {
|
|
450
|
+
return candidate[key];
|
|
451
|
+
}
|
|
452
|
+
const defaultExport = candidate.default;
|
|
453
|
+
if (defaultExport && Array.isArray(defaultExport[key])) {
|
|
454
|
+
return defaultExport[key];
|
|
455
|
+
}
|
|
456
|
+
return null;
|
|
457
|
+
};
|
|
458
|
+
var extractStrategyPluginDefinition = (moduleExport) => {
|
|
459
|
+
const strategyEntries = extractModuleEntries(
|
|
460
|
+
moduleExport,
|
|
461
|
+
"strategyEntries"
|
|
462
|
+
);
|
|
463
|
+
return strategyEntries ? { strategyEntries } : null;
|
|
464
|
+
};
|
|
465
|
+
var extractIndicatorPluginDefinition = (moduleExport) => {
|
|
466
|
+
const indicatorEntries = extractModuleEntries(
|
|
467
|
+
moduleExport,
|
|
468
|
+
"indicatorEntries"
|
|
469
|
+
);
|
|
470
|
+
return indicatorEntries ? { indicatorEntries } : null;
|
|
471
|
+
};
|
|
472
|
+
var registerEntries = (entries, source, state) => {
|
|
473
|
+
for (const entry of entries) {
|
|
474
|
+
const strategyName = entry.manifest?.name;
|
|
475
|
+
if (!strategyName) {
|
|
476
|
+
import_logger2.logger.warn("Skip strategy entry without name from %s", source);
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
if (state.strategyCreators.has(strategyName)) {
|
|
480
|
+
import_logger2.logger.warn(
|
|
481
|
+
'Skip duplicate strategy "%s" from %s: already registered',
|
|
482
|
+
strategyName,
|
|
483
|
+
source
|
|
484
|
+
);
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
state.strategyCreators.set(strategyName, entry.creator);
|
|
488
|
+
state.strategyManifestsMap.set(strategyName, entry.manifest);
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
var importStrategyPluginModule = async (moduleName, cwd = getTradejsProjectCwd()) => {
|
|
492
|
+
if (typeof importTradejsModule === "function") {
|
|
493
|
+
return importTradejsModule(moduleName, cwd);
|
|
494
|
+
}
|
|
495
|
+
return import(
|
|
496
|
+
/* webpackIgnore: true */
|
|
497
|
+
moduleName
|
|
498
|
+
);
|
|
499
|
+
};
|
|
500
|
+
var ensureStrategyPluginsLoaded = async (cwd = getTradejsProjectCwd()) => {
|
|
501
|
+
const { projectRoot, state } = getStrategyRegistryState(cwd);
|
|
502
|
+
if (!state.pluginsLoadPromise) {
|
|
503
|
+
(0, import_indicators.resetIndicatorRegistryCache)(projectRoot);
|
|
504
|
+
state.pluginsLoadPromise = (async () => {
|
|
505
|
+
const { strategyModules, indicatorModules } = await getConfiguredPluginModuleNames(projectRoot);
|
|
506
|
+
const strategySet = new Set(strategyModules);
|
|
507
|
+
const indicatorSet = new Set(indicatorModules);
|
|
508
|
+
const pluginModuleNames = [
|
|
509
|
+
.../* @__PURE__ */ new Set([...strategyModules, ...indicatorModules])
|
|
510
|
+
];
|
|
511
|
+
if (!pluginModuleNames.length) {
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
for (const moduleName of pluginModuleNames) {
|
|
515
|
+
try {
|
|
516
|
+
const resolvedModuleName = resolvePluginModuleSpecifier(
|
|
517
|
+
moduleName,
|
|
518
|
+
projectRoot
|
|
519
|
+
);
|
|
520
|
+
const moduleExport = await importStrategyPluginModule(
|
|
521
|
+
resolvedModuleName,
|
|
522
|
+
projectRoot
|
|
523
|
+
);
|
|
524
|
+
if (strategySet.has(moduleName)) {
|
|
525
|
+
const pluginDefinition = extractStrategyPluginDefinition(moduleExport);
|
|
526
|
+
if (!pluginDefinition) {
|
|
527
|
+
import_logger2.logger.warn(
|
|
528
|
+
'Skip strategy plugin "%s": export { strategyEntries } is missing',
|
|
529
|
+
moduleName
|
|
530
|
+
);
|
|
531
|
+
} else {
|
|
532
|
+
registerEntries(
|
|
533
|
+
pluginDefinition.strategyEntries,
|
|
534
|
+
moduleName,
|
|
535
|
+
state
|
|
536
|
+
);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
if (indicatorSet.has(moduleName)) {
|
|
540
|
+
const indicatorPluginDefinition = extractIndicatorPluginDefinition(moduleExport);
|
|
541
|
+
if (!indicatorPluginDefinition) {
|
|
542
|
+
import_logger2.logger.warn(
|
|
543
|
+
'Skip indicator plugin "%s": export { indicatorEntries } is missing',
|
|
544
|
+
moduleName
|
|
545
|
+
);
|
|
546
|
+
} else {
|
|
547
|
+
(0, import_indicators.registerIndicatorEntries)(
|
|
548
|
+
indicatorPluginDefinition.indicatorEntries,
|
|
549
|
+
moduleName,
|
|
550
|
+
projectRoot
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
if (!strategySet.has(moduleName) && !indicatorSet.has(moduleName)) {
|
|
555
|
+
import_logger2.logger.warn(
|
|
556
|
+
'Skip plugin "%s": no strategy/indicator sections requested in config',
|
|
557
|
+
moduleName
|
|
558
|
+
);
|
|
559
|
+
}
|
|
560
|
+
} catch (error) {
|
|
561
|
+
import_logger2.logger.warn(
|
|
562
|
+
'Failed to load plugin "%s": %s',
|
|
563
|
+
moduleName,
|
|
564
|
+
String(error)
|
|
565
|
+
);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
})();
|
|
569
|
+
}
|
|
570
|
+
await state.pluginsLoadPromise;
|
|
571
|
+
};
|
|
572
|
+
var getStrategyManifest = (name, cwd = getTradejsProjectCwd()) => {
|
|
573
|
+
if (!name) {
|
|
574
|
+
return void 0;
|
|
575
|
+
}
|
|
576
|
+
const { state } = getStrategyRegistryState(cwd);
|
|
577
|
+
return state.strategyManifestsMap.get(name);
|
|
578
|
+
};
|
|
579
|
+
var strategies = new Proxy(
|
|
580
|
+
{},
|
|
581
|
+
{
|
|
582
|
+
get: (_target, property) => {
|
|
583
|
+
if (typeof property !== "string") {
|
|
584
|
+
return void 0;
|
|
585
|
+
}
|
|
586
|
+
return getStrategyRegistryState().state.strategyCreators.get(property);
|
|
587
|
+
},
|
|
588
|
+
ownKeys: () => {
|
|
589
|
+
return [...getStrategyRegistryState().state.strategyCreators.keys()];
|
|
590
|
+
},
|
|
591
|
+
getOwnPropertyDescriptor: () => ({
|
|
592
|
+
enumerable: true,
|
|
593
|
+
configurable: true
|
|
594
|
+
})
|
|
595
|
+
}
|
|
596
|
+
);
|
|
597
|
+
|
|
598
|
+
// src/strategyAdapters/ai.ts
|
|
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
|
+
};
|
|
629
|
+
var defaultAiAdapter = {};
|
|
630
|
+
var getStrategyAiAdapter = (strategy) => getStrategyManifest(strategy)?.aiAdapter ?? defaultAiAdapter;
|
|
631
|
+
var getSignalAiAdapter = (signal) => getStrategyAiAdapter(signal.strategy);
|
|
632
|
+
var buildAiPayloadByStrategy = (signal) => {
|
|
633
|
+
const basePayload = buildBaseAiPayload(signal);
|
|
634
|
+
const adapter = getSignalAiAdapter(signal);
|
|
635
|
+
return adapter.buildPayload?.({ signal, basePayload }) ?? basePayload;
|
|
636
|
+
};
|
|
637
|
+
var buildAiSystemPromptAddonByStrategy = (signal) => getSignalAiAdapter(signal).buildSystemPromptAddon?.({ signal }) ?? "";
|
|
638
|
+
var buildAiHumanPromptAddonByStrategy = (signal, payload) => getSignalAiAdapter(signal).buildHumanPromptAddon?.({
|
|
639
|
+
signal,
|
|
640
|
+
payload
|
|
641
|
+
}) ?? "";
|
|
642
|
+
var postProcessAiAnalysisByStrategy = (signal, analysis, payload = buildAiPayloadByStrategy(signal)) => getSignalAiAdapter(signal).postProcessAnalysis?.({
|
|
643
|
+
signal,
|
|
644
|
+
payload,
|
|
645
|
+
analysis
|
|
646
|
+
}) ?? analysis;
|
|
647
|
+
|
|
648
|
+
// src/ai.ts
|
|
649
|
+
var parseAIResponse = (input) => {
|
|
650
|
+
try {
|
|
651
|
+
if (typeof input === "object" && input !== null) return input;
|
|
652
|
+
const match = input.match(/\{[\s\S]*\}/);
|
|
653
|
+
if (!match) throw new Error("JSON block not found");
|
|
654
|
+
return JSON.parse(match[0]);
|
|
655
|
+
} catch (err) {
|
|
656
|
+
console.error("Failed to parse AI response:", err);
|
|
657
|
+
console.log("Raw AI response:", input);
|
|
658
|
+
return {};
|
|
659
|
+
}
|
|
660
|
+
};
|
|
661
|
+
var normalizeResponseContent = (content) => {
|
|
662
|
+
if (typeof content === "string" || content && typeof content === "object") {
|
|
663
|
+
if (typeof content !== "object" || !Array.isArray(content)) {
|
|
664
|
+
return content;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
if (Array.isArray(content)) {
|
|
668
|
+
const text = content.map((part) => typeof part?.text === "string" ? part.text : "").join("\n").trim();
|
|
669
|
+
return text;
|
|
670
|
+
}
|
|
671
|
+
return String(content ?? "");
|
|
672
|
+
};
|
|
673
|
+
var normalizeAnalysis = (raw) => {
|
|
674
|
+
const direction = raw?.direction === "LONG" || raw?.direction === "SHORT" ? raw.direction : null;
|
|
675
|
+
const qualityNum = typeof raw?.quality === "number" ? Math.max(1, Math.min(5, Math.round(raw.quality))) : void 0;
|
|
676
|
+
const toNumberOrNull = (value) => {
|
|
677
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
678
|
+
if (typeof value === "string" && value.trim()) {
|
|
679
|
+
const parsed = Number(value);
|
|
680
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
681
|
+
}
|
|
682
|
+
return null;
|
|
683
|
+
};
|
|
684
|
+
const toText = (value) => typeof value === "string" ? value.slice(0, 400) : void 0;
|
|
685
|
+
return {
|
|
686
|
+
direction,
|
|
687
|
+
quality: qualityNum,
|
|
688
|
+
needRetest: Boolean(raw?.needRetest),
|
|
689
|
+
retestPrice: toNumberOrNull(raw?.retestPrice),
|
|
690
|
+
takeProfitPrice: toNumberOrNull(raw?.takeProfitPrice),
|
|
691
|
+
stopLossPrice: toNumberOrNull(raw?.stopLossPrice),
|
|
692
|
+
setup: toText(raw?.setup),
|
|
693
|
+
confirmations: toText(raw?.confirmations),
|
|
694
|
+
btcContext: toText(raw?.btcContext),
|
|
695
|
+
retestPlan: toText(raw?.retestPlan),
|
|
696
|
+
riskLevels: toText(raw?.riskLevels),
|
|
697
|
+
qualityReason: toText(raw?.qualityReason),
|
|
698
|
+
triggerInvalidation: toText(raw?.triggerInvalidation),
|
|
699
|
+
comment: typeof raw?.comment === "string" ? raw.comment.slice(0, 1024) : ""
|
|
700
|
+
};
|
|
701
|
+
};
|
|
702
|
+
var asRecord = (value) => {
|
|
703
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
704
|
+
return null;
|
|
705
|
+
}
|
|
706
|
+
return value;
|
|
707
|
+
};
|
|
708
|
+
var getSignalDirection = (signal) => signal.direction === "LONG" || signal.direction === "SHORT" ? signal.direction : null;
|
|
709
|
+
var getDeterministicQuality = (gateContext) => {
|
|
710
|
+
const deterministicQuality = Number(gateContext?.deterministicQuality);
|
|
711
|
+
if (Number.isFinite(deterministicQuality)) {
|
|
712
|
+
return Math.max(1, Math.min(5, Math.round(deterministicQuality)));
|
|
713
|
+
}
|
|
714
|
+
const maxAllowedQuality = Number(gateContext?.maxAllowedQuality);
|
|
715
|
+
if (Number.isFinite(maxAllowedQuality)) {
|
|
716
|
+
return Math.max(1, Math.min(5, Math.round(maxAllowedQuality)));
|
|
717
|
+
}
|
|
718
|
+
return Array.isArray(gateContext?.structuralHardBlockReasons) && gateContext.structuralHardBlockReasons.length > 0 ? 2 : 3;
|
|
719
|
+
};
|
|
720
|
+
var buildAiSystemPrompt = (signal) => `
|
|
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.
|
|
724
|
+
|
|
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.
|
|
735
|
+
|
|
736
|
+
Return exactly one JSON object and nothing else:
|
|
737
|
+
|
|
738
|
+
{
|
|
739
|
+
"direction": payload.signal.direction | null,
|
|
740
|
+
"quality": 1 | 2 | 3 | 4 | 5,
|
|
741
|
+
"needRetest": boolean,
|
|
742
|
+
"retestPrice": number | null,
|
|
743
|
+
"takeProfitPrice": number | null,
|
|
744
|
+
"stopLossPrice": number | null,
|
|
745
|
+
"setup": string,
|
|
746
|
+
"confirmations": string,
|
|
747
|
+
"btcContext": string,
|
|
748
|
+
"retestPlan": string,
|
|
749
|
+
"riskLevels": string,
|
|
750
|
+
"qualityReason": string,
|
|
751
|
+
"triggerInvalidation": string
|
|
752
|
+
}
|
|
753
|
+
|
|
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.
|
|
771
|
+
|
|
772
|
+
If the data is insufficient or the setup is weak, return \`"direction": null\`, \`quality <= 2\`, and explain why.
|
|
773
|
+
|
|
774
|
+
Input payload structure:
|
|
775
|
+
- payload.signal:
|
|
776
|
+
symbol, signalId, interval, direction, timestamp, strategy, prices
|
|
777
|
+
- payload.signal.prices:
|
|
778
|
+
currentPrice, takeProfitPrice, stopLossPrice
|
|
779
|
+
- payload.figures:
|
|
780
|
+
strategy-specific figures or geometry when available. Fields vary by strategy.
|
|
781
|
+
- payload.indicators:
|
|
782
|
+
indicator dictionaries and series for the coin and BTC; all series are already trimmed to the latest 5 values.
|
|
783
|
+
- payload.additionalIndicators:
|
|
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\`
|
|
795
|
+
|
|
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\`.
|
|
803
|
+
|
|
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\`.
|
|
817
|
+
|
|
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.
|
|
827
|
+
|
|
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
|
|
834
|
+
|
|
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.
|
|
843
|
+
|
|
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.
|
|
848
|
+
|
|
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."}
|
|
852
|
+
|
|
853
|
+
Return only the JSON object, with no extra characters.
|
|
854
|
+
${signal ? buildAiSystemPromptAddonByStrategy(signal) : ""}
|
|
855
|
+
`;
|
|
856
|
+
var buildAiPayload = (signal) => buildAiPayloadByStrategy(signal);
|
|
857
|
+
var getDeterministicAiGateContext = (payload) => {
|
|
858
|
+
const additionalIndicators = asRecord(payload.additionalIndicators);
|
|
859
|
+
const candidates = [
|
|
860
|
+
additionalIndicators,
|
|
861
|
+
...Object.values(additionalIndicators ?? {}).map(asRecord)
|
|
862
|
+
].filter((value) => Boolean(value));
|
|
863
|
+
return candidates.find(
|
|
864
|
+
(candidate) => Array.isArray(candidate.structuralHardBlockReasons) || typeof candidate.approvalAllowedNow === "boolean"
|
|
865
|
+
) ?? null;
|
|
866
|
+
};
|
|
867
|
+
var buildAiHumanPrompt = (signal, payload = buildAiPayload(signal)) => `
|
|
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.
|
|
870
|
+
|
|
871
|
+
Trade payload:
|
|
872
|
+
${JSON.stringify(payload)}
|
|
873
|
+
${buildAiHumanPromptAddonByStrategy(signal, payload)}
|
|
874
|
+
`;
|
|
875
|
+
var DEFAULT_AI_MODEL = "openai/gpt-5-mini";
|
|
876
|
+
var userSettingsCache = /* @__PURE__ */ new Map();
|
|
877
|
+
var aiModelCache = /* @__PURE__ */ new Map();
|
|
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
|
+
};
|
|
887
|
+
var getOpenRouterModelKwargs = (apiEndpoint) => {
|
|
888
|
+
const endpoint = String(apiEndpoint ?? "").trim();
|
|
889
|
+
if (!endpoint) {
|
|
890
|
+
return {};
|
|
891
|
+
}
|
|
892
|
+
let hostname = "";
|
|
893
|
+
try {
|
|
894
|
+
hostname = new URL(endpoint).hostname;
|
|
895
|
+
} catch {
|
|
896
|
+
hostname = endpoint;
|
|
897
|
+
}
|
|
898
|
+
if (!hostname.toLowerCase().includes("openrouter")) {
|
|
899
|
+
return {};
|
|
900
|
+
}
|
|
901
|
+
return {
|
|
902
|
+
provider: {
|
|
903
|
+
ignore: ["azure"]
|
|
904
|
+
}
|
|
905
|
+
};
|
|
906
|
+
};
|
|
907
|
+
var getAiSettings = async (userName = "root") => {
|
|
908
|
+
let settingsPromise = userSettingsCache.get(userName);
|
|
909
|
+
if (!settingsPromise) {
|
|
910
|
+
settingsPromise = (0, import_userSettings.getUserSettings)(userName);
|
|
911
|
+
settingsPromise.catch(() => {
|
|
912
|
+
userSettingsCache.delete(userName);
|
|
913
|
+
});
|
|
914
|
+
userSettingsCache.set(userName, settingsPromise);
|
|
915
|
+
}
|
|
916
|
+
const settings = await settingsPromise;
|
|
917
|
+
if (!settings.AI_API_KEY || !settings.AI_API_ENDPOINT) {
|
|
918
|
+
throw new Error(`AI settings are incomplete for user ${userName}`);
|
|
919
|
+
}
|
|
920
|
+
return settings;
|
|
921
|
+
};
|
|
922
|
+
var createAiModel = async (userName = "root", requestedModelName) => {
|
|
923
|
+
const settings = await getAiSettings(userName);
|
|
924
|
+
const modelName = resolveAiModelName(settings, requestedModelName);
|
|
925
|
+
const cacheKey = getAiModelCacheKey(userName, modelName);
|
|
926
|
+
let modelPromise = aiModelCache.get(cacheKey);
|
|
927
|
+
if (!modelPromise) {
|
|
928
|
+
modelPromise = (async () => {
|
|
929
|
+
const { ChatOpenAI } = await import("@langchain/openai");
|
|
930
|
+
const modelKwargs = getOpenRouterModelKwargs(settings.AI_API_ENDPOINT);
|
|
931
|
+
return new ChatOpenAI({
|
|
932
|
+
temperature: 0.2,
|
|
933
|
+
modelName,
|
|
934
|
+
apiKey: settings.AI_API_KEY,
|
|
935
|
+
...Object.keys(modelKwargs).length ? { modelKwargs } : {},
|
|
936
|
+
configuration: {
|
|
937
|
+
baseURL: settings.AI_API_ENDPOINT,
|
|
938
|
+
defaultHeaders: {
|
|
939
|
+
"HTTP-Referer": "https://tradejs.dev",
|
|
940
|
+
"X-Title": "Inv"
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
});
|
|
944
|
+
})();
|
|
945
|
+
modelPromise.catch(() => {
|
|
946
|
+
aiModelCache.delete(cacheKey);
|
|
947
|
+
});
|
|
948
|
+
aiModelCache.set(cacheKey, modelPromise);
|
|
949
|
+
}
|
|
950
|
+
return modelPromise;
|
|
951
|
+
};
|
|
952
|
+
var getAiModel = async (userName = "root", requestedModelName) => {
|
|
953
|
+
const settings = await getAiSettings(userName);
|
|
954
|
+
const resolvedModelName = resolveAiModelName(settings, requestedModelName);
|
|
955
|
+
try {
|
|
956
|
+
return await createAiModel(userName, resolvedModelName);
|
|
957
|
+
} catch (error) {
|
|
958
|
+
aiModelCache.delete(getAiModelCacheKey(userName, resolvedModelName));
|
|
959
|
+
userSettingsCache.delete(userName);
|
|
960
|
+
throw error;
|
|
961
|
+
}
|
|
962
|
+
};
|
|
963
|
+
var resetAiRuntimeCache = () => {
|
|
964
|
+
aiModelCache.clear();
|
|
965
|
+
userSettingsCache.clear();
|
|
966
|
+
};
|
|
967
|
+
var ensureAiStrategyPluginsLoaded = async () => {
|
|
968
|
+
await ensureStrategyPluginsLoaded();
|
|
969
|
+
};
|
|
970
|
+
var buildAiPrompts = (signal) => {
|
|
971
|
+
const payload = buildAiPayload(signal);
|
|
972
|
+
return {
|
|
973
|
+
systemPrompt: buildAiSystemPrompt(signal),
|
|
974
|
+
humanPrompt: buildAiHumanPrompt(signal, payload)
|
|
975
|
+
};
|
|
976
|
+
};
|
|
977
|
+
var runAiPrompt = async ({ systemPrompt, humanPrompt }, options = {}) => {
|
|
978
|
+
if (options.signal) {
|
|
979
|
+
await ensureAiStrategyPluginsLoaded();
|
|
980
|
+
}
|
|
981
|
+
const [{ HumanMessage, SystemMessage }, model, settings] = await Promise.all([
|
|
982
|
+
import("@langchain/core/messages"),
|
|
983
|
+
getAiModel(options.userName, options.model),
|
|
984
|
+
getAiSettings(options.userName)
|
|
985
|
+
]);
|
|
986
|
+
const messages = [];
|
|
987
|
+
const responseLanguage = (0, import_aiLanguages.getAiResponseLanguagePromptName)(
|
|
988
|
+
settings.AI_RESPONSE_LANGUAGE || import_aiLanguages.DEFAULT_AI_RESPONSE_LANGUAGE
|
|
989
|
+
);
|
|
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
|
+
);
|
|
996
|
+
messages.push(
|
|
997
|
+
new HumanMessage({
|
|
998
|
+
content: [
|
|
999
|
+
{
|
|
1000
|
+
type: "text",
|
|
1001
|
+
text: humanPrompt
|
|
1002
|
+
}
|
|
1003
|
+
]
|
|
1004
|
+
})
|
|
1005
|
+
);
|
|
1006
|
+
const response = await model.invoke(messages);
|
|
1007
|
+
const parsed = parseAIResponse(
|
|
1008
|
+
normalizeResponseContent(response.content)
|
|
1009
|
+
);
|
|
1010
|
+
const normalized = normalizeAnalysis(parsed);
|
|
1011
|
+
if (!options.signal) {
|
|
1012
|
+
return normalized;
|
|
1013
|
+
}
|
|
1014
|
+
return postProcessAiAnalysisByStrategy(
|
|
1015
|
+
options.signal,
|
|
1016
|
+
normalized,
|
|
1017
|
+
options.payload
|
|
1018
|
+
);
|
|
1019
|
+
};
|
|
1020
|
+
var runAiPromptLocal = async (signal, options = {}) => {
|
|
1021
|
+
await ensureAiStrategyPluginsLoaded();
|
|
1022
|
+
const payload = options.payload ?? buildAiPayload(signal);
|
|
1023
|
+
const gateContext = getDeterministicAiGateContext(payload);
|
|
1024
|
+
const signalDirection = getSignalDirection(signal);
|
|
1025
|
+
const deterministicQuality = getDeterministicQuality(gateContext);
|
|
1026
|
+
const approvalAllowedNow = typeof gateContext?.approvalAllowedNow === "boolean" ? gateContext.approvalAllowedNow : deterministicQuality >= 4;
|
|
1027
|
+
return postProcessAiAnalysisByStrategy(
|
|
1028
|
+
signal,
|
|
1029
|
+
{
|
|
1030
|
+
direction: approvalAllowedNow ? signalDirection : null,
|
|
1031
|
+
quality: deterministicQuality,
|
|
1032
|
+
needRetest: !approvalAllowedNow,
|
|
1033
|
+
retestPrice: null,
|
|
1034
|
+
takeProfitPrice: approvalAllowedNow ? signal.prices?.takeProfitPrice ?? null : null,
|
|
1035
|
+
stopLossPrice: approvalAllowedNow ? signal.prices?.stopLossPrice ?? null : null
|
|
1036
|
+
},
|
|
1037
|
+
payload
|
|
1038
|
+
);
|
|
1039
|
+
};
|
|
1040
|
+
var askAI = async (signal, options = {}) => {
|
|
1041
|
+
const { symbol } = signal;
|
|
1042
|
+
await ensureAiStrategyPluginsLoaded();
|
|
1043
|
+
const payload = buildAiPayload(signal);
|
|
1044
|
+
const content = await runAiPrompt(
|
|
1045
|
+
{
|
|
1046
|
+
systemPrompt: buildAiSystemPrompt(signal),
|
|
1047
|
+
humanPrompt: buildAiHumanPrompt(signal, payload)
|
|
1048
|
+
},
|
|
1049
|
+
{
|
|
1050
|
+
...options,
|
|
1051
|
+
signal,
|
|
1052
|
+
payload
|
|
1053
|
+
}
|
|
1054
|
+
);
|
|
1055
|
+
await (0, import_redis.setData)(import_redis.redisKeys.analysis(symbol, signal.signalId), content);
|
|
1056
|
+
return content;
|
|
1057
|
+
};
|
|
1058
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1059
|
+
0 && (module.exports = {
|
|
1060
|
+
DEFAULT_AI_MODEL,
|
|
1061
|
+
MAX_AI_SERIES_POINTS,
|
|
1062
|
+
askAI,
|
|
1063
|
+
buildAiHumanPrompt,
|
|
1064
|
+
buildAiPayload,
|
|
1065
|
+
buildAiPrompts,
|
|
1066
|
+
buildAiSystemPrompt,
|
|
1067
|
+
ensureAiStrategyPluginsLoaded,
|
|
1068
|
+
getDeterministicAiGateContext,
|
|
1069
|
+
getOpenRouterModelKwargs,
|
|
1070
|
+
resetAiRuntimeCache,
|
|
1071
|
+
runAiPrompt,
|
|
1072
|
+
runAiPromptLocal,
|
|
1073
|
+
trimSeriesDeep
|
|
1074
|
+
});
|