lbilli / Jib.jl

A Julia implementation of Interactive Brokers API
MIT License
62 stars 14 forks source link

How to respond to disconnection (e.g. Gateway restart) #46

Closed cmey closed 1 year ago

cmey commented 1 year ago

Hi, first of all, thank you for this package! :bowing_man:

I'm trying to make my software more robust in its usage of Jib.jl around Gateway disconnections. Currently, when IB Gateway (auto) restarts, my Julia client prints:

Warning: connection terminated
Info: reader exiting

I was wondering if / how the client could get notified in a way that allows it to take action in response to a disconnection from the Gateway?

For instance, when the Gateway (auto) restarts, it disconnects, and I would like to get notified of the disconnection (not just by a message print, but by a callback or maybe a variable I can repeatedly check) and take action.

The action I would take could be for example: trying connecting again repeatedly until Gateway is finished restarting and the connection succeeds, after which I would request data streams again (e.g. with reqMktData).

I went through the list of wrapper callbacks (in wrapper.jl) and did not see any that corresponds to what I need. However, there is this commented-out connectionClosed that sounded promising. Maybe it is planned for the future? In the meantime, do you see any easy workaround?

Maybe it's even something that looks easy to contribute, if that's the case, let me know and I can try to make a PR with your guidance :-)

Versions tested:

lbilli commented 1 year ago

In general wrapper callbacks are triggered by messages received from the server, TWS or IBGateway. The official IB API implementations also include "atypical" callbacks that are triggered by actions that happen on the client instead: for instance connectionClosed() is invoked when the user explicitly disconnects the client.

For a cleaner design, I decided to omit these "atypical" callbacks. In any case that would not address your situation.

When the server exits, restarts, crashes or unilaterally terminates the connection, e.g. due to pacing violations or duplicate client id usage, no warning message is sent and therefore no callback can be invoked.

Nevertheless, there are a couple of ways to inquire about the health of the connection:

ib = Jib.connect(port, clientId) t = start_reader(ib, wrap)

isopen(ib.socket) # if false the connection has been closed

istaskdone(t)    # if true the reader has exited for some reason and actions need to be taken

cmey commented 1 year ago

Ok, I can work with that. Thank you so much for your great answer. 🙂