Connecting to WebSocket

Learn how to connect to WebSocket

Establish a connection using Node.js as shown below or follow our guided receipe.

const WebSocket = require("ws"); // `npm install ws` or `yarn add ws` to install the ws package

const websocketUri = "websocket-uri-here"; // Subscribe to Business or Premium plan here for Websocket API access - https://alpha.vybenetwork.com/api-plans - generate API key and get websocket URI here https://alpha.vybenetwork.com/dashboard/api-management

let ws;
const enableReconnect = true; // Set to false if you don't want to reconnect automatically

function getTimestamp() {
    return Math.floor(Date.now() / 1000); // Unix timestamp
}

function connect() {
    ws = new WebSocket(websocketUri, {
        headers: {
            "X-API-Key": "your-api-key-here", // Subscribe to Business or Premium plan here for Websocket API access - https://alpha.vybenetwork.com/api-plans - and generate API key here https://alpha.vybenetwork.com/dashboard/api-management
        },
    });

    ws.on("open", () => {
        console.log("Connected to the WebSocket server " + getTimestamp());

        // On connection, send a configure message to specify the filters.
        const configureMessage = JSON.stringify({
            type: "configure",
            filters: {
                trades: [], // For the demo, we are adding an empty array for trades to receive all trade messages
            },
        });
        ws.send(configureMessage);
    });

    ws.on("message", (message) => {
        let parsedMessage;
        try {
            parsedMessage = JSON.parse(message);
            console.log(parsedMessage);

            // You can now used the data in the parsedMessage object for your application or trading bot
        } catch (e) {
            console.error(`Failed to parse message: ${e}`);
            return;
        }
    });

    ws.on("close", () => {
        console.log("Connection closed.");
        if (enableReconnect) {
            attemptReconnect();
        }
    });

    ws.on("error", (error) => {
        console.error(`WebSocket error: ${error}`);
        if (enableReconnect) {
            attemptReconnect();
        }
    });
}

function attemptReconnect() {
    console.log("Attempting to reconnect...");
    connect();
}

// Start the initial connection
connect();