firstock 1.0.1 → 1.0.5

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.
@@ -0,0 +1,668 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.connections = exports.UpdateType = void 0;
16
+ exports.getUrlAndHeaderData = getUrlAndHeaderData;
17
+ exports.readMessage = readMessage;
18
+ exports.subscribe = subscribe;
19
+ exports.unsubscribe = unsubscribe;
20
+ exports.subscribeOptionGreeks = subscribeOptionGreeks;
21
+ exports.unsubscribeOptionGreeks = unsubscribeOptionGreeks;
22
+ const ws_1 = __importDefault(require("ws"));
23
+ const fs_1 = require("fs");
24
+ // Configure logging
25
+ const logger = {
26
+ debug: (msg) => console.debug(`${new Date().toISOString()} - ${msg}`),
27
+ info: (msg) => console.info(`${new Date().toISOString()} - ${msg}`),
28
+ warning: (msg) => console.warn(`${new Date().toISOString()} - ${msg}`),
29
+ error: (msg, err) => {
30
+ console.error(`[ERROR] ${new Date().toISOString()} - ${msg}`);
31
+ if (err)
32
+ console.error(err);
33
+ }
34
+ };
35
+ var UpdateType;
36
+ (function (UpdateType) {
37
+ UpdateType["ORDER"] = "order";
38
+ UpdateType["POSITION"] = "position";
39
+ UpdateType["MARKET_FEED"] = "market_feed";
40
+ UpdateType["OPTION_GREEKS"] = "option_greeks";
41
+ })(UpdateType || (exports.UpdateType = UpdateType = {}));
42
+ class SafeConn {
43
+ constructor(ws) {
44
+ this.lock = false;
45
+ this.ws = ws;
46
+ }
47
+ acquireLock() {
48
+ return __awaiter(this, void 0, void 0, function* () {
49
+ while (this.lock) {
50
+ yield new Promise(resolve => setTimeout(resolve, 10));
51
+ }
52
+ this.lock = true;
53
+ });
54
+ }
55
+ releaseLock() {
56
+ this.lock = false;
57
+ }
58
+ }
59
+ class ConnectionManager {
60
+ constructor() {
61
+ this.connMap = new Map();
62
+ this.indexMap = new Map();
63
+ this.lock = false;
64
+ }
65
+ acquireLock() {
66
+ return __awaiter(this, void 0, void 0, function* () {
67
+ while (this.lock) {
68
+ yield new Promise(resolve => setTimeout(resolve, 10));
69
+ }
70
+ this.lock = true;
71
+ });
72
+ }
73
+ releaseLock() {
74
+ this.lock = false;
75
+ }
76
+ countConnections() {
77
+ return __awaiter(this, void 0, void 0, function* () {
78
+ yield this.acquireLock();
79
+ const count = this.connMap.size;
80
+ this.releaseLock();
81
+ return count;
82
+ });
83
+ }
84
+ addConnection(ws) {
85
+ return __awaiter(this, void 0, void 0, function* () {
86
+ yield this.acquireLock();
87
+ if (this.indexMap.has(ws)) {
88
+ logger.info("Connection already exists");
89
+ this.releaseLock();
90
+ return this.indexMap.get(ws);
91
+ }
92
+ const safe = new SafeConn(ws);
93
+ this.connMap.set(safe, true);
94
+ this.indexMap.set(ws, safe);
95
+ logger.info("Connection added");
96
+ this.releaseLock();
97
+ return safe;
98
+ });
99
+ }
100
+ checkIfConnectionExists(ws) {
101
+ return __awaiter(this, void 0, void 0, function* () {
102
+ yield this.acquireLock();
103
+ const exists = this.indexMap.has(ws);
104
+ this.releaseLock();
105
+ return exists;
106
+ });
107
+ }
108
+ writeMessage(ws, data) {
109
+ return __awaiter(this, void 0, void 0, function* () {
110
+ yield this.acquireLock();
111
+ const safe = this.indexMap.get(ws);
112
+ this.releaseLock();
113
+ if (!safe) {
114
+ return "connection not found";
115
+ }
116
+ yield safe.acquireLock();
117
+ try {
118
+ if (safe.ws.readyState === ws_1.default.OPEN) {
119
+ safe.ws.send(data);
120
+ safe.releaseLock();
121
+ return null;
122
+ }
123
+ else {
124
+ safe.releaseLock();
125
+ return "WebSocket is not open";
126
+ }
127
+ }
128
+ catch (e) {
129
+ safe.releaseLock();
130
+ return e.message;
131
+ }
132
+ });
133
+ }
134
+ deleteConnection(ws) {
135
+ return __awaiter(this, void 0, void 0, function* () {
136
+ yield this.acquireLock();
137
+ if (this.indexMap.has(ws)) {
138
+ // Set shutdown flag BEFORE closing
139
+ _setShutdownFlag(ws);
140
+ const safe = this.indexMap.get(ws);
141
+ this.connMap.delete(safe);
142
+ this.indexMap.delete(ws);
143
+ try {
144
+ if (ws.readyState === ws_1.default.OPEN || ws.readyState === ws_1.default.CONNECTING) {
145
+ ws.close();
146
+ }
147
+ }
148
+ catch (e) {
149
+ // Ignore errors during close
150
+ }
151
+ logger.info("Connection deleted");
152
+ // Clear subscription tracking
153
+ _clearTrackedSubscriptions(ws);
154
+ this.releaseLock();
155
+ return;
156
+ }
157
+ logger.info("Connection not found");
158
+ this.releaseLock();
159
+ });
160
+ }
161
+ }
162
+ exports.connections = new ConnectionManager();
163
+ const subscriptionTracker = new Map();
164
+ function _getWsId(ws) {
165
+ return ws.__wsId || (ws.__wsId = Math.random());
166
+ }
167
+ function _trackSubscription(ws, tokens, subscriptionType) {
168
+ const wsId = _getWsId(ws);
169
+ if (!subscriptionTracker.has(wsId)) {
170
+ subscriptionTracker.set(wsId, {
171
+ tokens: [],
172
+ option_greeks_tokens: []
173
+ });
174
+ }
175
+ const tracker = subscriptionTracker.get(wsId);
176
+ for (const token of tokens) {
177
+ if (!tracker[subscriptionType].includes(token)) {
178
+ tracker[subscriptionType].push(token);
179
+ }
180
+ }
181
+ logger.debug(`Tracked subscription: ${subscriptionType} - ${tokens.join(', ')}`);
182
+ }
183
+ function _untrackSubscription(ws, tokens, subscriptionType) {
184
+ const wsId = _getWsId(ws);
185
+ if (subscriptionTracker.has(wsId)) {
186
+ const tracker = subscriptionTracker.get(wsId);
187
+ for (const token of tokens) {
188
+ const index = tracker[subscriptionType].indexOf(token);
189
+ if (index > -1) {
190
+ tracker[subscriptionType].splice(index, 1);
191
+ }
192
+ }
193
+ }
194
+ logger.debug(`Untracked subscription: ${subscriptionType} - ${tokens.join(', ')}`);
195
+ }
196
+ function _getTrackedSubscriptions(ws) {
197
+ const wsId = _getWsId(ws);
198
+ return subscriptionTracker.get(wsId) || { tokens: [], option_greeks_tokens: [] };
199
+ }
200
+ function _clearTrackedSubscriptions(ws) {
201
+ const wsId = _getWsId(ws);
202
+ if (subscriptionTracker.has(wsId)) {
203
+ subscriptionTracker.delete(wsId);
204
+ logger.debug(`Cleared subscription tracking for connection ${wsId}`);
205
+ }
206
+ }
207
+ // Shutdown flags
208
+ const shutdownFlags = new Map();
209
+ function _setShutdownFlag(ws) {
210
+ const wsId = _getWsId(ws);
211
+ shutdownFlags.set(wsId, true);
212
+ logger.debug(`Shutdown flag set for connection ${wsId}`);
213
+ }
214
+ function _isShutdownRequested(ws) {
215
+ const wsId = _getWsId(ws);
216
+ return shutdownFlags.get(wsId) || false;
217
+ }
218
+ function _clearShutdownFlag(ws) {
219
+ const wsId = _getWsId(ws);
220
+ if (shutdownFlags.has(wsId)) {
221
+ shutdownFlags.delete(wsId);
222
+ logger.debug(`Shutdown flag cleared for connection ${wsId}`);
223
+ }
224
+ }
225
+ function getUrlAndHeaderData(userId, config) {
226
+ const scheme = config.scheme || 'wss';
227
+ const host = config.host || 'socket.firstock.in';
228
+ const path = config.path || '/ws';
229
+ const srcVal = config.source || 'API';
230
+ const acceptEncoding = config.accept_encoding || 'gzip, deflate, br';
231
+ const acceptLanguage = config.accept_language || 'en-US,en;q=0.9';
232
+ const origin = config.origin || '';
233
+ const baseUrl = `${scheme}://${host}${path}`;
234
+ logger.info(`Connecting to ${baseUrl}`);
235
+ let configJson;
236
+ try {
237
+ const configFile = (0, fs_1.readFileSync)('config.json', 'utf-8');
238
+ configJson = JSON.parse(configFile);
239
+ }
240
+ catch (e) {
241
+ return ['', null, new Error('Failed to read config.json')];
242
+ }
243
+ // Use the userId parameter to get the jKey
244
+ if (!configJson[userId]) {
245
+ return ['', null, new Error(`User ID '${userId}' not found in config.json`)];
246
+ }
247
+ const jkey = configJson[userId].jKey;
248
+ if (!jkey) {
249
+ return ['', null, new Error(`jKey not found for user '${userId}' in config.json`)];
250
+ }
251
+ const queryParams = new URLSearchParams({
252
+ userId: userId,
253
+ jKey: jkey,
254
+ source: 'developer-api'
255
+ });
256
+ const urlWithParams = `${baseUrl}?${queryParams.toString()}`;
257
+ const headers = {
258
+ 'accept-encoding': acceptEncoding,
259
+ 'accept-language': acceptLanguage,
260
+ 'cache-control': 'no-cache',
261
+ 'origin': origin,
262
+ 'pragma': 'no-cache'
263
+ };
264
+ return [urlWithParams, headers, null];
265
+ }
266
+ function _identifyUpdateType(data) {
267
+ if (data.norenordno) {
268
+ return UpdateType.ORDER;
269
+ }
270
+ else if (data.brkname) {
271
+ return UpdateType.POSITION;
272
+ }
273
+ else if (data.gamma) {
274
+ return UpdateType.OPTION_GREEKS;
275
+ }
276
+ else {
277
+ return UpdateType.MARKET_FEED;
278
+ }
279
+ }
280
+ function _handleAuthenticationResponse(message) {
281
+ if (message.includes("Authentication successful")) {
282
+ logger.info("Authentication successful");
283
+ return true;
284
+ }
285
+ else if (message.includes('"status":"failed"')) {
286
+ logger.warning(`Authentication failed: ${message}`);
287
+ return false;
288
+ }
289
+ return true;
290
+ }
291
+ function readMessage(userId, ws, model, config) {
292
+ return __awaiter(this, void 0, void 0, function* () {
293
+ const maxRetries = config.max_websocket_connection_retries || 3;
294
+ const timeInterval = config.time_interval || 5;
295
+ let messageCount = 0;
296
+ let isAuthenticated = true;
297
+ logger.info(`Starting message reader for user ${userId}`);
298
+ logger.info(`Callbacks configured - Feed: ${model.subscribe_feed_data !== undefined}, ` +
299
+ `Order: ${model.order_data !== undefined}, ` +
300
+ `Position: ${model.position_data !== undefined}, ` +
301
+ `Option Greeks: ${model.subscribe_option_greeks_data !== undefined}`);
302
+ const messageHandler = (data) => __awaiter(this, void 0, void 0, function* () {
303
+ if (!(yield exports.connections.checkIfConnectionExists(ws))) {
304
+ logger.info("Connection no longer exists, stopping reader");
305
+ _clearShutdownFlag(ws);
306
+ return;
307
+ }
308
+ try {
309
+ const message = data.toString();
310
+ messageCount++;
311
+ logger.debug(`Message #${messageCount}: ${message.substring(0, 200)}...`);
312
+ if (!message) {
313
+ logger.debug("Empty message received, skipping");
314
+ return;
315
+ }
316
+ let parsedData;
317
+ try {
318
+ parsedData = JSON.parse(message);
319
+ }
320
+ catch (e) {
321
+ logger.error(`JSON parse error: ${e.message}. Message: ${message.substring(0, 200)}`);
322
+ return;
323
+ }
324
+ // Handle authentication responses
325
+ if (parsedData.status && parsedData.message) {
326
+ if (_handleAuthenticationResponse(message)) {
327
+ isAuthenticated = true;
328
+ logger.info("Re-authentication successful");
329
+ }
330
+ return;
331
+ }
332
+ // Route messages to appropriate callbacks
333
+ const updateType = _identifyUpdateType(parsedData);
334
+ if (updateType === UpdateType.ORDER) {
335
+ if (model.order_data) {
336
+ try {
337
+ model.order_data(parsedData);
338
+ logger.debug("Order callback invoked");
339
+ }
340
+ catch (e) {
341
+ logger.error(`Error in order callback: ${e.message}`, e);
342
+ }
343
+ }
344
+ }
345
+ else if (updateType === UpdateType.POSITION) {
346
+ if (model.position_data) {
347
+ try {
348
+ model.position_data(parsedData);
349
+ logger.debug("Position callback invoked");
350
+ }
351
+ catch (e) {
352
+ logger.error(`Error in position callback: ${e.message}`, e);
353
+ }
354
+ }
355
+ }
356
+ else if (updateType === UpdateType.OPTION_GREEKS) {
357
+ if (model.subscribe_option_greeks_data) {
358
+ try {
359
+ if (typeof parsedData === 'object') {
360
+ for (const [key, value] of Object.entries(parsedData)) {
361
+ if (typeof value === 'object' && value.gamma) {
362
+ model.subscribe_option_greeks_data(value);
363
+ }
364
+ }
365
+ }
366
+ logger.debug("Option Greeks callback invoked");
367
+ }
368
+ catch (e) {
369
+ logger.error(`Error in option Greeks callback: ${e.message}`, e);
370
+ }
371
+ }
372
+ }
373
+ else {
374
+ if (model.subscribe_feed_data) {
375
+ try {
376
+ model.subscribe_feed_data(parsedData);
377
+ logger.debug("Feed callback invoked");
378
+ }
379
+ catch (e) {
380
+ logger.error(`Error in feed callback: ${e.message}`, e);
381
+ }
382
+ }
383
+ }
384
+ }
385
+ catch (e) {
386
+ logger.error(`Error processing message: ${e.message}`, e);
387
+ }
388
+ });
389
+ const closeHandler = () => __awaiter(this, void 0, void 0, function* () {
390
+ // Check if shutdown was requested
391
+ if (_isShutdownRequested(ws)) {
392
+ logger.info("Connection closed intentionally");
393
+ _clearShutdownFlag(ws);
394
+ return;
395
+ }
396
+ // Unexpected disconnection - attempt reconnection
397
+ logger.warning("Unexpected disconnection");
398
+ console.log("\n Connection lost");
399
+ console.log("Attempting to reconnect...");
400
+ if (!(yield exports.connections.checkIfConnectionExists(ws))) {
401
+ logger.info("Connection no longer in manager, stopping reader");
402
+ return;
403
+ }
404
+ // Attempt reconnection
405
+ const newWs = yield _attemptReconnection(userId, ws, config, maxRetries, timeInterval, model);
406
+ if (newWs === null) {
407
+ logger.error("Failed to reconnect after all attempts");
408
+ console.log("✗ Failed to reconnect. Please restart the application.");
409
+ return;
410
+ }
411
+ logger.info("Reconnection successful, resuming message reading");
412
+ // Call user's reconnection callback if provided
413
+ if (model.on_reconnect) {
414
+ try {
415
+ model.on_reconnect(newWs);
416
+ logger.info("User's on_reconnect callback executed");
417
+ }
418
+ catch (callbackError) {
419
+ logger.error(`Error in on_reconnect callback: ${callbackError.message}`, callbackError);
420
+ }
421
+ }
422
+ });
423
+ const errorHandler = (error) => __awaiter(this, void 0, void 0, function* () {
424
+ logger.error(`WebSocket error: ${error.message}`, error);
425
+ // Trigger close handler for reconnection logic
426
+ yield closeHandler();
427
+ });
428
+ ws.on('message', messageHandler);
429
+ ws.on('close', closeHandler);
430
+ ws.on('error', errorHandler);
431
+ });
432
+ }
433
+ function _attemptReconnection(userId, oldWs, config, maxRetries, timeInterval, model) {
434
+ return __awaiter(this, void 0, void 0, function* () {
435
+ // Get the actual tracked subscriptions
436
+ const tracked = _getTrackedSubscriptions(oldWs);
437
+ const allTokens = tracked.tokens;
438
+ const allOptionGreeksTokens = tracked.option_greeks_tokens;
439
+ logger.info(`Attempting reconnection. Will restore: ${allTokens.length} market tokens, ${allOptionGreeksTokens.length} option greeks tokens`);
440
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
441
+ if (!(yield exports.connections.checkIfConnectionExists(oldWs))) {
442
+ logger.info("Connection no longer exists in manager, stopping reconnection");
443
+ return null;
444
+ }
445
+ logger.info(`Reconnection attempt ${attempt}/${maxRetries}...`);
446
+ console.log(`Reconnection attempt ${attempt}/${maxRetries}...`);
447
+ yield new Promise(resolve => setTimeout(resolve, timeInterval * 1000));
448
+ try {
449
+ // Create new connection
450
+ const [baseUrl, headers, err] = getUrlAndHeaderData(userId, config);
451
+ if (err) {
452
+ logger.error(`Failed to get URL/headers: ${err.message}`);
453
+ continue;
454
+ }
455
+ const newWs = new ws_1.default(baseUrl, { headers });
456
+ // Wait for connection to open
457
+ yield new Promise((resolve, reject) => {
458
+ const timeout = setTimeout(() => {
459
+ reject(new Error('Connection timeout'));
460
+ }, 10000);
461
+ newWs.once('open', () => {
462
+ clearTimeout(timeout);
463
+ resolve();
464
+ });
465
+ newWs.once('error', (error) => {
466
+ clearTimeout(timeout);
467
+ reject(error);
468
+ });
469
+ });
470
+ logger.info(`New WebSocket connection created (attempt ${attempt})`);
471
+ // Wait for authentication message
472
+ const authMessage = yield new Promise((resolve, reject) => {
473
+ const timeout = setTimeout(() => {
474
+ reject(new Error('Authentication timeout'));
475
+ }, 5000);
476
+ newWs.once('message', (data) => {
477
+ clearTimeout(timeout);
478
+ resolve(data.toString());
479
+ });
480
+ newWs.once('error', (error) => {
481
+ clearTimeout(timeout);
482
+ reject(error);
483
+ });
484
+ });
485
+ logger.info(`Reconnection auth message: ${authMessage}`);
486
+ if (!authMessage.includes("Authentication successful")) {
487
+ logger.warning(`Authentication failed on reconnect: ${authMessage}`);
488
+ newWs.close();
489
+ continue;
490
+ }
491
+ // Transfer subscription tracking from old connection to new connection
492
+ const oldWsId = _getWsId(oldWs);
493
+ const newWsId = _getWsId(newWs);
494
+ if (subscriptionTracker.has(oldWsId)) {
495
+ const oldTracker = subscriptionTracker.get(oldWsId);
496
+ subscriptionTracker.set(newWsId, {
497
+ tokens: [...oldTracker.tokens],
498
+ option_greeks_tokens: [...oldTracker.option_greeks_tokens]
499
+ });
500
+ logger.debug(`Transferred subscription tracking from ${oldWsId} to ${newWsId}`);
501
+ }
502
+ // Update connection manager
503
+ yield exports.connections.deleteConnection(oldWs);
504
+ yield exports.connections.addConnection(newWs);
505
+ logger.info("Connection manager updated with new connection");
506
+ // Resubscribe to all tracked tokens
507
+ logger.info("Resubscribing to previous subscriptions...");
508
+ console.log("Resubscribing to previous feeds...");
509
+ // Resubscribe to market feed tokens
510
+ if (allTokens.length > 0) {
511
+ yield new Promise(resolve => setTimeout(resolve, 500));
512
+ const tokensStr = allTokens.join("|");
513
+ const msg = JSON.stringify({ action: "subscribe", tokens: tokensStr });
514
+ const error = yield exports.connections.writeMessage(newWs, msg);
515
+ if (error) {
516
+ logger.error(`Failed to resubscribe to market tokens: ${error}`);
517
+ }
518
+ else {
519
+ logger.info(`Resubscribed to ${allTokens.length} market feed token(s): ${allTokens.join(', ')}`);
520
+ console.log(`✓ Resubscribed to ${allTokens.length} market feed token(s)`);
521
+ }
522
+ }
523
+ if (allOptionGreeksTokens.length > 0) {
524
+ yield new Promise(resolve => setTimeout(resolve, 500));
525
+ const tokensStr = allOptionGreeksTokens.join("|");
526
+ const msg = JSON.stringify({ action: "subscribe-option-greeks", tokens: tokensStr });
527
+ const error = yield exports.connections.writeMessage(newWs, msg);
528
+ if (error) {
529
+ logger.error(`Failed to resubscribe to option Greeks: ${error}`);
530
+ }
531
+ else {
532
+ logger.info(`Resubscribed to ${allOptionGreeksTokens.length} option Greeks token(s): ${allOptionGreeksTokens.join(', ')}`);
533
+ console.log(`✓ Resubscribed to ${allOptionGreeksTokens.length} option Greeks token(s)`);
534
+ }
535
+ }
536
+ yield new Promise(resolve => setTimeout(resolve, 1000));
537
+ logger.info("Reconnection and resubscription successful!");
538
+ console.log("✓ Reconnection complete - all subscriptions restored");
539
+ // IMPORTANT: Restart the message reader for the new WebSocket
540
+ readMessage(userId, newWs, model, config);
541
+ return newWs;
542
+ }
543
+ catch (e) {
544
+ logger.error(`Reconnection attempt ${attempt} failed: ${e.message}`, e);
545
+ console.log(`✗ Attempt ${attempt} failed: ${e.message.substring(0, 100)}...`);
546
+ if (attempt === maxRetries) {
547
+ logger.error("Max reconnection attempts reached");
548
+ console.log(`✗ All ${maxRetries} reconnection attempts failed`);
549
+ return null;
550
+ }
551
+ }
552
+ }
553
+ return null;
554
+ });
555
+ }
556
+ function subscribe(ws, tokens) {
557
+ return __awaiter(this, void 0, void 0, function* () {
558
+ if (!(yield exports.connections.checkIfConnectionExists(ws))) {
559
+ return {
560
+ error: {
561
+ message: "Connection does not exist"
562
+ }
563
+ };
564
+ }
565
+ _trackSubscription(ws, tokens, 'tokens');
566
+ let tokensStr;
567
+ if (tokens.length === 1 && tokens[0].includes("|")) {
568
+ tokensStr = tokens[0];
569
+ }
570
+ else {
571
+ tokensStr = tokens.join("|");
572
+ }
573
+ const msg = JSON.stringify({
574
+ action: "subscribe",
575
+ tokens: tokensStr
576
+ });
577
+ logger.info(`Sending subscribe message: ${msg}`);
578
+ const error = yield exports.connections.writeMessage(ws, msg);
579
+ if (error) {
580
+ return { error: { message: error } };
581
+ }
582
+ logger.info("Subscribe message sent successfully");
583
+ return null;
584
+ });
585
+ }
586
+ function unsubscribe(ws, tokens) {
587
+ return __awaiter(this, void 0, void 0, function* () {
588
+ if (!(yield exports.connections.checkIfConnectionExists(ws))) {
589
+ return {
590
+ error: {
591
+ message: "Connection does not exist"
592
+ }
593
+ };
594
+ }
595
+ _untrackSubscription(ws, tokens, 'tokens');
596
+ const tokensStr = tokens.join("|");
597
+ const msg = JSON.stringify({
598
+ action: "unsubscribe",
599
+ tokens: tokensStr
600
+ });
601
+ logger.info(`Sending unsubscribe message: ${msg}`);
602
+ const error = yield exports.connections.writeMessage(ws, msg);
603
+ if (error) {
604
+ return { error: { message: error } };
605
+ }
606
+ return null;
607
+ });
608
+ }
609
+ function subscribeOptionGreeks(ws, tokens) {
610
+ return __awaiter(this, void 0, void 0, function* () {
611
+ if (!(yield exports.connections.checkIfConnectionExists(ws))) {
612
+ return {
613
+ error: {
614
+ message: "Connection does not exist"
615
+ }
616
+ };
617
+ }
618
+ _trackSubscription(ws, tokens, 'option_greeks_tokens');
619
+ let tokensStr;
620
+ if (tokens.length === 1 && tokens[0].includes("|")) {
621
+ tokensStr = tokens[0];
622
+ }
623
+ else {
624
+ tokensStr = tokens.join("|");
625
+ }
626
+ const msg = JSON.stringify({
627
+ action: "subscribe-option-greeks",
628
+ tokens: tokensStr
629
+ });
630
+ logger.info(`Sending subscribe option greeks message: ${msg}`);
631
+ const error = yield exports.connections.writeMessage(ws, msg);
632
+ if (error) {
633
+ return { error: { message: error } };
634
+ }
635
+ logger.info("Subscribe option greeks message sent successfully");
636
+ return null;
637
+ });
638
+ }
639
+ function unsubscribeOptionGreeks(ws, tokens) {
640
+ return __awaiter(this, void 0, void 0, function* () {
641
+ if (!(yield exports.connections.checkIfConnectionExists(ws))) {
642
+ return {
643
+ error: {
644
+ message: "Connection does not exist"
645
+ }
646
+ };
647
+ }
648
+ _untrackSubscription(ws, tokens, 'option_greeks_tokens');
649
+ let tokensStr;
650
+ if (tokens.length === 1 && tokens[0].includes("|")) {
651
+ tokensStr = tokens[0];
652
+ }
653
+ else {
654
+ tokensStr = tokens.join("|");
655
+ }
656
+ const msg = JSON.stringify({
657
+ action: "unsubscribe-option-greeks",
658
+ tokens: tokensStr
659
+ });
660
+ logger.info(`Sending unsubscribe option greeks message: ${msg}`);
661
+ const error = yield exports.connections.writeMessage(ws, msg);
662
+ if (error) {
663
+ return { error: { message: error } };
664
+ }
665
+ logger.info("Unsubscribe option greeks message sent successfully");
666
+ return null;
667
+ });
668
+ }