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
@@ -0,0 +1,427 @@
1
+ /**
2
+ * =============================================================================
3
+ * HQX Algo Trading System - Logger (HQX CLI)
4
+ * =============================================================================
5
+ * Intelligent logging that only logs on STATE CHANGES
6
+ * No spam, no repetitive messages - ultra fluid
7
+ *
8
+ * Philosophy:
9
+ * - Only log when something CHANGES
10
+ * - Track state internally
11
+ * - Aggregate similar events
12
+ * - Show clear progression of algo activity
13
+ *
14
+ * COPIED FROM hqx_tg for consistency across platforms
15
+ */
16
+
17
+ const EventEmitter = require('events');
18
+
19
+ // =============================================================================
20
+ // STATE TRACKING
21
+ // =============================================================================
22
+
23
+ const defaultState = {
24
+ // Algo status
25
+ status: 'STOPPED', // 'STARTING' | 'SCANNING' | 'APPROACHING' | 'AT_ZONE' | 'TRADING' | 'IN_POSITION' | 'STOPPING' | 'STOPPED'
26
+
27
+ // Market direction
28
+ direction: 'NEUTRAL', // 'LONG' | 'SHORT' | 'NEUTRAL'
29
+
30
+ // Pressure category
31
+ pressure: 'NEUTRAL', // 'STRONG_BUY' | 'BUY' | 'NEUTRAL' | 'SELL' | 'STRONG_SELL'
32
+
33
+ // Zone info
34
+ nearZone: null, // e.g., "POC", "VAH", "VAL"
35
+ zoneDistance: 999, // ticks from zone
36
+
37
+ // Price tracking (rounded)
38
+ lastPriceLevel: 0,
39
+
40
+ // Market regime
41
+ regime: 'RANGING', // 'TRENDING' | 'RANGING' | 'VOLATILE' | 'QUIET'
42
+
43
+ // Session
44
+ session: '',
45
+
46
+ // Spread status
47
+ spreadOk: true,
48
+ };
49
+
50
+ // =============================================================================
51
+ // SMART LOGGER CLASS
52
+ // =============================================================================
53
+
54
+ class SmartLogger extends EventEmitter {
55
+ constructor() {
56
+ super();
57
+ this.state = { ...defaultState };
58
+ this.lastLogTime = new Map();
59
+ this.MIN_LOG_INTERVAL = 3000; // Min 3s between same log type
60
+ }
61
+
62
+ /**
63
+ * Reset state (when algo starts/stops)
64
+ */
65
+ reset() {
66
+ this.state = { ...defaultState };
67
+ this.lastLogTime.clear();
68
+ }
69
+
70
+ /**
71
+ * Core log function - emits log events
72
+ */
73
+ log(type, message, details) {
74
+ const logData = {
75
+ type,
76
+ message,
77
+ details,
78
+ timestamp: Date.now(),
79
+ };
80
+
81
+ this.emit('log', logData);
82
+
83
+ // Also print to console for CLI
84
+ this.printToConsole(logData);
85
+ }
86
+
87
+ /**
88
+ * Print formatted log to console
89
+ */
90
+ printToConsole(logData) {
91
+ const { type, message, details, timestamp } = logData;
92
+ const time = new Date(timestamp).toLocaleTimeString();
93
+
94
+ // Color codes for terminal
95
+ const colors = {
96
+ info: '\x1b[36m', // Cyan
97
+ signal: '\x1b[33m', // Yellow
98
+ trade: '\x1b[32m', // Green
99
+ warning: '\x1b[33m', // Yellow
100
+ error: '\x1b[31m', // Red
101
+ analysis: '\x1b[35m', // Magenta
102
+ reset: '\x1b[0m',
103
+ };
104
+
105
+ const color = colors[type] || colors.info;
106
+ const icon = this.getIcon(type);
107
+
108
+ let output = `${color}[${time}] ${icon} ${message}${colors.reset}`;
109
+ if (details) {
110
+ output += ` | ${details}`;
111
+ }
112
+
113
+ console.log(output);
114
+ }
115
+
116
+ getIcon(type) {
117
+ switch (type) {
118
+ case 'info': return 'ℹ️ ';
119
+ case 'signal': return '🎯';
120
+ case 'trade': return '💰';
121
+ case 'warning': return '⚠️ ';
122
+ case 'error': return '❌';
123
+ case 'analysis': return '📊';
124
+ default: return '•';
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Check if we should throttle this log
130
+ */
131
+ shouldThrottle(key) {
132
+ const now = Date.now();
133
+ const last = this.lastLogTime.get(key) || 0;
134
+ if (now - last < this.MIN_LOG_INTERVAL) {
135
+ return true;
136
+ }
137
+ this.lastLogTime.set(key, now);
138
+ return false;
139
+ }
140
+
141
+ // ===========================================================================
142
+ // STATUS CHANGES (always log)
143
+ // ===========================================================================
144
+
145
+ algoStarting(platform, symbol) {
146
+ this.state.status = 'STARTING';
147
+ this.log('info', 'ALGO STARTING...', `${platform} | ${symbol}`);
148
+ }
149
+
150
+ algoRunning() {
151
+ if (this.state.status !== 'SCANNING') {
152
+ this.state.status = 'SCANNING';
153
+ this.log('info', 'ALGO RUNNING', 'Scanning for alpha...');
154
+ }
155
+ }
156
+
157
+ algoStopping() {
158
+ if (this.state.status !== 'STOPPING') {
159
+ this.state.status = 'STOPPING';
160
+ this.log('warning', 'STOPPING ALGO...', 'Closing positions...');
161
+ }
162
+ }
163
+
164
+ algoStopped() {
165
+ this.state.status = 'STOPPED';
166
+ this.log('info', 'ALGO STOPPED', 'All positions flat');
167
+ this.reset();
168
+ }
169
+
170
+ // ===========================================================================
171
+ // MARKET SESSION (log on change)
172
+ // ===========================================================================
173
+
174
+ sessionChange(session, etTime) {
175
+ if (this.state.session !== session) {
176
+ this.state.session = session;
177
+ this.log('info', `MARKET OPEN`, `${session} SESSION | ${etTime} ET`);
178
+ }
179
+ }
180
+
181
+ marketClosed() {
182
+ if (this.state.session !== 'CLOSED') {
183
+ this.state.session = 'CLOSED';
184
+ this.log('warning', 'MARKET CLOSED', 'Trading paused');
185
+ }
186
+ }
187
+
188
+ // ===========================================================================
189
+ // DIRECTION & PRESSURE (log on significant change)
190
+ // ===========================================================================
191
+
192
+ updateMarketContext(direction, buyPressure, delta, bid, ask) {
193
+ // Determine pressure category
194
+ let newPressure;
195
+ if (buyPressure >= 70) newPressure = 'STRONG_BUY';
196
+ else if (buyPressure >= 55) newPressure = 'BUY';
197
+ else if (buyPressure <= 30) newPressure = 'STRONG_SELL';
198
+ else if (buyPressure <= 45) newPressure = 'SELL';
199
+ else newPressure = 'NEUTRAL';
200
+
201
+ // Only log if direction OR pressure category changed
202
+ const dirChanged = this.state.direction !== direction;
203
+ const pressureChanged = this.state.pressure !== newPressure;
204
+
205
+ if (dirChanged || pressureChanged) {
206
+ this.state.direction = direction;
207
+ this.state.pressure = newPressure;
208
+
209
+ const arrow = direction === 'LONG' ? '▲' : direction === 'SHORT' ? '▼' : '●';
210
+ const deltaStr = delta >= 0 ? `+${delta}` : `${delta}`;
211
+ const pressureIcon = this.getPressureIcon(newPressure);
212
+
213
+ this.log('analysis',
214
+ `${arrow} ${direction} ${pressureIcon}`,
215
+ `delta: ${deltaStr} | buy: ${buyPressure.toFixed(0)}% | bid: ${bid.toFixed(2)}`
216
+ );
217
+ }
218
+ }
219
+
220
+ getPressureIcon(pressure) {
221
+ switch (pressure) {
222
+ case 'STRONG_BUY': return '🟢🟢';
223
+ case 'BUY': return '🟢';
224
+ case 'STRONG_SELL': return '🔴🔴';
225
+ case 'SELL': return '🔴';
226
+ default: return '⚪';
227
+ }
228
+ }
229
+
230
+ // ===========================================================================
231
+ // ZONE PROXIMITY (log on state change)
232
+ // ===========================================================================
233
+
234
+ approachingZone(zoneType, distance, entryDistance, price) {
235
+ const wasApproaching = this.state.status === 'APPROACHING';
236
+ const sameZone = this.state.nearZone === zoneType;
237
+
238
+ if (!wasApproaching || !sameZone) {
239
+ this.state.status = 'APPROACHING';
240
+ this.state.nearZone = zoneType;
241
+ this.state.zoneDistance = distance;
242
+ this.log('analysis',
243
+ `APPROACHING ${zoneType}`,
244
+ `${distance}/${entryDistance} ticks to ${price.toFixed(2)}`
245
+ );
246
+ }
247
+ this.state.zoneDistance = distance;
248
+ }
249
+
250
+ enteredZone(zoneType, price) {
251
+ if (this.state.status !== 'AT_ZONE' || this.state.nearZone !== zoneType) {
252
+ this.state.status = 'AT_ZONE';
253
+ this.state.nearZone = zoneType;
254
+ this.log('signal', `AT ${zoneType} ZONE`, `@ ${price.toFixed(2)} - checking confirmations...`);
255
+ }
256
+ }
257
+
258
+ leftZone() {
259
+ if (this.state.nearZone) {
260
+ const oldZone = this.state.nearZone;
261
+ this.state.nearZone = null;
262
+ this.state.status = 'SCANNING';
263
+ this.log('info', `LEFT ${oldZone} ZONE`, 'Back to scanning...');
264
+ }
265
+ }
266
+
267
+ noZonesNearby() {
268
+ if (this.state.nearZone) {
269
+ this.state.nearZone = null;
270
+ this.state.status = 'SCANNING';
271
+ }
272
+ }
273
+
274
+ // ===========================================================================
275
+ // ZONE REJECTION REASONS (log with throttle)
276
+ // ===========================================================================
277
+
278
+ zoneNoDirection(zoneType) {
279
+ if (!this.shouldThrottle('nodir')) {
280
+ this.log('analysis', `${zoneType} - WAITING`, 'No clear direction yet');
281
+ }
282
+ }
283
+
284
+ zoneMissingConfirmations(zoneType, have, need, confirmations) {
285
+ if (!this.shouldThrottle('confirmations')) {
286
+ const confStr = confirmations.length > 0 ? confirmations.join(', ') : 'none';
287
+ this.log('analysis', `${zoneType} - ${have}/${need} CONF`, confStr);
288
+ }
289
+ }
290
+
291
+ zoneLowConfidence(zoneType, confidence, required) {
292
+ if (!this.shouldThrottle('confidence')) {
293
+ this.log('analysis', `${zoneType} - LOW CONF`, `${confidence.toFixed(0)}% < ${required.toFixed(0)}%`);
294
+ }
295
+ }
296
+
297
+ // ===========================================================================
298
+ // SIGNAL & TRADE EVENTS (always log)
299
+ // ===========================================================================
300
+
301
+ signalGenerated(direction, zoneType, confidence, orderType) {
302
+ const arrow = direction === 'LONG' ? '▲' : '▼';
303
+ this.log('signal',
304
+ `✓ SIGNAL ${arrow} ${direction}`,
305
+ `${zoneType} @ ${confidence.toFixed(0)}% conf | ${orderType}`
306
+ );
307
+ }
308
+
309
+ orderPlaced(side, size, symbol, price, type) {
310
+ this.state.status = 'TRADING';
311
+ this.log('trade',
312
+ `ORDER ${type.toUpperCase()}`,
313
+ `${side} ${size} ${symbol} @ ${price.toFixed(2)}`
314
+ );
315
+ }
316
+
317
+ orderFilled(side, size, symbol, price) {
318
+ this.state.status = 'IN_POSITION';
319
+ this.log('trade',
320
+ `✓ FILLED`,
321
+ `${side} ${size} ${symbol} @ ${price.toFixed(2)}`
322
+ );
323
+ }
324
+
325
+ orderRejected(reason) {
326
+ this.state.status = 'SCANNING';
327
+ this.log('error', 'ORDER REJECTED', reason);
328
+ }
329
+
330
+ positionClosed(side, pnl) {
331
+ this.state.status = 'SCANNING';
332
+ const pnlStr = pnl >= 0 ? `+$${pnl.toFixed(2)}` : `-$${Math.abs(pnl).toFixed(2)}`;
333
+ const type = pnl >= 0 ? 'trade' : 'warning';
334
+ this.log(type, 'POSITION CLOSED', `${side} | P&L: ${pnlStr}`);
335
+ }
336
+
337
+ // ===========================================================================
338
+ // VWAP & STRATEGY SPECIFIC (for Ultra Scalping V2)
339
+ // ===========================================================================
340
+
341
+ vwapUpdate(zScore, regime, confidence) {
342
+ if (!this.shouldThrottle('vwap')) {
343
+ const deviationStr = zScore >= 0 ? `+${zScore.toFixed(2)}σ` : `${zScore.toFixed(2)}σ`;
344
+ this.log('analysis', `VWAP: ${deviationStr}`, `Regime: ${regime} | Conf: ${(confidence * 100).toFixed(0)}%`);
345
+ }
346
+ }
347
+
348
+ strategySignal(direction, vwapZ, confidence, stopTicks, targetTicks) {
349
+ const arrow = direction === 'long' ? '▲' : '▼';
350
+ this.log('signal',
351
+ `${arrow} SIGNAL ${direction.toUpperCase()}`,
352
+ `VWAP: ${vwapZ.toFixed(2)}σ | Conf: ${(confidence * 100).toFixed(0)}% | SL: ${stopTicks}t TP: ${targetTicks}t`
353
+ );
354
+ }
355
+
356
+ // ===========================================================================
357
+ // RISK EVENTS (always log)
358
+ // ===========================================================================
359
+
360
+ riskPassed() {
361
+ // Don't log every risk check - too noisy
362
+ }
363
+
364
+ riskBlocked(reason) {
365
+ if (!this.shouldThrottle('risk_blocked')) {
366
+ this.log('warning', 'RISK BLOCKED', reason);
367
+ }
368
+ }
369
+
370
+ spreadWarning(spread) {
371
+ if (this.state.spreadOk) {
372
+ this.state.spreadOk = false;
373
+ this.log('warning', 'WIDE SPREAD', `${spread.toFixed(2)} pts - waiting...`);
374
+ }
375
+ }
376
+
377
+ spreadOk() {
378
+ if (!this.state.spreadOk) {
379
+ this.state.spreadOk = true;
380
+ }
381
+ }
382
+
383
+ // ===========================================================================
384
+ // PRICE MOVEMENTS (only significant)
385
+ // ===========================================================================
386
+
387
+ significantMove(direction, ticks, from, to) {
388
+ if (Math.abs(ticks) >= 3) {
389
+ const arrow = direction === 'up' ? '▲' : '▼';
390
+ this.log('info',
391
+ `PRICE ${arrow} ${Math.abs(ticks)} ticks`,
392
+ `${from.toFixed(2)} → ${to.toFixed(2)}`
393
+ );
394
+ }
395
+ }
396
+
397
+ // ===========================================================================
398
+ // CONNECTION EVENTS (always log)
399
+ // ===========================================================================
400
+
401
+ connected(source) {
402
+ this.log('info', 'CONNECTED', source);
403
+ }
404
+
405
+ disconnected(source) {
406
+ this.log('error', 'DISCONNECTED', source);
407
+ }
408
+
409
+ reconnecting(source) {
410
+ if (!this.shouldThrottle('reconnect')) {
411
+ this.log('warning', 'RECONNECTING...', source);
412
+ }
413
+ }
414
+
415
+ // ===========================================================================
416
+ // UTILITY
417
+ // ===========================================================================
418
+
419
+ getState() {
420
+ return { ...this.state };
421
+ }
422
+ }
423
+
424
+ // Singleton instance
425
+ const smartLogger = new SmartLogger();
426
+
427
+ module.exports = { SmartLogger, smartLogger };
@@ -0,0 +1,206 @@
1
+ /**
2
+ * X Algo - Python Bridge
3
+ * Wrapper to call Cython-compiled algo-core from Node.js
4
+ */
5
+
6
+ const { spawn } = require('child_process');
7
+ const path = require('path');
8
+ const EventEmitter = require('events');
9
+
10
+ // Path to algo-core Python module
11
+ const ALGO_CORE_PATH = path.join(__dirname, '../../algo-core');
12
+
13
+ class PythonBridge extends EventEmitter {
14
+ constructor() {
15
+ super();
16
+ this.process = null;
17
+ this.ready = false;
18
+ this.pendingCallbacks = new Map();
19
+ this.callId = 0;
20
+ }
21
+
22
+ /**
23
+ * Start the Python process
24
+ */
25
+ async start() {
26
+ return new Promise((resolve, reject) => {
27
+ // Spawn Python process running the bridge server
28
+ this.process = spawn('python3', [
29
+ '-u', // Unbuffered output
30
+ path.join(ALGO_CORE_PATH, 'bridge_server.py')
31
+ ], {
32
+ cwd: ALGO_CORE_PATH,
33
+ env: { ...process.env, PYTHONPATH: ALGO_CORE_PATH }
34
+ });
35
+
36
+ let startupOutput = '';
37
+
38
+ this.process.stdout.on('data', (data) => {
39
+ const lines = data.toString().split('\n').filter(l => l.trim());
40
+
41
+ for (const line of lines) {
42
+ try {
43
+ const msg = JSON.parse(line);
44
+
45
+ if (msg.type === 'ready') {
46
+ this.ready = true;
47
+ resolve();
48
+ } else if (msg.type === 'response') {
49
+ const callback = this.pendingCallbacks.get(msg.id);
50
+ if (callback) {
51
+ this.pendingCallbacks.delete(msg.id);
52
+ if (msg.error) {
53
+ callback.reject(new Error(msg.error));
54
+ } else {
55
+ callback.resolve(msg.result);
56
+ }
57
+ }
58
+ } else if (msg.type === 'signal') {
59
+ this.emit('signal', msg.data);
60
+ } else if (msg.type === 'log') {
61
+ this.emit('log', msg.data);
62
+ }
63
+ } catch (e) {
64
+ // Not JSON, just log output
65
+ startupOutput += line + '\n';
66
+ }
67
+ }
68
+ });
69
+
70
+ this.process.stderr.on('data', (data) => {
71
+ console.error('[Python Bridge Error]', data.toString());
72
+ });
73
+
74
+ this.process.on('error', (err) => {
75
+ this.ready = false;
76
+ reject(err);
77
+ });
78
+
79
+ this.process.on('close', (code) => {
80
+ this.ready = false;
81
+ if (code !== 0) {
82
+ console.error(`[Python Bridge] Process exited with code ${code}`);
83
+ }
84
+ this.emit('close', code);
85
+ });
86
+
87
+ // Timeout for startup
88
+ setTimeout(() => {
89
+ if (!this.ready) {
90
+ reject(new Error('Python bridge startup timeout'));
91
+ }
92
+ }, 10000);
93
+ });
94
+ }
95
+
96
+ /**
97
+ * Stop the Python process
98
+ */
99
+ stop() {
100
+ if (this.process) {
101
+ this.process.kill();
102
+ this.process = null;
103
+ this.ready = false;
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Call a method on the Python side
109
+ */
110
+ async call(method, args = {}) {
111
+ if (!this.ready || !this.process) {
112
+ throw new Error('Python bridge not ready');
113
+ }
114
+
115
+ const id = ++this.callId;
116
+
117
+ return new Promise((resolve, reject) => {
118
+ this.pendingCallbacks.set(id, { resolve, reject });
119
+
120
+ const message = JSON.stringify({
121
+ id,
122
+ method,
123
+ args
124
+ }) + '\n';
125
+
126
+ this.process.stdin.write(message);
127
+
128
+ // Timeout for call
129
+ setTimeout(() => {
130
+ if (this.pendingCallbacks.has(id)) {
131
+ this.pendingCallbacks.delete(id);
132
+ reject(new Error(`Call timeout: ${method}`));
133
+ }
134
+ }, 30000);
135
+ });
136
+ }
137
+
138
+ // =========================================================================
139
+ // Strategy Methods
140
+ // =========================================================================
141
+
142
+ // tickSize for tick calculations, P&L comes from API
143
+ async initialize(contractId, tickSize = 0.25) {
144
+ return this.call('initialize', { contractId, tickSize });
145
+ }
146
+
147
+ async processBar(contractId, bar) {
148
+ return this.call('process_bar', { contractId, bar });
149
+ }
150
+
151
+ async processTick(tick) {
152
+ return this.call('process_tick', { tick });
153
+ }
154
+
155
+ async recordTradeResult(pnl) {
156
+ return this.call('record_trade_result', { pnl });
157
+ }
158
+
159
+ async getStats() {
160
+ return this.call('get_stats', {});
161
+ }
162
+
163
+ async getAnalysisState(contractId, currentPrice) {
164
+ return this.call('get_analysis_state', { contractId, currentPrice });
165
+ }
166
+
167
+ async reset(contractId) {
168
+ return this.call('reset', { contractId });
169
+ }
170
+
171
+ // =========================================================================
172
+ // Smart Logs Methods
173
+ // =========================================================================
174
+
175
+ async getSmartLog(condition, data) {
176
+ return this.call('get_smart_log', { condition, data });
177
+ }
178
+
179
+ async getMarketCondition(delta, buyPressure, sellPressure, deltaChange) {
180
+ return this.call('get_market_condition', { delta, buyPressure, sellPressure, deltaChange });
181
+ }
182
+ }
183
+
184
+ // Singleton instance
185
+ let bridgeInstance = null;
186
+
187
+ async function getPythonBridge() {
188
+ if (!bridgeInstance) {
189
+ bridgeInstance = new PythonBridge();
190
+ await bridgeInstance.start();
191
+ }
192
+ return bridgeInstance;
193
+ }
194
+
195
+ function closePythonBridge() {
196
+ if (bridgeInstance) {
197
+ bridgeInstance.stop();
198
+ bridgeInstance = null;
199
+ }
200
+ }
201
+
202
+ module.exports = {
203
+ PythonBridge,
204
+ getPythonBridge,
205
+ closePythonBridge
206
+ };