4

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?

Shimul
  • 463
  • 2
  • 7
  • 33
  • Seems like you've made multiple connections and are trying to disconnect the disconnected (inactive) one. Monitor active connection count when this happens. – misantroop Apr 16 '21 at 11:41
  • Until I reload a page, there is only one connection. When I reload the page, I tried to disconnect the previous connection and establish a new one. So I don't think there have multiple connections and I tried to disconnect, that is already disconnected – Shimul Apr 18 '21 at 04:19
  • 504 means your disconnecting a nonexisting connection. This error is not on IB side, review your code or post here. I use many sessions with connect/disconnect and it works without fault. – misantroop Apr 18 '21 at 04:54
  • Here is the code of IB streaming I write: https://codeshare.io/2j3n1K – Shimul Apr 18 '21 at 11:10
  • Here is the code that is used in the show page of my Apps: https://codeshare.io/5zZdpk – Shimul Apr 18 '21 at 11:13

3 Answers3

0

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

0

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
Abhishake Gupta
  • 2,939
  • 1
  • 25
  • 34
0

Sample IB code. If you like to disconnect now, you just run: app.disconnect()

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
import threading
import time

tickers = ["NVDA", "SPY", "QQQ", "TQQQ", "SQQQ"]


class TradeApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.lastPrice = {}

    def tickPrice(self, reqId, tickType, price, attrib):
        super().tickPrice(reqId, tickType, price, attrib)
        # print("TickPrice. TickerId:", reqId, "tickType:", tickType, "Price:", price)
        self.lastPrice[reqId] = price


def usTechStk(symbol, sec_type="STK", currency="USD", exchange="ISLAND"):
    contract = Contract()
    contract.symbol = symbol
    contract.secType = sec_type
    contract.currency = currency
    contract.exchange = exchange
    return contract


def streamSnapshotData(tickers):
    """stream tick level data"""
    for ticker in tickers:
        app.reqMktData(reqId=tickers.index(ticker),
                       contract=usTechStk(ticker),
                       genericTickList="",
                       snapshot=False,
                       regulatorySnapshot=False,
                       mktDataOptions=[])
        time.sleep(1)


def last_price(ticker):
    return app.lastPrice[tickers.index(ticker)]


def connection():
    app.run()


app = TradeApp()
# port 4002 for ib gateway paper trading/7497 for TWS paper trading
app.connect(host='127.0.0.1', port=7497, clientId=23)

ConThread = threading.Thread(target=connection)
ConThread.start()

streamThread = threading.Thread(target=streamSnapshotData, args=(tickers,))
streamThread.start()
time.sleep(3)  # some lag added to ensure that streaming has started
Isak La Fleur
  • 4,428
  • 7
  • 34
  • 50