pilwon / node-ib

Interactive Brokers TWS API client library for Node.js
382 stars 134 forks source link

Client sometimes does not reconnect gracefully after sleeping for an hour #181

Open leebailey88 opened 1 year ago

leebailey88 commented 1 year ago

I've used this repo for 3 years now with varying success. My use case involves needing to run my model and possibly make trades every hour, with a sleeping period inbetween, at a high level:

let ib;
while (true) {
  try {
    ib = new IB({
      clientId: 1,
      host: '127.0.0.1',
      port: 4003
    });
    // add IB event handlers here
    break;
  } catch (e) {
    console.log('IB is down, restarting in 3 minutes', e);
    sleep(1000 * 60 * 3);
  }
}
while (true) {
  const mainArgs = { ib, sheets, sheetData, cacheEnabled, adjustLeverage, noTrades, longLeverage, shortLeverage };
  await mainLoop(mainArgs);
  const nextHourStart = getNextHourStart();
  const nextHourWait = nextHourStart.diff(moment().tz('America/New_York'));
  console.log('\nWaiting', roundTo(nextHourWait / (1000 * 60)), 'minutes to start at', nextHourStart.format('lll'), 'EST\n');
  await sleep(nextHourWait);
}

inside mainLoop:

const mainLoop = ({ ib, }) => {
  ib.connect();
  runModel(ib); // evaluate algorithm and possibly place trades
  ib.disconnect();
};

I've always had the problem that sometimes the IB client would fail to reconnect at the next hour, and even calling ib.disconnect() and ib.connect() again in a try catch would not resolve it. It's as if the client has died and only completely restarting my script and the Docker container for IB Gateway would fix it. This used to be an ok solution until IB started forcing the 2FA requirement. Now it's terrible as I'm trading futures and often asleep or not by my phone which means I experience downtime until I'm at my phone again to re-authenticate.

Has anyone else had intermittent connection issues? How did you resolve them? Is there a less buggy and more up to date Node IB API I should use instead?