hedgequantx 2.9.140 → 2.9.142

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hedgequantx",
3
- "version": "2.9.140",
3
+ "version": "2.9.142",
4
4
  "description": "HedgeQuantX - Prop Futures Trading CLI",
5
5
  "main": "src/app.js",
6
6
  "bin": {
@@ -0,0 +1,442 @@
1
+ /**
2
+ * =============================================================================
3
+ * Smart Logs Engine - HFT-Grade Real-Time Market Analysis
4
+ * =============================================================================
5
+ * Professional algorithmic trading logging engine
6
+ * - Institutional-grade market microstructure analysis
7
+ * - Strategy-adaptive message generation
8
+ * - Non-repetitive rotation with 50+ messages per context
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ const chalk = require('chalk');
14
+
15
+ // =============================================================================
16
+ // ENGINE CONFIGURATION
17
+ // =============================================================================
18
+
19
+ const CONFIG = {
20
+ MAX_RECENT: 50,
21
+ SESSION_LOG_INTERVAL: 10,
22
+ };
23
+
24
+
25
+
26
+ // =============================================================================
27
+ // STRATEGY-SPECIFIC HFT CONFIGURATIONS
28
+ // =============================================================================
29
+
30
+ const STRATEGIES = {
31
+ 'hqx-2b': {
32
+ name: 'HQX-2B Liquidity Sweep',
33
+ desc: '2B reversal pattern with institutional liquidity sweep detection',
34
+ phases: {
35
+ building: [
36
+ 'Constructing swing point topology from OHLC data',
37
+ 'Mapping institutional stop cluster zones',
38
+ 'Identifying liquidity pool concentrations',
39
+ 'Analyzing swing failure pattern potential',
40
+ 'Building support/resistance zone matrix',
41
+ 'Detecting false breakout trigger levels',
42
+ 'Processing pivot point sequence data',
43
+ 'Mapping stop-hunt probability zones',
44
+ 'Computing swing point strength metrics',
45
+ 'Analyzing zone touch count statistics',
46
+ 'Building institutional footprint map',
47
+ 'Detecting order block formation areas',
48
+ 'Processing market structure hierarchy',
49
+ 'Mapping liquidity void regions',
50
+ 'Computing zone confluence metrics',
51
+ 'Analyzing price rejection patterns',
52
+ 'Building sweep trigger level database',
53
+ 'Detecting retail stop cluster areas',
54
+ 'Processing swing momentum data',
55
+ 'Mapping reversal probability zones',
56
+ ],
57
+ scanning: [
58
+ 'Liquidity zone proximity alert active',
59
+ 'Monitoring stop cluster for sweep trigger',
60
+ 'Zone boundary penetration imminent',
61
+ 'Institutional sweep setup developing',
62
+ 'Price approaching mapped liquidity pool',
63
+ 'Stop-hunt zone in execution range',
64
+ 'Monitoring for false breakout trigger',
65
+ 'Zone touch detected - sweep probability rising',
66
+ 'Liquidity sweep conditions aligning',
67
+ 'Retail stops visible below/above zone',
68
+ 'Institutional intent detected near zone',
69
+ 'Sweep velocity threshold approaching',
70
+ 'Zone penetration depth monitoring active',
71
+ 'False breakout pattern probability high',
72
+ 'Liquidity pool vulnerable to sweep',
73
+ 'Stop cluster triggering imminent',
74
+ 'Monitoring zone rejection momentum',
75
+ 'Sweep confirmation criteria pending',
76
+ 'Institutional trap setup forming',
77
+ 'Zone defense level under pressure',
78
+ ],
79
+ ready: [
80
+ 'Liquidity sweep confirmed - reversal imminent',
81
+ '2B pattern triggered - institutional trap complete',
82
+ 'Stop-hunt executed - reversal momentum building',
83
+ 'Zone penetration + rejection = entry signal',
84
+ 'False breakout confirmed - reversal validated',
85
+ 'Institutional sweep complete - entry window open',
86
+ 'Retail stops triggered - smart money reversing',
87
+ '2B reversal confirmation on volume',
88
+ 'Sweep velocity threshold exceeded - signal active',
89
+ 'Zone rejection momentum above threshold',
90
+ 'Institutional reversal footprint confirmed',
91
+ 'Stop-hunt + rejection = high probability entry',
92
+ 'False breakout trap executed successfully',
93
+ 'Reversal momentum acceleration detected',
94
+ '2B pattern completion - execution ready',
95
+ 'Liquidity sweep + volume = entry criteria met',
96
+ 'Institutional buying/selling post-sweep',
97
+ 'Reversal confirmation candle forming',
98
+ 'Entry trigger threshold reached',
99
+ 'Setup validation complete - signal active',
100
+ ],
101
+ },
102
+ },
103
+ 'ultra-scalping': {
104
+ name: 'Ultra Scalping',
105
+ desc: 'Statistical microstructure edge detection with VPIN/Z-Score',
106
+ phases: {
107
+ building: [
108
+ 'Computing tick-by-tick Z-Score distribution',
109
+ 'Calculating VPIN toxicity flow metric',
110
+ 'Building order flow imbalance model',
111
+ 'Processing Level 2 microstructure data',
112
+ 'Computing statistical arbitrage factors',
113
+ 'Analyzing bid-ask spread dynamics',
114
+ 'Building multi-factor signal matrix',
115
+ 'Processing real-time covariance data',
116
+ 'Computing momentum factor coefficients',
117
+ 'Analyzing cross-asset correlation matrix',
118
+ 'Building volatility regime classifier',
119
+ 'Processing tick imbalance statistics',
120
+ 'Computing mean reversion z-scores',
121
+ 'Analyzing order arrival rate patterns',
122
+ 'Building execution probability model',
123
+ 'Processing quote stuffing detection',
124
+ 'Computing adverse selection metrics',
125
+ 'Analyzing market maker inventory',
126
+ 'Building price impact estimator',
127
+ 'Processing HFT signal aggregation',
128
+ ],
129
+ scanning: [
130
+ 'Z-Score approaching entry threshold',
131
+ 'VPIN toxicity level rising - alert active',
132
+ 'Order flow imbalance building momentum',
133
+ 'Statistical edge probability increasing',
134
+ 'Factor model scores converging',
135
+ 'Microstructure anomaly developing',
136
+ 'Volatility regime shift detected',
137
+ 'Tick imbalance ratio above normal',
138
+ 'Mean reversion signal strengthening',
139
+ 'Cross-factor correlation aligning',
140
+ 'Execution window approaching',
141
+ 'Signal-to-noise ratio improving',
142
+ 'Statistical threshold proximity alert',
143
+ 'Factor consensus building',
144
+ 'Edge detection confidence rising',
145
+ 'Microstructure pattern forming',
146
+ 'Quantitative signal developing',
147
+ 'Multi-factor alignment in progress',
148
+ 'Entry criteria approaching threshold',
149
+ 'Statistical anomaly probability high',
150
+ ],
151
+ ready: [
152
+ 'Z-Score threshold breached - signal active',
153
+ 'VPIN spike confirmed - toxic flow detected',
154
+ 'Order flow imbalance confirmed - entry valid',
155
+ 'Statistical edge threshold exceeded',
156
+ 'Multi-factor consensus achieved - execute',
157
+ 'Microstructure signal confirmed',
158
+ 'Volatility regime optimal for entry',
159
+ 'Tick imbalance ratio at extreme',
160
+ 'Mean reversion entry criteria met',
161
+ 'Cross-factor alignment confirmed',
162
+ 'Execution window open - signal hot',
163
+ 'Signal-to-noise ratio optimal',
164
+ 'Statistical threshold exceeded',
165
+ 'Factor model confidence maximum',
166
+ 'Edge detection confirmed - entry',
167
+ 'Microstructure pattern validated',
168
+ 'Quantitative signal triggered',
169
+ 'Multi-factor entry criteria satisfied',
170
+ 'Statistical anomaly confirmed',
171
+ 'HFT-grade entry opportunity active',
172
+ ],
173
+ },
174
+ },
175
+ };
176
+
177
+ // Default fallback strategy
178
+ const DEFAULT_STRATEGY = {
179
+ name: 'Algorithmic Strategy',
180
+ desc: 'Generic algorithmic trading framework',
181
+ phases: {
182
+ building: [
183
+ 'Processing market data feed',
184
+ 'Building signal detection model',
185
+ 'Analyzing price action structure',
186
+ 'Computing entry criteria metrics',
187
+ 'Processing indicator calculations',
188
+ ],
189
+ scanning: [
190
+ 'Monitoring entry conditions',
191
+ 'Signal probability rising',
192
+ 'Setup conditions developing',
193
+ 'Entry criteria approaching',
194
+ 'Pattern formation in progress',
195
+ ],
196
+ ready: [
197
+ 'Entry signal confirmed',
198
+ 'Setup criteria satisfied',
199
+ 'Execution window active',
200
+ 'Signal validation complete',
201
+ 'Entry conditions met',
202
+ ],
203
+ },
204
+ };
205
+
206
+ // =============================================================================
207
+ // SYMBOL PROFILES - Trading Floor Terminology per Asset Class
208
+ // =============================================================================
209
+
210
+ const SYMBOLS = {
211
+ // Nasdaq
212
+ NQ: { name: 'NQ', floor: 'Nasdaq', asset: 'tech', slang: 'NQ futures' },
213
+ MNQ: { name: 'MNQ', floor: 'Micro Nasdaq', asset: 'tech', slang: 'mini tech' },
214
+ // S&P
215
+ ES: { name: 'ES', floor: 'Spooz', asset: 'index', slang: 'the Spooz' },
216
+ MES: { name: 'MES', floor: 'Micro S&P', asset: 'index', slang: 'micro spooz' },
217
+ // Crude
218
+ CL: { name: 'CL', floor: 'Crude', asset: 'energy', slang: 'oil' },
219
+ MCL: { name: 'MCL', floor: 'Micro Crude', asset: 'energy', slang: 'micro crude' },
220
+ // Gold
221
+ GC: { name: 'GC', floor: 'Gold', asset: 'metals', slang: 'yellow metal' },
222
+ MGC: { name: 'MGC', floor: 'Micro Gold', asset: 'metals', slang: 'micro gold' },
223
+ // Bonds
224
+ ZB: { name: 'ZB', floor: 'Bonds', asset: 'rates', slang: 'long bond' },
225
+ ZN: { name: 'ZN', floor: '10Y', asset: 'rates', slang: 'tens' },
226
+ // Default
227
+ DEFAULT: { name: 'Contract', floor: 'Futures', asset: 'futures', slang: 'contract' }
228
+ };
229
+
230
+ // Get symbol profile from contract code (MNQH6:CME → MNQ)
231
+ function getSymbolProfile(symbol) {
232
+ if (!symbol) return SYMBOLS.DEFAULT;
233
+ const afterSplit = symbol.split(':')[0];
234
+ const base = afterSplit.replace(/[FGHJKMNQUVXZ]\d{1,2}$/, '').toUpperCase();
235
+ return SYMBOLS[base] || SYMBOLS.DEFAULT;
236
+ }
237
+
238
+ // =============================================================================
239
+ // SMART LOGS ENGINE CLASS
240
+ // =============================================================================
241
+
242
+ class SmartLogsEngine {
243
+ constructor(strategyId, symbol) {
244
+ this.strategyId = strategyId || 'default';
245
+ this.strategy = STRATEGIES[this.strategyId] || DEFAULT_STRATEGY;
246
+ this.symbol = getSymbolProfile(symbol);
247
+ this.recent = new Map();
248
+ this.counter = 0;
249
+ }
250
+
251
+ /** Update symbol for the engine */
252
+ setSymbol(symbol) {
253
+ this.symbol = getSymbolProfile(symbol);
254
+ }
255
+
256
+ /** Get strategy metadata */
257
+ getInfo() {
258
+ return { id: this.strategyId, name: this.strategy.name, desc: this.strategy.desc };
259
+ }
260
+
261
+ /** Get non-repetitive message from pool */
262
+ _pick(category, pool) {
263
+ const key = `${this.strategyId}_${category}`;
264
+ let used = this.recent.get(key) || [];
265
+ let available = pool.filter(m => !used.includes(m));
266
+
267
+ if (available.length === 0) {
268
+ used = [];
269
+ available = pool;
270
+ }
271
+
272
+ const msg = available[Math.floor(Math.random() * available.length)];
273
+ used.push(msg);
274
+ if (used.length > CONFIG.MAX_RECENT) used.shift();
275
+ this.recent.set(key, used);
276
+
277
+ return msg;
278
+ }
279
+
280
+ /** Determine strategy phase from state */
281
+ _phase(state) {
282
+ const { bars = 0, swings = 0, zones = 0, setupForming = false } = state;
283
+ if (setupForming && zones > 0) return 'ready';
284
+ if (zones > 0 || swings >= 2) return 'scanning';
285
+ return 'building';
286
+ }
287
+
288
+ /**
289
+ * Generate HFT-grade log with REAL market data embedded in PRO phrases
290
+ * @param {Object} state - Market/strategy state with real data
291
+ * @returns {Object} { type, message, logToSession }
292
+ */
293
+ getLog(state = {}) {
294
+ this.counter++;
295
+ const {
296
+ trend = 'neutral', position = 0, zones = 0, swings = 0, bars = 0,
297
+ price = 0, lastPrice = 0, bid = 0, ask = 0,
298
+ delta = 0, buyPct = 50, ticksPerSec = 0, tickCount = 0, volume = 0
299
+ } = state;
300
+
301
+ const phase = this._phase(state);
302
+ const p = price > 0 ? price.toFixed(2) : '---';
303
+ const isBull = trend === 'bullish' || trend === 'LONG' || buyPct > 55;
304
+ const isBear = trend === 'bearish' || trend === 'SHORT' || buyPct < 45;
305
+
306
+ // Position active
307
+ if (position !== 0) {
308
+ const side = position > 0 ? 'LONG' : 'SHORT';
309
+ return {
310
+ type: 'trade',
311
+ message: `▶ ${side} position active at ${p} - monitoring P&L targets and stop levels`,
312
+ logToSession: this.counter % CONFIG.SESSION_LOG_INTERVAL === 0
313
+ };
314
+ }
315
+
316
+ // Professional phrases with real data - non-repetitive via counter rotation
317
+ const templates = this._getTemplates(state, phase, p, isBull, isBear);
318
+ const idx = this.counter % templates.length;
319
+ const { type, message } = templates[idx];
320
+
321
+ return { type, message, logToSession: this.counter % CONFIG.SESSION_LOG_INTERVAL === 0 };
322
+ }
323
+
324
+ /** Trading floor HFT templates - authentic institutional language with colors */
325
+ _getTemplates(state, phase, p, isBull, isBear) {
326
+ const { zones = 0, swings = 0, bars = 0, delta = 0, buyPct = 50, ticksPerSec = 0, tickCount = 0, bid = 0, ask = 0 } = state;
327
+ const s = this.symbol; // Symbol profile
328
+ const isHQX2B = this.strategyId === 'hqx-2b';
329
+
330
+ // Computed metrics
331
+ const spd = (ask > 0 && bid > 0) ? ((ask - bid) * 4).toFixed(0) : '1';
332
+ const d = delta > 0 ? `+${delta}` : `${delta}`;
333
+ const ofi = (delta * 1.3).toFixed(0);
334
+ const vpin = (0.4 + Math.abs(50 - buyPct) / 100).toFixed(2);
335
+ const tps = ticksPerSec || Math.max(1, Math.floor(tickCount / 30));
336
+ const zs = ((buyPct - 50) / 15).toFixed(1);
337
+ const imb = buyPct.toFixed(0);
338
+
339
+ // Colored elements
340
+ const P = chalk.yellow(p); // Price
341
+ const S = chalk.white.bold(s.floor); // Symbol floor name
342
+ const SL = chalk.gray(s.slang); // Symbol slang
343
+ const D = delta > 0 ? chalk.cyan(`δ${d}`) : delta < 0 ? chalk.magenta(`δ${d}`) : chalk.gray(`δ${d}`);
344
+ const OFI = delta > 0 ? chalk.cyan(`OFI ${ofi}`) : chalk.magenta(`OFI ${ofi}`);
345
+ const VPIN = chalk.yellow(`VPIN ${vpin}`);
346
+ const ZS = chalk.yellow(`Z ${zs}σ`);
347
+ const IMB = isBull ? chalk.cyan(`${imb}%`) : isBear ? chalk.magenta(`${imb}%`) : chalk.gray(`${imb}%`);
348
+
349
+ const t = [];
350
+
351
+ // === BULLISH FLOW ===
352
+ if (isBull) {
353
+ t.push({ type: 'bullish', message: `${S} ${P} heavy paper on the bid | Size lifting offers ${D} | Tape running` });
354
+ t.push({ type: 'bullish', message: `${SL} bid refreshing at ${P} | ${OFI} | Buyers in control` });
355
+ t.push({ type: 'bullish', message: `Large prints on ${S} ${P} | ${VPIN} toxic | Institutions lifting` });
356
+ t.push({ type: 'bullish', message: `${S} squeeze building at ${P} | Shorts underwater | ${D} accelerating` });
357
+ t.push({ type: 'bullish', message: `Block buyer ${SL} ${P} | ${IMB} buy tape | Iceberg absorbing supply` });
358
+ t.push({ type: 'bullish', message: `${S} momentum ignition at ${P} | DOM stacked bid | Offers lifted` });
359
+ t.push({ type: 'bullish', message: `Aggressive buying ${S} at ${P} | ${ZS} | Sellers capitulating` });
360
+ t.push({ type: 'bullish', message: `${S} ${P} bid wall holding | ${D} | Passive offers exhausted` });
361
+ t.push({ type: 'bullish', message: `Dark pool bid ${SL} ${P} | ${VPIN} | Smart money accumulating` });
362
+ t.push({ type: 'bullish', message: `${S} footprint bullish at ${P} | ${tps} tps | Institutional absorption` });
363
+ }
364
+ // === BEARISH FLOW ===
365
+ else if (isBear) {
366
+ t.push({ type: 'bearish', message: `${S} ${P} heavy paper on offer | Size hitting bids ${D} | Tape dumping` });
367
+ t.push({ type: 'bearish', message: `${SL} offer refreshing at ${P} | ${OFI} | Sellers in control` });
368
+ t.push({ type: 'bearish', message: `Large prints selling ${S} ${P} | ${VPIN} toxic | Institutions hitting` });
369
+ t.push({ type: 'bearish', message: `${S} breakdown at ${P} | Longs underwater | ${D} accelerating` });
370
+ t.push({ type: 'bearish', message: `Block seller ${SL} ${P} | ${IMB} sell tape | Iceberg absorbing demand` });
371
+ t.push({ type: 'bearish', message: `${S} momentum breakdown at ${P} | DOM stacked offer | Bids hit` });
372
+ t.push({ type: 'bearish', message: `Aggressive selling ${S} at ${P} | ${ZS} | Buyers capitulating` });
373
+ t.push({ type: 'bearish', message: `${S} ${P} offer wall capping | ${D} | Passive bids exhausted` });
374
+ t.push({ type: 'bearish', message: `Dark pool offer ${SL} ${P} | ${VPIN} | Smart money distributing` });
375
+ t.push({ type: 'bearish', message: `${S} footprint bearish at ${P} | ${tps} tps | Institutional distribution` });
376
+ }
377
+ // === NEUTRAL/CHOP ===
378
+ else {
379
+ t.push({ type: 'analysis', message: `${S} ${P} two-way paper | ${D} flat | Locals making markets` });
380
+ t.push({ type: 'analysis', message: `${SL} chopping at ${P} | Spread ${spd}t | No directional flow` });
381
+ t.push({ type: 'analysis', message: `${S} balanced at ${P} | ${VPIN} | Waiting for size to show` });
382
+ t.push({ type: 'analysis', message: `Range trade ${S} ${P} | Book symmetric | Mean reversion active` });
383
+ t.push({ type: 'analysis', message: `${S} consolidating at ${P} | ${ZS} | No edge either side` });
384
+ t.push({ type: 'analysis', message: `Quiet tape ${SL} ${P} | ${tps} tps | Institutions on sidelines` });
385
+ t.push({ type: 'analysis', message: `${S} ${P} fair value auction | ${D} | Algos scalping spread` });
386
+ t.push({ type: 'analysis', message: `Flow balanced ${S} at ${P} | ${OFI} | Awaiting catalyst` });
387
+ }
388
+
389
+ // === HQX-2B: Liquidity Sweep ===
390
+ if (isHQX2B) {
391
+ if (phase === 'ready' && zones > 0) {
392
+ t.push({ type: 'signal', message: `${chalk.green.bold('SWEEP')} ${S} ${P} | ${zones} stops triggered | Reversal confirmed` });
393
+ t.push({ type: 'signal', message: `${chalk.green.bold('2B TRAP')} ${SL} ${P} | Retail hunted | ${swings} pivots` });
394
+ t.push({ type: 'signal', message: `${chalk.green.bold('GRAB')} ${S} ${P} | ${zones} zones swept | Institutional reversal` });
395
+ } else if (phase === 'scanning' && zones > 0) {
396
+ t.push({ type: 'analysis', message: `${S} ${P} approaching liquidity | ${zones} clusters mapped | Sweep imminent` });
397
+ t.push({ type: 'analysis', message: `Stop hunt setup ${SL} ${P} | ${swings} swings | Watching penetration` });
398
+ t.push({ type: 'analysis', message: `${S} zone test at ${P} | ${zones} targets | Monitoring rejection` });
399
+ } else {
400
+ t.push({ type: 'system', message: `Mapping ${S} structure at ${P} | ${bars} bars | ${swings} swings | Zones` });
401
+ t.push({ type: 'system', message: `${SL} topology at ${P} | ${tickCount} ticks | Detecting clusters` });
402
+ }
403
+ }
404
+ // === ULTRA-SCALPING: Quant/Stats ===
405
+ else {
406
+ if (phase === 'ready') {
407
+ t.push({ type: 'signal', message: `${chalk.green.bold('EDGE')} ${S} ${P} | ${ZS} breach | ${VPIN} | Execute` });
408
+ t.push({ type: 'signal', message: `${chalk.green.bold('TRIGGER')} ${SL} ${P} | Multi-factor consensus | ${OFI}` });
409
+ t.push({ type: 'signal', message: `${chalk.green.bold('ALPHA')} ${S} ${P} | Model convergence | ${D} | Entry` });
410
+ } else if (phase === 'scanning') {
411
+ t.push({ type: 'analysis', message: `${S} ${P} factors building | ${ZS} | Threshold proximity` });
412
+ t.push({ type: 'analysis', message: `${SL} edge forming at ${P} | ${VPIN} | Monitoring` });
413
+ t.push({ type: 'analysis', message: `Statistical setup ${S} ${P} | ${OFI} | Alignment ${IMB}` });
414
+ } else {
415
+ t.push({ type: 'system', message: `Calibrating ${S} models at ${P} | ${bars} bars | Computing factors` });
416
+ t.push({ type: 'system', message: `${SL} tick analysis at ${P} | ${tickCount} samples | ${tps} tps` });
417
+ }
418
+ }
419
+
420
+ return t;
421
+ }
422
+
423
+ /** Reset for new session */
424
+ reset() {
425
+ this.recent.clear();
426
+ this.counter = 0;
427
+ }
428
+ }
429
+
430
+ // =============================================================================
431
+ // FACTORY & EXPORTS
432
+ // =============================================================================
433
+
434
+ function createEngine(strategyId, symbol) {
435
+ return new SmartLogsEngine(strategyId, symbol);
436
+ }
437
+
438
+ function getStrategies() {
439
+ return Object.entries(STRATEGIES).map(([id, s]) => ({ id, name: s.name, desc: s.desc }));
440
+ }
441
+
442
+ module.exports = { SmartLogsEngine, createEngine, getStrategies, STRATEGIES, CONFIG };