forked from tiagosiebler/orderbooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bybit.js
44 lines (37 loc) · 1.51 KB
/
bybit.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
const { WebsocketClient, DefaultLogger } = require('bybit-api');
const { OrderBooksStore, OrderBookLevel } = require('orderbooks');
const OrderBooks = new OrderBooksStore({ traceLog: true, checkTimestamps: false });
// connect to a websocket and relay orderbook events to handlers
DefaultLogger.silly = () => {};
const ws = new WebsocketClient({ livenet: true });
ws.on('update', message => {
if (message.topic.toLowerCase().startsWith('orderbook')) {
return handleOrderbookUpdate(message);
}
});
ws.subscribe('orderBookL2_25.BTCUSD');
// parse orderbook messages, detect snapshot vs delta, and format properties using OrderBookLevel
function handleOrderbookUpdate(message) {
const { topic, type, data, timestamp_e6 } = message;
const [topicKey, symbol] = topic.split('.');
if (type == 'snapshot') {
return OrderBooks.handleSnapshot(symbol, data.map(mapBybitBookSlice), timestamp_e6 / 1000, message).print();
}
if (type == 'delta') {
const deleteLevels = data.delete.map(mapBybitBookSlice);
const updateLevels = data.update.map(mapBybitBookSlice);
const insertLevels = data.insert.map(mapBybitBookSlice);
return OrderBooks.handleDelta(
symbol,
deleteLevels,
updateLevels,
insertLevels,
timestamp_e6 / 1000
).print();
}
console.error('unhandled orderbook update type: ', type);
}
// Low level map of exchange properties to expected local properties
function mapBybitBookSlice(level) {
return OrderBookLevel(level.symbol, +level.price, level.side, level.size);
}