I'm encountering an issue similar to the one mentioned in the following stackoverflow query: How to set up an error handler for Interactive brokers using IB API or ib_insync? Python - Stack Overflow
Basically when the internet goes down at home for a few mins, TWS loses connection to the Historical Data Farm. When the internet comes back ON, the API->TWS connection is re-instated however the subscription request for historical market data is lost. Is there a way to re-initiate all requests/subscriptions in a clean way once connection is reestablished?
What you are looking for is a reconciliation logic, which by definition differs from strategy to strategy. In a situation similar to what you mentioned, one of the approaches can be as follows:
- On every iteration of the run, you should check whether you are connected to IB TWS or not using the app.isConnected() method. For example, if your trading frequency is 5 mins, you will check every 5 mins before your strategy logic executes.
- The above point takes care of the connection between your client and IB TWS. Another check to implement is to see whether you are connected to the internet or not. In this case, you can ping to your broker's server (if they provide) or any public websites.
- If you don't receive a response from the ping command, you set up a loop that keeps checking until your connection is restored.
- You can run this check in a loop with some interval.
- If you have a disconnection; upon reconnection:
- The algorithm should check for all the open positions in the account. Ideally, those positions should be present in the account. If they are not, you need to define what to do based on your strategy logic. For example, adjust positions in your algorithm.
- Fetch the historical data for whatever time the algorithm was disconnected. This is to ensure that your algorithm doesn't calculate incorrect technical or statistical indicators if any.
- Setup the streaming data again. TWS will do this by itself; you need to cancel your current subscription and subscribe again.
Thanks for your response, Jay. I will try out a few variants of the process you listed above and let you know if i face any further issues.