Repository navigation
Expand file tree
/
Copy pathbitfinex.ts
More file actions
473 lines (392 loc) · 13.9 KB
/
Copy pathbitfinex.ts
File metadata and controls
473 lines (392 loc) · 13.9 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
import { upperCaseSymbols } from '../handy.ts'
import { BookChange, BookTicker, DerivativeTicker, Exchange, FilterForExchange, Liquidation, Trade } from '../types.ts'
import { Mapper, PendingTickerInfoHelper } from './mapper.ts'
import { exchangeMappers } from './registry.ts'
// https://docs.bitfinex.com/v2/docs/ws-general
export const bitfinexMappers = exchangeMappers({
bitfinex: {
trades: () => new BitfinexTradesMapper('bitfinex'),
bookChanges: () => new BitfinexBookChangeMapper('bitfinex'),
bookTickers: () => new BitfinexBookTickerMapper('bitfinex')
},
'bitfinex-derivatives': {
trades: () => new BitfinexTradesMapper('bitfinex-derivatives'),
bookChanges: () => new BitfinexBookChangeMapper('bitfinex-derivatives'),
derivativeTickers: () => new BitfinexDerivativeTickerMapper(),
liquidations: () => new BitfinexLiquidationsMapper('bitfinex-derivatives'),
bookTickers: () => new BitfinexBookTickerMapper('bitfinex-derivatives')
}
})
class BitfinexTradesMapper implements Mapper<'bitfinex' | 'bitfinex-derivatives', Trade> {
private readonly _channelIdToSymbolMap: Map<number, string> = new Map()
constructor(private readonly _exchange: Exchange) {}
canHandle(message: BitfinexMessage) {
// non sub messages are provided as arrays
if (Array.isArray(message)) {
// first test if message itself provides channel name and if so if it's trades
const channelName = message[message.length - 2]
if (typeof channelName === 'string') {
return channelName === 'trades'
}
// otherwise use channel to id mapping
return this._channelIdToSymbolMap.get(message[0]) !== undefined
}
// store mapping between channel id and symbols
if (message.event === 'subscribed') {
const isTradeChannel = message.channel === 'trades'
if (isTradeChannel) {
this._channelIdToSymbolMap.set(message.chanId, message.pair)
}
}
return false
}
getFilters(symbols?: string[]) {
symbols = upperCaseSymbols(symbols)
return [
{
channel: 'trades',
symbols
} as const
]
}
*map(message: BitfinexTrades, localTimestamp: Date) {
const symbolFromMessage = message[message.length - 1]
const symbol = typeof symbolFromMessage === 'string' ? symbolFromMessage : this._channelIdToSymbolMap.get(message[0])
// ignore if we don't have matching symbol
if (symbol === undefined) {
return
}
// ignore heartbeats
if (message[1] === 'hb') {
return
}
// ignore snapshots
if (message[1] !== 'te') {
return
}
const [id, timestamp, amount, price] = message[2]
const trade: Trade = {
type: 'trade',
symbol,
exchange: this._exchange,
id: String(id),
price,
amount: Math.abs(amount),
side: amount < 0 ? 'sell' : 'buy',
timestamp: new Date(timestamp),
localTimestamp: localTimestamp
}
yield trade
}
}
class BitfinexBookChangeMapper implements Mapper<'bitfinex' | 'bitfinex-derivatives', BookChange> {
private readonly _channelIdToSymbolMap: Map<number, string> = new Map()
constructor(private readonly _exchange: Exchange) {}
canHandle(message: BitfinexMessage) {
// non sub messages are provided as arrays
if (Array.isArray(message)) {
// first test if message itself provides channel name and if so if it's a book
const channelName = message[message.length - 2]
if (typeof channelName === 'string') {
return channelName === 'book'
}
// otherwise use channel to id mapping
return this._channelIdToSymbolMap.get(message[0]) !== undefined
}
// store mapping between channel id and symbols
if (message.event === 'subscribed') {
const isBookP0Channel = message.channel === 'book' && message.prec === 'P0'
if (isBookP0Channel) {
this._channelIdToSymbolMap.set(message.chanId, message.pair)
}
}
return false
}
getFilters(symbols?: string[]) {
symbols = upperCaseSymbols(symbols)
return [
{
channel: 'book',
symbols
} as const
]
}
*map(message: BitfinexBooks, localTimestamp: Date) {
const symbolFromMessage = message[message.length - 1]
const symbol = typeof symbolFromMessage === 'string' ? symbolFromMessage : this._channelIdToSymbolMap.get(message[0])
// ignore if we don't have matching symbol
if (symbol === undefined) {
return
}
// ignore heartbeats
if (message[1] === 'hb') {
return
}
const isSnapshot = Array.isArray(message[1][0])
const bookLevels = (isSnapshot ? message[1] : [message[1]]) as BitfinexBookLevel[]
const asks = bookLevels.filter((level) => level[2] < 0)
const bids = bookLevels.filter((level) => level[2] > 0)
const bookChange: BookChange = {
type: 'book_change',
symbol,
exchange: this._exchange,
isSnapshot,
bids: bids.map(this._mapBookLevel),
asks: asks.map(this._mapBookLevel),
timestamp: new Date(message[3]),
localTimestamp: localTimestamp
}
yield bookChange
}
private _mapBookLevel(level: BitfinexBookLevel) {
const [price, count, bitfinexAmount] = level
const amount = count === 0 ? 0 : Math.abs(bitfinexAmount)
return { price, amount }
}
}
class BitfinexDerivativeTickerMapper implements Mapper<'bitfinex-derivatives', DerivativeTicker> {
private readonly _channelIdToSymbolMap: Map<number, string> = new Map()
private readonly pendingTickerInfoHelper = new PendingTickerInfoHelper()
canHandle(message: BitfinexMessage) {
// non sub messages are provided as arrays
if (Array.isArray(message)) {
// first test if message itself provides channel name and if so if it's a status
const channelName = message[message.length - 2]
if (typeof channelName === 'string') {
return channelName === 'status'
}
// otherwise use channel to id mapping
return this._channelIdToSymbolMap.get(message[0]) !== undefined
}
// store mapping between channel id and symbols
if (message.event === 'subscribed') {
const isDerivStatusChannel = message.channel === 'status' && message.key && message.key.startsWith('deriv:')
if (isDerivStatusChannel) {
this._channelIdToSymbolMap.set(message.chanId, message.key!.replace('deriv:t', ''))
}
}
return false
}
getFilters(symbols?: string[]) {
symbols = upperCaseSymbols(symbols)
return [
{
channel: 'status',
symbols
} as const
]
}
*map(message: BitfinexStatusMessage, localTimestamp: Date): IterableIterator<DerivativeTicker> {
const symbolFromMessage = message[message.length - 1]
const symbol = typeof symbolFromMessage === 'string' ? symbolFromMessage : this._channelIdToSymbolMap.get(message[0])
// ignore if we don't have matching symbol
if (symbol === undefined) {
return
}
// ignore heartbeats
if (message[1] === 'hb') {
return
}
const statusInfo = message[1]
// https://docs.bitfinex.com/v2/reference#ws-public-status
const fundingRate = statusInfo[11]
const indexPrice = statusInfo[3]
const lastPrice = statusInfo[2]
const markPrice = statusInfo[14]
const openInterest = statusInfo[17]
const nextFundingTimestamp = statusInfo[7]
const predictedFundingRate = statusInfo[8]
const pendingTickerInfo = this.pendingTickerInfoHelper.getPendingTickerInfo(symbol, 'bitfinex-derivatives')
pendingTickerInfo.updateFundingRate(fundingRate)
pendingTickerInfo.updateFundingTimestamp(nextFundingTimestamp !== undefined ? new Date(nextFundingTimestamp) : undefined)
pendingTickerInfo.updatePredictedFundingRate(predictedFundingRate)
pendingTickerInfo.updateIndexPrice(indexPrice)
pendingTickerInfo.updateLastPrice(lastPrice)
pendingTickerInfo.updateMarkPrice(markPrice)
pendingTickerInfo.updateOpenInterest(openInterest)
pendingTickerInfo.updateTimestamp(new Date(message[3]))
if (pendingTickerInfo.hasChanged()) {
yield pendingTickerInfo.getSnapshot(localTimestamp)
}
}
}
class BitfinexLiquidationsMapper implements Mapper<'bitfinex-derivatives', Liquidation> {
private _liquidationsChannelId: number | undefined = undefined
constructor(private readonly _exchange: Exchange) {}
canHandle(message: BitfinexMessage) {
// non sub messages are provided as arrays
if (Array.isArray(message)) {
// first test if message itself provides channel name and if so if it's liquidations
const channelName = message[message.length - 2]
if (typeof channelName === 'string') {
return channelName === 'liquidations'
}
// otherwise use channel id
return this._liquidationsChannelId === message[0]
}
// store liquidation channel id
if (message.event === 'subscribed') {
const isLiquidationsChannel = message.channel === 'status' && message.key === 'liq:global'
if (isLiquidationsChannel) {
this._liquidationsChannelId = message.chanId
}
}
return false
}
getFilters() {
// liquidations channel is global, not per symbol
return [
{
channel: 'liquidations'
} as const
]
}
*map(message: BitfinexLiquidation, localTimestamp: Date) {
// ignore heartbeats
if (message[1] === 'hb') {
return
}
if (!message[1]) {
return
}
// see https://docs.bitfinex.com/reference#ws-public-status
for (let bitfinexLiquidation of message[1]) {
const isInitialLiquidationTrigger = bitfinexLiquidation[8] === 0
// process only initial liquidation triggers not subsequent 'matches', assumption here is that
// there's only single initial liquidation trigger but there can be multiple matches for single liquidation
if (isInitialLiquidationTrigger) {
const id = String(bitfinexLiquidation[1])
const timestamp = new Date(bitfinexLiquidation[2])
const symbol = bitfinexLiquidation[4].replace('t', '')
// liq:global also includes spot margin liquidations.
if (!symbol.includes('F0')) continue
const price = bitfinexLiquidation[6]
const amount = bitfinexLiquidation[5]
const liquidation: Liquidation = {
type: 'liquidation',
symbol,
exchange: this._exchange,
id,
price,
amount: Math.abs(amount),
side: amount < 0 ? 'buy' : 'sell',
timestamp,
localTimestamp: localTimestamp
}
yield liquidation
}
}
}
}
class BitfinexBookTickerMapper implements Mapper<'bitfinex' | 'bitfinex-derivatives', BookTicker> {
private readonly _channelIdToSymbolMap: Map<number, string> = new Map()
constructor(private readonly _exchange: Exchange) {}
canHandle(message: BitfinexMessage) {
// non sub messages are provided as arrays
if (Array.isArray(message)) {
// first test if message itself provides channel name and if so if it's trades
const channelName = message[message.length - 2]
if (typeof channelName === 'string') {
return channelName === 'ticker'
}
// otherwise use channel to id mapping
return this._channelIdToSymbolMap.get(message[0]) !== undefined
}
// store mapping between channel id and symbols
if (message.event === 'subscribed') {
const isTicker = message.channel === 'ticker' && message.pair !== undefined
if (isTicker) {
this._channelIdToSymbolMap.set(message.chanId, message.pair)
}
}
return false
}
getFilters(symbols?: string[]) {
symbols = upperCaseSymbols(symbols)
return [
{
channel: 'ticker',
symbols
} as const
]
}
*map(message: BitfinexTicker, localTimestamp: Date) {
const symbolFromMessage = message[message.length - 1]
const symbol = typeof symbolFromMessage === 'string' ? symbolFromMessage : this._channelIdToSymbolMap.get(message[0])
if (symbol === undefined) {
return
}
// ignore heartbeats
if (message[1] === 'hb') {
return
}
// ignore funding tickers
const tickerData = message[1]
if (tickerData.length > 11) {
return
}
const [bidPrice, bidAmount, askPrice, askAmount] = tickerData
const ticker: BookTicker = {
type: 'book_ticker',
symbol,
exchange: this._exchange,
askAmount,
askPrice,
bidPrice,
bidAmount,
timestamp: new Date(message[3]),
localTimestamp: localTimestamp
}
yield ticker
}
}
type BitfinexMessage =
| {
event: 'subscribed'
channel: FilterForExchange['bitfinex-derivatives']['channel']
chanId: number
pair: string
prec: string
key?: string
}
| Array<any>
type BitfinexHeartbeat = [number, 'hb']
type BitfinexTrades = [number, 'te' | any[], [number, number, number, number]] | BitfinexHeartbeat
type BitfinexBookLevel = [number, number, number]
type BitfinexBooks = [number, BitfinexBookLevel | BitfinexBookLevel[], number, number] | BitfinexHeartbeat
type BitfinexStatusMessage = [number, (number | undefined)[], number, number] | BitfinexHeartbeat
type BitfinexLiquidation =
[number, ['pos', number, number, null, string, number, number, null, number, number, null, number][]] | BitfinexHeartbeat
type BitfinexTicker =
| [
CHANNEL_ID: number,
ITEMS:
| [
BID: number,
BID_SIZE: number,
ASK: number,
ASK_SIZE: number,
DAILY_CHANGE: number,
DAILY_CHANGE_RELATIVE: number,
LAST_PRICE: number,
VOLUME: number,
HIGH: number,
LOW: number
]
| [
BID: number,
BID_SIZE: number,
ASK: number,
ASK_SIZE: number,
DAILY_CHANGE: number,
DAILY_CHANGE_RELATIVE: number,
LAST_PRICE: number,
VOLUME: number,
HIGH: number,
LOW: number,
EXTRA: null
],
SEQ_ID: number,
TIMESTAMP: number
]
| BitfinexHeartbeat