-
Notifications
You must be signed in to change notification settings - Fork 215
/
transports_ws2.js.html
2873 lines (2507 loc) · 88.1 KB
/
transports_ws2.js.html
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>transports/ws2.js - Documentation</title>
<script src="scripts/prettify/prettify.js"></script>
<script src="scripts/prettify/lang-css.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc.css">
<script src="scripts/nav.js" defer></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
<nav >
<h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="WS2Manager.html">WS2Manager</a><ul class='methods'><li data-type='method'><a href="WS2Manager.html#auth">auth</a></li><li data-type='method'><a href="WS2Manager.html#close">close</a></li><li data-type='method'><a href="WS2Manager.html#getAuthArgs">getAuthArgs</a></li><li data-type='method'><a href="WS2Manager.html#getAuthenticatedSocket">getAuthenticatedSocket</a></li><li data-type='method'><a href="WS2Manager.html#getFreeDataSocket">getFreeDataSocket</a></li><li data-type='method'><a href="WS2Manager.html#getNumSockets">getNumSockets</a></li><li data-type='method'><a href="WS2Manager.html#getSocket">getSocket</a></li><li data-type='method'><a href="WS2Manager.html#getSocketInfo">getSocketInfo</a></li><li data-type='method'><a href="WS2Manager.html#getSocketWithChannel">getSocketWithChannel</a></li><li data-type='method'><a href="WS2Manager.html#getSocketWithDataChannel">getSocketWithDataChannel</a></li><li data-type='method'><a href="WS2Manager.html#getSocketWithSubRef">getSocketWithSubRef</a></li><li data-type='method'><a href="WS2Manager.html#managedUnsubscribe">managedUnsubscribe</a></li><li data-type='method'><a href="WS2Manager.html#onCandle">onCandle</a></li><li data-type='method'><a href="WS2Manager.html#onOrderBook">onOrderBook</a></li><li data-type='method'><a href="WS2Manager.html#onTicker">onTicker</a></li><li data-type='method'><a href="WS2Manager.html#onTrades">onTrades</a></li><li data-type='method'><a href="WS2Manager.html#openSocket">openSocket</a></li><li data-type='method'><a href="WS2Manager.html#reconnect">reconnect</a></li><li data-type='method'><a href="WS2Manager.html#setAuthArgs">setAuthArgs</a></li><li data-type='method'><a href="WS2Manager.html#subscribe">subscribe</a></li><li data-type='method'><a href="WS2Manager.html#subscribeCandles">subscribeCandles</a></li><li data-type='method'><a href="WS2Manager.html#subscribeOrderBook">subscribeOrderBook</a></li><li data-type='method'><a href="WS2Manager.html#subscribeTicker">subscribeTicker</a></li><li data-type='method'><a href="WS2Manager.html#subscribeTrades">subscribeTrades</a></li><li data-type='method'><a href="WS2Manager.html#unsubscribe">unsubscribe</a></li><li data-type='method'><a href="WS2Manager.html#withAllSockets">withAllSockets</a></li><li data-type='method'><a href="WS2Manager.html#.getDataChannelCount">getDataChannelCount</a></li></ul></li><li><a href="WSv2.html">WSv2</a><ul class='methods'><li data-type='method'><a href="WSv2.html#auth">auth</a></li><li data-type='method'><a href="WSv2.html#cancelOrder">cancelOrder</a></li><li data-type='method'><a href="WSv2.html#cancelOrders">cancelOrders</a></li><li data-type='method'><a href="WSv2.html#close">close</a></li><li data-type='method'><a href="WSv2.html#enableFlag">enableFlag</a></li><li data-type='method'><a href="WSv2.html#enableSequencing">enableSequencing</a></li><li data-type='method'><a href="WSv2.html#getAuthArgs">getAuthArgs</a></li><li data-type='method'><a href="WSv2.html#getCandles">getCandles</a></li><li data-type='method'><a href="WSv2.html#getChannelData">getChannelData</a></li><li data-type='method'><a href="WSv2.html#getDataChannelCount">getDataChannelCount</a></li><li data-type='method'><a href="WSv2.html#getDataChannelId">getDataChannelId</a></li><li data-type='method'><a href="WSv2.html#getLosslessOB">getLosslessOB</a></li><li data-type='method'><a href="WSv2.html#getOB">getOB</a></li><li data-type='method'><a href="WSv2.html#getURL">getURL</a></li><li data-type='method'><a href="WSv2.html#hasChannel">hasChannel</a></li><li data-type='method'><a href="WSv2.html#hasDataChannel">hasDataChannel</a></li><li data-type='method'><a href="WSv2.html#hasSubscriptionRef">hasSubscriptionRef</a></li><li data-type='method'><a href="WSv2.html#isAuthenticated">isAuthenticated</a></li><li data-type='method'><a href="WSv2.html#isFlagEnabled">isFlagEnabled</a></li><li data-type='method'><a href="WSv2.html#isOpen">isOpen</a></li><li data-type='method'><a href="WSv2.html#isReconnecting">isReconnecting</a></li><li data-type='method'><a href="WSv2.html#managedSubscribe">managedSubscribe</a></li><li data-type='method'><a href="WSv2.html#managedUnsubscribe">managedUnsubscribe</a></li><li data-type='method'><a href="WSv2.html#notifyUI">notifyUI</a></li><li data-type='method'><a href="WSv2.html#onAccountTradeEntry">onAccountTradeEntry</a></li><li data-type='method'><a href="WSv2.html#onAccountTradeUpdate">onAccountTradeUpdate</a></li><li data-type='method'><a href="WSv2.html#onBalanceInfoUpdate">onBalanceInfoUpdate</a></li><li data-type='method'><a href="WSv2.html#onCandle">onCandle</a></li><li data-type='method'><a href="WSv2.html#onFundingCreditClose">onFundingCreditClose</a></li><li data-type='method'><a href="WSv2.html#onFundingCreditNew">onFundingCreditNew</a></li><li data-type='method'><a href="WSv2.html#onFundingCreditSnapshot">onFundingCreditSnapshot</a></li><li data-type='method'><a href="WSv2.html#onFundingCreditUpdate">onFundingCreditUpdate</a></li><li data-type='method'><a href="WSv2.html#onFundingInfoUpdate">onFundingInfoUpdate</a></li><li data-type='method'><a href="WSv2.html#onFundingLoanClose">onFundingLoanClose</a></li><li data-type='method'><a href="WSv2.html#onFundingLoanNew">onFundingLoanNew</a></li><li data-type='method'><a href="WSv2.html#onFundingLoanSnapshot">onFundingLoanSnapshot</a></li><li data-type='method'><a href="WSv2.html#onFundingLoanUpdate">onFundingLoanUpdate</a></li><li data-type='method'><a href="WSv2.html#onFundingOfferClose">onFundingOfferClose</a></li><li data-type='method'><a href="WSv2.html#onFundingOfferNew">onFundingOfferNew</a></li><li data-type='method'><a href="WSv2.html#onFundingOfferSnapshot">onFundingOfferSnapshot</a></li><li data-type='method'><a href="WSv2.html#onFundingOfferUpdate">onFundingOfferUpdate</a></li><li data-type='method'><a href="WSv2.html#onFundingTradeEntry">onFundingTradeEntry</a></li><li data-type='method'><a href="WSv2.html#onFundingTradeUpdate">onFundingTradeUpdate</a></li><li data-type='method'><a href="WSv2.html#onInfoMessage">onInfoMessage</a></li><li data-type='method'><a href="WSv2.html#onMaintenanceEnd">onMaintenanceEnd</a></li><li data-type='method'><a href="WSv2.html#onMaintenanceStart">onMaintenanceStart</a></li><li data-type='method'><a href="WSv2.html#onMarginInfoUpdate">onMarginInfoUpdate</a></li><li data-type='method'><a href="WSv2.html#onMessage">onMessage</a></li><li data-type='method'><a href="WSv2.html#onNotification">onNotification</a></li><li data-type='method'><a href="WSv2.html#onOrderBook">onOrderBook</a></li><li data-type='method'><a href="WSv2.html#onOrderBookChecksum">onOrderBookChecksum</a></li><li data-type='method'><a href="WSv2.html#onOrderClose">onOrderClose</a></li><li data-type='method'><a href="WSv2.html#onOrderNew">onOrderNew</a></li><li data-type='method'><a href="WSv2.html#onOrderSnapshot">onOrderSnapshot</a></li><li data-type='method'><a href="WSv2.html#onOrderUpdate">onOrderUpdate</a></li><li data-type='method'><a href="WSv2.html#onPositionClose">onPositionClose</a></li><li data-type='method'><a href="WSv2.html#onPositionNew">onPositionNew</a></li><li data-type='method'><a href="WSv2.html#onPositionSnapshot">onPositionSnapshot</a></li><li data-type='method'><a href="WSv2.html#onPositionUpdate">onPositionUpdate</a></li><li data-type='method'><a href="WSv2.html#onServerRestart">onServerRestart</a></li><li data-type='method'><a href="WSv2.html#onStatus">onStatus</a></li><li data-type='method'><a href="WSv2.html#onTicker">onTicker</a></li><li data-type='method'><a href="WSv2.html#onTradeEntry">onTradeEntry</a></li><li data-type='method'><a href="WSv2.html#onTrades">onTrades</a></li><li data-type='method'><a href="WSv2.html#onWalletSnapshot">onWalletSnapshot</a></li><li data-type='method'><a href="WSv2.html#onWalletUpdate">onWalletUpdate</a></li><li data-type='method'><a href="WSv2.html#open">open</a></li><li data-type='method'><a href="WSv2.html#reconnect">reconnect</a></li><li data-type='method'><a href="WSv2.html#removeListeners">removeListeners</a></li><li data-type='method'><a href="WSv2.html#requestCalc">requestCalc</a></li><li data-type='method'><a href="WSv2.html#send">send</a></li><li data-type='method'><a href="WSv2.html#sequencingEnabled">sequencingEnabled</a></li><li data-type='method'><a href="WSv2.html#submitOrder">submitOrder</a></li><li data-type='method'><a href="WSv2.html#submitOrderMultiOp">submitOrderMultiOp</a></li><li data-type='method'><a href="WSv2.html#subscribe">subscribe</a></li><li data-type='method'><a href="WSv2.html#subscribeCandles">subscribeCandles</a></li><li data-type='method'><a href="WSv2.html#subscribeOrderBook">subscribeOrderBook</a></li><li data-type='method'><a href="WSv2.html#subscribeStatus">subscribeStatus</a></li><li data-type='method'><a href="WSv2.html#subscribeTicker">subscribeTicker</a></li><li data-type='method'><a href="WSv2.html#subscribeTrades">subscribeTrades</a></li><li data-type='method'><a href="WSv2.html#unsubscribe">unsubscribe</a></li><li data-type='method'><a href="WSv2.html#unsubscribeCandles">unsubscribeCandles</a></li><li data-type='method'><a href="WSv2.html#unsubscribeOrderBook">unsubscribeOrderBook</a></li><li data-type='method'><a href="WSv2.html#unsubscribeStatus">unsubscribeStatus</a></li><li data-type='method'><a href="WSv2.html#unsubscribeTicker">unsubscribeTicker</a></li><li data-type='method'><a href="WSv2.html#unsubscribeTrades">unsubscribeTrades</a></li><li data-type='method'><a href="WSv2.html#updateAuthArgs">updateAuthArgs</a></li><li data-type='method'><a href="WSv2.html#updateOrder">updateOrder</a></li><li data-type='method'><a href="WSv2.html#usesAgent">usesAgent</a></li></ul></li><li></li></ul><h3>Global</h3><ul><li><a href="global.html#setSigFig">setSigFig</a></li></ul>
</nav>
<div id="main">
<h1 class="page-title">transports/ws2.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>'use strict'
const { EventEmitter } = require('events')
const debug = require('debug')('bfx:ws2')
const WebSocket = require('ws')
const CbQ = require('cbq')
const _Throttle = require('lodash.throttle') // eslint-disable-line
const _isArray = require('lodash/isArray')
const _isEmpty = require('lodash/isEmpty')
const _isString = require('lodash/isString')
const _isNumber = require('lodash/isNumber')
const _includes = require('lodash/includes')
const _pick = require('lodash/pick')
const _isEqual = require('lodash/isEqual')
const _isFinite = require('lodash/isFinite')
const { genAuthSig, nonce } = require('bfx-api-node-util')
const LosslessJSON = require('lossless-json')
const getMessagePayload = require('../util/ws2')
const {
BalanceInfo,
FundingCredit,
FundingInfo,
FundingLoan,
FundingOffer,
FundingTrade,
MarginInfo,
Notification,
Order,
Position,
Trade,
PublicTrade,
Wallet,
OrderBook,
Candle,
TradingTicker,
FundingTicker
} = require('bfx-api-node-models')
const DATA_CHANNEL_TYPES = ['ticker', 'book', 'candles', 'trades']
const UCM_NOTIFICATION_TYPE = 'ucm-notify-ui'
const MAX_CALC_OPS = 8
/**
* A Promise Throttle instance
*
* @typedef {object} PromiseThrottle
* @property {Function} add - add a promise to be throttled
*/
/**
* Communicates with v2 of the Bitfinex WebSocket API
*
* @class
*/
class WSv2 extends EventEmitter {
/**
* Instantiate a new ws2 transport. Does not auto-open
*
* @class WSv2
* @param {object} [opts] - instance options
* @param {string} [opts.affCode] - affiliate code to be applied to all orders
* @param {string} [opts.apiKey] - API key
* @param {string} [opts.apiSecret] - API secret
* @param {string} [opts.url] - ws connection url, defaults to {@link WSv2#url}
* @param {number} [opts.orderOpBufferDelay] - multi-order op batching timeout
* @param {boolean} [opts.transform] - if true, packets are converted to models
* @param {object} [opts.agent] - optional node agent for ws connection (proxy)
* @param {boolean} [opts.manageOrderBooks] - enable local OB persistence
* @param {boolean} [opts.manageCandles] - enable local candle persistence
* @param {boolean} [opts.seqAudit] - enable sequence numbers & verification
* @param {boolean} [opts.autoReconnect] - if true, we will reconnect on close
* @param {number} [opts.reconnectDelay] - optional, defaults to 1000 (ms)
* @param {PromiseThrottle} [opts.reconnectThrottler] - optional pt to limit reconnect freq
* @param {number} [opts.packetWDDelay] - watch-dog forced reconnection delay
* @example
* const ws = new WSv2()
*
* ws.on('open', async () => {
* ws.onTrades({ symbol: 'tBTCUSD' }, (trades) => {
* console.log('recv trades: %j', trades)
* })
*
* await ws.subscribeTrades('tBTCUSD')
* })
*
* await ws.open()
*/
constructor (opts = {
apiKey: '',
apiSecret: '',
url: WSv2.url,
affCode: null
}) {
super()
this.setMaxListeners(1000)
this._affCode = opts.affCode
this._agent = opts.agent
this._url = opts.url || WSv2.url
this._transform = opts.transform === true
this._orderOpBufferDelay = opts.orderOpBufferDelay || -1
this._orderOpBuffer = []
this._orderOpTimeout = null
this._seqAudit = opts.seqAudit === true
this._autoReconnect = opts.autoReconnect === true
this._reconnectDelay = opts.reconnectDelay || 1000
this._reconnectThrottler = opts.reconnectThrottler
this._manageOrderBooks = opts.manageOrderBooks === true
this._manageCandles = opts.manageCandles === true
this._packetWDDelay = opts.packetWDDelay
this._packetWDTimeout = null
this._packetWDLastTS = 0
this._orderBooks = {}
this._losslessOrderBooks = {}
this._candles = {}
this._authArgs = {
apiKey: opts.apiKey,
apiSecret: opts.apiSecret
}
/**
* {
* [groupID]: {
* [eventName]: [{
* modelClass: ..,
* filter: { symbol: 'tBTCUSD' }, // only works w/ serialize
* cb: () => {}
* }]
* }
* }
*
* @private
*/
this._listeners = {}
this._infoListeners = {} // { [code]: <listeners> }
this._subscriptionRefs = {}
this._channelMap = {}
this._orderBooks = {}
this._enabledFlags = this._seqAudit ? WSv2.flags.SEQ_ALL : 0
this._eventCallbacks = new CbQ()
this._isAuthenticated = false
this._authOnReconnect = false // used for auto-auth on reconnect
this._lastPubSeq = -1
this._lastAuthSeq = -1
this._isOpen = false
this._ws = null
this._isClosing = false // used to block reconnect on direct close() call
this._isReconnecting = false
this._onWSOpen = this._onWSOpen.bind(this)
this._onWSClose = this._onWSClose.bind(this)
this._onWSError = this._onWSError.bind(this)
this._onWSMessage = this._onWSMessage.bind(this)
this._triggerPacketWD = this._triggerPacketWD.bind(this)
this._sendCalc = _Throttle(this._sendCalc.bind(this), 1000 / MAX_CALC_OPS)
}
/**
* @returns {string} url
*/
getURL () {
return this._url
}
/**
* @returns {boolean} usesAgent
*/
usesAgent () {
return !!this._agent
}
/**
* Set `calc` and `dms` values to be used on the next {@link WSv2#auth} call
*
* @param {object} args - arguments
* @param {number} [args.calc] - calc value
* @param {number} [args.dms] - dms value, active 4
* @param {number} [args.apiKey] API key
* @param {number} [args.apiSecret] API secret
* @see WSv2#auth
*/
updateAuthArgs (args = {}) {
this._authArgs = {
...this._authArgs,
...args
}
}
/**
* Fetch the current default auth parameters
*
* @returns {object} authArgs
* @see WSv2#updateAuthArgs
* @see WSv2#auth
*/
getAuthArgs () {
return this._authArgs
}
/**
* Get the total number of data channels this instance is currently
* subscribed too.
*
* @returns {number} count
* @see WSv2#subscribeTrades
* @see WSv2#subscribeTicker
* @see WSv2#subscribeCandles
* @see WSv2#subscribeOrderBook
*/
getDataChannelCount () {
return Object
.values(this._channelMap)
.filter(c => _includes(DATA_CHANNEL_TYPES, c.channel))
.length
}
/**
* Check if the instance is subscribed to the specified channel ID
*
* @param {number} chanId - ID of channel to query
* @returns {boolean} isSubscribed
*/
hasChannel (chanId) {
return !!this._channelMap[chanId]
}
/**
* Check if a channel/identifier pair has been subscribed too
*
* @param {string} channel - channel type
* @param {string} identifier - unique identifier for the reference
* @returns {boolean} hasRef
* @see WSv2#managedSubscribe
*/
hasSubscriptionRef (channel, identifier) {
const key = `${channel}:${identifier}`
return !!Object.keys(this._subscriptionRefs).find(ref => ref === key)
}
/**
* Fetch the ID of a channel matched by type and channel data filter
*
* @param {string} type - channel type
* @param {object} filter - to be matched against channel data
* @returns {number} channelID
*/
getDataChannelId (type, filter) {
return Object
.keys(this._channelMap)
.find(cid => {
const c = this._channelMap[cid]
const fv = _pick(c, Object.keys(filter))
return c.channel === type && _isEqual(fv, filter)
})
}
/**
* Check if the instance is subscribed to a data channel matching the
* specified type and filter.
*
* @param {string} type - channel type
* @param {object} filter - to be matched against channel data
* @returns {boolean} hasChannel
*/
hasDataChannel (type, filter) {
return !!this.getDataChannelId(type, filter)
}
/**
* Opens a connection to the API server. Rejects with an error if a
* connection is already open. Resolves on success.
*
* @returns {Promise} p
*/
async open () {
if (this._isOpen || this._ws !== null) {
throw new Error('already open')
}
debug('connecting to %s...', this._url)
this._ws = new WebSocket(this._url, {
agent: this._agent
})
this._subscriptionRefs = {}
this._candles = {}
this._orderBooks = {}
this._ws.on('message', this._onWSMessage)
this._ws.on('error', this._onWSError)
this._ws.on('close', this._onWSClose)
return new Promise((resolve) => {
this._ws.on('open', () => {
// call manually instead of binding to open event so it fires at the
// right time
this._onWSOpen()
if (this._enabledFlags !== 0) {
this.sendEnabledFlags()
}
debug('connected')
resolve()
})
})
}
/**
* Closes the active connection. If there is none, rejects with a promise.
* Resolves on success
*
* @param {number} code - passed to ws
* @param {string} reason - passed to ws
* @returns {Promise} p
*/
async close (code, reason) {
if (!this._isOpen || this._ws === null) {
throw new Error('not open')
}
debug('disconnecting...')
return new Promise((resolve) => {
this._ws.once('close', () => {
this._isOpen = false
this._ws = null
debug('disconnected')
resolve()
})
if (!this._isClosing) {
this._isClosing = true
this._ws.close(code, reason)
}
})
}
/**
* Generates & sends an authentication packet to the server; if already
* authenticated, rejects with an error, resolves on success.
*
* If a DMS flag of 4 is provided, all open orders are cancelled when the
* connection terminates.
*
* @param {number?} calc - optional, default is 0
* @param {number?} dms - optional dead man switch flag, active 4
* @returns {Promise} p
*/
async auth (calc, dms) {
this._authOnReconnect = true
if (!this._isOpen) {
throw new Error('not open')
}
if (this._isAuthenticated) {
throw new Error('already authenticated')
}
const authNonce = nonce()
const authPayload = `AUTH${authNonce}${authNonce}`
const { sig } = genAuthSig(this._authArgs.apiSecret, authPayload)
const authArgs = { ...this._authArgs }
if (_isFinite(calc)) authArgs.calc = calc
if (_isFinite(dms)) authArgs.dms = dms
return new Promise((resolve) => {
this.once('auth', () => {
debug('authenticated')
resolve()
})
this.send({
event: 'auth',
apiKey: this._authArgs.apiKey,
authSig: sig,
authPayload,
authNonce,
...authArgs
})
})
}
/**
* Utility method to close & re-open the ws connection. Re-authenticates if
* previously authenticated
*
* @returns {Promise} p - resolves on completion
*/
async reconnect () {
this._isReconnecting = true
if (this._ws !== null && this._isOpen) { // did we get a watchdog timeout and need to close the connection?
await this.close()
return new Promise((resolve) => {
this.once(this._authOnReconnect ? 'auth' : 'open', resolve)
})
}
return this.reconnectAfterClose() // we are already closed, so reopen and re-auth
}
/**
* @private
*/
async reconnectAfterClose () {
if (!this._isReconnecting || this._ws !== null || this._isOpen) {
return this.reconnect()
}
await this.open()
if (this._authOnReconnect) {
await this.auth()
}
}
/**
* Returns an error if the message has an invalid (out of order) sequence #
* The last-seen sequence #s are updated internally.
*
* @param {Array} msg - incoming message
* @returns {Error} err - null if no error or sequencing not enabled
* @private
*/
_validateMessageSeq (msg = []) {
if (!this._seqAudit) return null
if (!Array.isArray(msg)) return null
if (msg.length === 0) return null
// The auth sequence # is the last value in channel 0 non-heartbeat packets.
const authSeq = msg[0] === 0 && msg[1] !== 'hb'
? msg[msg.length - 1]
: NaN
// *-req packets don't include public seq numbers
if (`${(msg[2] || [])[1] || ''}`.slice(-4) !== '-req') {
// All other packets provide a public sequence # as the last value. For chan
// 0 packets, these are included as the 2nd to last value
const seq = (
(msg[0] === 0) &&
(msg[1] !== 'hb') &&
!(msg[1] === 'n' && ((msg[2] || [])[1] || '').slice(-4) === '-req')
)
? msg[msg.length - 2]
: msg[msg.length - 1]
if (!_isFinite(seq)) return null
if (this._lastPubSeq === -1) { // first pub seq received
this._lastPubSeq = seq
return null
}
if (seq !== this._lastPubSeq + 1) { // check pub seq
return new Error(`invalid pub seq #; last ${this._lastPubSeq}, got ${seq}`)
}
this._lastPubSeq = seq
}
if (!_isFinite(authSeq)) return null
if (authSeq === 0) return null // still syncing
// notifications don't advance seq
if (msg[1] === 'n') {
return authSeq !== this._lastAuthSeq
? new Error(
`invalid auth seq #, expected no advancement but got ${authSeq}`
)
: null
}
if (authSeq === this._lastAuthSeq) {
return new Error(
`expected auth seq # advancement but got same seq: ${authSeq}`
)
}
// check
if (this._lastAuthSeq !== -1 && authSeq !== this._lastAuthSeq + 1) {
return new Error(
`invalid auth seq #; last ${this._lastAuthSeq}, got ${authSeq}`
)
}
this._lastAuthSeq = authSeq
return null
}
/**
* Trigger the packet watch-dog; called when we haven't seen a new WS packet
* for longer than our WD duration (if provided)
*
* @returns {Promise} p
* @private
*/
async _triggerPacketWD () {
if (!this._packetWDDelay || !this._isOpen) {
return Promise.resolve()
}
debug(
'packet delay watchdog triggered [last packet %dms ago]',
Date.now() - this._packetWDLastTS
)
this._packetWDTimeout = null
return this.reconnect()
}
/**
* Reset the packet watch-dog timeout. Should be called on every new WS packet
* if the watch-dog is enabled
*
* @private
*/
_resetPacketWD () {
if (!this._packetWDDelay) return
if (this._packetWDTimeout !== null) {
clearTimeout(this._packetWDTimeout)
}
if (!this._isOpen) return
this._packetWDTimeout = setTimeout(() => {
this._triggerPacketWD().catch((err) => {
debug('error triggering packet watchdog: %s', err.message)
})
}, this._packetWDDelay)
}
/**
* Subscribes to previously subscribed channels, used after reconnecting
*
* @private
*/
resubscribePreviousChannels () {
Object.values(this._prevChannelMap).forEach((chan) => {
const { channel } = chan
switch (channel) {
case 'ticker': {
const { symbol } = chan
this.subscribeTicker(symbol)
break
}
case 'trades': {
const { symbol } = chan
this.subscribeTrades(symbol)
break
}
case 'book': {
const { symbol, len, prec } = chan
this.subscribeOrderBook(symbol, prec, len)
break
}
case 'candles': {
const { key } = chan
this.subscribeCandles(key)
break
}
default: {
debug('unknown previously subscribed channel type: %s', channel)
}
}
})
}
/**
* @private
*/
_onWSOpen () {
this._isOpen = true
this._isReconnecting = false
this._packetWDLastTS = Date.now()
this._lastAuthSeq = -1
this._lastPubSeq = -1
this.emit('open')
if (!_isEmpty(this._prevChannelMap)) {
this.resubscribePreviousChannels()
this._prevChannelMap = {}
}
debug('connection open')
}
/**
* @private
*/
async _onWSClose () {
this._isOpen = false
this._isAuthenticated = false
this._lastAuthSeq = -1
this._lastPubSeq = -1
this._enabledFlags = 0
this._ws = null
this._subscriptionRefs = {}
this.emit('close')
debug('connection closed')
// _isReconnecting = true - if a reconnection has been requested. In that case always call reconnectAfterClose
// _isClosing = true - if the user explicitly requested a close
// _autoReconnect = true - if the user likes to reconnect automatically
if (this._isReconnecting || (this._autoReconnect && !this._isClosing)) {
this._prevChannelMap = this._channelMap
setTimeout(async () => {
try {
if (this._reconnectThrottler) {
await this._reconnectThrottler.add(this.reconnectAfterClose.bind(this))
} else {
await this.reconnectAfterClose()
}
} catch (err) {
debug('error reconnectAfterClose: %s', err.stack)
}
}, this._reconnectDelay)
}
this._channelMap = {}
this._isClosing = false
}
/**
* @param {Error} err - error
* @private
*/
_onWSError (err) {
this.emit('error', err)
debug('error: %s', err)
}
/**
* @param {Array} arrN - notification in ws array format
* @private
*/
_onWSNotification (arrN) {
const status = arrN[6]
const msg = arrN[7]
if (!arrN[4]) return
if (arrN[1] === 'on-req') {
const [,, cid] = arrN[4]
const k = `order-new-${cid}`
if (status === 'SUCCESS') {
this._eventCallbacks.trigger(k, null, arrN[4])
} else {
this._eventCallbacks.trigger(k, new Error(`${status}: ${msg}`), arrN[4])
}
} else if (arrN[1] === 'oc-req') {
const [id] = arrN[4]
const k = `order-cancel-${id}`
if (status === 'SUCCESS') {
this._eventCallbacks.trigger(k, null, arrN[4])
} else {
this._eventCallbacks.trigger(k, new Error(`${status}: ${msg}`), arrN[4])
}
} else if (arrN[1] === 'ou-req') {
const [id] = arrN[4]
const k = `order-update-${id}`
if (status === 'SUCCESS') {
this._eventCallbacks.trigger(k, null, arrN[4])
} else {
this._eventCallbacks.trigger(k, new Error(`${status}: ${msg}`), arrN[4])
}
}
}
/**
* @param {string} rawMsg - incoming message JSON
* @param {string} flags - flags
* @private
*/
_onWSMessage (rawMsg, flags) {
debug('recv msg: %s', rawMsg)
this._packetWDLastTS = Date.now()
this._resetPacketWD()
let msg
try {
msg = JSON.parse(rawMsg)
} catch (e) {
this.emit('error', `invalid message JSON: ${rawMsg}`)
return
}
debug('recv msg: %j', msg)
if (this._seqAudit) {
const seqErr = this._validateMessageSeq(msg)
if (seqErr !== null) {
this.emit('error', seqErr)
return
}
}
this.emit('message', msg, flags)
if (Array.isArray(msg)) {
this._handleChannelMessage(msg, rawMsg)
} else if (msg.event) {
this._handleEventMessage(msg)
} else {
debug('recv unidentified message: %j', msg)
}
}
/**
* @param {Array} msg - message
* @param {string} rawMsg - message JSON
* @private
*/
_handleChannelMessage (msg, rawMsg) {
const [chanId, type] = msg
const channelData = this._channelMap[chanId]
if (!channelData) {
debug('recv msg from unknown channel %d: %j', chanId, msg)
return
}
if (msg.length < 2) return
if (msg[1] === 'hb') return
if (channelData.channel === 'book') {
if (type === 'cs') {
this._handleOBChecksumMessage(msg, channelData)
} else {
this._handleOBMessage(msg, channelData, rawMsg)
}
} else if (channelData.channel === 'trades') {
this._handleTradeMessage(msg, channelData)
} else if (channelData.channel === 'ticker') {
this._handleTickerMessage(msg, channelData)
} else if (channelData.channel === 'candles') {
this._handleCandleMessage(msg, channelData)
} else if (channelData.channel === 'status') {
this._handleStatusMessage(msg, channelData)
} else if (channelData.channel === 'auth') {
this._handleAuthMessage(msg, channelData)
} else {
this._propagateMessageToListeners(msg, channelData)
this.emit(channelData.channel, msg)
}
}
/**
* @param {Array} msg - message
* @param {object} chanData - channel definition
* @private
*/
_handleOBChecksumMessage (msg, chanData) {
this.emit('cs', msg)
if (!this._manageOrderBooks) {
return
}
const { symbol, prec } = chanData
const cs = msg[2]
// NOTE: Checksums are temporarily disabled for funding books, due to
// invalid book sorting on the backend. This change is temporary
if (symbol[0] === 't') {
const err = this._verifyManagedOBChecksum(symbol, prec, cs)
if (err) {
this.emit('error', err)
return
}
}
const internalMessage = [chanData.chanId, 'ob_checksum', cs]
internalMessage.filterOverride = [
chanData.symbol,
chanData.prec,
chanData.len
]
this._propagateMessageToListeners(internalMessage, false)
this.emit('cs', symbol, cs)
}
/**
* Called for messages from the 'book' channel. Might be an update or a
* snapshot
*
* @param {Array|Array[]} msg - message
* @param {object} chanData - entry from _channelMap
* @param {string} rawMsg - message JSON
* @private
*/
_handleOBMessage (msg, chanData, rawMsg) {
const { symbol, prec } = chanData
const raw = prec === 'R0'
let data = getMessagePayload(msg)
if (this._manageOrderBooks) {
const err = this._updateManagedOB(symbol, data, raw, rawMsg)
if (err) {
this.emit('error', err)
return
}
data = this._orderBooks[symbol]
}
// Always transform an array of entries
if (this._transform) {
data = new OrderBook((Array.isArray(data[0]) ? data : [data]), raw)
}
const internalMessage = [chanData.chanId, 'orderbook', data]
internalMessage.filterOverride = [
chanData.symbol,
chanData.prec,
chanData.len
]
this._propagateMessageToListeners(internalMessage, chanData, false)
this.emit('orderbook', symbol, data)
}
/**
* @param {string} symbol - symbol for order book
* @param {number[]|number[][]} data - incoming data
* @param {boolean} raw - if true, the order book is considered R*
* @param {string} rawMsg - source message JSON
* @returns {Error} err - null on success
* @private
*/
_updateManagedOB (symbol, data, raw, rawMsg) {
// parse raw string with lossless parse which takes
// the exact strict values rather than converting to floats
// [0.00001, [1, 2, 3]] -> ['0.00001', ['1', '2', '3']]
const rawLossless = LosslessJSON.parse(rawMsg, (key, value) => {
if (value && value.isLosslessNumber) {
return value.toString()
} else {
return value
}
})
const losslessUpdate = rawLossless[1]
// Snapshot, new OB. Note that we don't protect against duplicates, as they
// could come in on re-sub
if (Array.isArray(data[0])) {
this._orderBooks[symbol] = data
this._losslessOrderBooks[symbol] = losslessUpdate
return null
}
// entry, needs to be applied to OB
if (!this._orderBooks[symbol]) {
return new Error(`recv update for unknown OB: ${symbol}`)
}
OrderBook.updateArrayOBWith(this._orderBooks[symbol], data, raw)
OrderBook.updateArrayOBWith(this._losslessOrderBooks[symbol], losslessUpdate, raw)
return null
}
/**
* @param {string} symbol - symbol for order book
* @param {string} prec - precision
* @param {number} cs - expected checksum
* @returns {Error} err - null if none
* @private
*/
_verifyManagedOBChecksum (symbol, prec, cs) {
const ob = this._losslessOrderBooks[symbol]
if (!ob) return null
const localCS = ob instanceof OrderBook
? ob.checksum()
: OrderBook.checksumArr(ob, prec === 'R0')
return localCS !== cs
? new Error(`OB checksum mismatch: got ${localCS}, want ${cs}`)
: null
}
/**
* Returns an up-to-date copy of the order book for the specified symbol, or
* null if no OB is managed for that symbol.
*
* Set `managedOrderBooks: true` in the constructor to use.
*
* @param {string} symbol - symbol for order book
* @returns {OrderBook} ob - null if not found
* @example
* const ws = new WSv2({ managedOrderBooks: true })
*
* ws.on('open', async () => {
* ws.onOrderBook({ symbol: 'tBTCUSD' }, () => {
* const book = ws.getOB('tBTCUSD')
*
* if (!book) return
*
* const spread = book.midPrice()
* console.log('spread for tBTCUSD: %f', spread)
* })
*
* ws.subscribeOrderBook({ symbol: 'tBTCUSD' })
* })
*
* await ws.open()
*/
getOB (symbol) {
if (!this._orderBooks[symbol]) return null
return new OrderBook(this._orderBooks[symbol])
}
/**
* Returns an up-to-date lossless copy of the order book for the specified symbol, or
* null if no OB is managed for that symbol. All amounts and prices are in original
* string format.
*
* Set `manageOrderBooks: true` in the constructor to use.
*
* @param {string} symbol - symbol for order book
* @returns {OrderBook} ob - null if not found
*/
getLosslessOB (symbol) {
if (!this._losslessOrderBooks[symbol]) return null
return new OrderBook(this._losslessOrderBooks[symbol])
}
/**
* @param {Array} msg - incoming message