Skip to content

Instantly share code, notes, and snippets.

@tiagosiebler
Created November 18, 2024 14:32
Show Gist options
  • Save tiagosiebler/113c7dec34f75603254cff990f36849b to your computer and use it in GitHub Desktop.
Save tiagosiebler/113c7dec34f75603254cff990f36849b to your computer and use it in GitHub Desktop.
Simple demo for connecting to OKX websockets in javascript/node.js
import { DefaultLogger, WebsocketClient } from 'okx-api';
// Optional: Inject a custom logger.
// This example overrides the default logger to also log "silly" (super verbose) messages, which are disabled by default
const logger = {
...DefaultLogger,
silly: (...params) => console.log('silly', ...params),
};
const wsClient = new WebsocketClient(
{
// prod is used by default, but you can choose other markets through this parameter:
// market: 'prod',
// market: 'aws',
// market: 'demo',
},
logger // Optional: inject the custom logger here
);
// Raw data will arrive on the 'update' event
wsClient.on('update', (data) => {
console.log(
new Date(),
'ws update (raw data received)',
JSON.stringify(data)
);
// console.log('ws update (raw data received)', JSON.stringify(data, null, 2));
});
wsClient.on('open', (data) => {
console.log('ws connection opened open:', data.wsKey);
});
// Replies (e.g. authenticating or subscribing to channels) will arrive on the 'response' event
wsClient.on('response', (data) => {
console.log('ws response received: ', JSON.stringify(data, null, 2));
});
wsClient.on('reconnect', ({ wsKey }) => {
console.log('ws automatically reconnecting.... ', wsKey);
});
wsClient.on('reconnected', (data) => {
console.log('ws has reconnected ', data?.wsKey);
});
wsClient.on('error', (data) => {
console.error('ws exception: ', data);
});
// Candlesticks channel
wsClient.subscribe({
channel: 'candle1m',
instId: 'BTC-USDT',
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment