hedgequantx 2.7.15 → 2.7.16

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/data2.js DELETED
@@ -1,492 +0,0 @@
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
- };