@tradejs/cli 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.
Files changed (76) hide show
  1. package/dist/cli.js +29748 -13641
  2. package/dist/lib/aiPocketSearch.js +1316 -0
  3. package/dist/lib/aiTrainCharts.js +711 -0
  4. package/dist/lib/aiTrainDataset.js +40 -0
  5. package/dist/lib/aiTrainEvaluationDump.js +76 -0
  6. package/dist/lib/aiTrainMetrics.js +148 -8
  7. package/dist/lib/aiTrainOptions.js +130 -0
  8. package/dist/lib/aiTrainQuarantine.js +199 -0
  9. package/dist/lib/aiTrainResearch.js +467 -0
  10. package/dist/lib/binanceMarketContextBackfill.js +841 -0
  11. package/dist/lib/binanceMarketData.js +392 -0
  12. package/dist/lib/coinMarketCapContextBackfill.js +1088 -0
  13. package/dist/lib/continuity.js +60 -0
  14. package/dist/lib/derivativesContextBackfill.js +490 -77
  15. package/dist/lib/executionCalibration.js +705 -0
  16. package/dist/lib/marketContextPrepare.js +4403 -0
  17. package/dist/lib/paritySummary.js +101 -0
  18. package/dist/lib/runBot.js +1 -0
  19. package/dist/lib/runEnvironment.js +2254 -0
  20. package/dist/lib/runFormatting.js +1657 -0
  21. package/dist/lib/runtimeDebugEvidence.js +526 -0
  22. package/dist/lib/runtimeModeConfig.js +53 -0
  23. package/dist/lib/runtimeParity.js +88 -11
  24. package/dist/lib/runtimeParityDetails.js +751 -0
  25. package/dist/lib/runtimeRedis.js +157 -0
  26. package/dist/lib/runtimeSignalsLoader.js +187 -0
  27. package/dist/lib/runtimeSignalsStorage.js +185 -0
  28. package/dist/lib/runtimeStrategyBacktest.js +134 -0
  29. package/dist/lib/runtimeTradeSync.js +263 -0
  30. package/dist/lib/telegramReports.js +9 -0
  31. package/dist/lib/tickerUniverseCache.js +116 -0
  32. package/dist/lib/timeWindow.js +3 -3
  33. package/dist/scripts/agentRun.js +28 -8
  34. package/dist/scripts/aiExport.js +1721 -7
  35. package/dist/scripts/aiExportSelect.js +16 -4
  36. package/dist/scripts/aiPocketSearch.js +4190 -0
  37. package/dist/scripts/aiTrain.js +1866 -87
  38. package/dist/scripts/backtest.js +4509 -818
  39. package/dist/scripts/binanceMarketIngest.js +565 -0
  40. package/dist/scripts/bot.js +16 -2
  41. package/dist/scripts/candlesMigrateProvider.js +32 -22
  42. package/dist/scripts/cleanDir.js +15 -2
  43. package/dist/scripts/cleanRedis.js +15 -2
  44. package/dist/scripts/cleanTests.js +38 -2
  45. package/dist/scripts/cleanupMarketContext.js +69 -0
  46. package/dist/scripts/continuity.js +148 -67
  47. package/dist/scripts/derivativesIngest.js +14 -4
  48. package/dist/scripts/derivativesIngestCoinalyzeAll.js +14 -4
  49. package/dist/scripts/doctor.js +14 -4
  50. package/dist/scripts/executionCalibration.js +792 -0
  51. package/dist/scripts/infraCommon.js +10 -0
  52. package/dist/scripts/infraDown.js +14 -4
  53. package/dist/scripts/infraInit.js +24 -4
  54. package/dist/scripts/infraUp.js +14 -4
  55. package/dist/scripts/marketWs.js +222 -0
  56. package/dist/scripts/migration.js +15 -2
  57. package/dist/scripts/mlExport.js +1698 -10
  58. package/dist/scripts/mlExportSelect.js +16 -4
  59. package/dist/scripts/mlInspect.js +13 -3
  60. package/dist/scripts/mlTrainLatestSelect.js +14 -4
  61. package/dist/scripts/replay.js +8824 -0
  62. package/dist/scripts/replayRunner.js +8827 -0
  63. package/dist/scripts/replayRuntimeEvidence.js +868 -0
  64. package/dist/scripts/researchAuto.js +289 -60
  65. package/dist/scripts/results.js +3 -3
  66. package/dist/scripts/runtimeEvidence.js +605 -0
  67. package/dist/scripts/runtimeParity.js +6360 -1004
  68. package/dist/scripts/serverHealth.js +588 -0
  69. package/dist/scripts/signals.js +5623 -486
  70. package/dist/scripts/signalsDaemon.js +6167 -0
  71. package/dist/scripts/signalsSummary.js +954 -312
  72. package/dist/scripts/test-ml.js +25 -3
  73. package/dist/scripts/test.js +26 -1
  74. package/dist/scripts/user-add.js +15 -2
  75. package/dist/workers/testerWorker.js +130 -21
  76. package/package.json +18 -12
@@ -0,0 +1,605 @@
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/scripts/runtimeEvidence.ts
31
+ var runtimeEvidence_exports = {};
32
+ __export(runtimeEvidence_exports, {
33
+ main: () => main,
34
+ runtimeEvidence: () => runtimeEvidence
35
+ });
36
+ module.exports = __toCommonJS(runtimeEvidence_exports);
37
+ var import_promises = __toESM(require("fs/promises"));
38
+ var import_node_path = __toESM(require("path"));
39
+ var import_args = __toESM(require("args"));
40
+ var import_chalk = __toESM(require("chalk"));
41
+
42
+ // src/lib/runtimeDebugEvidence.ts
43
+ var import_redis3 = require("@tradejs/infra/redis");
44
+
45
+ // src/lib/runtimeRedis.ts
46
+ var import_redis = require("@tradejs/infra/redis");
47
+ var import_time = require("@tradejs/core/time");
48
+ var RESERVED_STRATEGY_NAMES = /* @__PURE__ */ new Set(["charts"]);
49
+ var RESERVED_CONFIG_IDS = /* @__PURE__ */ new Set(["results"]);
50
+ var resolveStrategyConfigIdentityByKey = (userName, key) => {
51
+ const parts = key.split(":");
52
+ if (parts.length !== 5) return null;
53
+ const [users, keyUserName, strategiesKey, strategyName, configId] = parts;
54
+ if (users !== "users" || keyUserName !== userName || strategiesKey !== "strategies" || !strategyName || !configId || RESERVED_STRATEGY_NAMES.has(strategyName) || RESERVED_CONFIG_IDS.has(configId) || !/^[a-zA-Z0-9_-]+$/.test(configId)) {
55
+ return null;
56
+ }
57
+ return { strategyName, configId };
58
+ };
59
+ var isRuntimeTradeRecord = (value) => {
60
+ if (!value || typeof value !== "object") {
61
+ return false;
62
+ }
63
+ const record = value;
64
+ return typeof record.orderId === "string" && typeof record.strategy === "string" && typeof record.symbol === "string" && typeof record.entryTimestamp === "number" && typeof record.entryPrice === "number" && typeof record.qty === "number" && (record.direction === "LONG" || record.direction === "SHORT");
65
+ };
66
+ var resolveStrategyNameByConfigKey = (userName, key) => {
67
+ return resolveStrategyConfigIdentityByKey(userName, key)?.strategyName ?? null;
68
+ };
69
+ var getRuntimeStrategyConfigKeys = async (userName) => {
70
+ const keys = await (0, import_redis.getKeys)(`${import_redis.redisKeys.strategies(userName)}:`);
71
+ return keys.filter((key) => resolveStrategyConfigIdentityByKey(userName, key)).sort((left, right) => left.localeCompare(right));
72
+ };
73
+ var loadRuntimeStrategyConfigs = async (userName, {
74
+ onInvalidConfig
75
+ } = {}) => {
76
+ const configKeys = await getRuntimeStrategyConfigKeys(userName);
77
+ const strategyConfigs = await Promise.all(
78
+ configKeys.map(async (key) => {
79
+ const strategyName = resolveStrategyNameByConfigKey(userName, key);
80
+ const identity = resolveStrategyConfigIdentityByKey(userName, key);
81
+ if (!strategyName || !identity) {
82
+ return null;
83
+ }
84
+ const strategyConfig = await (0, import_redis.getData)(
85
+ key,
86
+ null
87
+ );
88
+ if (!strategyConfig || typeof strategyConfig !== "object" || Array.isArray(strategyConfig)) {
89
+ onInvalidConfig?.(key);
90
+ return null;
91
+ }
92
+ return {
93
+ key,
94
+ strategyName,
95
+ configId: identity.configId,
96
+ strategyConfig
97
+ };
98
+ })
99
+ );
100
+ return strategyConfigs.filter(Boolean);
101
+ };
102
+ var loadRuntimeTrades = async (userName, {
103
+ startTime,
104
+ endTime
105
+ } = {}) => {
106
+ const hasWindow = Number.isFinite(startTime) && Number.isFinite(endTime) && startTime != null && endTime != null;
107
+ const filterByWindow = (trade) => !hasWindow || trade.entryTimestamp >= startTime && trade.entryTimestamp <= endTime;
108
+ if (hasWindow) {
109
+ const dayKeys = (0, import_time.getRuntimeStorageDayKeys)(startTime, endTime);
110
+ const bucketTrades = (await Promise.all(
111
+ dayKeys.map(
112
+ (dayKey) => (0, import_redis.getHashJsonValues)(
113
+ import_redis.redisKeys.runtimeTradeBucket(userName, dayKey)
114
+ )
115
+ )
116
+ )).flat();
117
+ const dedupedBucketTrades = /* @__PURE__ */ new Map();
118
+ for (const trade of bucketTrades) {
119
+ if (!isRuntimeTradeRecord(trade)) {
120
+ continue;
121
+ }
122
+ dedupedBucketTrades.set(trade.orderId, trade);
123
+ }
124
+ const windowedTrades = [...dedupedBucketTrades.values()].filter(filterByWindow).sort((left, right) => left.entryTimestamp - right.entryTimestamp);
125
+ if (windowedTrades.length > 0 || dayKeys.length === 0) {
126
+ return windowedTrades;
127
+ }
128
+ }
129
+ const tradePrefix = import_redis.redisKeys.runtimeTrades(userName);
130
+ const bucketPrefix = import_redis.redisKeys.runtimeTradeBuckets(userName);
131
+ const keys = (await (0, import_redis.getKeys)(tradePrefix)).filter(
132
+ (key) => !key.startsWith(bucketPrefix)
133
+ );
134
+ const trades = await Promise.all(keys.map((key) => (0, import_redis.getData)(key, null)));
135
+ return trades.filter(isRuntimeTradeRecord).filter(filterByWindow).sort((left, right) => left.entryTimestamp - right.entryTimestamp);
136
+ };
137
+
138
+ // src/lib/runtimeSignalsLoader.ts
139
+ var import_redis2 = require("@tradejs/infra/redis");
140
+
141
+ // src/lib/runtimeSignalsStorage.ts
142
+ var import_constants = require("@tradejs/core/constants");
143
+ var import_time2 = require("@tradejs/core/time");
144
+ var isRuntimeSignalBucketRef = (value) => {
145
+ if (!value || typeof value !== "object") {
146
+ return false;
147
+ }
148
+ const record = value;
149
+ return typeof record.signalId === "string" && typeof record.symbol === "string" && typeof record.strategy === "string" && typeof record.timestamp === "number";
150
+ };
151
+ var toCount = (value) => {
152
+ const parsed = Number.parseInt(String(value ?? "0"), 10);
153
+ return Number.isFinite(parsed) ? parsed : 0;
154
+ };
155
+ var parseRuntimeSignalStatsBucket = (value) => {
156
+ const reasonGroups = /* @__PURE__ */ new Map();
157
+ for (const [field, rawCount] of Object.entries(value)) {
158
+ if (!field.startsWith("reason:")) {
159
+ continue;
160
+ }
161
+ const [, source, ...reasonParts] = field.split(":");
162
+ const reason = reasonParts.join(":");
163
+ if (!source || !reason) {
164
+ continue;
165
+ }
166
+ const reasons = reasonGroups.get(source) ?? /* @__PURE__ */ new Map();
167
+ reasons.set(reason, toCount(rawCount));
168
+ reasonGroups.set(source, reasons);
169
+ }
170
+ return {
171
+ evaluated: toCount(value.evaluated),
172
+ signals: toCount(value.signals),
173
+ reasonGroups
174
+ };
175
+ };
176
+
177
+ // src/lib/runtimeSignalsLoader.ts
178
+ var isSignalRecord = (value) => {
179
+ if (!value || typeof value !== "object") {
180
+ return false;
181
+ }
182
+ const record = value;
183
+ return typeof record.signalId === "string" && typeof record.strategy === "string" && typeof record.symbol === "string" && typeof record.timestamp === "number";
184
+ };
185
+ var isRuntimeSignalEvaluationRecord = (value) => {
186
+ if (!value || typeof value !== "object") {
187
+ return false;
188
+ }
189
+ const record = value;
190
+ return typeof record.evaluationId === "string" && typeof record.strategy === "string" && typeof record.symbol === "string" && typeof record.timestamp === "number" && (record.status === "signal" || record.status === "skip" || record.status === "error");
191
+ };
192
+ var sortByTimestamp = (records) => [...records].sort((left, right) => left.timestamp - right.timestamp);
193
+ var filterBucketKeysByWindow = (bucketKeys, prefix, startTime, endTime) => {
194
+ if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || startTime == null || endTime == null) {
195
+ return bucketKeys;
196
+ }
197
+ const allowedDayKeys = new Set((0, import_time2.getRuntimeStorageDayKeys)(startTime, endTime));
198
+ if (!allowedDayKeys.size) {
199
+ return [];
200
+ }
201
+ return bucketKeys.filter((key) => {
202
+ const suffix = key.slice(prefix.length);
203
+ const firstColon = suffix.indexOf(":");
204
+ if (firstColon <= 0) {
205
+ return false;
206
+ }
207
+ return allowedDayKeys.has(suffix.slice(0, firstColon));
208
+ });
209
+ };
210
+ var loadRuntimeSignals = async (userName, {
211
+ startTime,
212
+ endTime
213
+ } = {}) => {
214
+ const bucketPrefix = import_redis2.redisKeys.runtimeSignalBuckets(userName);
215
+ const bucketKeys = filterBucketKeysByWindow(
216
+ await (0, import_redis2.getKeys)(bucketPrefix),
217
+ bucketPrefix,
218
+ startTime,
219
+ endTime
220
+ );
221
+ const refs = (await Promise.all(bucketKeys.map((key) => (0, import_redis2.getHashJsonValues)(key)))).flat().filter(isRuntimeSignalBucketRef);
222
+ const seen = /* @__PURE__ */ new Set();
223
+ const payloads = await Promise.all(
224
+ refs.map(async (ref) => {
225
+ const dedupeKey = `${ref.symbol}:${ref.signalId}`;
226
+ if (seen.has(dedupeKey)) {
227
+ return null;
228
+ }
229
+ seen.add(dedupeKey);
230
+ const signal = await (0, import_redis2.getData)(
231
+ import_redis2.redisKeys.storeSignal(ref.symbol, ref.signalId),
232
+ null
233
+ );
234
+ return isSignalRecord(signal) ? signal : null;
235
+ })
236
+ );
237
+ return sortByTimestamp(payloads.filter(isSignalRecord));
238
+ };
239
+ var loadRuntimeSignalEvaluations = async (userName, {
240
+ startTime,
241
+ endTime
242
+ } = {}) => {
243
+ const bucketPrefix = import_redis2.redisKeys.runtimeSignalEvaluationBuckets(userName);
244
+ const bucketKeys = filterBucketKeysByWindow(
245
+ await (0, import_redis2.getKeys)(bucketPrefix),
246
+ bucketPrefix,
247
+ startTime,
248
+ endTime
249
+ );
250
+ const evaluations = (await Promise.all(bucketKeys.map((key) => (0, import_redis2.getHashJsonValues)(key)))).flat().filter(isRuntimeSignalEvaluationRecord);
251
+ const deduped = /* @__PURE__ */ new Map();
252
+ for (const evaluation of evaluations) {
253
+ deduped.set(evaluation.evaluationId, evaluation);
254
+ }
255
+ return sortByTimestamp([...deduped.values()]);
256
+ };
257
+ var parseBucketKey = (prefix, key) => {
258
+ if (!key.startsWith(prefix)) {
259
+ return null;
260
+ }
261
+ const suffix = key.slice(prefix.length);
262
+ const firstColon = suffix.indexOf(":");
263
+ if (firstColon <= 0 || firstColon >= suffix.length - 1) {
264
+ return null;
265
+ }
266
+ return {
267
+ dayKey: suffix.slice(0, firstColon),
268
+ strategy: suffix.slice(firstColon + 1)
269
+ };
270
+ };
271
+ var loadRuntimeSignalEvaluationStatsBuckets = async (userName) => {
272
+ const prefix = import_redis2.redisKeys.runtimeSignalEvaluationStatsBuckets(userName);
273
+ const keys = await (0, import_redis2.getKeys)(prefix);
274
+ const entries = await Promise.all(
275
+ keys.map(async (key) => {
276
+ const parsedKey = parseBucketKey(prefix, key);
277
+ if (!parsedKey) {
278
+ return null;
279
+ }
280
+ return {
281
+ key,
282
+ ...parsedKey,
283
+ stats: parseRuntimeSignalStatsBucket(await (0, import_redis2.getHashData)(key))
284
+ };
285
+ })
286
+ );
287
+ return entries.filter(Boolean);
288
+ };
289
+
290
+ // src/lib/runtimeDebugEvidence.ts
291
+ var RUNTIME_DEBUG_TIMEZONE = "Europe/Moscow";
292
+ var formatRuntimeDebugDateTime = (timestamp) => new Intl.DateTimeFormat("ru-RU", {
293
+ timeZone: RUNTIME_DEBUG_TIMEZONE,
294
+ year: "numeric",
295
+ month: "2-digit",
296
+ day: "2-digit",
297
+ hour: "2-digit",
298
+ minute: "2-digit",
299
+ hour12: false
300
+ }).format(new Date(timestamp));
301
+ var buildRuntimeDebugEvaluationId = ({
302
+ strategy,
303
+ symbol,
304
+ timestamp
305
+ }) => `${strategy}:${symbol}:${timestamp}`;
306
+ var filterByStrategies = (values, strategies) => {
307
+ if (!strategies?.length) {
308
+ return values;
309
+ }
310
+ const strategySet = new Set(strategies);
311
+ return values.filter((value) => strategySet.has(value.strategy));
312
+ };
313
+ var collectRuntimeDebugEvidence = async ({
314
+ userName,
315
+ startTime,
316
+ endTime,
317
+ strategies
318
+ }) => {
319
+ const dayKeys = (0, import_time2.getRuntimeStorageDayKeys)(startTime, endTime);
320
+ const dayKeySet = new Set(dayKeys);
321
+ const [trades, signals, evaluations, evaluationStatsBuckets, configs] = await Promise.all([
322
+ loadRuntimeTrades(userName, { startTime, endTime }),
323
+ loadRuntimeSignals(userName, { startTime, endTime }),
324
+ loadRuntimeSignalEvaluations(userName, { startTime, endTime }),
325
+ loadRuntimeSignalEvaluationStatsBuckets(userName),
326
+ loadRuntimeStrategyConfigs(userName)
327
+ ]);
328
+ const filteredStats = evaluationStatsBuckets.filter(
329
+ (entry) => dayKeySet.has(entry.dayKey) && (!strategies?.length || strategies.includes(entry.strategy))
330
+ );
331
+ return {
332
+ dayKeys,
333
+ trades: filterByStrategies(trades, strategies),
334
+ signals: filterByStrategies(signals, strategies),
335
+ evaluations: filterByStrategies(evaluations, strategies),
336
+ evaluationStatsBuckets: filteredStats,
337
+ strategyConfigs: configs.filter(
338
+ (config) => !strategies?.length || strategies.includes(config.strategyName)
339
+ )
340
+ };
341
+ };
342
+ var buildRuntimeDebugReportPayload = async ({
343
+ userName,
344
+ startTime,
345
+ endTime,
346
+ signals,
347
+ evaluations,
348
+ trades,
349
+ strategyConfigs,
350
+ evaluationStatsBuckets
351
+ }) => {
352
+ const signalById = new Map(
353
+ signals.map((signal) => [signal.signalId, signal])
354
+ );
355
+ const evaluationById = new Map(
356
+ evaluations.map((evaluation) => [evaluation.evaluationId, evaluation])
357
+ );
358
+ const evaluationBySignalShape = new Map(
359
+ evaluations.map((evaluation) => [
360
+ buildRuntimeDebugEvaluationId(evaluation),
361
+ evaluation
362
+ ])
363
+ );
364
+ const dayKeys = (0, import_time2.getRuntimeStorageDayKeys)(startTime, endTime);
365
+ const debugTrades = await Promise.all(
366
+ trades.map(async (trade) => {
367
+ const signal = trade.signalId != null ? signalById.get(trade.signalId) : void 0;
368
+ const evaluationId = buildRuntimeDebugEvaluationId({
369
+ strategy: trade.strategy,
370
+ symbol: trade.symbol,
371
+ timestamp: signal?.timestamp ?? trade.entryTimestamp
372
+ });
373
+ const knownEvaluation = evaluationById.get(evaluationId) ?? evaluationBySignalShape.get(evaluationId);
374
+ const tradeDayKey = (0, import_time2.getRuntimeStorageDayKey)(trade.entryTimestamp);
375
+ const signalDayKey = signal != null ? (0, import_time2.getRuntimeStorageDayKey)(signal.timestamp) : tradeDayKey;
376
+ const evaluationDayKey = knownEvaluation != null ? (0, import_time2.getRuntimeStorageDayKey)(knownEvaluation.timestamp) : signalDayKey;
377
+ const tradeKey = import_redis3.redisKeys.runtimeTrade(userName, trade.orderId);
378
+ const tradeBucketKey = import_redis3.redisKeys.runtimeTradeBucket(
379
+ userName,
380
+ tradeDayKey
381
+ );
382
+ const activeTradeKey = import_redis3.redisKeys.runtimeActiveTrade(
383
+ userName,
384
+ trade.symbol
385
+ );
386
+ const signalKey = trade.signalId != null ? import_redis3.redisKeys.storeSignal(trade.symbol, trade.signalId) : null;
387
+ const evaluationBucketKey = import_redis3.redisKeys.runtimeSignalEvaluationBucket(
388
+ userName,
389
+ evaluationDayKey,
390
+ knownEvaluation?.strategy ?? trade.strategy
391
+ );
392
+ const evaluationField = knownEvaluation?.evaluationId ?? evaluationId;
393
+ const evaluationKey = import_redis3.redisKeys.runtimeSignalEvaluation(
394
+ userName,
395
+ evaluationField
396
+ );
397
+ const [
398
+ tradeValue,
399
+ activeTradeValue,
400
+ signalValue,
401
+ directEvaluationValue,
402
+ bucketEvaluationValue
403
+ ] = await Promise.all([
404
+ (0, import_redis3.getData)(tradeKey, null),
405
+ (0, import_redis3.getData)(activeTradeKey, null),
406
+ signalKey ? (0, import_redis3.getData)(signalKey, null) : Promise.resolve(null),
407
+ (0, import_redis3.getData)(evaluationKey, null),
408
+ knownEvaluation ? Promise.resolve(knownEvaluation) : (0, import_redis3.getHashJsonField)(
409
+ evaluationBucketKey,
410
+ evaluationField,
411
+ null
412
+ )
413
+ ]);
414
+ const evaluationValue = directEvaluationValue ?? bucketEvaluationValue ?? knownEvaluation ?? null;
415
+ return {
416
+ redisDebug: {
417
+ trade: tradeKey,
418
+ tradeBucket: {
419
+ key: tradeBucketKey,
420
+ field: trade.orderId
421
+ },
422
+ activeTrade: activeTradeKey,
423
+ signal: signalKey,
424
+ evaluation: {
425
+ key: evaluationBucketKey,
426
+ field: evaluationField,
427
+ directKey: evaluationKey
428
+ }
429
+ },
430
+ trade,
431
+ redisValues: {
432
+ trade: tradeValue,
433
+ tradeBucket: trade,
434
+ activeTrade: activeTradeValue,
435
+ signal: signalValue ?? signal ?? null,
436
+ evaluation: evaluationValue ?? knownEvaluation ?? null
437
+ }
438
+ };
439
+ })
440
+ );
441
+ const linkedEvaluations = /* @__PURE__ */ new Map();
442
+ for (const trade of debugTrades) {
443
+ const evaluation = trade.redisValues.evaluation;
444
+ if (evaluation && typeof evaluation === "object" && "evaluationId" in evaluation && typeof evaluation.evaluationId === "string") {
445
+ linkedEvaluations.set(
446
+ evaluation.evaluationId,
447
+ evaluation
448
+ );
449
+ }
450
+ }
451
+ const reportEvaluations = evaluations.length > 0 ? evaluations : [...linkedEvaluations.values()];
452
+ return {
453
+ reportType: "runtime-daily-debug",
454
+ generatedAt: Date.now(),
455
+ generatedAtMsk: formatRuntimeDebugDateTime(Date.now()),
456
+ userName,
457
+ window: {
458
+ startTime,
459
+ endTime,
460
+ startMsk: formatRuntimeDebugDateTime(startTime),
461
+ endMsk: formatRuntimeDebugDateTime(endTime),
462
+ dayKeys
463
+ },
464
+ redisPrefixes: {
465
+ runtimeTrades: import_redis3.redisKeys.runtimeTrades(userName),
466
+ runtimeTradeBuckets: import_redis3.redisKeys.runtimeTradeBuckets(userName),
467
+ runtimeActiveTrades: import_redis3.redisKeys.runtimeActiveTrades(userName),
468
+ runtimeSignals: import_redis3.redisKeys.runtimeSignalBuckets(userName),
469
+ runtimeSignalEvaluations: import_redis3.redisKeys.runtimeSignalEvaluationBuckets(userName),
470
+ runtimeSignalEvaluationStats: import_redis3.redisKeys.runtimeSignalEvaluationStatsBuckets(userName)
471
+ },
472
+ counts: {
473
+ trades: trades.length,
474
+ signals: signals.length,
475
+ evaluations: reportEvaluations.length,
476
+ evaluationStatsBuckets: evaluationStatsBuckets?.length ?? 0,
477
+ strategyConfigs: strategyConfigs?.length ?? 0
478
+ },
479
+ trades: debugTrades,
480
+ signals: signals.map((signal) => ({
481
+ redisKey: import_redis3.redisKeys.storeSignal(signal.symbol, signal.signalId),
482
+ signal
483
+ })),
484
+ evaluations: reportEvaluations.map((evaluation) => ({
485
+ redisDebug: {
486
+ key: import_redis3.redisKeys.runtimeSignalEvaluationBucket(
487
+ userName,
488
+ (0, import_time2.getRuntimeStorageDayKey)(evaluation.timestamp),
489
+ evaluation.strategy
490
+ ),
491
+ field: evaluation.evaluationId,
492
+ directKey: import_redis3.redisKeys.runtimeSignalEvaluation(
493
+ userName,
494
+ evaluation.evaluationId
495
+ )
496
+ },
497
+ evaluation
498
+ })),
499
+ evaluationStatsBuckets: evaluationStatsBuckets ?? [],
500
+ strategyConfigs: strategyConfigs ?? []
501
+ };
502
+ };
503
+
504
+ // src/scripts/runtimeEvidence.ts
505
+ import_args.default.option(["u", "user"], "Use user config", "root");
506
+ import_args.default.option(
507
+ ["S", "startTime"],
508
+ "Window start timestamp, seconds/ms, or ISO date"
509
+ );
510
+ import_args.default.option(["E", "endTime"], "Window end timestamp, seconds/ms, or ISO date");
511
+ import_args.default.option(
512
+ ["H", "hours"],
513
+ "Fallback window in hours when start/end are omitted",
514
+ 24
515
+ );
516
+ import_args.default.option(["s", "strategy"], "Strategy filter, comma-separated");
517
+ import_args.default.option(["o", "out"], "Output JSON path", "output/runtime-evidence.json");
518
+ var flags = import_args.default.parse(process.argv);
519
+ var projectRoot = String(process.env.PROJECT_CWD || process.cwd()).trim() || process.cwd();
520
+ var toEpochMs = (value) => {
521
+ if (value == null || value === "") {
522
+ return null;
523
+ }
524
+ const raw = String(value).trim();
525
+ if (/^\d+$/.test(raw)) {
526
+ const parsed2 = Number(raw);
527
+ return parsed2 < 1e12 ? Math.trunc(parsed2 * 1e3) : Math.trunc(parsed2);
528
+ }
529
+ const parsed = Date.parse(raw);
530
+ return Number.isFinite(parsed) ? parsed : null;
531
+ };
532
+ var resolveWindow = () => {
533
+ const endTime = toEpochMs(flags.endTime) ?? Date.now();
534
+ const hours = Math.max(
535
+ 1,
536
+ Number.parseInt(String(flags.hours ?? 24), 10) || 24
537
+ );
538
+ const startTime = toEpochMs(flags.startTime) ?? endTime - hours * 60 * 60 * 1e3;
539
+ if (startTime >= endTime) {
540
+ throw new Error(
541
+ `Invalid window: startTime (${startTime}) must be less than endTime (${endTime})`
542
+ );
543
+ }
544
+ return {
545
+ startTime,
546
+ endTime,
547
+ source: flags.startTime != null || flags.endTime != null ? "explicit" : "hours"
548
+ };
549
+ };
550
+ var parseStrategyFilter = (value) => String(value ?? "").split(",").map((item) => item.trim()).filter(Boolean);
551
+ var runtimeEvidence = async () => {
552
+ const { startTime, endTime, source } = resolveWindow();
553
+ const strategies = parseStrategyFilter(flags.strategy);
554
+ const evidence = await collectRuntimeDebugEvidence({
555
+ userName: flags.user,
556
+ startTime,
557
+ endTime,
558
+ strategies: strategies.length ? strategies : void 0
559
+ });
560
+ const runtime = await buildRuntimeDebugReportPayload({
561
+ userName: flags.user,
562
+ startTime,
563
+ endTime,
564
+ signals: evidence.signals,
565
+ evaluations: evidence.evaluations,
566
+ trades: evidence.trades,
567
+ strategyConfigs: evidence.strategyConfigs,
568
+ evaluationStatsBuckets: evidence.evaluationStatsBuckets
569
+ });
570
+ const artifact = {
571
+ reportType: "runtime-evidence",
572
+ generatedAt: Date.now(),
573
+ userName: flags.user,
574
+ window: {
575
+ startTime,
576
+ endTime,
577
+ startIso: new Date(startTime).toISOString(),
578
+ endIso: new Date(endTime).toISOString(),
579
+ source
580
+ },
581
+ strategies,
582
+ runtime
583
+ };
584
+ const outPath = import_node_path.default.resolve(projectRoot, String(flags.out));
585
+ await import_promises.default.mkdir(import_node_path.default.dirname(outPath), { recursive: true });
586
+ await import_promises.default.writeFile(outPath, `${JSON.stringify(artifact, null, 2)}
587
+ `, "utf8");
588
+ console.log(import_chalk.default.green(`Wrote ${outPath}`));
589
+ console.log(
590
+ JSON.stringify(
591
+ {
592
+ strategies: artifact.strategies,
593
+ runtimeCounts: artifact.runtime.counts
594
+ },
595
+ null,
596
+ 2
597
+ )
598
+ );
599
+ };
600
+ var main = runtimeEvidence;
601
+ // Annotate the CommonJS export names for ESM import in node:
602
+ 0 && (module.exports = {
603
+ main,
604
+ runtimeEvidence
605
+ });