To prepare for live trading with Interactive Brokers, the following steps are required:
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:
from quantrocket.ibg import start_gateways
start_gateways(wait=True)
Then collect the listings for all US stocks:
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
Monitor flightlog for completion, which may take several hours. (You can continue with the setup process while waiting for the listings collection to finish.)
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:
from quantrocket.realtime import create_ibkr_tick_db
create_ibkr_tick_db(
"us-stk-tick",
fields=["LastPrice", "Volume"],
# 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"
)
Then create the 1-minute aggregate database derived from the tick database:
from quantrocket.realtime import create_agg_db
create_agg_db(
"us-stk-tick-1min",
tick_db_code="us-stk-tick",
bar_size="1m",
fields={"LastPrice": ["Open","High","Low","Close"], "Volume":["Close"]})
Note in the above function call we use the close of Volume
to obtain the volume data. This contrasts to some real-time data providers where instead of the Volume
field we would use the sum of LastSize
to get volume. The before_trading_start()
function in the Zipline algo uses LastSizeSum
in the real-time database call, so we must update the code so that it uses VolumeClose
instead of LastSizeSum
.
Find the following block of code in the sell-gap.py
file and change LastSizeSum
to VolumeClose
:
# ...and point Zipline to the derived aggregate db
algo.set_realtime_db(
"us-stk-tick-1min",
fields={
"close": "LastPriceClose",
"open": "LastPriceOpen",
"high": "LastPriceHigh",
"low": "LastPriceLow",
"volume": "LastSizeSum"}) # for IBKR real-time data, use VolumeClose
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.