QuantRocket logo

Interactive Brokers Steps

To prepare for live trading with Interactive Brokers, the following steps are required:

  • Collect listings from IBKR
  • Create realtime database
  • Specify an exchange when submitting orders

Collect listings from IBKR

To place orders and/or collect real-time data through Interactive Brokers, it is necessary to collect securities master listings from Interactive Brokers. It is not sufficient to have collected the listings from another vendor; specific IBKR fields must be present in the securities master database in order to allow QuantRocket to communite with the IBKR API.

First, start IB Gateway:

In [1]:
from quantrocket.ibg import start_gateways
start_gateways(wait=True)
Out[1]:
{'ibg1': {'status': 'running'}}

Then collect the listings for all US stocks:

In [2]:
from quantrocket.master import collect_ibkr_listings
collect_ibkr_listings(
    exchanges=['NASDAQ', 'NYSE', 'AMEX', 'BATS', 'ARCA'], 
    sec_types=['STK']) # or STK and ETF if you need ETFs
Out[2]:
{'status': 'the IBKR listing details will be collected asynchronously'}

Monitor flightlog for completion, which may take several hours. (You can continue with the setup process while waiting for the listings collection to finish.)

Real-time database

Next, create the real-time database. These steps simply create the database. Real-time data collection will be initiated from the Zipline strategy code. First, create the tick database:

In [3]:
from quantrocket.realtime import create_ibkr_tick_db
create_ibkr_tick_db(
    "us-stk-realtime", 
    # specifying a universe is required, but we will override this when initiating data 
    # collection in the Zipline strategy, so the universe need not exist
    universes="us-stk",
    fields=["LastPrice", "LastSize"]  
)
Out[3]:
{'status': 'successfully created tick database us-stk-realtime'}

Then create the 1-minute aggregate database derived from the tick database:

In [4]:
from quantrocket.realtime import create_agg_db
create_agg_db(
    "us-stk-realtime-1min",
    tick_db_code="us-stk-realtime",
    bar_size="1m",
    fields={
        "LastPrice":["Open","High","Low","Close"],
        "LastSize": ["Sum"]})
Out[4]:
{'status': 'successfully created aggregate database us-stk-realtime-1min from tick database us-stk-realtime'}

Specify an exchange

Unlike some brokers, Interactive Brokers requires that you specify an exchange when submitting orders. In the sell-gap.py file, find the block of code where orders are placed and add the exchange param, for example exchange="SMART":

algo.order_value(
    asset,
    context.target_value_per_position,
    style=MarketOrder(exchange="SMART")
)

Repeat this step for the block of code that places orders to close positions.