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.


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://');
// When message received from web socket then...
socket.onmessage = function (event) {

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

    // "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.
    } else {
        // Updating line with my custom function.

Source: stackoverflow