Error when reconnecting
mpolavieja opened this issue · 2 comments
Hello,
I am using ib-insync 0.9.86 on a windows server 2022 machine. On the daily restart, I reconnect automatically to TWS using the following code (core is an object that inherits from IB class):
def _connect_to_broker():
''' Tries to connect to Interactive Brokers '''
global log
global configurationBase
core.disconnect()
currentReconnect = 1
while True:
try:
connection_loss_seconds = time.time() - core.last_connection_time
core.connect("127.0.0.1", port=7497, clientId=configurationBase['client_tws'], timeout=5)
if core.isConnected():
text = 'BOT CONNECTED SUCCESFULLY'
print('{} {}'.format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), text))
log.info(text)
core.last_connection_time = time.time()
if conection_loss_seconds > configurationBase['max_connection_loss_seconds']:
text = 'BOT RESTARTING STRATEGIES. Disconnected for {} seconds.'
.format(round(connection_loss_seconds))
print(text)
log.info(text)
core.cancel_all_orders()
core.parameters.reset()
break
except Exception as e:
text = 'Not possible to connect on attempt {}. Next attempt in {} seconds.'.format(
currentReconnect, configurationBase['reconnection_seconds']
)
print(text)
log.error(text)
currentReconnect += 1
core.sleep(configurationBase['reconnection_seconds'])
And below is the error I am always getting in the console (I've been unable to handle the error through the except clause). I am pretty sure there are no other instances of TWS running. Despite the error, everything seems to work properly, but I am not comfortable at all not knowing why this is happening and not being able to handle the error:
2023-10-19 09:47:17 BOT CONNECTED SUCCESFULLY
Exception in callback _ProactorBasePipeTransport._call_connection_lost (None)
handle: Handle _ProactorBasePipeTransport._call_connection_lost(None)>
Traceback (most recent call last):
File "C:\Users\Administrator\AppDsta\Local\Programs\Python\Python311\Lib\asyncio\events.py”, line 80, in _run
self. _context.run(self._callback, *self. args)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\asyncio\proactor_events.py”, line 165, in _c
ll_connection_lost
self._sock. shutdown (socket . SHUT_RDWR)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
Thank you in advance for your help
Edit: I am not able to capture the error within my except clause, but If I delete my except clause, I am not able to capture the error using "disconnectedEvent" or "errorEvent" either (but I might be doing something wrong).
Since I was dealing with connection errors lately, a quick comment: I catch connection errors with the exact error name, in this case "ConnectionResetError", so this should work:
try:
...
except ConnectionResetError as error:
print(f"Exception {error}")
...