Error sending ping to keep listenKey alive

Hi guys,
Every 60m, listenKey will be expired, we need to renew its.
I created function to renew but error:
When starting code, everything is fine, but after 60m, server error:

Error sending ping to keep listenKey alive: AxiosError: Request failed with status code 400
    at settle (C:\Users\pc\Downloads\Website\node_modules\axios\dist\node\axios.cjs:1909:12)
    at IncomingMessage.handleStreamEnd (C:\Users\pc\Downloads\Website\node_modules\axios\dist\node\axios.cjs:2989:11)
    at IncomingMessage.emit (node:events:525:35)
    at endReadableNT (node:internal/streams/readable:1359:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

My code:

const BASE_URL = 'https://fapi.binance.com';
  const STREAM_URL = 'wss://fstream.binance.com/stream';
  
  let listenKey = '';
  
  const createListenKey = async () => {
    try {
      const response = await axios.post(`${BASE_URL}/fapi/v1/listenKey`, null, {
        headers: {
          'X-MBX-APIKEY': apiKey,
        },
      });
      return response.data.listenKey;
    } catch (error) {
      console.error('Error creating listenKey:', error.message);
      throw error;
    }
  };
  
  const keepListenKeyAlive = async () => {
    try {
      await axios.put(`${BASE_URL}/fapi/v1/listenKey`, null, {
        headers: {
          'X-MBX-APIKEY': apiKey,
        },
      });
      console.log('Ping sent to keep listenKey alive.');
    } catch (error) {
      console.error('Error sending ping to keep listenKey alive:', error);
    }
  };
  
  const startUserDataStream = async () => {
    try {
      // Create a listenKey
      listenKey = await createListenKey();
      console.log('listenKey:', listenKey);
  
      // Set interval to send a ping every 60 minutes
      setInterval(keepListenKeyAlive, 60 * 60 * 1000);
  
      // Establish a WebSocket connection
      const ws = new WebSocket(`${STREAM_URL}/${listenKey}`);
  
      // Handle incoming WebSocket messages
      ws.on('message', message => {
        console.log('Received WebSocket message:', message);
  
      });
  
      // Handle WebSocket connection open
      ws.on('open', () => {
        console.log('WebSocket connection opened');
      });
  
      // Handle WebSocket connection close
      ws.on('close', () => {
        console.log('WebSocket connection closed');
      });
    } catch (error) {
      console.error('Error starting User Data Stream:', error.message);
    }
  };
  
  // Start the User Data Stream
  startUserDataStream();

Many thanks for your support.

Try to debug by setting the setInterval to less than 60mins, you can test with for example 5000ms first.
Maybe it’s getting 400 because the listenkey is already expired, because 60mins has already passed.

Yes, thank you.

Hi @aisling2 ,
I am using ‘ORDER_TRADE_UPDATE’. I want to get data if what happen with open orders, such as: create new, or delete, or open orders => position.
But i test, don’t see anything in console if “create new, or delete, or open orders => position.”.


  const startUserDataStream = async () => {
    try {
      // Create a listenKey
      listenKey = await createListenKey();
      //console.log('listenKey:', listenKey);
  
      // Set interval to send a ping about every 50 minutes
      setInterval(keepListenKeyAlive, 50 * 60 * 1000);
  
      // Establish a WebSocket connection
      const ws = new WebSocket(`${STREAM_URL}/${listenKey}`);
  
      // Handle incoming WebSocket messages
      ws.on('message', message => {
        console.log('Received WebSocket message:', message);
  
        const data = JSON.parse(message);
        if (data && data.e === 'ACCOUNT_UPDATE') {
          const balance = data.a.find(asset => asset.a === 'USDT');
          const positions = data.p.filter(position => position.s === 'USDTM');
  
          if (balance) {
            console.log('Account Balance:', balance.w);
          }
  
          if (positions.length > 0) {
            positions.forEach(position => {
              console.log('Position:');
              console.log('Symbol:', position.s);
              console.log('Entry Price:', position.ep);
              console.log('Mark Price:', position.mr);
              console.log('Liquidation Price:', position.l);
  
              // Calculate PNL (ROE%)
              const pnl = (position.up * 100) / position.op;
              console.log('PNL (ROE%):', pnl);
            });
          }
        } else if (data && data.e === 'ORDER_TRADE_UPDATE') {
          console.log('Order Update:', data);
        }
      });
  
      // Handle WebSocket connection open
      ws.on('open', () => {
        console.log('WebSocket connection opened');
      });
  
      // Handle WebSocket connection close
      ws.on('close', () => {
        console.log('WebSocket connection closed');
      });
    } catch (error) {
      console.error('Error starting User Data Stream:', error.message);
    }
  };
  
  // Start the User Data Stream
  startUserDataStream();