hedgequantx 2.6.90 → 2.6.91

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.6.90",
3
+ "version": "2.6.91",
4
4
  "description": "HedgeQuantX - Prop Futures Trading CLI",
5
5
  "main": "src/app.js",
6
6
  "bin": {
@@ -23,6 +23,7 @@ const { MarketDataFeed } = require('../../../dist/lib/data');
23
23
  const { RithmicMarketDataFeed } = require('../../services/rithmic/market-data');
24
24
  const { algoLogger } = require('./logger');
25
25
  const { recoveryMath } = require('../../services/strategy/recovery-math');
26
+ const { sessionHistory, SessionHistory } = require('../../services/session-history');
26
27
 
27
28
  // Use HFT tick-based strategy for Rithmic (fast path), M1 for ProjectX
28
29
  const USE_HFT_STRATEGY = true;
@@ -286,6 +287,26 @@ const launchAlgo = async (service, account, contract, config) => {
286
287
  let tickCount = 0;
287
288
  let lastTradeCount = 0; // Track number of trades from API
288
289
  let lastPositionQty = 0; // Track position changes
290
+ let currentTradeId = null; // Track current trade for history
291
+
292
+ // ═══════════════════════════════════════════════════════════════════════════
293
+ // SESSION HISTORY - Save all activity for AI learning
294
+ // ═══════════════════════════════════════════════════════════════════════════
295
+ sessionHistory.start(account.accountId, symbolName, account.propfirm || 'unknown', {
296
+ contracts,
297
+ dailyTarget,
298
+ maxRisk,
299
+ aiEnabled: config.enableAI,
300
+ agentCount: config.enableAI ? 2 : 0,
301
+ });
302
+
303
+ // Load historical data for AI learning
304
+ const historicalData = SessionHistory.getAILearningData();
305
+ if (historicalData.totalSessions > 0) {
306
+ algoLogger.info(ui, 'HISTORY LOADED',
307
+ `${historicalData.totalSessions} sessions | ${historicalData.totalTrades} trades | ` +
308
+ `WR: ${(historicalData.statistics?.winRate * 100 || 0).toFixed(0)}%`);
309
+ }
289
310
 
290
311
  // Initialize Strategy
291
312
  // Use HFT tick-based strategy for Rithmic (fast path), M1 for ProjectX
@@ -647,6 +668,19 @@ const launchAlgo = async (service, account, contract, config) => {
647
668
  algoLogger.positionOpened(ui, symbolName, positionSide, contracts, entry);
648
669
  algoLogger.entryConfirmed(ui, sideStr, contracts, symbolName, entry);
649
670
 
671
+ // Record trade entry in session history
672
+ currentTradeId = sessionHistory.recordEntry({
673
+ direction,
674
+ symbol: symbolName,
675
+ quantity: contracts,
676
+ entryPrice: entry,
677
+ stopLoss,
678
+ takeProfit,
679
+ momentum: strategy.getMomentum?.() || 0,
680
+ zscore: strategy.getZScore?.() || 0,
681
+ ofi: strategy.getOFI?.() || 0,
682
+ });
683
+
650
684
  // Place bracket orders (SL/TP) - SLOW PATH ONLY
651
685
  if (stopLoss && takeProfit) {
652
686
  // Stop Loss
@@ -946,6 +980,14 @@ const launchAlgo = async (service, account, contract, config) => {
946
980
  // Record in strategy for adaptation
947
981
  strategy.recordTradeResult(pnl);
948
982
 
983
+ // Record trade exit in session history
984
+ sessionHistory.recordExit(currentTradeId, {
985
+ exitPrice,
986
+ pnl,
987
+ reason: pnl >= 0 ? 'takeProfit' : 'stopLoss',
988
+ });
989
+ currentTradeId = null;
990
+
949
991
  // Feed trade result to AI supervisor - THIS IS WHERE AGENTS LEARN
950
992
  if (stats.aiSupervision) {
951
993
  StrategySupervisor.feedTradeResult({
@@ -1193,6 +1235,15 @@ const launchAlgo = async (service, account, contract, config) => {
1193
1235
  };
1194
1236
  }
1195
1237
 
1238
+ // End session history and save to disk
1239
+ sessionHistory.end({
1240
+ totalTrades: stats.trades,
1241
+ wins: stats.wins,
1242
+ losses: stats.losses,
1243
+ totalPnl: stats.pnl,
1244
+ stopReason,
1245
+ });
1246
+
1196
1247
  // Disconnect market feed with timeout
1197
1248
  try {
1198
1249
  await Promise.race([
@@ -0,0 +1,475 @@
1
+ /**
2
+ * =============================================================================
3
+ * Session History - Persistent learning across trading sessions
4
+ * =============================================================================
5
+ *
6
+ * Saves all trading activity for AI agents to learn from:
7
+ * - Trade entries/exits with P&L
8
+ * - Signals generated (taken and skipped)
9
+ * - Market conditions at each signal
10
+ * - AI recommendations and outcomes
11
+ *
12
+ * Data is stored in ~/.hqx/history/ as JSON files
13
+ */
14
+
15
+ 'use strict';
16
+
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+ const os = require('os');
20
+
21
+ // History directory
22
+ const HISTORY_DIR = path.join(os.homedir(), '.hqx', 'history');
23
+ const MAX_SESSIONS = 100; // Keep last 100 sessions
24
+ const MAX_TRADES_PER_FILE = 1000;
25
+
26
+ /**
27
+ * Ensure history directory exists
28
+ */
29
+ function ensureDir() {
30
+ if (!fs.existsSync(HISTORY_DIR)) {
31
+ fs.mkdirSync(HISTORY_DIR, { recursive: true });
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Session History Manager
37
+ */
38
+ class SessionHistory {
39
+ constructor() {
40
+ this.sessionId = null;
41
+ this.sessionFile = null;
42
+ this.data = {
43
+ sessionId: null,
44
+ startTime: null,
45
+ endTime: null,
46
+ account: null,
47
+ symbol: null,
48
+ propfirm: null,
49
+ config: {},
50
+ trades: [],
51
+ signals: [],
52
+ aiRecommendations: [],
53
+ marketConditions: [],
54
+ summary: {
55
+ totalTrades: 0,
56
+ wins: 0,
57
+ losses: 0,
58
+ breakeven: 0,
59
+ totalPnl: 0,
60
+ maxDrawdown: 0,
61
+ winRate: 0,
62
+ avgWin: 0,
63
+ avgLoss: 0,
64
+ profitFactor: 0,
65
+ }
66
+ };
67
+ this.dirty = false;
68
+ this.saveTimer = null;
69
+ }
70
+
71
+ /**
72
+ * Start a new session
73
+ */
74
+ start(accountId, symbol, propfirm, config = {}) {
75
+ ensureDir();
76
+
77
+ this.sessionId = `${Date.now()}_${accountId}_${symbol}`;
78
+ this.sessionFile = path.join(HISTORY_DIR, `session_${this.sessionId}.json`);
79
+
80
+ this.data = {
81
+ sessionId: this.sessionId,
82
+ startTime: new Date().toISOString(),
83
+ endTime: null,
84
+ account: accountId,
85
+ symbol,
86
+ propfirm,
87
+ config: {
88
+ contracts: config.contracts || 1,
89
+ dailyTarget: config.dailyTarget || 0,
90
+ maxRisk: config.maxRisk || 0,
91
+ aiEnabled: config.aiEnabled || false,
92
+ agentCount: config.agentCount || 0,
93
+ },
94
+ trades: [],
95
+ signals: [],
96
+ aiRecommendations: [],
97
+ marketConditions: [],
98
+ summary: {
99
+ totalTrades: 0,
100
+ wins: 0,
101
+ losses: 0,
102
+ breakeven: 0,
103
+ totalPnl: 0,
104
+ maxDrawdown: 0,
105
+ winRate: 0,
106
+ avgWin: 0,
107
+ avgLoss: 0,
108
+ profitFactor: 0,
109
+ }
110
+ };
111
+
112
+ this.dirty = true;
113
+ this._scheduleSave();
114
+
115
+ return this.sessionId;
116
+ }
117
+
118
+ /**
119
+ * Record a trade signal (generated by strategy)
120
+ */
121
+ recordSignal(signal) {
122
+ if (!this.sessionId) return;
123
+
124
+ this.data.signals.push({
125
+ timestamp: new Date().toISOString(),
126
+ direction: signal.direction,
127
+ entry: signal.entry,
128
+ stopLoss: signal.stopLoss,
129
+ takeProfit: signal.takeProfit,
130
+ confidence: signal.confidence,
131
+ taken: signal.taken !== false, // Default true unless explicitly false
132
+ skipReason: signal.skipReason || null,
133
+ // Market context
134
+ momentum: signal.momentum,
135
+ zscore: signal.zscore,
136
+ ofi: signal.ofi,
137
+ atr: signal.atr,
138
+ volume: signal.volume,
139
+ });
140
+
141
+ this.dirty = true;
142
+ this._scheduleSave();
143
+ }
144
+
145
+ /**
146
+ * Record a trade entry
147
+ */
148
+ recordEntry(trade) {
149
+ if (!this.sessionId) return;
150
+
151
+ const tradeRecord = {
152
+ id: `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
153
+ entryTime: new Date().toISOString(),
154
+ exitTime: null,
155
+ direction: trade.direction,
156
+ symbol: trade.symbol,
157
+ quantity: trade.quantity,
158
+ entryPrice: trade.entryPrice,
159
+ exitPrice: null,
160
+ stopLoss: trade.stopLoss,
161
+ takeProfit: trade.takeProfit,
162
+ pnl: null,
163
+ exitReason: null,
164
+ // Market context at entry
165
+ momentum: trade.momentum,
166
+ zscore: trade.zscore,
167
+ ofi: trade.ofi,
168
+ // AI context
169
+ aiAdvice: trade.aiAdvice || null,
170
+ aiConfidence: trade.aiConfidence || null,
171
+ };
172
+
173
+ this.data.trades.push(tradeRecord);
174
+ this.dirty = true;
175
+ this._scheduleSave();
176
+
177
+ return tradeRecord.id;
178
+ }
179
+
180
+ /**
181
+ * Record a trade exit
182
+ */
183
+ recordExit(tradeId, exitData) {
184
+ if (!this.sessionId) return;
185
+
186
+ const trade = this.data.trades.find(t => t.id === tradeId);
187
+ if (!trade) {
188
+ // Find last unclosed trade
189
+ const unclosed = this.data.trades.filter(t => !t.exitTime);
190
+ if (unclosed.length > 0) {
191
+ const lastTrade = unclosed[unclosed.length - 1];
192
+ lastTrade.exitTime = new Date().toISOString();
193
+ lastTrade.exitPrice = exitData.exitPrice;
194
+ lastTrade.pnl = exitData.pnl;
195
+ lastTrade.exitReason = exitData.reason || 'unknown';
196
+ }
197
+ } else {
198
+ trade.exitTime = new Date().toISOString();
199
+ trade.exitPrice = exitData.exitPrice;
200
+ trade.pnl = exitData.pnl;
201
+ trade.exitReason = exitData.reason || 'unknown';
202
+ }
203
+
204
+ this._updateSummary();
205
+ this.dirty = true;
206
+ this._scheduleSave();
207
+ }
208
+
209
+ /**
210
+ * Record AI recommendation
211
+ */
212
+ recordAIRecommendation(recommendation) {
213
+ if (!this.sessionId) return;
214
+
215
+ this.data.aiRecommendations.push({
216
+ timestamp: new Date().toISOString(),
217
+ agent: recommendation.agent,
218
+ action: recommendation.action, // 'proceed', 'skip', 'adjust'
219
+ reason: recommendation.reason,
220
+ confidence: recommendation.confidence,
221
+ adjustment: recommendation.adjustment || null,
222
+ outcome: null, // Will be filled when trade closes
223
+ });
224
+
225
+ this.dirty = true;
226
+ this._scheduleSave();
227
+ }
228
+
229
+ /**
230
+ * Record market conditions snapshot
231
+ */
232
+ recordMarketConditions(conditions) {
233
+ if (!this.sessionId) return;
234
+
235
+ // Only record every 30 seconds to avoid bloat
236
+ const lastCondition = this.data.marketConditions[this.data.marketConditions.length - 1];
237
+ if (lastCondition) {
238
+ const timeDiff = Date.now() - new Date(lastCondition.timestamp).getTime();
239
+ if (timeDiff < 30000) return;
240
+ }
241
+
242
+ this.data.marketConditions.push({
243
+ timestamp: new Date().toISOString(),
244
+ price: conditions.price,
245
+ bid: conditions.bid,
246
+ ask: conditions.ask,
247
+ volume: conditions.volume,
248
+ momentum: conditions.momentum,
249
+ zscore: conditions.zscore,
250
+ ofi: conditions.ofi,
251
+ volatility: conditions.volatility,
252
+ });
253
+
254
+ // Keep only last 1000 conditions
255
+ if (this.data.marketConditions.length > 1000) {
256
+ this.data.marketConditions = this.data.marketConditions.slice(-1000);
257
+ }
258
+
259
+ this.dirty = true;
260
+ this._scheduleSave();
261
+ }
262
+
263
+ /**
264
+ * End session and save final data
265
+ */
266
+ end(finalStats = {}) {
267
+ if (!this.sessionId) return;
268
+
269
+ this.data.endTime = new Date().toISOString();
270
+ this.data.summary = {
271
+ ...this.data.summary,
272
+ ...finalStats,
273
+ };
274
+
275
+ this._updateSummary();
276
+ this._saveNow();
277
+ this._cleanup();
278
+
279
+ const sessionId = this.sessionId;
280
+ this.sessionId = null;
281
+
282
+ return sessionId;
283
+ }
284
+
285
+ /**
286
+ * Load all historical sessions for AI learning
287
+ */
288
+ static loadHistory(limit = 50) {
289
+ ensureDir();
290
+
291
+ try {
292
+ const files = fs.readdirSync(HISTORY_DIR)
293
+ .filter(f => f.startsWith('session_') && f.endsWith('.json'))
294
+ .sort()
295
+ .reverse()
296
+ .slice(0, limit);
297
+
298
+ const sessions = [];
299
+ for (const file of files) {
300
+ try {
301
+ const data = JSON.parse(fs.readFileSync(path.join(HISTORY_DIR, file), 'utf8'));
302
+ sessions.push(data);
303
+ } catch (e) {
304
+ // Skip corrupted files
305
+ }
306
+ }
307
+
308
+ return sessions;
309
+ } catch (e) {
310
+ return [];
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Get aggregated learning data for AI
316
+ */
317
+ static getAILearningData() {
318
+ const sessions = SessionHistory.loadHistory(50);
319
+
320
+ if (sessions.length === 0) {
321
+ return {
322
+ totalSessions: 0,
323
+ totalTrades: 0,
324
+ patterns: { winning: [], losing: [] },
325
+ statistics: null,
326
+ };
327
+ }
328
+
329
+ // Aggregate all trades
330
+ const allTrades = sessions.flatMap(s => s.trades || []).filter(t => t.pnl !== null);
331
+ const winningTrades = allTrades.filter(t => t.pnl > 0);
332
+ const losingTrades = allTrades.filter(t => t.pnl < 0);
333
+
334
+ // Extract patterns from winning trades
335
+ const winningPatterns = winningTrades.map(t => ({
336
+ direction: t.direction,
337
+ momentum: t.momentum,
338
+ zscore: t.zscore,
339
+ ofi: t.ofi,
340
+ pnl: t.pnl,
341
+ })).slice(-100); // Last 100 winning patterns
342
+
343
+ // Extract patterns from losing trades
344
+ const losingPatterns = losingTrades.map(t => ({
345
+ direction: t.direction,
346
+ momentum: t.momentum,
347
+ zscore: t.zscore,
348
+ ofi: t.ofi,
349
+ pnl: t.pnl,
350
+ })).slice(-100); // Last 100 losing patterns
351
+
352
+ // Calculate aggregate statistics
353
+ const totalPnl = allTrades.reduce((sum, t) => sum + (t.pnl || 0), 0);
354
+ const winRate = allTrades.length > 0 ? winningTrades.length / allTrades.length : 0;
355
+ const avgWin = winningTrades.length > 0
356
+ ? winningTrades.reduce((sum, t) => sum + t.pnl, 0) / winningTrades.length
357
+ : 0;
358
+ const avgLoss = losingTrades.length > 0
359
+ ? Math.abs(losingTrades.reduce((sum, t) => sum + t.pnl, 0) / losingTrades.length)
360
+ : 0;
361
+ const profitFactor = avgLoss > 0 ? (avgWin * winRate) / (avgLoss * (1 - winRate)) : 0;
362
+
363
+ return {
364
+ totalSessions: sessions.length,
365
+ totalTrades: allTrades.length,
366
+ patterns: {
367
+ winning: winningPatterns,
368
+ losing: losingPatterns,
369
+ },
370
+ statistics: {
371
+ totalPnl,
372
+ winRate,
373
+ avgWin,
374
+ avgLoss,
375
+ profitFactor,
376
+ winningTrades: winningTrades.length,
377
+ losingTrades: losingTrades.length,
378
+ },
379
+ // AI recommendations effectiveness
380
+ aiRecommendations: sessions.flatMap(s => s.aiRecommendations || []).slice(-200),
381
+ };
382
+ }
383
+
384
+ /**
385
+ * Update summary statistics
386
+ */
387
+ _updateSummary() {
388
+ const trades = this.data.trades.filter(t => t.pnl !== null);
389
+ const wins = trades.filter(t => t.pnl > 0);
390
+ const losses = trades.filter(t => t.pnl < 0);
391
+ const breakeven = trades.filter(t => t.pnl === 0);
392
+
393
+ const totalPnl = trades.reduce((sum, t) => sum + t.pnl, 0);
394
+ const avgWin = wins.length > 0 ? wins.reduce((sum, t) => sum + t.pnl, 0) / wins.length : 0;
395
+ const avgLoss = losses.length > 0 ? Math.abs(losses.reduce((sum, t) => sum + t.pnl, 0) / losses.length) : 0;
396
+
397
+ // Calculate max drawdown
398
+ let peak = 0;
399
+ let maxDrawdown = 0;
400
+ let cumPnl = 0;
401
+ for (const trade of trades) {
402
+ cumPnl += trade.pnl;
403
+ if (cumPnl > peak) peak = cumPnl;
404
+ const drawdown = peak - cumPnl;
405
+ if (drawdown > maxDrawdown) maxDrawdown = drawdown;
406
+ }
407
+
408
+ this.data.summary = {
409
+ totalTrades: trades.length,
410
+ wins: wins.length,
411
+ losses: losses.length,
412
+ breakeven: breakeven.length,
413
+ totalPnl,
414
+ maxDrawdown,
415
+ winRate: trades.length > 0 ? wins.length / trades.length : 0,
416
+ avgWin,
417
+ avgLoss,
418
+ profitFactor: avgLoss > 0 ? avgWin / avgLoss : 0,
419
+ };
420
+ }
421
+
422
+ /**
423
+ * Schedule a save (debounced)
424
+ */
425
+ _scheduleSave() {
426
+ if (this.saveTimer) return;
427
+ this.saveTimer = setTimeout(() => {
428
+ this._saveNow();
429
+ this.saveTimer = null;
430
+ }, 5000); // Save every 5 seconds if dirty
431
+ }
432
+
433
+ /**
434
+ * Save immediately
435
+ */
436
+ _saveNow() {
437
+ if (!this.dirty || !this.sessionFile) return;
438
+
439
+ try {
440
+ fs.writeFileSync(this.sessionFile, JSON.stringify(this.data, null, 2));
441
+ this.dirty = false;
442
+ } catch (e) {
443
+ // Silent fail - don't interrupt trading
444
+ }
445
+ }
446
+
447
+ /**
448
+ * Cleanup old sessions
449
+ */
450
+ _cleanup() {
451
+ try {
452
+ const files = fs.readdirSync(HISTORY_DIR)
453
+ .filter(f => f.startsWith('session_') && f.endsWith('.json'))
454
+ .sort();
455
+
456
+ // Remove old sessions beyond MAX_SESSIONS
457
+ if (files.length > MAX_SESSIONS) {
458
+ const toRemove = files.slice(0, files.length - MAX_SESSIONS);
459
+ for (const file of toRemove) {
460
+ fs.unlinkSync(path.join(HISTORY_DIR, file));
461
+ }
462
+ }
463
+ } catch (e) {
464
+ // Silent fail
465
+ }
466
+ }
467
+ }
468
+
469
+ // Singleton instance
470
+ const sessionHistory = new SessionHistory();
471
+
472
+ module.exports = {
473
+ SessionHistory,
474
+ sessionHistory,
475
+ };