forked from bitfinexcom/bitfinex-api-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathws2.js
247 lines (224 loc) · 6.63 KB
/
ws2.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
'use strict'
const {EventEmitter} = require('events')
const debug = require('debug')('bitfinex:ws')
const crypto = require('crypto')
const WebSocket = require('ws')
/**
* Handles communitaction with Bitfinex WebSocket API.
* @param {string} APIKey
* @param {string} APISecret
* @event
* @class
*/
class BitfinexWS2 extends EventEmitter {
constructor (apiKey, apiSecret, opts = {}) {
super()
this.apiKey = apiKey
this.apiSecret = apiSecret
this.websocketURI = opts.websocketURI || 'wss://api.bitfinex.com/ws/2'
}
open () {
this.ws = new WebSocket(this.websocketURI)
this.ws.on('message', this.onMessage.bind(this))
this.ws.on('open', this.onOpen.bind(this))
this.ws.on('error', this.onError.bind(this))
this.ws.on('close', this.onClose.bind(this))
}
onMessage (msg, flags) {
msg = JSON.parse(msg)
debug('Received message: %j', msg)
debug('Emited 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,
symbol: msg.symbol
}
// 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} symbol - Symbol of the asset in question (either a trading pair or a funding currency)
* @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')
}
}
}
}
_processUserEvent (msg) {
if (msg[0] === 'hb') { // HeatBeart
debug('Received HeatBeart in user channel')
} else {
let event = msg[0]
const data = msg[1]
// Snapshot
if (Array.isArray(data[0])) {
data.forEach((ele) => {
debug('Emitting notification \'%s\' %j', event, ele)
this.emit(event, ele)
})
} else if (event === 'n') { // Notification
event = data[1]
this.emit(event, data)
debug('Emitting \'%s\', %j', event, data)
} else if (data.length) { // Update
debug('Emitting \'%s\', %j', event, data)
this.emit(event, data)
}
}
}
_processTickerEvent (msg, event) {
if (msg[0] === 'hb') { // HeatBeart
debug('Received HeatBeart in %s ticker channel', event.symbol)
} else {
msg = msg[0]
debug('Emitting ticker, %s, %j', event.symbol, msg)
this.emit('ticker', event.symbol, msg)
}
}
_processBookEvent (msg, event) {
if (Array.isArray(msg[0])) {
msg[0].forEach((bookLevel) => {
debug('Emitting orderbook, %s, %j', event.symbol, bookLevel)
this.emit('orderbook', event.symbol, bookLevel)
})
} else if (msg[0] === 'hb') { // HeatBeart
debug('Received HeatBeart in %s book channel', event.symbol)
} else if (msg.length > 2) {
debug('Emitting orderbook, %s, %j', event.symbol, msg)
this.emit('orderbook', event.symbol, msg)
}
}
_processTradeEvent (msg, event) {
if (Array.isArray(msg[0])) {
msg[0].forEach((trade) => {
debug('Emitting trade, %s, %j', event.symbol, trade)
this.emit('trade', event.symbol, trade)
})
} else if (msg[0] === 'hb') { // HeatBeart
debug('Received HeatBeart in %s trade channel', event.symbol)
} else if (msg[0] === 'te') { // Trade executed
debug('Emitting trade, %s, %j', event.symbol, msg)
this.emit('trade', event.symbol, msg)
} else if (msg[0] === 'tu') { // Trade executed
debug('Emitting trade, %s, %j', event.symbol, msg)
this.emit('trade', event.symbol, msg)
}
}
close () {
this.ws.close()
}
onOpen () {
this.channelMap = {} // Map channels IDs to events
debug('Connection opening, emitting open')
this.emit('open')
}
onError (error) {
this.emit('error', error)
}
onClose () {
this.emit('close')
}
send (msg) {
debug('Sending %j', msg)
this.ws.send(JSON.stringify(msg))
}
subscribeOrderBook (symbol = 'tBTCUSD', precision = 'P0', length = '25') {
this.send({
event: 'subscribe',
channel: 'book',
symbol,
len: length,
prec: precision
})
}
subscribeTrades (symbol = 'BTCUSD') {
this.send({
event: 'subscribe',
channel: 'trades',
symbol
})
}
subscribeTicker (symbol = 'tBTCUSD') {
this.send({
event: 'subscribe',
channel: 'ticker',
symbol
})
}
unsubscribe (chanId) {
this.send({
event: 'unsubscribe',
chanId
})
}
submitOrder (order) {
this.send(order)
}
cancelOrder (orderId) {
this.send([0, 'oc', null, {
id: orderId
}])
}
config (flags) {
this.send({
flags,
'event': 'conf'
})
}
auth (calc = 0) {
const authNonce = (new Date()).getTime() * 1000
const payload = 'AUTH' + authNonce + authNonce
const signature = crypto.createHmac('sha384', this.apiSecret).update(payload).digest('hex')
this.send({
event: 'auth',
apiKey: this.apiKey,
authSig: signature,
authPayload: payload,
authNonce: +authNonce + 1,
calc
})
}
}
module.exports = BitfinexWS2