-
Notifications
You must be signed in to change notification settings - Fork 210
Expand file tree
/
Copy pathws2_manager.js.html
More file actions
629 lines (526 loc) · 26.1 KB
/
ws2_manager.js.html
File metadata and controls
629 lines (526 loc) · 26.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ws2_manager.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#.getDataChannelCount">getDataChannelCount</a></li><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></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#cancelFundingOffer">cancelFundingOffer</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#closeFundingCredit">closeFundingCredit</a></li><li data-type='method'><a href="WSv2.html#closeFundingLoan">closeFundingLoan</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#setAPICredentials">setAPICredentials</a></li><li data-type='method'><a href="WSv2.html#submitFundingOffer">submitFundingOffer</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">ws2_manager.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>'use strict'
const { EventEmitter } = require('events')
const debug = require('debug')('bfx:ws2:manager')
const _isEqual = require('lodash/isEqual')
const _isFinite = require('lodash/isFinite')
const _includes = require('lodash/includes')
const _pick = require('lodash/pick')
const Promise = require('bluebird')
const PromiseThrottle = require('promise-throttle')
const WSv2 = require('./transports/ws2')
const DATA_CHANNEL_LIMIT = 30
const reconnectThrottler = new PromiseThrottle({
requestsPerSecond: 10 / 60.0,
promiseImplementation: Promise
})
/**
* Provides a wrapper around the WSv2 class, opening new sockets when a
* subscription would push a single socket over the data channel limit.
*
* For more complex operations, grab a socket reference with getSocket() or
* getFreeDataSocket(), or create a new WSv2 instance manually
*
* @example
* const rest = new RESTv2()
* const details = await rest.symbolDetails()
* const symbols = details.map(d => `t${d.pair.toUpperCase()}`)
* const timeFrames = ['1m', '5m', '30m', '1h', '6h']
* const keys = _flatten(symbols.map(s => {
* return timeFrames.map(tf => `trade:${tf}:${s}`)
* }))
*
* const m = new Manager()
*
* m.on('error', (err) => {
* debug('error: %s', err)
* })
*
* m.once('open', () => {
* debug('open')
*
* keys.forEach(key => {
* m.subscribeCandles(key)
* m.onCandle({ key }, (candles) => {
* debug('recv %d candles on channel %s', candles.length, key)
* })
* })
*
* symbols.forEach(symbol => {
* m.subscribeTrades(symbol)
* m.onTrades({ symbol }, (trades) => {
* debug('recv %d trades on channel %s', trades.length, symbol)
* })
* })
*
* symbols.forEach(symbol => {
* m.subscribeTicker(symbol)
* m.onTicker({ symbol }, (ticker) => {
* debug('recv ticker on channel %s: %j', symbol, ticker)
* })
* })
*
* symbols.forEach(symbol => {
* m.subscribeOrderBook(symbol)
* m.onOrderBook({ symbol }, (update) => {
* debug('recv book update on channel %s: %j', symbol, update)
* })
* })
*
* setInterval(() => {
* debug('num keys: %d', keys.length)
* debug('num sockets: %d', m.getNumSockets())
* debug('socket info: %j', m.getSocketInfo())
* }, 5000)
* })
*
* m.openSocket()
*/
class WS2Manager extends EventEmitter {
/**
* @param {object} socketArgs - passed to WSv2 constructors
* @param {object} [authArgs] - cached for all internal socket auth() calls
* @param {object} [authArgs.calc] - default 0
* @param {object} [authArgs.dms] - default 0
*/
constructor (socketArgs, authArgs = { calc: 0, dms: 0 }) {
super()
this.setMaxListeners(1000)
this._authArgs = authArgs
this._sockets = []
this._socketArgs = {
...(socketArgs || {}),
reconnectThrottler
}
}
/**
* Update authentication arguments on all sockets
*
* @param {object} args - arguments
* @param {object} [args.calc] - calc value
* @param {object} [args.dms] - active 4
*/
setAuthArgs (args = {}) {
this._authArgs = {
...this._authArgs,
...args
}
this._sockets.forEach(socket => socket.ws.updateAuthArgs(this._authArgs))
}
/**
* Retrieve internal authentication arguments
*
* @returns {object} args
*/
getAuthArgs () {
return this._authArgs
}
/**
* Reconnects all open sockets
*
* @returns {Promise} p
*/
async reconnect () {
return Promise.all(this._sockets.map(socket => socket.ws.reconnect()))
}
/**
* Closes all open sockets
*
* @returns {Promise} p
*/
async close () {
return Promise.all(this._sockets.map(socket => socket.ws.close()))
}
/**
* @param {object} s - socket state
* @returns {number} count - # of subscribed/pending data channels
*/
static getDataChannelCount (s) {
let count = s.ws.getDataChannelCount()
count += s.pendingSubscriptions.length
count -= s.pendingUnsubscriptions.length
return count
}
/**
* @returns {number} n
*/
getNumSockets () {
return this._sockets.length
}
/**
* @param {number} i - index into pool
* @returns {object} state
*/
getSocket (i) {
return this._sockets[i]
}
/**
* Returns an object which can be logged to inspect the socket pool
*
* @returns {object[]} socketInfo
*/
getSocketInfo () {
return this._sockets.map(s => ({
nChannels: WS2Manager.getDataChannelCount(s)
}))
}
/**
* Authenticates all existing & future sockets with the provided credentials.
* Does nothing if an apiKey/apiSecret pair are already known.
*
* @param {object} args - arguments
* @param {object} args.apiKey - saved if not already provided
* @param {object} args.apiSecret - saved if not already provided
* @param {object} [args.calc] - default 0
* @param {object} [args.dms] - dead man switch, active 4
*/
auth ({ apiKey, apiSecret, calc, dms } = {}) {
if (this._socketArgs.apiKey || this._socketArgs.apiSecret) {
debug('error: auth credentials already provided! refusing auth')
return
}
this._socketArgs.apiKey = apiKey
this._socketArgs.apiSecret = apiSecret
if (_isFinite(calc)) this._authArgs.calc = calc
if (_isFinite(dms)) this._authArgs.dms = dms
this._sockets.forEach(s => {
if (!s.ws.isAuthenticated()) {
s.ws.setAPICredentials(apiKey, apiSecret)
s.ws.updateAuthArgs(this._authArgs)
s.ws.auth()
}
})
}
/**
* Creates a new socket/state instance and adds it to the internal pool. Binds
* event listeners to forward via our own event emitter, and to manage pending
* subs/unsubs.
*
* @returns {object} state
*/
openSocket () {
const { apiKey, apiSecret } = this._socketArgs
const ws = new WSv2(this._socketArgs)
const wsState = {
pendingSubscriptions: [],
pendingUnsubscriptions: [],
ws
}
ws.updateAuthArgs(this._authArgs)
ws.on('open', () => this.emit('open', ws))
ws.on('message', (msg = {}) => this.emit('message', msg, ws))
ws.on('error', (error) => this.emit('error', error, ws))
ws.on('auth', () => this.emit('auth', ws))
ws.on('close', () => this.emit('close', ws))
ws.on('subscribed', (msg = {}) => {
this.emit('subscribed', msg)
const i = wsState.pendingSubscriptions.find(sub => {
const fv = _pick(msg, Object.keys(sub[1]))
return (
(sub[0] === msg.channel) &&
_isEqual(fv, sub[1])
)
})
if (i === -1) {
debug('error removing pending sub: %j', msg)
return
}
wsState.pendingSubscriptions.splice(i, 1)
})
ws.on('unsubscribed', (msg = {}) => {
this.emit('unsubscribed', msg)
const { chanId } = msg
const i = wsState.pendingUnsubscriptions.findIndex(cid => (
cid === `${chanId}`
))
if (i === -1) {
debug('error removing pending unsub: %j', msg)
return
}
wsState.pendingUnsubscriptions.splice(i, 1)
})
if (apiKey && apiSecret) { // auto-auth
ws.once('open', () => {
debug('authenticating socket...')
ws.auth().then(() => {
return debug('socket authenticated')
}).catch((err) => {
debug('error authenticating socket: %s', err.message)
})
})
}
ws.open().then(() => {
return debug('socket connection opened')
}).catch((err) => {
debug('error opening socket: %s', err.stack)
})
this._sockets.push(wsState)
return wsState
}
/**
* @returns {object} state
*/
getAuthenticatedSocket () {
return this._sockets.find(s => s.ws.isAuthenticated())
}
/**
* Returns the first socket that has less active/pending channels than the
* DATA_CHANNEL_LIMIT
*
* @returns {object} state - undefined if none found
*/
getFreeDataSocket () {
return this._sockets.find(s => (
WS2Manager.getDataChannelCount(s) < DATA_CHANNEL_LIMIT
))
}
/**
* Returns the first socket that is subscribed/pending sub to the specified
* channel.
*
* @param {string} type - i.e. 'book'
* @param {object} filter - i.e. { symbol: 'tBTCUSD', prec: 'R0' }
* @returns {object} wsState - undefined if not found
*/
getSocketWithDataChannel (type, filter) {
return this._sockets.find(s => {
const subI = s.pendingSubscriptions.findIndex(s => (
s[0] === type && _isEqual(s[1], filter)
))
if (subI !== -1) {
return true
}
// Confirm unsub is not pending
const cid = s.ws.getDataChannelId(type, filter)
if (!cid) {
return false
}
return cid && !_includes(s.pendingUnsubscriptions, cid)
})
}
/**
* NOTE: Cannot filter against pending subscriptions, due to unknown chanId
*
* @param {number} chanId - channel ID
* @returns {object} wsState - undefined if not found
*/
getSocketWithChannel (chanId) {
return this._sockets.find(s => {
return (
s.ws.hasChannel(chanId) &&
!_includes(s.pendingUnsubscriptions, chanId)
)
})
}
/**
* @param {string} channel - channel type
* @param {string} identifier - unique channel identifier
* @returns {object} wsState - undefined if not found
*/
getSocketWithSubRef (channel, identifier) {
return this._sockets.find(s => s.ws.hasSubscriptionRef(channel, identifier))
}
/**
* Calls the provided cb with all internal socket instances
*
* @param {Function} cb - callback
*/
withAllSockets (cb) {
this._sockets.forEach((ws2) => {
cb(ws2)
})
}
/**
* Subscribes a free data socket if available to the specified channel, or
* opens a new socket & subs if needed.
*
* @param {string} type - i.e. 'book'
* @param {string} ident - i.e. 'tBTCUSD'
* @param {object} filter - i.e. { symbol: 'tBTCUSD', prec: 'R0' }
*/
subscribe (type, ident, filter) {
let s = this.getFreeDataSocket()
if (!s) {
s = this.openSocket()
}
const doSub = () => {
s.ws.managedSubscribe(type, ident, filter)
}
if (!s.ws.isOpen()) {
s.ws.once('open', doSub)
} else {
doSub()
}
s.pendingSubscriptions.push([type, filter])
}
/**
* @param {string} channel - channel type
* @param {string} identifier - unique channel identifier
*/
managedUnsubscribe (channel, identifier) {
const s = this.getSocketWithSubRef(channel, identifier)
if (!s) {
debug('cannot unsub from unknown channel %s: %s', channel, identifier)
return
}
const chanId = s.ws._chanIdByIdentifier(channel, identifier)
s.ws.managedUnsubscribe(channel, identifier)
s.pendingUnsubscriptions.push(chanId)
}
/**
* Unsubscribes the first socket w/ the specified channel. Does nothing if no
* such socket is found.
*
* @param {number} chanId - channel ID
*/
unsubscribe (chanId) {
const s = this.getSocketWithChannel(chanId)
if (!s) {
debug('cannot unsub from unknown channel: %d', chanId)
return
}
s.ws.unsubscribe(chanId)
s.pendingUnsubscriptions.push(chanId)
}
/**
* @param {string} symbol - symbol for ticker
*/
subscribeTicker (symbol) {
this.subscribe('ticker', symbol, { symbol })
}
/**
* @param {string} symbol - symbol for trades
*/
subscribeTrades (symbol) {
this.subscribe('trades', symbol, { symbol })
}
/**
* @param {string} symbol - symbol for order book
* @param {string} [prec] - precision, i.e. 'R0', default 'P0'
* @param {string} [len] - length, default '25'
* @param {string} [freq] - default 'F0'
*/
subscribeOrderBook (symbol, prec = 'P0', len = '25', freq = 'F0') {
const filter = {}
if (symbol) filter.symbol = symbol
if (prec) filter.prec = prec
if (len) filter.len = len
if (freq) filter.freq = freq
this.subscribe('book', symbol, filter)
}
/**
* @param {string} key - candle channel key
*/
subscribeCandles (key) {
this.subscribe('candles', key, { key })
}
/**
* @param {object} opts - options
* @param {string} opts.key - candle set key, i.e. trade:30m:tBTCUSD
* @param {string} [opts.cbGID] - callback group id
* @param {Function} cb - callback
* @throws an error if no data socket is available
* @see https://docs.bitfinex.com/v2/reference#ws-public-candle
*/
onCandle ({ key, cbGID }, cb) {
const s = this.getSocketWithDataChannel('candles', { key })
if (!s) {
throw new Error('no data socket available; did you provide a key?')
}
s.ws.onCandle({ key, cbGID }, cb)
}
/**
* @param {object} opts - options
* @param {string} opts.symbol - order book symbol
* @param {string} [opts.prec] - precision, i.e. 'R0', default 'P0'
* @param {string} [opts.len] - length, default '25'
* @param {string} [opts.freq] - default 'F0'
* @param {string} [opts.cbGID] - callback group id
* @param {Function} cb - callback
* @throws an error if no data socket is available
* @see https://docs.bitfinex.com/v2/reference#ws-public-order-books
*/
onOrderBook ({ symbol, prec = 'P0', len = '25', freq = 'F0', cbGID }, cb) {
const filter = {}
if (symbol) filter.symbol = symbol
if (prec) filter.prec = prec
if (len) filter.len = len
if (freq) filter.freq = freq
const s = this.getSocketWithDataChannel('book', filter)
if (!s) {
throw new Error('no data socket available; did you provide a symbol?')
}
s.ws.onOrderBook({ cbGID, ...filter }, cb)
}
/**
* @param {object} opts - options
* @param {string} [opts.symbol] - symbol for trades
* @param {string} [opts.cbGID] - callback group id
* @param {Function} cb - callback
* @throws an error if no data socket is available
* @see https://docs.bitfinex.com/v2/reference#ws-public-trades
*/
onTrades ({ symbol, cbGID }, cb) {
const s = this.getSocketWithDataChannel('trades', { symbol })
if (!s) {
throw new Error('no data socket available; did you provide a symbol?')
}
s.ws.onTrades({ symbol, cbGID }, cb)
}
/**
* @param {object} opts - options
* @param {string} [opts.symbol] - symbol for ticker
* @param {string} [opts.cbGID] - callback group id
* @param {Function} cb - callback
* @throws an error if no data socket is available
* @see https://docs.bitfinex.com/v2/reference#ws-public-ticker
*/
onTicker ({ symbol = '', cbGID } = {}, cb) {
const s = this.getSocketWithDataChannel('ticker', { symbol })
if (!s) {
throw new Error('no data socket available; did you provide a symbol?')
}
s.ws.onTicker({ symbol, cbGID }, cb)
}
}
module.exports = WS2Manager
</code></pre>
</article>
</section>
</div>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.6.4</a> on Fri Jun 05 2020 17:26:26 GMT+0300 (Eastern European Summer Time) using the <a href="https://github.com/clenemt/docdash">docdash</a> theme.
</footer>
<script>prettyPrint();</script>
<script src="scripts/polyfill.js"></script>
<script src="scripts/linenumber.js"></script>
</body>
</html>