hedgequantx 2.6.163 → 2.7.1
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/README.md +15 -88
- package/bin/cli.js +0 -11
- package/dist/lib/api.jsc +0 -0
- package/dist/lib/api2.jsc +0 -0
- package/dist/lib/core.jsc +0 -0
- package/dist/lib/core2.jsc +0 -0
- package/dist/lib/data.js +1 -1
- package/dist/lib/data.jsc +0 -0
- package/dist/lib/data2.jsc +0 -0
- package/dist/lib/decoder.jsc +0 -0
- package/dist/lib/m/mod1.jsc +0 -0
- package/dist/lib/m/mod2.jsc +0 -0
- package/dist/lib/n/r1.jsc +0 -0
- package/dist/lib/n/r2.jsc +0 -0
- package/dist/lib/n/r3.jsc +0 -0
- package/dist/lib/n/r4.jsc +0 -0
- package/dist/lib/n/r5.jsc +0 -0
- package/dist/lib/n/r6.jsc +0 -0
- package/dist/lib/n/r7.jsc +0 -0
- package/dist/lib/o/util1.jsc +0 -0
- package/dist/lib/o/util2.jsc +0 -0
- package/package.json +8 -5
- package/src/app.js +40 -162
- package/src/config/constants.js +31 -33
- package/src/config/propfirms.js +13 -217
- package/src/config/settings.js +0 -43
- package/src/lib/api.js +198 -0
- package/src/lib/api2.js +353 -0
- package/src/lib/core.js +539 -0
- package/src/lib/core2.js +341 -0
- package/src/lib/data.js +555 -0
- package/src/lib/data2.js +492 -0
- package/src/lib/decoder.js +599 -0
- package/src/lib/m/s1.js +804 -0
- package/src/lib/m/s2.js +34 -0
- package/src/lib/n/r1.js +454 -0
- package/src/lib/n/r2.js +514 -0
- package/src/lib/n/r3.js +631 -0
- package/src/lib/n/r4.js +401 -0
- package/src/lib/n/r5.js +335 -0
- package/src/lib/n/r6.js +425 -0
- package/src/lib/n/r7.js +530 -0
- package/src/lib/o/l1.js +44 -0
- package/src/lib/o/l2.js +427 -0
- package/src/lib/python-bridge.js +206 -0
- package/src/menus/connect.js +14 -176
- package/src/menus/dashboard.js +65 -110
- package/src/pages/accounts.js +18 -18
- package/src/pages/algo/copy-trading.js +210 -240
- package/src/pages/algo/index.js +41 -104
- package/src/pages/algo/one-account.js +386 -33
- package/src/pages/algo/ui.js +312 -151
- package/src/pages/orders.js +3 -3
- package/src/pages/positions.js +3 -3
- package/src/pages/stats/chart.js +74 -0
- package/src/pages/stats/display.js +228 -0
- package/src/pages/stats/index.js +236 -0
- package/src/pages/stats/metrics.js +213 -0
- package/src/pages/user.js +6 -6
- package/src/services/hqx-server/constants.js +55 -0
- package/src/services/hqx-server/index.js +401 -0
- package/src/services/hqx-server/latency.js +81 -0
- package/src/services/index.js +12 -3
- package/src/services/rithmic/accounts.js +7 -32
- package/src/services/rithmic/connection.js +1 -204
- package/src/services/rithmic/contracts.js +116 -99
- package/src/services/rithmic/handlers.js +21 -196
- package/src/services/rithmic/index.js +63 -120
- package/src/services/rithmic/market.js +31 -0
- package/src/services/rithmic/orders.js +5 -111
- package/src/services/rithmic/protobuf.js +384 -138
- package/src/services/session.js +22 -173
- package/src/ui/box.js +10 -18
- package/src/ui/index.js +1 -3
- package/src/ui/menu.js +1 -1
- package/src/utils/prompts.js +2 -2
- package/dist/lib/m/s1.js +0 -1
- package/src/menus/ai-agent-connect.js +0 -181
- package/src/menus/ai-agent-models.js +0 -219
- package/src/menus/ai-agent-oauth.js +0 -292
- package/src/menus/ai-agent-ui.js +0 -141
- package/src/menus/ai-agent.js +0 -484
- package/src/pages/algo/algo-config.js +0 -195
- package/src/pages/algo/algo-multi.js +0 -801
- package/src/pages/algo/algo-utils.js +0 -58
- package/src/pages/algo/copy-engine.js +0 -449
- package/src/pages/algo/custom-strategy.js +0 -459
- package/src/pages/algo/logger.js +0 -245
- package/src/pages/algo/smart-logs-data.js +0 -218
- package/src/pages/algo/smart-logs.js +0 -387
- package/src/pages/algo/ui-constants.js +0 -144
- package/src/pages/algo/ui-summary.js +0 -184
- package/src/pages/stats-calculations.js +0 -191
- package/src/pages/stats-ui.js +0 -381
- package/src/pages/stats.js +0 -339
- package/src/services/ai/client-analysis.js +0 -194
- package/src/services/ai/client-models.js +0 -333
- package/src/services/ai/client.js +0 -343
- package/src/services/ai/index.js +0 -384
- package/src/services/ai/oauth-anthropic.js +0 -265
- package/src/services/ai/oauth-gemini.js +0 -223
- package/src/services/ai/oauth-iflow.js +0 -269
- package/src/services/ai/oauth-openai.js +0 -233
- package/src/services/ai/oauth-qwen.js +0 -279
- package/src/services/ai/providers/direct-providers.js +0 -323
- package/src/services/ai/providers/index.js +0 -62
- package/src/services/ai/providers/other-providers.js +0 -104
- package/src/services/ai/proxy-install.js +0 -249
- package/src/services/ai/proxy-manager.js +0 -494
- package/src/services/ai/proxy-remote.js +0 -161
- package/src/services/ai/strategy-supervisor.js +0 -1312
- package/src/services/ai/supervisor-data.js +0 -195
- package/src/services/ai/supervisor-optimize.js +0 -215
- package/src/services/ai/supervisor-sync.js +0 -178
- package/src/services/ai/supervisor-utils.js +0 -158
- package/src/services/ai/supervisor.js +0 -484
- package/src/services/ai/validation.js +0 -250
- package/src/services/hqx-server-events.js +0 -110
- package/src/services/hqx-server-handlers.js +0 -217
- package/src/services/hqx-server-latency.js +0 -136
- package/src/services/hqx-server.js +0 -403
- package/src/services/position-constants.js +0 -28
- package/src/services/position-exit-logic.js +0 -174
- package/src/services/position-manager.js +0 -438
- package/src/services/position-momentum.js +0 -206
- package/src/services/projectx/accounts.js +0 -142
- package/src/services/projectx/index.js +0 -443
- package/src/services/projectx/market.js +0 -172
- package/src/services/projectx/stats.js +0 -110
- package/src/services/projectx/trading.js +0 -180
- package/src/services/rithmic/latency-tracker.js +0 -182
- package/src/services/rithmic/market-data-decoders.js +0 -229
- package/src/services/rithmic/market-data.js +0 -272
- package/src/services/rithmic/orders-fast.js +0 -246
- package/src/services/rithmic/proto-decoders.js +0 -403
- package/src/services/rithmic/specs.js +0 -146
- package/src/services/rithmic/trade-history.js +0 -254
- package/src/services/session-history.js +0 -475
- package/src/services/strategy/hft-signal-calc.js +0 -147
- package/src/services/strategy/hft-tick.js +0 -407
- package/src/services/strategy/recovery-math.js +0 -402
- package/src/services/tradovate/constants.js +0 -109
- package/src/services/tradovate/index.js +0 -392
- package/src/services/tradovate/market.js +0 -47
- package/src/services/tradovate/orders.js +0 -145
- package/src/services/tradovate/websocket.js +0 -97
package/src/lib/data2.js
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rithmic Market Data Feed
|
|
3
|
+
* Connects to Rithmic via WebSocket/Protobuf for real-time market data
|
|
4
|
+
* Used for Apex, TopstepTrader (Rithmic), Bulenox (Rithmic), etc.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const EventEmitter = require('events');
|
|
8
|
+
const WebSocket = require('ws');
|
|
9
|
+
const protobuf = require('protobufjs');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
|
|
12
|
+
// Rithmic Gateway Endpoints
|
|
13
|
+
const RITHMIC_GATEWAYS = {
|
|
14
|
+
CHICAGO: 'wss://rprotocol.rithmic.com:443',
|
|
15
|
+
EUROPE: 'wss://rprotocol-ie.rithmic.com:443',
|
|
16
|
+
FRANKFURT: 'wss://rprotocol-de.rithmic.com:443',
|
|
17
|
+
SINGAPORE: 'wss://rprotocol-sg.rithmic.com:443',
|
|
18
|
+
SYDNEY: 'wss://rprotocol-au.rithmic.com:443',
|
|
19
|
+
TOKYO: 'wss://rprotocol-jp.rithmic.com:443',
|
|
20
|
+
TEST: 'wss://rituz00100.rithmic.com:443',
|
|
21
|
+
PAPER: 'wss://ritpa11120.11.rithmic.com:443'
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// Rithmic System Names for PropFirms
|
|
25
|
+
const RITHMIC_SYSTEMS = {
|
|
26
|
+
'apex': 'Apex',
|
|
27
|
+
'apex_rithmic': 'Apex',
|
|
28
|
+
'topsteptrader': 'TopstepTrader',
|
|
29
|
+
'topstep_r': 'TopstepTrader',
|
|
30
|
+
'bulenox_r': 'Bulenox',
|
|
31
|
+
'mescapital': 'MES Capital',
|
|
32
|
+
'earn2trade': 'Earn2Trade',
|
|
33
|
+
'tradefundrr': 'TradeFundrr',
|
|
34
|
+
'thetradingpit': 'TheTradingPit',
|
|
35
|
+
'fundedfutures': 'FundedFuturesNetwork',
|
|
36
|
+
'propshop': 'PropShopTrader',
|
|
37
|
+
'4proptrader': '4PropTrader',
|
|
38
|
+
'daytraders': 'DayTraders.com',
|
|
39
|
+
'10xfutures': '10XFutures',
|
|
40
|
+
'lucidtrading': 'LucidTrading',
|
|
41
|
+
'thrivetrading': 'ThriveTrading',
|
|
42
|
+
'legendstrading': 'LegendsTrading'
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// Proto path
|
|
46
|
+
const PROTO_PATH = path.join(__dirname, '../../protos/rithmic');
|
|
47
|
+
|
|
48
|
+
class RithmicMarketDataFeed extends EventEmitter {
|
|
49
|
+
constructor(config) {
|
|
50
|
+
super();
|
|
51
|
+
|
|
52
|
+
this.config = config;
|
|
53
|
+
this.ws = null;
|
|
54
|
+
this.isConnected = false;
|
|
55
|
+
this.reconnectAttempts = 0;
|
|
56
|
+
this.maxReconnectAttempts = 5;
|
|
57
|
+
this.subscriptions = new Set();
|
|
58
|
+
this.protoRoot = null;
|
|
59
|
+
|
|
60
|
+
// Message types
|
|
61
|
+
this.RequestLogin = null;
|
|
62
|
+
this.ResponseLogin = null;
|
|
63
|
+
this.RequestMarketDataUpdate = null;
|
|
64
|
+
this.LastTrade = null;
|
|
65
|
+
this.BestBidOffer = null;
|
|
66
|
+
|
|
67
|
+
// Data state
|
|
68
|
+
this.lastTick = new Map();
|
|
69
|
+
this.lastBid = 0;
|
|
70
|
+
this.lastAsk = 0;
|
|
71
|
+
this.lastPrice = 0;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Load protobuf definitions
|
|
76
|
+
*/
|
|
77
|
+
async _loadProtos() {
|
|
78
|
+
if (this.protoRoot) return;
|
|
79
|
+
|
|
80
|
+
try {
|
|
81
|
+
this.protoRoot = await protobuf.load([
|
|
82
|
+
path.join(PROTO_PATH, 'request_login.proto'),
|
|
83
|
+
path.join(PROTO_PATH, 'response_login.proto'),
|
|
84
|
+
path.join(PROTO_PATH, 'request_market_data_update.proto'),
|
|
85
|
+
path.join(PROTO_PATH, 'last_trade.proto'),
|
|
86
|
+
path.join(PROTO_PATH, 'best_bid_offer.proto'),
|
|
87
|
+
path.join(PROTO_PATH, 'request_heartbeat.proto'),
|
|
88
|
+
path.join(PROTO_PATH, 'response_heartbeat.proto')
|
|
89
|
+
]);
|
|
90
|
+
|
|
91
|
+
this.RequestLogin = this.protoRoot.lookupType('rti.RequestLogin');
|
|
92
|
+
this.ResponseLogin = this.protoRoot.lookupType('rti.ResponseLogin');
|
|
93
|
+
this.RequestMarketDataUpdate = this.protoRoot.lookupType('rti.RequestMarketDataUpdate');
|
|
94
|
+
this.LastTrade = this.protoRoot.lookupType('rti.LastTrade');
|
|
95
|
+
this.BestBidOffer = this.protoRoot.lookupType('rti.BestBidOffer');
|
|
96
|
+
this.RequestHeartbeat = this.protoRoot.lookupType('rti.RequestHeartbeat');
|
|
97
|
+
this.ResponseHeartbeat = this.protoRoot.lookupType('rti.ResponseHeartbeat');
|
|
98
|
+
|
|
99
|
+
console.log('[RITHMIC] Protos loaded successfully');
|
|
100
|
+
} catch (error) {
|
|
101
|
+
console.error('[RITHMIC] Failed to load protos:', error.message);
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Connect to Rithmic market data feed
|
|
108
|
+
* @param {Object} credentials - { userId, password, systemName, gateway }
|
|
109
|
+
*/
|
|
110
|
+
async connect(credentials) {
|
|
111
|
+
await this._loadProtos();
|
|
112
|
+
|
|
113
|
+
const { userId, password, systemName, gateway } = credentials;
|
|
114
|
+
const gatewayUrl = gateway || RITHMIC_GATEWAYS.CHICAGO;
|
|
115
|
+
|
|
116
|
+
console.log(`[RITHMIC] Connecting to ${gatewayUrl} as ${userId} on ${systemName}`);
|
|
117
|
+
|
|
118
|
+
return new Promise((resolve, reject) => {
|
|
119
|
+
this.ws = new WebSocket(gatewayUrl, {
|
|
120
|
+
rejectUnauthorized: false
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
const timeout = setTimeout(() => {
|
|
124
|
+
this.ws.close();
|
|
125
|
+
reject(new Error('Connection timeout'));
|
|
126
|
+
}, 15000);
|
|
127
|
+
|
|
128
|
+
this.ws.on('open', async () => {
|
|
129
|
+
console.log('[RITHMIC] WebSocket connected, sending login...');
|
|
130
|
+
|
|
131
|
+
try {
|
|
132
|
+
await this._sendLogin(userId, password, systemName);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
clearTimeout(timeout);
|
|
135
|
+
reject(error);
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
this.ws.on('message', (data) => {
|
|
140
|
+
// Debug: log raw message receipt
|
|
141
|
+
this.rawMsgCount = (this.rawMsgCount || 0) + 1;
|
|
142
|
+
if (this.rawMsgCount <= 5 || this.rawMsgCount % 50 === 0) {
|
|
143
|
+
console.log(`[RITHMIC] Raw message #${this.rawMsgCount} received: ${data.length || data.byteLength} bytes`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
this._handleMessage(data, (success, error) => {
|
|
147
|
+
if (success !== undefined) {
|
|
148
|
+
clearTimeout(timeout);
|
|
149
|
+
if (success) {
|
|
150
|
+
this.isConnected = true;
|
|
151
|
+
this.reconnectAttempts = 0;
|
|
152
|
+
this._startHeartbeat();
|
|
153
|
+
this.emit('connected');
|
|
154
|
+
resolve(true);
|
|
155
|
+
} else {
|
|
156
|
+
reject(new Error(error || 'Login failed'));
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
this.ws.on('error', (error) => {
|
|
163
|
+
console.error('[RITHMIC] WebSocket error:', error.message);
|
|
164
|
+
this.emit('error', error);
|
|
165
|
+
clearTimeout(timeout);
|
|
166
|
+
reject(error);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
this.ws.on('close', (code, reason) => {
|
|
170
|
+
console.log(`[RITHMIC] WebSocket closed: ${code} - ${reason}`);
|
|
171
|
+
this.isConnected = false;
|
|
172
|
+
this._stopHeartbeat();
|
|
173
|
+
this.emit('disconnected', { code, reason: reason.toString() });
|
|
174
|
+
this._attemptReconnect(credentials);
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Send login request
|
|
181
|
+
*/
|
|
182
|
+
async _sendLogin(userId, password, systemName) {
|
|
183
|
+
// Template ID 10 = RequestLogin
|
|
184
|
+
// Field names must match proto (snake_case): template_id, template_version, etc.
|
|
185
|
+
const loginRequest = this.RequestLogin.create({
|
|
186
|
+
templateId: 10, // template_id = 154467, value = 10
|
|
187
|
+
templateVersion: '3.9', // template_version = 153634
|
|
188
|
+
user: userId, // user = 131003
|
|
189
|
+
password: password, // password = 130004
|
|
190
|
+
appName: 'App', // app_name = 130002
|
|
191
|
+
appVersion: '1.0.0', // app_version = 131803
|
|
192
|
+
systemName: systemName, // system_name = 153628
|
|
193
|
+
infraType: 1 // infra_type = 153621, TICKER_PLANT = 1
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
console.log('[RITHMIC] Login message:', JSON.stringify(loginRequest));
|
|
197
|
+
|
|
198
|
+
const buffer = this.RequestLogin.encode(loginRequest).finish();
|
|
199
|
+
console.log('[RITHMIC] Login buffer size:', buffer.length);
|
|
200
|
+
console.log('[RITHMIC] Login buffer hex:', Buffer.from(buffer).toString('hex').slice(0, 100) + '...');
|
|
201
|
+
|
|
202
|
+
this.ws.send(buffer);
|
|
203
|
+
console.log('[RITHMIC] Login request sent');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Handle incoming message
|
|
208
|
+
*/
|
|
209
|
+
_handleMessage(data, loginCallback) {
|
|
210
|
+
try {
|
|
211
|
+
const buffer = new Uint8Array(data);
|
|
212
|
+
|
|
213
|
+
// Log message count
|
|
214
|
+
this.msgCount = (this.msgCount || 0) + 1;
|
|
215
|
+
if (this.msgCount <= 20 || this.msgCount % 100 === 0) {
|
|
216
|
+
console.log(`[RITHMIC] Message #${this.msgCount}: ${buffer.length} bytes`);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Try to decode as ResponseLogin first
|
|
220
|
+
try {
|
|
221
|
+
const response = this.ResponseLogin.decode(buffer);
|
|
222
|
+
console.log(`[RITHMIC] Decoded response - templateId: ${response.templateId}, rpCode: ${JSON.stringify(response.rpCode)}`);
|
|
223
|
+
|
|
224
|
+
// Template ID 11 is ResponseLogin
|
|
225
|
+
if (response.templateId === 11) {
|
|
226
|
+
const rpCode = Array.isArray(response.rpCode) ? response.rpCode[0] : response.rpCode;
|
|
227
|
+
|
|
228
|
+
if (rpCode === '0') {
|
|
229
|
+
console.log('[RITHMIC] Login successful!');
|
|
230
|
+
console.log(`[RITHMIC] FCM: ${response.fcmId}, IB: ${response.ibId}`);
|
|
231
|
+
loginCallback(true);
|
|
232
|
+
} else {
|
|
233
|
+
console.log(`[RITHMIC] Login failed: ${response.textMsg || rpCode}`);
|
|
234
|
+
loginCallback(false, response.textMsg || `Error code: ${rpCode}`);
|
|
235
|
+
}
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Template ID 75 is RejectRequest (error)
|
|
240
|
+
if (response.templateId === 75) {
|
|
241
|
+
const errorMsg = Array.isArray(response.rpCode) ? response.rpCode.join(' - ') : response.rpCode;
|
|
242
|
+
console.log(`[RITHMIC] Request rejected: ${errorMsg}`);
|
|
243
|
+
loginCallback(false, errorMsg);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
} catch (e) {
|
|
247
|
+
// Not a login response, try other decoders
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Use manual decoder for market data (protobufjs can't handle large field IDs)
|
|
251
|
+
const { getTemplateId, decodeLastTrade, decodeBestBidOffer } = require('./decoder');
|
|
252
|
+
const nodeBuffer = Buffer.from(buffer);
|
|
253
|
+
const templateId = getTemplateId(nodeBuffer);
|
|
254
|
+
|
|
255
|
+
// LastTrade (template_id = 150)
|
|
256
|
+
if (templateId === 150) {
|
|
257
|
+
const trade = decodeLastTrade(nodeBuffer);
|
|
258
|
+
this._handleTrade(trade);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// BestBidOffer (template_id = 151)
|
|
263
|
+
if (templateId === 151) {
|
|
264
|
+
const quote = decodeBestBidOffer(nodeBuffer);
|
|
265
|
+
this._handleQuote(quote);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// Try heartbeat response
|
|
270
|
+
try {
|
|
271
|
+
const heartbeat = this.ResponseHeartbeat.decode(buffer);
|
|
272
|
+
if (heartbeat.templateId === 19) {
|
|
273
|
+
// Heartbeat acknowledged
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
} catch (e) {
|
|
277
|
+
// Not a heartbeat
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
} catch (error) {
|
|
281
|
+
console.error('[RITHMIC] Message decode error:', error.message);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Handle trade data
|
|
287
|
+
*/
|
|
288
|
+
_handleTrade(trade) {
|
|
289
|
+
const price = trade.tradePrice || 0;
|
|
290
|
+
const size = trade.tradeSize || 1;
|
|
291
|
+
|
|
292
|
+
// Determine side from aggressor field, or infer from bid/ask
|
|
293
|
+
let side = 'unknown';
|
|
294
|
+
if (trade.aggressor === 1) {
|
|
295
|
+
side = 'buy';
|
|
296
|
+
} else if (trade.aggressor === 2) {
|
|
297
|
+
side = 'sell';
|
|
298
|
+
} else if (this.lastBid > 0 && this.lastAsk > 0) {
|
|
299
|
+
// Infer from price vs bid/ask
|
|
300
|
+
if (price >= this.lastAsk) {
|
|
301
|
+
side = 'buy'; // Bought at ask (aggressor buyer)
|
|
302
|
+
} else if (price <= this.lastBid) {
|
|
303
|
+
side = 'sell'; // Sold at bid (aggressor seller)
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Debug log every 500th trade
|
|
308
|
+
this.tradeCount = (this.tradeCount || 0) + 1;
|
|
309
|
+
if (this.tradeCount % 500 === 1) {
|
|
310
|
+
console.log(`[RITHMIC:MarketData] Trade #${this.tradeCount}: ${trade.symbol} @ ${price} x ${size} (${side})`);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
if (price > 0) {
|
|
314
|
+
this.lastPrice = price;
|
|
315
|
+
|
|
316
|
+
const tradeData = {
|
|
317
|
+
type: 'trade',
|
|
318
|
+
symbol: trade.symbol || this.config.symbol,
|
|
319
|
+
price: price,
|
|
320
|
+
size: size,
|
|
321
|
+
side: side,
|
|
322
|
+
volume: size,
|
|
323
|
+
timestamp: Date.now()
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
this.emit('trade', tradeData);
|
|
327
|
+
this.emit('tick', {
|
|
328
|
+
price: price,
|
|
329
|
+
bid: this.lastBid,
|
|
330
|
+
ask: this.lastAsk,
|
|
331
|
+
volume: size,
|
|
332
|
+
timestamp: Date.now()
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Handle quote data
|
|
339
|
+
*/
|
|
340
|
+
_handleQuote(quote) {
|
|
341
|
+
const bid = quote.bidPrice || 0;
|
|
342
|
+
const ask = quote.askPrice || 0;
|
|
343
|
+
|
|
344
|
+
if (bid > 0) this.lastBid = bid;
|
|
345
|
+
if (ask > 0) this.lastAsk = ask;
|
|
346
|
+
|
|
347
|
+
// Only emit if we have valid bid AND ask
|
|
348
|
+
if (this.lastBid <= 0 || this.lastAsk <= 0) return;
|
|
349
|
+
|
|
350
|
+
const quoteData = {
|
|
351
|
+
type: 'quote',
|
|
352
|
+
symbol: quote.symbol || this.config.symbol,
|
|
353
|
+
bid: this.lastBid,
|
|
354
|
+
ask: this.lastAsk,
|
|
355
|
+
bidSize: quote.bidSize || 0,
|
|
356
|
+
askSize: quote.askSize || 0,
|
|
357
|
+
spread: this.lastAsk - this.lastBid,
|
|
358
|
+
price: this.lastPrice || this.lastBid, // Use last trade price, fallback to bid
|
|
359
|
+
timestamp: Date.now()
|
|
360
|
+
};
|
|
361
|
+
|
|
362
|
+
this.emit('quote', quoteData);
|
|
363
|
+
this.emit('tick', {
|
|
364
|
+
price: quoteData.price,
|
|
365
|
+
bid: this.lastBid,
|
|
366
|
+
ask: this.lastAsk,
|
|
367
|
+
spread: quoteData.spread,
|
|
368
|
+
timestamp: Date.now()
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Subscribe to symbol market data
|
|
374
|
+
*/
|
|
375
|
+
async subscribe(symbol, exchange = 'CME') {
|
|
376
|
+
if (!this.isConnected || !this.ws) {
|
|
377
|
+
throw new Error('Not connected');
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
console.log(`[RITHMIC] Subscribing to ${symbol} on ${exchange}`);
|
|
381
|
+
|
|
382
|
+
// Template ID 100 = RequestMarketDataUpdate
|
|
383
|
+
const request = this.RequestMarketDataUpdate.create({
|
|
384
|
+
templateId: 100,
|
|
385
|
+
symbol: symbol,
|
|
386
|
+
exchange: exchange,
|
|
387
|
+
request: 1, // Subscribe
|
|
388
|
+
updateBits: 3 // LAST_TRADE (1) + BBO (2)
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
const buffer = this.RequestMarketDataUpdate.encode(request).finish();
|
|
392
|
+
this.ws.send(buffer);
|
|
393
|
+
|
|
394
|
+
this.subscriptions.add(`${symbol}:${exchange}`);
|
|
395
|
+
console.log(`[RITHMIC] Subscribed to ${symbol}`);
|
|
396
|
+
|
|
397
|
+
return true;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Unsubscribe from symbol
|
|
402
|
+
*/
|
|
403
|
+
async unsubscribe(symbol, exchange = 'CME') {
|
|
404
|
+
if (!this.isConnected || !this.ws) return;
|
|
405
|
+
|
|
406
|
+
const request = this.RequestMarketDataUpdate.create({
|
|
407
|
+
templateId: 100,
|
|
408
|
+
symbol: symbol,
|
|
409
|
+
exchange: exchange,
|
|
410
|
+
request: 2 // Unsubscribe
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
const buffer = this.RequestMarketDataUpdate.encode(request).finish();
|
|
414
|
+
this.ws.send(buffer);
|
|
415
|
+
|
|
416
|
+
this.subscriptions.delete(`${symbol}:${exchange}`);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Start heartbeat
|
|
421
|
+
*/
|
|
422
|
+
_startHeartbeat() {
|
|
423
|
+
this.heartbeatInterval = setInterval(() => {
|
|
424
|
+
if (this.isConnected && this.ws && this.RequestHeartbeat) {
|
|
425
|
+
const heartbeat = this.RequestHeartbeat.create({
|
|
426
|
+
templateId: 18
|
|
427
|
+
});
|
|
428
|
+
const buffer = this.RequestHeartbeat.encode(heartbeat).finish();
|
|
429
|
+
this.ws.send(buffer);
|
|
430
|
+
}
|
|
431
|
+
}, 30000);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Stop heartbeat
|
|
436
|
+
*/
|
|
437
|
+
_stopHeartbeat() {
|
|
438
|
+
if (this.heartbeatInterval) {
|
|
439
|
+
clearInterval(this.heartbeatInterval);
|
|
440
|
+
this.heartbeatInterval = null;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Attempt reconnection
|
|
446
|
+
*/
|
|
447
|
+
_attemptReconnect(credentials) {
|
|
448
|
+
// Don't reconnect if intentionally disconnected
|
|
449
|
+
if (this.intentionalDisconnect) {
|
|
450
|
+
this.intentionalDisconnect = false;
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
if (this.reconnectAttempts < this.maxReconnectAttempts) {
|
|
455
|
+
this.reconnectAttempts++;
|
|
456
|
+
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
|
|
457
|
+
|
|
458
|
+
console.log(`[RITHMIC] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
|
|
459
|
+
|
|
460
|
+
setTimeout(() => {
|
|
461
|
+
this.connect(credentials).catch(err => {
|
|
462
|
+
console.error('[RITHMIC] Reconnect failed:', err.message);
|
|
463
|
+
});
|
|
464
|
+
}, delay);
|
|
465
|
+
} else {
|
|
466
|
+
console.error('[RITHMIC] Max reconnect attempts reached');
|
|
467
|
+
this.emit('error', new Error('Max reconnect attempts reached'));
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Disconnect
|
|
473
|
+
*/
|
|
474
|
+
async disconnect() {
|
|
475
|
+
this._stopHeartbeat();
|
|
476
|
+
this.subscriptions.clear();
|
|
477
|
+
this.intentionalDisconnect = true; // Prevent reconnect attempts
|
|
478
|
+
|
|
479
|
+
if (this.ws) {
|
|
480
|
+
this.ws.close();
|
|
481
|
+
this.ws = null;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
this.isConnected = false;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
module.exports = {
|
|
489
|
+
RithmicMarketDataFeed,
|
|
490
|
+
RITHMIC_GATEWAYS,
|
|
491
|
+
RITHMIC_SYSTEMS
|
|
492
|
+
};
|