Search code examples
javascriptwebsocketblockchainbinance

WebSocket API connection to Binance returns an error: How to get crypto price in real-time?


I wanted to test websocket connection to binance api wss://testnet-dex.binance.org/api/ws. But whenever I run js script I am getting error as response from ws.

Script looks like that

const WebSocket = require('ws');

const conn = new WebSocket("wss://testnet-dex.binance.org/api/ws");
conn.onopen = function(evt) {
    conn.send(JSON.stringify({ method: "subscribe", topic: "trades", symbols: ["ETH_BNB"] })); // I did try using as an symbols 'BNB_USDT.B-B7C', but got the same error
}
conn.onmessage = function(evt) {
    console.info('received data', evt.data);
};
conn.onerror = function(evt) {
    console.error('an error occurred', evt.data);
};

And whenever script is run I am getting

received data {"method":"subscribe","error":{"error":"Invalid symbol(s)"}}

received data {"method":"subscribe","error":{"error":"Symbols [BNB_USDT.B-B7C] are not valid for topic: trades, for user: 100.x.x.x:3333 \u003e 100.xx.x.x:59558"}}

It seems like I am getting error because I did write wrong symbol. But I used multiple symbols, and all of them produced the same error. Not saying that I just copy/paste this code fron binance documentation https://docs.binance.org/api-reference/dex-api/ws-streams.html


Solution

  • The .org domain is a domain of the (legacy) Binance Chain - predecessor of the currently widely used Binance Smart Chain network.

    If you want to use WS API of the Binance exchange (located at the .com domain), it's published at wss://stream.binance.com:9443 (docs) and you can subscribe to trade channels in the format of <symbol>@trade (docs).