code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
async reconnect () {
return Promise.all(this._sockets.map(socket => socket.ws.reconnect()))
}
|
Reconnects all open sockets
@returns {Promise} p
|
reconnect
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
async close () {
return Promise.all(this._sockets.map(socket => socket.ws.close()))
}
|
Closes all open sockets
@returns {Promise} p
|
close
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
static getDataChannelCount (s) {
let count = s.ws.getDataChannelCount()
count += s.pendingSubscriptions.length
count -= s.pendingUnsubscriptions.length
return count
}
|
@param {object} s - socket state
@returns {number} count - # of subscribed/pending data channels
|
getDataChannelCount
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
getSocket (i) {
return this._sockets[i]
}
|
@param {number} i - index into pool
@returns {object} state
|
getSocket
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
getSocketInfo () {
return this._sockets.map(s => ({
nChannels: WS2Manager.getDataChannelCount(s)
}))
}
|
Returns an object which can be logged to inspect the socket pool
@returns {object[]} socketInfo
|
getSocketInfo
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
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
if (apiKey) this._authArgs.apiKey = apiKey
if (apiSecret) this._authArgs.apiSecret = apiSecret
this._sockets.forEach(s => {
if (!s.ws.isAuthenticated()) {
s.ws.updateAuthArgs(this._authArgs)
s.ws.auth()
}
})
}
|
Authenticates all existing & future sockets with the provided credentials.
Does nothing if an apiKey/apiSecret pair are already known.
@param {object} args - arguments
@param {string} args.apiKey - saved if not already provided
@param {string} args.apiSecret - saved if not already provided
@param {number} [args.calc] - default 0
@param {number} [args.dms] - dead man switch, active 4
|
auth
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
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)
})
}
|
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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
getSocketWithChannel (chanId) {
return this._sockets.find(s => {
return (
s.ws.hasChannel(chanId) &&
!_includes(s.pendingUnsubscriptions, chanId)
)
})
}
|
NOTE: Cannot filter against pending subscriptions, due to unknown chanId
@param {number} chanId - channel ID
@returns {object} wsState - undefined if not found
|
getSocketWithChannel
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
getSocketWithSubRef (channel, identifier) {
return this._sockets.find(s => s.ws.hasSubscriptionRef(channel, identifier))
}
|
@param {string} channel - channel type
@param {string} identifier - unique channel identifier
@returns {object} wsState - undefined if not found
|
getSocketWithSubRef
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
withAllSockets (cb) {
this._sockets.forEach((ws2) => {
cb(ws2)
})
}
|
Calls the provided cb with all internal socket instances
@param {Function} cb - callback
|
withAllSockets
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
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])
}
|
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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
doSub = () => {
s.ws.managedSubscribe(type, ident, filter)
}
|
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' }
|
doSub
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
doSub = () => {
s.ws.managedSubscribe(type, ident, filter)
}
|
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' }
|
doSub
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
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)
}
|
@param {string} channel - channel type
@param {string} identifier - unique channel identifier
|
managedUnsubscribe
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
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)
}
|
Unsubscribes the first socket w/ the specified channel. Does nothing if no
such socket is found.
@param {number} chanId - channel ID
|
unsubscribe
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
subscribeTicker (symbol) {
this.subscribe('ticker', symbol, { symbol })
}
|
@param {string} symbol - symbol for ticker
|
subscribeTicker
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
subscribeTrades (symbol) {
this.subscribe('trades', symbol, { symbol })
}
|
@param {string} symbol - symbol for trades
|
subscribeTrades
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
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} 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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
subscribeCandles (key) {
this.subscribe('candles', key, { key })
}
|
@param {string} key - candle channel key
|
subscribeCandles
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
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.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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
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 - 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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
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 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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
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)
}
|
@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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/ws2_manager.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/ws2_manager.js
|
MIT
|
updateAuthArgs (args = {}) {
this._authArgs = {
...this._authArgs,
...args
}
}
|
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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
getAuthArgs () {
return this._authArgs
}
|
Fetch the current default auth parameters
@returns {object} authArgs
@see WSv2#updateAuthArgs
@see WSv2#auth
|
getAuthArgs
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
getDataChannelCount () {
return Object
.values(this._channelMap)
.filter(c => _includes(DATA_CHANNEL_TYPES, c.channel))
.length
}
|
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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
hasChannel (chanId) {
return !!this._channelMap[chanId]
}
|
Check if the instance is subscribed to the specified channel ID
@param {number} chanId - ID of channel to query
@returns {boolean} isSubscribed
|
hasChannel
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
hasSubscriptionRef (channel, identifier) {
const key = `${channel}:${identifier}`
return !!Object.keys(this._subscriptionRefs).find(ref => ref === key)
}
|
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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
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)
})
}
|
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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
hasDataChannel (type, filter) {
return !!this.getDataChannelId(type, 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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
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()
})
})
}
|
Opens a connection to the API server. Rejects with an error if a
connection is already open. Resolves on success.
@returns {Promise} p
|
open
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
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)
}
})
}
|
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
|
close
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
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
})
})
}
|
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
|
auth
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
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
}
|
Utility method to close & re-open the ws connection. Re-authenticates if
previously authenticated
@returns {Promise} p - resolves on completion
|
reconnect
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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
}
|
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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
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()
}
|
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
|
_triggerPacketWD
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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)
}
|
Reset the packet watch-dog timeout. Should be called on every new WS packet
if the watch-dog is enabled
@private
|
_resetPacketWD
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
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)
}
}
})
}
|
Subscribes to previously subscribed channels, used after reconnecting
@private
|
resubscribePreviousChannels
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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 {Array} arrN - notification in ws array format
@private
|
_onWSNotification
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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 {string} rawMsg - incoming message JSON
@param {string} flags - flags
@private
|
_onWSMessage
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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 {string} rawMsg - message JSON
@private
|
_handleChannelMessage
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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)
}
|
@param {Array} msg - message
@param {object} chanData - channel definition
@private
|
_handleOBChecksumMessage
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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)
}
|
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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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 {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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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
}
|
@param {string} symbol - symbol for order book
@param {string} prec - precision
@param {number} cs - expected checksum
@returns {Error} err - null if none
@private
|
_verifyManagedOBChecksum
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
getOB (symbol) {
if (!this._orderBooks[symbol]) return null
return new OrderBook(this._orderBooks[symbol])
}
|
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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
getLosslessOB (symbol) {
if (!this._losslessOrderBooks[symbol]) return null
return new OrderBook(this._losslessOrderBooks[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
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_handleTradeMessage (msg, chanData) {
const eventName = msg[1][0] === 'f'
? msg[1] // Funding trades are passed to fte/ftu handlers
: msg[1] === 'te'
? 'trade-entry'
: 'trades'
let payload = getMessagePayload(msg)
if (!Array.isArray(payload[0])) {
payload = [payload]
}
let data = payload
if (this._transform) { // correctly parse single trade/array of trades
const M = eventName[0] === 'f' && msg[2].length === 8 ? FundingTrade : PublicTrade
const trades = M.unserialize(data)
if (_isArray(trades) && trades.length === 1) {
data = trades[0]
} else {
data = trades
}
data = new M(data)
}
const internalMessage = [chanData.chanId, eventName, data]
internalMessage.filterOverride = [chanData.symbol || chanData.pair]
this._propagateMessageToListeners(internalMessage, chanData, false)
this.emit('trades', chanData.symbol || chanData.pair, data)
}
|
@param {Array} msg - incoming message
@param {object} chanData - channel definition
@private
|
_handleTradeMessage
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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)
}
|
@param {Array} msg - incoming message
@param {object} chanData - channel definition
@private
|
_handleTickerMessage
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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)
}
|
Called for messages from a 'candles' channel. Might be an update or
snapshot.
@param {Array|Array[]} msg - incoming message
@param {object} chanData - entry from _channelMap
@private
|
_handleCandleMessage
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_handleStatusMessage (msg, chanData) {
const { key } = chanData
const data = getMessagePayload(msg)
const internalMessage = [chanData.chanId, 'status', data]
internalMessage.filterOverride = [chanData.key]
this._propagateMessageToListeners(internalMessage, chanData, false)
this.emit('status', data, key)
}
|
Called for messages from a 'status' channel.
@param {Array|Array[]} msg - incoming message
@param {object} chanData - entry from _channelMap
@private
|
_handleStatusMessage
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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
}
|
@param {string} key - key for candle set
@param {number[]|number[][]} data - incoming dataset (single or multiple)
@returns {Error} err - null on success
@private
|
_updateManagedCandles
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
getCandles (key) {
return this._candles[key] || []
}
|
Fetch a reference to the full set of synced candles for the specified key.
Set `managedCandles: true` in the constructor to use.
@param {string} key - key for candle set
@returns {Array} candles - empty array if none exist
@example
const ws = new WSv2({ managedCandles: true })
ws.on('open', async () => {
ws.onCandles({ key: 'trade:1m:tBTCUSD' }, () => {
const candles = ws.getCandles('trade:1m:tBTCUSD')
if (!candles) return
console.log('%d candles in dataset', candles.length)
})
ws.subscribeCandles({ key: 'trade:1m:tBTCUSD' })
})
await ws.open()
|
getCandles
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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 - incoming message
@param {object} chanData - channel data
@private
|
_handleAuthMessage
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_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)
}
}
|
@param {Array} msg - incoming message
@param {object} chan - channel data
@param {boolean} transform - defaults to internal flag
@private
|
_propagateMessageToListeners
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
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 (!ModelClass || !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)
}
})
}
|
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
|
_notifyListenerGroup
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
static _payloadPassesFilter (payload, filter) {
const filterIndices = Object.keys(filter)
let filterValue
for (let k = 0; k < filterIndices.length; k++) {
filterValue = filter[filterIndices[k]]
if (_isEmpty(filterValue) || filterValue === '*') {
continue
}
if (payload[+filterIndices[k]] !== filterValue) {
return false
}
}
return true
}
|
@param {Array} payload - payload to verify
@param {object} filter - filter to match against payload
@returns {boolean} pass
@private
|
_payloadPassesFilter
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
static _notifyCatchAllListeners (lGroup, data) {
if (!lGroup['']) return
for (let j = 0; j < lGroup[''].length; j++) {
lGroup[''][j].cb(data)
}
}
|
@param {object} lGroup - listener group keyed by event ('' in this case)
@param {*} data - packet to pass to listeners
@private
|
_notifyCatchAllListeners
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_handleEventMessage (msg) {
if (msg.event === 'auth') {
this._handleAuthEvent(msg)
} else if (msg.event === 'subscribed') {
this._handleSubscribedEvent(msg)
} else if (msg.event === 'unsubscribed') {
this._handleUnsubscribedEvent(msg)
} else if (msg.event === 'info') {
this._handleInfoEvent(msg)
} else if (msg.event === 'conf') {
this._handleConfigEvent(msg)
} else if (msg.event === 'error') {
this._handleErrorEvent(msg)
} else if (msg.event === 'pong') {
this._handlePongEvent(msg)
} else {
debug('recv unknown event message: %j', msg)
}
}
|
@param {object} msg - incoming message
@private
|
_handleEventMessage
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_handlePongEvent (msg) {
debug('pong: %s', JSON.stringify(msg))
this.emit('pong', msg)
}
|
@param {object} msg - incoming message
@private
|
_handlePongEvent
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_handleErrorEvent (msg) {
debug('error: %s', JSON.stringify(msg))
this.emit('error', msg)
}
|
@param {object} msg - incoming message
@private
|
_handleErrorEvent
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_handleAuthEvent (data = {}) {
const { chanId, msg = '', status = '' } = data
if (status !== 'OK') {
const err = new Error(msg.match(/nonce/)
? 'auth failed: nonce small; you may need to generate a new API key to reset the nonce counter'
: `auth failed: ${msg} (${status})`
)
debug('%s', err.message)
this.emit('error', err)
return
}
this._channelMap[chanId] = { channel: 'auth' }
this._isAuthenticated = true
this.emit('auth', data)
debug('authenticated!')
}
|
@param {object} data - incoming message
@private
|
_handleAuthEvent
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_handleSubscribedEvent (msg) {
this._channelMap[msg.chanId] = msg
debug('subscribed to %s [%d]', msg.channel, msg.chanId)
this.emit('subscribed', msg)
}
|
@param {object} msg - incoming message
@private
|
_handleSubscribedEvent
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_handleUnsubscribedEvent (msg) {
delete this._channelMap[msg.chanId]
debug('unsubscribed from %d', msg.chanId)
this.emit('unsubscribed', msg)
}
|
@param {object} msg - incoming message
@private
|
_handleUnsubscribedEvent
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_handleInfoEvent (msg = {}) {
const { version, code } = msg
if (version) {
if (version !== 2) {
const err = new Error(`server not running API v2: v${version}`)
this.emit('error', err)
this.close().catch((err) => {
debug('error closing connection: %s', err.stack)
})
return
}
const { status } = msg.platform || {}
debug(
'server running API v2 (platform: %s (%d))',
status === 0 ? 'under maintenance' : 'operating normally', status
)
} else if (code) {
if (this._infoListeners[code]) {
this._infoListeners[code].forEach(cb => cb(msg))
}
if (code === WSv2.info.SERVER_RESTART) {
debug('server restarted, please reconnect')
} else if (code === WSv2.info.MAINTENANCE_START) {
debug('server maintenance period started!')
} else if (code === WSv2.info.MAINTENANCE_END) {
debug('server maintenance period ended!')
}
}
this.emit('info', msg)
}
|
@param {object} msg - incoming message
@private
|
_handleInfoEvent
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
managedSubscribe (channel = '', identifier = '', payload = {}) {
const key = `${channel}:${identifier}`
if (this._subscriptionRefs[key]) {
this._subscriptionRefs[key]++
return false
}
this._subscriptionRefs[key] = 1
this.subscribe(channel, payload)
return true
}
|
Subscribes and tracks subscriptions per channel/identifier pair. If
already subscribed to the specified pair, nothing happens.
@param {string} channel - channel name
@param {string} identifier - for uniquely identifying the ref count
@param {object} payload - merged with sub packet
@returns {boolean} subSent
@todo will be refactored to return promise from subscribe() call instead
of sub action taken flag
@see WSv2#subscribeTrades
@see WSv2#subscribeTicker
@see WSv2#subscribeCandles
@see WSv2#subscribeOrderBook
@example
const ws = new WSv2()
ws.on('open', async () => {
ws.onTrades({ symbol: 'tBTCUSD' }, (trades) => {
console.log('recv trades: %j', trades)
})
ws.managedSubscribe('trades', 'tBTCUSD', { symbol: 'tBTCUSD' })
})
await ws.open()
|
managedSubscribe
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
managedUnsubscribe (channel = '', identifier = '') {
const key = `${channel}:${identifier}`
const chanId = this._chanIdByIdentifier(channel, identifier)
if (chanId === null || isNaN(this._subscriptionRefs[key])) return false
this._subscriptionRefs[key]--
if (this._subscriptionRefs[key] > 0) return false
this.unsubscribe(chanId)
delete this._subscriptionRefs[key]
return true
}
|
Decreases the subscription ref count for the channel/identifier pair, and
unsubscribes from the channel if it reaches 0.
@param {string} channel - channel name
@param {string} identifier - for uniquely identifying the ref count
@returns {boolean} unsubSent
|
managedUnsubscribe
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
getChannelData ({ chanId, channel, symbol, key }) {
const id = chanId || this._chanIdByIdentifier(channel, symbol || key)
return this._channelMap[id] || null
}
|
Fetch a channel definition
@param {object} opts - options
@param {number} opts.chanId - channel ID
@param {string} opts.channel - channel name
@param {string} [opts.symbol] - match by symbol
@param {string} [opts.key] - match by key (for candle channels)
@returns {object} chanData - null if not found
|
getChannelData
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_chanIdByIdentifier (channel, identifier) {
const channelIds = Object.keys(this._channelMap)
let chan
for (let i = 0; i < channelIds.length; i++) {
chan = this._channelMap[channelIds[i]]
if (chan.channel === channel && (
chan.symbol === identifier ||
chan.key === identifier
)) {
return channelIds[i]
}
}
return null
}
|
@param {string} channel - channel name
@param {string} identifier - unique identifier for the channel
@returns {number} channelID
@private
|
_chanIdByIdentifier
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_getEventPromise (key) {
return new Promise((resolve, reject) => {
this._eventCallbacks.push(key, (err, res) => {
if (err) {
return reject(err)
}
resolve(res)
})
})
}
|
@param {string} key - key for the promise
@returns {Promise} p - resolves on event
@private
|
_getEventPromise
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
send (msg) {
if (!this._ws || !this._isOpen) {
this.emit('error', new Error('no ws client or not open'))
} else if (this._isClosing) {
this.emit('error', new Error('connection currently closing'))
} else {
debug('sending %j', msg)
this._ws.send(JSON.stringify(msg))
}
}
|
Send a packet to the WS server
@param {*} msg - packet, gets stringified
|
send
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
async enableFlag (flag) {
this._enabledFlags = this._enabledFlags | flag
if (!this._isOpen) {
return
}
this.sendEnabledFlags()
return this._getEventPromise(this._getConfigEventKey(flag))
}
|
Enables a configuration flag.
@param {number} flag - flag to update, as numeric value
@returns {Promise} p
@see WSv2#flags
@example
const ws = new WSv2()
ws.on('open', async () => {
await ws.enableFlag(WSv2.flags.CHECKSUM)
console.log('ob checkums enabled')
})
await ws.open()
|
enableFlag
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
sendEnabledFlags () {
this.send({
event: 'conf',
flags: this._enabledFlags
})
}
|
Sends the local flags value to the server, updating the config
@private
|
sendEnabledFlags
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
isFlagEnabled (flag) {
return (this._enabledFlags & flag) === flag
}
|
Checks local state, relies on successful server config responses
@see enableFlag
@param {number} flag - flag to check for
@returns {boolean} enabled
|
isFlagEnabled
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_getConfigEventKey (flag) {
return `conf-res-${flag}`
}
|
@param {string} flag - flag to fetch event key for
@returns {string} key
@private
|
_getConfigEventKey
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
onServerRestart (cb) {
this.onInfoMessage(WSv2.info.SERVER_RESTART, cb)
}
|
Register a callback in case of a ws server restart message; Use this to
call reconnect() if needed. (code 20051)
@param {Function} cb - called on event trigger
|
onServerRestart
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
onMaintenanceStart (cb) {
this.onInfoMessage(WSv2.info.MAINTENANCE_START, cb)
}
|
Register a callback in case of a 'maintenance started' message from the
server. This is a good time to pause server packets until maintenance ends
@param {Function} cb - called on event trigger
|
onMaintenanceStart
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
onMaintenanceEnd (cb) {
this.onInfoMessage(WSv2.info.MAINTENANCE_END, cb)
}
|
Register a callback to be notified of a maintenance period ending
@param {Function} cb - called on event trigger
|
onMaintenanceEnd
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
subscribe (channel, payload) {
this.send(Object.assign({
event: 'subscribe',
channel
}, payload))
}
|
Subscribe to a channel with the given filter payload
@param {string} channel - channel payload/data
@param {object} payload - optional extra packet data
@example
const ws = new WSv2()
ws.on('open', () => {
ws.onTrades({ symbol: 'tBTCUSD' }, (trades) => {
// ...
})
ws.subscribe('trades', { symbol: 'tBTCUSD' })
})
await ws.open()
|
subscribe
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
async subscribeTicker (symbol) {
return this.managedSubscribe('ticker', symbol, { symbol })
}
|
Subscribe to a ticker data channel
@param {string} symbol - symbol of ticker
@returns {boolean} subscribed
@see WSv2#managedSubscribe
@example
await ws.subscribeTicker('tBTCUSD')
|
subscribeTicker
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
async subscribeTrades (symbol) {
return this.managedSubscribe('trades', symbol, { symbol })
}
|
Subscribe to a trades data channel
@param {string} symbol - symbol of market to monitor
@returns {boolean} subscribed
@see WSv2#managedSubscribe
@example
await ws.subscribeTrades('tBTCUSD')
|
subscribeTrades
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
async subscribeOrderBook (symbol, prec = 'P0', len = '25') {
return this.managedSubscribe('book', symbol, { symbol, len, prec })
}
|
Subscribe to an order book data channel
@param {string} symbol - symbol of order book
@param {string} prec - P0, P1, P2, or P3 (default P0)
@param {string} len - 25 or 100 (default 25)
@returns {boolean} subscribed
@see WSv2#managedSubscribe
@example
await ws.subscribeOrderBook('tBTCUSD', 'R0', '25')
|
subscribeOrderBook
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
async subscribeCandles (key) {
return this.managedSubscribe('candles', key, { key })
}
|
Subscribe to a candle data channel
@param {string} key - 'trade:5m:tBTCUSD'
@returns {boolean} subscribed
@see WSv2#managedSubscribe
@example
await ws.subscribeCandles('trade:5m:tBTCUSD')
|
subscribeCandles
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
async subscribeStatus (key) {
return this.managedSubscribe('status', key, { key })
}
|
Subscribe to a status data channel
@param {string} key - i.e. 'liq:global'
@returns {boolean} subscribed
@see WSv2#managedSubscribe
@example
await ws.subscribeStatus('liq:global')
|
subscribeStatus
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
unsubscribe (chanId) {
this.send({
event: 'unsubscribe',
chanId: +chanId
})
}
|
Unsubscribe from a channel by ID
@param {number} chanId - ID of channel to unsubscribe from
@example
const id = ws.getDataChannelId('ticker', { symbol: 'tBTCUSD' })
if (id) {
ws.unsubscribe(id)
}
|
unsubscribe
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
async unsubscribeTicker (symbol) {
return this.managedUnsubscribe('ticker', symbol)
}
|
Unsubscribe from a ticker data channel
@param {string} symbol - symbol of ticker
@returns {boolean} unsubscribed
@see WSv2#subscribeTicker
@example
await ws.unsubscribeTicker('tBTCUSD')
|
unsubscribeTicker
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
async unsubscribeTrades (symbol) {
return this.managedUnsubscribe('trades', symbol)
}
|
Unsubscribe from a trades data channel
@param {string} symbol - symbol of market to unsubscribe from
@returns {boolean} unsubscribed
@see WSv2#subscribeTrades
@example
await ws.unsubcribeTrades('tBTCUSD')
|
unsubscribeTrades
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
async unsubscribeOrderBook (symbol) {
return this.managedUnsubscribe('book', symbol)
}
|
Unsubscribe from an order book data channel
@param {string} symbol - symbol of order book
@returns {boolean} unsubscribed
@see WSv2#subscribeOrderBook
@example
await ws.unsubcribeOrderBook('tBTCUSD')
|
unsubscribeOrderBook
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
async unsubscribeCandles (symbol, frame) {
return this.managedUnsubscribe('candles', `trade:${frame}:${symbol}`)
}
|
@param {string} symbol - symbol of candles
@param {string} frame - time frame
@returns {boolean} unsubscribed
@see WSv2#subscribeCandles
@example
await ws.unsubscribeCandles('tBTCUSD', '1m')
|
unsubscribeCandles
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
async unsubscribeStatus (key) {
return this.managedUnsubscribe('status', key)
}
|
@param {string} key - key that was used in initial {@link WSv2#subscribeStatus} call
@returns {boolean} unsubscribed
@see WSv2#subscribeStatus
|
unsubscribeStatus
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
removeListeners (cbGID) {
delete this._listeners[cbGID]
}
|
Remove all listeners by callback group ID
@param {string} cbGID - callback group to remove
@example
await ws.subscribeTrades({ symbol: 'tBTCUSD', cbGID: 42 })
await ws.subscribeTrades({ symbol: 'tLEOUSD', cbGID: 42 })
await ws.subscribeTrades({ symbol: 'tETHUSD', cbGID: 42 })
// ...
ws.removeListeners(42)
|
removeListeners
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
requestCalc (prefixes) {
this._sendCalc([0, 'calc', null, prefixes.map(p => [p])])
}
|
Request a calc operation to be performed on the specified indexes
@param {string[]} prefixes - desired prefixes to be calculated
|
requestCalc
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_sendCalc (msg) {
debug('req calc: %j', msg)
this._ws.send(JSON.stringify(msg))
}
|
Throttled call to ws.send, max 8 op/s
@param {Array} msg - message
@private
|
_sendCalc
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
async submitOrderMultiOp (opPayloads) {
if (!this._isAuthenticated) {
throw new Error('not authenticated')
}
// TODO: multi-op tracking
this.send([0, 'ox_multi', null, opPayloads])
}
|
Sends the op payloads to the server as an 'ox_multi' command. A promise is
returned and resolves immediately if authenticated, as no confirmation is
available for this message type.
@param {object[]} opPayloads - order operations
@returns {Promise} p - rejects if not authenticated
|
submitOrderMultiOp
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_flushOrderOps () {
this._orderOpTimeout = null
const packets = this._orderOpBuffer.map(p => [p[1], p[3]])
this._orderOpBuffer = []
if (packets.length <= 15) {
return this.submitOrderMultiOp(packets)
}
const promises = []
while (packets.length > 0) {
const opPackets = packets.splice(0, Math.min(packets.length, 15))
promises.push(this.submitOrderMultiOp(opPackets))
}
return Promise.all(promises)
}
|
Splits the op buffer into packets of max 15 ops each, and sends them down
the wire.
@returns {Promise} p - resolves after send
@private
|
_flushOrderOps
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
notifyUI (opts = {}) {
const { type, message, level, image, link, sound } = opts
if (!_isString(type) || !_isString(message)) {
throw new Error(`notified with invalid type/message: ${type}/${message}`)
}
if (!this._isOpen) {
throw new Error('socket not open')
}
if (!this._isAuthenticated) {
throw new Error('socket not authenticated')
}
this.send([0, 'n', null, {
type: UCM_NOTIFICATION_TYPE,
info: {
type,
message,
level,
image,
link,
sound
}
}])
}
|
Sends a broadcast notification, which will be received by any active UI
websocket connections (at bitfinex.com), triggering a desktop notification.
In the future our mobile app will also support spawning native push
notifications in response to incoming ucm-notify-ui packets.
@param {object} opts - options
@param {string} [opts.message] - message to display
@param {string} [opts.type] - notification type, 'ucm-*' for broadcasts
@param {string} [opts.level] - 'info', 'error', or 'success'
@param {string} [opts.image] - link to an image to be shown
@param {string} [opts.link] - URL the notification should forward too
@param {string} [opts.sound] - URL of sound to play
@throws an error if given no type or message, or the instance is not open
and authenticated
|
notifyUI
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
_registerListener (eventName, filter, modelClass, cbGID, cb) {
if (!cbGID) cbGID = null
if (!this._listeners[cbGID]) {
this._listeners[cbGID] = { [eventName]: [] }
}
const listeners = this._listeners[cbGID]
if (!listeners[eventName]) {
listeners[eventName] = []
}
const l = {
cb,
modelClass,
filter
}
listeners[eventName].push(l)
}
|
Adds a listener to the internal listener set, with an optional grouping
for batch unsubscribes (GID) & automatic ws packet matching (filterKey)
@param {string} eventName - as received on ws stream
@param {object} filter - map of index & value in ws packet
@param {object} modelClass - model to use for serialization
@param {string} cbGID - listener group ID for mass removal
@param {Function} cb - listener
@private
|
_registerListener
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
onInfoMessage (code, cb) {
if (!this._infoListeners[code]) {
this._infoListeners[code] = []
}
this._infoListeners[code].push(cb)
}
|
Registers a new callback to be called when a matching info message is
received.
@param {number} code - from #WSv2.info
@param {Function} cb - callback
|
onInfoMessage
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
onMessage ({ cbGID }, cb) {
this._registerListener('', null, null, cbGID, cb)
}
|
Register a generic handler to be called with each received message
@param {object} opts - options
@param {string|number} [opts.cbGID] - callback group id
@param {Function} cb - callback
|
onMessage
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
onCandle ({ key, cbGID }, cb) {
this._registerListener('candle', { 0: key }, Candle, cbGID, cb)
}
|
Register a handler to be called with each received candle
@param {object} opts - options
@param {string} opts.key - candle set key, i.e. trade:30m:tBTCUSD
@param {string|number} [opts.cbGID] - callback group id
@param {Function} cb - callback
@see https://docs.bitfinex.com/v2/reference#ws-public-candle
@see WSv2#subscribeCandles
@see WSv2#unsubscribeCandles
|
onCandle
|
javascript
|
bitfinexcom/bitfinex-api-node
|
lib/transports/ws2.js
|
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.