-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorderbook.js
55 lines (45 loc) · 1.58 KB
/
orderbook.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
const { DefaultLogger, WebsocketClient } = require("bybit-api");
const { OrderBookLevel, OrderBooksStore } = require("orderbooks");
const OrderBooks = new OrderBooksStore({
traceLog: true,
checkTimestamps: false,
});
// connect to a websocket and relay orderbook events to handlers
const ws = new WebsocketClient({ testnet: false, market: "spot" });
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);
}
module.export = handleOrderbookUpdate;