hedgequantx 2.6.163 → 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 (146) 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 +116 -99
  67. package/src/services/rithmic/handlers.js +21 -196
  68. package/src/services/rithmic/index.js +63 -120
  69. package/src/services/rithmic/market.js +31 -0
  70. package/src/services/rithmic/orders.js +5 -111
  71. package/src/services/rithmic/protobuf.js +384 -138
  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/direct-providers.js +0 -323
  106. package/src/services/ai/providers/index.js +0 -62
  107. package/src/services/ai/providers/other-providers.js +0 -104
  108. package/src/services/ai/proxy-install.js +0 -249
  109. package/src/services/ai/proxy-manager.js +0 -494
  110. package/src/services/ai/proxy-remote.js +0 -161
  111. package/src/services/ai/strategy-supervisor.js +0 -1312
  112. package/src/services/ai/supervisor-data.js +0 -195
  113. package/src/services/ai/supervisor-optimize.js +0 -215
  114. package/src/services/ai/supervisor-sync.js +0 -178
  115. package/src/services/ai/supervisor-utils.js +0 -158
  116. package/src/services/ai/supervisor.js +0 -484
  117. package/src/services/ai/validation.js +0 -250
  118. package/src/services/hqx-server-events.js +0 -110
  119. package/src/services/hqx-server-handlers.js +0 -217
  120. package/src/services/hqx-server-latency.js +0 -136
  121. package/src/services/hqx-server.js +0 -403
  122. package/src/services/position-constants.js +0 -28
  123. package/src/services/position-exit-logic.js +0 -174
  124. package/src/services/position-manager.js +0 -438
  125. package/src/services/position-momentum.js +0 -206
  126. package/src/services/projectx/accounts.js +0 -142
  127. package/src/services/projectx/index.js +0 -443
  128. package/src/services/projectx/market.js +0 -172
  129. package/src/services/projectx/stats.js +0 -110
  130. package/src/services/projectx/trading.js +0 -180
  131. package/src/services/rithmic/latency-tracker.js +0 -182
  132. package/src/services/rithmic/market-data-decoders.js +0 -229
  133. package/src/services/rithmic/market-data.js +0 -272
  134. package/src/services/rithmic/orders-fast.js +0 -246
  135. package/src/services/rithmic/proto-decoders.js +0 -403
  136. package/src/services/rithmic/specs.js +0 -146
  137. package/src/services/rithmic/trade-history.js +0 -254
  138. package/src/services/session-history.js +0 -475
  139. package/src/services/strategy/hft-signal-calc.js +0 -147
  140. package/src/services/strategy/hft-tick.js +0 -407
  141. package/src/services/strategy/recovery-math.js +0 -402
  142. package/src/services/tradovate/constants.js +0 -109
  143. package/src/services/tradovate/index.js +0 -392
  144. package/src/services/tradovate/market.js +0 -47
  145. package/src/services/tradovate/orders.js +0 -145
  146. package/src/services/tradovate/websocket.js +0 -97
@@ -1,158 +0,0 @@
1
- /**
2
- * Supervisor Utility Functions
3
- * Pure functions for market analysis - no state dependencies
4
- */
5
-
6
- 'use strict';
7
-
8
- const calculateTrendStrength = (ticks) => {
9
- if (!ticks || ticks.length < 20) return { strength: 0, direction: 'unknown' };
10
- const prices = ticks.map(t => t.price).filter(Boolean);
11
- if (prices.length < 20) return { strength: 0, direction: 'unknown' };
12
- const shortTerm = prices.slice(-20);
13
- const shortChange = shortTerm[shortTerm.length - 1] - shortTerm[0];
14
- const mediumTerm = prices.slice(-50);
15
- const mediumChange = mediumTerm[mediumTerm.length - 1] - mediumTerm[0];
16
- const aligned = (shortChange > 0 && mediumChange > 0) || (shortChange < 0 && mediumChange < 0);
17
- const avgRange = Math.abs(Math.max(...prices) - Math.min(...prices)) || 1;
18
- return {
19
- strength: aligned ? Math.min(1, (Math.abs(shortChange) + Math.abs(mediumChange)) / avgRange) : 0,
20
- direction: mediumChange > 0 ? 'bullish' : mediumChange < 0 ? 'bearish' : 'neutral',
21
- shortTermDirection: shortChange > 0 ? 'up' : shortChange < 0 ? 'down' : 'flat',
22
- aligned
23
- };
24
- };
25
-
26
- const calculateRecentRange = (ticks, count) => {
27
- if (!ticks || ticks.length === 0) return { high: 0, low: 0, range: 0 };
28
- const prices = ticks.slice(-count).map(t => t.price).filter(Boolean);
29
- if (prices.length === 0) return { high: 0, low: 0, range: 0 };
30
- const high = Math.max(...prices);
31
- const low = Math.min(...prices);
32
- return { high, low, range: high - low };
33
- };
34
-
35
- const calculatePriceVelocity = (ticks, count) => {
36
- if (!ticks || ticks.length < 2) return { velocity: 0, acceleration: 0 };
37
- const recentTicks = ticks.slice(-count);
38
- if (recentTicks.length < 2) return { velocity: 0, acceleration: 0 };
39
- const prices = recentTicks.map(t => t.price).filter(Boolean);
40
- if (prices.length < 2) return { velocity: 0, acceleration: 0 };
41
- const totalChange = prices[prices.length - 1] - prices[0];
42
- const velocity = totalChange / prices.length;
43
- const midPoint = Math.floor(prices.length / 2);
44
- const firstHalfVelocity = (prices[midPoint] - prices[0]) / midPoint;
45
- const secondHalfVelocity = (prices[prices.length - 1] - prices[midPoint]) / (prices.length - midPoint);
46
- const acceleration = secondHalfVelocity - firstHalfVelocity;
47
- return { velocity, acceleration };
48
- };
49
-
50
- const getMarketSession = (hour) => {
51
- if (hour >= 9 && hour < 12) return 'morning';
52
- if (hour >= 12 && hour < 14) return 'midday';
53
- if (hour >= 14 && hour < 16) return 'afternoon';
54
- if (hour >= 16 && hour < 18) return 'close';
55
- if (hour >= 18 || hour < 9) return 'overnight';
56
- return 'unknown';
57
- };
58
-
59
- const getMinutesSinceOpen = (hour) => {
60
- const now = new Date();
61
- const currentMinutes = hour * 60 + now.getMinutes();
62
- const openMinutes = 9 * 60 + 30;
63
- return Math.max(0, currentMinutes - openMinutes);
64
- };
65
-
66
- const analyzePriceLevelInteraction = (entryPrice, ticks) => {
67
- if (!ticks || ticks.length < 20) return null;
68
- const prices = ticks.map(t => t.price).filter(Boolean);
69
- if (prices.length < 20) return null;
70
- const high = Math.max(...prices);
71
- const low = Math.min(...prices);
72
- const range = high - low || 1;
73
- const positionInRange = (entryPrice - low) / range;
74
- let levelType = 'middle';
75
- if (positionInRange > 0.8) levelType = 'near_high';
76
- else if (positionInRange < 0.2) levelType = 'near_low';
77
- else if (positionInRange > 0.6) levelType = 'upper_middle';
78
- else if (positionInRange < 0.4) levelType = 'lower_middle';
79
- return {
80
- positionInRange: Math.round(positionInRange * 100) / 100,
81
- distanceToHigh: high - entryPrice,
82
- distanceToLow: entryPrice - low,
83
- recentHigh: high,
84
- recentLow: low,
85
- levelType
86
- };
87
- };
88
-
89
- const determineLevelType = (price, ticks) => {
90
- if (!ticks || ticks.length < 10) return 'unknown';
91
- const prices = ticks.map(t => t.price).filter(Boolean);
92
- if (prices.length < 10) return 'unknown';
93
- const high = Math.max(...prices);
94
- const low = Math.min(...prices);
95
- const tickSize = 0.25;
96
- if (Math.abs(price - high) <= tickSize * 4) return 'resistance';
97
- if (Math.abs(price - low) <= tickSize * 4) return 'support';
98
- if (price > high) return 'breakout_high';
99
- if (price < low) return 'breakout_low';
100
- return 'middle';
101
- };
102
-
103
- const analyzePriceAction = (ticks) => {
104
- if (!ticks || ticks.length < 2) return { trend: 'unknown', strength: 0 };
105
- const prices = ticks.map(t => t.price).filter(Boolean);
106
- if (prices.length < 2) return { trend: 'unknown', strength: 0 };
107
- const first = prices[0];
108
- const last = prices[prices.length - 1];
109
- const change = last - first;
110
- const range = Math.max(...prices) - Math.min(...prices);
111
- return {
112
- trend: change > 0 ? 'up' : change < 0 ? 'down' : 'flat',
113
- strength: range > 0 ? Math.abs(change) / range : 0,
114
- range,
115
- change
116
- };
117
- };
118
-
119
- const analyzeVolume = (ticks) => {
120
- if (!ticks || ticks.length === 0) return { total: 0, avg: 0, trend: 'unknown' };
121
- const volumes = ticks.map(t => t.volume || 0);
122
- const total = volumes.reduce((a, b) => a + b, 0);
123
- const avg = total / volumes.length;
124
- const mid = Math.floor(volumes.length / 2);
125
- const firstHalf = volumes.slice(0, mid).reduce((a, b) => a + b, 0);
126
- const secondHalf = volumes.slice(mid).reduce((a, b) => a + b, 0);
127
- return {
128
- total,
129
- avg,
130
- trend: secondHalf > firstHalf * 1.2 ? 'increasing' : secondHalf < firstHalf * 0.8 ? 'decreasing' : 'stable'
131
- };
132
- };
133
-
134
- const calculateVolatility = (ticks) => {
135
- if (!ticks || ticks.length < 2) return 0;
136
- const prices = ticks.map(t => t.price).filter(Boolean);
137
- if (prices.length < 2) return 0;
138
- const returns = [];
139
- for (let i = 1; i < prices.length; i++) {
140
- returns.push((prices[i] - prices[i-1]) / prices[i-1]);
141
- }
142
- const mean = returns.reduce((a, b) => a + b, 0) / returns.length;
143
- const variance = returns.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / returns.length;
144
- return Math.sqrt(variance);
145
- };
146
-
147
- module.exports = {
148
- calculateTrendStrength,
149
- calculateRecentRange,
150
- calculatePriceVelocity,
151
- getMarketSession,
152
- getMinutesSinceOpen,
153
- analyzePriceLevelInteraction,
154
- determineLevelType,
155
- analyzePriceAction,
156
- analyzeVolume,
157
- calculateVolatility
158
- };
@@ -1,484 +0,0 @@
1
- /**
2
- * AI Supervisor
3
- * Manages AI supervision of algo trading
4
- *
5
- * STRICT RULE: NO MOCK DATA, NO SIMULATION, NO ESTIMATION
6
- * All data comes from real APIs (ProjectX, Rithmic, Tradovate)
7
- */
8
-
9
- const { connections } = require('../session');
10
- const { analyzeTrading, analyzePerformance, getMarketAdvice: getMarketAdviceClient } = require('./client');
11
- const { feedTick: feedTickImpl, feedSignal: feedSignalImpl, feedTrade: feedTradeImpl,
12
- updatePosition: updatePositionImpl, updatePnL: updatePnLImpl,
13
- checkIntervention: checkInterventionImpl, getSyncStatus: getSyncStatusImpl } = require('./supervisor-sync');
14
- const { requestOptimization: requestOptimizationImpl, getMarketAdvice: getMarketAdviceImpl,
15
- applyOptimization: applyOptimizationImpl } = require('./supervisor-optimize');
16
-
17
- let aiService = null;
18
-
19
- // Lazy load to avoid circular dependency
20
- const getAIService = () => {
21
- if (!aiService) {
22
- aiService = require('./index');
23
- }
24
- return aiService;
25
- };
26
-
27
- // In-memory supervision sessions
28
- const supervisionSessions = new Map();
29
-
30
- // Consensus supervision interval
31
- let consensusInterval = null;
32
-
33
- /**
34
- * AI Supervisor Class
35
- * Uses REAL data from connected trading APIs
36
- */
37
- class AISupervisor {
38
- /**
39
- * Start supervision for an agent
40
- */
41
- static start(agentId, service, accountId) {
42
- if (supervisionSessions.has(agentId)) {
43
- return { success: false, error: 'Supervision already active' };
44
- }
45
-
46
- const agentInfo = getAIService().getAgent(agentId);
47
- if (!agentInfo) {
48
- return { success: false, error: 'Agent not found' };
49
- }
50
-
51
- if (!service || !accountId) {
52
- return { success: false, error: 'Service and accountId required' };
53
- }
54
-
55
- const session = {
56
- agentId,
57
- agent: agentInfo,
58
- service,
59
- accountId,
60
- startTime: Date.now(),
61
- lastCheck: Date.now(),
62
- lastData: null,
63
- decisions: [],
64
- metrics: {
65
- totalDecisions: 0,
66
- interventions: 0,
67
- optimizations: 0,
68
- riskWarnings: 0
69
- },
70
- interval: null
71
- };
72
-
73
- const currentSessionCount = supervisionSessions.size;
74
-
75
- if (currentSessionCount === 0) {
76
- session.interval = setInterval(() => {
77
- this.supervise(agentId);
78
- }, 10000);
79
-
80
- supervisionSessions.set(agentId, session);
81
-
82
- return {
83
- success: true,
84
- message: `AI supervision started: ${agentInfo.name}`,
85
- mode: 'single'
86
- };
87
-
88
- } else {
89
- this.switchToConsensusMode();
90
- session.interval = null;
91
- supervisionSessions.set(agentId, session);
92
-
93
- return {
94
- success: true,
95
- message: `Added ${agentInfo.name} to supervision`,
96
- mode: 'consensus',
97
- totalAgents: currentSessionCount + 1
98
- };
99
- }
100
- }
101
-
102
- /**
103
- * Switch to consensus mode when multiple agents
104
- */
105
- static switchToConsensusMode() {
106
- for (const [agentId, session] of supervisionSessions.entries()) {
107
- if (session.interval) {
108
- clearInterval(session.interval);
109
- session.interval = null;
110
- }
111
- }
112
-
113
- if (!consensusInterval) {
114
- consensusInterval = setInterval(() => {
115
- this.superviseConsensus();
116
- }, 10000);
117
- }
118
- }
119
-
120
- /**
121
- * Stop supervision for an agent
122
- */
123
- static stop(agentId) {
124
- const session = supervisionSessions.get(agentId);
125
- if (!session) {
126
- return { success: false, error: 'Session not found' };
127
- }
128
-
129
- if (session.interval) {
130
- clearInterval(session.interval);
131
- }
132
-
133
- const duration = Date.now() - session.startTime;
134
- supervisionSessions.delete(agentId);
135
-
136
- const remainingSessions = supervisionSessions.size;
137
- if (remainingSessions === 1 && consensusInterval) {
138
- clearInterval(consensusInterval);
139
- consensusInterval = null;
140
-
141
- const remainingSession = supervisionSessions.values().next().value;
142
- if (remainingSession && !remainingSession.interval) {
143
- const remainingAgentId = remainingSession.agentId;
144
- remainingSession.interval = setInterval(() => {
145
- this.supervise(remainingAgentId);
146
- }, 10000);
147
- }
148
- } else if (remainingSessions === 0 && consensusInterval) {
149
- clearInterval(consensusInterval);
150
- consensusInterval = null;
151
- }
152
-
153
- return {
154
- success: true,
155
- duration: Math.round(duration / 1000),
156
- metrics: session.metrics
157
- };
158
- }
159
-
160
- /**
161
- * Process AI decision and update session metrics
162
- */
163
- static processDecision(session, aiDecision, data, agentId = null) {
164
- const decision = {
165
- timestamp: Date.now(),
166
- action: aiDecision.action || null,
167
- confidence: aiDecision.confidence || null,
168
- reason: aiDecision.reason || null,
169
- dataSnapshot: {
170
- balance: data.account?.balance ?? null,
171
- pnl: data.account?.profitAndLoss ?? null,
172
- positions: data.positions?.length ?? 0,
173
- orders: data.orders?.length ?? 0
174
- }
175
- };
176
- if (agentId) { decision.agentId = agentId; decision.agentName = session.agent.name; }
177
- session.decisions.push(decision);
178
- session.metrics.totalDecisions++;
179
- if (aiDecision.action === 'REDUCE_SIZE' || aiDecision.action === 'PAUSE') session.metrics.interventions++;
180
- else if (aiDecision.action === 'CONTINUE') session.metrics.optimizations++;
181
- if (aiDecision.confidence !== null && aiDecision.confidence < 50) session.metrics.riskWarnings++;
182
- if (session.decisions.length > 100) session.decisions = session.decisions.slice(-100);
183
- return decision;
184
- }
185
-
186
- /** Main supervision loop - single agent */
187
- static async supervise(agentId) {
188
- const session = supervisionSessions.get(agentId);
189
- if (!session) return;
190
- try {
191
- session.lastCheck = Date.now();
192
- const data = await this.fetchRealData(session.service, session.accountId);
193
- if (!data) return;
194
- session.lastData = data;
195
- session.metrics.lastFetch = Date.now();
196
- const aiDecision = await analyzeTrading(session.agent, data);
197
- if (aiDecision) this.processDecision(session, aiDecision, data);
198
- } catch (error) { /* Silent fail */ }
199
- }
200
-
201
- /** Multi-agent consensus supervision loop */
202
- static async superviseConsensus() {
203
- const allSessions = Array.from(supervisionSessions.entries());
204
- if (allSessions.length === 0) return;
205
- try {
206
- const decisions = [];
207
- for (const [agentId, session] of allSessions) {
208
- const data = await this.fetchRealData(session.service, session.accountId);
209
- if (!data) continue;
210
- session.lastData = data;
211
- session.lastCheck = Date.now();
212
- session.metrics.lastFetch = Date.now();
213
- const aiDecision = await analyzeTrading(session.agent, data);
214
- if (aiDecision) decisions.push(this.processDecision(session, aiDecision, data, agentId));
215
- }
216
- if (decisions.length > 1) this.calculateConsensus(decisions);
217
- } catch (error) { /* Silent fail */ }
218
- }
219
-
220
- /**
221
- * Calculate consensus from multiple agent decisions
222
- */
223
- static calculateConsensus(decisions) {
224
- if (!decisions || decisions.length === 0) return null;
225
-
226
- const votes = {};
227
- let totalConfidence = 0;
228
- let validConfidenceCount = 0;
229
-
230
- for (const decision of decisions) {
231
- if (decision.action) {
232
- votes[decision.action] = (votes[decision.action] || 0) + 1;
233
- }
234
- if (decision.confidence !== null) {
235
- totalConfidence += decision.confidence;
236
- validConfidenceCount++;
237
- }
238
- }
239
-
240
- let unanimousAction = null;
241
- let isUnanimous = false;
242
-
243
- for (const [action, count] of Object.entries(votes)) {
244
- if (count === decisions.length) {
245
- unanimousAction = action;
246
- isUnanimous = true;
247
- break;
248
- }
249
- }
250
-
251
- const avgConfidence = validConfidenceCount > 0
252
- ? Math.round(totalConfidence / validConfidenceCount)
253
- : null;
254
-
255
- const consensus = {
256
- timestamp: Date.now(),
257
- action: isUnanimous ? unanimousAction : 'HOLD',
258
- confidence: isUnanimous ? avgConfidence : null,
259
- votes,
260
- agentCount: decisions.length,
261
- isUnanimous,
262
- agreement: isUnanimous ? 1.0 : 0
263
- };
264
-
265
- const firstSession = supervisionSessions.values().next().value;
266
- if (firstSession) {
267
- firstSession.lastConsensus = consensus;
268
- }
269
-
270
- return consensus;
271
- }
272
-
273
- /**
274
- * Fetch REAL data from trading API
275
- */
276
- static async fetchRealData(service, accountId) {
277
- if (!service || !accountId) return null;
278
-
279
- const data = {
280
- timestamp: Date.now(),
281
- account: null,
282
- positions: [],
283
- orders: [],
284
- trades: []
285
- };
286
-
287
- try {
288
- const accountResult = await service.getTradingAccounts();
289
- if (accountResult.success && accountResult.accounts) {
290
- data.account = accountResult.accounts.find(a =>
291
- a.accountId === accountId ||
292
- a.rithmicAccountId === accountId ||
293
- String(a.accountId) === String(accountId)
294
- );
295
- }
296
-
297
- const posResult = await service.getPositions(accountId);
298
- if (posResult.success && posResult.positions) {
299
- data.positions = posResult.positions;
300
- }
301
-
302
- const orderResult = await service.getOrders(accountId);
303
- if (orderResult.success && orderResult.orders) {
304
- data.orders = orderResult.orders;
305
- }
306
-
307
- if (typeof service.getTrades === 'function') {
308
- const tradesResult = await service.getTrades(accountId);
309
- if (tradesResult.success && tradesResult.trades) {
310
- data.trades = tradesResult.trades;
311
- }
312
- }
313
-
314
- } catch (error) {
315
- return null;
316
- }
317
-
318
- return data;
319
- }
320
-
321
- /**
322
- * Get supervision status for an agent
323
- */
324
- static getStatus(agentId) {
325
- const session = supervisionSessions.get(agentId);
326
- if (!session) {
327
- return { active: false };
328
- }
329
-
330
- const duration = Date.now() - session.startTime;
331
- return {
332
- active: true,
333
- agentId: session.agentId,
334
- agentName: session.agent.name,
335
- accountId: session.accountId,
336
- duration,
337
- lastCheck: session.lastCheck,
338
- lastData: session.lastData,
339
- metrics: session.metrics,
340
- decisionsCount: session.decisions.length
341
- };
342
- }
343
-
344
- /**
345
- * Get all active supervision sessions
346
- */
347
- static getAllStatus() {
348
- const sessions = [];
349
- const isConsensusMode = supervisionSessions.size > 1 && consensusInterval !== null;
350
-
351
- for (const [agentId, session] of supervisionSessions.entries()) {
352
- sessions.push({
353
- active: true,
354
- agentId,
355
- agentName: session.agent.name,
356
- accountId: session.accountId,
357
- duration: Date.now() - session.startTime,
358
- lastCheck: session.lastCheck,
359
- metrics: session.metrics,
360
- mode: isConsensusMode ? 'consensus' : 'single'
361
- });
362
- }
363
-
364
- return sessions;
365
- }
366
-
367
- /**
368
- * Get aggregated data from all supervised accounts
369
- */
370
- static getAggregatedData() {
371
- const result = {
372
- totalAccounts: 0,
373
- totalBalance: 0,
374
- totalPnL: 0,
375
- totalPositions: 0,
376
- totalOrders: 0,
377
- totalTrades: 0,
378
- accounts: []
379
- };
380
-
381
- for (const [agentId, session] of supervisionSessions.entries()) {
382
- if (session.lastData) {
383
- const data = session.lastData;
384
-
385
- if (data.account) {
386
- result.totalAccounts++;
387
- result.totalBalance += data.account.balance || 0;
388
- result.totalPnL += data.account.profitAndLoss || 0;
389
- result.accounts.push({
390
- accountId: data.account.accountId,
391
- accountName: data.account.accountName,
392
- balance: data.account.balance,
393
- pnl: data.account.profitAndLoss,
394
- platform: data.account.platform
395
- });
396
- }
397
-
398
- result.totalPositions += data.positions?.length || 0;
399
- result.totalOrders += data.orders?.length || 0;
400
- result.totalTrades += data.trades?.length || 0;
401
- }
402
- }
403
-
404
- return result;
405
- }
406
-
407
- /**
408
- * Get latest AI decision for an agent
409
- */
410
- static getLatestDecision(agentId) {
411
- const session = supervisionSessions.get(agentId);
412
- if (!session || session.decisions.length === 0) {
413
- return null;
414
- }
415
- return session.decisions[session.decisions.length - 1];
416
- }
417
-
418
- /**
419
- * Get all decisions for an agent
420
- */
421
- static getDecisions(agentId, limit = 10) {
422
- const session = supervisionSessions.get(agentId);
423
- if (!session) {
424
- return [];
425
- }
426
- return session.decisions.slice(-limit);
427
- }
428
-
429
- /**
430
- * Get latest consensus (multi-agent mode only)
431
- */
432
- static getConsensus() {
433
- if (supervisionSessions.size <= 1) {
434
- return null;
435
- }
436
- const firstSession = supervisionSessions.values().next().value;
437
- return firstSession?.lastConsensus || null;
438
- }
439
-
440
- /**
441
- * Stop all supervision sessions
442
- */
443
- static stopAll() {
444
- const results = [];
445
- const agentIds = Array.from(supervisionSessions.keys());
446
-
447
- for (const agentId of agentIds) {
448
- const result = this.stop(agentId);
449
- results.push({ agentId, ...result });
450
- }
451
-
452
- return results;
453
- }
454
-
455
- /**
456
- * Check if any supervision is active
457
- */
458
- static isActive() {
459
- return supervisionSessions.size > 0;
460
- }
461
-
462
- /**
463
- * Get session count
464
- */
465
- static getSessionCount() {
466
- return supervisionSessions.size;
467
- }
468
-
469
- // Strategy sync methods (delegated to supervisor-sync.js)
470
- static feedTick(tick) { feedTickImpl(supervisionSessions, tick); }
471
- static feedSignal(signal) { feedSignalImpl(supervisionSessions, signal); }
472
- static feedTrade(trade) { feedTradeImpl(supervisionSessions, trade); }
473
- static updatePosition(position) { updatePositionImpl(supervisionSessions, position); }
474
- static updatePnL(pnl, balance) { updatePnLImpl(supervisionSessions, pnl, balance); }
475
- static checkIntervention() { return checkInterventionImpl(supervisionSessions, () => this.getConsensus()); }
476
- static getSyncStatus() { return getSyncStatusImpl(supervisionSessions); }
477
-
478
- // Optimization methods (delegated to supervisor-optimize.js)
479
- static async requestOptimization(performanceData) { return requestOptimizationImpl(supervisionSessions, performanceData); }
480
- static async getMarketAdvice(marketData) { return getMarketAdviceImpl(supervisionSessions, marketData); }
481
- static applyOptimization(strategy, optimization) { return applyOptimizationImpl(strategy, optimization); }
482
- }
483
-
484
- module.exports = AISupervisor;