hedgequantx 2.7.15 → 2.7.17

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.
package/src/lib/o/l2.js DELETED
@@ -1,427 +0,0 @@
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 };
@@ -1,206 +0,0 @@
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
- };