-
Notifications
You must be signed in to change notification settings - Fork 209
Expand file tree
/
Copy pathws2.js
More file actions
2178 lines (1871 loc) · 55.7 KB
/
ws2.js
File metadata and controls
2178 lines (1871 loc) · 55.7 KB
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
'use strict'
const { EventEmitter } = require('events')
const debug = require('debug')('bfx:ws2')
const WebSocket = require('ws')
const Promise = require('bluebird')
const CbQ = require('cbq')
const { isFinite } = require('lodash')
const _Throttle = require('lodash.throttle')
const _isEmpty = require('lodash/isEmpty')
const _isString = require('lodash/isString')
const _includes = require('lodash/includes')
const _pick = require('lodash/pick')
const _isEqual = require('lodash/isEqual')
const { genAuthSig, nonce } = require('bfx-api-node-util')
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 WS_URL = 'wss://api.bitfinex.com/ws/2'
const MAX_CALC_OPS = 8
const INFO_CODES = {
SERVER_RESTART: 20051,
MAINTENANCE_START: 20060,
MAINTENANCE_END: 20061
}
const FLAGS = {
DEC_S: 8, // enables all decimals as strings
TIME_S: 32, // enables all timestamps as strings
TIMESTAMP: 32768, // timestamps in milliseconds
SEQ_ALL: 65536, // enable sequencing
CHECKSUM: 131072 // enable checksum per OB change, top 25 levels per-side
}
/**
* Communicates with v2 of the Bitfinex WebSocket API
*/
class WSv2 extends EventEmitter {
/**
* Instantiate a new ws2 transport. Does not auto-open
*
* @param {string} opts.apiKey
* @param {string} opts.apiSecret
* @param {string} opts.url - ws connection 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 {number} opts.packetWDDelay - watch-dog forced reconnection delay
*/
constructor (opts = { apiKey: '', apiSecret: '', url: WS_URL }) {
super()
this.setMaxListeners(1000)
this._apiKey = opts.apiKey || ''
this._apiSecret = opts.apiSecret || ''
this._agent = opts.agent
this._url = opts.url || WS_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._manageOrderBooks = opts.manageOrderBooks === true
this._manageCandles = opts.manageCandles === true
this._packetWDDelay = opts.packetWDDelay
this._packetWDTimeout = null
this._packetWDLastTS = 0
this._orderBooks = {}
this._candles = {}
/**
* {
* [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 = 0
this._eventCallbacks = new CbQ()
this._isAuthenticated = false
this._wasEverAuthenticated = 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)
}
setAPICredentials (apiKey, apiSecret) {
this._apiKey = apiKey
this._apiSecret = apiSecret
}
getDataChannelCount () {
return Object
.values(this._channelMap)
.filter(c => _includes(DATA_CHANNEL_TYPES, c.channel))
.length
}
hasChannel (chanId) {
return _includes(Object.keys(this._channelMap), chanId)
}
getDataChannelId (type, filter) {
return Object
.keys(this._channelMap)
.find(cid => {
const c = this._channelMap[cid]
const fv = _pick(c, Object.keys(filter))
return _isEqual(fv, filter)
})
}
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
*
* @return {Promise} p
*/
open () {
if (this._isOpen || this._ws !== null) {
return Promise.reject(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('open', this._onWSOpen)
this._ws.on('error', this._onWSError)
this._ws.on('close', this._onWSClose)
if (this._seqAudit) {
this._ws.once('open', this.enableSequencing.bind(this))
}
return new Promise((resolve, reject) => {
this._ws.once('open', () => {
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
* @return {Promise}
*/
close (code, reason) {
if (!this._isOpen || this._ws === null) {
return Promise.reject(new Error('not open'))
}
debug('disconnecting...')
return new Promise((resolve, reject) => {
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
* @return {Promise} p
*/
auth (calc = 0, dms = 0) {
if (!this._isOpen) return Promise.reject(new Error('not open'))
if (this._isAuthenticated) {
return Promise.reject(new Error('already authenticated'))
}
const authNonce = nonce()
const authPayload = `AUTH${authNonce}${authNonce}`
const { sig } = genAuthSig(this._apiSecret, authPayload)
return new Promise((resolve, reject) => {
this.once('auth', () => {
debug('authenticated')
resolve()
})
this.send({
event: 'auth',
apiKey: this._apiKey,
authSig: sig,
authPayload,
authNonce,
dms,
calc
})
})
}
/**
* Utility method to close & re-open the ws connection. Re-authenticates if
* previously authenticated
*
* @return {Promise} p - resolves on completion
*/
async reconnect () {
if (!this._ws) {
return this.open()
}
this._isReconnecting = true
await this.close()
await this.open()
if (this._wasEverAuthenticated) {
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
* @return {Error} err - null if no error or sequencing not enabled
*/
_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
// 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][6] === 'ERROR') // error notifications lack seq
)
? 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
if (msg[1] === 'n' && msg[2][6] === 'ERROR') return null // err notifications lack seq
if (authSeq === this._lastAuthSeq) return null // seq didn't advance
// 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)
* @private
*/
_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)
}
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: {}
}
})
}
/**
* @private
*/
_onWSOpen () {
// TODO: Add _resetState() method for this, see _onWSClose
this._isOpen = true
this._isReconnecting = false
this._packetWDLastTS = Date.now()
this._enabledFlags = 0
this._lastAuthSeq = -1
this._lastPubSeq = -1
this.emit('open')
if (!_isEmpty(this._prevChannelMap)) {
this.resubscribePreviousChannels()
this._prevChannelMap = {}
}
debug('connection open')
}
/**
* @private
*/
_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')
if (this._autoReconnect && !this._isClosing) {
this._prevChannelMap = this._channelMap
setTimeout(this.reconnect.bind(this), this._reconnectDelay)
}
this._channelMap = {}
this._isClosing = false
}
/**
* @private
*/
_onWSError (err) {
this.emit('error', err)
debug('error: %j', 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') {
return this._eventCallbacks.trigger(k, null, arrN[4])
}
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') {
return this._eventCallbacks.trigger(k, null, arrN[4])
}
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') {
return this._eventCallbacks.trigger(k, null, arrN[4])
}
this._eventCallbacks.trigger(k, new Error(`${status}: ${msg}`), arrN[4])
}
}
/**
* @param {string} msgJSON
* @param {string} flags
* @private
*/
_onWSMessage (msgJSON, flags) {
this._packetWDLastTS = Date.now()
this._resetPacketWD()
let msg
try {
msg = JSON.parse(msgJSON)
} catch (e) {
this.emit('error', `invalid message JSON: ${msgJSON}`)
return
}
debug('recv msg: %j', msg)
if (this._seqAudit) {
const seqErr = this._validateMessageSeq(msg)
if (seqErr !== null) {
return this.emit('error', seqErr)
}
}
this.emit('message', msg, flags)
if (Array.isArray(msg)) {
this._handleChannelMessage(msg)
} else if (msg.event) {
this._handleEventMessage(msg)
} else {
debug('recv unidentified message: %j', msg)
}
}
/**
* @param {array} msg
* @private
*/
_handleChannelMessage (msg) {
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 // TODO: optionally track seq
if (channelData.channel === 'book') {
if (type === 'cs') {
return this._handleOBChecksumMessage(msg, channelData)
}
return this._handleOBMessage(msg, channelData)
} else if (channelData.channel === 'trades') {
return this._handleTradeMessage(msg, channelData)
} else if (channelData.channel === 'ticker') {
return this._handleTickerMessage(msg, channelData)
} else if (channelData.channel === 'candles') {
return this._handleCandleMessage(msg, channelData)
} else if (channelData.channel === 'auth') {
return this._handleAuthMessage(msg, channelData)
} else {
this._propagateMessageToListeners(msg, channelData)
this.emit(channelData.channel, msg)
}
}
_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
* @param {Object} chanData - entry from _channelMap
* @private
*/
_handleOBMessage (msg, chanData) {
const { symbol, prec } = chanData
const raw = prec === 'R0'
let data = getMessagePayload(msg)
if (this._manageOrderBooks) {
const err = this._updateManagedOB(symbol, data, raw)
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
* @param {number[]|number[][]} data
* @param {boolean} raw
* @return {Error} err - null on success
* @private
*/
_updateManagedOB (symbol, data, raw) {
// 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
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)
return null
}
/**
* @param {string} symbol
* @param {string} prec - precision
* @param {number} cs - expected checksum
* @return {Error} err - null if none
*/
_verifyManagedOBChecksum (symbol, prec, cs) {
const ob = this._orderBooks[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 `manageOrderBooks: true` in the constructor to use.
*
* @param {string} symbol
* @return {OrderBook} ob - null if not found
*/
getOB (symbol) {
if (!this._orderBooks[symbol]) return null
return new OrderBook(this._orderBooks[symbol])
}
/**
* @param {Array} msg
* @param {Object} chanData
* @private
*/
_handleTradeMessage (msg, chanData) {
const eventName = msg[1] === 'te' ? 'trade-entry' : 'trades'
let payload = getMessagePayload(msg)
if (!Array.isArray(payload[0])) {
payload = [payload]
}
const data = this._transform ? PublicTrade.unserialize(payload) : payload
const internalMessage = [chanData.chanId, eventName, data]
internalMessage.filterOverride = [chanData.symbol]
this._propagateMessageToListeners(internalMessage, chanData, false)
this.emit('trades', chanData.pair, data)
}
/**
* @param {Array} msg
* @param {Object} chanData
* @private
*/
_handleTickerMessage (msg = [], chanData = {}) {
let data = getMessagePayload(msg)
if (this._transform) {
data = (chanData.symbol || '')[0] === 't'
? new TradingTicker([chanData.symbol, ...msg[1]])
: new FundingTicker([chanData.symbol, ...msg[1]])
}
const internalMessage = [chanData.chanId, 'ticker', data]
internalMessage.filterOverride = [chanData.symbol]
this._propagateMessageToListeners(internalMessage, chanData, false)
this.emit('ticker', chanData.symbol, data)
}
/**
* Called for messages from a 'candles' channel. Might be an update or
* snapshot.
*
* @param {Array|Array[]} msg
* @param {Object} chanData - entry from _channelMap
* @private
*/
_handleCandleMessage (msg, chanData) {
const { key } = chanData
let data = getMessagePayload(msg)
if (this._manageCandles) {
const err = this._updateManagedCandles(key, data)
if (err) {
this.emit('error', err)
return
}
data = this._candles[key]
} else if (data.length > 0 && !Array.isArray(data[0])) {
data = [data] // always pass on an array of candles
}
if (this._transform) {
data = Candle.unserialize(data)
}
const internalMessage = [chanData.chanId, 'candle', data]
internalMessage.filterOverride = [chanData.key]
this._propagateMessageToListeners(internalMessage, chanData, false)
this.emit('candle', data, key)
}
/**
* @param {string} symbol
* @param {number[]|number[][]} data
* @return {Error} err - null on success
* @private
*/
_updateManagedCandles (key, data) {
if (Array.isArray(data[0])) { // snapshot, new candles
data.sort((a, b) => b[0] - a[0])
this._candles[key] = data
return null
}
// entry, needs to be applied to candle set
if (!this._candles[key]) {
return new Error(`recv update for unknown candles: ${key}`)
}
const candles = this._candles[key]
let updated = false
for (let i = 0; i < candles.length; i++) {
if (data[0] === candles[i][0]) {
candles[i] = data
updated = true
break
}
}
if (!updated) {
candles.unshift(data)
}
return null
}
/**
* Fetch a reference to the full set of synced candles for the specified key.
* Set `manageCandles: true` in the constructor to use.
*
* @param {string} key
* @return {Array} candles - empty array if none exist
*/
getCandles (key) {
return this._candles[key] || []
}
/**
* @param {Array} msg
* @param {Object} chanData
* @private
*/
_handleAuthMessage (msg, chanData) {
if (msg[1] === 'n') {
const payload = getMessagePayload(msg)
if (payload) {
this._onWSNotification(payload)
}
} else if (msg[1] === 'te') {
msg[1] = 'auth-te'
} else if (msg[1] === 'tu') {
msg[1] = 'auth-tu'
}
this._propagateMessageToListeners(msg, chanData)
}
/**
* @param {Array} msg
* @param {Object} chan - channel data
* @param {boolean} transform - defaults to internal flag
* @private
*/
_propagateMessageToListeners (msg, chan, transform = this._transform) {
const listenerGroups = Object.values(this._listeners)
for (let i = 0; i < listenerGroups.length; i++) {
WSv2._notifyListenerGroup(listenerGroups[i], msg, transform, this, chan)
}
}
/**
* Applies filtering & transform to a packet before sending it out to matching
* listeners in the group.
*
* @param {Object} lGroup - listener group to parse & notify
* @param {Object} msg - passed to each matched listener
* @param {boolean} transform - whether or not to instantiate a model
* @param {WSv2} ws - instance to pass to models if transforming
* @param {Object} chanData - channel data
* @private
*/
static _notifyListenerGroup (lGroup, msg, transform, ws, chanData) {
const [, eventName, data = []] = msg
let filterByData
// Catch-all can't filter/transform
WSv2._notifyCatchAllListeners(lGroup, msg)
if (!lGroup[eventName] || lGroup[eventName].length === 0) return
const listeners = lGroup[eventName].filter((listener) => {
const { filter } = listener
if (!filter) return true
// inspect snapshots for matching packets
if (Array.isArray(data[0])) {
const matchingData = data.filter((item) => {
filterByData = msg.filterOverride ? msg.filterOverride : item
return WSv2._payloadPassesFilter(filterByData, filter)
})
return matchingData.length !== 0
}
// inspect single packet
filterByData = msg.filterOverride ? msg.filterOverride : data
return WSv2._payloadPassesFilter(filterByData, filter)
})
if (listeners.length === 0) return
listeners.forEach(({ cb, modelClass }) => {
const ModelClass = modelClass
if (!transform || data.length === 0) {
cb(data, chanData)
} else if (Array.isArray(data[0])) {
cb(data.map((entry) => {
return new ModelClass(entry, ws)
}), chanData)
} else {
cb(new ModelClass(data, ws), chanData)
}
})
}
/**
* @param {Array} payload
* @param {Object} filter
* @return {boolean} pass
* @private
*/
static _payloadPassesFilter (payload, filter) {
const filterIndices = Object.keys(filter)
for (let k = 0; k < filterIndices.length; k++) {
if (!filter[filterIndices[k]]) continue // no value provided
if (payload[+filterIndices[k]] !== filter[filterIndices[k]]) {
return false
}
}
return true
}
/**
* @param {Object} lGroup - listener group keyed by event ('' in this case)
* @param {*} data - packet to pass to listeners
* @private
*/
static _notifyCatchAllListeners (lGroup, data) {
if (!lGroup['']) return
for (let j = 0; j < lGroup[''].length; j++) {
lGroup[''][j].cb(data)
}
}
/**
* @param {Object} msg
* @private
*/
_handleEventMessage (msg) {
if (msg.event === 'auth') {
return this._handleAuthEvent(msg)
} else if (msg.event === 'subscribed') {
return this._handleSubscribedEvent(msg)
} else if (msg.event === 'unsubscribed') {
return this._handleUnsubscribedEvent(msg)
} else if (msg.event === 'info') {
return this._handleInfoEvent(msg)
} else if (msg.event === 'conf') {
return this._handleConfigEvent(msg)
} else if (msg.event === 'error') {
return this._handleErrorEvent(msg)
} else if (msg.event === 'pong') {
return this._handlePongEvent(msg)
}
debug('recv unknown event message: %j', msg)
return null
}