Untitled

 avatar
unknown
plain_text
2 years ago
1.2 kB
5
Indexable
const Binance = require('binance-api-node').default;
const Redis = require('redis');

const binanceClient = Binance();
const redisClient = Redis.createClient();

const symbols = ['ETH', 'BTC'];

// Define an object to store the latest prices for each symbol
const latestPrices = {};

// Define an asynchronous function to handle the ticker updates
async function handleTickerUpdate(symbol, price) {
  return new Promise((resolve, reject) => {
    redisClient.set(symbol, price, (error, result) => {
      if (error) {
        reject(error);
      } else {
        latestPrices[symbol] = price; // Update the latest price for the symbol
        resolve(result);
      }
    });
  });
}

// Subscribe to the real-time price feed for each symbol
symbols.forEach(symbol => {
  binanceClient.ws.ticker(symbol + 'USDT', async ticker => {
    const timestamp = new Date(ticker.eventTime).getTime();
    const price = parseFloat(ticker.bestBid);
    if (!latestPrices[symbol] || timestamp > latestPrices[symbol].timestamp) {
      try {
        await handleTickerUpdate(symbol, price);
      } catch (error) {
        console.error(`Error updating ${symbol} price in Redis: ${error}`);
      }
    }
  });
});
Editor is loading...