forked from tiagosiebler/orderbooks
/
binance.js
74 lines (62 loc) · 2.09 KB
/
binance.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
const Binance = require('node-binance-api');
const binance = new Binance().options({});
const { OrderBooksStore, OrderBookLevel } = require('../src');
const OrderBooks = new OrderBooksStore({ traceLog: true, checkTimestamps: false, maxDepth: 50 });
// connect to a websocket and relay orderbook events to handlers
const symbol = 'BTCUSDT';
binance.websockets.depth([symbol], depth => {
console.clear();
if (depth.e == 'depthUpdate') {
return handleOrderbookUpdate(depth);
}
debugger;
console.log('unknown event type: ', depth);
});
// get initial book snapshot
binance.depth(symbol).then(results => {
// combine bids and asks
const { bids, asks } = results;
const bidsArray = Object.keys(bids).map(price => {
return OrderBookLevel(symbol, +price, 'Buy', +bids[price])
});
const asksArray = Object.keys(asks).map(price => {
return OrderBookLevel(symbol, +price, 'Sell', +asks[price])
});
// store inititial snapshot
OrderBooks.handleSnapshot(
symbol,
[...bidsArray, ...asksArray],
new Date().getTime()
).print();
});
// process delta update event from websocket
const handleOrderbookUpdate = depth => {
let { e:eventType, E:eventTime, s:symbol, u:updateId, b:bidDepth, a:askDepth } = depth;
const deleteLevels = [];
const upsertLevels = [];
bidDepth.forEach(([ price, amount ]) => {
assignLevel(OrderBookLevel(symbol, +price, 'Buy', +amount), upsertLevels, deleteLevels);
});
askDepth.forEach(([ price, amount ]) => {
assignLevel(OrderBookLevel(symbol, +price, 'Sell', +amount), upsertLevels, deleteLevels);
});
// upsert/insert is automatically decided using price as primary key.
// Binance has these mixed, so let the book handler decide
const insertLevels = [];
return OrderBooks.handleDelta(
symbol,
deleteLevels,
upsertLevels,
insertLevels,
eventTime
).print();
};
// utility method to decide if a delta level is an upsert or deletion
const assignLevel = (level, updateArray, deleteArray) => {
const qtyIndex = 3;
if (level[qtyIndex]) {
updateArray.push(level);
} else {
deleteArray.push(level);
}
};