hedgequantx 2.6.162 → 2.7.0

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 (138) hide show
  1. package/README.md +15 -88
  2. package/bin/cli.js +0 -11
  3. package/dist/lib/api.jsc +0 -0
  4. package/dist/lib/api2.jsc +0 -0
  5. package/dist/lib/core.jsc +0 -0
  6. package/dist/lib/core2.jsc +0 -0
  7. package/dist/lib/data.js +1 -1
  8. package/dist/lib/data.jsc +0 -0
  9. package/dist/lib/data2.jsc +0 -0
  10. package/dist/lib/decoder.jsc +0 -0
  11. package/dist/lib/m/mod1.jsc +0 -0
  12. package/dist/lib/m/mod2.jsc +0 -0
  13. package/dist/lib/n/r1.jsc +0 -0
  14. package/dist/lib/n/r2.jsc +0 -0
  15. package/dist/lib/n/r3.jsc +0 -0
  16. package/dist/lib/n/r4.jsc +0 -0
  17. package/dist/lib/n/r5.jsc +0 -0
  18. package/dist/lib/n/r6.jsc +0 -0
  19. package/dist/lib/n/r7.jsc +0 -0
  20. package/dist/lib/o/util1.jsc +0 -0
  21. package/dist/lib/o/util2.jsc +0 -0
  22. package/package.json +6 -3
  23. package/src/app.js +40 -162
  24. package/src/config/constants.js +31 -33
  25. package/src/config/propfirms.js +13 -217
  26. package/src/config/settings.js +0 -43
  27. package/src/lib/api.js +198 -0
  28. package/src/lib/api2.js +353 -0
  29. package/src/lib/core.js +539 -0
  30. package/src/lib/core2.js +341 -0
  31. package/src/lib/data.js +555 -0
  32. package/src/lib/data2.js +492 -0
  33. package/src/lib/decoder.js +599 -0
  34. package/src/lib/m/s1.js +804 -0
  35. package/src/lib/m/s2.js +34 -0
  36. package/src/lib/n/r1.js +454 -0
  37. package/src/lib/n/r2.js +514 -0
  38. package/src/lib/n/r3.js +631 -0
  39. package/src/lib/n/r4.js +401 -0
  40. package/src/lib/n/r5.js +335 -0
  41. package/src/lib/n/r6.js +425 -0
  42. package/src/lib/n/r7.js +530 -0
  43. package/src/lib/o/l1.js +44 -0
  44. package/src/lib/o/l2.js +427 -0
  45. package/src/lib/python-bridge.js +206 -0
  46. package/src/menus/connect.js +14 -176
  47. package/src/menus/dashboard.js +65 -110
  48. package/src/pages/accounts.js +18 -18
  49. package/src/pages/algo/copy-trading.js +210 -240
  50. package/src/pages/algo/index.js +41 -104
  51. package/src/pages/algo/one-account.js +386 -33
  52. package/src/pages/algo/ui.js +312 -151
  53. package/src/pages/orders.js +3 -3
  54. package/src/pages/positions.js +3 -3
  55. package/src/pages/stats/chart.js +74 -0
  56. package/src/pages/stats/display.js +228 -0
  57. package/src/pages/stats/index.js +236 -0
  58. package/src/pages/stats/metrics.js +213 -0
  59. package/src/pages/user.js +6 -6
  60. package/src/services/hqx-server/constants.js +55 -0
  61. package/src/services/hqx-server/index.js +401 -0
  62. package/src/services/hqx-server/latency.js +81 -0
  63. package/src/services/index.js +12 -3
  64. package/src/services/rithmic/accounts.js +7 -32
  65. package/src/services/rithmic/connection.js +1 -204
  66. package/src/services/rithmic/contracts.js +235 -0
  67. package/src/services/rithmic/handlers.js +21 -196
  68. package/src/services/rithmic/index.js +60 -291
  69. package/src/services/rithmic/market.js +31 -0
  70. package/src/services/rithmic/orders.js +5 -361
  71. package/src/services/rithmic/protobuf.js +5 -195
  72. package/src/services/session.js +22 -173
  73. package/src/ui/box.js +10 -18
  74. package/src/ui/index.js +1 -3
  75. package/src/ui/menu.js +1 -1
  76. package/src/utils/prompts.js +2 -2
  77. package/dist/lib/m/s1.js +0 -1
  78. package/src/menus/ai-agent-connect.js +0 -181
  79. package/src/menus/ai-agent-models.js +0 -219
  80. package/src/menus/ai-agent-oauth.js +0 -292
  81. package/src/menus/ai-agent-ui.js +0 -141
  82. package/src/menus/ai-agent.js +0 -484
  83. package/src/pages/algo/algo-config.js +0 -195
  84. package/src/pages/algo/algo-multi.js +0 -801
  85. package/src/pages/algo/algo-utils.js +0 -58
  86. package/src/pages/algo/copy-engine.js +0 -449
  87. package/src/pages/algo/custom-strategy.js +0 -459
  88. package/src/pages/algo/logger.js +0 -245
  89. package/src/pages/algo/smart-logs-data.js +0 -218
  90. package/src/pages/algo/smart-logs.js +0 -387
  91. package/src/pages/algo/ui-constants.js +0 -144
  92. package/src/pages/algo/ui-summary.js +0 -184
  93. package/src/pages/stats-calculations.js +0 -191
  94. package/src/pages/stats-ui.js +0 -381
  95. package/src/pages/stats.js +0 -339
  96. package/src/services/ai/client-analysis.js +0 -194
  97. package/src/services/ai/client-models.js +0 -333
  98. package/src/services/ai/client.js +0 -343
  99. package/src/services/ai/index.js +0 -384
  100. package/src/services/ai/oauth-anthropic.js +0 -265
  101. package/src/services/ai/oauth-gemini.js +0 -223
  102. package/src/services/ai/oauth-iflow.js +0 -269
  103. package/src/services/ai/oauth-openai.js +0 -233
  104. package/src/services/ai/oauth-qwen.js +0 -279
  105. package/src/services/ai/providers/index.js +0 -526
  106. package/src/services/ai/proxy-install.js +0 -249
  107. package/src/services/ai/proxy-manager.js +0 -494
  108. package/src/services/ai/proxy-remote.js +0 -161
  109. package/src/services/ai/strategy-supervisor.js +0 -1312
  110. package/src/services/ai/supervisor-data.js +0 -195
  111. package/src/services/ai/supervisor-optimize.js +0 -215
  112. package/src/services/ai/supervisor-sync.js +0 -178
  113. package/src/services/ai/supervisor-utils.js +0 -158
  114. package/src/services/ai/supervisor.js +0 -484
  115. package/src/services/ai/validation.js +0 -250
  116. package/src/services/hqx-server-events.js +0 -110
  117. package/src/services/hqx-server-handlers.js +0 -217
  118. package/src/services/hqx-server-latency.js +0 -136
  119. package/src/services/hqx-server.js +0 -403
  120. package/src/services/position-constants.js +0 -28
  121. package/src/services/position-manager.js +0 -528
  122. package/src/services/position-momentum.js +0 -206
  123. package/src/services/projectx/accounts.js +0 -142
  124. package/src/services/projectx/index.js +0 -443
  125. package/src/services/projectx/market.js +0 -172
  126. package/src/services/projectx/stats.js +0 -110
  127. package/src/services/projectx/trading.js +0 -180
  128. package/src/services/rithmic/latency-tracker.js +0 -182
  129. package/src/services/rithmic/market-data.js +0 -549
  130. package/src/services/rithmic/specs.js +0 -146
  131. package/src/services/rithmic/trade-history.js +0 -254
  132. package/src/services/session-history.js +0 -475
  133. package/src/services/strategy/hft-tick.js +0 -507
  134. package/src/services/strategy/recovery-math.js +0 -402
  135. package/src/services/tradovate/constants.js +0 -109
  136. package/src/services/tradovate/index.js +0 -505
  137. package/src/services/tradovate/market.js +0 -47
  138. package/src/services/tradovate/websocket.js +0 -97
@@ -1,144 +0,0 @@
1
- /**
2
- * @fileoverview Algo UI Constants and Helpers
3
- * Box drawing, colors, icons, and utility functions
4
- */
5
-
6
- const chalk = require('chalk');
7
-
8
- // Box drawing characters
9
- const BOX = {
10
- TOP: '\u2554', BOT: '\u255A', V: '\u2551', H: '\u2550',
11
- TR: '\u2557', BR: '\u255D', ML: '\u2560', MR: '\u2563',
12
- TM: '\u2564', BM: '\u2567', MM: '\u256A', VS: '\u2502'
13
- };
14
-
15
- // Spinner characters
16
- const SPINNER = ['\u280B', '\u2819', '\u2839', '\u2838', '\u283C', '\u2834', '\u2826', '\u2827', '\u2807', '\u280F'];
17
-
18
- // Log type colors - HF grade BOLD (FIXED colors - no variation)
19
- const LOG_COLORS = {
20
- fill_buy: chalk.green,
21
- fill_sell: chalk.red,
22
- fill_win: chalk.green,
23
- fill_loss: chalk.red,
24
- win: chalk.green,
25
- loss: chalk.red,
26
- be: chalk.yellow,
27
- entry: chalk.cyan,
28
- filled: chalk.green,
29
- connected: chalk.cyan,
30
- ready: chalk.green,
31
- error: chalk.red,
32
- reject: chalk.red,
33
- info: chalk.gray,
34
- system: chalk.magenta,
35
- signal: chalk.yellow,
36
- trade: chalk.green,
37
- warning: chalk.yellow,
38
- success: chalk.green,
39
- analysis: chalk.magenta
40
- };
41
-
42
- // Log type icons - Unicode icons (ALL 8 chars wide for alignment)
43
- const LOG_ICONS = {
44
- fill_buy: '⬆ BUY ',
45
- fill_sell: '⬇ SELL ',
46
- fill_win: '✔ WIN ',
47
- fill_loss: '✘ LOSS ',
48
- win: '✔ WIN ',
49
- loss: '✘ LOSS ',
50
- be: '★ BE ',
51
- entry: '➡ ENTRY',
52
- filled: '✔ FILL ',
53
- connected: '✔ CONN ',
54
- ready: '✔ READY',
55
- error: '✘ ERROR',
56
- reject: '✘ REJCT',
57
- info: '➡ INFO ',
58
- system: '★ SYSTM',
59
- signal: '★ SIGNL',
60
- trade: '✔ TRADE',
61
- success: '✔ SUCCS',
62
- warning: '⬅ WARNG',
63
- analysis: '★ ANLYS'
64
- };
65
-
66
- /** Strip ANSI codes from string */
67
- const stripAnsi = (str) => str.replace(/\x1B\[[0-9;]*m/g, '');
68
-
69
- /** Colorize message: positive numbers=cyan, negative=red, symbols=yellow */
70
- const colorizeMessage = (msg) => {
71
- if (!msg) return '';
72
- if (msg.includes('\x1B[')) return msg;
73
-
74
- return msg
75
- .replace(/\+\$[\d,]+\.?\d*/g, (m) => chalk.cyan.bold(m))
76
- .replace(/-\$[\d,]+\.?\d*/g, (m) => chalk.red.bold(m))
77
- .replace(/\+\d+\.?\d*/g, (m) => chalk.cyan(m))
78
- .replace(/-\d+\.?\d*/g, (m) => chalk.red(m))
79
- .replace(/\b(NQ|ES|MNQ|MES|RTY|M2K|YM|MYM|CL|GC|SI)[A-Z]\d\b/g, (m) => chalk.yellow.bold(m))
80
- .replace(/\d+\.?\d*%/g, (m) => chalk.cyan(m))
81
- .replace(/\b\d{4,5}\.\d{2}\b/g, (m) => chalk.white.bold(m));
82
- };
83
-
84
- /** Center text in width */
85
- const center = (text, width) => {
86
- const pad = Math.floor((width - text.length) / 2);
87
- return ' '.repeat(pad) + text + ' '.repeat(width - pad - text.length);
88
- };
89
-
90
- /** Fit text to exact width (truncate or pad) */
91
- const fitToWidth = (text, width) => {
92
- const plain = stripAnsi(text);
93
- if (plain.length > width) {
94
- let count = 0, cut = 0;
95
- for (let i = 0; i < text.length && count < width - 3; i++) {
96
- if (text[i] === '\x1B') { while (i < text.length && text[i] !== 'm') i++; }
97
- else { count++; cut = i + 1; }
98
- }
99
- return text.substring(0, cut) + '...';
100
- }
101
- return text + ' '.repeat(width - plain.length);
102
- };
103
-
104
- /** Build a labeled cell for grid - UPPERCASE BOLD style */
105
- const buildCell = (label, value, color, width) => {
106
- const upperLabel = label.toUpperCase();
107
- const upperValue = String(value).toUpperCase();
108
- const text = ` ${chalk.bold(upperLabel)}: ${color.bold(upperValue)}`;
109
- const plain = ` ${upperLabel}: ${upperValue}`;
110
- return { text, plain, padded: text + ' '.repeat(Math.max(0, width - plain.length)) };
111
- };
112
-
113
- /** Check market hours */
114
- const checkMarketStatus = () => {
115
- const now = new Date();
116
- const utcDay = now.getUTCDay();
117
- const utcHour = now.getUTCHours();
118
- const isDST = now.getTimezoneOffset() < Math.max(
119
- new Date(now.getFullYear(), 0, 1).getTimezoneOffset(),
120
- new Date(now.getFullYear(), 6, 1).getTimezoneOffset()
121
- );
122
- const ctOffset = isDST ? 5 : 6;
123
- const ctHour = (utcHour - ctOffset + 24) % 24;
124
- const ctDay = utcHour < ctOffset ? (utcDay + 6) % 7 : utcDay;
125
-
126
- if (ctDay === 6) return { isOpen: false, message: 'Market closed (Saturday)' };
127
- if (ctDay === 0 && ctHour < 17) return { isOpen: false, message: 'Market opens Sunday 5:00 PM CT' };
128
- if (ctDay === 5 && ctHour >= 16) return { isOpen: false, message: 'Market closed (Friday after 4PM CT)' };
129
- if (ctHour === 16 && ctDay >= 1 && ctDay <= 4) return { isOpen: false, message: 'Daily maintenance' };
130
- return { isOpen: true, message: 'Market OPEN' };
131
- };
132
-
133
- module.exports = {
134
- BOX,
135
- SPINNER,
136
- LOG_COLORS,
137
- LOG_ICONS,
138
- stripAnsi,
139
- colorizeMessage,
140
- center,
141
- fitToWidth,
142
- buildCell,
143
- checkMarketStatus,
144
- };
@@ -1,184 +0,0 @@
1
- /**
2
- * @fileoverview Algo UI Session Summary Renderers
3
- * Functions to render session summary screens
4
- */
5
-
6
- const chalk = require('chalk');
7
- const { BOX, center } = require('./ui-constants');
8
-
9
- /**
10
- * Render Session Summary - Same style as dashboard
11
- */
12
- const renderSessionSummary = (stats, stopReason) => {
13
- const W = 96;
14
- const colL = Math.floor(W / 2) - 1;
15
- const colR = W - colL - 1;
16
- const version = require('../../../package.json').version;
17
-
18
- console.clear();
19
- console.log();
20
-
21
- console.log(chalk.cyan(BOX.TOP + BOX.H.repeat(W) + BOX.TR));
22
-
23
- // Logo
24
- console.log(chalk.cyan(BOX.V) + chalk.cyan(' ██╗ ██╗███████╗██████╗ ██████╗ ███████╗ ██████╗ ██╗ ██╗ █████╗ ███╗ ██╗████████╗') + chalk.yellow('██╗ ██╗') + ' ' + chalk.cyan(BOX.V));
25
- console.log(chalk.cyan(BOX.V) + chalk.cyan(' ██║ ██║██╔════╝██╔══██╗██╔════╝ ██╔════╝██╔═══██╗██║ ██║██╔══██╗████╗ ██║╚══██╔══╝') + chalk.yellow('╚██╗██╔╝') + ' ' + chalk.cyan(BOX.V));
26
- console.log(chalk.cyan(BOX.V) + chalk.cyan(' ███████║█████╗ ██║ ██║██║ ███╗█████╗ ██║ ██║██║ ██║███████║██╔██╗ ██║ ██║ ') + chalk.yellow(' ╚███╔╝ ') + ' ' + chalk.cyan(BOX.V));
27
- console.log(chalk.cyan(BOX.V) + chalk.cyan(' ██╔══██║██╔══╝ ██║ ██║██║ ██║██╔══╝ ██║▄▄ ██║██║ ██║██╔══██║██║╚██╗██║ ██║ ') + chalk.yellow(' ██╔██╗ ') + ' ' + chalk.cyan(BOX.V));
28
- console.log(chalk.cyan(BOX.V) + chalk.cyan(' ██║ ██║███████╗██████╔╝╚██████╔╝███████╗╚██████╔╝╚██████╔╝██║ ██║██║ ╚████║ ██║ ') + chalk.yellow('██╔╝ ██╗') + ' ' + chalk.cyan(BOX.V));
29
- console.log(chalk.cyan(BOX.V) + chalk.cyan(' ╚═╝ ╚═╝╚══════╝╚═════╝ ╚═════╝ ╚══════╝ ╚══▀▀═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ') + chalk.yellow('╚═╝ ╚═╝') + ' ' + chalk.cyan(BOX.V));
30
-
31
- console.log(chalk.cyan(BOX.ML + BOX.H.repeat(W) + BOX.MR));
32
- console.log(chalk.cyan(BOX.V) + chalk.white(center(`PROP FUTURES ALGO TRADING v${version}`, W)) + chalk.cyan(BOX.V));
33
- console.log(chalk.cyan(BOX.ML + BOX.H.repeat(W) + BOX.MR));
34
- console.log(chalk.cyan(BOX.V) + chalk.yellow.bold(center('SESSION SUMMARY', W)) + chalk.cyan(BOX.V));
35
-
36
- const GT = BOX.ML + BOX.H.repeat(colL) + BOX.TM + BOX.H.repeat(colR) + BOX.MR;
37
- const GM = BOX.ML + BOX.H.repeat(colL) + BOX.MM + BOX.H.repeat(colR) + BOX.MR;
38
-
39
- const row = (label1, value1, color1, label2, value2, color2) => {
40
- const upperLabel1 = label1.toUpperCase();
41
- const upperLabel2 = label2.toUpperCase();
42
- const upperValue1 = String(value1).toUpperCase();
43
- const upperValue2 = String(value2).toUpperCase();
44
- const c1 = ` ${chalk.bold(upperLabel1)}: ${color1.bold(upperValue1)}`;
45
- const c2 = ` ${chalk.bold(upperLabel2)}: ${color2.bold(upperValue2)}`;
46
- const p1 = ` ${upperLabel1}: ${upperValue1}`;
47
- const p2 = ` ${upperLabel2}: ${upperValue2}`;
48
- const padded1 = c1 + ' '.repeat(Math.max(0, colL - p1.length));
49
- const padded2 = c2 + ' '.repeat(Math.max(0, colR - p2.length));
50
- console.log(chalk.cyan(BOX.V) + padded1 + chalk.cyan(BOX.VS) + padded2 + chalk.cyan(BOX.V));
51
- };
52
-
53
- console.log(chalk.cyan(GT));
54
-
55
- const duration = stats.duration || '--';
56
- const reasonColor = stopReason === 'target' ? chalk.green : stopReason === 'risk' ? chalk.red : chalk.yellow;
57
- row('Stop Reason', (stopReason || 'manual').toUpperCase(), reasonColor, 'Duration', duration, chalk.white);
58
-
59
- console.log(chalk.cyan(GM));
60
-
61
- const winRate = stats.trades > 0 ? ((stats.wins / stats.trades) * 100).toFixed(1) + '%' : '0%';
62
- row('Trades', String(stats.trades || 0), chalk.white, 'Win Rate', winRate, stats.wins >= stats.losses ? chalk.green : chalk.red);
63
-
64
- console.log(chalk.cyan(GM));
65
- row('Wins', String(stats.wins || 0), chalk.green, 'Losses', String(stats.losses || 0), chalk.red);
66
-
67
- console.log(chalk.cyan(GM));
68
-
69
- const pnl = stats.sessionPnl !== undefined ? stats.sessionPnl : (stats.pnl || 0);
70
- const pnlStr = `${pnl >= 0 ? '+' : ''}$${Math.abs(pnl).toFixed(2)}`;
71
- const pnlColor = pnl >= 0 ? chalk.green : chalk.red;
72
- const targetStr = `$${(stats.target || 0).toFixed(2)}`;
73
- row('Session P&L', pnlStr, pnlColor, 'TARGET', targetStr, chalk.cyan);
74
-
75
- console.log(chalk.cyan(BOX.BOT + BOX.H.repeat(W) + BOX.BR));
76
- console.log();
77
- };
78
-
79
- /**
80
- * Render Multi-Symbol Session Summary
81
- */
82
- const renderMultiSymbolSummary = (stats, stopReason, symbolStats) => {
83
- const W = 96;
84
- const version = require('../../../package.json').version;
85
-
86
- const centerCol = (text, width) => {
87
- const pad = Math.floor((width - text.length) / 2);
88
- return ' '.repeat(pad) + text + ' '.repeat(width - pad - text.length);
89
- };
90
-
91
- console.clear();
92
- console.log();
93
-
94
- console.log(chalk.cyan(BOX.TOP + BOX.H.repeat(W) + BOX.TR));
95
-
96
- // Logo
97
- console.log(chalk.cyan(BOX.V) + chalk.cyan(' ██╗ ██╗███████╗██████╗ ██████╗ ███████╗ ██████╗ ██╗ ██╗ █████╗ ███╗ ██╗████████╗') + chalk.yellow('██╗ ██╗') + ' ' + chalk.cyan(BOX.V));
98
- console.log(chalk.cyan(BOX.V) + chalk.cyan(' ██║ ██║██╔════╝██╔══██╗██╔════╝ ██╔════╝██╔═══██╗██║ ██║██╔══██╗████╗ ██║╚══██╔══╝') + chalk.yellow('╚██╗██╔╝') + ' ' + chalk.cyan(BOX.V));
99
- console.log(chalk.cyan(BOX.V) + chalk.cyan(' ███████║█████╗ ██║ ██║██║ ███╗█████╗ ██║ ██║██║ ██║███████║██╔██╗ ██║ ██║ ') + chalk.yellow(' ╚███╔╝ ') + ' ' + chalk.cyan(BOX.V));
100
- console.log(chalk.cyan(BOX.V) + chalk.cyan(' ██╔══██║██╔══╝ ██║ ██║██║ ██║██╔══╝ ██║▄▄ ██║██║ ██║██╔══██║██║╚██╗██║ ██║ ') + chalk.yellow(' ██╔██╗ ') + ' ' + chalk.cyan(BOX.V));
101
- console.log(chalk.cyan(BOX.V) + chalk.cyan(' ██║ ██║███████╗██████╔╝╚██████╔╝███████╗╚██████╔╝╚██████╔╝██║ ██║██║ ╚████║ ██║ ') + chalk.yellow('██╔╝ ██╗') + ' ' + chalk.cyan(BOX.V));
102
- console.log(chalk.cyan(BOX.V) + chalk.cyan(' ╚═╝ ╚═╝╚══════╝╚═════╝ ╚═════╝ ╚══════╝ ╚══▀▀═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ') + chalk.yellow('╚═╝ ╚═╝') + ' ' + chalk.cyan(BOX.V));
103
-
104
- console.log(chalk.cyan(BOX.ML + BOX.H.repeat(W) + BOX.MR));
105
- console.log(chalk.cyan(BOX.V) + chalk.white(center(`PROP FUTURES ALGO TRADING v${version}`, W)) + chalk.cyan(BOX.V));
106
- console.log(chalk.cyan(BOX.ML + BOX.H.repeat(W) + BOX.MR));
107
- console.log(chalk.cyan(BOX.V) + chalk.yellow.bold(center('MULTI-SYMBOL SESSION SUMMARY', W)) + chalk.cyan(BOX.V));
108
- console.log(chalk.cyan(BOX.ML + BOX.H.repeat(W) + BOX.MR));
109
-
110
- const colSymbol = 14;
111
- const colTrades = 12;
112
- const colWR = 14;
113
- const colWins = 12;
114
- const colLosses = 12;
115
- const colPnL = W - colSymbol - colTrades - colWR - colWins - colLosses - 5;
116
-
117
- const headerSymbol = centerCol('SYMBOL', colSymbol);
118
- const headerTrades = centerCol('TRADES', colTrades);
119
- const headerWR = centerCol('WIN RATE', colWR);
120
- const headerWins = centerCol('WINS', colWins);
121
- const headerLosses = centerCol('LOSSES', colLosses);
122
- const headerPnL = centerCol('P&L', colPnL);
123
-
124
- console.log(chalk.cyan(BOX.V) + chalk.bold.white(headerSymbol) + chalk.cyan(BOX.VS) +
125
- chalk.bold.white(headerTrades) + chalk.cyan(BOX.VS) +
126
- chalk.bold.white(headerWR) + chalk.cyan(BOX.VS) +
127
- chalk.bold.white(headerWins) + chalk.cyan(BOX.VS) +
128
- chalk.bold.white(headerLosses) + chalk.cyan(BOX.VS) +
129
- chalk.bold.white(headerPnL) + chalk.cyan(BOX.V));
130
-
131
- console.log(chalk.cyan(BOX.ML + BOX.H.repeat(W) + BOX.MR));
132
-
133
- for (const [symbol, symStats] of Object.entries(symbolStats)) {
134
- const winRate = symStats.trades > 0 ? ((symStats.wins / symStats.trades) * 100).toFixed(0) + '%' : '0%';
135
- const pnl = symStats.pnl || 0;
136
- const pnlStr = (pnl >= 0 ? '+$' : '-$') + Math.abs(pnl).toFixed(2);
137
- const pnlColor = pnl >= 0 ? chalk.green : chalk.red;
138
- const wrColor = symStats.wins >= symStats.losses ? chalk.green : chalk.red;
139
-
140
- console.log(chalk.cyan(BOX.V) + chalk.yellow(centerCol(symbol, colSymbol)) + chalk.cyan(BOX.VS) +
141
- chalk.white(centerCol(String(symStats.trades || 0), colTrades)) + chalk.cyan(BOX.VS) +
142
- wrColor(centerCol(winRate, colWR)) + chalk.cyan(BOX.VS) +
143
- chalk.green(centerCol(String(symStats.wins || 0), colWins)) + chalk.cyan(BOX.VS) +
144
- chalk.red(centerCol(String(symStats.losses || 0), colLosses)) + chalk.cyan(BOX.VS) +
145
- pnlColor.bold(centerCol(pnlStr, colPnL)) + chalk.cyan(BOX.V));
146
- }
147
-
148
- console.log(chalk.cyan(BOX.ML + BOX.H.repeat(W) + BOX.MR));
149
-
150
- const totalWinRate = stats.trades > 0 ? ((stats.wins / stats.trades) * 100).toFixed(0) + '%' : '0%';
151
- const totalPnl = stats.sessionPnl || 0;
152
- const totalPnlStr = (totalPnl >= 0 ? '+$' : '-$') + Math.abs(totalPnl).toFixed(2);
153
- const totalPnlColor = totalPnl >= 0 ? chalk.green : chalk.red;
154
- const totalWrColor = stats.wins >= stats.losses ? chalk.green : chalk.red;
155
-
156
- console.log(chalk.cyan(BOX.V) + chalk.bold.cyan(centerCol('TOTAL', colSymbol)) + chalk.cyan(BOX.VS) +
157
- chalk.bold.white(centerCol(String(stats.trades || 0), colTrades)) + chalk.cyan(BOX.VS) +
158
- totalWrColor.bold(centerCol(totalWinRate, colWR)) + chalk.cyan(BOX.VS) +
159
- chalk.bold.green(centerCol(String(stats.wins || 0), colWins)) + chalk.cyan(BOX.VS) +
160
- chalk.bold.red(centerCol(String(stats.losses || 0), colLosses)) + chalk.cyan(BOX.VS) +
161
- totalPnlColor.bold(centerCol(totalPnlStr, colPnL)) + chalk.cyan(BOX.V));
162
-
163
- console.log(chalk.cyan(BOX.ML + BOX.H.repeat(W) + BOX.MR));
164
-
165
- const duration = stats.duration || '--';
166
- const reasonColor = stopReason === 'target' ? chalk.green : stopReason === 'risk' ? chalk.red : chalk.yellow;
167
- const reasonStr = (stopReason || 'manual').toUpperCase();
168
- const infoPlain = `STOP: ${reasonStr} | DURATION: ${duration} | TARGET: $${(stats.target || 0).toFixed(2)} | RISK: $${(stats.risk || 0).toFixed(2)}`;
169
-
170
- const padLeft = Math.floor((W - infoPlain.length) / 2);
171
- const padRight = W - infoPlain.length - padLeft;
172
- const infoColored = ' '.repeat(padLeft) +
173
- chalk.bold('STOP') + ': ' + reasonColor.bold(reasonStr) + ' | ' +
174
- chalk.bold('DURATION') + ': ' + chalk.white(duration) + ' | ' +
175
- chalk.bold('TARGET') + ': ' + chalk.cyan('$' + (stats.target || 0).toFixed(2)) + ' | ' +
176
- chalk.bold('RISK') + ': ' + chalk.red('$' + (stats.risk || 0).toFixed(2)) +
177
- ' '.repeat(padRight);
178
-
179
- console.log(chalk.cyan(BOX.V) + infoColored + chalk.cyan(BOX.V));
180
- console.log(chalk.cyan(BOX.BOT + BOX.H.repeat(W) + BOX.BR));
181
- console.log();
182
- };
183
-
184
- module.exports = { renderSessionSummary, renderMultiSymbolSummary };
@@ -1,191 +0,0 @@
1
- /**
2
- * @fileoverview Stats Calculations
3
- * Calculate trading statistics from API data
4
- *
5
- * STRICT RULE: Calculate ONLY from values returned by API
6
- * - NO estimation, NO simulation, NO mock data
7
- */
8
-
9
- /**
10
- * Calculate trade statistics from completed trades
11
- * @param {Array} completedTrades - Trades with P&L != 0
12
- * @returns {Object} Statistics object
13
- */
14
- const calculateTradeStats = (completedTrades) => {
15
- const stats = {
16
- totalTrades: 0, winningTrades: 0, losingTrades: 0,
17
- totalWinAmount: 0, totalLossAmount: 0,
18
- bestTrade: 0, worstTrade: 0, totalVolume: 0,
19
- maxConsecutiveWins: 0, maxConsecutiveLosses: 0,
20
- longTrades: 0, shortTrades: 0, longWins: 0, shortWins: 0
21
- };
22
-
23
- if (!completedTrades || completedTrades.length === 0) {
24
- return stats;
25
- }
26
-
27
- stats.totalTrades = completedTrades.length;
28
- let consecutiveWins = 0, consecutiveLosses = 0;
29
-
30
- // Sort by time for consecutive win/loss calculation
31
- const sortedTrades = [...completedTrades].sort((a, b) => {
32
- const timeA = new Date(a.creationTimestamp || a.timestamp || 0).getTime();
33
- const timeB = new Date(b.creationTimestamp || b.timestamp || 0).getTime();
34
- return timeA - timeB;
35
- });
36
-
37
- for (const trade of sortedTrades) {
38
- const grossPnl = trade.profitAndLoss || trade.pnl || 0;
39
- const fees = Math.abs(trade.fees || trade.commission || 0);
40
- const netPnl = grossPnl - fees;
41
- const size = trade.size || trade.quantity || 1;
42
- const exitSide = trade.side;
43
-
44
- stats.totalVolume += Math.abs(size);
45
-
46
- // Determine original trade direction from exit side
47
- if (exitSide === 1) {
48
- stats.longTrades++;
49
- if (netPnl > 0) stats.longWins++;
50
- } else if (exitSide === 0) {
51
- stats.shortTrades++;
52
- if (netPnl > 0) stats.shortWins++;
53
- }
54
-
55
- if (netPnl > 0) {
56
- stats.winningTrades++;
57
- stats.totalWinAmount += netPnl;
58
- consecutiveWins++;
59
- consecutiveLosses = 0;
60
- if (consecutiveWins > stats.maxConsecutiveWins) stats.maxConsecutiveWins = consecutiveWins;
61
- if (netPnl > stats.bestTrade) stats.bestTrade = netPnl;
62
- } else if (netPnl < 0) {
63
- stats.losingTrades++;
64
- stats.totalLossAmount += Math.abs(netPnl);
65
- consecutiveLosses++;
66
- consecutiveWins = 0;
67
- if (consecutiveLosses > stats.maxConsecutiveLosses) stats.maxConsecutiveLosses = consecutiveLosses;
68
- if (netPnl < stats.worstTrade) stats.worstTrade = netPnl;
69
- }
70
- }
71
-
72
- return stats;
73
- };
74
-
75
- /**
76
- * Calculate quantitative metrics from trade P&Ls
77
- * @param {Array} completedTrades - Completed trades
78
- * @param {number} totalStartingBalance - Starting balance
79
- * @returns {Object} Quantitative metrics
80
- */
81
- const calculateQuantMetrics = (completedTrades, totalStartingBalance) => {
82
- const tradePnLs = completedTrades.map(t => {
83
- const grossPnl = t.profitAndLoss || t.pnl || 0;
84
- const fees = Math.abs(t.fees || t.commission || 0);
85
- return grossPnl - fees;
86
- });
87
-
88
- const avgReturn = tradePnLs.length > 0 ? tradePnLs.reduce((a, b) => a + b, 0) / tradePnLs.length : 0;
89
-
90
- // Standard deviation
91
- const variance = tradePnLs.length > 0
92
- ? tradePnLs.reduce((sum, pnl) => sum + Math.pow(pnl - avgReturn, 2), 0) / tradePnLs.length
93
- : 0;
94
- const stdDev = Math.sqrt(variance);
95
-
96
- // Downside deviation
97
- const downsideReturns = tradePnLs.filter(pnl => pnl < 0);
98
- const downsideVariance = downsideReturns.length > 0
99
- ? downsideReturns.reduce((sum, pnl) => sum + Math.pow(pnl, 2), 0) / downsideReturns.length
100
- : 0;
101
- const downsideDev = Math.sqrt(downsideVariance);
102
-
103
- // Ratios
104
- const sharpeRatio = stdDev > 0 ? (avgReturn / stdDev).toFixed(2) : 'N/A';
105
- const sortinoRatio = downsideDev > 0 ? (avgReturn / downsideDev).toFixed(2) : 'N/A';
106
-
107
- // Max Drawdown
108
- let maxDrawdown = 0;
109
- let peak = totalStartingBalance || 0;
110
- let equity = peak;
111
- if (peak > 0 && tradePnLs.length > 0) {
112
- tradePnLs.forEach(pnl => {
113
- equity += pnl;
114
- if (equity > peak) peak = equity;
115
- const drawdown = peak > 0 ? (peak - equity) / peak * 100 : 0;
116
- if (drawdown > maxDrawdown) maxDrawdown = drawdown;
117
- });
118
- }
119
-
120
- return {
121
- avgReturn,
122
- stdDev,
123
- sharpeRatio,
124
- sortinoRatio,
125
- maxDrawdown,
126
- tradePnLs,
127
- };
128
- };
129
-
130
- /**
131
- * Calculate HQX Score from stats
132
- * @param {Object} stats - Trade statistics
133
- * @param {number} totalStartingBalance - Starting balance
134
- * @param {string} returnPercent - Return percentage string
135
- * @param {string} profitFactor - Profit factor string
136
- * @param {string} winRate - Win rate string
137
- * @returns {Object} HQX Score components
138
- */
139
- const calculateHQXScore = (stats, totalStartingBalance, returnPercent, profitFactor, winRate) => {
140
- const winRateNum = winRate !== 'N/A' ? parseFloat(winRate) : 0;
141
- const winRateScore = Math.min(100, winRateNum * 1.5);
142
- const profitFactorScore = profitFactor === '∞' ? 100 : profitFactor === 'N/A' ? 0 : Math.min(100, parseFloat(profitFactor) * 40);
143
- const consistencyScore = stats.maxConsecutiveLosses > 0 ? Math.max(0, 100 - (stats.maxConsecutiveLosses * 15)) : 100;
144
- const riskScore = stats.worstTrade !== 0 && totalStartingBalance > 0
145
- ? Math.max(0, 100 - (Math.abs(stats.worstTrade) / totalStartingBalance * 1000))
146
- : 50;
147
- const volumeScore = Math.min(100, stats.totalTrades * 2);
148
- const returnNum = returnPercent !== 'N/A' ? parseFloat(returnPercent) : 0;
149
- const returnScore = Math.min(100, Math.max(0, returnNum * 10 + 50));
150
-
151
- const hqxScore = Math.round((winRateScore + profitFactorScore + consistencyScore + riskScore + volumeScore + returnScore) / 6);
152
- const scoreGrade = hqxScore >= 90 ? 'S' : hqxScore >= 80 ? 'A' : hqxScore >= 70 ? 'B' : hqxScore >= 60 ? 'C' : hqxScore >= 50 ? 'D' : 'F';
153
-
154
- return {
155
- hqxScore,
156
- scoreGrade,
157
- metrics: [
158
- { name: 'WIN RATE', score: winRateScore },
159
- { name: 'PROFIT FACTOR', score: profitFactorScore },
160
- { name: 'CONSISTENCY', score: consistencyScore },
161
- { name: 'RISK MANAGEMENT', score: riskScore },
162
- { name: 'VOLUME', score: volumeScore },
163
- { name: 'RETURNS', score: returnScore }
164
- ]
165
- };
166
- };
167
-
168
- /**
169
- * Extract symbol from contractId
170
- * @param {string} contractId - Contract ID (e.g., "CON.F.US.EP.H25")
171
- * @returns {string} Symbol (e.g., "ES H25")
172
- */
173
- const extractSymbol = (contractId) => {
174
- if (!contractId) return 'N/A';
175
- const parts = contractId.split('.');
176
- if (parts.length >= 5) {
177
- const sym = parts[3];
178
- const month = parts[4];
179
- const symbolMap = { 'EP': 'ES', 'ENQ': 'NQ', 'MES': 'MES', 'MNQ': 'MNQ', 'YM': 'YM', 'NKD': 'NKD', 'RTY': 'RTY' };
180
- return (symbolMap[sym] || sym) + ' ' + month;
181
- }
182
- if (contractId.length <= 10) return contractId;
183
- return contractId.substring(0, 10);
184
- };
185
-
186
- module.exports = {
187
- calculateTradeStats,
188
- calculateQuantMetrics,
189
- calculateHQXScore,
190
- extractSymbol,
191
- };