generated from bennycode/ts-node-starter
-
Notifications
You must be signed in to change notification settings - Fork 62
/
websocket-ticker.ts
42 lines (36 loc) · 1.25 KB
/
websocket-ticker.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
import {initClient} from './init-client.js';
import {WebSocketChannelName, WebSocketEvent} from '../index.js';
// 1. Setup Coinbase Pro client
const client = initClient();
// 2. Setup WebSocket channel info
const channel = {
name: WebSocketChannelName.TICKER,
product_ids: ['BTC-USD', 'ETH-EUR'],
};
// 3. Wait for open WebSocket to send messages
client.ws.on(WebSocketEvent.ON_OPEN, async () => {
// 7. Subscribe to WebSocket channel
await client.ws.subscribe([channel]);
});
// 4. Listen to WebSocket subscription updates
client.ws.on(WebSocketEvent.ON_SUBSCRIPTION_UPDATE, subscriptions => {
// When there are no more subscriptions...
if (subscriptions.channels.length === 0) {
// 10. Disconnect WebSocket (and end program)
client.ws.disconnect();
}
});
// 5. Listen to WebSocket channel updates
client.ws.on(WebSocketEvent.ON_MESSAGE_TICKER, async tickerMessage => {
// 8. Receive message from WebSocket channel
console.info(`Received message of type "${tickerMessage.type}".`, tickerMessage);
// 9. Unsubscribe from WebSocket channel
await client.ws.unsubscribe([
{
name: WebSocketChannelName.TICKER,
product_ids: [tickerMessage.product_id],
},
]);
});
// 6. Connect to WebSocket
client.ws.connect({debug: true});