最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

websocket - Binance API How to connect with a web socket using Javascript? - Stack Overflow

programmeradmin6浏览0评论

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.

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.

Share Improve this question asked Jan 16, 2021 at 14:21 AllartAllart 92813 silver badges39 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 6

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.: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);
    }
}

I would like to add another solution which handles the connection and configuration part under the hood. Using Mida, a JavaScript framework for connecting to exchanges/brokers to get data and/or trade automatically.

https://github./Reiryoku-Technologies/Mida

First we need to login to Binance

import { login, } from "@reiryoku/mida";

const myAccount = await login("Binance/Spot", {
    apiKey: "***",
    apiSecrect: "***",
});

Then to watch ETHUSDT live prices and candles we just use the market watcher API

import { MidaMarketWatcher, MidaTimeframe, } from "@reiryoku/mida";

const marketWatcher = new MidaMarketWatcher({ tradingAccount: myAccount, });

await marketWatcher.watch("ETHUSDT", {
    watchPeriods: true,
    timeframes: [ MidaTimeframe.M30, ],
});

// Listen M30 candlesticks being closed
marketWatcher.on("period-close", (event) => {
   const candle = event.descriptor.period;

   console.log("M30 candle closed at " + candle.close);
});
发布评论

评论列表(0)

  1. 暂无评论