jaggedsoft / node-binance-api

Node Binance API is an asynchronous node.js library for the Binance API designed to be easy to use.
MIT License
1.58k stars 769 forks source link

Kline streams - How to connect it to React ? #615

Open Tom687 opened 3 years ago

Tom687 commented 3 years ago

Hi, first of all, thank you for this amazing API.

However, I was a problem : I am trying to get all the Klines streams for USDT pairs into a React dashboard.

I am using this code I found in the docs :

binance.prevDay(false, (error, prevDay) => {
    let markets = [];
    for ( let obj of prevDay ) {
        let symbol = obj.symbol;
        console.log(symbol+" volume:"+obj.volume+" change: "+obj.priceChangePercent+"%");
        markets.push(symbol);
    }
    binance.websockets.candlesticks(markets, '1m', (candlestickData) => {
        let tick = binance.last(candlestickData);
        const symbol = candlestickData.s;
        const close = candlestickData[tick].c;
        console.log(symbol+": "+close);
    });
});

Problem is, if I put this code directly in my frontend, I get this error :

Access to fetch at '…' from origin 'http://localhost:3001' has been blocked by CORS policy: Request header field x-mbx-apikey is not allowed by Access-Control-Allow-Headers in preflight response.

After a lot of digging, I concluded that I had to go through my Nodejs backend to execute the function. Alright, it works. However, what kind of Websocket event / listener does the function returns ? I can see all the pairs live in my terminal, but I have no idea how to get it to the actual React dashboard. I have tried many many things and did a lot of research, all of them failed.

Could someone please point me in the right direction ?

Thank you very much

Kuzmich100kM commented 3 years ago

You can use SocketIO.

For example, on the client side:

let room = `${symbol.toLowerCase()}@kline_${interval}`
socket.emit(`GET_CANDLES_WS`, symbol, interval, room)
socket.on(`RES_CANDLES_WS_${room}`, data => console.log(data))

On server side


socket.on("GET_CANDLES_WS", (symbol, interval, room) => {
        socket.join(room)
    binance.websockets.candlesticks(symbol, interval', (candlestickData) => {
               io.sockets.in(room).emit(`RES_CANDLES_WS_${room}`, candlestickData))
             }
    })