How can I convert 1minute live candlestick data into two minute
There is no one to reply my question how to make 2m live chart for binance symbole coin same as tradingview I have tried to aggregate the data but only historical is done it is not happening live please help me I have tried many things but it is not happening, at least tell me is it possible or not.
wss.on(‘connection’, (ws, req) => {
console.log(‘Client connected’);
const symbol = 'BTCUSDT';
const interval = '1m';
const binanceSocket = new WebSocket(
`wss://stream.binance.com:9443/ws/${symbol.toLowerCase()}@kline_${interval}`
);
binanceSocket.onopen = () => {
console.log(`Connected to Binance stream for ${symbol}`);
};
// Listen for messages from Binance WebSocket
binanceSocket.onmessage = async (event) => {
const data = JSON.parse(event.data);
const kline = data.k;
// let klineData = {
// // time: Date(kline.t / 1000 + 19800), // Adjust to seconds and timezone (if needed)
// time: kline.t / 1000 + 19800,
// open: parseFloat(kline.o),
// high: parseFloat(kline.h),
// low: parseFloat(kline.l),
// close: parseFloat(kline.c),
// volume: parseFloat(kline.v),
// // closeTime: Date(kline.T / 1000 + 19800),
// closeTime: kline.T / 1000 + 19800,
// };
// console.log(klineData);
// ws.send(JSON.stringify(klineData));
const isCandleClosed = kline.x; // Check if the candle is closed
// If a new 1-minute candle has closed
if (isCandleClosed) {
const currentCandle = {
openTime: kline.t,
open: parseFloat(kline.o),
high: parseFloat(kline.h),
low: parseFloat(kline.l),
close: parseFloat(kline.c),
volume: parseFloat(kline.v),
closeTime: kline.T,
};
if (!lastCandle) {
// If this is the first candle we're receiving
lastCandle = currentCandle;
} else {
// Combine two 1-minute candles into one 2-minute candle
const combinedCandle = {
openTime: lastCandle.openTime,
open: lastCandle.open,
high: Math.max(lastCandle.high, currentCandle.high), // Highest high
low: Math.min(lastCandle.low, currentCandle.low), // Lowest low
close: currentCandle.close, // Close price of the second candle
volume: (lastCandle.volume + currentCandle.volume).toFixed(
8
), // Sum of volumes
closeTime: currentCandle.closeTime,
};
// Log the 2-minute combined candle
console.log(
`2m Candle -> Open: ${combinedCandle.open}, High: ${combinedCandle.high}, Low: ${combinedCandle.low}, Close: ${combinedCandle.close}, Volume: ${combinedCandle.volume}`
);
// Reset lastCandle so we can combine the next two 1-minute candles
lastCandle = null;
ws.send(JSON.stringify(combinedCandle));
}
// If this is the first candle of a new 2-minute interval, store it for combining
if (!lastCandle) {
lastCandle = currentCandle;
}
}
};
// Error handling
binanceSocket.onerror = (error) => {
console.error(`WebSocket error: ${error.message}`);
};
// Close connection handling
ws.on('close', () => {
console.log('Client disconnected');
binanceSocket.close(); // Close Binance WebSocket when client disconnects
});
});