Reputation: 53
my node-js application uses the bitfinex-api-node npm package to establish a websocket connection to receive data from the Bitfinex crypto-currency exchange.
Unfortunately, the connections silently breaks after some hours and the app stops receiving data over the websocket. This seems to be a known issue, maybe a bug of the bitfinex-api-module.
Now, I'm trying to "manually" reconnect by first connecting the websocket and subscribing to some candle data. Then the websocket.close() function gets called to simulate a connection error at runtime. In the on close function I set another timeout and try to create a new BFX() object and open() it but .on(open) never gets called.
=> I must be doing something wrong. Is there a mistake in my logic? Is there a better way to reconnect?
The following code works, just copy paste it and run to see for yourself. I am very thankful for any hints or tips.
const BFX = require('bitfinex-api-node');
//websocket
const opts = {
manageCandles: true,
transform: true,
API_KEY: 'hidden',
API_SECRET: 'hidden',
ws: {
autoReconnect: true,
seqAudit: true,
packetWDDelay: 10 * 1000
}
};
var websocket = new BFX().ws(2, opts);
websocket.on('open', () => {
//websocket.auth.bind(websocket)
console.log('.on(open) called');
websocket.subscribeCandles('trade:5m:tBTCUSD')
});
websocket.on('close', ()=>{
console.log('.on(close) called');
setTimeout(function() {
websocket = new BFX().ws(2, opts);
websocket.open();
}, 10000);
});
websocket.onCandle({key: 'trade:5m:tBTCUSD'},(candles) => {
console.log(candles[0]);
})
websocket.open();
// this closes the connection after 20 seconds
//after start for debugging purposes:
setTimeout(function() {
websocket.close();
}, 10000);
Upvotes: 4
Views: 885
Reputation: 14928
The problem is that you don't attach any listeners to a new instance of websocket, when a previous one is closed:
websocket.on('close', ()=>{
console.log('.on(close) called');
setTimeout(function() {
// this creates a new instance without listeners
websocket = new BFX().ws(2, opts);
websocket.open();
}, 10000);
});
While when you initialize the websocket for the first time, you add them:
websocket.on('open', /* code */);
websocket.onCandle(/* code */);
To resolve the issue, I suggest writing a function that creates and configures a new instance of websocket:
function createWebsocket() {
const websocket = new BFX().ws(2, opts);
websocket.on('open', /* code */);
websocket.onCandle(/* code */);
websocket.open();
}
And calling it in on('close')
:
websocket.on('close', ()=>{
console.log('.on(close) called');
setTimeout(createWebsocket, 10000);
});
Upvotes: 1