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.