@tradejs/cli 1.0.5 → 1.0.6

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.
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/lib/aiTrainMetrics.ts
21
+ var aiTrainMetrics_exports = {};
22
+ __export(aiTrainMetrics_exports, {
23
+ summarizeAiTrainEvaluations: () => summarizeAiTrainEvaluations,
24
+ summarizeAiTrainEvaluationsByDirection: () => summarizeAiTrainEvaluationsByDirection
25
+ });
26
+ module.exports = __toCommonJS(aiTrainMetrics_exports);
27
+ var divideOrNull = (num, denom) => {
28
+ if (denom <= 0) {
29
+ return null;
30
+ }
31
+ return num / denom;
32
+ };
33
+ var qualitySortKey = (quality) => quality == null ? Number.POSITIVE_INFINITY : quality;
34
+ var summarizeAiTrainEvaluations = (evaluations) => {
35
+ let approved = 0;
36
+ let rejected = 0;
37
+ let correct = 0;
38
+ let incorrect = 0;
39
+ let profitable = 0;
40
+ let unprofitable = 0;
41
+ let flat = 0;
42
+ let truePositive = 0;
43
+ let falsePositive = 0;
44
+ let trueNegative = 0;
45
+ let falseNegative = 0;
46
+ let totalProfitAll = 0;
47
+ let totalProfitApproved = 0;
48
+ const bucketMap = /* @__PURE__ */ new Map();
49
+ for (const evaluation of evaluations) {
50
+ const { profit, profitableTrade, aiApproved, quality } = evaluation;
51
+ totalProfitAll += profit;
52
+ if (profitableTrade) {
53
+ profitable += 1;
54
+ } else if (profit < 0) {
55
+ unprofitable += 1;
56
+ } else {
57
+ flat += 1;
58
+ }
59
+ if (aiApproved) {
60
+ approved += 1;
61
+ totalProfitApproved += profit;
62
+ } else {
63
+ rejected += 1;
64
+ }
65
+ const isCorrect = aiApproved === profitableTrade;
66
+ if (isCorrect) {
67
+ correct += 1;
68
+ } else {
69
+ incorrect += 1;
70
+ }
71
+ if (aiApproved && profitableTrade) {
72
+ truePositive += 1;
73
+ } else if (aiApproved && !profitableTrade) {
74
+ falsePositive += 1;
75
+ } else if (!aiApproved && profitableTrade) {
76
+ falseNegative += 1;
77
+ } else {
78
+ trueNegative += 1;
79
+ }
80
+ const bucket = bucketMap.get(quality) ?? {
81
+ quality,
82
+ count: 0,
83
+ approved: 0,
84
+ profitable: 0,
85
+ totalProfit: 0
86
+ };
87
+ bucket.count += 1;
88
+ bucket.totalProfit += profit;
89
+ if (aiApproved) {
90
+ bucket.approved += 1;
91
+ }
92
+ if (profitableTrade) {
93
+ bucket.profitable += 1;
94
+ }
95
+ bucketMap.set(quality, bucket);
96
+ }
97
+ const avgProfitAll = divideOrNull(totalProfitAll, evaluations.length);
98
+ const avgProfitApproved = divideOrNull(totalProfitApproved, approved);
99
+ const expectancyDelta = avgProfitAll == null || avgProfitApproved == null ? null : avgProfitApproved - avgProfitAll;
100
+ return {
101
+ approved,
102
+ rejected,
103
+ correct,
104
+ incorrect,
105
+ truePositive,
106
+ falsePositive,
107
+ trueNegative,
108
+ falseNegative,
109
+ profitable,
110
+ unprofitable,
111
+ flat,
112
+ precisionApproved: divideOrNull(truePositive, approved),
113
+ recallWinners: divideOrNull(truePositive, profitable),
114
+ avgProfitAll,
115
+ avgProfitApproved,
116
+ expectancyDelta,
117
+ qualityBuckets: [...bucketMap.values()].sort(
118
+ (a, b) => qualitySortKey(a.quality) - qualitySortKey(b.quality)
119
+ )
120
+ };
121
+ };
122
+ var getDirectionSortKey = (direction) => {
123
+ if (direction === "LONG") {
124
+ return 0;
125
+ }
126
+ if (direction === "SHORT") {
127
+ return 1;
128
+ }
129
+ return 2;
130
+ };
131
+ var summarizeAiTrainEvaluationsByDirection = (evaluations) => {
132
+ const grouped = /* @__PURE__ */ new Map();
133
+ for (const evaluation of evaluations) {
134
+ const direction = typeof evaluation.direction === "string" && evaluation.direction.trim() ? evaluation.direction : "UNKNOWN";
135
+ const bucket = grouped.get(direction) ?? [];
136
+ bucket.push(evaluation);
137
+ grouped.set(direction, bucket);
138
+ }
139
+ return [...grouped.entries()].sort(
140
+ ([leftDirection], [rightDirection]) => getDirectionSortKey(leftDirection) - getDirectionSortKey(rightDirection) || leftDirection.localeCompare(rightDirection)
141
+ ).map(([direction, directionEvaluations]) => ({
142
+ direction,
143
+ summary: summarizeAiTrainEvaluations(directionEvaluations)
144
+ }));
145
+ };
146
+ // Annotate the CommonJS export names for ESM import in node:
147
+ 0 && (module.exports = {
148
+ summarizeAiTrainEvaluations,
149
+ summarizeAiTrainEvaluationsByDirection
150
+ });
@@ -0,0 +1,192 @@
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 __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
15
+ };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+
25
+ // src/scripts/aiExport.ts
26
+ var import_args = __toESM(require("args"));
27
+ var import_chalk2 = __toESM(require("chalk"));
28
+ var import_promises = __toESM(require("fs/promises"));
29
+ var import_path = __toESM(require("path"));
30
+ var import_ai = require("@tradejs/infra/ai");
31
+
32
+ // src/scripts/selectStrategy.ts
33
+ var import_readline = __toESM(require("readline"));
34
+ var import_chalk = __toESM(require("chalk"));
35
+ var import_strategies = require("@tradejs/node/strategies");
36
+ var defaultStrategy = "TrendLine";
37
+ var projectRoot = String(process.env.PROJECT_CWD || process.cwd()).trim() || process.cwd();
38
+ var getStrategyChoices = async () => {
39
+ try {
40
+ const loaded = await (0, import_strategies.getAvailableStrategyNames)(projectRoot);
41
+ if (loaded.length) {
42
+ return loaded;
43
+ }
44
+ } catch (error) {
45
+ console.warn(`Failed to load strategy list: ${String(error)}`);
46
+ }
47
+ return [
48
+ "Breakout",
49
+ "MaStrategy",
50
+ "AdaptiveMomentumRibbon",
51
+ "TrendLine",
52
+ "VolumeDivergence"
53
+ ];
54
+ };
55
+ var selectStrategy = async (promptLabel = "Select strategy", options) => {
56
+ const strategies = options?.strategies && options.strategies.length ? options.strategies : await getStrategyChoices();
57
+ const preferredDefault = options?.defaultStrategy || defaultStrategy;
58
+ const fallbackStrategy = strategies.includes(preferredDefault) ? preferredDefault : strategies[0];
59
+ if (!process.stdin.isTTY) {
60
+ return fallbackStrategy;
61
+ }
62
+ console.log(import_chalk.default.cyan("Available strategies:"));
63
+ strategies.forEach((name, index) => {
64
+ const isDefault = name === defaultStrategy;
65
+ const label = isDefault ? import_chalk.default.green(name) : name;
66
+ const suffix = isDefault ? import_chalk.default.gray(" (default)") : "";
67
+ console.log(` ${import_chalk.default.yellow(String(index + 1))}) ${label}${suffix}`);
68
+ });
69
+ const rl = import_readline.default.createInterface({
70
+ input: process.stdin,
71
+ output: process.stdout
72
+ });
73
+ const question = (text) => new Promise((resolve) => rl.question(text, resolve));
74
+ const answer = await question(
75
+ `${promptLabel} [${import_chalk.default.green(fallbackStrategy)}]: `
76
+ );
77
+ rl.close();
78
+ const trimmed = answer.trim();
79
+ if (!trimmed) {
80
+ return fallbackStrategy;
81
+ }
82
+ const asNumber = Number(trimmed);
83
+ if (Number.isFinite(asNumber) && asNumber >= 1 && asNumber <= strategies.length) {
84
+ return strategies[asNumber - 1];
85
+ }
86
+ const byName = strategies.find(
87
+ (name) => name.toLowerCase() === trimmed.toLowerCase()
88
+ );
89
+ if (byName) {
90
+ return byName;
91
+ }
92
+ console.warn(`Unknown strategy "${trimmed}", using ${fallbackStrategy}.`);
93
+ return fallbackStrategy;
94
+ };
95
+
96
+ // src/scripts/resolveExportStrategy.ts
97
+ var resolveExportStrategy = async ({
98
+ explicitStrategy,
99
+ outDir,
100
+ datasetLabel,
101
+ promptLabel,
102
+ listStrategies
103
+ }) => {
104
+ const raw = String(explicitStrategy || "").trim();
105
+ if (raw) {
106
+ return raw;
107
+ }
108
+ const availableStrategies = await listStrategies({ outDir });
109
+ if (!availableStrategies.length) {
110
+ return null;
111
+ }
112
+ if (availableStrategies.length === 1) {
113
+ return availableStrategies[0];
114
+ }
115
+ if (!process.stdin.isTTY) {
116
+ throw new Error(
117
+ `Multiple ${datasetLabel} chunk strategies found in ${outDir}: ${availableStrategies.join(", ")}. Pass --strategy.`
118
+ );
119
+ }
120
+ return selectStrategy(promptLabel, {
121
+ strategies: availableStrategies,
122
+ defaultStrategy: availableStrategies[0]
123
+ });
124
+ };
125
+
126
+ // src/scripts/aiExport.ts
127
+ import_args.default.example(
128
+ "yarn ts-node ./src/scripts/aiExport --strategy trendline",
129
+ "Merge per-worker AI prompt chunks into one dataset JSONL"
130
+ );
131
+ import_args.default.option(["o", "outDir"], "Dataset directory", "data/ai/export");
132
+ import_args.default.option(["s", "strategy"], "Strategy name", "");
133
+ import_args.default.option(
134
+ ["k", "keepChunks"],
135
+ "Keep source chunk files after successful merge",
136
+ false
137
+ );
138
+ var flags = import_args.default.parse(process.argv);
139
+ var main = async () => {
140
+ const outDir = String(flags.outDir || "data/ai/export");
141
+ await import_promises.default.mkdir(outDir, { recursive: true });
142
+ const strategyName = await resolveExportStrategy({
143
+ explicitStrategy: String(flags.strategy || ""),
144
+ outDir,
145
+ datasetLabel: "AI",
146
+ promptLabel: "Select AI export strategy",
147
+ listStrategies: import_ai.listAiChunkStrategies
148
+ });
149
+ if (!strategyName) {
150
+ console.log(import_chalk2.default.yellow(`No AI chunk files found in ${outDir}`));
151
+ process.exit(0);
152
+ }
153
+ const chunkFiles = await (0, import_ai.listAiChunkFiles)({
154
+ strategyName,
155
+ outDir
156
+ });
157
+ if (!chunkFiles.length) {
158
+ console.log(
159
+ import_chalk2.default.yellow(
160
+ `No chunk files found for strategy "${strategyName}" in ${outDir}`
161
+ )
162
+ );
163
+ process.exit(0);
164
+ }
165
+ const mergedPath = import_path.default.join(
166
+ outDir,
167
+ `ai-dataset-${(0, import_ai.toFileToken)(strategyName)}-merged-${Date.now()}.jsonl`
168
+ );
169
+ await (0, import_ai.mergeAiJsonlFiles)({
170
+ filePaths: chunkFiles,
171
+ outPath: mergedPath
172
+ });
173
+ const shouldDeleteChunks = !Boolean(flags.keepChunks);
174
+ if (shouldDeleteChunks) {
175
+ for (const filePath of chunkFiles) {
176
+ await import_promises.default.rm(filePath, { force: true });
177
+ }
178
+ }
179
+ console.log(import_chalk2.default.green(`Merged AI dataset saved: ${mergedPath}`));
180
+ console.log(
181
+ import_chalk2.default.gray(
182
+ `strategy=${strategyName}, source_chunks=${chunkFiles.length}, deleteChunks=${Boolean(
183
+ shouldDeleteChunks
184
+ )}`
185
+ )
186
+ );
187
+ process.exit(0);
188
+ };
189
+ main().catch((error) => {
190
+ console.error(import_chalk2.default.red(error?.message || String(error)));
191
+ process.exit(1);
192
+ });
@@ -0,0 +1,135 @@
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 __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
15
+ };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+
25
+ // src/scripts/selectStrategy.ts
26
+ var import_readline = __toESM(require("readline"));
27
+ var import_chalk = __toESM(require("chalk"));
28
+ var import_strategies = require("@tradejs/node/strategies");
29
+ var defaultStrategy = "TrendLine";
30
+ var projectRoot = String(process.env.PROJECT_CWD || process.cwd()).trim() || process.cwd();
31
+ var getStrategyChoices = async () => {
32
+ try {
33
+ const loaded = await (0, import_strategies.getAvailableStrategyNames)(projectRoot);
34
+ if (loaded.length) {
35
+ return loaded;
36
+ }
37
+ } catch (error) {
38
+ console.warn(`Failed to load strategy list: ${String(error)}`);
39
+ }
40
+ return [
41
+ "Breakout",
42
+ "MaStrategy",
43
+ "AdaptiveMomentumRibbon",
44
+ "TrendLine",
45
+ "VolumeDivergence"
46
+ ];
47
+ };
48
+ var selectStrategy = async (promptLabel = "Select strategy", options) => {
49
+ const strategies = options?.strategies && options.strategies.length ? options.strategies : await getStrategyChoices();
50
+ const preferredDefault = options?.defaultStrategy || defaultStrategy;
51
+ const fallbackStrategy = strategies.includes(preferredDefault) ? preferredDefault : strategies[0];
52
+ if (!process.stdin.isTTY) {
53
+ return fallbackStrategy;
54
+ }
55
+ console.log(import_chalk.default.cyan("Available strategies:"));
56
+ strategies.forEach((name, index) => {
57
+ const isDefault = name === defaultStrategy;
58
+ const label = isDefault ? import_chalk.default.green(name) : name;
59
+ const suffix = isDefault ? import_chalk.default.gray(" (default)") : "";
60
+ console.log(` ${import_chalk.default.yellow(String(index + 1))}) ${label}${suffix}`);
61
+ });
62
+ const rl = import_readline.default.createInterface({
63
+ input: process.stdin,
64
+ output: process.stdout
65
+ });
66
+ const question = (text) => new Promise((resolve) => rl.question(text, resolve));
67
+ const answer = await question(
68
+ `${promptLabel} [${import_chalk.default.green(fallbackStrategy)}]: `
69
+ );
70
+ rl.close();
71
+ const trimmed = answer.trim();
72
+ if (!trimmed) {
73
+ return fallbackStrategy;
74
+ }
75
+ const asNumber = Number(trimmed);
76
+ if (Number.isFinite(asNumber) && asNumber >= 1 && asNumber <= strategies.length) {
77
+ return strategies[asNumber - 1];
78
+ }
79
+ const byName = strategies.find(
80
+ (name) => name.toLowerCase() === trimmed.toLowerCase()
81
+ );
82
+ if (byName) {
83
+ return byName;
84
+ }
85
+ console.warn(`Unknown strategy "${trimmed}", using ${fallbackStrategy}.`);
86
+ return fallbackStrategy;
87
+ };
88
+
89
+ // src/scripts/spawnSiblingScript.ts
90
+ var import_fs = __toESM(require("fs"));
91
+ var import_path = __toESM(require("path"));
92
+ var import_child_process = require("child_process");
93
+ var spawnSiblingScript = (currentDir, scriptBaseName, extraArgs) => {
94
+ const searchDirs = [currentDir, import_path.default.resolve(currentDir, "scripts")];
95
+ const candidates = searchDirs.flatMap((dir) => [
96
+ import_path.default.resolve(dir, `${scriptBaseName}.js`),
97
+ import_path.default.resolve(dir, `${scriptBaseName}.ts`)
98
+ ]);
99
+ const scriptPath = candidates.find((candidate) => import_fs.default.existsSync(candidate));
100
+ if (!scriptPath) {
101
+ throw new Error(
102
+ `Script "${scriptBaseName}" not found. Checked: ${candidates.join(", ")}`
103
+ );
104
+ }
105
+ const commandArgs = scriptPath.endsWith(".ts") ? [
106
+ "-r",
107
+ "ts-node/register",
108
+ "-r",
109
+ "tsconfig-paths/register",
110
+ scriptPath,
111
+ ...extraArgs
112
+ ] : [scriptPath, ...extraArgs];
113
+ const result = (0, import_child_process.spawnSync)(process.execPath, commandArgs, {
114
+ env: process.env,
115
+ stdio: "inherit"
116
+ });
117
+ if (result.error) {
118
+ throw result.error;
119
+ }
120
+ return result.status ?? 1;
121
+ };
122
+
123
+ // src/scripts/aiExportSelect.ts
124
+ var run = async () => {
125
+ const selected = await selectStrategy("Select AI export strategy");
126
+ const status = spawnSiblingScript(__dirname, "aiExport", [
127
+ "--strategy",
128
+ selected
129
+ ]);
130
+ process.exit(status);
131
+ };
132
+ run().catch((err) => {
133
+ console.error("Failed to select AI export strategy:", err);
134
+ process.exit(1);
135
+ });