This is the implementation I have. I decided to use a single WebSocket connection for @depth and account updates. Some days are worse than others. I connected over the wire now rather than wife and still get disconnected sporadically. Here is the code. Please let me know where it can be improved.
let refreshInterval;
const listenKey = // getting a listenKey here using POST /fapi/v1/listenKey
const ws = new WebSocket(“wss://fstream.binance.com/ws/” + listenKey);
ws.onopen = () => {
refreshInterval = setInterval(() => {
// doing PUT /fapi/v1/listenKey to keep the listenkey alive
}, 1000 * 60 * 29);
ws.send(
JSON.stringify({
method: ‘SUBSCRIBE’,
params: [someTicker + ‘@depth’],
id: 1,
})
);
};
ws.onclose = async () => {
clearInterval(refreshInterval);
// handling reconnect here. it happens many very randomly sometimes multiple times an hour - sometimes not as often - the least is probably a few times a day.
};