The provided examples in JavaScript and Python demonstrate basic techniques for sending and receiving messages to NDAX over a WebSocket and for reconnecting and resubscribing in the event of network failures. These examples can serve as a starting point for building WebSocket functionality into your own system, but you will likely need to customize them to fit your specific language, library, framework, and system requirements. Be sure to modify the examples as needed to suit your needs.
const WebSocket = require('ws');
const crypto = require('crypto');
// NB: THESE CREDENTIALS SHOULD NOT BE STORED IN PLAINTEXT
// Keys here are kept in plaintext for the purposes of demonstration
// We encourage you to encrypt your keys and decrypt them only when being used
const KEY = '...';
const SECRET = '...';
const PASSPHRASE = '...';
const sign = (body, secret) => {
let ts = String(Math.round(Date.now() / 1000));
let payload = ts + 'POST' + '/' + JSON.stringify(body);
let decodedSecret = Buffer.from(secret, 'base64');
let hmac = crypto.createHmac('sha256', decodedSecret);
let signedPayload = hmac.update(payload).digest('base64');
};
const sendWebsocketMessage = (client, type, body, secret, key, phrase) => {
const ts = String(Math.round(Date.now() / 1000));
const payload = ts + 'POST' + '/' + JSON.stringify(body);
const decodedSecret = Buffer.from(secret, 'base64');
const hmac = crypto.createHmac('sha256', decodedSecret);
const signedPayload = hmac.update(payload).digest('base64');
let data = JSON.stringify({
messageType: type,
body: body,
key: key,
passphrase: phrase,
timestamp: ts,
signature: signedPayload
});
console.log('sending message:', data);
client.send(data);
};
const ws = new WebSocket(`wss://ws.ndax.in`);
ws.on('open', () => {
sendWebsocketMessage(ws, 'subscribe', { filter: {} }, SECRET, KEY, PASSPHRASE);
});
ws.on('message', (data) => {
console.log('received message:', JSON.parse(data));
});
ws.on('error', (data) => {
console.log('unexpected error:', data);
});
setInterval(() => {
sendWebsocketMessage(ws, 'ping', {}, SECRET, KEY, PASSPHRASE);
}, 10000);