Skip to content
Advertisement

Binance API How to connect with a web socket using Javascript?

Im using binance to get data about Ethereum. I did the single kLine response with an GET request to the API so I get the old data but now I want to keep the kLines and the price updating automaticly.

For this I need to connect with the Binance web socket. How do I do this? Im using Javascript.

Advertisement

Answer

This code opens a web socket connected with Binance. It receives data about (the symbol) ETH/USDT each 2 seconds (depth). Every 30 minutes the data sets variable “x” to true so you know when to add a line.

If you want to change the 30 minutes, symbol, depth or kline data you should check out the Binance api documentation on how to do it correctly.

// Symbol: ETH/USDT - Kline 30 minutes.
var socket = new WebSocket('wss://stream.binance.com:9443/ws/ethusdt@kline_30m');
    
// When message received from web socket then...
socket.onmessage = function (event) {

    // Easier and shorter.
    var data = JSON.parse(event.data);

    // "x" means: Is this kline closed? Return "true" if closed. Closed means new line to be added.
    if (data.k.x === true) {
        log("Add line.");

        // Adding a line with my custom function.
        addLine(data);
    } else {
        // Updating line with my custom function.
        updatePrice(data);
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement