/
websocket.ts
684 lines (566 loc) · 17.8 KB
/
websocket.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
import {WebSocket} from "./_websocket";
import {Response, Authorization} from "./http";
export {Response, Authorization} from "./http";
// CONSTANTS
// =========
/** Root URL for Market data notifications. */
export const MARKET_DATA_URL: string = "wss://api.fyers.in/socket/v2/dataSock";
/** Root URL for Order update notifications. */
export const ORDER_UPDATE_URL: string = "wss://api.fyers.in/socket/v2/orderSock";
/** Base query string for Market data notifications. */
const MARKET_DATA_QUERY:string = "user-agent=fyers-api&type=symbolUpdate";
/** Base query string for Order update notifications. */
const ORDER_UPDATE_QUERY:string = "user-agent=fyers-api&type=orderUpdate";
/** Ping interval on the WebSocket connection. */
const PING_INTERVAL: number = 5000;
// TYPES
// =====
// NOTIFICATION
// ------------
/** Common notification format. */
export type Notification = Response;
// ORDER-UPDATE
// ------------
/** Update for order placed by the user in the current trading day. */
export interface OrderUpdate {
/** The unique order id assigned for each order. */
id: string,
/** The order id provided by the exchange. */
exchOrdId: string,
/** The symbol for which order is placed. */
symbol: string,
/** Fytoken is a unique identifier for every symbol. */
fyToken: string,
/** The segment this order is placed in. */
segment: string,
/** Exchange instrument type. */
instrument: string,
/** The type of order. */
type: number,
/** The order is buy or sell. */
side: number,
/** The product type. */
productType: string,
/** The status of the order. */
status: number,
/** The order number and status of the order. */
orderNumStatus: string,
/** True when placing AMO order. */
offlineOrder: boolean,
/** The original order qty. */
qty: number,
/** The remaining qty. */
remainingQuantity: number,
/** The filled qty after partial trades. */
filledQty: number,
/** The limit price for the order. */
limitPrice: number,
/** The stop price for the order. */
stopPrice: number,
/** Disclosed quantity. */
discloseQty: number,
/** Remaining disclosed quantity. */
dqQtyRem: number,
/** Day or IOC. */
orderValidity: string,
/** The order time as per DD-MMM-YYYY hh:mm:ss in IST. */
orderDateTime: string,
/** The parent order id will be provided only for applicable orders. */
parentId?: string,
/** The average traded price for the order. */
tradedPrice: number,
/** This is used to sort the orders based on the time. */
slNo: number,
/** The error messages are shown here. */
message: string,
}
/** String notification on order update. */
export interface OrderUpdateNotification extends Notification {
/** Websocket type [1]. */
ws_type?: number,
/** Data for the notification. */
d?: OrderUpdate,
}
// MARKET-DATA HEADER
// ------------------
/** Size of header in binary message. */
const HEADER_SIZE = 24;
/** Offset of header in binary message. */
const HEADER_OFFSET = 0;
/** Header for each binary message. */
export interface Header {
/** Fytoken is a unique identifier for every symbol. */
token: BigInt,
/** Timestamp sent by exchange (UNIX epoch). */
tt: number,
/** 7202: OI data (NSE FO/CD, MCX), 7207/7208: NSE, BSE (indices/data), 31038: MCX. */
fyCode: number,
/** Market status flag? */
marketStat: number,
/** Packet length, including header? */
pktlen: number,
/** Has L2 data (market depth)? */
L2: number,
}
function toHeader(x: DataView, i: number): Header {
return {
token: x.getBigUint64(i + 0),
tt: x.getUint32(i + 8),
fyCode: x.getUint16(i + 12),
marketStat: x.getUint16(i + 14),
pktlen: x.getUint16(i + 16),
L2: x.getUint8(i + 18),
};
}
function writeHeader(a: Header, x: DataView, i: number): void {
a.token = x.getBigUint64(i + 0);
a.tt = x.getUint32(i + 8);
a.fyCode = x.getUint16(i + 12);
a.marketStat = x.getUint16(i + 14);
a.pktlen = x.getUint16(i + 16);
a.L2 = x.getUint8(i + 18);
}
// MARKET-DATA OI-DATA
// -------------------
/** Size of OI data in binary message. */
const OI_DATA_SIZE = 8;
/** Offset of OI data in binary message. */
const OI_DATA_OFFSET = HEADER_SIZE;
/** Open interest data (fyCode === 7202). */
export interface OiData {
/** Open interest. */
oi: number,
/** Previous day open interest. */
pdoi: number,
}
function toOiData(x: DataView, i: number): OiData {
return {
oi: x.getUint32(i + 0),
pdoi: x.getUint32(i + 4),
};
}
function writeOiData(a: CommonData, x: DataView, i: number): void {
a.oi = BigInt(x.getUint32(i + 0));
a.pdoi = BigInt(x.getUint32(i + 4));
}
// MARKET-DATA COMMON-DATA
// -----------------------
/** Size of common data in binary message. */
const COMMON_DATA_SIZE = 64;
/** Offset of common data in binary message. */
const COMMON_DATA_OFFSET = HEADER_SIZE;
/** Common data (fyCode !== 7202). */
export interface CommonData {
/** Price conversion, divisor for all prices. */
price_conv: number,
/** LTP is the price from which the next sale of the stocks happens. */
ltp: number,
/** Price at market opening time. */
open_price: number,
/** Highest price for the day. */
high_price: number,
/** Lowest price for the day. */
low_price: number,
/** Close price of the previous trading day. */
prev_close_price: number,
/** Open price (1 minute). */
o: number,
/** High price (1 minute). */
h: number,
/** Low price (1 minute). */
l: number,
/** Close price (1 minute). */
c: number,
/** Volume (1 minute). */
v: BigInt,
/** Open interest. */
oi: BigInt,
/** Previous day open interest. */
pdoi: BigInt,
}
function toCommonData(x: DataView, i: number, hasOi: boolean): CommonData {
return {
price_conv: x.getUint32(i + 0),
ltp: x.getUint32(i + 4),
open_price: x.getUint32(i + 8),
high_price: x.getUint32(i + 12),
low_price: x.getUint32(i + 16),
prev_close_price: x.getUint32(i + 20),
o: x.getUint32(i + 24),
h: x.getUint32(i + 28),
l: x.getUint32(i + 32),
c: x.getUint32(i + 36),
v: x.getBigUint64(i + 40),
oi: hasOi? x.getBigUint64(i + 48) : BigInt(0),
pdoi: hasOi? x.getBigUint64(i + 56) : BigInt(0),
};
}
function writeCommonData(a: CommonData, x: DataView, i: number, hasOi: boolean): void {
a.price_conv = x.getUint32(i + 0);
a.ltp = x.getUint32(i + 4);
a.open_price = x.getUint32(i + 8);
a.high_price = x.getUint32(i + 12);
a.low_price = x.getUint32(i + 16);
a.prev_close_price = x.getUint32(i + 20);
a.o = x.getUint32(i + 24);
a.h = x.getUint32(i + 28);
a.l = x.getUint32(i + 32);
a.c = x.getUint32(i + 36);
a.v = x.getBigUint64(i + 40);
if (!hasOi) return;
a.oi = x.getBigUint64(i + 48);
a.pdoi = x.getBigUint64(i + 56);
}
// MARKET-DATA L1-DATA
// -------------------
/** Minimum size of L1 data in binary message. */
const L1_DATA_SIZE = 32;
/** Offset of L1 data in binary message. */
const L1_DATA_OFFSET = HEADER_SIZE + COMMON_DATA_SIZE;
/** Additional data (fyCode === 7208, 31038). */
export interface L1Data {
/** Last traded quantity. */
LTQ: number,
/** Last traded time (UNIX epoch). */
L2_LTT: number,
/** Average traded price. */
ATP: number,
/** Today's volume. */
volume: number,
/** Total buy quantity. */
tot_buy: BigInt,
/** Total sell quantity. */
tot_sell: BigInt,
/** Highest bid price. */
bid: number,
/** Lowest ask price. */
ask: number,
}
function toL1Data(x: DataView, i: number, bidAsk: boolean): L1Data {
return {
LTQ: x.getUint32(i + 0),
L2_LTT: x.getUint32(i + 4),
ATP: x.getUint32(i + 8),
volume: x.getUint32(i + 12),
tot_buy: x.getBigUint64(i + 16),
tot_sell: x.getBigUint64(i + 24),
bid: bidAsk? x.getUint32(i + 32) : 0,
ask: bidAsk? x.getUint32(i + 36) : 0,
};
}
function writeL1Data(a: L1Data, x: DataView, i: number, bidAsk: boolean): void {
a.LTQ = x.getUint32(i + 0);
a.L2_LTT = x.getUint32(i + 4);
a.ATP = x.getUint32(i + 8);
a.volume = x.getUint32(i + 12);
a.tot_buy = x.getBigUint64(i + 16);
a.tot_sell = x.getBigUint64(i + 24);
if (!bidAsk) return;
a.bid = x.getUint32(i + 32);
a.ask = x.getUint32(i + 36);
}
// MARKET-DATA L2-DATA
// -------------------
/** Open buy/sell orders at a particular price (L2 === 1). */
export interface L2MarketOffer {
/** Bid/ask price. */
price: number,
/** Bid/ask volume. */
volume: number,
/** Number of orders. */
ord: number,
}
/** Size of L2 data in binary message. */
const L2_DATA_SIZE = 120;
/** Offset of L1 data in binary message. */
const L2_DATA_OFFSET = HEADER_SIZE + COMMON_DATA_SIZE + L1_DATA_SIZE;
/** Market depth data, 5 rows (L2 === 1). */
export interface L2Data {
/** Bidding price along with volume and total number of orders. */
bids: L2MarketOffer[],
/** Offer price with volume and total number of orders. */
asks: L2MarketOffer[],
}
function toL2MarketOffer(x: DataView, i: number): L2MarketOffer {
return {
price: x.getUint32(i + 0),
volume: x.getUint32(i + 4),
ord: x.getUint32(i + 8),
};
}
function toL2Data(x: DataView, i: number): L2Data {
var bids = [], asks = [];
for (var j = 0; j < 60; j += 12) {
bids.push(toL2MarketOffer(x, i + j));
asks.push(toL2MarketOffer(x, i + j + 60));
}
return {bids, asks};
}
function writeL2Data(a: L2Data, x: DataView, i: number): void {
var bids = [], asks = [];
for (var j = 0; j < 60; j += 12) {
bids.push(toL2MarketOffer(x, i + j));
asks.push(toL2MarketOffer(x, i + j + 60));
}
a.bids = bids;
a.asks = asks;
}
// MARKET-DATA
// -----------
/** Split Market data (oi/quote/depth) for symbols subscribed by the user. */
interface SplitMarketData extends Header {
/** Open interest data (fyCode === 7202). */
oi_data: OiData | null,
/** Common data (fyCode !== 7202). */
common_data: CommonData | null,
/** Additional data (fyCode === 7208, 31038). */
l1_data: L1Data | null,
/** Market depth data, 5 rows (L2 === 1). */
l2_data: L2Data | null,
}
/** Market data (oi/quote/depth) for symbols subscribed by the user. */
export interface MarketData extends Header, CommonData, L1Data, L2Data {}
function toSplitMarketData(x: DataView, i: number): SplitMarketData {
var fyCode = x.getUint16(i + 12);
var L2 = x.getUint8(i + 18);
var hasOi = fyCode === 7202 || fyCode === 31038;
var l1Off = hasOi? 88 : 72;
return {
token: x.getBigUint64(i + 0),
tt: x.getUint32(i + 8),
fyCode: x.getUint16(i + 12),
marketStat: x.getUint16(i + 14),
pktlen: x.getUint16(i + 16),
L2: x.getUint8(i + 18),
oi_data: fyCode === 7202? toOiData(x, i + 24) : null,
common_data: fyCode !== 7202? toCommonData(x, i + 24, hasOi) : null,
l1_data: fyCode === 7208 || fyCode === 31038? toL1Data(x, i + l1Off, L2 !== 1) : null,
l2_data: L2 === 1? toL2Data(x, i + l1Off + 32) : null,
};
}
function writeMarketData(a: MarketData, x: DataView, i: number): void {
writeHeader(a, x, i + 0);
var hasOi = a.fyCode === 7202 || a.fyCode === 31038;
var l1Off = hasOi? 88 : 72;
if (a.fyCode === 7202) writeOiData(a, x, i + 24);
else writeCommonData(a, x, i + 24, hasOi);
if (a.fyCode === 7208 || a.fyCode === 31038) writeL1Data(a, x, i + l1Off, a.L2 !== 1);
if (a.L2 === 1) writeL2Data(a, x, i + l1Off + 32);
}
function toMarketData(x: DataView, i: number): MarketData {
var a: MarketData = {
// HEADER
token: BigInt(0),
tt: 0,
fyCode: 0,
marketStat: 0,
pktlen: 0,
L2: 0,
// COMMON DATA
price_conv: 0,
ltp: 0,
open_price: 0,
high_price: 0,
low_price: 0,
prev_close_price: 0,
o: 0,
h: 0,
l: 0,
c: 0,
v: BigInt(0),
oi: BigInt(0),
pdoi: BigInt(0),
// L1 DATA
LTQ: 0,
L2_LTT: 0,
ATP: 0,
volume: 0,
tot_buy: BigInt(0),
tot_sell: BigInt(0),
bid: 0,
ask: 0,
// L2 DATA
bids: null,
asks: null,
};
writeMarketData(a, x, i);
return a;
}
/** Binary notification on Market data. */
export interface MarketDataNotification extends Notification {
/** Data for the notification. */
d?: MarketData,
}
// FUNCTIONS
// =========
/**
* Notified function.
* @param notification notification
*/
export type OnNotification = (notification: Notification) => void;
/**
* Order update notified function.
* @param notification notification
*/
export type OnOrderUpdateNotification = (notification: OrderUpdateNotification) => void;
/**
* Market data notified function.
* @param notification notification
*/
export type OnMarketDataNotification = (notification: MarketDataNotification) => void;
// WEB-CHANNEL
// -----------
/** Handler for reciever which has passed (resolved). */
export type OnResolve = (response: Response) => void;
/** Handler for reciever which has failed (rejected). */
export type OnReject = (error: Error) => void;
/** Recieve response to a request, which can pass or fail. */
export interface Reciever {
/** Pass (resolve) handler for reciever. */
resolve: OnResolve,
/** Fail (reject) handler for reciever. */
reject: OnReject;
}
/**
* Provides the API for creating and managing a WebSocket connection to
* a server, as well as for sending and receiving data on the connection.
*/
export class Connection extends WebSocket {
/** To recieve response to a request. */
recievers: Reciever[] = [];
}
// Wait for response to request.
function waitResponse(conn: Connection): Promise<Response> {
return new Promise((resolve, reject) => conn.recievers.push({resolve, reject}));
}
// ORDER-UPDATE
// ------------
/**
* Connect to Order update URL with WebSocket.
* @param auth authorization \{app_id, access_token\}
* @param fn notified function
* @returns WebSocket connection
*/
export function connectOrderUpdate(auth: Authorization, fn: OnOrderUpdateNotification): Promise<Connection> {
return new Promise((resolve, reject) => {
var {app_id, access_token} = auth;
var query = `${ORDER_UPDATE_QUERY}&access_token=${app_id}:${access_token}`;
var conn = new Connection(`${ORDER_UPDATE_URL}?${query}`);
var ping = setInterval(() => {
if (conn.readyState !== WebSocket.OPEN) return;
conn.send("ping");
}, PING_INTERVAL);
conn.binaryType = "arraybuffer";
conn.onerror = e => {
for (var r of conn.recievers)
r.reject(e.error);
clearInterval(ping);
reject(e.error);
};
conn.onopen = () => resolve(conn);
conn.onmessage = e => {
if (typeof e.data !== "string") return;
if (e.data === "pong") return;
var x = JSON.parse(e.data); fn(x);
if (x.hasOwnProperty("d") || x.code === 0) return;
if (conn.recievers.length > 0) conn.recievers.shift().resolve(x);
};
});
}
/**
* Subscribe to order update.
* @param conn websocket connection
*/
export function subscribeOrderUpdate(conn: Connection): Promise<Response> {
var req = {T: "SUB_ORD", SLIST: ["orderUpdate"], SUB_T: 1};
conn.send(JSON.stringify(req));
return waitResponse(conn);
}
/**
* Unsubscribe to order update.
* @param conn websocket connection
*/
export function unsubscribeOrderUpdate(conn: Connection): Promise<Response> {
var req = {T: "SUB_ORD", SLIST: ["orderUpdate"], SUB_T: 0};
conn.send(JSON.stringify(req));
return waitResponse(conn);
}
// MARKET-DATA
// -----------
/**
* Connect to Market data URL with WebSocket.
* @param auth authorization \{app_id, access_token\}
* @param fn notified function
* @returns WebSocket connection
*/
export function connectMarketData(auth: Authorization, fn: OnMarketDataNotification): Promise<Connection> {
return new Promise((resolve, reject) => {
var {app_id, access_token} = auth;
var query = `${MARKET_DATA_QUERY}&access_token=${app_id}:${access_token}`;
var conn = new Connection(`${MARKET_DATA_URL}?${query}`);
var ping = setInterval(() => {
if (conn.readyState !== WebSocket.OPEN) return;
conn.send("ping");
}, PING_INTERVAL);
conn.binaryType = "arraybuffer";
conn.onerror = e => {
for (var r of conn.recievers)
r.reject(e.error);
clearInterval(ping);
reject(e.error);
};
conn.onopen = () => resolve(conn);
conn.onmessage = e => {
if (typeof e.data === "string") {
if (e.data === "pong") return;
var x = JSON.parse(e.data); fn(x);
if (x.hasOwnProperty("d") || x.code === 0) return;
if (conn.recievers.length > 0) conn.recievers.shift().resolve(x);
}
else {
var binary = new DataView(e.data as ArrayBuffer);
fn({s: "ok", d: toMarketData(binary, 0)});
}
};
});
}
/**
* Subscribe to market quote.
* @param conn websocket connection
* @param symbols list of symbols
*/
export function subscribeMarketQuote(conn: Connection, symbols: string[]): Promise<Response> {
var req = {T: "SUB_DATA", TLIST: symbols, SUB_T: 1};
conn.send(JSON.stringify(req));
return waitResponse(conn);
}
/**
* Subscribe to market depth.
* @param conn websocket connection
* @param symbols list of symbols
*/
export function subscribeMarketDepth(conn: Connection, symbols: string[]): Promise<Response> {
var req = {T: "SUB_L2", L2LIST: symbols, SUB_T: 1};
conn.send(JSON.stringify(req));
return waitResponse(conn);
}
/**
* Unsubscribe to market quote.
* @param conn websocket connection
* @param symbols list of symbols
*/
export function unsubscribeMarketQuote(conn: Connection, symbols: string[]): Promise<Response> {
var req = {T: "SUB_DATA", TLIST: symbols, SUB_T: 0};
conn.send(JSON.stringify(req));
return waitResponse(conn);
}
/**
* Unsubscribe to market depth.
* @param conn websocket connection
* @param symbols list of symbols
*/
export function unsubscribeMarketDepth(conn: Connection, symbols: string[]): Promise<Response> {
var req = {T: "SUB_L2", L2LIST: symbols, SUB_T: 0};
conn.send(JSON.stringify(req));
return waitResponse(conn);
}