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,195 +0,0 @@
1
- /**
2
- * Supervisor Data Management
3
- * Handles persistence and data operations for AI learning
4
- */
5
-
6
- 'use strict';
7
-
8
- const fs = require('fs');
9
- const path = require('path');
10
- const os = require('os');
11
-
12
- const DATA_DIR = path.join(os.homedir(), '.hqx');
13
- const LEARNING_FILE = path.join(DATA_DIR, 'ai-learning.json');
14
-
15
- const loadLearningData = () => {
16
- try {
17
- if (!fs.existsSync(DATA_DIR)) {
18
- fs.mkdirSync(DATA_DIR, { recursive: true });
19
- }
20
- if (fs.existsSync(LEARNING_FILE)) {
21
- const data = JSON.parse(fs.readFileSync(LEARNING_FILE, 'utf8'));
22
- const oneMonthAgo = Date.now() - (31 * 24 * 60 * 60 * 1000);
23
- const sessions = (data.sessions || []).filter(s =>
24
- new Date(s.date).getTime() > oneMonthAgo
25
- );
26
- return {
27
- winningPatterns: data.winningPatterns || [],
28
- losingPatterns: data.losingPatterns || [],
29
- optimizations: data.optimizations || [],
30
- symbols: data.symbols || {},
31
- sessions,
32
- hourlyStats: data.hourlyStats || {},
33
- dayOfWeekStats: data.dayOfWeekStats || {},
34
- strategyProfile: data.strategyProfile || {
35
- bestHours: [], worstHours: [], avgWinStreak: 0, avgLossStreak: 0, preferredConditions: null
36
- },
37
- totalSessions: data.totalSessions || 0,
38
- totalTrades: data.totalTrades || 0,
39
- totalWins: data.totalWins || 0,
40
- totalLosses: data.totalLosses || 0,
41
- lifetimePnL: data.lifetimePnL || 0,
42
- lastUpdated: data.lastUpdated || null,
43
- firstSession: data.firstSession || null
44
- };
45
- }
46
- } catch (e) { /* Silent fail */ }
47
- return {
48
- winningPatterns: [], losingPatterns: [], optimizations: [], symbols: {}, sessions: [],
49
- hourlyStats: {}, dayOfWeekStats: {},
50
- strategyProfile: { bestHours: [], worstHours: [], avgWinStreak: 0, avgLossStreak: 0, preferredConditions: null },
51
- totalSessions: 0, totalTrades: 0, totalWins: 0, totalLosses: 0, lifetimePnL: 0,
52
- lastUpdated: null, firstSession: null
53
- };
54
- };
55
-
56
- const getSymbolData = (symbolName) => {
57
- const data = loadLearningData();
58
- if (!data.symbols[symbolName]) {
59
- return {
60
- name: symbolName, levels: { support: [], resistance: [] },
61
- patterns: { winning: [], losing: [] }, stats: { trades: 0, wins: 0, avgWin: 0, avgLoss: 0 }
62
- };
63
- }
64
- return data.symbols[symbolName];
65
- };
66
-
67
- const recordPriceLevel = (symbolName, price, type, outcome) => {
68
- const data = loadLearningData();
69
- if (!data.symbols[symbolName]) {
70
- data.symbols[symbolName] = {
71
- name: symbolName, levels: { support: [], resistance: [] },
72
- patterns: { winning: [], losing: [] }, stats: { trades: 0, wins: 0, avgWin: 0, avgLoss: 0 }
73
- };
74
- }
75
- const symbol = data.symbols[symbolName];
76
- const levelKey = type === 'support' ? 'support' : 'resistance';
77
- const existingLevel = symbol.levels[levelKey].find(l => Math.abs(l.price - price) <= 0.5);
78
- if (existingLevel) {
79
- existingLevel.touches++;
80
- existingLevel.lastTouched = Date.now();
81
- if (outcome === 'held') existingLevel.held++;
82
- else existingLevel.broken++;
83
- } else {
84
- symbol.levels[levelKey].push({
85
- price, touches: 1, held: outcome === 'held' ? 1 : 0,
86
- broken: outcome === 'broken' ? 1 : 0, firstSeen: Date.now(), lastTouched: Date.now()
87
- });
88
- }
89
- symbol.levels[levelKey].sort((a, b) => b.touches - a.touches);
90
- if (symbol.levels[levelKey].length > 20) {
91
- symbol.levels[levelKey] = symbol.levels[levelKey].slice(0, 20);
92
- }
93
- saveLearningData(data);
94
- };
95
-
96
- const analyzeNearbyLevels = (symbolName, currentPrice) => {
97
- const symbolData = getSymbolData(symbolName);
98
- const nearby = { support: [], resistance: [] };
99
- const range = 10;
100
- symbolData.levels.support.forEach(level => {
101
- if (Math.abs(level.price - currentPrice) <= range) {
102
- nearby.support.push({ ...level, distance: currentPrice - level.price });
103
- }
104
- });
105
- symbolData.levels.resistance.forEach(level => {
106
- if (Math.abs(level.price - currentPrice) <= range) {
107
- nearby.resistance.push({ ...level, distance: level.price - currentPrice });
108
- }
109
- });
110
- nearby.support.sort((a, b) => a.distance - b.distance);
111
- nearby.resistance.sort((a, b) => a.distance - b.distance);
112
- return nearby;
113
- };
114
-
115
- const saveLearningData = (data) => {
116
- try {
117
- if (!fs.existsSync(DATA_DIR)) {
118
- fs.mkdirSync(DATA_DIR, { recursive: true });
119
- }
120
- data.lastUpdated = new Date().toISOString();
121
- fs.writeFileSync(LEARNING_FILE, JSON.stringify(data, null, 2));
122
- return true;
123
- } catch (e) {
124
- return false;
125
- }
126
- };
127
-
128
- const buildStrategyProfile = (hourlyStats, dayOfWeekStats, sessions) => {
129
- const profile = { bestHours: [], worstHours: [], avgWinStreak: 0, avgLossStreak: 0, preferredConditions: null };
130
- const hourlyArray = Object.entries(hourlyStats)
131
- .filter(([_, stats]) => stats.trades >= 5)
132
- .map(([hour, stats]) => ({ hour: parseInt(hour), winRate: stats.wins / stats.trades, trades: stats.trades, pnl: stats.pnl }));
133
- hourlyArray.sort((a, b) => b.winRate - a.winRate);
134
- profile.bestHours = hourlyArray.slice(0, 3).map(h => ({ hour: h.hour, winRate: Math.round(h.winRate * 100) }));
135
- profile.worstHours = hourlyArray.slice(-3).reverse().map(h => ({ hour: h.hour, winRate: Math.round(h.winRate * 100) }));
136
- if (sessions.length >= 5) {
137
- const winStreaks = sessions.map(s => s.maxWinStreak || 0).filter(Boolean);
138
- const lossStreaks = sessions.map(s => s.maxLossStreak || 0).filter(Boolean);
139
- profile.avgWinStreak = winStreaks.length > 0 ? winStreaks.reduce((a, b) => a + b, 0) / winStreaks.length : 0;
140
- profile.avgLossStreak = lossStreaks.length > 0 ? lossStreaks.reduce((a, b) => a + b, 0) / lossStreaks.length : 0;
141
- }
142
- return profile;
143
- };
144
-
145
- const mergePatterns = (existing, current, maxCount) => {
146
- const merged = [...existing];
147
- current.forEach(pattern => {
148
- const similar = merged.find(p => p.timeContext?.hour === pattern.timeContext?.hour && p.direction === pattern.direction);
149
- if (!similar) merged.push(pattern);
150
- });
151
- merged.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
152
- return merged.slice(0, maxCount);
153
- };
154
-
155
- const mergeLevels = (existing, current, maxCount) => {
156
- const merged = [...existing];
157
- current.forEach(level => {
158
- const similar = merged.find(l => Math.abs(l.price - level.price) <= 0.5);
159
- if (similar) {
160
- similar.touches += level.touches || 1;
161
- similar.held += level.held || 0;
162
- similar.broken += level.broken || 0;
163
- similar.lastTouched = Math.max(similar.lastTouched || 0, level.lastTouched || Date.now());
164
- } else {
165
- merged.push(level);
166
- }
167
- });
168
- merged.sort((a, b) => b.touches - a.touches);
169
- return merged.slice(0, maxCount);
170
- };
171
-
172
- const clearLearningData = () => {
173
- try {
174
- if (fs.existsSync(LEARNING_FILE)) {
175
- fs.unlinkSync(LEARNING_FILE);
176
- }
177
- return true;
178
- } catch (e) {
179
- return false;
180
- }
181
- };
182
-
183
- module.exports = {
184
- DATA_DIR,
185
- LEARNING_FILE,
186
- loadLearningData,
187
- getSymbolData,
188
- recordPriceLevel,
189
- analyzeNearbyLevels,
190
- saveLearningData,
191
- buildStrategyProfile,
192
- mergePatterns,
193
- mergeLevels,
194
- clearLearningData
195
- };
@@ -1,215 +0,0 @@
1
- /**
2
- * @fileoverview AI Supervisor - Optimization & Market Advice
3
- *
4
- * Methods for AI-driven strategy optimization and market analysis
5
- * In CONSENSUS mode, only unanimous suggestions are applied
6
- */
7
-
8
- const { analyzePerformance, getMarketAdvice: getMarketAdviceFromClient } = require('./client');
9
-
10
- /**
11
- * Request strategy optimization from all agents
12
- * @param {Map} supervisionSessions - Sessions map
13
- * @param {Object} performanceData - Strategy performance data
14
- * @returns {Promise<Object|null>} Optimization suggestions
15
- */
16
- const requestOptimization = async (supervisionSessions, performanceData) => {
17
- if (supervisionSessions.size === 0) return null;
18
-
19
- const allSessions = Array.from(supervisionSessions.values());
20
- const suggestions = [];
21
-
22
- // Get optimization suggestions from each agent
23
- for (const session of allSessions) {
24
- try {
25
- const suggestion = await analyzePerformance(session.agent, performanceData);
26
- if (suggestion) {
27
- suggestions.push({
28
- agentId: session.agentId,
29
- agentName: session.agent.name,
30
- ...suggestion
31
- });
32
- }
33
- } catch (e) {
34
- // Silent fail for individual agent
35
- }
36
- }
37
-
38
- if (suggestions.length === 0) return null;
39
-
40
- // If single agent, return its suggestion
41
- if (suggestions.length === 1) {
42
- return {
43
- mode: 'INDIVIDUAL',
44
- ...suggestions[0]
45
- };
46
- }
47
-
48
- // CONSENSUS MODE: Find common optimizations
49
- const consensusOptimizations = [];
50
- const allOptimizations = suggestions.flatMap(s => s.optimizations || []);
51
-
52
- // Group by parameter name
53
- const paramGroups = {};
54
- for (const opt of allOptimizations) {
55
- if (!opt.param) continue;
56
- if (!paramGroups[opt.param]) {
57
- paramGroups[opt.param] = [];
58
- }
59
- paramGroups[opt.param].push(opt);
60
- }
61
-
62
- // Find unanimous suggestions (all agents agree on direction)
63
- for (const [param, opts] of Object.entries(paramGroups)) {
64
- if (opts.length === suggestions.length) {
65
- // All agents suggested this param - check if they agree on direction
66
- const directions = opts.map(o => {
67
- const current = parseFloat(o.current) || 0;
68
- const suggested = parseFloat(o.suggested) || 0;
69
- return suggested > current ? 'increase' : suggested < current ? 'decrease' : 'same';
70
- });
71
-
72
- const allSame = directions.every(d => d === directions[0]);
73
- if (allSame && directions[0] !== 'same') {
74
- // Unanimous - use average of suggested values
75
- const avgSuggested = opts.reduce((sum, o) => sum + (parseFloat(o.suggested) || 0), 0) / opts.length;
76
- consensusOptimizations.push({
77
- param,
78
- current: opts[0].current,
79
- suggested: avgSuggested.toFixed(2),
80
- reason: `Unanimous (${suggestions.length} agents agree)`,
81
- direction: directions[0]
82
- });
83
- }
84
- }
85
- }
86
-
87
- // Calculate average confidence
88
- const avgConfidence = Math.round(
89
- suggestions.reduce((sum, s) => sum + (s.confidence || 0), 0) / suggestions.length
90
- );
91
-
92
- // Determine consensus market condition
93
- const conditions = suggestions.map(s => s.marketCondition).filter(Boolean);
94
- const conditionCounts = {};
95
- for (const c of conditions) {
96
- conditionCounts[c] = (conditionCounts[c] || 0) + 1;
97
- }
98
- const consensusCondition = Object.entries(conditionCounts)
99
- .sort((a, b) => b[1] - a[1])[0]?.[0] || 'unknown';
100
-
101
- return {
102
- mode: 'CONSENSUS',
103
- agentCount: suggestions.length,
104
- isUnanimous: consensusOptimizations.length > 0,
105
- optimizations: consensusOptimizations,
106
- marketCondition: consensusCondition,
107
- confidence: avgConfidence,
108
- individualSuggestions: suggestions
109
- };
110
- };
111
-
112
- /**
113
- * Get real-time market advice from all agents
114
- * @param {Map} supervisionSessions - Sessions map
115
- * @param {Object} marketData - Current market data
116
- * @returns {Promise<Object|null>} Market advice (consensus)
117
- */
118
- const getMarketAdvice = async (supervisionSessions, marketData) => {
119
- if (supervisionSessions.size === 0) return null;
120
-
121
- const allSessions = Array.from(supervisionSessions.values());
122
- const advices = [];
123
-
124
- // Get advice from each agent
125
- for (const session of allSessions) {
126
- try {
127
- const advice = await getMarketAdviceFromClient(session.agent, marketData);
128
- if (advice) {
129
- advices.push({
130
- agentId: session.agentId,
131
- agentName: session.agent.name,
132
- ...advice
133
- });
134
- }
135
- } catch (e) {
136
- // Silent fail
137
- }
138
- }
139
-
140
- if (advices.length === 0) return null;
141
-
142
- // Single agent
143
- if (advices.length === 1) {
144
- return {
145
- mode: 'INDIVIDUAL',
146
- ...advices[0]
147
- };
148
- }
149
-
150
- // CONSENSUS: All agents must agree on action
151
- const actions = advices.map(a => a.action);
152
- const allSameAction = actions.every(a => a === actions[0]);
153
-
154
- if (allSameAction) {
155
- // Unanimous action - average the size multiplier
156
- const avgMultiplier = advices.reduce((sum, a) => sum + (a.sizeMultiplier || 1), 0) / advices.length;
157
- const avgConfidence = Math.round(advices.reduce((sum, a) => sum + (a.confidence || 0), 0) / advices.length);
158
-
159
- return {
160
- mode: 'CONSENSUS',
161
- isUnanimous: true,
162
- action: actions[0],
163
- sizeMultiplier: Math.round(avgMultiplier * 100) / 100,
164
- confidence: avgConfidence,
165
- reason: `${advices.length} agents unanimous`,
166
- agentCount: advices.length
167
- };
168
- } else {
169
- // Agents disagree - be conservative
170
- return {
171
- mode: 'CONSENSUS',
172
- isUnanimous: false,
173
- action: 'CAUTIOUS',
174
- sizeMultiplier: 0.5,
175
- confidence: 0,
176
- reason: 'Agents disagree - reducing exposure',
177
- agentCount: advices.length,
178
- votes: actions.reduce((acc, a) => { acc[a] = (acc[a] || 0) + 1; return acc; }, {})
179
- };
180
- }
181
- };
182
-
183
- /**
184
- * Apply optimization to strategy
185
- * @param {Object} strategy - Strategy instance
186
- * @param {Object} optimization - Optimization to apply
187
- * @returns {boolean} Success
188
- */
189
- const applyOptimization = (strategy, optimization) => {
190
- if (!strategy || !optimization) return false;
191
-
192
- try {
193
- // Check if strategy has optimization method
194
- if (typeof strategy.applyOptimization === 'function') {
195
- strategy.applyOptimization(optimization);
196
- return true;
197
- }
198
-
199
- // Fallback: try to set individual parameters
200
- if (typeof strategy.setParameter === 'function' && optimization.param) {
201
- strategy.setParameter(optimization.param, optimization.suggested);
202
- return true;
203
- }
204
-
205
- return false;
206
- } catch (e) {
207
- return false;
208
- }
209
- };
210
-
211
- module.exports = {
212
- requestOptimization,
213
- getMarketAdvice,
214
- applyOptimization,
215
- };
@@ -1,178 +0,0 @@
1
- /**
2
- * @fileoverview AI Supervisor - Strategy Sync
3
- *
4
- * Methods to sync AI supervision with trading strategy in real-time
5
- * Agents receive the same data as the strategy
6
- */
7
-
8
- /**
9
- * Feed market tick to all sessions
10
- * @param {Map} supervisionSessions - Sessions map
11
- * @param {Object} tick - Market tick { price, bid, ask, volume, timestamp }
12
- */
13
- const feedTick = (supervisionSessions, tick) => {
14
- if (supervisionSessions.size === 0) return;
15
-
16
- for (const [agentId, session] of supervisionSessions.entries()) {
17
- if (!session.marketData) {
18
- session.marketData = { ticks: [], lastTick: null };
19
- }
20
- session.marketData.lastTick = tick;
21
- session.marketData.ticks.push(tick);
22
-
23
- // Keep only last 1000 ticks to prevent memory bloat
24
- if (session.marketData.ticks.length > 1000) {
25
- session.marketData.ticks = session.marketData.ticks.slice(-1000);
26
- }
27
- }
28
- };
29
-
30
- /**
31
- * Feed strategy signal to all sessions
32
- * @param {Map} supervisionSessions - Sessions map
33
- * @param {Object} signal - Strategy signal
34
- */
35
- const feedSignal = (supervisionSessions, signal) => {
36
- if (supervisionSessions.size === 0) return;
37
-
38
- const signalData = {
39
- timestamp: Date.now(),
40
- direction: signal.direction,
41
- entry: signal.entry,
42
- stopLoss: signal.stopLoss,
43
- takeProfit: signal.takeProfit,
44
- confidence: signal.confidence
45
- };
46
-
47
- for (const [agentId, session] of supervisionSessions.entries()) {
48
- if (!session.signals) {
49
- session.signals = [];
50
- }
51
- session.signals.push(signalData);
52
-
53
- // Keep only last 100 signals
54
- if (session.signals.length > 100) {
55
- session.signals = session.signals.slice(-100);
56
- }
57
- }
58
- };
59
-
60
- /**
61
- * Feed trade execution to all sessions
62
- * @param {Map} supervisionSessions - Sessions map
63
- * @param {Object} trade - Trade data
64
- */
65
- const feedTrade = (supervisionSessions, trade) => {
66
- if (supervisionSessions.size === 0) return;
67
-
68
- const tradeData = {
69
- timestamp: Date.now(),
70
- side: trade.side,
71
- qty: trade.qty,
72
- price: trade.price,
73
- pnl: trade.pnl,
74
- symbol: trade.symbol
75
- };
76
-
77
- for (const [agentId, session] of supervisionSessions.entries()) {
78
- if (!session.trades) {
79
- session.trades = [];
80
- }
81
- session.trades.push(tradeData);
82
- }
83
- };
84
-
85
- /**
86
- * Update current position for all sessions
87
- * @param {Map} supervisionSessions - Sessions map
88
- * @param {Object} position - Position data
89
- */
90
- const updatePosition = (supervisionSessions, position) => {
91
- if (supervisionSessions.size === 0) return;
92
-
93
- for (const [agentId, session] of supervisionSessions.entries()) {
94
- session.currentPosition = {
95
- timestamp: Date.now(),
96
- qty: position.qty,
97
- side: position.side,
98
- entryPrice: position.entryPrice,
99
- pnl: position.pnl
100
- };
101
- }
102
- };
103
-
104
- /**
105
- * Update P&L for all sessions
106
- * @param {Map} supervisionSessions - Sessions map
107
- * @param {number} pnl - Current session P&L
108
- * @param {number} balance - Account balance
109
- */
110
- const updatePnL = (supervisionSessions, pnl, balance) => {
111
- if (supervisionSessions.size === 0) return;
112
-
113
- for (const [agentId, session] of supervisionSessions.entries()) {
114
- session.currentPnL = pnl;
115
- session.currentBalance = balance;
116
- }
117
- };
118
-
119
- /**
120
- * Check if agents recommend intervention
121
- * @param {Map} supervisionSessions - Sessions map
122
- * @param {Function} getConsensus - Function to get consensus
123
- * @returns {Object} Intervention check result
124
- */
125
- const checkIntervention = (supervisionSessions, getConsensus) => {
126
- if (supervisionSessions.size === 0) {
127
- return { shouldContinue: true, action: 'CONTINUE', reason: 'No AI supervision active' };
128
- }
129
-
130
- const consensus = getConsensus();
131
-
132
- if (consensus && consensus.isUnanimous) {
133
- if (consensus.action === 'PAUSE' || consensus.action === 'STOP') {
134
- return { shouldContinue: false, action: consensus.action, reason: 'AI agents recommend pause' };
135
- }
136
- if (consensus.action === 'REDUCE_SIZE') {
137
- return { shouldContinue: true, action: 'REDUCE_SIZE', reason: 'AI agents recommend reducing size' };
138
- }
139
- } else if (consensus && !consensus.isUnanimous) {
140
- return { shouldContinue: false, action: 'HOLD', reason: 'AI agents disagree - waiting for consensus' };
141
- }
142
-
143
- return { shouldContinue: true, action: 'CONTINUE', reason: 'AI supervision active' };
144
- };
145
-
146
- /**
147
- * Get real-time sync status
148
- * @param {Map} supervisionSessions - Sessions map
149
- * @returns {Object} Sync status
150
- */
151
- const getSyncStatus = (supervisionSessions) => {
152
- if (supervisionSessions.size === 0) {
153
- return { synced: false, agents: 0 };
154
- }
155
-
156
- const firstSession = supervisionSessions.values().next().value;
157
-
158
- return {
159
- synced: true,
160
- agents: supervisionSessions.size,
161
- lastTick: firstSession?.marketData?.lastTick?.timestamp || null,
162
- tickCount: firstSession?.marketData?.ticks?.length || 0,
163
- signalCount: firstSession?.signals?.length || 0,
164
- tradeCount: firstSession?.trades?.length || 0,
165
- currentPnL: firstSession?.currentPnL || 0,
166
- currentPosition: firstSession?.currentPosition || null
167
- };
168
- };
169
-
170
- module.exports = {
171
- feedTick,
172
- feedSignal,
173
- feedTrade,
174
- updatePosition,
175
- updatePnL,
176
- checkIntervention,
177
- getSyncStatus,
178
- };