Interactive Brokers API - How to disconnect an existing connection of IB Gateway and establish a new connection using Python?

Viewed 1068

I am testing Interactive Brokers Python API in a Hobby project. I am using Interactive Brokers Gateway (rather TWS). My project is a simple Django-based application. I can connect successfully and receive real-time data using the method reqMktData(). Everything is OK so far.

But when I refresh the page it shows 504 Not Connected, although in IB Gateway it shows there is a running connection. To stop this, During a page reload I am trying to disconnect the previous connection using the Eclient disconnect() method available in the API, but it can not disconnect the running connection.

Can anyone have any idea how can I disconnect a running connection in IB Gateway and start a new connection?

2 Answers

Changing my client Id seems to fix it for me. Maybe toggle back and forth between 2 of them?

To disconnect from TWS IBAPI (python)

  1. set attribute ib.conn = None
  2. then call ib.disconnect() function,
  3. then the callback function would stop() of EWrapper class
Related