-
Notifications
You must be signed in to change notification settings - Fork 5
/
wsClient.ts
44 lines (35 loc) · 1.72 KB
/
wsClient.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
import WebSocket from 'ws';
const ws = new WebSocket('wss://dlob.drift.trade/ws');
import { sleep } from '../src/utils/utils';
ws.on('open', async () => {
console.log('Connected to the server');
// Subscribe and unsubscribe to orderbook channels
ws.send(JSON.stringify({ type: 'subscribe', marketType: 'perp', channel: 'orderbook', market: 'SOL-PERP' }));
ws.send(JSON.stringify({ type: 'subscribe', marketType: 'perp', channel: 'orderbook', market: 'INJ-PERP' }));
ws.send(JSON.stringify({ type: 'subscribe', marketType: 'perp', channel: 'orderbook', market: 'BTC-PERP' }));
ws.send(JSON.stringify({ type: 'subscribe', marketType: 'spot', channel: 'orderbook', market: 'SOL' }));
await sleep(5000);
ws.send(JSON.stringify({ type: 'unsubscribe', marketType: 'perp', channel: 'orderbook', market: 'SOL-PERP' }));
console.log("####################");
// Subscribe to trades data
ws.send(JSON.stringify({ type: 'subscribe', marketType: 'perp', channel: 'trades', market: 'SOL-PERP' }));
ws.send(JSON.stringify({ type: 'subscribe', marketType: 'spot', channel: 'trades', market: 'SOL' }));
await sleep(5000);
ws.send(JSON.stringify({ type: 'unsubscribe', marketType: 'perp', channel: 'trades', market: 'SOL-PERP' }));
console.log("####################");
});
ws.on('message', (data: WebSocket.Data) => {
try {
const message = JSON.parse(data.toString());
console.log(`Received data from channel: ${JSON.stringify(message.channel)}`);
// book and trades data is in message.data
} catch (e) {
console.error('Invalid message:', data);
}
});
ws.on('close', () => {
console.log('Disconnected from the server');
});
ws.on('error', (error: Error) => {
console.error('WebSocket error:', error);
});