Skip to content

Advanced WebSocket

voyz edited this page Apr 29, 2024 · 4 revisions

Advanced WebSocket Functionalities

Advanced Lifecycle Management

IBKR WebSocket API may behave unexpectedly in the future if the previous connections are not closed gracefully. We need to ensure to always call IbkrWsClient.shutdown method when the program stops.

To do so, use signal module to shutdown when the program is terminated.

import signal

# assuming we subscribe to Orders channel
ws_client.subscribe(channel='or', data=None, needs_confirmation=False)

# this is a callback used when the program stops
def stop(_, _1):
    # we unsubscribe from the Orders channel
    ws_client.unsubscribe(channel='or', data=None, needs_confirmation=False)

    # we gracefully close the connection
    ws_client.shutdown()

# register the `stop` callback to be called when the program stops
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop)

Advanced Subscribing and Unsubscribing