Contents
Brokerages
Interactive Brokers
Introduction
QuantConnect enables you to run your algorithms in live mode with real-time market data. We have successfully hosted more than 200,000 live algorithms and have had more than $15B in volume traded on our servers since 2015. Brokerages supply a connection to the exchanges so that you can automate orders using LEAN. You can use multiple data feeds in live trading algorithms.
Interactive Brokers (IB) was founded by Thomas Peterffy in 1993 with the goal to "create technology to provide liquidity on better terms. Compete on price, speed, size, diversity of global products and advanced trading tools". IB provides access to trading Equities, ETFs, Options, Futures, Future Options, Forex, Gold, Warrants, Bonds, and Mutual Funds for clients in over 200 countries and territories with no minimum deposit. IB also provides paper trading, a trading platform, and educational services.
Account Types
The IB API does not support the IBKR LITE plan. You need an IBKR PRO plan. Individual and Financial Advisor (FA) accounts are available.
Individual Accounts
IB supports cash and margin accounts.
SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash); SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin);
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash) self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)
FA Accounts
IB supports FA accounts for Trading Firm and Institution organizations. FA accounts enable certified professionals to use a single trading algorithm to manage several client accounts. For more information about FA accounts, see Financial Advisors.
Create an Account
You need to open an IBKR Pro account to deploy algorithms with IB. The IB API does not support IBKR Lite accounts. To create an IB account, see the Open an Account page on the IB website.
You need to activate IBKR Mobile Authentication (IB Key) to deploy live algorithms with your brokerage account. After you open your account, follow the installation and activation instructions on the IB website.
Paper Trading
IB supports paper trading. Follow the Opening a Paper Trading Account page in the IB documentation to set up your paper trading account.
If you want to use IB data feeds and trade with your paper trading account, follow these steps:
- Log in to the IB Client Portal.
- In the top-right corner, click the person icon and then click .
- In the Account Configuration section, click Paper Trading Account.
- Click .
- Click .
Financial Advisors
IB supports FA accounts for Trading Firm and Institution organizations. FA accounts enable certified professionals to use a single trading algorithm to manage several client accounts.
To place trades using a subset of client accounts, create Account Groups in Trader Workstation and then define the InteractiveBrokersOrderProperties
when you create orders.
DefaultOrderProperties = new InteractiveBrokersOrderProperties { FaGroup = "TestGroupEQ", FaMethod = "EqualQuantity", FaProfile = "TestProfileP", Account = "DU123456" };
self.DefaultOrderProperties = InteractiveBrokersOrderProperties() self.DefaultOrderProperties.FaGroup = "TestGroupEQ" self.DefaultOrderProperties.FaMethod = "EqualQuantity" self.DefaultOrderProperties.FaProfile = "TestProfileP" self.DefaultOrderProperties.Account = "DU123456"
SecurityHolding objects aggregate your positions across all the account groups. If you have two groups where group A has 10 shares of SPY and group B has -10 shares of SPY, then self.Portfolio["SPY"].Quantity
Portfolio["SPY"].Quantity
is zero.
The following table shows the supported allocation methods for FA group orders:
FaMethod | Description |
---|---|
"EqualQuantity" | Distributes shares equally between all accounts in the group. If you use this method, specify an order quantity. |
"NetLiq" | Distributes shares based on the net liquidation value of each account. The system calculates ratios based on the net liquidation value in each account and allocates shares based on these ratios. If you use this method, specify an order quantity. |
"AvailableEquity" | Distributes shares based on the amount of available equity in each account. The system calculates ratios based on the available equity in each account and allocates shares based on these ratios. If you use this method, specify an order quantity. |
"PctChange" | Increases or decreases an already existing position. Positive percents increase positions and negative percents decrease positions. If you use this method, specify a percent instead of an order quantity. |
public override void Initialize() { // Set the default order properties DefaultOrderProperties = new InteractiveBrokersOrderProperties() { FaGroup = "TestGroupEQ", FaMethod = "EqualQuantity", FaProfile = "TestProfileP", Account = "DU123456" }; } public override void OnData(Slice slice) { // Use default order order properties LimitOrder(_symbol, quantity, limitPrice); // Override the default order properties // "NetLiq" requires a order size input LimitOrder(_symbol, quantity, limitPrice, orderProperties: new InteractiveBrokersOrderProperties { FaMethod = "NetLiq" }); // "AvailableEquity" requires a order size input LimitOrder(_symbol, quantity, limitPrice, orderProperties: new InteractiveBrokersOrderProperties { FaMethod = "AvailableEquity" }); // "PctChange" requires a percentage of portfolio input SetHoldings(_symbol, pctPortfolio, orderProperties: new InteractiveBrokersOrderProperties { FaMethod = "PctChange" }); }
def Initialize(self) -> None: # Set the default order properties self.DefaultOrderProperties = InteractiveBrokersOrderProperties() self.DefaultOrderProperties.FaGroup = "TestGroupEQ" self.DefaultOrderProperties.FaMethod = "EqualQuantity" self.DefaultOrderProperties.FaProfile = "TestProfileP" self.DefaultOrderProperties.Account = "DU123456" def OnData(self, slice: Slice) -> None: # Override the default order properties # "NetLiq" requires a order size input order_properties = InteractiveBrokersOrderProperties() order_properties.FaMethod = "NetLiq" self.LimitOrder(self.symbol, quantity, limit_price, orderProperties=order_properties) # "AvailableEquity" requires a order size input order_properties.FaMethod = "AvailableEquity" self.LimitOrder(self.symbol, quantity, limit_price, orderProperties=order_properties) # "PctChange" requires a percentage of portfolio input order_properties.FaMethod = "PctChange" self.SetHoldings(self.symbol, pct_portfolio, orderProperties=order_properties)
Asset Classes
Our IB integration supports trading Equities, Options, Forex, Futures, Future Options, and Index Options.
AddEquity("SPY", Resolution.Minute, Market.USA); AddOption("SPY", Resolution.Minute, Market.USA); AddForex("EURUSD", Resolution.Minute, Market.Oanda).Symbol; var goldFutures = AddFuture(Futures.Metals.Gold, Resolution.Minute, Market.CME); AddFutureOption(goldFutures.Symbol, universe => universe.Strikes(-5, +5)); var vixIndex = AddIndex("VIX", Resolution.Minute, Market.USA); AddOption(vixIndex.Symbol);
self.AddEquity("SPY", Resolution.Minute, Market.USA) self.AddOption("SPY", Resolution.Minute, Market.USA) self.AddForex("EURUSD", Resolution.Minute, Market.Oanda).Symbol gold_futures = self.AddFuture(Futures.Metals.Gold, Resolution.Minute, Market.CME) self.AddFutureOption(gold_futures.Symbol, lambda universe: universe.Strikes(-5, +5)) vix_index = self.AddIndex("VIX", Resolution.Minute, Market.USA) self.AddOption(vix_index.Symbol)
If you call the SetBrokerageModel
method with the correct BrokerageName
, then you don't need to pass a Market
argument to the method calls above because the brokerage model automatically selects the correct market.
Assets Available
Refer to the dataset listing of the asset class you are trading to see the assets available. The following table shows the dataset listing of each asset class supported by IB:
Asset Class | Dataset Listing |
---|---|
Equities | US Equities |
Options | US Equity Options |
Forex | FOREX Data |
Futures | US Futures |
Future Options | US Future Options |
Index Options | US Index Options |
Data Feeds
You might need to purchase an IB data subscription for your trading. For more information about live data feeds, see Data Feeds.
ETFs
You may not be able to trade all assets with IB. For example, if you live in the EU, you can’t trade US ETFs. Check with your local regulators to know which assets you are allowed to trade. You may need to adjust settings in your brokerage account to live trade some assets.
Orders
We model the IB API by supporting several order types, order properties, and order updates. When you deploy live algorithms, you can place manual orders through the IDE.
Order Types
The following table describes the order types that IB supports. For specific details about each order type, refer to the IB documentation.
Order Type | IB Documentation Page |
---|---|
MarketOrder | Market Orders |
LimitOrder | Limit Orders |
StopMarketOrder | Stop Orders |
StopLimitOrder | Stop-Limit Orders |
MarketOnOpenOrder | Market-on-Open (MOO) Orders |
MarketOnCloseOrder | Market-on-Close (MOC) Orders |
LimitIfTouchedOrder | Limit if Touched Orders |
ExerciseOption | Options Exercise |
MarketOrder(_symbol, quantity); LimitOrder(_symbol, quantity, limitPrice); StopMarketOrder(_symbol, quantity, stopPrice); StopLimitOrder(_symbol, quantity, stopPrice, limitPrice); MarketOnOpenOrder(_symbol, quantity); MarketOnCloseOrder(_symbol, quantity); LimitIfTouchedOrder(_symbol, quantity, triggerPrice, limitPrice); ExerciseOption(_optionSymbol, quantity);
self.MarketOrder(self.symbol, quantity) self.LimitOrder(self.symbol, quantity, limit_price) self.StopMarketOrder(self.symbol, quantity, stop_price) self.StopLimitOrder(self.symbol, quantity, stop_price, limit_price) self.MarketOnOpenOrder(self.symbol, quantity) self.MarketOnCloseOrder(self.symbol, quantity) self.LimitIfTouchedOrder(self.symbol, quantity, trigger_price, limit_price) self.ExerciseOption(self.option_symbol, quantity)
Market on open orders are not available for Futures or Future Options.
Order Properties
We model custom order properties from the IB API. The following table describes the members of the InteractiveBrokersOrderProperties
object that you can set to customize order execution. The table does not include the preceding methods for FA accounts.
Property | Description |
---|---|
TimeInForce | A TimeInForce instruction to apply to the order. The following instructions are supported:
|
OutsideRegularTradingHours | A flag to signal that the order may be triggered and filled outside of regular trading hours. |
public override void Initialize() { // Set the default order properties DefaultOrderProperties = new InteractiveBrokersOrderProperties { TimeInForce = TimeInForce.GoodTilCanceled, OutsideRegularTradingHours = false }; } public override void OnData(Slice slice) { // Use default order order properties LimitOrder(_symbol, quantity, limitPrice); // Override the default order properties LimitOrder(_symbol, quantity, limitPrice, orderProperties: new InteractiveBrokersOrderProperties { TimeInForce = TimeInForce.Day, OutsideRegularTradingHours = false }); LimitOrder(_symbol, quantity, limitPrice, orderProperties: new InteractiveBrokersOrderProperties { TimeInForce = TimeInForce.GoodTilDate(new DateTime(year, month, day)), OutsideRegularTradingHours = true }); }
def Initialize(self) -> None: # Set the default order properties self.DefaultOrderProperties = InteractiveBrokersOrderProperties() self.DefaultOrderProperties.TimeInForce = TimeInForce.GoodTilCanceled self.DefaultOrderProperties.OutsideRegularTradingHours = False def OnData(self, slice: Slice) -> None: # Use default order order properties self.LimitOrder(self.symbol, quantity, limit_price) # Override the default order properties order_properties = InteractiveBrokersOrderProperties() order_properties.TimeInForce = TimeInForce.Day order_properties.OutsideRegularTradingHours = True self.LimitOrder(self.symbol, quantity, limit_price, orderProperties=order_properties) order_properties.TimeInForce = TimeInForce.GoodTilDate(datetime(year, month, day)) self.LimitOrder(self.symbol, quantity, limit_price, orderProperties=order_properties)
Updates
IB supports order updates. You can define the following members of an UpdateOrderFields
object to update active orders:
Quantity
LimitPrice
StopPrice
TriggerPrice
Tag
var ticket = StopLimitOrder(symbol, quantity, stopPrice, limitPrice, tag); var orderFields = new UpdateOrderFields {
Quantity = newQuantity,
LimitPrice = newLimitPrice,
StopPrice = newStopPrice,
Tag = newTag
}; ticket.Update(orderFields);
ticket = self.StopLimitOrder(symbol, quantity, stop_price, limit_price, tag)
update_fields = UpdateOrderFields() update_fields.Quantity = new_quantity
update_fields.LimitPrice = new_limit_price
update_fields.StopPrice = new_stop_price update_fields.Tag = new_tag ticket.Update(update_fields)
Fill Time
IB has a 400 millisecond fill time for live orders.
Financial Advisor Group Orders
To place FA group orders, see Financial Advisors.
Fees
We model the order fees of IB for each asset class. The following table shows the fees:
Asset Class | Fee |
---|---|
Equities | $0.005/share with a $1 minimum fee |
Futures | $1.85/contract |
Future Options | $1.85/contract |
The fees for trading Options depend on your monthly volume and the premium of the contract that you're trading. The following table shows the fees for trading Options:
Monthly Volume (Contacts) | Premium ($) | Fee per Contract ($) |
---|---|---|
<= 10,000 | < 0.05 | 0.25 |
<= 10,000 | 0.05 <= premium < 0.10 | 0.50 |
<= 10,000 | >= 0.10 | 0.70 |
10,000 < volume <= 50,000 | < 0.05 | 0.25 |
10,000 < volume <= 50,000 | >= 0.05 | 0.50 |
50,000 < volume <= 100,000 | Any | 0.25 |
> 100,000 | Any | 0.15 |
There is no fee to exercise Option contracts.
To check the latest fees, see the Commissions page on the IB website.
Margin
We model buying power and margin calls to ensure your algorithm stays within the margin requirements.
Buying Power
In the US, IB allows up to 2x leverage on Equity trades for margin accounts. In other countries, IB may offer different amounts of leverage. To figure out how much leverage you can access, check with your local legislation or contact an IB representative. We model the US version of IB leverage by default.
Margin Calls
Regulation T margin rules apply. When the amount of margin remaining in your portfolio drops below 5% of the total portfolio value, you receive a warning. When the amount of margin remaining in your portfolio drops to zero or goes negative, the portfolio sorts the generated margin call orders by their unrealized profit and executes each order synchronously until your portfolio is within the margin requirements.
Pattern Day Trading
If all of the following statements are true, you are classified as a pattern day trader:
- You reside in the United States.
- You trade in a margin account.
- You execute 4+ intraday US Equity trades within 5 business days.
- Your intraday US Equity trades represent more than 6% of your total trades.
Pattern day traders must maintain a minimum equity of $25,000 in their margin account to continue trading. For more information about pattern day trading, see Am I a Pattern Day Trader? on the FINRA website.
The PatternDayTradingMarginModel
doesn't enforce minimum equity rules and doesn't limit your trades, but it adjusts your available leverage based on the market state. During regular market hours, you can use up to 4x leverage. During extended market hours, you can use up to 2x leverage.
security.MarginModel = new PatternDayTradingMarginModel();
security.MarginModel = PatternDayTradingMarginModel()
In live trading, if you have less than $25,000 in your account and you try to open a 4th day trade for an Equity asset in a 5 business day period, you'll get the following error message:
Settlements
If you trade with a margin account, trades settle immediately. If you trade with a cash account, Equity trades settle 3 days after the transaction date (T+3) and Option trades settle on the business day following the transaction (T+1).
security.SettlementModel = new ImmediateSettlementModel();
security.SettlementModel = ImmediateSettlementModel()
Security and Stability
Note the following security and stability aspects of our IB integration.
Account Credentials
When you deploy live algorithms with IB, we don't save your brokerage account credentials.
API Outages
We call the IB API to place live trades. Sometimes the API may be down. Check the IB status page to see if the API is currently working.
Connections
By default, IB only supports one connection at a time to your account. If you interfere with your brokerage account while an algorithm is connected to it, the algorithm may stop executing. If you deploy a live running algorithm with your IB account and want to open Trader Workstation (TWS) with the same IB account, create a second user on your IB account and log in to TWS with the new user credentials. To run more than one algorithm with IB, open an IB subaccount for each additional algorithm.
SMS 2FA
Our IB integration doesn't support Two-Factor Authentication (2FA) via SMS. Use the IB Key Security via IBKR Mobile instead.
System Resets
If your IB account has 2FA enabled, you'll need to re-authenticate once a week. The reset schedule is available on the IB Status page. If you miss the timeout period, your algorithm quits executing.
Deploy Live Algorithms
You must have an available live trading node for each live trading algorithm you deploy.
Follow these steps to deploy a live algorithm:
- Open the project that you want to deploy.
- Click the
Deploy Live icon.
- On the Deploy Live page, click the Brokerage field and then click from the drop-down menu.
- Enter your IB user name, ID, and password.
- Click the Data Provider field and then click one of the data feeds from the drop-down menu.
- If you have subscriptions to IB data feeds and want to use them, click the Data Provider field and then click from the drop-down menu.
- Click the Node field and then click the live trading node that you want to use from the drop-down menu.
- (Optional) Set up notifications.
- Configure the Automatically restart algorithm setting.
- Click .
Your account details are not saved on QuantConnect.
The following table describes the available data feeds:
Data Feed | Description |
---|---|
QuantConnect | Use data collected across all of the exchanges. For more details about this data feed, see Data Feeds. |
IB | Use data sourced directly from IB. For more details about this data feed, see the IB data feed guide. |
QuantConnect + IB | Use a combination of the QuantConnect and IB data feeds. For more details about this option, see Hybrid QuantConnect Data Feed. |
If you use IB data feeds and trade with a paper trading account, you need to share the data feed with your paper trading account. For instructions on sharing data feeds, see Account Types.
By enabling automatic restarts, the algorithm will use best efforts to restart the algorithm if it fails due to a runtime error. This can help improve the algorithm's resilience to temporary outages such as a brokerage API disconnection.
The deployment process can take up to 5 minutes. When the algorithm deploys, the live results page displays. If you know your brokerage positions before you deployed, you can verify they have been loaded properly by checking your equity value in the runtime statistics, your cashbook holdings, and your position holdings.