-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathbinance.ts
More file actions
553 lines (467 loc) · 16.9 KB
/
binance.ts
File metadata and controls
553 lines (467 loc) · 16.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
import { debug } from '../debug'
import { CircularBuffer, lowerCaseSymbols } from '../handy'
import { BookChange, BookTicker, DerivativeTicker, Exchange, FilterForExchange, Liquidation, Trade } from '../types'
import { Mapper, PendingTickerInfoHelper } from './mapper'
// https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md
export class BinanceTradesMapper
implements Mapper<'binance' | 'binance-jersey' | 'binance-us' | 'binance-futures' | 'binance-delivery', Trade>
{
constructor(private readonly _exchange: Exchange) { }
canHandle(message: BinanceResponse<any>) {
if (message.stream === undefined) {
return false
}
return message.stream.endsWith('@trade')
}
getFilters(symbols?: string[]) {
symbols = lowerCaseSymbols(symbols)
return [
{
channel: 'trade',
symbols
} as const
]
}
*map(binanceTradeResponse: BinanceResponse<BinanceTradeData>, localTimestamp: Date) {
const binanceTrade = binanceTradeResponse.data
const isOffBookTrade = binanceTrade.X === 'INSURANCE_FUND' || binanceTrade.X === 'ADL'
if (isOffBookTrade) {
return
}
const trade: Trade = {
type: 'trade',
symbol: binanceTrade.s,
exchange: this._exchange,
id: String(binanceTrade.t),
price: Number(binanceTrade.p),
amount: Number(binanceTrade.q),
side: binanceTrade.m ? 'sell' : 'buy',
timestamp: new Date(binanceTrade.T),
localTimestamp: localTimestamp
}
yield trade
}
}
export class BinanceBookChangeMapper
implements Mapper<'binance' | 'binance-jersey' | 'binance-us' | 'binance-futures' | 'binance-delivery', BookChange>
{
protected readonly symbolToDepthInfoMapping: {
[key: string]: LocalDepthInfo
} = {}
constructor(protected readonly exchange: Exchange, protected readonly ignoreBookSnapshotOverlapError: boolean) { }
canHandle(message: BinanceResponse<any>) {
if (message.stream === undefined) {
return false
}
return message.stream.includes('@depth')
}
getFilters(symbols?: string[]) {
symbols = lowerCaseSymbols(symbols)
return [
{
channel: 'depth',
symbols
} as const,
{
channel: 'depthSnapshot',
symbols
} as const
]
}
*map(message: BinanceResponse<BinanceDepthData | BinanceDepthSnapshotData>, localTimestamp: Date) {
const symbol = message.stream.split('@')[0].toUpperCase()
if (this.symbolToDepthInfoMapping[symbol] === undefined) {
this.symbolToDepthInfoMapping[symbol] = {
bufferedUpdates: new CircularBuffer<BinanceDepthData>(2000)
}
}
const symbolDepthInfo = this.symbolToDepthInfoMapping[symbol]
const snapshotAlreadyProcessed = symbolDepthInfo.snapshotProcessed
// first check if received message is snapshot and process it as such if it is
if (message.data.lastUpdateId !== undefined) {
// if we've already received 'manual' snapshot, ignore if there is another one
if (snapshotAlreadyProcessed) {
return
}
// produce snapshot book_change
const binanceDepthSnapshotData = message.data
// mark given symbol depth info that has snapshot processed
symbolDepthInfo.lastUpdateId = binanceDepthSnapshotData.lastUpdateId
symbolDepthInfo.snapshotProcessed = true
// if there were any depth updates buffered, let's proccess those by adding to or updating the initial snapshot
for (const update of symbolDepthInfo.bufferedUpdates.items()) {
const bookChange = this.mapBookDepthUpdate(update, localTimestamp)
if (bookChange !== undefined) {
for (const bid of update.b) {
const matchingBid = binanceDepthSnapshotData.bids.find((b) => b[0] === bid[0])
if (matchingBid !== undefined) {
matchingBid[1] = bid[1]
} else {
binanceDepthSnapshotData.bids.push(bid)
}
}
for (const ask of update.a) {
const matchingAsk = binanceDepthSnapshotData.asks.find((a) => a[0] === ask[0])
if (matchingAsk !== undefined) {
matchingAsk[1] = ask[1]
} else {
binanceDepthSnapshotData.asks.push(ask)
}
}
}
}
// remove all buffered updates
symbolDepthInfo.bufferedUpdates.clear()
const bookChange: BookChange = {
type: 'book_change',
symbol,
exchange: this.exchange,
isSnapshot: true,
bids: binanceDepthSnapshotData.bids.map(this.mapBookLevel),
asks: binanceDepthSnapshotData.asks.map(this.mapBookLevel),
uid: binanceDepthSnapshotData.lastUpdateId,
timestamp: binanceDepthSnapshotData.T !== undefined ? new Date(binanceDepthSnapshotData.T) : localTimestamp,
localTimestamp
}
yield bookChange
} else if (snapshotAlreadyProcessed) {
// snapshot was already processed let's map the message as normal book_change
const bookChange = this.mapBookDepthUpdate(message.data as BinanceDepthData, localTimestamp)
if (bookChange !== undefined) {
yield bookChange
}
} else {
const binanceDepthUpdateData = message.data as BinanceDepthData
symbolDepthInfo.bufferedUpdates.append(binanceDepthUpdateData)
}
}
protected mapBookDepthUpdate(binanceDepthUpdateData: BinanceDepthData, localTimestamp: Date): BookChange | undefined {
// we can safely assume here that depthContext and lastUpdateId aren't null here as this is method only works
// when we've already processed the snapshot
const depthContext = this.symbolToDepthInfoMapping[binanceDepthUpdateData.s]!
const lastUpdateId = depthContext.lastUpdateId!
// Drop any event where u is <= lastUpdateId in the snapshot
if (binanceDepthUpdateData.u <= lastUpdateId) {
return
}
// The first processed event should have U <= lastUpdateId+1 AND u >= lastUpdateId+1.
if (!depthContext.validatedFirstUpdate) {
// if there is new instrument added it can have empty book at first and that's normal
const bookSnapshotIsEmpty = lastUpdateId == -1
if ((binanceDepthUpdateData.U <= lastUpdateId + 1 && binanceDepthUpdateData.u >= lastUpdateId + 1) || bookSnapshotIsEmpty) {
depthContext.validatedFirstUpdate = true
} else {
const message = `Book depth snaphot has no overlap with first update, update ${JSON.stringify(
binanceDepthUpdateData
)}, lastUpdateId: ${lastUpdateId}, exchange ${this.exchange}`
if (this.ignoreBookSnapshotOverlapError) {
depthContext.validatedFirstUpdate = true
debug(message)
} else {
throw new Error(message)
}
}
}
return {
type: 'book_change',
symbol: binanceDepthUpdateData.s,
exchange: this.exchange,
isSnapshot: false,
bids: binanceDepthUpdateData.b.map(this.mapBookLevel),
asks: binanceDepthUpdateData.a.map(this.mapBookLevel),
uid: binanceDepthUpdateData.u,
timestamp: new Date(binanceDepthUpdateData.E),
localTimestamp: localTimestamp
}
}
protected mapBookLevel(level: BinanceBookLevel) {
const price = Number(level[0])
const amount = Number(level[1])
return { price, amount }
}
}
export class BinanceFuturesBookChangeMapper
extends BinanceBookChangeMapper
implements Mapper<'binance-futures' | 'binance-delivery', BookChange>
{
constructor(protected readonly exchange: Exchange, protected readonly ignoreBookSnapshotOverlapError: boolean) {
super(exchange, ignoreBookSnapshotOverlapError)
}
protected mapBookDepthUpdate(binanceDepthUpdateData: BinanceFuturesDepthData, localTimestamp: Date): BookChange | undefined {
// we can safely assume here that depthContext and lastUpdateId aren't null here as this is method only works
// when we've already processed the snapshot
const depthContext = this.symbolToDepthInfoMapping[binanceDepthUpdateData.s]!
const lastUpdateId = depthContext.lastUpdateId!
// based on https://binanceapitest.github.io/Binance-Futures-API-doc/wss/#how-to-manage-a-local-order-book-correctly
// Drop any event where u is < lastUpdateId in the snapshot
if (binanceDepthUpdateData.u < lastUpdateId) {
return
}
// The first processed should have U <= lastUpdateId AND u >= lastUpdateId
if (!depthContext.validatedFirstUpdate) {
if (binanceDepthUpdateData.U <= lastUpdateId && binanceDepthUpdateData.u >= lastUpdateId) {
depthContext.validatedFirstUpdate = true
} else {
const message = `Book depth snaphot has no overlap with first update, update ${JSON.stringify(
binanceDepthUpdateData
)}, lastUpdateId: ${lastUpdateId}, exchange ${this.exchange}`
if (this.ignoreBookSnapshotOverlapError) {
depthContext.validatedFirstUpdate = true
debug(message)
} else {
throw new Error(message)
}
}
}
return {
type: 'book_change',
symbol: binanceDepthUpdateData.s,
exchange: this.exchange,
isSnapshot: false,
bids: binanceDepthUpdateData.b.map(this.mapBookLevel),
asks: binanceDepthUpdateData.a.map(this.mapBookLevel),
uid: binanceDepthUpdateData.u,
timestamp: new Date(binanceDepthUpdateData.E),
localTimestamp: localTimestamp
}
}
}
export class BinanceFuturesDerivativeTickerMapper implements Mapper<'binance-futures' | 'binance-delivery', DerivativeTicker> {
private readonly pendingTickerInfoHelper = new PendingTickerInfoHelper()
private readonly _indexPrices = new Map<string, number>()
constructor(protected readonly exchange: Exchange) { }
canHandle(message: BinanceResponse<any>) {
if (message.stream === undefined) {
return false
}
return (
message.stream.includes('@markPrice') ||
message.stream.endsWith('@ticker') ||
message.stream.endsWith('@openInterest') ||
message.stream.includes('@indexPrice')
)
}
getFilters(symbols?: string[]): FilterForExchange['binance-futures' | 'binance-delivery'][] {
symbols = lowerCaseSymbols(symbols)
const filters = [
{
channel: 'markPrice',
symbols
} as const,
{
channel: 'ticker',
symbols
} as const,
{
channel: 'openInterest',
symbols
} as const
]
if (this.exchange === 'binance-delivery') {
// index channel requires index symbol
filters.push({
channel: 'indexPrice' as any,
symbols: symbols !== undefined ? symbols.map((s) => s.split('_')[0]) : undefined
})
}
return filters
}
*map(
message: BinanceResponse<
BinanceFuturesMarkPriceData | BinanceFuturesTickerData | BinanceFuturesOpenInterestData | BinanceFuturesIndexPriceData
>,
localTimestamp: Date
): IterableIterator<DerivativeTicker> {
if (message.data.e === 'indexPriceUpdate') {
this._indexPrices.set(message.data.i, Number(message.data.p))
} else {
const symbol = 's' in message.data ? message.data.s : message.data.symbol
const pendingTickerInfo = this.pendingTickerInfoHelper.getPendingTickerInfo(symbol, this.exchange)
const lastIndexPrice = this._indexPrices.get(symbol.split('_')[0])
if (lastIndexPrice !== undefined) {
pendingTickerInfo.updateIndexPrice(lastIndexPrice)
}
if (message.data.e === 'markPriceUpdate') {
if ('r' in message.data && message.data.r !== '' && message.data.T !== 0) {
// only perpetual futures have funding rate info in mark price
// delivery futures sometimes send empty ('') r value
pendingTickerInfo.updateFundingRate(Number(message.data.r))
pendingTickerInfo.updateFundingTimestamp(new Date(message.data.T!))
}
if (message.data.i !== undefined) {
pendingTickerInfo.updateIndexPrice(Number(message.data.i))
}
pendingTickerInfo.updateMarkPrice(Number(message.data.p))
pendingTickerInfo.updateTimestamp(new Date(message.data.E))
}
if (message.data.e === '24hrTicker') {
pendingTickerInfo.updateLastPrice(Number(message.data.c))
pendingTickerInfo.updateTimestamp(new Date(message.data.E))
}
if ('openInterest' in message.data) {
pendingTickerInfo.updateOpenInterest(Number(message.data.openInterest))
}
if (pendingTickerInfo.hasChanged()) {
yield pendingTickerInfo.getSnapshot(localTimestamp)
}
}
}
}
export class BinanceLiquidationsMapper implements Mapper<'binance-futures' | 'binance-delivery', Liquidation> {
constructor(private readonly _exchange: Exchange) { }
canHandle(message: BinanceResponse<any>) {
if (message.stream === undefined) {
return false
}
return message.stream.endsWith('@forceOrder')
}
getFilters(symbols?: string[]) {
symbols = lowerCaseSymbols(symbols)
return [
{
channel: 'forceOrder',
symbols
} as const
]
}
*map(binanceTradeResponse: BinanceResponse<BinanceFuturesForceOrderData>, localTimestamp: Date) {
const binanceLiquidation = binanceTradeResponse.data.o
// not sure if order status can be different to 'FILLED' for liquidations in practice, but...
if (binanceLiquidation.X !== 'FILLED') {
return
}
const liquidation: Liquidation = {
type: 'liquidation',
symbol: binanceLiquidation.s,
exchange: this._exchange,
id: undefined,
price: Number(binanceLiquidation.p),
amount: Number(binanceLiquidation.l), // Order Last Filled Quantity
side: binanceLiquidation.S === 'SELL' ? 'sell' : 'buy',
timestamp: new Date(binanceLiquidation.T),
localTimestamp: localTimestamp
}
yield liquidation
}
}
export class BinanceBookTickerMapper implements Mapper<'binance-futures' | 'binance-delivery' | 'binance', BookTicker> {
constructor(private readonly _exchange: Exchange) { }
canHandle(message: BinanceResponse<any>) {
if (message.stream === undefined) {
return false
}
return message.stream.endsWith('@bookTicker')
}
getFilters(symbols?: string[]) {
symbols = lowerCaseSymbols(symbols)
return [
{
channel: 'bookTicker',
symbols
} as const
]
}
*map(binanceBookTickerResponse: BinanceResponse<BinanceBookTickerData>, localTimestamp: Date) {
const binanceBookTicker = binanceBookTickerResponse.data
const ticker: BookTicker = {
type: 'book_ticker',
symbol: binanceBookTicker.s,
exchange: this._exchange,
askAmount: binanceBookTicker.A !== undefined ? Number(binanceBookTicker.A) : undefined,
askPrice: binanceBookTicker.a !== undefined ? Number(binanceBookTicker.a) : undefined,
bidPrice: binanceBookTicker.b !== undefined ? Number(binanceBookTicker.b) : undefined,
bidAmount: binanceBookTicker.B !== undefined ? Number(binanceBookTicker.B) : undefined,
timestamp: binanceBookTicker.E !== undefined ? new Date(binanceBookTicker.E) : localTimestamp,
localTimestamp: localTimestamp
}
yield ticker
}
}
type BinanceResponse<T> = {
stream: string
data: T
}
type BinanceTradeData = {
s: string
t: number
p: string
q: string
T: number
m: true
X?: 'INSURANCE_FUND' | 'MARKET' | 'ADL'
}
type BinanceBookLevel = [string, string]
type BinanceDepthData = {
lastUpdateId: undefined
E: number
s: string
U: number
u: number
b: BinanceBookLevel[]
a: BinanceBookLevel[]
}
// T is the time that updated in matching engine, while E is when pushing out from ws server
type BinanceFuturesDepthData = BinanceDepthData & {
pu: number
T: number
}
type BinanceDepthSnapshotData = {
lastUpdateId: number
bids: BinanceBookLevel[]
asks: BinanceBookLevel[]
T?: number
}
type LocalDepthInfo = {
bufferedUpdates: CircularBuffer<BinanceDepthData>
snapshotProcessed?: boolean
lastUpdateId?: number
validatedFirstUpdate?: boolean
}
type BinanceFuturesMarkPriceData = {
e: 'markPriceUpdate'
s: string // Symbol
E: number // Event time
p: string // Mark price
r?: string // Funding rate
T?: number // Next funding time
i?: string
}
type BinanceFuturesTickerData = {
e: '24hrTicker'
E: number // Event time
s: string // Symbol
c: string // Last price
}
type BinanceFuturesOpenInterestData = {
e: undefined
symbol: string
openInterest: string
}
type BinanceFuturesIndexPriceData = {
e: 'indexPriceUpdate' // Event type
E: 1591261236000 // Event time
i: string // Pair
p: string // Index Price
}
type BinanceFuturesForceOrderData = {
o: {
s: string // Symbol
S: string // Side
q: string // Original Quantity
p: string // Price
ap: string // Average Price
X: 'FILLED' // Order Status
l: '0.014' // Order Last Filled Quantity
T: 1568014460893 // Order Trade Time
z: string // Order Filled Accumulated Quantity
}
}
type BinanceBookTickerData = {
u: number // order book updateId
s: string // symbol
b: string // best bid price
B: string // best bid qty
a: string // best ask price
A: string // best ask qty
E?: number // transaction time
}