-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathbybit.ts
99 lines (81 loc) · 2.37 KB
/
bybit.ts
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
import {
DefaultLogger,
isWsOrderbookEventV5,
WebsocketClient,
WSOrderbookEventV5,
} from 'bybit-api';
import {
OrderBookLevel,
OrderBookLevelState,
OrderBooksStore,
} from 'orderbooks';
// import { OrderBookLevel, OrderBookLevelState, OrderBooksStore } from '../src';
const OrderBooks = new OrderBooksStore({
traceLog: true,
checkTimestamps: false,
});
// eslint-disable-next-line @typescript-eslint/no-empty-function
DefaultLogger.silly = () => {};
// connect to a websocket and relay orderbook events to handlers
const ws = new WebsocketClient({
market: 'v5',
});
ws.on('update', (message) => {
if (isWsOrderbookEventV5(message)) {
// console.log('message', JSON.stringify(message, null, 2));
handleOrderbookUpdate(message);
return;
}
});
ws.on('error', (message) => {
console.error(`bybit ws error: `, message);
});
ws.subscribeV5(['orderbook.50.BTCUSDT'], 'spot');
// parse orderbook messages, detect snapshot vs delta, and format properties using OrderBookLevel
function handleOrderbookUpdate(message: WSOrderbookEventV5) {
const { topic, type, data, cts } = message;
const [topicKey, symbol] = topic.split('.');
const bidsArray = data.b.map(([price, amount]) => {
return OrderBookLevel(symbol, +price, 'Buy', +amount);
});
const asksArray = data.a.map(([price, amount]) => {
return OrderBookLevel(symbol, +price, 'Sell', +amount);
});
const allBidsAndAsks = [...bidsArray, ...asksArray];
if (type === 'snapshot') {
// store inititial snapshot
const storedOrderbook = OrderBooks.handleSnapshot(
symbol,
allBidsAndAsks,
cts,
);
// log book state to screen
storedOrderbook.print();
return;
}
if (type === 'delta') {
const upsertLevels: OrderBookLevelState[] = [];
const deleteLevels: OrderBookLevelState[] = [];
// Seperate "deletes" from "updates/inserts"
allBidsAndAsks.forEach((level) => {
const [_symbol, _price, _side, qty] = level;
if (qty === 0) {
deleteLevels.push(level);
} else {
upsertLevels.push(level);
}
});
// Feed delta into orderbook store
const storedOrderbook = OrderBooks.handleDelta(
symbol,
deleteLevels,
upsertLevels,
[],
cts,
);
// log book state to screen
storedOrderbook.print();
return;
}
console.error('unhandled orderbook update type: ', type);
}