connect websocket to binance api and store t he true value in the db

 


const WebSocket = require('ws');

const bitcoindata = require('../model/bitcoindata.model');

function connectToBinanceWebSocket() {
  // Connect to Binance's WebSocket API for the BTC/USDT trading pair
  const socket = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@kline_1m');

  // Handle messages received from the WebSocket
  socket.on('message', (data) => {
    const message = JSON.parse(data);
    if (message.e === 'kline') {
      const candle = message.k;
      console.log(`[${new Date(candle.t).toLocaleTimeString()}] Open: ${candle.o}, High: ${candle.h}, Low: ${candle.l}, Close: ${candle.c}`);
      if(candle.x == true) {
        console.log({candle})
        bitcoindata.create({
            closeprice: candle.c,
            openprice: candle.o,
            volume: candle.V,
        })
      }
    }
  });

  // Send a message to subscribe to the WebSocket's candlestick data
  socket.on('open', () => {
    socket.send(JSON.stringify({
      method: 'SUBSCRIBE',
      params: ['btcusdt@kline_1m'],
      id: 1,
    }));
  });

  // Handle errors and reconnect the WebSocket after a delay
  socket.on('error', (error) => {
    console.error(`WebSocket error: ${error}`);
    setTimeout(() => {
      console.log('Reconnecting to WebSocket...');
      connectToBinanceWebSocket();
    }, 5000);
  });
}

// Call the function to connect to the WebSocket
connectToBinanceWebSocket();

Comments

All time Best Post

Write a program that declares a class named Person. It should have instance variables to record name, age and salary. Use new operator to create a Person object. Set and display its instance variables.

IMAGE CRUD OPERATION USING EXPRESS MONGOOSE MULTER

CRUD APP WITH SORT IN NODE EXPRESS AND MONGODB

express session login system using node express mongodb

how to delete image from the folder directly from a Request (MULTER)

calculate rsi

java program for 1 to 10 print using while loop

How to fetch last one minute volume of BTC in CCXT Nodejs.