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
Post a Comment