@tradejs/cli 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.
Files changed (34) hide show
  1. package/README.md +4 -1
  2. package/dist/cli.js +13791 -7652
  3. package/dist/lib/aiTrainMetrics.js +173 -0
  4. package/dist/lib/candlesProviderMigration.js +266 -0
  5. package/dist/lib/cliArgs.js +40 -0
  6. package/dist/lib/derivativesContextBackfill.js +487 -0
  7. package/dist/lib/researchAgent.js +195 -0
  8. package/dist/lib/runtimeParity.js +234 -0
  9. package/dist/lib/telegramReports.js +91 -0
  10. package/dist/lib/timeWindow.js +101 -0
  11. package/dist/scripts/agentRun.js +895 -0
  12. package/dist/scripts/aiExport.js +192 -0
  13. package/dist/scripts/aiExportSelect.js +135 -0
  14. package/dist/scripts/aiTrain.js +2321 -0
  15. package/dist/scripts/backtest.js +998 -111
  16. package/dist/scripts/candlesMigrateProvider.js +5302 -0
  17. package/dist/scripts/continuity.js +1 -1
  18. package/dist/scripts/derivativesIngest.js +5 -0
  19. package/dist/scripts/derivativesIngestCoinalyzeAll.js +21 -12
  20. package/dist/scripts/migration.js +1 -1
  21. package/dist/scripts/mlExport.js +112 -13
  22. package/dist/scripts/mlExportSelect.js +43 -9
  23. package/dist/scripts/mlTrainLatestSelect.js +4 -3
  24. package/dist/scripts/researchAuto.js +845 -0
  25. package/dist/scripts/resolveExportStrategy.js +133 -0
  26. package/dist/scripts/results.js +46 -22
  27. package/dist/scripts/runtimeParity.js +1651 -0
  28. package/dist/scripts/selectStrategy.js +4 -3
  29. package/dist/scripts/signals.js +799 -62
  30. package/dist/scripts/signalsSummary.js +655 -0
  31. package/dist/scripts/spawnSiblingScript.js +71 -0
  32. package/dist/scripts/user-add.js +0 -9
  33. package/dist/workers/testerWorker.js +13 -2
  34. package/package.json +18 -12
@@ -0,0 +1,2321 @@
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 __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+
28
+ // ../../node_modules/debug/node_modules/ms/index.js
29
+ var require_ms = __commonJS({
30
+ "../../node_modules/debug/node_modules/ms/index.js"(exports2, module2) {
31
+ "use strict";
32
+ var s = 1e3;
33
+ var m = s * 60;
34
+ var h = m * 60;
35
+ var d = h * 24;
36
+ var w = d * 7;
37
+ var y = d * 365.25;
38
+ module2.exports = function(val, options) {
39
+ options = options || {};
40
+ var type = typeof val;
41
+ if (type === "string" && val.length > 0) {
42
+ return parse(val);
43
+ } else if (type === "number" && isFinite(val)) {
44
+ return options.long ? fmtLong(val) : fmtShort(val);
45
+ }
46
+ throw new Error(
47
+ "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
48
+ );
49
+ };
50
+ function parse(str) {
51
+ str = String(str);
52
+ if (str.length > 100) {
53
+ return;
54
+ }
55
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
56
+ str
57
+ );
58
+ if (!match) {
59
+ return;
60
+ }
61
+ var n = parseFloat(match[1]);
62
+ var type = (match[2] || "ms").toLowerCase();
63
+ switch (type) {
64
+ case "years":
65
+ case "year":
66
+ case "yrs":
67
+ case "yr":
68
+ case "y":
69
+ return n * y;
70
+ case "weeks":
71
+ case "week":
72
+ case "w":
73
+ return n * w;
74
+ case "days":
75
+ case "day":
76
+ case "d":
77
+ return n * d;
78
+ case "hours":
79
+ case "hour":
80
+ case "hrs":
81
+ case "hr":
82
+ case "h":
83
+ return n * h;
84
+ case "minutes":
85
+ case "minute":
86
+ case "mins":
87
+ case "min":
88
+ case "m":
89
+ return n * m;
90
+ case "seconds":
91
+ case "second":
92
+ case "secs":
93
+ case "sec":
94
+ case "s":
95
+ return n * s;
96
+ case "milliseconds":
97
+ case "millisecond":
98
+ case "msecs":
99
+ case "msec":
100
+ case "ms":
101
+ return n;
102
+ default:
103
+ return void 0;
104
+ }
105
+ }
106
+ function fmtShort(ms) {
107
+ var msAbs = Math.abs(ms);
108
+ if (msAbs >= d) {
109
+ return Math.round(ms / d) + "d";
110
+ }
111
+ if (msAbs >= h) {
112
+ return Math.round(ms / h) + "h";
113
+ }
114
+ if (msAbs >= m) {
115
+ return Math.round(ms / m) + "m";
116
+ }
117
+ if (msAbs >= s) {
118
+ return Math.round(ms / s) + "s";
119
+ }
120
+ return ms + "ms";
121
+ }
122
+ function fmtLong(ms) {
123
+ var msAbs = Math.abs(ms);
124
+ if (msAbs >= d) {
125
+ return plural(ms, msAbs, d, "day");
126
+ }
127
+ if (msAbs >= h) {
128
+ return plural(ms, msAbs, h, "hour");
129
+ }
130
+ if (msAbs >= m) {
131
+ return plural(ms, msAbs, m, "minute");
132
+ }
133
+ if (msAbs >= s) {
134
+ return plural(ms, msAbs, s, "second");
135
+ }
136
+ return ms + " ms";
137
+ }
138
+ function plural(ms, msAbs, n, name) {
139
+ var isPlural = msAbs >= n * 1.5;
140
+ return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
141
+ }
142
+ }
143
+ });
144
+
145
+ // ../../node_modules/debug/src/common.js
146
+ var require_common = __commonJS({
147
+ "../../node_modules/debug/src/common.js"(exports2, module2) {
148
+ "use strict";
149
+ function setup(env) {
150
+ createDebug.debug = createDebug;
151
+ createDebug.default = createDebug;
152
+ createDebug.coerce = coerce;
153
+ createDebug.disable = disable;
154
+ createDebug.enable = enable;
155
+ createDebug.enabled = enabled;
156
+ createDebug.humanize = require_ms();
157
+ createDebug.destroy = destroy;
158
+ Object.keys(env).forEach((key) => {
159
+ createDebug[key] = env[key];
160
+ });
161
+ createDebug.names = [];
162
+ createDebug.skips = [];
163
+ createDebug.formatters = {};
164
+ function selectColor(namespace) {
165
+ let hash = 0;
166
+ for (let i = 0; i < namespace.length; i++) {
167
+ hash = (hash << 5) - hash + namespace.charCodeAt(i);
168
+ hash |= 0;
169
+ }
170
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
171
+ }
172
+ createDebug.selectColor = selectColor;
173
+ function createDebug(namespace) {
174
+ let prevTime;
175
+ let enableOverride = null;
176
+ let namespacesCache;
177
+ let enabledCache;
178
+ function debug(...args2) {
179
+ if (!debug.enabled) {
180
+ return;
181
+ }
182
+ const self = debug;
183
+ const curr = Number(/* @__PURE__ */ new Date());
184
+ const ms = curr - (prevTime || curr);
185
+ self.diff = ms;
186
+ self.prev = prevTime;
187
+ self.curr = curr;
188
+ prevTime = curr;
189
+ args2[0] = createDebug.coerce(args2[0]);
190
+ if (typeof args2[0] !== "string") {
191
+ args2.unshift("%O");
192
+ }
193
+ let index = 0;
194
+ args2[0] = args2[0].replace(/%([a-zA-Z%])/g, (match, format) => {
195
+ if (match === "%%") {
196
+ return "%";
197
+ }
198
+ index++;
199
+ const formatter = createDebug.formatters[format];
200
+ if (typeof formatter === "function") {
201
+ const val = args2[index];
202
+ match = formatter.call(self, val);
203
+ args2.splice(index, 1);
204
+ index--;
205
+ }
206
+ return match;
207
+ });
208
+ createDebug.formatArgs.call(self, args2);
209
+ const logFn = self.log || createDebug.log;
210
+ logFn.apply(self, args2);
211
+ }
212
+ debug.namespace = namespace;
213
+ debug.useColors = createDebug.useColors();
214
+ debug.color = createDebug.selectColor(namespace);
215
+ debug.extend = extend;
216
+ debug.destroy = createDebug.destroy;
217
+ Object.defineProperty(debug, "enabled", {
218
+ enumerable: true,
219
+ configurable: false,
220
+ get: () => {
221
+ if (enableOverride !== null) {
222
+ return enableOverride;
223
+ }
224
+ if (namespacesCache !== createDebug.namespaces) {
225
+ namespacesCache = createDebug.namespaces;
226
+ enabledCache = createDebug.enabled(namespace);
227
+ }
228
+ return enabledCache;
229
+ },
230
+ set: (v) => {
231
+ enableOverride = v;
232
+ }
233
+ });
234
+ if (typeof createDebug.init === "function") {
235
+ createDebug.init(debug);
236
+ }
237
+ return debug;
238
+ }
239
+ function extend(namespace, delimiter) {
240
+ const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
241
+ newDebug.log = this.log;
242
+ return newDebug;
243
+ }
244
+ function enable(namespaces) {
245
+ createDebug.save(namespaces);
246
+ createDebug.namespaces = namespaces;
247
+ createDebug.names = [];
248
+ createDebug.skips = [];
249
+ let i;
250
+ const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
251
+ const len = split.length;
252
+ for (i = 0; i < len; i++) {
253
+ if (!split[i]) {
254
+ continue;
255
+ }
256
+ namespaces = split[i].replace(/\*/g, ".*?");
257
+ if (namespaces[0] === "-") {
258
+ createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$"));
259
+ } else {
260
+ createDebug.names.push(new RegExp("^" + namespaces + "$"));
261
+ }
262
+ }
263
+ }
264
+ function disable() {
265
+ const namespaces = [
266
+ ...createDebug.names.map(toNamespace),
267
+ ...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
268
+ ].join(",");
269
+ createDebug.enable("");
270
+ return namespaces;
271
+ }
272
+ function enabled(name) {
273
+ if (name[name.length - 1] === "*") {
274
+ return true;
275
+ }
276
+ let i;
277
+ let len;
278
+ for (i = 0, len = createDebug.skips.length; i < len; i++) {
279
+ if (createDebug.skips[i].test(name)) {
280
+ return false;
281
+ }
282
+ }
283
+ for (i = 0, len = createDebug.names.length; i < len; i++) {
284
+ if (createDebug.names[i].test(name)) {
285
+ return true;
286
+ }
287
+ }
288
+ return false;
289
+ }
290
+ function toNamespace(regexp) {
291
+ return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
292
+ }
293
+ function coerce(val) {
294
+ if (val instanceof Error) {
295
+ return val.stack || val.message;
296
+ }
297
+ return val;
298
+ }
299
+ function destroy() {
300
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
301
+ }
302
+ createDebug.enable(createDebug.load());
303
+ return createDebug;
304
+ }
305
+ module2.exports = setup;
306
+ }
307
+ });
308
+
309
+ // ../../node_modules/debug/src/browser.js
310
+ var require_browser = __commonJS({
311
+ "../../node_modules/debug/src/browser.js"(exports2, module2) {
312
+ "use strict";
313
+ exports2.formatArgs = formatArgs;
314
+ exports2.save = save;
315
+ exports2.load = load;
316
+ exports2.useColors = useColors;
317
+ exports2.storage = localstorage();
318
+ exports2.destroy = /* @__PURE__ */ (() => {
319
+ let warned = false;
320
+ return () => {
321
+ if (!warned) {
322
+ warned = true;
323
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
324
+ }
325
+ };
326
+ })();
327
+ exports2.colors = [
328
+ "#0000CC",
329
+ "#0000FF",
330
+ "#0033CC",
331
+ "#0033FF",
332
+ "#0066CC",
333
+ "#0066FF",
334
+ "#0099CC",
335
+ "#0099FF",
336
+ "#00CC00",
337
+ "#00CC33",
338
+ "#00CC66",
339
+ "#00CC99",
340
+ "#00CCCC",
341
+ "#00CCFF",
342
+ "#3300CC",
343
+ "#3300FF",
344
+ "#3333CC",
345
+ "#3333FF",
346
+ "#3366CC",
347
+ "#3366FF",
348
+ "#3399CC",
349
+ "#3399FF",
350
+ "#33CC00",
351
+ "#33CC33",
352
+ "#33CC66",
353
+ "#33CC99",
354
+ "#33CCCC",
355
+ "#33CCFF",
356
+ "#6600CC",
357
+ "#6600FF",
358
+ "#6633CC",
359
+ "#6633FF",
360
+ "#66CC00",
361
+ "#66CC33",
362
+ "#9900CC",
363
+ "#9900FF",
364
+ "#9933CC",
365
+ "#9933FF",
366
+ "#99CC00",
367
+ "#99CC33",
368
+ "#CC0000",
369
+ "#CC0033",
370
+ "#CC0066",
371
+ "#CC0099",
372
+ "#CC00CC",
373
+ "#CC00FF",
374
+ "#CC3300",
375
+ "#CC3333",
376
+ "#CC3366",
377
+ "#CC3399",
378
+ "#CC33CC",
379
+ "#CC33FF",
380
+ "#CC6600",
381
+ "#CC6633",
382
+ "#CC9900",
383
+ "#CC9933",
384
+ "#CCCC00",
385
+ "#CCCC33",
386
+ "#FF0000",
387
+ "#FF0033",
388
+ "#FF0066",
389
+ "#FF0099",
390
+ "#FF00CC",
391
+ "#FF00FF",
392
+ "#FF3300",
393
+ "#FF3333",
394
+ "#FF3366",
395
+ "#FF3399",
396
+ "#FF33CC",
397
+ "#FF33FF",
398
+ "#FF6600",
399
+ "#FF6633",
400
+ "#FF9900",
401
+ "#FF9933",
402
+ "#FFCC00",
403
+ "#FFCC33"
404
+ ];
405
+ function useColors() {
406
+ if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
407
+ return true;
408
+ }
409
+ if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
410
+ return false;
411
+ }
412
+ return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
413
+ typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
414
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
415
+ typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
416
+ typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
417
+ }
418
+ function formatArgs(args2) {
419
+ args2[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args2[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
420
+ if (!this.useColors) {
421
+ return;
422
+ }
423
+ const c = "color: " + this.color;
424
+ args2.splice(1, 0, c, "color: inherit");
425
+ let index = 0;
426
+ let lastC = 0;
427
+ args2[0].replace(/%[a-zA-Z%]/g, (match) => {
428
+ if (match === "%%") {
429
+ return;
430
+ }
431
+ index++;
432
+ if (match === "%c") {
433
+ lastC = index;
434
+ }
435
+ });
436
+ args2.splice(lastC, 0, c);
437
+ }
438
+ exports2.log = console.debug || console.log || (() => {
439
+ });
440
+ function save(namespaces) {
441
+ try {
442
+ if (namespaces) {
443
+ exports2.storage.setItem("debug", namespaces);
444
+ } else {
445
+ exports2.storage.removeItem("debug");
446
+ }
447
+ } catch (error) {
448
+ }
449
+ }
450
+ function load() {
451
+ let r;
452
+ try {
453
+ r = exports2.storage.getItem("debug");
454
+ } catch (error) {
455
+ }
456
+ if (!r && typeof process !== "undefined" && "env" in process) {
457
+ r = process.env.DEBUG;
458
+ }
459
+ return r;
460
+ }
461
+ function localstorage() {
462
+ try {
463
+ return localStorage;
464
+ } catch (error) {
465
+ }
466
+ }
467
+ module2.exports = require_common()(exports2);
468
+ var { formatters } = module2.exports;
469
+ formatters.j = function(v) {
470
+ try {
471
+ return JSON.stringify(v);
472
+ } catch (error) {
473
+ return "[UnexpectedJSONParseError]: " + error.message;
474
+ }
475
+ };
476
+ }
477
+ });
478
+
479
+ // ../../node_modules/has-flag/index.js
480
+ var require_has_flag = __commonJS({
481
+ "../../node_modules/has-flag/index.js"(exports2, module2) {
482
+ "use strict";
483
+ module2.exports = (flag, argv = process.argv) => {
484
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
485
+ const position = argv.indexOf(prefix + flag);
486
+ const terminatorPosition = argv.indexOf("--");
487
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
488
+ };
489
+ }
490
+ });
491
+
492
+ // ../../node_modules/supports-color/index.js
493
+ var require_supports_color = __commonJS({
494
+ "../../node_modules/supports-color/index.js"(exports2, module2) {
495
+ "use strict";
496
+ var os = require("os");
497
+ var tty = require("tty");
498
+ var hasFlag = require_has_flag();
499
+ var { env } = process;
500
+ var flagForceColor;
501
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
502
+ flagForceColor = 0;
503
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
504
+ flagForceColor = 1;
505
+ }
506
+ function envForceColor() {
507
+ if ("FORCE_COLOR" in env) {
508
+ if (env.FORCE_COLOR === "true") {
509
+ return 1;
510
+ }
511
+ if (env.FORCE_COLOR === "false") {
512
+ return 0;
513
+ }
514
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
515
+ }
516
+ }
517
+ function translateLevel(level) {
518
+ if (level === 0) {
519
+ return false;
520
+ }
521
+ return {
522
+ level,
523
+ hasBasic: true,
524
+ has256: level >= 2,
525
+ has16m: level >= 3
526
+ };
527
+ }
528
+ function supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
529
+ const noFlagForceColor = envForceColor();
530
+ if (noFlagForceColor !== void 0) {
531
+ flagForceColor = noFlagForceColor;
532
+ }
533
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
534
+ if (forceColor === 0) {
535
+ return 0;
536
+ }
537
+ if (sniffFlags) {
538
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
539
+ return 3;
540
+ }
541
+ if (hasFlag("color=256")) {
542
+ return 2;
543
+ }
544
+ }
545
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
546
+ return 0;
547
+ }
548
+ const min = forceColor || 0;
549
+ if (env.TERM === "dumb") {
550
+ return min;
551
+ }
552
+ if (process.platform === "win32") {
553
+ const osRelease = os.release().split(".");
554
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
555
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
556
+ }
557
+ return 1;
558
+ }
559
+ if ("CI" in env) {
560
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
561
+ return 1;
562
+ }
563
+ return min;
564
+ }
565
+ if ("TEAMCITY_VERSION" in env) {
566
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
567
+ }
568
+ if (env.COLORTERM === "truecolor") {
569
+ return 3;
570
+ }
571
+ if ("TERM_PROGRAM" in env) {
572
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
573
+ switch (env.TERM_PROGRAM) {
574
+ case "iTerm.app":
575
+ return version >= 3 ? 3 : 2;
576
+ case "Apple_Terminal":
577
+ return 2;
578
+ }
579
+ }
580
+ if (/-256(color)?$/i.test(env.TERM)) {
581
+ return 2;
582
+ }
583
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
584
+ return 1;
585
+ }
586
+ if ("COLORTERM" in env) {
587
+ return 1;
588
+ }
589
+ return min;
590
+ }
591
+ function getSupportLevel(stream, options = {}) {
592
+ const level = supportsColor(stream, {
593
+ streamIsTTY: stream && stream.isTTY,
594
+ ...options
595
+ });
596
+ return translateLevel(level);
597
+ }
598
+ module2.exports = {
599
+ supportsColor: getSupportLevel,
600
+ stdout: getSupportLevel({ isTTY: tty.isatty(1) }),
601
+ stderr: getSupportLevel({ isTTY: tty.isatty(2) })
602
+ };
603
+ }
604
+ });
605
+
606
+ // ../../node_modules/debug/src/node.js
607
+ var require_node = __commonJS({
608
+ "../../node_modules/debug/src/node.js"(exports2, module2) {
609
+ "use strict";
610
+ var tty = require("tty");
611
+ var util = require("util");
612
+ exports2.init = init;
613
+ exports2.log = log;
614
+ exports2.formatArgs = formatArgs;
615
+ exports2.save = save;
616
+ exports2.load = load;
617
+ exports2.useColors = useColors;
618
+ exports2.destroy = util.deprecate(
619
+ () => {
620
+ },
621
+ "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
622
+ );
623
+ exports2.colors = [6, 2, 3, 4, 5, 1];
624
+ try {
625
+ const supportsColor = require_supports_color();
626
+ if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
627
+ exports2.colors = [
628
+ 20,
629
+ 21,
630
+ 26,
631
+ 27,
632
+ 32,
633
+ 33,
634
+ 38,
635
+ 39,
636
+ 40,
637
+ 41,
638
+ 42,
639
+ 43,
640
+ 44,
641
+ 45,
642
+ 56,
643
+ 57,
644
+ 62,
645
+ 63,
646
+ 68,
647
+ 69,
648
+ 74,
649
+ 75,
650
+ 76,
651
+ 77,
652
+ 78,
653
+ 79,
654
+ 80,
655
+ 81,
656
+ 92,
657
+ 93,
658
+ 98,
659
+ 99,
660
+ 112,
661
+ 113,
662
+ 128,
663
+ 129,
664
+ 134,
665
+ 135,
666
+ 148,
667
+ 149,
668
+ 160,
669
+ 161,
670
+ 162,
671
+ 163,
672
+ 164,
673
+ 165,
674
+ 166,
675
+ 167,
676
+ 168,
677
+ 169,
678
+ 170,
679
+ 171,
680
+ 172,
681
+ 173,
682
+ 178,
683
+ 179,
684
+ 184,
685
+ 185,
686
+ 196,
687
+ 197,
688
+ 198,
689
+ 199,
690
+ 200,
691
+ 201,
692
+ 202,
693
+ 203,
694
+ 204,
695
+ 205,
696
+ 206,
697
+ 207,
698
+ 208,
699
+ 209,
700
+ 214,
701
+ 215,
702
+ 220,
703
+ 221
704
+ ];
705
+ }
706
+ } catch (error) {
707
+ }
708
+ exports2.inspectOpts = Object.keys(process.env).filter((key) => {
709
+ return /^debug_/i.test(key);
710
+ }).reduce((obj, key) => {
711
+ const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
712
+ return k.toUpperCase();
713
+ });
714
+ let val = process.env[key];
715
+ if (/^(yes|on|true|enabled)$/i.test(val)) {
716
+ val = true;
717
+ } else if (/^(no|off|false|disabled)$/i.test(val)) {
718
+ val = false;
719
+ } else if (val === "null") {
720
+ val = null;
721
+ } else {
722
+ val = Number(val);
723
+ }
724
+ obj[prop] = val;
725
+ return obj;
726
+ }, {});
727
+ function useColors() {
728
+ return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd);
729
+ }
730
+ function formatArgs(args2) {
731
+ const { namespace: name, useColors: useColors2 } = this;
732
+ if (useColors2) {
733
+ const c = this.color;
734
+ const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
735
+ const prefix = ` ${colorCode};1m${name} \x1B[0m`;
736
+ args2[0] = prefix + args2[0].split("\n").join("\n" + prefix);
737
+ args2.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m");
738
+ } else {
739
+ args2[0] = getDate() + name + " " + args2[0];
740
+ }
741
+ }
742
+ function getDate() {
743
+ if (exports2.inspectOpts.hideDate) {
744
+ return "";
745
+ }
746
+ return (/* @__PURE__ */ new Date()).toISOString() + " ";
747
+ }
748
+ function log(...args2) {
749
+ return process.stderr.write(util.format(...args2) + "\n");
750
+ }
751
+ function save(namespaces) {
752
+ if (namespaces) {
753
+ process.env.DEBUG = namespaces;
754
+ } else {
755
+ delete process.env.DEBUG;
756
+ }
757
+ }
758
+ function load() {
759
+ return process.env.DEBUG;
760
+ }
761
+ function init(debug) {
762
+ debug.inspectOpts = {};
763
+ const keys = Object.keys(exports2.inspectOpts);
764
+ for (let i = 0; i < keys.length; i++) {
765
+ debug.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]];
766
+ }
767
+ }
768
+ module2.exports = require_common()(exports2);
769
+ var { formatters } = module2.exports;
770
+ formatters.o = function(v) {
771
+ this.inspectOpts.colors = this.useColors;
772
+ return util.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
773
+ };
774
+ formatters.O = function(v) {
775
+ this.inspectOpts.colors = this.useColors;
776
+ return util.inspect(v, this.inspectOpts);
777
+ };
778
+ }
779
+ });
780
+
781
+ // ../../node_modules/debug/src/index.js
782
+ var require_src = __commonJS({
783
+ "../../node_modules/debug/src/index.js"(exports2, module2) {
784
+ "use strict";
785
+ if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
786
+ module2.exports = require_browser();
787
+ } else {
788
+ module2.exports = require_node();
789
+ }
790
+ }
791
+ });
792
+
793
+ // ../../node_modules/eastasianwidth/eastasianwidth.js
794
+ var require_eastasianwidth = __commonJS({
795
+ "../../node_modules/eastasianwidth/eastasianwidth.js"(exports2, module2) {
796
+ "use strict";
797
+ var eaw = {};
798
+ if ("undefined" == typeof module2) {
799
+ window.eastasianwidth = eaw;
800
+ } else {
801
+ module2.exports = eaw;
802
+ }
803
+ eaw.eastAsianWidth = function(character) {
804
+ var x = character.charCodeAt(0);
805
+ var y = character.length == 2 ? character.charCodeAt(1) : 0;
806
+ var codePoint = x;
807
+ if (55296 <= x && x <= 56319 && (56320 <= y && y <= 57343)) {
808
+ x &= 1023;
809
+ y &= 1023;
810
+ codePoint = x << 10 | y;
811
+ codePoint += 65536;
812
+ }
813
+ if (12288 == codePoint || 65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510) {
814
+ return "F";
815
+ }
816
+ if (8361 == codePoint || 65377 <= codePoint && codePoint <= 65470 || 65474 <= codePoint && codePoint <= 65479 || 65482 <= codePoint && codePoint <= 65487 || 65490 <= codePoint && codePoint <= 65495 || 65498 <= codePoint && codePoint <= 65500 || 65512 <= codePoint && codePoint <= 65518) {
817
+ return "H";
818
+ }
819
+ if (4352 <= codePoint && codePoint <= 4447 || 4515 <= codePoint && codePoint <= 4519 || 4602 <= codePoint && codePoint <= 4607 || 9001 <= codePoint && codePoint <= 9002 || 11904 <= codePoint && codePoint <= 11929 || 11931 <= codePoint && codePoint <= 12019 || 12032 <= codePoint && codePoint <= 12245 || 12272 <= codePoint && codePoint <= 12283 || 12289 <= codePoint && codePoint <= 12350 || 12353 <= codePoint && codePoint <= 12438 || 12441 <= codePoint && codePoint <= 12543 || 12549 <= codePoint && codePoint <= 12589 || 12593 <= codePoint && codePoint <= 12686 || 12688 <= codePoint && codePoint <= 12730 || 12736 <= codePoint && codePoint <= 12771 || 12784 <= codePoint && codePoint <= 12830 || 12832 <= codePoint && codePoint <= 12871 || 12880 <= codePoint && codePoint <= 13054 || 13056 <= codePoint && codePoint <= 19903 || 19968 <= codePoint && codePoint <= 42124 || 42128 <= codePoint && codePoint <= 42182 || 43360 <= codePoint && codePoint <= 43388 || 44032 <= codePoint && codePoint <= 55203 || 55216 <= codePoint && codePoint <= 55238 || 55243 <= codePoint && codePoint <= 55291 || 63744 <= codePoint && codePoint <= 64255 || 65040 <= codePoint && codePoint <= 65049 || 65072 <= codePoint && codePoint <= 65106 || 65108 <= codePoint && codePoint <= 65126 || 65128 <= codePoint && codePoint <= 65131 || 110592 <= codePoint && codePoint <= 110593 || 127488 <= codePoint && codePoint <= 127490 || 127504 <= codePoint && codePoint <= 127546 || 127552 <= codePoint && codePoint <= 127560 || 127568 <= codePoint && codePoint <= 127569 || 131072 <= codePoint && codePoint <= 194367 || 177984 <= codePoint && codePoint <= 196605 || 196608 <= codePoint && codePoint <= 262141) {
820
+ return "W";
821
+ }
822
+ if (32 <= codePoint && codePoint <= 126 || 162 <= codePoint && codePoint <= 163 || 165 <= codePoint && codePoint <= 166 || 172 == codePoint || 175 == codePoint || 10214 <= codePoint && codePoint <= 10221 || 10629 <= codePoint && codePoint <= 10630) {
823
+ return "Na";
824
+ }
825
+ if (161 == codePoint || 164 == codePoint || 167 <= codePoint && codePoint <= 168 || 170 == codePoint || 173 <= codePoint && codePoint <= 174 || 176 <= codePoint && codePoint <= 180 || 182 <= codePoint && codePoint <= 186 || 188 <= codePoint && codePoint <= 191 || 198 == codePoint || 208 == codePoint || 215 <= codePoint && codePoint <= 216 || 222 <= codePoint && codePoint <= 225 || 230 == codePoint || 232 <= codePoint && codePoint <= 234 || 236 <= codePoint && codePoint <= 237 || 240 == codePoint || 242 <= codePoint && codePoint <= 243 || 247 <= codePoint && codePoint <= 250 || 252 == codePoint || 254 == codePoint || 257 == codePoint || 273 == codePoint || 275 == codePoint || 283 == codePoint || 294 <= codePoint && codePoint <= 295 || 299 == codePoint || 305 <= codePoint && codePoint <= 307 || 312 == codePoint || 319 <= codePoint && codePoint <= 322 || 324 == codePoint || 328 <= codePoint && codePoint <= 331 || 333 == codePoint || 338 <= codePoint && codePoint <= 339 || 358 <= codePoint && codePoint <= 359 || 363 == codePoint || 462 == codePoint || 464 == codePoint || 466 == codePoint || 468 == codePoint || 470 == codePoint || 472 == codePoint || 474 == codePoint || 476 == codePoint || 593 == codePoint || 609 == codePoint || 708 == codePoint || 711 == codePoint || 713 <= codePoint && codePoint <= 715 || 717 == codePoint || 720 == codePoint || 728 <= codePoint && codePoint <= 731 || 733 == codePoint || 735 == codePoint || 768 <= codePoint && codePoint <= 879 || 913 <= codePoint && codePoint <= 929 || 931 <= codePoint && codePoint <= 937 || 945 <= codePoint && codePoint <= 961 || 963 <= codePoint && codePoint <= 969 || 1025 == codePoint || 1040 <= codePoint && codePoint <= 1103 || 1105 == codePoint || 8208 == codePoint || 8211 <= codePoint && codePoint <= 8214 || 8216 <= codePoint && codePoint <= 8217 || 8220 <= codePoint && codePoint <= 8221 || 8224 <= codePoint && codePoint <= 8226 || 8228 <= codePoint && codePoint <= 8231 || 8240 == codePoint || 8242 <= codePoint && codePoint <= 8243 || 8245 == codePoint || 8251 == codePoint || 8254 == codePoint || 8308 == codePoint || 8319 == codePoint || 8321 <= codePoint && codePoint <= 8324 || 8364 == codePoint || 8451 == codePoint || 8453 == codePoint || 8457 == codePoint || 8467 == codePoint || 8470 == codePoint || 8481 <= codePoint && codePoint <= 8482 || 8486 == codePoint || 8491 == codePoint || 8531 <= codePoint && codePoint <= 8532 || 8539 <= codePoint && codePoint <= 8542 || 8544 <= codePoint && codePoint <= 8555 || 8560 <= codePoint && codePoint <= 8569 || 8585 == codePoint || 8592 <= codePoint && codePoint <= 8601 || 8632 <= codePoint && codePoint <= 8633 || 8658 == codePoint || 8660 == codePoint || 8679 == codePoint || 8704 == codePoint || 8706 <= codePoint && codePoint <= 8707 || 8711 <= codePoint && codePoint <= 8712 || 8715 == codePoint || 8719 == codePoint || 8721 == codePoint || 8725 == codePoint || 8730 == codePoint || 8733 <= codePoint && codePoint <= 8736 || 8739 == codePoint || 8741 == codePoint || 8743 <= codePoint && codePoint <= 8748 || 8750 == codePoint || 8756 <= codePoint && codePoint <= 8759 || 8764 <= codePoint && codePoint <= 8765 || 8776 == codePoint || 8780 == codePoint || 8786 == codePoint || 8800 <= codePoint && codePoint <= 8801 || 8804 <= codePoint && codePoint <= 8807 || 8810 <= codePoint && codePoint <= 8811 || 8814 <= codePoint && codePoint <= 8815 || 8834 <= codePoint && codePoint <= 8835 || 8838 <= codePoint && codePoint <= 8839 || 8853 == codePoint || 8857 == codePoint || 8869 == codePoint || 8895 == codePoint || 8978 == codePoint || 9312 <= codePoint && codePoint <= 9449 || 9451 <= codePoint && codePoint <= 9547 || 9552 <= codePoint && codePoint <= 9587 || 9600 <= codePoint && codePoint <= 9615 || 9618 <= codePoint && codePoint <= 9621 || 9632 <= codePoint && codePoint <= 9633 || 9635 <= codePoint && codePoint <= 9641 || 9650 <= codePoint && codePoint <= 9651 || 9654 <= codePoint && codePoint <= 9655 || 9660 <= codePoint && codePoint <= 9661 || 9664 <= codePoint && codePoint <= 9665 || 9670 <= codePoint && codePoint <= 9672 || 9675 == codePoint || 9678 <= codePoint && codePoint <= 9681 || 9698 <= codePoint && codePoint <= 9701 || 9711 == codePoint || 9733 <= codePoint && codePoint <= 9734 || 9737 == codePoint || 9742 <= codePoint && codePoint <= 9743 || 9748 <= codePoint && codePoint <= 9749 || 9756 == codePoint || 9758 == codePoint || 9792 == codePoint || 9794 == codePoint || 9824 <= codePoint && codePoint <= 9825 || 9827 <= codePoint && codePoint <= 9829 || 9831 <= codePoint && codePoint <= 9834 || 9836 <= codePoint && codePoint <= 9837 || 9839 == codePoint || 9886 <= codePoint && codePoint <= 9887 || 9918 <= codePoint && codePoint <= 9919 || 9924 <= codePoint && codePoint <= 9933 || 9935 <= codePoint && codePoint <= 9953 || 9955 == codePoint || 9960 <= codePoint && codePoint <= 9983 || 10045 == codePoint || 10071 == codePoint || 10102 <= codePoint && codePoint <= 10111 || 11093 <= codePoint && codePoint <= 11097 || 12872 <= codePoint && codePoint <= 12879 || 57344 <= codePoint && codePoint <= 63743 || 65024 <= codePoint && codePoint <= 65039 || 65533 == codePoint || 127232 <= codePoint && codePoint <= 127242 || 127248 <= codePoint && codePoint <= 127277 || 127280 <= codePoint && codePoint <= 127337 || 127344 <= codePoint && codePoint <= 127386 || 917760 <= codePoint && codePoint <= 917999 || 983040 <= codePoint && codePoint <= 1048573 || 1048576 <= codePoint && codePoint <= 1114109) {
826
+ return "A";
827
+ }
828
+ return "N";
829
+ };
830
+ eaw.characterLength = function(character) {
831
+ var code = this.eastAsianWidth(character);
832
+ if (code == "F" || code == "W" || code == "A") {
833
+ return 2;
834
+ } else {
835
+ return 1;
836
+ }
837
+ };
838
+ function stringToArray(string) {
839
+ return string.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
840
+ }
841
+ eaw.length = function(string) {
842
+ var characters = stringToArray(string);
843
+ var len = 0;
844
+ for (var i = 0; i < characters.length; i++) {
845
+ len = len + this.characterLength(characters[i]);
846
+ }
847
+ return len;
848
+ };
849
+ eaw.slice = function(text, start, end) {
850
+ textLen = eaw.length(text);
851
+ start = start ? start : 0;
852
+ end = end ? end : 1;
853
+ if (start < 0) {
854
+ start = textLen + start;
855
+ }
856
+ if (end < 0) {
857
+ end = textLen + end;
858
+ }
859
+ var result = "";
860
+ var eawLen = 0;
861
+ var chars = stringToArray(text);
862
+ for (var i = 0; i < chars.length; i++) {
863
+ var char = chars[i];
864
+ var charLen = eaw.length(char);
865
+ if (eawLen >= start - (charLen == 2 ? 1 : 0)) {
866
+ if (eawLen + charLen <= end) {
867
+ result += char;
868
+ } else {
869
+ break;
870
+ }
871
+ }
872
+ eawLen += charLen;
873
+ }
874
+ return result;
875
+ };
876
+ }
877
+ });
878
+
879
+ // ../../node_modules/list-it/lib/data-cell.js
880
+ var require_data_cell = __commonJS({
881
+ "../../node_modules/list-it/lib/data-cell.js"(exports2, module2) {
882
+ "use strict";
883
+ var eaw = require_eastasianwidth();
884
+ function DataCell() {
885
+ this.data = "";
886
+ }
887
+ module2.exports = DataCell;
888
+ DataCell.prototype.getData = function() {
889
+ return this.data;
890
+ };
891
+ DataCell.prototype.setData = function(data) {
892
+ this.data = data;
893
+ };
894
+ DataCell.prototype.visibleLength = function() {
895
+ if (typeof this.data != "string") {
896
+ return ("" + this.data).length;
897
+ }
898
+ return DataCell.visibleLength(this.data);
899
+ };
900
+ DataCell.visibleLength = function(data) {
901
+ const s = data.replace(/\x1b[^m]*m/g, "");
902
+ return eaw.length(s);
903
+ };
904
+ }
905
+ });
906
+
907
+ // ../../node_modules/list-it/lib/row.js
908
+ var require_row = __commonJS({
909
+ "../../node_modules/list-it/lib/row.js"(exports2, module2) {
910
+ "use strict";
911
+ function Row() {
912
+ this.cells = [];
913
+ this.empty = true;
914
+ this.fixed = false;
915
+ }
916
+ module2.exports = Row;
917
+ Row.prototype.getCellLength = function() {
918
+ return this.cells.length;
919
+ };
920
+ Row.prototype.getCell = function(idx) {
921
+ return this.cells[idx];
922
+ };
923
+ Row.prototype.pushCell = function(cell) {
924
+ if (this.isFixed()) {
925
+ throw "pushCell Fail, The row was already fixed.";
926
+ }
927
+ this.empty = false;
928
+ return this.cells.push(cell);
929
+ };
930
+ Row.prototype.fix = function() {
931
+ this.fixed = true;
932
+ };
933
+ Row.prototype.isEmpty = function() {
934
+ return this.empty;
935
+ };
936
+ Row.prototype.isFixed = function() {
937
+ return this.fixed;
938
+ };
939
+ }
940
+ });
941
+
942
+ // ../../node_modules/list-it/lib/column.js
943
+ var require_column = __commonJS({
944
+ "../../node_modules/list-it/lib/column.js"(exports2, module2) {
945
+ "use strict";
946
+ var DataCell = require_data_cell();
947
+ function Column() {
948
+ this.opt = {
949
+ "autoAlign": false
950
+ };
951
+ this.width = 0;
952
+ this.textWidth = null;
953
+ this.intLen = 0;
954
+ this.fracLen = 0;
955
+ this.expLen = 0;
956
+ this.cellAtRow = {};
957
+ this.header = null;
958
+ }
959
+ module2.exports = Column;
960
+ Column.prototype.getWidth = function() {
961
+ return this.width;
962
+ };
963
+ Column.prototype.setTextWidth = function(textWidth) {
964
+ this.textWidth = textWidth;
965
+ };
966
+ Column.prototype.setCellAt = function(row, cell) {
967
+ this.cellAtRow[row] = cell;
968
+ };
969
+ Column.prototype.setHeader = function(header) {
970
+ this.header = header;
971
+ };
972
+ Column.prototype.hasHeader = function() {
973
+ return this.header != null;
974
+ };
975
+ Column.prototype.updateWidth = function() {
976
+ const headerWidth = !this.hasHeader() ? 0 : DataCell.visibleLength("" + this.header);
977
+ this.width = headerWidth;
978
+ Object.keys(this.cellAtRow).forEach((key) => {
979
+ const cell = this.cellAtRow[key];
980
+ const data = cell.getData();
981
+ let width = cell.visibleLength();
982
+ if (typeof data == "number") {
983
+ if (this.opt.autoAlign) {
984
+ this.updateNumWidth(data);
985
+ width = this.getNumMaxWidth();
986
+ }
987
+ }
988
+ if (width > this.width) {
989
+ this.width = width;
990
+ }
991
+ if (typeof data == "string") {
992
+ if (this.textWidth && this.textWidth > headerWidth) {
993
+ if (this.width > this.textWidth) {
994
+ this.width = this.textWidth;
995
+ }
996
+ }
997
+ }
998
+ });
999
+ };
1000
+ Column.prototype.formatColumnHeader = function() {
1001
+ if (!this.hasHeader()) {
1002
+ return null;
1003
+ }
1004
+ const width = this.getWidth();
1005
+ const header = this.header;
1006
+ const headerWidth = DataCell.visibleLength("" + header);
1007
+ if (header.length == headerWidth && width - headerWidth <= 0) {
1008
+ return ("" + header).substring(0, width);
1009
+ }
1010
+ return "" + header + " ".repeat(width - headerWidth);
1011
+ };
1012
+ Column.prototype.formatCell = function(data) {
1013
+ const width = this.getWidth();
1014
+ if (this.opt.autoAlign) {
1015
+ if (typeof data == "number") {
1016
+ return this.makeAutoAlignNum(data).padStart(width, " ");
1017
+ }
1018
+ }
1019
+ const dataWidth = DataCell.visibleLength("" + data);
1020
+ if (data.length == dataWidth && width - dataWidth <= 0) {
1021
+ return ("" + data).substring(0, width);
1022
+ }
1023
+ return "" + data + " ".repeat(width - dataWidth);
1024
+ };
1025
+ Column.prototype.setAutoAlign = function(autoAlign) {
1026
+ this.opt.autoAlign = autoAlign;
1027
+ };
1028
+ Column.prototype.updateNumWidth = function(num) {
1029
+ const numInfo = this.analyzeNumber(num);
1030
+ const intLen = numInfo.intStr.length;
1031
+ const fracLen = numInfo.fracStr.length;
1032
+ const expLen = numInfo.expStr.length;
1033
+ if (intLen > this.intLen) {
1034
+ this.intLen = intLen;
1035
+ }
1036
+ if (fracLen > this.fracLen) {
1037
+ this.fracLen = fracLen;
1038
+ }
1039
+ if (expLen > this.expLen) {
1040
+ this.expLen = expLen;
1041
+ }
1042
+ };
1043
+ Column.prototype.getNumMaxWidth = function() {
1044
+ return this.intLen + this.fracLen + (this.fracLen > 0 ? 1 : 0) + this.expLen + (this.expLen > 0 ? 1 : 0);
1045
+ };
1046
+ Column.prototype.makeAutoAlignNum = function(num) {
1047
+ const numInfo = this.analyzeNumber(num);
1048
+ const intStr = numInfo.intStr.padStart(this.intLen, " ");
1049
+ const fracStr = numInfo.expStr != "" ? numInfo.fracStr.padEnd(this.fracLen, "0") : numInfo.fracStr.padEnd(this.fracLen, " ");
1050
+ const expStr = numInfo.expStr.padEnd(this.expLen, " ");
1051
+ if (numInfo.expStr != "") {
1052
+ return [intStr, ".", fracStr, "e", expStr].join("");
1053
+ }
1054
+ if (numInfo.pointPos >= 0) {
1055
+ if (this.expLen > 0) {
1056
+ return [intStr, ".", fracStr, " ", expStr].join("");
1057
+ }
1058
+ return [intStr, ".", fracStr].join("");
1059
+ } else if (this.fracLen == 0) {
1060
+ return intStr;
1061
+ }
1062
+ if (this.expLen > 0) {
1063
+ return [intStr, ".0", fracStr.substr(1), " ", expStr].join("");
1064
+ }
1065
+ return [intStr, ".0", fracStr.substr(1)].join("");
1066
+ };
1067
+ Column.prototype.analyzeNumber = function(num) {
1068
+ const s = "" + num;
1069
+ let intStr = "";
1070
+ let fracStr = "";
1071
+ const pointPos = s.indexOf(".");
1072
+ const expIndex = s.indexOf("e");
1073
+ if (expIndex >= 0) {
1074
+ if (pointPos < 0) {
1075
+ return {
1076
+ pointPos: expIndex,
1077
+ intStr: s.substr(0, expIndex),
1078
+ fracStr: "0",
1079
+ expStr: s.substr(expIndex + 1)
1080
+ };
1081
+ }
1082
+ return {
1083
+ pointPos,
1084
+ intStr: s.substr(0, pointPos),
1085
+ fracStr: s.substring(pointPos + 1, expIndex),
1086
+ expStr: s.substr(expIndex + 1)
1087
+ };
1088
+ }
1089
+ if (pointPos < 0) {
1090
+ intStr = s;
1091
+ } else {
1092
+ intStr = s.substr(0, pointPos);
1093
+ fracStr = s.substr(pointPos + 1);
1094
+ }
1095
+ return {
1096
+ "pointPos": pointPos,
1097
+ "intStr": intStr,
1098
+ "fracStr": fracStr,
1099
+ "expStr": ""
1100
+ };
1101
+ };
1102
+ }
1103
+ });
1104
+
1105
+ // ../../node_modules/ansi-escape-sequences/dist/index.cjs
1106
+ var require_dist = __commonJS({
1107
+ "../../node_modules/ansi-escape-sequences/dist/index.cjs"(exports2, module2) {
1108
+ "use strict";
1109
+ function isObject(input) {
1110
+ return typeof input === "object" && input !== null;
1111
+ }
1112
+ function isArrayLike(input) {
1113
+ return isObject(input) && typeof input.length === "number";
1114
+ }
1115
+ function arrayify(input) {
1116
+ if (Array.isArray(input)) {
1117
+ return input;
1118
+ } else if (input === void 0) {
1119
+ return [];
1120
+ } else if (isArrayLike(input) || input instanceof Set) {
1121
+ return Array.from(input);
1122
+ } else {
1123
+ return [input];
1124
+ }
1125
+ }
1126
+ var csi = "\x1B[";
1127
+ var ansi = {};
1128
+ ansi.style = {
1129
+ reset: "\x1B[0m",
1130
+ bold: "\x1B[1m",
1131
+ italic: "\x1B[3m",
1132
+ underline: "\x1B[4m",
1133
+ fontDefault: "\x1B[10m",
1134
+ font2: "\x1B[11m",
1135
+ font3: "\x1B[12m",
1136
+ font4: "\x1B[13m",
1137
+ font5: "\x1B[14m",
1138
+ font6: "\x1B[15m",
1139
+ imageNegative: "\x1B[7m",
1140
+ imagePositive: "\x1B[27m",
1141
+ black: "\x1B[30m",
1142
+ red: "\x1B[31m",
1143
+ green: "\x1B[32m",
1144
+ yellow: "\x1B[33m",
1145
+ blue: "\x1B[34m",
1146
+ magenta: "\x1B[35m",
1147
+ cyan: "\x1B[36m",
1148
+ white: "\x1B[37m",
1149
+ grey: "\x1B[90m",
1150
+ gray: "\x1B[90m",
1151
+ brightRed: "\x1B[91m",
1152
+ brightGreen: "\x1B[92m",
1153
+ brightYellow: "\x1B[93m",
1154
+ brightBlue: "\x1B[94m",
1155
+ brightMagenta: "\x1B[95m",
1156
+ brightCyan: "\x1B[96m",
1157
+ brightWhite: "\x1B[97m",
1158
+ "bg-black": "\x1B[40m",
1159
+ "bg-red": "\x1B[41m",
1160
+ "bg-green": "\x1B[42m",
1161
+ "bg-yellow": "\x1B[43m",
1162
+ "bg-blue": "\x1B[44m",
1163
+ "bg-magenta": "\x1B[45m",
1164
+ "bg-cyan": "\x1B[46m",
1165
+ "bg-white": "\x1B[47m",
1166
+ "bg-grey": "\x1B[100m",
1167
+ "bg-gray": "\x1B[100m",
1168
+ "bg-brightRed": "\x1B[101m",
1169
+ "bg-brightGreen": "\x1B[102m",
1170
+ "bg-brightYellow": "\x1B[103m",
1171
+ "bg-brightBlue": "\x1B[104m",
1172
+ "bg-brightMagenta": "\x1B[105m",
1173
+ "bg-brightCyan": "\x1B[106m",
1174
+ "bg-brightWhite": "\x1B[107m"
1175
+ };
1176
+ ansi.rgb = function(r, g, b) {
1177
+ return `\x1B[38;2;${r};${g};${b}m`;
1178
+ };
1179
+ ansi.bgRgb = function(r, g, b) {
1180
+ return `\x1B[48;2;${r};${g};${b}m`;
1181
+ };
1182
+ ansi.styles = function(styles) {
1183
+ styles = arrayify(styles);
1184
+ return styles.map(function(effect) {
1185
+ const rgbMatches = effect.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
1186
+ const bgRgbMatches = effect.match(/bg-rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
1187
+ if (bgRgbMatches) {
1188
+ const [full, r, g, b] = bgRgbMatches;
1189
+ return ansi.bgRgb(r, g, b);
1190
+ } else if (rgbMatches) {
1191
+ const [full, r, g, b] = rgbMatches;
1192
+ return ansi.rgb(r, g, b);
1193
+ } else {
1194
+ return ansi.style[effect];
1195
+ }
1196
+ }).join("");
1197
+ };
1198
+ ansi.format = function(str, styleArray) {
1199
+ const re = /\[([\w\s-\(\),]+)\]{([^]*?)}/;
1200
+ let matches;
1201
+ str = String(str);
1202
+ if (!str) return "";
1203
+ while (matches = str.match(re)) {
1204
+ const inlineStyles = matches[1].split(/\s+/);
1205
+ const inlineString = matches[2];
1206
+ str = str.replace(matches[0], ansi.format(inlineString, inlineStyles));
1207
+ }
1208
+ return styleArray && styleArray.length ? ansi.styles(styleArray) + str + ansi.style.reset : str;
1209
+ };
1210
+ ansi.cursor = {
1211
+ /**
1212
+ * Moves the cursor `lines` cells up. If the cursor is already at the edge of the screen, this has no effect
1213
+ * @param [lines=1] {number}
1214
+ * @return {string}
1215
+ */
1216
+ up: function(lines) {
1217
+ return csi + (lines || 1) + "A";
1218
+ },
1219
+ /**
1220
+ * Moves the cursor `lines` cells down. If the cursor is already at the edge of the screen, this has no effect
1221
+ * @param [lines=1] {number}
1222
+ * @return {string}
1223
+ */
1224
+ down: function(lines) {
1225
+ return csi + (lines || 1) + "B";
1226
+ },
1227
+ /**
1228
+ * Moves the cursor `lines` cells forward. If the cursor is already at the edge of the screen, this has no effect
1229
+ * @param [lines=1] {number}
1230
+ * @return {string}
1231
+ */
1232
+ forward: function(lines) {
1233
+ return csi + (lines || 1) + "C";
1234
+ },
1235
+ /**
1236
+ * Moves the cursor `lines` cells back. If the cursor is already at the edge of the screen, this has no effect
1237
+ * @param [lines=1] {number}
1238
+ * @return {string}
1239
+ */
1240
+ back: function(lines) {
1241
+ return csi + (lines || 1) + "D";
1242
+ },
1243
+ /**
1244
+ * Moves cursor to beginning of the line n lines down.
1245
+ * @param [lines=1] {number}
1246
+ * @return {string}
1247
+ */
1248
+ nextLine: function(lines) {
1249
+ return csi + (lines || 1) + "E";
1250
+ },
1251
+ /**
1252
+ * Moves cursor to beginning of the line n lines up.
1253
+ * @param [lines=1] {number}
1254
+ * @return {string}
1255
+ */
1256
+ previousLine: function(lines) {
1257
+ return csi + (lines || 1) + "F";
1258
+ },
1259
+ /**
1260
+ * Moves the cursor to column n.
1261
+ * @param n {number} - column number
1262
+ * @return {string}
1263
+ */
1264
+ horizontalAbsolute: function(n) {
1265
+ return csi + n + "G";
1266
+ },
1267
+ /**
1268
+ * Moves the cursor to row n, column m. The values are 1-based, and default to 1 (top left corner) if omitted.
1269
+ * @param n {number} - row number
1270
+ * @param m {number} - column number
1271
+ * @return {string}
1272
+ */
1273
+ position: function(n, m) {
1274
+ return csi + (n || 1) + ";" + (m || 1) + "H";
1275
+ },
1276
+ /**
1277
+ * Hides the cursor
1278
+ */
1279
+ hide: csi + "?25l",
1280
+ /**
1281
+ * Shows the cursor
1282
+ */
1283
+ show: csi + "?25h"
1284
+ };
1285
+ ansi.erase = {
1286
+ /**
1287
+ * Clears part of the screen. If n is 0 (or missing), clear from cursor to end of screen. If n is 1, clear from cursor to beginning of the screen. If n is 2, clear entire screen.
1288
+ * @param n {number}
1289
+ * @return {string}
1290
+ */
1291
+ display: function(n) {
1292
+ return csi + (n || 0) + "J";
1293
+ },
1294
+ /**
1295
+ * Erases part of the line. If n is zero (or missing), clear from cursor to the end of the line. If n is one, clear from cursor to beginning of the line. If n is two, clear entire line. Cursor position does not change.
1296
+ * @param n {number}
1297
+ * @return {string}
1298
+ */
1299
+ inLine: function(n) {
1300
+ return csi + (n || 0) + "K";
1301
+ }
1302
+ };
1303
+ module2.exports = ansi;
1304
+ }
1305
+ });
1306
+
1307
+ // ../../node_modules/list-it/lib/list-it-buffer.js
1308
+ var require_list_it_buffer = __commonJS({
1309
+ "../../node_modules/list-it/lib/list-it-buffer.js"(exports2, module2) {
1310
+ "use strict";
1311
+ var debug = require_src()("list-it-buffer");
1312
+ var DataCell = require_data_cell();
1313
+ var Row = require_row();
1314
+ var Column = require_column();
1315
+ var ansi = require_dist();
1316
+ function ListItBuffer(opt) {
1317
+ opt = opt || {};
1318
+ this.opt = {
1319
+ "autoAlign": true,
1320
+ "columnWidth": null,
1321
+ "header": null,
1322
+ "headerBold": false,
1323
+ "headerColor": "",
1324
+ "headerUnderline": false
1325
+ };
1326
+ if (opt.header != null && !Array.isArray(opt.header)) {
1327
+ throw new Error([
1328
+ `Invalid header was specified. It must be an array, but (${JSON.stringify(opt.header)}):${typeof opt.header} was specified.`
1329
+ ].join(" "));
1330
+ }
1331
+ if (opt.headerColor && !(opt.headerColor in COLORS)) {
1332
+ throw new Error([
1333
+ `Invalid color ${JSON.stringify(opt.headerColor)} was specified.`,
1334
+ "Available color names:",
1335
+ ...AVAILABLE_COLORS.map((color) => `* ${JSON.stringify(color)}`)
1336
+ ].join("\n"));
1337
+ }
1338
+ Object.keys(this.opt).forEach((key) => {
1339
+ if (key in opt) {
1340
+ this.opt[key] = opt[key];
1341
+ }
1342
+ });
1343
+ this.lines = [];
1344
+ this.columns = [];
1345
+ this.columnWidth = this.opt.columnWidth;
1346
+ if (this.opt.header) {
1347
+ this.setHeaderRow(this.opt.header);
1348
+ }
1349
+ }
1350
+ module2.exports = ListItBuffer;
1351
+ ListItBuffer.prototype.nl = function() {
1352
+ const lastRowIndex = this.lines.length - 1;
1353
+ if (lastRowIndex >= 0 && !this.lines[lastRowIndex].isFixed()) {
1354
+ this.lines[lastRowIndex].fix();
1355
+ }
1356
+ this.pushNewRow();
1357
+ return this;
1358
+ };
1359
+ ListItBuffer.prototype.d = function(data) {
1360
+ if (arguments.length > 1) {
1361
+ const array = Array.apply(null, arguments);
1362
+ if (ListItBuffer.isMultiDimensionalArray(array)) {
1363
+ array.forEach((row) => this.addRow(row));
1364
+ } else {
1365
+ array.forEach((data2) => this.d(data2));
1366
+ }
1367
+ return this;
1368
+ }
1369
+ if (Array.isArray(data)) {
1370
+ if (ListItBuffer.isMultiDimensionalArray(data)) {
1371
+ data.forEach((row) => this.addRow(row));
1372
+ } else if (ListItBuffer.isObjectArray(data)) {
1373
+ data = objectArrayToTable(data);
1374
+ if (!this.header && (this.opt.headerBold || this.opt.headerColor || this.opt.headerUnderline)) {
1375
+ this.setHeaderRow(data.shift());
1376
+ }
1377
+ data.forEach((row) => this.addRow(row));
1378
+ } else {
1379
+ this.addRow(data);
1380
+ }
1381
+ return this;
1382
+ }
1383
+ const rowidx = this.lines.length - 1;
1384
+ if (rowidx < 0 || this.lines[rowidx].isFixed()) {
1385
+ this.pushNewRow();
1386
+ }
1387
+ const cell = new DataCell();
1388
+ cell.setData(data);
1389
+ const iRow = this.lines.length - 1;
1390
+ let iCol = this.lines[iRow].getCellLength();
1391
+ if (iCol >= this.columns.length) {
1392
+ this.addColumn();
1393
+ }
1394
+ this.columns[iCol].setCellAt(iRow, cell);
1395
+ this.lines[iRow].pushCell(cell);
1396
+ return this;
1397
+ };
1398
+ ListItBuffer.isMultiDimensionalArray = function(arr) {
1399
+ if (!Array.isArray(arr)) {
1400
+ throw Error("The parameter arr must be array");
1401
+ }
1402
+ for (let element of arr) {
1403
+ if (!Array.isArray(element)) {
1404
+ return false;
1405
+ }
1406
+ }
1407
+ return true;
1408
+ };
1409
+ ListItBuffer.isObjectArray = function(arr) {
1410
+ if (!Array.isArray(arr)) {
1411
+ throw Error("The parameter arr must be array");
1412
+ }
1413
+ const ctor = arr[0].constructor;
1414
+ for (let element of arr) {
1415
+ if (typeof element != "object") {
1416
+ return false;
1417
+ } else {
1418
+ if (element.constructor.name != ctor.name) {
1419
+ return false;
1420
+ }
1421
+ }
1422
+ }
1423
+ return true;
1424
+ };
1425
+ ListItBuffer.prototype.addRow = function(row) {
1426
+ row.forEach((col) => {
1427
+ switch (typeof col) {
1428
+ case "string":
1429
+ case "number":
1430
+ this.d(col);
1431
+ break;
1432
+ default:
1433
+ this.d(col != null ? col.toString() : "(null)");
1434
+ break;
1435
+ }
1436
+ });
1437
+ this.nl();
1438
+ };
1439
+ ListItBuffer.prototype.pushNewRow = function() {
1440
+ this.lines.push(new Row());
1441
+ };
1442
+ ListItBuffer.prototype.toString = function() {
1443
+ const rows = [];
1444
+ this.columns.forEach((column, iCol) => {
1445
+ if (this.header != null) {
1446
+ column.setHeader(this.header[iCol] || "");
1447
+ }
1448
+ column.setTextWidth(this.getColumnWidth(iCol));
1449
+ column.updateWidth();
1450
+ });
1451
+ if (this.header != null) {
1452
+ const headerLine = this.applyHeaderStyleOption(
1453
+ this.columns.map((column) => column.formatColumnHeader()).join(" ")
1454
+ );
1455
+ rows.push(headerLine);
1456
+ const headerUnderline = this.generateHeaderUnderline();
1457
+ if (headerUnderline) {
1458
+ rows.push(headerUnderline);
1459
+ }
1460
+ }
1461
+ this.lines.forEach((line) => {
1462
+ if (line.isFixed() || !line.isEmpty()) {
1463
+ if (line.isEmpty()) {
1464
+ rows.push("\n");
1465
+ } else {
1466
+ rows.push(this.columns.map((column, iCol) => {
1467
+ const cell = line.getCell(iCol);
1468
+ const data = cell.getData();
1469
+ return column.formatCell(data);
1470
+ }).join(" "));
1471
+ }
1472
+ }
1473
+ });
1474
+ return rows.join("\n");
1475
+ };
1476
+ var COLORS = {};
1477
+ var BGCOLORS = {};
1478
+ Object.keys(ansi.style).forEach((key) => {
1479
+ const value = ansi.style[key];
1480
+ if (/^bg-/.test(key)) {
1481
+ BGCOLORS[key.substr(3)] = value;
1482
+ } else {
1483
+ COLORS[key] = value;
1484
+ debug(`COLOR-KEY: ${key}`);
1485
+ }
1486
+ });
1487
+ Object.keys(COLORS).forEach((key) => {
1488
+ if (!(key in BGCOLORS)) {
1489
+ delete COLORS[key];
1490
+ debug(`remove COLOR-KEY: ${key}`);
1491
+ }
1492
+ });
1493
+ var AVAILABLE_COLORS = Object.keys(COLORS);
1494
+ debug(`AVAILABLE_COLORS:${JSON.stringify(AVAILABLE_COLORS)}`);
1495
+ ListItBuffer.prototype.applyHeaderStyleOption = function(line) {
1496
+ if (!this.opt.headerBold && !this.opt.headerColor) {
1497
+ return line;
1498
+ }
1499
+ const textBuffer = [];
1500
+ if (this.opt.headerBold) {
1501
+ textBuffer.push(ansi.style.bold);
1502
+ }
1503
+ if (this.opt.headerColor) {
1504
+ textBuffer.push(COLORS[this.opt.headerColor]);
1505
+ }
1506
+ textBuffer.push(line);
1507
+ textBuffer.push(ansi.style.reset);
1508
+ return textBuffer.join("");
1509
+ };
1510
+ ListItBuffer.prototype.generateHeaderUnderline = function() {
1511
+ if (!this.opt.headerUnderline) {
1512
+ return null;
1513
+ }
1514
+ if (this.header == null) {
1515
+ return null;
1516
+ }
1517
+ return this.columns.map(
1518
+ (column) => "-".repeat(column.getWidth())
1519
+ ).join(" ");
1520
+ };
1521
+ function objectArrayToTable(objects) {
1522
+ const keys = Object.keys(objects[0]);
1523
+ const body = objects.map((item) => keys.map((key) => {
1524
+ if (item[key] != null && typeof item[key] == "object" && item[key].constructor.name == "Date") {
1525
+ return item[key].toISOString();
1526
+ }
1527
+ return item[key];
1528
+ }));
1529
+ return [keys, ...body];
1530
+ }
1531
+ ListItBuffer.prototype.setColumnWidth = function(indexOfColumns, width) {
1532
+ this.columnWidth = this.columnWidth || [];
1533
+ if (typeof indexOfColumns !== "number") {
1534
+ throw new Error("indexOfColumns must be a number");
1535
+ }
1536
+ if (!width) {
1537
+ delete this.columnWidth[indexOfColumns];
1538
+ } else {
1539
+ if (typeof width !== "number") {
1540
+ throw new Error("width must be a number");
1541
+ }
1542
+ this.columnWidth[indexOfColumns] = width;
1543
+ }
1544
+ return this;
1545
+ };
1546
+ ListItBuffer.prototype.setColumnWidthAll = function(widthForAll) {
1547
+ if (widthForAll != null && !Array.isArray(widthForAll) && typeof widthForAll !== "number") {
1548
+ throw new Error(
1549
+ "widthForAll must be one of a null, an Array or a number"
1550
+ );
1551
+ }
1552
+ if (Array.isArray(widthForAll)) {
1553
+ for (let i = 0; i < widthForAll.length; i++) {
1554
+ const width = widthForAll[i];
1555
+ if (width != void 0 && typeof width !== "number") {
1556
+ throw new Error(
1557
+ `widthForAll[${i}] must be an undefined or a number`
1558
+ );
1559
+ }
1560
+ }
1561
+ }
1562
+ this.columnWidth = widthForAll;
1563
+ return this;
1564
+ };
1565
+ ListItBuffer.prototype.getColumnWidth = function(indexOfColumns) {
1566
+ if (Array.isArray(this.columnWidth)) {
1567
+ return this.columnWidth[indexOfColumns];
1568
+ }
1569
+ return this.columnWidth;
1570
+ };
1571
+ ListItBuffer.prototype.setHeaderRow = function(header) {
1572
+ if (header && !Array.isArray(header)) {
1573
+ throw new Error([
1574
+ "The header must be an array,",
1575
+ `but ${typeof header} was specified.`,
1576
+ `header: ${JSON.stringify(header)}`
1577
+ ].join(" "));
1578
+ }
1579
+ this.header = header;
1580
+ if (this.header == null) {
1581
+ this.columns.forEach((column) => column.setHeader(null));
1582
+ } else {
1583
+ this.header.forEach((headerText, iCol) => {
1584
+ if (iCol >= this.columns.length) {
1585
+ this.addColumn(headerText);
1586
+ }
1587
+ });
1588
+ }
1589
+ return this;
1590
+ };
1591
+ ListItBuffer.prototype.addColumn = function(headerText) {
1592
+ const column = new Column();
1593
+ if (headerText) {
1594
+ column.setHeader(headerText);
1595
+ }
1596
+ if (this.opt.autoAlign) {
1597
+ column.setAutoAlign(true);
1598
+ }
1599
+ this.columns.push(column);
1600
+ };
1601
+ }
1602
+ });
1603
+
1604
+ // ../../node_modules/list-it/index.js
1605
+ var require_list_it = __commonJS({
1606
+ "../../node_modules/list-it/index.js"(exports2, module2) {
1607
+ "use strict";
1608
+ var ListItBuffer = require_list_it_buffer();
1609
+ function ListIt2(opt) {
1610
+ ListItBuffer.call(this, opt);
1611
+ }
1612
+ ListIt2.prototype = new ListItBuffer();
1613
+ ListIt2.buffer = function(opt) {
1614
+ opt = opt || {};
1615
+ if (!("autoAlign" in opt)) {
1616
+ opt.autoAlign = false;
1617
+ }
1618
+ return new ListIt2(opt);
1619
+ };
1620
+ module2.exports = ListIt2;
1621
+ }
1622
+ });
1623
+
1624
+ // src/scripts/aiTrain.ts
1625
+ var import_args = __toESM(require("args"));
1626
+ var import_chalk = __toESM(require("chalk"));
1627
+ var import_promises = __toESM(require("fs/promises"));
1628
+ var import_path = __toESM(require("path"));
1629
+ var import_progress = __toESM(require("progress"));
1630
+ var import_async = require("@tradejs/core/async");
1631
+ var import_ai = require("@tradejs/infra/ai");
1632
+ var import_ai2 = require("@tradejs/node/ai");
1633
+ var import_constants = require("@tradejs/node/constants");
1634
+
1635
+ // src/lib/aiTrainMetrics.ts
1636
+ var divideOrNull = (num, denom) => {
1637
+ if (denom <= 0) {
1638
+ return null;
1639
+ }
1640
+ return num / denom;
1641
+ };
1642
+ var DAY_MS = 24 * 60 * 60 * 1e3;
1643
+ var DAYS_PER_WEEK = 7;
1644
+ var DAYS_PER_MONTH = 30.4375;
1645
+ var getEvaluationPeriodDays = (evaluations) => {
1646
+ const timestamps = evaluations.map(
1647
+ (evaluation) => typeof evaluation.timestamp === "number" && Number.isFinite(evaluation.timestamp) ? evaluation.timestamp : null
1648
+ ).filter((timestamp) => timestamp != null);
1649
+ if (!timestamps.length) {
1650
+ return null;
1651
+ }
1652
+ const minTimestamp = Math.min(...timestamps);
1653
+ const maxTimestamp = Math.max(...timestamps);
1654
+ return Math.max((maxTimestamp - minTimestamp) / DAY_MS, 1);
1655
+ };
1656
+ var qualitySortKey = (quality) => quality == null ? Number.POSITIVE_INFINITY : quality;
1657
+ var summarizeAiTrainEvaluations = (evaluations) => {
1658
+ let approved = 0;
1659
+ let rejected = 0;
1660
+ let correct = 0;
1661
+ let incorrect = 0;
1662
+ let profitable = 0;
1663
+ let unprofitable = 0;
1664
+ let flat = 0;
1665
+ let truePositive = 0;
1666
+ let falsePositive = 0;
1667
+ let trueNegative = 0;
1668
+ let falseNegative = 0;
1669
+ let totalProfitAll = 0;
1670
+ let totalProfitApproved = 0;
1671
+ const bucketMap = /* @__PURE__ */ new Map();
1672
+ for (const evaluation of evaluations) {
1673
+ const { profit, profitableTrade, aiApproved, quality } = evaluation;
1674
+ totalProfitAll += profit;
1675
+ if (profitableTrade) {
1676
+ profitable += 1;
1677
+ } else if (profit < 0) {
1678
+ unprofitable += 1;
1679
+ } else {
1680
+ flat += 1;
1681
+ }
1682
+ if (aiApproved) {
1683
+ approved += 1;
1684
+ totalProfitApproved += profit;
1685
+ } else {
1686
+ rejected += 1;
1687
+ }
1688
+ const isCorrect = aiApproved === profitableTrade;
1689
+ if (isCorrect) {
1690
+ correct += 1;
1691
+ } else {
1692
+ incorrect += 1;
1693
+ }
1694
+ if (aiApproved && profitableTrade) {
1695
+ truePositive += 1;
1696
+ } else if (aiApproved && !profitableTrade) {
1697
+ falsePositive += 1;
1698
+ } else if (!aiApproved && profitableTrade) {
1699
+ falseNegative += 1;
1700
+ } else {
1701
+ trueNegative += 1;
1702
+ }
1703
+ const bucket = bucketMap.get(quality) ?? {
1704
+ quality,
1705
+ count: 0,
1706
+ approved: 0,
1707
+ profitable: 0,
1708
+ totalProfit: 0
1709
+ };
1710
+ bucket.count += 1;
1711
+ bucket.totalProfit += profit;
1712
+ if (aiApproved) {
1713
+ bucket.approved += 1;
1714
+ }
1715
+ if (profitableTrade) {
1716
+ bucket.profitable += 1;
1717
+ }
1718
+ bucketMap.set(quality, bucket);
1719
+ }
1720
+ const avgProfitAll = divideOrNull(totalProfitAll, evaluations.length);
1721
+ const avgProfitApproved = divideOrNull(totalProfitApproved, approved);
1722
+ const periodDays = getEvaluationPeriodDays(evaluations);
1723
+ const avgProfitApprovedPerDay = periodDays == null ? null : divideOrNull(totalProfitApproved, periodDays);
1724
+ const avgApprovedTradesPerDay = periodDays == null ? null : divideOrNull(approved, periodDays);
1725
+ const avgProfitApprovedPerMonth = avgProfitApprovedPerDay == null ? null : avgProfitApprovedPerDay * DAYS_PER_MONTH;
1726
+ const avgApprovedTradesPerWeek = avgApprovedTradesPerDay == null ? null : avgApprovedTradesPerDay * DAYS_PER_WEEK;
1727
+ const expectancyDelta = avgProfitAll == null || avgProfitApproved == null ? null : avgProfitApproved - avgProfitAll;
1728
+ return {
1729
+ approved,
1730
+ rejected,
1731
+ correct,
1732
+ incorrect,
1733
+ truePositive,
1734
+ falsePositive,
1735
+ trueNegative,
1736
+ falseNegative,
1737
+ profitable,
1738
+ unprofitable,
1739
+ flat,
1740
+ precisionApproved: divideOrNull(truePositive, approved),
1741
+ recallWinners: divideOrNull(truePositive, profitable),
1742
+ avgProfitAll,
1743
+ avgProfitApproved,
1744
+ avgProfitApprovedPerDay,
1745
+ avgProfitApprovedPerMonth,
1746
+ avgApprovedTradesPerDay,
1747
+ avgApprovedTradesPerWeek,
1748
+ expectancyDelta,
1749
+ qualityBuckets: [...bucketMap.values()].sort(
1750
+ (a, b) => qualitySortKey(a.quality) - qualitySortKey(b.quality)
1751
+ )
1752
+ };
1753
+ };
1754
+ var getDirectionSortKey = (direction) => {
1755
+ if (direction === "LONG") {
1756
+ return 0;
1757
+ }
1758
+ if (direction === "SHORT") {
1759
+ return 1;
1760
+ }
1761
+ return 2;
1762
+ };
1763
+ var summarizeAiTrainEvaluationsByDirection = (evaluations) => {
1764
+ const grouped = /* @__PURE__ */ new Map();
1765
+ for (const evaluation of evaluations) {
1766
+ const direction = typeof evaluation.direction === "string" && evaluation.direction.trim() ? evaluation.direction : "UNKNOWN";
1767
+ const bucket = grouped.get(direction) ?? [];
1768
+ bucket.push(evaluation);
1769
+ grouped.set(direction, bucket);
1770
+ }
1771
+ return [...grouped.entries()].sort(
1772
+ ([leftDirection], [rightDirection]) => getDirectionSortKey(leftDirection) - getDirectionSortKey(rightDirection) || leftDirection.localeCompare(rightDirection)
1773
+ ).map(([direction, directionEvaluations]) => ({
1774
+ direction,
1775
+ summary: summarizeAiTrainEvaluations(directionEvaluations)
1776
+ }));
1777
+ };
1778
+
1779
+ // src/scripts/aiTrain.ts
1780
+ var ListIt = require_list_it();
1781
+ import_args.default.example(
1782
+ "yarn ai-train -n 50 --minQuality 4",
1783
+ "Replay latest AI prompt dataset and measure approval accuracy"
1784
+ );
1785
+ import_args.default.option(["o", "outDir"], "Dataset directory", "data/ai/export");
1786
+ import_args.default.option(["s", "strategy"], "Strategy name filter for merged file", "");
1787
+ import_args.default.option(["f", "file"], "Explicit merged dataset file path", "");
1788
+ import_args.default.option(
1789
+ ["n", "recent"],
1790
+ "How many recent trades to evaluate from the end (0 = all)",
1791
+ 50
1792
+ );
1793
+ import_args.default.option(
1794
+ "skip",
1795
+ "How many recent trades to skip from the end before selecting replay rows",
1796
+ 0
1797
+ );
1798
+ import_args.default.option(
1799
+ ["p", "parallel"],
1800
+ "Concurrent AI requests during replay",
1801
+ import_constants.AI_CONCURRENCY_LIMIT
1802
+ );
1803
+ import_args.default.option(
1804
+ "model",
1805
+ "OpenRouter model id override for this replay run",
1806
+ import_ai2.DEFAULT_AI_MODEL
1807
+ );
1808
+ import_args.default.option("minQuality", "Minimum AI quality required to approve entry", 4);
1809
+ import_args.default.option(
1810
+ "localOnly",
1811
+ "Replay deterministic adapter gate without AI provider calls",
1812
+ false
1813
+ );
1814
+ import_args.default.option("json", "Print structured JSON summary", false);
1815
+ var flags = import_args.default.parse(process.argv);
1816
+ var createListIt = () => new ListIt({
1817
+ autoAlign: true,
1818
+ headerUnderline: true
1819
+ });
1820
+ var createTable = (headers, rows) => createListIt().setHeaderRow(headers).d(rows).toString();
1821
+ var formatRatio = (value) => value == null ? "n/a" : `${(value * 100).toFixed(1)}%`;
1822
+ var formatProfit = (value) => value == null ? "n/a" : value.toFixed(2);
1823
+ var formatMetricNumber = (value) => value == null ? "n/a" : value.toFixed(2);
1824
+ var colorizeRatio = (value) => {
1825
+ const text = formatRatio(value);
1826
+ if (value == null) {
1827
+ return import_chalk.default.gray(text);
1828
+ }
1829
+ if (value >= 0.6) {
1830
+ return import_chalk.default.green(text);
1831
+ }
1832
+ if (value >= 0.3) {
1833
+ return import_chalk.default.yellow(text);
1834
+ }
1835
+ return import_chalk.default.red(text);
1836
+ };
1837
+ var colorizePercent = (value, total) => {
1838
+ const ratio = total > 0 ? value / total : null;
1839
+ return colorizeRatio(ratio);
1840
+ };
1841
+ var colorizeProfit = (value) => {
1842
+ const text = formatProfit(value);
1843
+ if (value == null) {
1844
+ return import_chalk.default.gray(text);
1845
+ }
1846
+ if (value > 0) {
1847
+ return import_chalk.default.green(text);
1848
+ }
1849
+ if (value < 0) {
1850
+ return import_chalk.default.red(text);
1851
+ }
1852
+ return import_chalk.default.yellow(text);
1853
+ };
1854
+ var colorizeMetricNumber = (value) => {
1855
+ const text = formatMetricNumber(value);
1856
+ return value == null ? import_chalk.default.gray(text) : import_chalk.default.cyan(text);
1857
+ };
1858
+ var colorizeQuality = (quality) => {
1859
+ const text = quality == null ? "n/a" : String(quality);
1860
+ if (quality == null) {
1861
+ return import_chalk.default.gray(text);
1862
+ }
1863
+ if (quality >= 4) {
1864
+ return import_chalk.default.green(text);
1865
+ }
1866
+ if (quality === 3) {
1867
+ return import_chalk.default.yellow(text);
1868
+ }
1869
+ return import_chalk.default.red(text);
1870
+ };
1871
+ var normalizeInt = (value, fallback) => {
1872
+ const parsed = Number(value);
1873
+ return Number.isFinite(parsed) ? Math.max(0, Math.trunc(parsed)) : fallback;
1874
+ };
1875
+ var normalizePositiveInt = (value, fallback) => {
1876
+ const parsed = Number(value);
1877
+ return Number.isFinite(parsed) && parsed > 0 ? Math.trunc(parsed) : fallback;
1878
+ };
1879
+ var normalizeQuality = (analysis) => {
1880
+ const quality = Number(analysis?.quality);
1881
+ return Number.isFinite(quality) ? Math.round(quality) : null;
1882
+ };
1883
+ var isProfitableTrade = (row) => Number(row.profit) > 0;
1884
+ var isAiApproval = (row, analysis, minQuality) => {
1885
+ const quality = normalizeQuality(analysis);
1886
+ return analysis.direction === row.direction && quality != null && quality >= minQuality;
1887
+ };
1888
+ var listMergedFiles = async (params) => {
1889
+ const { outDir, strategyName } = params;
1890
+ let entries = [];
1891
+ try {
1892
+ entries = await import_promises.default.readdir(outDir);
1893
+ } catch {
1894
+ return [];
1895
+ }
1896
+ const prefix = strategyName ? `ai-dataset-${(0, import_ai.toFileToken)(strategyName)}-merged-` : "ai-dataset-";
1897
+ return entries.filter((name) => name.startsWith(prefix)).filter((name) => name.includes("-merged-") && name.endsWith(".jsonl")).sort().map((name) => import_path.default.join(outDir, name));
1898
+ };
1899
+ var deriveStrategyNameFromFile = (filePath) => {
1900
+ const match = import_path.default.basename(filePath).match(/^ai-dataset-(.+)-merged-\d+\.jsonl$/);
1901
+ return match?.[1] ? match[1] : "unknown";
1902
+ };
1903
+ var extractSignalFromDatasetRow = (row) => {
1904
+ const { payload } = row;
1905
+ return {
1906
+ ...payload.signal,
1907
+ strategy: payload.signal.strategy,
1908
+ figures: payload.figures ?? {},
1909
+ indicators: payload.indicators ?? {},
1910
+ additionalIndicators: payload.additionalIndicators ?? {},
1911
+ prices: payload.signal.prices
1912
+ };
1913
+ };
1914
+ var resolvePromptRunContext = (row) => {
1915
+ const signal = extractSignalFromDatasetRow(row);
1916
+ return {
1917
+ signal,
1918
+ promptPair: (0, import_ai2.buildAiPrompts)(signal)
1919
+ };
1920
+ };
1921
+ var getDeterministicGateContext = (signal) => {
1922
+ const payload = (0, import_ai2.buildAiPayload)(signal);
1923
+ return (0, import_ai2.getDeterministicAiGateContext)(payload);
1924
+ };
1925
+ var resolveDeterministicGateEvaluation = (signal, fallbackDirection) => {
1926
+ if (!signal) {
1927
+ return {
1928
+ direction: fallbackDirection || "UNKNOWN",
1929
+ signalAvailable: false,
1930
+ coreBlocked: false,
1931
+ adapterBlocked: false,
1932
+ modelCandidate: false
1933
+ };
1934
+ }
1935
+ const gateContext = getDeterministicGateContext(signal);
1936
+ const structuralHardBlockReasons = Array.isArray(
1937
+ gateContext?.structuralHardBlockReasons
1938
+ ) ? gateContext.structuralHardBlockReasons.filter(
1939
+ (reason) => typeof reason === "string" && reason.trim().length > 0
1940
+ ) : [];
1941
+ const coreBlocked = structuralHardBlockReasons.length > 0;
1942
+ const approvalAllowedNow = typeof gateContext?.approvalAllowedNow === "boolean" ? gateContext.approvalAllowedNow : null;
1943
+ const adapterBlocked = !coreBlocked && approvalAllowedNow === false;
1944
+ return {
1945
+ direction: typeof signal.direction === "string" && signal.direction.trim() ? signal.direction : fallbackDirection || "UNKNOWN",
1946
+ signalAvailable: true,
1947
+ coreBlocked,
1948
+ adapterBlocked,
1949
+ modelCandidate: !coreBlocked && !adapterBlocked
1950
+ };
1951
+ };
1952
+ var summarizeDeterministicGateEvaluations = (deterministicEvaluations, evaluations) => {
1953
+ const summary = {
1954
+ selected: deterministicEvaluations.length,
1955
+ signalAvailable: 0,
1956
+ signalMissing: 0,
1957
+ coreBlocked: 0,
1958
+ adapterBlocked: 0,
1959
+ modelCandidate: 0,
1960
+ modelApproved: 0,
1961
+ modelRejected: 0,
1962
+ modelFailed: 0
1963
+ };
1964
+ for (const evaluation of deterministicEvaluations) {
1965
+ if (evaluation.signalAvailable) {
1966
+ summary.signalAvailable += 1;
1967
+ } else {
1968
+ summary.signalMissing += 1;
1969
+ }
1970
+ if (evaluation.coreBlocked) {
1971
+ summary.coreBlocked += 1;
1972
+ } else if (evaluation.adapterBlocked) {
1973
+ summary.adapterBlocked += 1;
1974
+ } else if (evaluation.modelCandidate) {
1975
+ summary.modelCandidate += 1;
1976
+ }
1977
+ }
1978
+ for (const evaluation of evaluations) {
1979
+ if (!evaluation.modelCandidate) {
1980
+ continue;
1981
+ }
1982
+ if (evaluation.aiApproved) {
1983
+ summary.modelApproved += 1;
1984
+ } else {
1985
+ summary.modelRejected += 1;
1986
+ }
1987
+ }
1988
+ summary.modelFailed = summary.modelCandidate - summary.modelApproved - summary.modelRejected;
1989
+ return summary;
1990
+ };
1991
+ var printSection = (title, table) => {
1992
+ console.log(import_chalk.default.gray(`${title}:`));
1993
+ console.log(table);
1994
+ console.log("");
1995
+ };
1996
+ var resolveDatasetFile = async () => {
1997
+ const explicitFile = String(flags.file || "").trim();
1998
+ if (explicitFile) {
1999
+ return import_path.default.resolve(explicitFile);
2000
+ }
2001
+ const outDir = String(flags.outDir || "data/ai/export");
2002
+ const strategyName = String(flags.strategy || "").trim() || void 0;
2003
+ const mergedFiles = await listMergedFiles({
2004
+ outDir,
2005
+ strategyName
2006
+ });
2007
+ if (!mergedFiles.length) {
2008
+ throw new Error(
2009
+ strategyName ? `No merged AI dataset found for strategy "${strategyName}" in ${outDir}. Run yarn ai-export first.` : `No merged AI dataset found in ${outDir}. Run yarn ai-export first.`
2010
+ );
2011
+ }
2012
+ return mergedFiles[mergedFiles.length - 1];
2013
+ };
2014
+ var main = async () => {
2015
+ const recent = normalizeInt(flags.recent, 50);
2016
+ const skip = normalizeInt(flags.skip, 0);
2017
+ const minQuality = normalizeInt(flags.minQuality, 4);
2018
+ const localOnly = Boolean(flags.localOnly);
2019
+ const jsonOutput = Boolean(flags.json);
2020
+ const model = String(flags.model || import_ai2.DEFAULT_AI_MODEL).trim() || import_ai2.DEFAULT_AI_MODEL;
2021
+ const parallel = normalizePositiveInt(flags.parallel, import_constants.AI_CONCURRENCY_LIMIT);
2022
+ await (0, import_ai2.ensureAiStrategyPluginsLoaded)();
2023
+ const filePath = await resolveDatasetFile();
2024
+ const { rows, totalRows } = await (0, import_ai.readAiDatasetRows)({
2025
+ filePath,
2026
+ limitFromEnd: recent,
2027
+ skipFromEnd: skip
2028
+ });
2029
+ if (!rows.length) {
2030
+ console.log(
2031
+ import_chalk.default.yellow(
2032
+ `No AI prompt rows selected in ${filePath} (recent=${recent || "all"}, skip=${skip})`
2033
+ )
2034
+ );
2035
+ process.exit(0);
2036
+ }
2037
+ const strategyName = rows[0]?.strategyName || deriveStrategyNameFromFile(filePath);
2038
+ const preparedRows = rows.map((row) => {
2039
+ const { promptPair, signal } = resolvePromptRunContext(row);
2040
+ const payload = (0, import_ai2.buildAiPayload)(signal);
2041
+ return {
2042
+ row,
2043
+ promptPair,
2044
+ payload,
2045
+ signal,
2046
+ deterministic: resolveDeterministicGateEvaluation(signal, row.direction)
2047
+ };
2048
+ });
2049
+ const concurrency = Math.max(1, Math.min(parallel, rows.length));
2050
+ const bar = jsonOutput ? null : new import_progress.default(":current/:total [:bar][:percent] :symbol :status", {
2051
+ total: rows.length,
2052
+ width: 20
2053
+ });
2054
+ let failed = 0;
2055
+ const errorMessages = [];
2056
+ const evaluations = [];
2057
+ await (0, import_async.runWithConcurrency)(preparedRows, concurrency, async (preparedRow) => {
2058
+ const { row, promptPair, payload, signal, deterministic } = preparedRow;
2059
+ const profit = Number(row.profit);
2060
+ const profitableTrade = isProfitableTrade(row);
2061
+ try {
2062
+ const analysis = localOnly ? await (0, import_ai2.runAiPromptLocal)(signal, { payload }) : await (0, import_ai2.runAiPrompt)(
2063
+ promptPair,
2064
+ signal ? {
2065
+ model,
2066
+ signal,
2067
+ payload
2068
+ } : { model }
2069
+ );
2070
+ const aiApproved = isAiApproval(row, analysis, minQuality);
2071
+ const quality = normalizeQuality(analysis);
2072
+ const isCorrect = aiApproved === profitableTrade;
2073
+ evaluations.push({
2074
+ profit,
2075
+ profitableTrade,
2076
+ aiApproved,
2077
+ quality,
2078
+ direction: row.direction,
2079
+ timestamp: Number.isFinite(Number(row.timestamp)) ? Number(row.timestamp) : null,
2080
+ modelCandidate: deterministic.modelCandidate
2081
+ });
2082
+ bar?.tick(1, {
2083
+ symbol: import_chalk.default.gray(row.symbol),
2084
+ status: isCorrect ? import_chalk.default.green("ok") : import_chalk.default.red("miss")
2085
+ });
2086
+ } catch (error) {
2087
+ failed += 1;
2088
+ if (errorMessages.length < 5) {
2089
+ errorMessages.push(
2090
+ `[${row.symbol}/${row.signalId}] ${error instanceof Error ? error.message : String(error)}`
2091
+ );
2092
+ }
2093
+ bar?.tick(1, {
2094
+ symbol: import_chalk.default.gray(row.symbol),
2095
+ status: import_chalk.default.yellow("error")
2096
+ });
2097
+ }
2098
+ });
2099
+ const summary = summarizeAiTrainEvaluations(evaluations);
2100
+ const directionSummaries = summarizeAiTrainEvaluationsByDirection(evaluations);
2101
+ const deterministicSummary = summarizeDeterministicGateEvaluations(
2102
+ preparedRows.map((preparedRow) => preparedRow.deterministic),
2103
+ evaluations
2104
+ );
2105
+ const evaluated = summary.correct + summary.incorrect;
2106
+ const result = {
2107
+ run: {
2108
+ strategy: strategyName,
2109
+ filePath,
2110
+ selected: rows.length,
2111
+ sourceRows: totalRows,
2112
+ recent,
2113
+ skip,
2114
+ minQuality,
2115
+ mode: localOnly ? "local-deterministic" : "llm",
2116
+ model: localOnly ? "local-deterministic" : model,
2117
+ parallel: concurrency
2118
+ },
2119
+ outcome: summary,
2120
+ byDirection: directionSummaries,
2121
+ deterministicFlow: deterministicSummary,
2122
+ qualityBreakdown: summary.qualityBuckets,
2123
+ errors: {
2124
+ failed,
2125
+ providerErrors: errorMessages
2126
+ }
2127
+ };
2128
+ if (jsonOutput) {
2129
+ console.log(JSON.stringify(result));
2130
+ process.exit(failed === rows.length ? 1 : 0);
2131
+ }
2132
+ console.log("");
2133
+ console.log(import_chalk.default.green("AI train finished"));
2134
+ console.log(import_chalk.default.gray(filePath));
2135
+ console.log("");
2136
+ printSection(
2137
+ "RUN",
2138
+ createTable(
2139
+ [import_chalk.default.gray("FIELD"), import_chalk.default.gray("VALUE")],
2140
+ [
2141
+ ["strategy", import_chalk.default.yellow(strategyName)],
2142
+ ["selected", import_chalk.default.blue(String(rows.length))],
2143
+ ["source_rows", import_chalk.default.blue(String(totalRows))],
2144
+ ["recent", import_chalk.default.blue(recent === 0 ? "all" : String(recent))],
2145
+ ["skip", import_chalk.default.blue(String(skip))],
2146
+ ["min_quality", import_chalk.default.magenta(String(minQuality))],
2147
+ [
2148
+ "mode",
2149
+ localOnly ? import_chalk.default.green("local-deterministic") : import_chalk.default.yellow("llm")
2150
+ ],
2151
+ ["model", import_chalk.default.yellow(localOnly ? "local-deterministic" : model)],
2152
+ ["parallel", import_chalk.default.magenta(String(concurrency))]
2153
+ ]
2154
+ )
2155
+ );
2156
+ printSection(
2157
+ "OUTCOME",
2158
+ createTable(
2159
+ [import_chalk.default.gray("METRIC"), import_chalk.default.gray("VALUE")],
2160
+ [
2161
+ ["accuracy", colorizePercent(summary.correct, evaluated)],
2162
+ ["evaluated", import_chalk.default.blue(String(evaluated))],
2163
+ ["correct", import_chalk.default.green(String(summary.correct))],
2164
+ ["incorrect", import_chalk.default.red(String(summary.incorrect))],
2165
+ [
2166
+ "failed",
2167
+ failed > 0 ? import_chalk.default.yellow(String(failed)) : import_chalk.default.green("0")
2168
+ ],
2169
+ ["approved", import_chalk.default.cyan(String(summary.approved))],
2170
+ ["rejected", import_chalk.default.cyan(String(summary.rejected))],
2171
+ ["profitable", import_chalk.default.green(String(summary.profitable))],
2172
+ ["unprofitable", import_chalk.default.red(String(summary.unprofitable))],
2173
+ ["flat", import_chalk.default.yellow(String(summary.flat))],
2174
+ ["precision_approved", colorizeRatio(summary.precisionApproved)],
2175
+ ["recall_winners", colorizeRatio(summary.recallWinners)],
2176
+ ["avg_profit_all", colorizeProfit(summary.avgProfitAll)],
2177
+ ["avg_profit_approved", colorizeProfit(summary.avgProfitApproved)],
2178
+ [
2179
+ "avg_profit_approved_per_day",
2180
+ colorizeProfit(summary.avgProfitApprovedPerDay)
2181
+ ],
2182
+ [
2183
+ "avg_profit_approved_per_month",
2184
+ colorizeProfit(summary.avgProfitApprovedPerMonth)
2185
+ ],
2186
+ [
2187
+ "avg_approved_trades_per_day",
2188
+ colorizeMetricNumber(summary.avgApprovedTradesPerDay)
2189
+ ],
2190
+ [
2191
+ "avg_approved_trades_per_week",
2192
+ colorizeMetricNumber(summary.avgApprovedTradesPerWeek)
2193
+ ],
2194
+ ["expectancy_delta", colorizeProfit(summary.expectancyDelta)]
2195
+ ]
2196
+ )
2197
+ );
2198
+ printSection(
2199
+ "CONFUSION",
2200
+ createTable(
2201
+ [import_chalk.default.green("TP"), import_chalk.default.red("FP"), import_chalk.default.green("TN"), import_chalk.default.red("FN")],
2202
+ [
2203
+ [
2204
+ import_chalk.default.green(String(summary.truePositive)),
2205
+ import_chalk.default.red(String(summary.falsePositive)),
2206
+ import_chalk.default.green(String(summary.trueNegative)),
2207
+ import_chalk.default.red(String(summary.falseNegative))
2208
+ ]
2209
+ ]
2210
+ )
2211
+ );
2212
+ if (directionSummaries.length) {
2213
+ printSection(
2214
+ "BY DIRECTION",
2215
+ createTable(
2216
+ [
2217
+ import_chalk.default.gray("DIR"),
2218
+ import_chalk.default.gray("EVAL"),
2219
+ import_chalk.default.gray("ACCURACY"),
2220
+ import_chalk.default.gray("APPROVED"),
2221
+ import_chalk.default.green("TP"),
2222
+ import_chalk.default.red("FP"),
2223
+ import_chalk.default.green("TN"),
2224
+ import_chalk.default.red("FN"),
2225
+ import_chalk.default.gray("PRECISION"),
2226
+ import_chalk.default.gray("RECALL")
2227
+ ],
2228
+ directionSummaries.map(({ direction, summary: directionSummary }) => {
2229
+ const directionEvaluated = directionSummary.correct + directionSummary.incorrect;
2230
+ return [
2231
+ import_chalk.default.yellow(direction),
2232
+ import_chalk.default.blue(String(directionEvaluated)),
2233
+ colorizePercent(directionSummary.correct, directionEvaluated),
2234
+ import_chalk.default.cyan(String(directionSummary.approved)),
2235
+ import_chalk.default.green(String(directionSummary.truePositive)),
2236
+ import_chalk.default.red(String(directionSummary.falsePositive)),
2237
+ import_chalk.default.green(String(directionSummary.trueNegative)),
2238
+ import_chalk.default.red(String(directionSummary.falseNegative)),
2239
+ colorizeRatio(directionSummary.precisionApproved),
2240
+ colorizeRatio(directionSummary.recallWinners)
2241
+ ];
2242
+ })
2243
+ )
2244
+ );
2245
+ }
2246
+ printSection(
2247
+ "DETERMINISTIC FLOW",
2248
+ createTable(
2249
+ [import_chalk.default.gray("METRIC"), import_chalk.default.gray("VALUE")],
2250
+ [
2251
+ ["selected", import_chalk.default.blue(String(deterministicSummary.selected))],
2252
+ [
2253
+ "signal_available",
2254
+ import_chalk.default.blue(String(deterministicSummary.signalAvailable))
2255
+ ],
2256
+ [
2257
+ "signal_missing",
2258
+ deterministicSummary.signalMissing > 0 ? import_chalk.default.yellow(String(deterministicSummary.signalMissing)) : import_chalk.default.green("0")
2259
+ ],
2260
+ [
2261
+ "core_blocked_now",
2262
+ deterministicSummary.coreBlocked > 0 ? import_chalk.default.yellow(String(deterministicSummary.coreBlocked)) : import_chalk.default.green("0")
2263
+ ],
2264
+ [
2265
+ "adapter_blocked_now",
2266
+ deterministicSummary.adapterBlocked > 0 ? import_chalk.default.yellow(String(deterministicSummary.adapterBlocked)) : import_chalk.default.green("0")
2267
+ ],
2268
+ [
2269
+ "left_to_model_now",
2270
+ import_chalk.default.cyan(String(deterministicSummary.modelCandidate))
2271
+ ],
2272
+ [
2273
+ "model_approved",
2274
+ import_chalk.default.green(String(deterministicSummary.modelApproved))
2275
+ ],
2276
+ [
2277
+ "model_rejected",
2278
+ import_chalk.default.red(String(deterministicSummary.modelRejected))
2279
+ ],
2280
+ [
2281
+ "model_failed",
2282
+ deterministicSummary.modelFailed > 0 ? import_chalk.default.yellow(String(deterministicSummary.modelFailed)) : import_chalk.default.green("0")
2283
+ ]
2284
+ ]
2285
+ )
2286
+ );
2287
+ if (summary.qualityBuckets.length) {
2288
+ printSection(
2289
+ "QUALITY BREAKDOWN",
2290
+ createTable(
2291
+ [
2292
+ import_chalk.default.gray("QUALITY"),
2293
+ import_chalk.default.gray("COUNT"),
2294
+ import_chalk.default.gray("APPROVED"),
2295
+ import_chalk.default.gray("APPROVAL_RATE"),
2296
+ import_chalk.default.gray("WINRATE"),
2297
+ import_chalk.default.gray("AVG_PROFIT")
2298
+ ],
2299
+ summary.qualityBuckets.map((bucket) => [
2300
+ colorizeQuality(bucket.quality),
2301
+ import_chalk.default.blue(String(bucket.count)),
2302
+ import_chalk.default.cyan(String(bucket.approved)),
2303
+ colorizeRatio(bucket.approved / bucket.count),
2304
+ colorizeRatio(bucket.profitable / bucket.count),
2305
+ colorizeProfit(bucket.totalProfit / bucket.count)
2306
+ ])
2307
+ )
2308
+ );
2309
+ }
2310
+ if (errorMessages.length) {
2311
+ console.log(import_chalk.default.yellow("AI provider errors:"));
2312
+ errorMessages.forEach((message) => {
2313
+ console.log(import_chalk.default.yellow(`- ${message}`));
2314
+ });
2315
+ }
2316
+ process.exit(failed === rows.length ? 1 : 0);
2317
+ };
2318
+ main().catch((error) => {
2319
+ console.error(import_chalk.default.red(error?.message || String(error)));
2320
+ process.exit(1);
2321
+ });