Brokerages

Interactive Brokers

Introduction

QuantConnect enables you to run your algorithms in live mode with real-time market data.

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, CFDs, 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.

To view the implementation of the IB brokerage integration, see the Lean.Brokerages.InteractiveBrokers repository.

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. To set the account type in an algorithm, see the IB brokerage model documentation.

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. If your account code starts with F, FA, or I, then you have an FA account. 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 Paper Trading Account page in the IB documentation to set up your paper trading account.

If you want to use IB market data 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.

The IB paper trading environment simulates most aspects of a production Trader Workstation account, but you may encounter some differences due to its construction as a simulator with no execution or clearing abilities.

Insured Bank Deposit Sweep Program

LEAN doesn't support IB accounts in the Insured Bank Deposit Sweep Program because when LEAN reads your account balances, it includes cash that's in the FDIC Sweep Account Cash, which isn't tradable. For example, if your account has $150K USD of cash, only $100K may be available to trade if $50K is in FDIC Sweep Account Cash. To opt-out the program, see Insured Bank Deposit Sweep Program.

Dividend Election

Dividend election is an option where you can elect how you wish to receive your dividends for stocks and mutual funds. You must turn automatic dividend election off to receive them in cash. Reinvestment can change the quantity of shares you own to fractional shares, and LEAN doesn't support fractional trading. For example, if your account has 1270.8604 shares of TLT after dividend reinvestment, you cannot liquidate the position.

FIX Integration

FIX (Financial Information eXchange) integration lets existing Interactive Brokers (IB) clients route orders from QuantConnect through their IB account. If you already hold an IB account, you can subscribe to QuantConnect directly from the IB Client Portal to enable FIX order routing.

FIX integration is not supported for IB simulated accounts, which start with the letters 'DU'. You can trade multiple IB subaccounts, but all subaccounts must be linked to the same QuantConnect account.

The QC-IBKR fix integration remains up forever, and prevents the need for weekly re-logins associated with the IB-Gateway technology. It also routes the trades through a dedicated VPN resulting in better stability and fills. The FIX connectivity is also lightweight, resulting in lower memory usage.

Before you start, make sure you have an active IB account and access to the IB Client Portal.

The IB user you log in with needs Market Data access to manage research subscriptions. If the Research Subscriptions section is missing or empty, open the user's access rights in the IB Client Portal and then enable Market Data. IB applies this permission immediately. Subscriber Status access alone is not enough.

Each IB account has its own IBKR QC UID, but a master user can only save one UID for all of the accounts it manages. To register a different UID for each subaccount, log in as the subaccount user and then follow these steps for that account.

Step 5 asks for the IBKR QC UID that links your IB account to QuantConnect. QuantConnect generates this value, so get it first. To get it, open the live deployment wizard, authenticate with your IB user name, and then select the account you want to trade.

Follow these steps to add FIX support to your IB account:

  1. Log in to the IB Client Portal, open Settings, click Research Subscriptions, open News & Research Subscriptions, and then click Manage Subscriptions.
  2. Select QuantConnect from the list of subscriptions to create the FIX session, and then click Continue.
  3. On the Review Your Research Subscriptions screen, review the market-data agreements and disclosures, and then confirm to proceed.
  4. On the Service Account Configuration screen, click the Configure gear next to QuantConnect.
  5. In the Service Account Configuration for QuantConnect dialog, select the IB account(s) you want to link, enter your IBKR QC UID in the QuantConnect UID field, and then click Save.
  6. The IBKR QC UID you enter is the default subscriber for the QuantConnect service. You can select multiple accounts here.

    To get your IBKR QC UID, see Deploy Live Algorithms FIX.

  7. Back on the Service Account Configuration screen, click Continue.
  8. Acknowledge and confirm the OMS Riders and Addendum.
  9. After you confirm, your subscription is complete and the selected information is added to the FIX connection for order validation.

    You only need to complete these steps once for each IBKR QC UID, so repeat them when you trade an account you haven't registered yet. Wait about 5 minutes for IB to apply the change before you deploy a live algorithm.

    After you subscribe, the Service Account Configuration screen no longer appears in your subscriptions. To edit an IBKR QC UID you already saved, click Manage Subscriptions, click Continue twice without changing any subscription, and then click the Configure gear next to QuantConnect.

Asset Classes

Our Interactive Brokers integration supports the following asset classes:

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. You can trade the CFD equivalent. 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.

Data Providers

We recommend the QuantConnect data provider, which is free and supplies US Equities, US Equity Options, US Index Options, Futures, Forex, and CFD data during live trading. It doesn't supply Index or Future Options data, so combine it with the IB data provider to trade Indices, Index Options, or Future Options. Index Options need data for the underlying index, such as SPX, VIX, and NDX. To receive that data, you might need to purchase a market data subscription from IB. For more information about live data providers, see Datasets.

If you route orders through FIX, use the QuantConnect data provider on its own. The IB data provider streams data through the IB API instead of your FIX session, so it brings back the weekly logins that FIX removes. To trade Indices, Index Options, or Future Options, you need the IB data provider, so you have to accept those logins.

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 our IB integration supports: supports. For specific details about each order type, refer to the IB documentation.

Order TypeIB Documentation Page
MarketMarket Orders
LimitLimit Orders
Limit if touchedLimit if Touched Orders
Stop marketStop Orders
Stop limitStop-Limit Orders
Trailing stopTrailing Stop Orders
Market on openMarket-on-Open (MOO) Orders
Market on closeMarket-on-Close (MOC) Orders
Combo marketSpread Orders
Combo limitSpread Orders
Combo leg limitSpread Orders
Exercise OptionOptions Exercise

The following table describes the available order types for each asset class that IB supports:

Order TypeUS EquityEquity OptionsForexFuturesFutures OptionsIndex OptionsCFD
Marketgreen checkgreen checkgreen checkgreen checkgreen checkgreen checkgreen check
Limitgreen checkgreen checkgreen checkgreen checkgreen checkgreen checkgreen check
Limit if touchedgreen checkgreen checkgreen checkgreen checkgreen checkgreen checkgreen check
Stop marketgreen checkgreen checkgreen checkgreen checkgreen checkgreen checkgreen check
Stopl imitgreen checkgreen checkgreen checkgreen checkgreen checkgreen checkgreen check
Trailing stopgreen checkgreen checkgreen checkgreen checkgreen checkgreen checkgreen check
Market on opengreen checkgreen checkgreen checkgreen checkgreen check
Market on closegreen checkgreen checkgreen check
Combo marketgreen checkgreen checkgreen check
Combo limitgreen checkgreen checkgreen check
Combo leg limitgreen checkgreen checkgreen check
Exercise Optiongreen check
Not supported for cash-settled Options
green check

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 methods for FA accounts.

PropertyData TypeDescriptionDefault Value
TimeInForcetime_in_forceTimeInForceA TimeInForce instruction to apply to the order. The following instructions are supported:
  • DayDAY
  • GoodTilCanceledGOOD_TIL_CANCELED
  • GoodTilDategood_til_date
TimeInForce.GoodTilCanceledTimeInForce.GOOD_TIL_CANCELED
OutsideRegularTradingHoursoutside_regular_trading_hoursboolA flag to signal that the order may be triggered and filled outside of regular trading hours.falseFalse

Updates

We model the IB API by supporting order updates.

Financial Advisor Group Orders

To place FA group orders, see Financial Advisors.

Fractional Trading

The IB API and FIX/CTCI don't support fractional trading.

Handling Splits

If you're using raw data normalization and you have active orders with a limit, stop, or trigger price in the market for a US Equity when a stock split occurs, the following properties of your orders automatically adjust to reflect the stock split:

  • Quantity
  • Limit price
  • Stop price
  • Trigger price

Fill Time

IB has a 400 millisecond fill time for live orders.

Brokerage Liquidations

When IB liquidates part of your position, you receive an order event that contains the Brokerage Liquidation message.

Fees

To view the IB trading fees, see the Commissions page on the IB website. To view how we model their fees, see Fees.

Margin

We model buying power and margin calls to ensure your algorithm stays within the margin requirements.

Slippage

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

To view how we model IB slippage, see Slippage.

Fills

QuantConnect fills market orders immediately and completely in backtests. In IB paper trading and 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.

To view how we model IB order fills, see Fills.

Settlements

If you trade with a margin account, trades settle immediately

To view how we model settlement for IB trades, see Settlement.

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 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.

If you can't log in to TWS with your credentials, contact IB. If you can log in to TWS but can't log in to the deployment wizard, contact us and provide the algorithm ID and deployment ID.

SMS 2FA

Our IB integration doesn't support Two-Factor Authentication (2FA) via SMS, the Online Security Code Card, or third-party authenticator apps (e.g., Microsoft Authenticator and Google Authenticator). Use the IB Key Security via IBKR Mobile instead.

IP Restrictions

If you have IP restrictions enabled on your IB account, ensure to whitelist our IP address 207.182.16.137.

System Resets

You'll receive a notification on your IB Key device every Sunday to re-authenticate the connection between IB and your live algorithm. When you deploy your algorithm, you can select a time on Sunday to receive the notification. Ensure your IB Key device has sufficient battery for the time you expect to receive the notification.

If you don't re-authenticate before the timeout period, you will receive an email from QuantConnect with two options: Connect and Stop. Click Connect to restart the authentication process and receive a notification on your IB Key device. Click Stop to stop the deployment. If you don't take action, your algorithm quits executing before the market opens for the assets in your portfolio. For example, 9:30 AM EST if your algorithm trades US Equities.

If you don't receive a notification, see I am not receiving IBKR Mobile notifications on the IB website.

Deposits and Withdrawals

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:

// Demonstrate IB brokerage functionality with an EMA crossover strategy on SPY.
public class InteractiveBrokersDemoAlgorithm : QCAlgorithm
{
    private ExponentialMovingAverage _fast;
    private ExponentialMovingAverage _slow;

    public override void Initialize()
    {
        SetStartDate(2024, 9, 1);
        SetEndDate(2024, 12, 31);
        SetCash(100000);
        SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin);
        var symbol = AddEquity("SPY", Resolution.Daily).Symbol;
        _fast = EMA(symbol, 10, Resolution.Daily);
        _slow = EMA(symbol, 50, Resolution.Daily);
    }

    public override void OnData(Slice slice)
    {
        if (!_slow.IsReady) return;
        if (_fast > _slow && !Portfolio.Invested)
            SetHoldings("SPY", 1);
        else if (_fast < _slow && Portfolio.Invested)
            Liquidate();
    }
}
# Demonstrate IB brokerage functionality with an EMA crossover strategy on SPY.
class InteractiveBrokersDemoAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(100000)
        self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE, AccountType.MARGIN)
        symbol = self.add_equity("SPY", Resolution.DAILY).symbol
        self._fast = self.ema(symbol, 10, Resolution.DAILY)
        self._slow = self.ema(symbol, 50, Resolution.DAILY)

    def on_data(self, slice: Slice) -> None:
        if not self._slow.is_ready:
            return
        if self._fast.current.value > self._slow.current.value and not self.portfolio.invested:
            self.set_holdings("SPY", 1)
        elif self._fast.current.value < self._slow.current.value and self.portfolio.invested:
            self.liquidate()

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 you want to deploy.
  2. Click the Lightning icon 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. In the Weekly Restart UTC field, enter the Coordinated Universal Time (UTC) time of when you want to receive notifications on Sundays to re-authenticate your account connection.
  7. For example, 4 PM UTC is equivalent to 11 AM Eastern Standard Time, 12 PM Eastern Daylight Time, 8 AM Pacific Standard Time, and 9 AM Pacific Daylight Time. To convert from UTC to a different time zone, see the UTC Time Zone Converter on the UTC Time website.

    If your IB account has 2FA enabled, you receive a notification on your IB Key device every Sunday to re-authenticate the connection between IB and your live algorithm. If you don't re-authenticate before the timeout period, your algorithm quits executing.

  8. In the Region section, click the region where you want to run the algorithm.
  9. Click the Node field and then click the live trading node that you want to use from the drop-down menu.
  10. (Optional) In the Data Provider section, click Show and change the data provider or add additional providers.
  11. In most cases, we suggest using both the QC and IB data providers.

    If you use IB data provider and trade with a paper trading account, you need to share the market data subscription with your paper trading account. For instructions on sharing market data subscription, see Account Types.

  12. (Optional) Set up notifications.
  13. Configure the Automatically restart algorithm setting.
  14. 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.

  15. Click Deploy.
  16. If your IB account has 2FA enabled, tap the notification on your IB Key device and then enter your pin.

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.

Deploy Live Algorithms FIX

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 you want to deploy.
  2. Click the Lightning icon Deploy Live icon.
  3. On the Deploy Live page, click the Brokerage field and then click Interactive Brokers from the drop-down menu.
  4. In the Interactive Brokers (FIX) Authentication section, follow these steps:
    1. Click the Account field and then click your IB user name from the drop-down menu.
    2. To use an IB user name you haven't linked yet, click + Add Account and then enter it in the IBKR User Name field.

    3. Click Authenticate and then log in to IB.
    4. When you succeed, the Authorization row shows Authorization Complete and the wizard displays the Account ID and IBKR QC UID fields.

    5. Click the Account ID field and then click the IB account you want to trade from the drop-down menu.
    6. Copy the value in the IBKR QC UID field and then add it to your IB account.
    7. QuantConnect generates the IBKR QC UID from the account you select, so it stays empty until you select an Account ID. Your IB account only accepts orders from QuantConnect after you register this value, so add it before you continue.

      To register it, follow the steps in FIX Integration and then return to this page. You only need to register each IBKR QC UID once, so repeat those steps when you trade an account you haven't registered yet. After you save it, wait about 5 minutes for IB to apply the change before you deploy.

  5. In the Region section, click the region where you want to run the algorithm.
  6. Click the Node field and then click the live trading node that you want to use from the drop-down menu.
  7. (Optional) In the Data Provider section, click Show and change the data provider or add additional providers.
  8. In most cases, we suggest using both the QC and IB data providers.

    If you use IB data provider and trade with a paper trading account, you need to share the market data subscription with your paper trading account. For instructions on sharing market data subscription, see Account Types.

  9. (Optional) Set up notifications.
  10. Configure the Automatically restart algorithm setting.
  11. 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.

  12. Click Deploy.
  13. If your IB account has 2FA enabled, tap the notification on your IB Key device and then enter your pin.

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.

Troubleshooting

The following table describes errors and warnings you may see when deploying to IB:

Error Message(s)Possible Cause and Fix
Login failed.
The credentials you provided are incorrect. Typically, the password contains leading and/or trailing white spaces. Copy the password to a text editor to ensure the password is correct. If you can't log in to Trader Workstation (TWS) with your credentials, contact IB. If you can log in to TWS but can't log in to the deployment wizard, contact us and provide the algorithm Id and deployment Id.
Login to the IB Gateway failed because
a user account-tasks is required.
Download IB Gateway, run it, and follow the instructions provided.
An existing session was detected and will not be automatically disconnected.

Historical Market Data Service error message: Trading TWS session is connected from a different IP address.
IB still recognizes your previous live deployment as being partially connected. It can take a minute to fully disconnect. For more information, see Security and Stability > Connections.
The two factor authentication request timed out.

A security dialog was detected for Code Card Authentication.

Unknown message window detected: Challenge: 123 456
You haven't replied to the two factor authentication requests. The code card authentication ("Challenge") is triggered when you don't reply to the IB mobile 2FA requests. Ensure your IB Key device has sufficient battery for the time you expect to receive the notification. If you don't receive a notification, see I am not receiving IBKR Mobile notifications on the IB website.
API support is not available for accounts that support free trading.
Upgrade your plan from IBKR Lite to IBKR Pro.
No security definition has been found for the request.
Your algorithm added an invalid or unsupported security. For example, a delisted stock, an expired contract, inexistent contract (invalid expiration date or strike price), or a warrant (unsupported). If the security should be valid and supported, open a support ticket and attach the live deployment Id. The algorithm will continue running, but it won't trade the security. If you don't want to deploy to an account with an invalid or unsupported security, set Settings.IgnoreUnknownAssetsself.settings.ignore_unknown_assets is falseFalse.
Requested market data is not subscribed.

Historical Market Data Service error message: No market data permissions for ...
Your algorithm uses the Interactive Brokers Data Provider, but you don't have a subscription to it. Subscribe to the data bundle you need, contact IB, or re-deploy the algorithm with a different data provider. Try the QuantConnect or the hybrid QuantConnect + Interactive Brokers data providers on QuantConnect Cloud or try a third-party provider.
Timeout waiting for brokerage response for brokerage order id 37 lean id 31
IB didn't respond to an order request. Stop and re-deploy the algorithm. On the next deployment, LEAN retrieves this order or the positions it opened or closed.
No market data during competing live session.
You have logged in to IB from another location while your live deployment is running. This disconnects your live deployment from IB datafeed. If you close the other session, your algorithm will restore the data connection automatically, and will not stop with an error. See the "An existing session was detected and will not be automatically disconnected" case.

To view the description of less common errors, see Error Codes in the TWS API Documentation. If you need further support, open a new support ticker and add the live deployment with the error.

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: