hedgequantx 2.6.161 → 2.6.162

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 (42) hide show
  1. package/package.json +1 -1
  2. package/src/menus/ai-agent-connect.js +181 -0
  3. package/src/menus/ai-agent-models.js +219 -0
  4. package/src/menus/ai-agent-oauth.js +292 -0
  5. package/src/menus/ai-agent-ui.js +141 -0
  6. package/src/menus/ai-agent.js +88 -1489
  7. package/src/pages/algo/copy-engine.js +449 -0
  8. package/src/pages/algo/copy-trading.js +11 -543
  9. package/src/pages/algo/smart-logs-data.js +218 -0
  10. package/src/pages/algo/smart-logs.js +9 -214
  11. package/src/pages/algo/ui-constants.js +144 -0
  12. package/src/pages/algo/ui-summary.js +184 -0
  13. package/src/pages/algo/ui.js +42 -526
  14. package/src/pages/stats-calculations.js +191 -0
  15. package/src/pages/stats-ui.js +381 -0
  16. package/src/pages/stats.js +14 -507
  17. package/src/services/ai/client-analysis.js +194 -0
  18. package/src/services/ai/client-models.js +333 -0
  19. package/src/services/ai/client.js +6 -489
  20. package/src/services/ai/index.js +2 -257
  21. package/src/services/ai/proxy-install.js +249 -0
  22. package/src/services/ai/proxy-manager.js +29 -411
  23. package/src/services/ai/proxy-remote.js +161 -0
  24. package/src/services/ai/supervisor-optimize.js +215 -0
  25. package/src/services/ai/supervisor-sync.js +178 -0
  26. package/src/services/ai/supervisor.js +50 -515
  27. package/src/services/ai/validation.js +250 -0
  28. package/src/services/hqx-server-events.js +110 -0
  29. package/src/services/hqx-server-handlers.js +217 -0
  30. package/src/services/hqx-server-latency.js +136 -0
  31. package/src/services/hqx-server.js +51 -403
  32. package/src/services/position-constants.js +28 -0
  33. package/src/services/position-manager.js +105 -554
  34. package/src/services/position-momentum.js +206 -0
  35. package/src/services/projectx/accounts.js +142 -0
  36. package/src/services/projectx/index.js +40 -289
  37. package/src/services/projectx/trading.js +180 -0
  38. package/src/services/rithmic/handlers.js +2 -208
  39. package/src/services/rithmic/index.js +32 -542
  40. package/src/services/rithmic/latency-tracker.js +182 -0
  41. package/src/services/rithmic/specs.js +146 -0
  42. package/src/services/rithmic/trade-history.js +254 -0
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Rithmic Latency Tracking
3
+ * @module services/rithmic/latency-tracker
4
+ *
5
+ * High-precision order-to-fill latency tracking.
6
+ * Uses circular buffer and high-resolution timing.
7
+ */
8
+
9
+ /**
10
+ * Get high-resolution timestamp in nanoseconds
11
+ * @returns {bigint}
12
+ */
13
+ const hrNow = () => process.hrtime.bigint();
14
+
15
+ /**
16
+ * Convert nanoseconds to milliseconds with precision
17
+ * @param {bigint} ns
18
+ * @returns {number}
19
+ */
20
+ const nsToMs = (ns) => Number(ns) / 1_000_000;
21
+
22
+ /**
23
+ * Latency tracker with circular buffer for O(1) operations
24
+ */
25
+ const LatencyTracker = {
26
+ _pending: new Map(), // orderTag -> entryTime (bigint nanoseconds)
27
+ _samples: null, // Pre-allocated Float64Array circular buffer
28
+ _maxSamples: 100,
29
+ _head: 0, // Next write position
30
+ _count: 0, // Number of valid samples
31
+ _initialized: false,
32
+
33
+ /** Initialize circular buffer (lazy init) */
34
+ _init() {
35
+ if (this._initialized) return;
36
+ this._samples = new Float64Array(this._maxSamples);
37
+ this._initialized = true;
38
+ },
39
+
40
+ /** Record order sent time with high-resolution timestamp */
41
+ recordEntry(orderTag, entryTimeMs) {
42
+ this._pending.set(orderTag, hrNow());
43
+ },
44
+
45
+ /** Record fill received, calculate latency with sub-ms precision */
46
+ recordFill(orderTag) {
47
+ const entryTime = this._pending.get(orderTag);
48
+ if (!entryTime) return null;
49
+
50
+ this._pending.delete(orderTag);
51
+ const latencyNs = hrNow() - entryTime;
52
+ const latencyMs = nsToMs(latencyNs);
53
+
54
+ // Store in circular buffer (no shift, O(1))
55
+ this._init();
56
+ this._samples[this._head] = latencyMs;
57
+ this._head = (this._head + 1) % this._maxSamples;
58
+ if (this._count < this._maxSamples) this._count++;
59
+
60
+ return latencyMs;
61
+ },
62
+
63
+ /** Get average latency */
64
+ getAverage() {
65
+ if (this._count === 0) return null;
66
+ let sum = 0;
67
+ for (let i = 0; i < this._count; i++) {
68
+ sum += this._samples[i];
69
+ }
70
+ return sum / this._count;
71
+ },
72
+
73
+ /** Get min/max/avg stats with high precision */
74
+ getStats() {
75
+ if (this._count === 0) {
76
+ return { min: null, max: null, avg: null, p50: null, p99: null, samples: 0 };
77
+ }
78
+
79
+ const valid = [];
80
+ for (let i = 0; i < this._count; i++) {
81
+ valid.push(this._samples[i]);
82
+ }
83
+ valid.sort((a, b) => a - b);
84
+
85
+ const sum = valid.reduce((a, b) => a + b, 0);
86
+
87
+ return {
88
+ min: valid[0],
89
+ max: valid[valid.length - 1],
90
+ avg: sum / valid.length,
91
+ p50: valid[Math.floor(valid.length * 0.5)],
92
+ p99: valid[Math.floor(valid.length * 0.99)] || valid[valid.length - 1],
93
+ samples: this._count,
94
+ };
95
+ },
96
+
97
+ /** Get last N latency samples */
98
+ getRecent(n = 10) {
99
+ if (this._count === 0) return [];
100
+ const result = [];
101
+ const start = this._count < this._maxSamples ? 0 : this._head;
102
+ for (let i = 0; i < Math.min(n, this._count); i++) {
103
+ const idx = (start + this._count - 1 - i + this._maxSamples) % this._maxSamples;
104
+ result.push(this._samples[idx]);
105
+ }
106
+ return result;
107
+ },
108
+
109
+ /** Clear all tracking data */
110
+ clear() {
111
+ this._pending.clear();
112
+ this._head = 0;
113
+ this._count = 0;
114
+ if (this._samples) {
115
+ this._samples.fill(0);
116
+ }
117
+ }
118
+ };
119
+
120
+ /**
121
+ * Pre-allocated fill info pool for zero-allocation in hot path
122
+ */
123
+ const FillInfoPool = {
124
+ _template: {
125
+ orderTag: null,
126
+ basketId: null,
127
+ orderId: null,
128
+ status: null,
129
+ symbol: null,
130
+ exchange: null,
131
+ accountId: null,
132
+ fillQuantity: 0,
133
+ totalFillQuantity: 0,
134
+ remainingQuantity: 0,
135
+ avgFillPrice: 0,
136
+ lastFillPrice: 0,
137
+ transactionType: 0,
138
+ orderType: 0,
139
+ quantity: 0,
140
+ ssboe: 0,
141
+ usecs: 0,
142
+ localTimestamp: 0,
143
+ roundTripLatencyMs: null,
144
+ },
145
+
146
+ /** Fill template with notification data */
147
+ fill(notif, receiveTime, latency) {
148
+ const o = this._template;
149
+ o.orderTag = notif.userTag || null;
150
+ o.basketId = notif.basketId;
151
+ o.orderId = notif.exchangeOrderId || notif.orderId;
152
+ o.status = notif.status;
153
+ o.symbol = notif.symbol;
154
+ o.exchange = notif.exchange;
155
+ o.accountId = notif.accountId;
156
+ o.fillQuantity = notif.totalFillSize || notif.fillQuantity || 0;
157
+ o.totalFillQuantity = notif.totalFillSize || notif.totalFillQuantity || 0;
158
+ o.remainingQuantity = notif.totalUnfilledSize || notif.remainingQuantity || 0;
159
+ o.avgFillPrice = parseFloat(notif.avgFillPrice || 0);
160
+ o.lastFillPrice = parseFloat(notif.price || notif.fillPrice || 0);
161
+ o.transactionType = notif.transactionType;
162
+ o.orderType = notif.priceType || notif.orderType;
163
+ o.quantity = notif.quantity;
164
+ o.ssboe = notif.ssboe;
165
+ o.usecs = notif.usecs;
166
+ o.localTimestamp = receiveTime;
167
+ o.roundTripLatencyMs = latency;
168
+ return o;
169
+ },
170
+
171
+ /** Create a copy for async operations */
172
+ clone(fillInfo) {
173
+ return { ...fillInfo };
174
+ }
175
+ };
176
+
177
+ module.exports = {
178
+ hrNow,
179
+ nsToMs,
180
+ LatencyTracker,
181
+ FillInfoPool,
182
+ };
@@ -0,0 +1,146 @@
1
+ /**
2
+ * @fileoverview Rithmic Specifications and Configurations
3
+ * CME Contract Specifications and PropFirm configurations
4
+ *
5
+ * NO FAKE DATA - These are official exchange constants
6
+ */
7
+
8
+ const { RITHMIC_ENDPOINTS, RITHMIC_SYSTEMS } = require('./constants');
9
+
10
+ /**
11
+ * CME Contract Specifications - Official exchange tick sizes, values, and names
12
+ * These are technical constants defined by the exchange, not market data.
13
+ * Source: CME Group contract specifications
14
+ */
15
+ const CME_CONTRACT_SPECS = {
16
+ // E-mini Index Futures (CME)
17
+ ES: { tickSize: 0.25, tickValue: 12.50, name: 'E-mini S&P 500' },
18
+ NQ: { tickSize: 0.25, tickValue: 5.00, name: 'E-mini NASDAQ-100' },
19
+ RTY: { tickSize: 0.10, tickValue: 5.00, name: 'E-mini Russell 2000' },
20
+ YM: { tickSize: 1.00, tickValue: 5.00, name: 'E-mini Dow' },
21
+
22
+ // Micro Index Futures (CME)
23
+ MES: { tickSize: 0.25, tickValue: 1.25, name: 'Micro E-mini S&P 500' },
24
+ MNQ: { tickSize: 0.25, tickValue: 0.50, name: 'Micro E-mini NASDAQ-100' },
25
+ M2K: { tickSize: 0.10, tickValue: 0.50, name: 'Micro E-mini Russell 2000' },
26
+ MYM: { tickSize: 1.00, tickValue: 0.50, name: 'Micro E-mini Dow' },
27
+
28
+ // Energy Futures (NYMEX)
29
+ CL: { tickSize: 0.01, tickValue: 10.00, name: 'Crude Oil' },
30
+ QM: { tickSize: 0.025, tickValue: 12.50, name: 'E-mini Crude Oil' },
31
+ MCL: { tickSize: 0.01, tickValue: 1.00, name: 'Micro Crude Oil' },
32
+ NG: { tickSize: 0.001, tickValue: 10.00, name: 'Natural Gas' },
33
+ QG: { tickSize: 0.005, tickValue: 12.50, name: 'E-mini Natural Gas' },
34
+
35
+ // Metal Futures (COMEX)
36
+ GC: { tickSize: 0.10, tickValue: 10.00, name: 'Gold' },
37
+ MGC: { tickSize: 0.10, tickValue: 1.00, name: 'Micro Gold' },
38
+ SI: { tickSize: 0.005, tickValue: 25.00, name: 'Silver' },
39
+ SIL: { tickSize: 0.005, tickValue: 2.50, name: '1000oz Silver' },
40
+ HG: { tickSize: 0.0005, tickValue: 12.50, name: 'Copper' },
41
+ MHG: { tickSize: 0.0005, tickValue: 1.25, name: 'Micro Copper' },
42
+
43
+ // Treasury Futures (CBOT)
44
+ ZB: { tickSize: 0.03125, tickValue: 31.25, name: '30-Year T-Bond' },
45
+ ZN: { tickSize: 0.015625, tickValue: 15.625, name: '10-Year T-Note' },
46
+ ZF: { tickSize: 0.0078125, tickValue: 7.8125, name: '5-Year T-Note' },
47
+ ZT: { tickSize: 0.0078125, tickValue: 15.625, name: '2-Year T-Note' },
48
+
49
+ // Agricultural Futures (CBOT)
50
+ ZC: { tickSize: 0.25, tickValue: 12.50, name: 'Corn' },
51
+ ZS: { tickSize: 0.25, tickValue: 12.50, name: 'Soybeans' },
52
+ ZW: { tickSize: 0.25, tickValue: 12.50, name: 'Wheat' },
53
+ ZL: { tickSize: 0.01, tickValue: 6.00, name: 'Soybean Oil' },
54
+ ZM: { tickSize: 0.10, tickValue: 10.00, name: 'Soybean Meal' },
55
+
56
+ // Currency Futures (CME)
57
+ '6E': { tickSize: 0.00005, tickValue: 6.25, name: 'Euro FX' },
58
+ '6J': { tickSize: 0.0000005, tickValue: 6.25, name: 'Japanese Yen' },
59
+ '6B': { tickSize: 0.0001, tickValue: 6.25, name: 'British Pound' },
60
+ '6A': { tickSize: 0.0001, tickValue: 10.00, name: 'Australian Dollar' },
61
+ '6C': { tickSize: 0.00005, tickValue: 5.00, name: 'Canadian Dollar' },
62
+ '6M': { tickSize: 0.0001, tickValue: 5.00, name: 'Mexican Peso' },
63
+
64
+ // Nikkei (CME)
65
+ NKD: { tickSize: 5.0, tickValue: 25.00, name: 'Nikkei 225' },
66
+
67
+ // VIX Futures (CFE)
68
+ VX: { tickSize: 0.05, tickValue: 50.00, name: 'VIX Futures' },
69
+ };
70
+
71
+ /**
72
+ * PropFirm configurations
73
+ */
74
+ const PROPFIRM_CONFIGS = {
75
+ apex: { name: 'Apex Trader Funding', systemName: 'Apex', gateway: RITHMIC_ENDPOINTS.CHICAGO },
76
+ apex_rithmic: { name: 'Apex Trader Funding', systemName: 'Apex', gateway: RITHMIC_ENDPOINTS.CHICAGO },
77
+ topstep_r: { name: 'Topstep (Rithmic)', systemName: RITHMIC_SYSTEMS.TOPSTEP, gateway: RITHMIC_ENDPOINTS.CHICAGO },
78
+ bulenox_r: { name: 'Bulenox (Rithmic)', systemName: RITHMIC_SYSTEMS.BULENOX, gateway: RITHMIC_ENDPOINTS.CHICAGO },
79
+ earn2trade: { name: 'Earn2Trade', systemName: RITHMIC_SYSTEMS.EARN_2_TRADE, gateway: RITHMIC_ENDPOINTS.CHICAGO },
80
+ mescapital: { name: 'MES Capital', systemName: RITHMIC_SYSTEMS.MES_CAPITAL, gateway: RITHMIC_ENDPOINTS.CHICAGO },
81
+ tradefundrr: { name: 'TradeFundrr', systemName: RITHMIC_SYSTEMS.TRADEFUNDRR, gateway: RITHMIC_ENDPOINTS.CHICAGO },
82
+ thetradingpit: { name: 'The Trading Pit', systemName: RITHMIC_SYSTEMS.THE_TRADING_PIT, gateway: RITHMIC_ENDPOINTS.CHICAGO },
83
+ fundedfutures: { name: 'Funded Futures Network', systemName: RITHMIC_SYSTEMS.FUNDED_FUTURES_NETWORK, gateway: RITHMIC_ENDPOINTS.CHICAGO },
84
+ propshop: { name: 'PropShop Trader', systemName: RITHMIC_SYSTEMS.PROPSHOP_TRADER, gateway: RITHMIC_ENDPOINTS.CHICAGO },
85
+ '4proptrader': { name: '4PropTrader', systemName: RITHMIC_SYSTEMS.FOUR_PROP_TRADER, gateway: RITHMIC_ENDPOINTS.CHICAGO },
86
+ daytraders: { name: 'DayTraders.com', systemName: RITHMIC_SYSTEMS.DAY_TRADERS, gateway: RITHMIC_ENDPOINTS.CHICAGO },
87
+ '10xfutures': { name: '10X Futures', systemName: RITHMIC_SYSTEMS.TEN_X_FUTURES, gateway: RITHMIC_ENDPOINTS.CHICAGO },
88
+ lucidtrading: { name: 'Lucid Trading', systemName: RITHMIC_SYSTEMS.LUCID_TRADING, gateway: RITHMIC_ENDPOINTS.CHICAGO },
89
+ thrivetrading: { name: 'Thrive Trading', systemName: RITHMIC_SYSTEMS.THRIVE_TRADING, gateway: RITHMIC_ENDPOINTS.CHICAGO },
90
+ legendstrading: { name: 'Legends Trading', systemName: RITHMIC_SYSTEMS.LEGENDS_TRADING, gateway: RITHMIC_ENDPOINTS.CHICAGO },
91
+ };
92
+
93
+ /**
94
+ * Get tick multiplier for P&L calculation
95
+ * @param {string} symbol - Trading symbol
96
+ * @returns {number} Multiplier for P&L calculation
97
+ */
98
+ const getTickMultiplier = (symbol) => {
99
+ const sym = (symbol || '').toUpperCase();
100
+ if (sym.startsWith('ES')) return 50; // E-mini S&P 500: $50 per point
101
+ if (sym.startsWith('NQ')) return 20; // E-mini Nasdaq: $20 per point
102
+ if (sym.startsWith('YM')) return 5; // E-mini Dow: $5 per point
103
+ if (sym.startsWith('RTY')) return 50; // E-mini Russell: $50 per point
104
+ if (sym.startsWith('MES')) return 5; // Micro E-mini S&P: $5 per point
105
+ if (sym.startsWith('MNQ')) return 2; // Micro E-mini Nasdaq: $2 per point
106
+ if (sym.startsWith('GC')) return 100; // Gold: $100 per point
107
+ if (sym.startsWith('SI')) return 5000; // Silver: $5000 per point
108
+ if (sym.startsWith('CL')) return 1000; // Crude Oil: $1000 per point
109
+ if (sym.startsWith('NG')) return 10000; // Natural Gas: $10000 per point
110
+ if (sym.startsWith('ZB') || sym.startsWith('ZN')) return 1000; // Bonds
111
+ if (sym.startsWith('6E')) return 125000; // Euro FX
112
+ if (sym.startsWith('6J')) return 12500000; // Japanese Yen
113
+ return 1; // Default
114
+ };
115
+
116
+ /**
117
+ * Check market hours
118
+ * @returns {{isOpen: boolean, message: string}}
119
+ */
120
+ const checkMarketHours = () => {
121
+ const now = new Date();
122
+ const utcDay = now.getUTCDay();
123
+ const utcHour = now.getUTCHours();
124
+
125
+ const isDST = now.getTimezoneOffset() < Math.max(
126
+ new Date(now.getFullYear(), 0, 1).getTimezoneOffset(),
127
+ new Date(now.getFullYear(), 6, 1).getTimezoneOffset()
128
+ );
129
+ const ctOffset = isDST ? 5 : 6;
130
+ const ctHour = (utcHour - ctOffset + 24) % 24;
131
+ const ctDay = utcHour < ctOffset ? (utcDay + 6) % 7 : utcDay;
132
+
133
+ if (ctDay === 6) return { isOpen: false, message: 'Market closed (Saturday)' };
134
+ if (ctDay === 0 && ctHour < 17) return { isOpen: false, message: 'Market opens Sunday 5:00 PM CT' };
135
+ if (ctDay === 5 && ctHour >= 16) return { isOpen: false, message: 'Market closed (Friday after 4PM CT)' };
136
+ if (ctHour === 16 && ctDay >= 1 && ctDay <= 4) return { isOpen: false, message: 'Daily maintenance (4:00-5:00 PM CT)' };
137
+
138
+ return { isOpen: true, message: 'Market is open' };
139
+ };
140
+
141
+ module.exports = {
142
+ CME_CONTRACT_SPECS,
143
+ PROPFIRM_CONFIGS,
144
+ getTickMultiplier,
145
+ checkMarketHours,
146
+ };
@@ -0,0 +1,254 @@
1
+ /**
2
+ * @fileoverview Rithmic Trade History
3
+ * Handles trade history fetching and P&L calculation
4
+ *
5
+ * NO FAKE DATA - Only real values from Rithmic API
6
+ */
7
+
8
+ const { logger } = require('../../utils/logger');
9
+ const { getTickMultiplier } = require('./specs');
10
+
11
+ const log = logger.scope('RithmicTradeHistory');
12
+
13
+ /**
14
+ * Get trade history from Rithmic API
15
+ * Uses RequestShowOrderHistory to fetch historical fills
16
+ * @param {Object} service - RithmicService instance
17
+ * @param {string} accountId - Optional account filter
18
+ * @param {number} days - Number of days to fetch (default: 30)
19
+ * @returns {Promise<{success: boolean, trades: Array}>}
20
+ */
21
+ const getTradeHistory = async (service, accountId, days = 30) => {
22
+ if (!service.orderConn || !service.loginInfo) {
23
+ return { success: true, trades: service.completedTrades || [] };
24
+ }
25
+
26
+ return new Promise((resolve) => {
27
+ const historyOrders = [];
28
+ let resolved = false;
29
+
30
+ // Timeout after 5 seconds
31
+ const timeout = setTimeout(() => {
32
+ if (!resolved) {
33
+ resolved = true;
34
+ cleanup();
35
+ // Combine API history with session trades
36
+ const allTrades = [...processHistoryToTrades(historyOrders, service), ...service.completedTrades];
37
+ resolve({ success: true, trades: allTrades });
38
+ }
39
+ }, 5000);
40
+
41
+ // Listen for order history snapshots
42
+ const onOrderNotification = (data) => {
43
+ try {
44
+ if (data.isSnapshot || data.status === 'complete' || data.status === 'Complete') {
45
+ const order = {
46
+ orderId: data.orderId || data.orderTag,
47
+ accountId: data.accountId,
48
+ symbol: data.symbol,
49
+ exchange: data.exchange,
50
+ side: data.transactionType === 1 ? 0 : 1,
51
+ quantity: data.quantity || data.totalFillQuantity || 0,
52
+ fillPrice: data.avgFillPrice || data.lastFillPrice || 0,
53
+ timestamp: data.ssboe ? data.ssboe * 1000 : Date.now(),
54
+ status: data.status,
55
+ };
56
+
57
+ if (order.quantity > 0 && order.fillPrice > 0) {
58
+ historyOrders.push(order);
59
+ }
60
+ }
61
+ } catch (e) {
62
+ // Ignore parse errors
63
+ }
64
+ };
65
+
66
+ const onHistoryComplete = () => {
67
+ if (!resolved) {
68
+ resolved = true;
69
+ cleanup();
70
+ const allTrades = [...processHistoryToTrades(historyOrders, service), ...service.completedTrades];
71
+ resolve({ success: true, trades: allTrades });
72
+ }
73
+ };
74
+
75
+ const cleanup = () => {
76
+ clearTimeout(timeout);
77
+ service.removeListener('orderNotification', onOrderNotification);
78
+ service.removeListener('orderHistoryComplete', onHistoryComplete);
79
+ };
80
+
81
+ service.on('orderNotification', onOrderNotification);
82
+ service.on('orderHistoryComplete', onHistoryComplete);
83
+
84
+ // Request order history for each account
85
+ try {
86
+ const accounts = accountId
87
+ ? service.accounts.filter(a => a.accountId === accountId)
88
+ : service.accounts;
89
+
90
+ for (const acc of accounts) {
91
+ service.orderConn.send('RequestShowOrderHistory', {
92
+ templateId: 324,
93
+ userMsg: ['HQX-HISTORY'],
94
+ fcmId: acc.fcmId || service.loginInfo.fcmId,
95
+ ibId: acc.ibId || service.loginInfo.ibId,
96
+ accountId: acc.accountId,
97
+ });
98
+ }
99
+ } catch (e) {
100
+ if (!resolved) {
101
+ resolved = true;
102
+ cleanup();
103
+ resolve({ success: false, error: e.message, trades: service.completedTrades || [] });
104
+ }
105
+ }
106
+ });
107
+ };
108
+
109
+ /**
110
+ * Process historical orders into trades with P&L
111
+ * Matches entries and exits to calculate P&L
112
+ * @param {Array} orders - Historical orders
113
+ * @param {Object} service - RithmicService instance (for _getTickMultiplier)
114
+ * @returns {Array} Processed trades
115
+ */
116
+ const processHistoryToTrades = (orders, service) => {
117
+ const trades = [];
118
+ const openPositions = new Map();
119
+
120
+ // Sort by timestamp (oldest first)
121
+ const sorted = [...orders].sort((a, b) => a.timestamp - b.timestamp);
122
+
123
+ for (const order of sorted) {
124
+ const key = `${order.accountId}:${order.symbol}`;
125
+ const open = openPositions.get(key);
126
+
127
+ if (open && open.side !== order.side) {
128
+ // Closing trade - calculate P&L
129
+ const closeQty = Math.min(order.quantity, open.quantity);
130
+ let pnl;
131
+
132
+ if (open.side === 0) {
133
+ pnl = (order.fillPrice - open.price) * closeQty;
134
+ } else {
135
+ pnl = (open.price - order.fillPrice) * closeQty;
136
+ }
137
+
138
+ const tickMultiplier = getTickMultiplier(order.symbol);
139
+ pnl = pnl * tickMultiplier;
140
+
141
+ trades.push({
142
+ id: order.orderId,
143
+ accountId: order.accountId,
144
+ symbol: order.symbol,
145
+ exchange: order.exchange,
146
+ side: open.side,
147
+ size: closeQty,
148
+ entryPrice: open.price,
149
+ exitPrice: order.fillPrice,
150
+ price: order.fillPrice,
151
+ timestamp: order.timestamp,
152
+ creationTimestamp: new Date(order.timestamp).toISOString(),
153
+ status: 'CLOSED',
154
+ profitAndLoss: pnl,
155
+ pnl: pnl,
156
+ fees: 0,
157
+ });
158
+
159
+ const remaining = open.quantity - closeQty;
160
+ if (remaining <= 0) {
161
+ openPositions.delete(key);
162
+ } else {
163
+ open.quantity = remaining;
164
+ }
165
+ } else if (open && open.side === order.side) {
166
+ // Adding to position
167
+ const totalQty = open.quantity + order.quantity;
168
+ open.price = ((open.price * open.quantity) + (order.fillPrice * order.quantity)) / totalQty;
169
+ open.quantity = totalQty;
170
+ } else {
171
+ // Opening new position
172
+ openPositions.set(key, {
173
+ side: order.side,
174
+ quantity: order.quantity,
175
+ price: order.fillPrice,
176
+ timestamp: order.timestamp,
177
+ });
178
+ }
179
+ }
180
+
181
+ return trades;
182
+ };
183
+
184
+ /**
185
+ * Setup order fill listener for real-time P&L tracking
186
+ * @param {Object} service - RithmicService instance
187
+ */
188
+ const setupOrderFillListener = (service) => {
189
+ service._openEntries = new Map();
190
+
191
+ service.on('orderFilled', (fillInfo) => {
192
+ const key = `${fillInfo.accountId}:${fillInfo.symbol}`;
193
+ const side = fillInfo.transactionType === 1 ? 0 : 1;
194
+ const qty = fillInfo.fillQuantity || fillInfo.totalFillQuantity || 0;
195
+ const price = fillInfo.avgFillPrice || fillInfo.lastFillPrice || 0;
196
+
197
+ const openEntry = service._openEntries.get(key);
198
+ let pnl = null;
199
+
200
+ if (openEntry && openEntry.side !== side) {
201
+ // Closing trade
202
+ const closeQty = Math.min(qty, openEntry.qty);
203
+
204
+ if (openEntry.side === 0) {
205
+ pnl = (price - openEntry.price) * closeQty;
206
+ } else {
207
+ pnl = (openEntry.price - price) * closeQty;
208
+ }
209
+
210
+ const remainingQty = openEntry.qty - closeQty;
211
+ if (remainingQty <= 0) {
212
+ service._openEntries.delete(key);
213
+ } else {
214
+ openEntry.qty = remainingQty;
215
+ }
216
+
217
+ service.completedTrades.push({
218
+ id: fillInfo.orderId || fillInfo.orderTag,
219
+ orderTag: fillInfo.orderTag,
220
+ accountId: fillInfo.accountId,
221
+ symbol: fillInfo.symbol,
222
+ exchange: fillInfo.exchange,
223
+ side: openEntry.side,
224
+ size: closeQty,
225
+ entryPrice: openEntry.price,
226
+ exitPrice: price,
227
+ price: price,
228
+ timestamp: fillInfo.localTimestamp || Date.now(),
229
+ creationTimestamp: new Date().toISOString(),
230
+ status: 'CLOSED',
231
+ profitAndLoss: pnl,
232
+ pnl: pnl,
233
+ fees: 0,
234
+ });
235
+ log.debug('Trade closed', { symbol: fillInfo.symbol, pnl, trades: service.completedTrades.length });
236
+ } else {
237
+ // Opening or adding to position
238
+ if (openEntry && openEntry.side === side) {
239
+ const totalQty = openEntry.qty + qty;
240
+ openEntry.price = ((openEntry.price * openEntry.qty) + (price * qty)) / totalQty;
241
+ openEntry.qty = totalQty;
242
+ } else {
243
+ service._openEntries.set(key, { side, qty, price, timestamp: Date.now() });
244
+ }
245
+ log.debug('Position opened/added', { symbol: fillInfo.symbol, side, qty, price });
246
+ }
247
+ });
248
+ };
249
+
250
+ module.exports = {
251
+ getTradeHistory,
252
+ processHistoryToTrades,
253
+ setupOrderFillListener,
254
+ };