hedgequantx 2.6.160 → 2.6.162

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 (45) hide show
  1. package/package.json +1 -1
  2. package/src/menus/ai-agent-connect.js +181 -0
  3. package/src/menus/ai-agent-models.js +219 -0
  4. package/src/menus/ai-agent-oauth.js +292 -0
  5. package/src/menus/ai-agent-ui.js +141 -0
  6. package/src/menus/ai-agent.js +88 -1489
  7. package/src/pages/algo/copy-engine.js +449 -0
  8. package/src/pages/algo/copy-trading.js +11 -543
  9. package/src/pages/algo/smart-logs-data.js +218 -0
  10. package/src/pages/algo/smart-logs.js +9 -214
  11. package/src/pages/algo/ui-constants.js +144 -0
  12. package/src/pages/algo/ui-summary.js +184 -0
  13. package/src/pages/algo/ui.js +42 -526
  14. package/src/pages/stats-calculations.js +191 -0
  15. package/src/pages/stats-ui.js +381 -0
  16. package/src/pages/stats.js +14 -507
  17. package/src/services/ai/client-analysis.js +194 -0
  18. package/src/services/ai/client-models.js +333 -0
  19. package/src/services/ai/client.js +6 -489
  20. package/src/services/ai/index.js +2 -257
  21. package/src/services/ai/proxy-install.js +249 -0
  22. package/src/services/ai/proxy-manager.js +29 -411
  23. package/src/services/ai/proxy-remote.js +161 -0
  24. package/src/services/ai/strategy-supervisor.js +10 -765
  25. package/src/services/ai/supervisor-data.js +195 -0
  26. package/src/services/ai/supervisor-optimize.js +215 -0
  27. package/src/services/ai/supervisor-sync.js +178 -0
  28. package/src/services/ai/supervisor-utils.js +158 -0
  29. package/src/services/ai/supervisor.js +50 -515
  30. package/src/services/ai/validation.js +250 -0
  31. package/src/services/hqx-server-events.js +110 -0
  32. package/src/services/hqx-server-handlers.js +217 -0
  33. package/src/services/hqx-server-latency.js +136 -0
  34. package/src/services/hqx-server.js +51 -403
  35. package/src/services/position-constants.js +28 -0
  36. package/src/services/position-manager.js +105 -554
  37. package/src/services/position-momentum.js +206 -0
  38. package/src/services/projectx/accounts.js +142 -0
  39. package/src/services/projectx/index.js +40 -289
  40. package/src/services/projectx/trading.js +180 -0
  41. package/src/services/rithmic/handlers.js +2 -208
  42. package/src/services/rithmic/index.js +32 -542
  43. package/src/services/rithmic/latency-tracker.js +182 -0
  44. package/src/services/rithmic/specs.js +146 -0
  45. package/src/services/rithmic/trade-history.js +254 -0
@@ -0,0 +1,191 @@
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
+ };
@@ -0,0 +1,381 @@
1
+ /**
2
+ * @fileoverview Stats UI Rendering
3
+ * UI rendering functions for stats page
4
+ */
5
+
6
+ const chalk = require('chalk');
7
+ const asciichart = require('asciichart');
8
+ const { drawBoxHeader, drawBoxFooter, draw2ColHeader, fmtRow } = require('../ui');
9
+
10
+ /**
11
+ * Render AI Supervision section
12
+ * @param {Array} aiAgents - Connected AI agents
13
+ * @param {Array} supervisionStatus - Status from AISupervisor
14
+ * @param {Object} AISupervisor - AISupervisor module
15
+ * @param {number} boxWidth - Box width
16
+ * @param {number} col1 - Column 1 width
17
+ * @param {number} col2 - Column 2 width
18
+ */
19
+ const renderAISupervision = (aiAgents, supervisionStatus, AISupervisor, boxWidth, col1, col2) => {
20
+ drawBoxHeader('AI SUPERVISION', boxWidth);
21
+ draw2ColHeader('AGENTS', 'PERFORMANCE', boxWidth);
22
+
23
+ const isConsensusMode = aiAgents.length >= 2;
24
+ const agentMode = isConsensusMode ? 'CONSENSUS' : 'INDIVIDUAL';
25
+ const modeColor = isConsensusMode ? chalk.magenta : chalk.cyan;
26
+ const consensusData = isConsensusMode ? AISupervisor.getConsensus() : null;
27
+
28
+ let totalSessionTime = 0;
29
+ for (const status of supervisionStatus) {
30
+ if (status.active) {
31
+ totalSessionTime += status.duration || 0;
32
+ }
33
+ }
34
+
35
+ const sessionTimeStr = totalSessionTime > 0
36
+ ? Math.floor(totalSessionTime / 60000) + 'm ' + Math.floor((totalSessionTime % 60000) / 1000) + 's'
37
+ : 'INACTIVE';
38
+
39
+ const supervisionData = AISupervisor.getAggregatedData();
40
+ const supervisedAccounts = supervisionData.totalAccounts;
41
+ const supervisedPnL = supervisionData.totalPnL;
42
+ const maxAgentNameLen = col1 - 20;
43
+
44
+ const perfData = [
45
+ { label: 'SUPERVISED ACCOUNTS:', value: chalk.white(String(supervisedAccounts)) },
46
+ { label: 'SUPERVISED P&L:', value: supervisedPnL >= 0 ? chalk.green('$' + supervisedPnL.toFixed(2)) : chalk.red('$' + supervisedPnL.toFixed(2)) },
47
+ { label: 'POSITIONS:', value: chalk.white(String(supervisionData.totalPositions)) },
48
+ { label: 'OPEN ORDERS:', value: chalk.white(String(supervisionData.totalOrders)) },
49
+ { label: 'TRADES TODAY:', value: chalk.white(String(supervisionData.totalTrades)) }
50
+ ];
51
+
52
+ const agentsData = [
53
+ { label: 'CONNECTED:', value: chalk.green(String(aiAgents.length) + ' AGENT' + (aiAgents.length > 1 ? 'S' : '')) },
54
+ { label: 'MODE:', value: modeColor(agentMode) },
55
+ { label: 'SESSION:', value: sessionTimeStr === 'INACTIVE' ? chalk.yellow(sessionTimeStr) : chalk.white(sessionTimeStr) }
56
+ ];
57
+
58
+ if (isConsensusMode && consensusData) {
59
+ const isUnanimous = consensusData.isUnanimous;
60
+ const consensusAction = consensusData.action || 'PENDING';
61
+ const consensusDisplay = isUnanimous
62
+ ? chalk.green(consensusAction + ' (UNANIMOUS)')
63
+ : chalk.yellow(consensusAction + ' (DISAGREEMENT)');
64
+ agentsData.push({ label: 'DECISION:', value: consensusDisplay });
65
+ } else if (isConsensusMode) {
66
+ agentsData.push({ label: 'DECISION:', value: chalk.white('WAITING...') });
67
+ }
68
+
69
+ aiAgents.forEach((agent, idx) => {
70
+ const agentLabel = idx === 0 ? 'AGENTS:' : '';
71
+ const agentName = agent.name.length > maxAgentNameLen
72
+ ? agent.name.substring(0, maxAgentNameLen - 4) + '..'
73
+ : agent.name;
74
+ const agentDisplay = chalk.green('● ') + chalk.white(agentName);
75
+ agentsData.push({ label: agentLabel, value: agentDisplay });
76
+ });
77
+
78
+ const maxRows = Math.max(agentsData.length, perfData.length);
79
+ for (let i = 0; i < maxRows; i++) {
80
+ const leftData = agentsData[i] || { label: '', value: '' };
81
+ const rightData = perfData[i] || { label: '', value: '' };
82
+ console.log(chalk.cyan('\u2551') + fmtRow(leftData.label, leftData.value, col1) + chalk.cyan('\u2502') + fmtRow(rightData.label, rightData.value, col2) + chalk.cyan('\u2551'));
83
+ }
84
+
85
+ drawBoxFooter(boxWidth);
86
+ };
87
+
88
+ /**
89
+ * Render AI Behavior section
90
+ * @param {Object} StrategySupervisor - StrategySupervisor module
91
+ * @param {number} boxWidth - Box width
92
+ */
93
+ const renderAIBehavior = (StrategySupervisor, boxWidth) => {
94
+ const behaviorData = StrategySupervisor.getBehaviorHistory(100);
95
+ const learningStats = StrategySupervisor.getLearningStats();
96
+
97
+ console.log();
98
+ drawBoxHeader('AI AGENTS BEHAVIOR', boxWidth);
99
+
100
+ const behaviorInnerWidth = boxWidth - 2;
101
+ const behaviorCounts = { AGGRESSIVE: 0, NORMAL: 0, CAUTIOUS: 0, PAUSE: 0 };
102
+ const valueToAction = { 3: 'AGGRESSIVE', 2: 'NORMAL', 1: 'CAUTIOUS', 0: 'PAUSE' };
103
+
104
+ if (behaviorData.values.length > 0) {
105
+ for (const val of behaviorData.values) {
106
+ const action = valueToAction[Math.round(val)] || 'NORMAL';
107
+ behaviorCounts[action]++;
108
+ }
109
+ } else {
110
+ behaviorCounts.NORMAL = 1;
111
+ }
112
+
113
+ const total = Object.values(behaviorCounts).reduce((a, b) => a + b, 0) || 1;
114
+ const percentages = {
115
+ AGGRESSIVE: Math.round((behaviorCounts.AGGRESSIVE / total) * 100),
116
+ NORMAL: Math.round((behaviorCounts.NORMAL / total) * 100),
117
+ CAUTIOUS: Math.round((behaviorCounts.CAUTIOUS / total) * 100),
118
+ PAUSE: Math.round((behaviorCounts.PAUSE / total) * 100)
119
+ };
120
+
121
+ const currentValue = behaviorData.values.length > 0 ? behaviorData.values[behaviorData.values.length - 1] : 2;
122
+ const currentAction = valueToAction[Math.round(currentValue)] || 'NORMAL';
123
+
124
+ const barColors = {
125
+ AGGRESSIVE: chalk.green,
126
+ NORMAL: chalk.cyan,
127
+ CAUTIOUS: chalk.yellow,
128
+ PAUSE: chalk.red
129
+ };
130
+
131
+ const barLabels = ['AGGRESSIVE', 'NORMAL', 'CAUTIOUS', 'PAUSE'];
132
+ const shortLabels = ['AGR', 'NOR', 'CAU', 'PAU'];
133
+ const labelWidth = 6;
134
+ const pctWidth = 6;
135
+ const spacing = 4;
136
+
137
+ const availableWidth = behaviorInnerWidth - (labelWidth * 4) - (pctWidth * 4) - (spacing * 3) - 4;
138
+ const maxBarWidth = Math.floor(availableWidth / 4);
139
+
140
+ const barWidths = {
141
+ AGGRESSIVE: Math.round((percentages.AGGRESSIVE / 100) * maxBarWidth),
142
+ NORMAL: Math.round((percentages.NORMAL / 100) * maxBarWidth),
143
+ CAUTIOUS: Math.round((percentages.CAUTIOUS / 100) * maxBarWidth),
144
+ PAUSE: Math.round((percentages.PAUSE / 100) * maxBarWidth)
145
+ };
146
+
147
+ for (let i = 0; i < 4; i++) {
148
+ const label = barLabels[i];
149
+ const shortLabel = shortLabels[i];
150
+ const pct = percentages[label];
151
+ const barWidth = barWidths[label];
152
+ const color = barColors[label];
153
+ const isCurrent = label === currentAction;
154
+
155
+ const block = isCurrent ? '█' : '▓';
156
+ const bar = barWidth > 0 ? color(block.repeat(barWidth)) : '';
157
+ const emptySpace = ' '.repeat(Math.max(0, maxBarWidth - barWidth));
158
+
159
+ const labelPart = ' ' + color(shortLabel.padEnd(labelWidth));
160
+ const barPart = bar + emptySpace;
161
+ const pctPart = chalk.white((pct + '%').padStart(pctWidth));
162
+
163
+ let line = labelPart + barPart + pctPart;
164
+ const lineLen = line.replace(/\x1b\[[0-9;]*m/g, '').length;
165
+ line += ' '.repeat(Math.max(0, behaviorInnerWidth - lineLen));
166
+ console.log(chalk.cyan('\u2551') + line + chalk.cyan('\u2551'));
167
+ }
168
+
169
+ console.log(chalk.cyan('\u2551') + ' '.repeat(behaviorInnerWidth) + chalk.cyan('\u2551'));
170
+
171
+ const statsLine = ` CURRENT: ${barColors[currentAction](currentAction)} | SESSION PATTERNS: ${learningStats.patternsLearned.total} (${learningStats.patternsLearned.winning}W/${learningStats.patternsLearned.losing}L) | OPTIMIZATIONS: ${learningStats.optimizations}`;
172
+ const statsLen = statsLine.replace(/\x1b\[[0-9;]*m/g, '').length;
173
+ console.log(chalk.cyan('\u2551') + statsLine + ' '.repeat(Math.max(0, behaviorInnerWidth - statsLen)) + chalk.cyan('\u2551'));
174
+
175
+ const lifetimeStats = StrategySupervisor.getLifetimeStats();
176
+ if (lifetimeStats.totalSessions > 0) {
177
+ const lifetimeLine = ` LIFETIME: ${lifetimeStats.totalSessions} sessions | ${lifetimeStats.totalTrades} trades | WR: ${lifetimeStats.lifetimeWinRate} | P&L: $${lifetimeStats.lifetimePnL.toFixed(2)} | ${lifetimeStats.patternsLearned.winning + lifetimeStats.patternsLearned.losing} patterns learned`;
178
+ const lifetimeLen = lifetimeLine.length;
179
+ console.log(chalk.cyan('\u2551') + chalk.magenta(lifetimeLine) + ' '.repeat(Math.max(0, behaviorInnerWidth - lifetimeLen)) + chalk.cyan('\u2551'));
180
+ }
181
+
182
+ drawBoxFooter(boxWidth);
183
+ };
184
+
185
+ /**
186
+ * Render Equity Curve section
187
+ * @param {Array} allTrades - All trades
188
+ * @param {number} totalStartingBalance - Starting balance
189
+ * @param {Object} connectionTypes - Connection type counts
190
+ * @param {number} boxWidth - Box width
191
+ */
192
+ const renderEquityCurve = (allTrades, totalStartingBalance, connectionTypes, boxWidth) => {
193
+ drawBoxHeader('EQUITY CURVE', boxWidth);
194
+
195
+ const chartInnerWidth = boxWidth - 2;
196
+
197
+ if (allTrades.length > 0) {
198
+ const yAxisWidth = 10;
199
+ const chartAreaWidth = chartInnerWidth - yAxisWidth - 4;
200
+
201
+ let equityData = [totalStartingBalance || 100000];
202
+ let eqVal = equityData[0];
203
+ allTrades.forEach(trade => {
204
+ eqVal += (trade.profitAndLoss || trade.pnl || 0);
205
+ equityData.push(eqVal);
206
+ });
207
+
208
+ const maxDataPoints = chartAreaWidth - 5;
209
+ if (equityData.length > maxDataPoints) {
210
+ const step = Math.ceil(equityData.length / maxDataPoints);
211
+ equityData = equityData.filter((_, i) => i % step === 0);
212
+ }
213
+
214
+ const chartConfig = {
215
+ height: 10,
216
+ colors: [equityData[equityData.length - 1] < equityData[0] ? asciichart.red : asciichart.green],
217
+ format: (x) => ('$' + (x / 1000).toFixed(0) + 'K').padStart(yAxisWidth)
218
+ };
219
+
220
+ const chart = asciichart.plot(equityData, chartConfig);
221
+ chart.split('\n').forEach(line => {
222
+ let chartLine = ' ' + line;
223
+ const len = chartLine.replace(/\x1b\[[0-9;]*m/g, '').length;
224
+ if (len < chartInnerWidth) chartLine += ' '.repeat(chartInnerWidth - len);
225
+ console.log(chalk.cyan('\u2551') + chartLine + chalk.cyan('\u2551'));
226
+ });
227
+ } else {
228
+ const msg = connectionTypes.rithmic > 0
229
+ ? ' NO TRADE HISTORY (RITHMIC DOES NOT PROVIDE TRADE HISTORY API)'
230
+ : ' NO TRADE DATA AVAILABLE';
231
+ console.log(chalk.cyan('\u2551') + chalk.gray(msg) + ' '.repeat(Math.max(0, chartInnerWidth - msg.length)) + chalk.cyan('\u2551'));
232
+ }
233
+
234
+ drawBoxFooter(boxWidth);
235
+ };
236
+
237
+ /**
238
+ * Render Trades History section
239
+ * @param {Array} completedTrades - Completed trades (P&L != 0)
240
+ * @param {Object} connectionTypes - Connection type counts
241
+ * @param {Function} extractSymbol - Symbol extraction function
242
+ * @param {number} boxWidth - Box width
243
+ */
244
+ const renderTradesHistory = (completedTrades, connectionTypes, extractSymbol, boxWidth) => {
245
+ drawBoxHeader('TRADES HISTORY', boxWidth);
246
+
247
+ const innerWidth = boxWidth - 2;
248
+
249
+ if (completedTrades.length > 0) {
250
+ const colTime = 9;
251
+ const colSymbol = 10;
252
+ const colSide = 6;
253
+ const colPnl = 10;
254
+ const colFees = 8;
255
+ const colNet = 10;
256
+ const fixedCols = colTime + colSymbol + colSide + colPnl + colFees + colNet;
257
+ const separatorChars = 6 * 2;
258
+ const leadingSpace = 1;
259
+ const colAccount = innerWidth - fixedCols - separatorChars - leadingSpace;
260
+
261
+ const headerParts = [
262
+ ' ' + 'TIME'.padEnd(colTime),
263
+ 'SYMBOL'.padEnd(colSymbol),
264
+ 'SIDE'.padEnd(colSide),
265
+ 'P&L'.padEnd(colPnl),
266
+ 'FEES'.padEnd(colFees),
267
+ 'NET'.padEnd(colNet),
268
+ 'ACCOUNT'.padEnd(colAccount)
269
+ ];
270
+ const header = headerParts.join('| ');
271
+ console.log(chalk.cyan('\u2551') + chalk.white(header) + chalk.cyan('\u2551'));
272
+ console.log(chalk.cyan('\u255F') + chalk.cyan('\u2500'.repeat(innerWidth)) + chalk.cyan('\u2562'));
273
+
274
+ const sortedTrades = [...completedTrades].sort((a, b) => {
275
+ const timeA = new Date(a.creationTimestamp || a.timestamp || 0).getTime();
276
+ const timeB = new Date(b.creationTimestamp || b.timestamp || 0).getTime();
277
+ return timeB - timeA;
278
+ });
279
+
280
+ for (const trade of sortedTrades) {
281
+ const timestamp = trade.creationTimestamp || trade.timestamp;
282
+ const time = timestamp ? new Date(timestamp).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true }) : '--:--';
283
+ const symbol = extractSymbol(trade.contractId || trade.symbol);
284
+ const pnl = trade.profitAndLoss || trade.pnl || 0;
285
+ const fees = trade.fees || trade.commission || 0;
286
+ const netPnl = pnl - Math.abs(fees);
287
+
288
+ const pnlText = pnl >= 0 ? `+$${pnl.toFixed(0)}` : `-$${Math.abs(pnl).toFixed(0)}`;
289
+ const feesText = fees !== 0 ? `-$${Math.abs(fees).toFixed(2)}` : '$0';
290
+ const netText = netPnl >= 0 ? `+$${netPnl.toFixed(0)}` : `-$${Math.abs(netPnl).toFixed(0)}`;
291
+
292
+ const exitSide = trade.side;
293
+ const tradeSide = exitSide === 0 ? 'SHORT' : 'LONG';
294
+ const accountName = (trade.accountName || 'N/A').substring(0, colAccount - 3);
295
+
296
+ const timeStr = time.padEnd(colTime);
297
+ const symbolStr = symbol.padEnd(colSymbol);
298
+ const sideStr = tradeSide.padEnd(colSide);
299
+ const pnlStr = pnlText.padEnd(colPnl);
300
+ const feesStr = feesText.padEnd(colFees);
301
+ const netStr = netText.padEnd(colNet);
302
+ const accountStr = accountName.padEnd(colAccount);
303
+
304
+ const pnlColored = pnl >= 0 ? chalk.green(pnlStr) : chalk.red(pnlStr);
305
+ const feesColored = chalk.yellow(feesStr);
306
+ const netColored = netPnl >= 0 ? chalk.green(netStr) : chalk.red(netStr);
307
+ const sideColored = tradeSide === 'LONG' ? chalk.green(sideStr) : chalk.red(sideStr);
308
+
309
+ const rowParts = [
310
+ ' ' + timeStr,
311
+ symbolStr,
312
+ sideColored,
313
+ pnlColored,
314
+ feesColored,
315
+ netColored,
316
+ accountStr
317
+ ];
318
+ const row = rowParts.join('| ');
319
+ console.log(chalk.cyan('\u2551') + row + chalk.cyan('\u2551'));
320
+ }
321
+
322
+ if (sortedTrades.length === 0) {
323
+ const msg = ' NO COMPLETED TRADES YET';
324
+ console.log(chalk.cyan('\u2551') + chalk.gray(msg.padEnd(innerWidth)) + chalk.cyan('\u2551'));
325
+ }
326
+ } else {
327
+ const msg = connectionTypes.rithmic > 0
328
+ ? ' NO TRADE HISTORY (RITHMIC API LIMITATION)'
329
+ : ' NO TRADE HISTORY AVAILABLE';
330
+ console.log(chalk.cyan('\u2551') + chalk.gray(msg.padEnd(innerWidth)) + chalk.cyan('\u2551'));
331
+ }
332
+
333
+ drawBoxFooter(boxWidth);
334
+ };
335
+
336
+ /**
337
+ * Render HQX Score section
338
+ * @param {Object} hqxData - HQX score data from calculateHQXScore
339
+ * @param {number} boxWidth - Box width
340
+ */
341
+ const renderHQXScore = (hqxData, boxWidth) => {
342
+ drawBoxHeader('HQX SCORE', boxWidth);
343
+
344
+ const innerWidth = boxWidth - 2;
345
+ const { hqxScore, scoreGrade, metrics: metricsDisplay } = hqxData;
346
+ const scoreColor = hqxScore >= 70 ? chalk.green : hqxScore >= 50 ? chalk.yellow : chalk.red;
347
+
348
+ const makeBar = (score, width = 20) => {
349
+ const filled = Math.round((score / 100) * width);
350
+ const empty = width - filled;
351
+ const color = score >= 70 ? chalk.green : score >= 50 ? chalk.yellow : chalk.red;
352
+ return color('\u2588'.repeat(filled)) + chalk.gray('\u2591'.repeat(empty));
353
+ };
354
+
355
+ const barWidth = 30;
356
+ const labelWidth = 18;
357
+
358
+ const overallLine = ` OVERALL SCORE: ${scoreColor(String(hqxScore))} / 100 [GRADE: ${scoreColor(scoreGrade)}]`;
359
+ const overallVisLen = overallLine.replace(/\x1b\[[0-9;]*m/g, '').length;
360
+ console.log(chalk.cyan('\u2551') + overallLine + ' '.repeat(innerWidth - overallVisLen) + chalk.cyan('\u2551'));
361
+ console.log(chalk.cyan('\u2551') + chalk.gray('\u2500'.repeat(innerWidth)) + chalk.cyan('\u2551'));
362
+
363
+ for (const metric of metricsDisplay) {
364
+ const label = (' ' + metric.name + ':').padEnd(labelWidth);
365
+ const bar = makeBar(metric.score, barWidth);
366
+ const pct = (metric.score.toFixed(0) + '%').padStart(5);
367
+ const line = label + bar + ' ' + pct;
368
+ const visLen = line.replace(/\x1b\[[0-9;]*m/g, '').length;
369
+ console.log(chalk.cyan('\u2551') + chalk.white(label) + bar + ' ' + chalk.white(pct) + ' '.repeat(innerWidth - visLen) + chalk.cyan('\u2551'));
370
+ }
371
+
372
+ drawBoxFooter(boxWidth);
373
+ };
374
+
375
+ module.exports = {
376
+ renderAISupervision,
377
+ renderAIBehavior,
378
+ renderEquityCurve,
379
+ renderTradesHistory,
380
+ renderHQXScore,
381
+ };