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:

  1. Log in to the IB Client Portal.
  2. In the top-right corner, click the person icon and then click Settings.
  3. In the Account Configuration section, click Paper Trading Account.
  4. Click Yes.
  5. Click Save.

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"].QuantityPortfolio["SPY"].Quantity is zero.

The following table shows the supported allocation methods for FA group orders:

FaMethodDescription
"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 ClassDataset Listing
EquitiesUS Equities
OptionsUS Equity Options
ForexFOREX Data
FuturesUS Futures
Future OptionsUS Future Options
Index OptionsUS 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 TypeIB Documentation Page
MarketOrderMarket Orders
LimitOrderLimit Orders
StopMarketOrderStop Orders
StopLimitOrderStop-Limit Orders
MarketOnOpenOrderMarket-on-Open (MOO) Orders
MarketOnCloseOrderMarket-on-Close (MOC) Orders
LimitIfTouchedOrderLimit if Touched Orders
ExerciseOptionOptions 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.

PropertyDescription
TimeInForceA TimeInForce instruction to apply to the order. The following instructions are supported:
  • Day
  • GoodTilCanceled
  • GoodTilDate
OutsideRegularTradingHoursA 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.050.25
<= 10,0000.05 <= premium < 0.100.50
<= 10,000>= 0.100.70
10,000 < volume <= 50,000< 0.05
0.25
10,000 < volume <= 50,000>= 0.05
0.50
50,000 < volume <= 100,000Any0.25
> 100,000Any0.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:

Message: 201 - Order rejected - reason:Potential Pattern Day Trade. A potential pattern day trader error message means that an account has less than the SEC required USD 25,000 minimum Net Liquidation Value AND the number of available day trades (3) has already been used within the last 5 days.. You need to maintain an account balance of at least USD 25,000 if you wish to day trade. If you do not, we restrict you to no more than 3 day trades within any 5 business day period as a 4th trade would create a violation.. This order rejection serves to prevent you from opening a 4th trade and possibly closing it today. Please refer to our Knowledge Base for further details.

Slippage

Orders through IB do not experience slippage in backtests. In paper trading and live trading, your orders may experience slippage.

Fills

We fill market orders immediately and completely in backtests. In live trading, if the quantity of your market orders exceeds the quantity available at the top of the order book, your orders are filled according to what is available in the order book.

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.

Deposits and Withdraws

You can deposit and withdraw cash from your brokerage account while you run an algorithm that's connected to the account. We sync the algorithm's cash holdings with the cash holdings in your brokerage account every day at 7:45 AM Eastern Time (ET).

Demo Algorithm

The following algorithm demonstrates the functionality of the IB brokerage:

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:

  1. Open the project that you want to deploy.
  2. Click the Deploy Live icon.
  3. On the Deploy Live page, click the Brokerage field and then click Interactive Brokers from the drop-down menu.
  4. Enter your IB user name, ID, and password.
  5. Your account details are not saved on QuantConnect.

  6. Click the Data Provider field and then click one of the data feeds from the drop-down menu.
  7. The following table describes the available data feeds:

    Data FeedDescription
    QuantConnectUse data collected across all of the exchanges. For more details about this data feed, see Data Feeds.
    IBUse data sourced directly from IB. For more details about this data feed, see the IB data feed guide.
    QuantConnect + IBUse a combination of the QuantConnect and IB data feeds. For more details about this option, see Hybrid QuantConnect Data Feed.
  8. If you have subscriptions to IB data feeds and want to use them, click the Data Provider field and then click Interactive Brokers from the drop-down menu.
  9. 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.

  10. Click the Node field and then click the live trading node that you want to use from the drop-down menu.
  11. (Optional) Set up notifications.
  12. Configure the Automatically restart algorithm setting.
  13. 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.

  14. Click Deploy.

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.

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: