forked from bitfinexcom/bitfinex-api-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathws.js
411 lines (389 loc) · 11.2 KB
/
ws.js
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
'use strict'
const {EventEmitter} = require('events')
const debug = require('debug')('bitfinex:ws')
const crypto = require('crypto')
const WebSocket = require('ws')
const util = require('util')
/**
* Handles communitaction with Bitfinex WebSocket API.
* @param {sting} APIKey
* @param {string} APISecret
* @event
* @class
*/
const BitfinexWS = function (APIKey, APISecret) {
EventEmitter.call(this)
this.APIKey = APIKey
this.APISecret = APISecret
this.ws = new WebSocket(BitfinexWS.WebSocketURI)
/**
* @event BitfinexWS#message
* @type {object}
*/
this.ws.on('message', this.onMessage.bind(this))
/**
* WebSocket connection is open. Ready to send.
* @event BitfinexWS#open
*/
this.ws.on('open', this.onOpen.bind(this))
/**
* @event BitfinexWS#error
*/
this.ws.on('error', this.onError.bind(this))
/**
* WebSocket connection is closed.
* @event BitfinexWS#close
*/
this.ws.on('close', this.onClose.bind(this))
}
util.inherits(BitfinexWS, EventEmitter)
/**
* @constant
* @type {String}
*/
BitfinexWS.WebSocketURI = 'wss://api.bitfinex.com/ws/'
BitfinexWS.prototype.onMessage = function (msg, flags) {
msg = JSON.parse(msg)
debug('Received message: %j', msg)
debug('Emmited message event')
this.emit('message', msg, flags)
if (!Array.isArray(msg) && msg.event) {
if (msg.event === 'subscribed') {
debug('Subscription report received')
// Inform the user the new event name that will be triggered
const data = {
channel: msg.channel,
chanId: msg.chanId,
pair: msg.pair
}
// Save to event map
this.channelMap[msg.chanId] = data
debug('Emitting \'subscribed\' %j', data)
/**
* @event BitfinexWS#subscribed
* @type {object}
* @property {string} channel - Channel type
* @property {string} pair - Currency pair.
* @property {number} chanId - Channel ID sended by Bitfinex
*/
this.emit('subscribed', data)
} else if (msg.event === 'auth' && msg.status !== 'OK') {
this.emit('error', msg)
debug('Emitting \'error\' %j', msg)
} else if (msg.event === 'auth') {
this.channelMap[msg.chanId] = {
channel: 'auth'
}
debug('Emitting \'%s\' %j', msg.event, msg)
/**
* @event BitfinexWS#auth
*/
this.emit(msg.event, msg)
} else {
debug('Emitting \'%s\' %j', msg.event, msg)
this.emit(msg.event, msg)
}
} else {
debug('Received data from a channel')
// First element of Array is the channelId, the rest is the info.
const channelId = msg.shift() // Pop the first element
const event = this.channelMap[channelId]
if (event) {
debug('Message in \'%s\' channel', event.channel)
if (event.channel === 'book') {
this._processBookEvent(msg, event)
} else if (event.channel === 'trades') {
this._processTradeEvent(msg, event)
} else if (event.channel === 'ticker') {
this._processTickerEvent(msg, event)
} else if (event.channel === 'auth') {
this._processUserEvent(msg)
} else {
debug('Message in unknown channel')
}
}
}
}
BitfinexWS.prototype._processUserEvent = function (msg) {
if (msg[0] === 'hb') { // HeatBeart
debug('Received HeatBeart in user channel')
} else {
const event = msg[0]
const data = msg[1]
if (Array.isArray(data[0])) {
data[0].forEach((ele) => {
debug('Emitting \'%s\' %j', event, ele)
this.emit(event, ele)
})
} else if (data.length) {
debug('Emitting \'%s\', %j', event, data)
/**
* position snapshot
* @event BitfinexWS#ps
*/
/**
* new position
* @event BitfinexWS#pn
*/
/**
* position update
* @event BitfinexWS#pu
*/
/**
* position close
* @event BitfinexWS#pc
*/
/**
* wallet snapshot
* @event BitfinexWS#ws
*/
/**
* wallet snapshot
* @event BitfinexWS#ws
*/
/**
* order snapshot
* @event BitfinexWS#os
*/
/**
* new order
* @event BitfinexWS#on
*/
/**
* order update
* @event BitfinexWS#ou
*/
/**
* order cancel
* @event BitfinexWS#oc
*/
/**
* trade executed
* @event BitfinexWS#te
*/
/**
* trade execution update
* @event BitfinexWS#tu
*/
// TODO: send Object with key: values
this.emit(event, data)
}
}
}
BitfinexWS.prototype._processTickerEvent = function (msg, event) {
if (msg[0] === 'hb') { // HeatBeart
debug('Received HeatBeart in %s ticker channel', event.pair)
} else if (msg.length > 9) { // Update
const update = {
bid: msg[0],
bidSize: msg[1],
ask: msg[2],
askSize: msg[3],
dailyChange: msg[4],
dailyChangePerc: msg[5],
lastPrice: msg[6],
volume: msg[7],
high: msg[8],
low: msg[9]
}
debug('Emitting ticker, %s, %j', event.pair, update)
/**
* @event BitfinexWS#ticker
* @type {string}
* @type {object}
* @property {number} bid
* @property {number} bidSize
* @property {number} ask
* @property {number} askSize
* @property {number} dailyChange
* @property {number} dailyChangePerc
* @property {number} lastPrice
* @property {number} volume
* @property {number} high
* @property {number} low
*/
this.emit('ticker', event.pair, update)
}
}
BitfinexWS.prototype._processTradeEvent = function (msg, event) {
// Snapshot
if (Array.isArray(msg[0])) {
msg[0].forEach((update) => {
update = {
seq: update[0],
timestamp: update[1],
price: update[2],
amount: update[3]
}
debug('Emitting trade, %s, %j', event.pair, update)
this.emit('trade', event.pair, update)
})
} else if (msg[0] === 'hb') { // HeatBeart
debug('Received HeatBeart in %s trade channel', event.pair)
} else if (msg[0] === 'te') { // Trade executed
const update = {
seq: msg[1],
timestamp: msg[2],
price: msg[3],
amount: msg[4]
}
debug('Emitting trade, %s, %j', event.pair, update)
/**
* @event BitfinexWS#trade
* @type {string}
* @type {object}
* @property {string} seq
* @property {number} timestamp
* @property {number} price
* @property {number} amount
* @see http://docs.bitfinex.com/#trades75
*/
this.emit('trade', event.pair, update)
} else if (msg[0] === 'tu') { // Trade executed
const update = {
seq: msg[1],
id: msg[2],
timestamp: msg[3],
price: msg[4],
amount: msg[5]
}
debug('Emitting trade, %s, %j', event.pair, update)
/**
* @event BitfinexWS#trade
* @type {string}
* @type {object}
* @property {string} seq
* @property {number} id
* @property {number} timestamp
* @property {number} price
* @property {number} amount
* @see http://docs.bitfinex.com/#trades75
*/
this.emit('trade', event.pair, update)
}
}
BitfinexWS.prototype._processBookEvent = function (msg, event) {
// Snapshot
if (Array.isArray(msg[0])) {
msg[0].forEach((update) => {
update = {
price: update[0],
count: update[1],
amount: update[2]
}
debug('Emitting orderbook, %s, %j', event.pair, update)
this.emit('orderbook', event.pair, update)
})
} else if (msg[0] === 'hb') { // HeatBeart
debug('Received HeatBeart in %s book channel', event.pair)
} else if (msg.length > 2) { // Update
const update = {
price: msg[0],
count: msg[1],
amount: msg[2]
}
debug('Emitting orderbook, %s, %j', event.pair, update)
/**
* @event BitfinexWS#orderbook
* @type {string}
* @type {object}
* @property {string} price
* @property {number} count
* @property {number} amount
* @see http://docs.bitfinex.com/#order-books
*/
this.emit('orderbook', event.pair, update)
}
}
BitfinexWS.prototype.close = function () {
this.ws.close()
}
BitfinexWS.prototype.onOpen = function () {
this.channelMap = {} // Map channels IDs to events
this.emit('open')
}
BitfinexWS.prototype.onError = function (error) {
this.emit('error', error)
}
BitfinexWS.prototype.onClose = function () {
this.emit('close')
}
BitfinexWS.prototype.send = function (msg) {
debug('Sending %j', msg)
this.ws.send(JSON.stringify(msg))
}
/**
* Subscribe to Order book updates. Snapshot will be sended as multiple updates.
* Event will be emited as `PAIRNAME_book`.
* @param {string} [pair] BTCUSD, LTCUSD or LTCBTC. Default BTCUSD
* @param {string} [precision] Level of price aggregation (P0, P1, P2, P3).
* The default is P0.
* @param {string} [length] Number of price points. 25 (default) or 100.
* @see http://docs.bitfinex.com/#order-books
*/
BitfinexWS.prototype.subscribeOrderBook =
function (pair = 'BTCUSD', precision = 'P0', length = '25') {
this.send({
event: 'subscribe',
channel: 'book',
pair,
prec: precision,
len: length
})
}
/**
* Subscribe to trades. Snapshot will be sended as multiple updates.
* Event will be emited as `PAIRNAME_trades`.
* @param {string} [pair] BTCUSD, LTCUSD or LTCBTC. Default BTCUSD
* @see http://docs.bitfinex.com/#trades75
*/
BitfinexWS.prototype.subscribeTrades = function (pair = 'BTCUSD') {
this.send({
event: 'subscribe',
channel: 'trades',
pair
})
}
/**
* Subscribe to ticker updates. The ticker is a high level overview of the state
* of the market. It shows you the current best bid and ask, as well as the last
* trade price.
*
* Event will be emited as `PAIRNAME_ticker`.
* @param {string} [pair] BTCUSD, LTCUSD or LTCBTC. Default BTCUSD
* @see http://docs.bitfinex.com/#ticker76
*/
BitfinexWS.prototype.subscribeTicker = function (pair = 'BTCUSD') {
this.send({
event: 'subscribe',
channel: 'ticker',
pair
})
}
/**
* Unsubscribe to a channel.
* @param {number} chanId ID of the channel received on `subscribed` event.
*/
BitfinexWS.prototype.unsubscribe = function (chanId) {
this.send({
event: 'unsubscribe',
chanId
})
}
/**
* Autenticate the user. Will receive executed traded updates.
* @see http://docs.bitfinex.com/#wallet-updates
*/
BitfinexWS.prototype.auth = function () {
const payload = 'AUTH' + (new Date().getTime())
const signature = crypto.createHmac('sha384', this.APISecret)
.update(payload)
.digest('hex')
this.send({
event: 'auth',
apiKey: this.APIKey,
authSig: signature,
authPayload: payload
})
}
module.exports = BitfinexWS