🚀 AI One-Click Generation of quantconnect Strategy Code

What is the `BrokerageModelSecurityInitializer` and How to Use It in QuantConnect?

quantconnect | Published on: 2025/12/5
The following content is generated by EasyQuant .

Problem Description

How do I make sure the securities in my backtest behave exactly like they would on my live brokerage account?

Solution

To ensure your backtest behaves exactly like your live brokerage account, you must configure the Brokerage Model and the Security Initializer within the initialize method of your algorithm.

Key Concepts

  1. set_brokerage_model: This method configures the transaction fees, slippage models, buying power (margin) models, and settlement rules to match a specific brokerage (e.g., Interactive Brokers, Binance, Bitfinex).
  2. set_security_initializer: This ensures that every time a new security is added to your algorithm (manually or via Universe selection), it is immediately configured with the correct models from your brokerage and "seeded" with the last known price. This prevents issues where a security has $0 price or incorrect margin requirements upon initialization.

Implementation

Here is a complete example demonstrating how to configure an algorithm to mimic an Interactive Brokers Margin account. I have also included a commented-out example for a Bitfinex Cash account to show how it differs for crypto.

#region imports
from AlgorithmImports import *
#endregion

class RealisticBrokerageSimulation(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2023, 1, 1)
        self.set_end_date(2023, 6, 1)
        self.set_cash(100000)

        # ------------------------------------------------------------
        # STEP 1: Select the Brokerage Model
        # ------------------------------------------------------------
        # This sets the FeeModel, SlippageModel, BuyingPowerModel, 
        # and SettlementModel to match Interactive Brokers.
        # Options include: INTERACTIVE_BROKERS_BROKERAGE, BINANCE, OANDA, BITFINEX, etc.
        self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE, AccountType.MARGIN)

        # ALTERNATIVE: For a Crypto Cash Account (e.g., Bitfinex)
        # self.set_brokerage_model(BrokerageName.BITFINEX, AccountType.CASH)
        # self.set_account_currency("USDT") # Optional: Set base currency if not USD

        # ------------------------------------------------------------
        # STEP 2: Configure Security Initializer
        # ------------------------------------------------------------
        # This is critical. It ensures that when a security is added:
        # 1. It inherits the models from the BrokerageModel defined above.
        # 2. It is "seeded" with the last known price immediately (no waiting for next tick).
        self.set_security_initializer(
            BrokerageModelSecurityInitializer(
                self.brokerage_model, 
                FuncSecuritySeeder(self.get_last_known_prices)
            )
        )

        # ------------------------------------------------------------
        # STEP 3: Add Securities
        # ------------------------------------------------------------
        # Because of the setup above, 'spy' will automatically use IB fees 
        # and margin requirements.
        self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol

    def on_data(self, data: Slice):
        if not self.portfolio.invested:
            # This order will be processed using the IB Fee Model and Slippage Model
            self.set_holdings(self.spy, 1.0)
            
            # Debugging: Verify the models are correct
            security = self.securities[self.spy]
            self.debug(f"Fee Model: {type(security.fee_model).__name__}")
            self.debug(f"Buying Power Model: {type(security.buying_power_model).__name__}")

Explanation of the Code

  1. self.set_brokerage_model(...):

    • By setting this to BrokerageName.INTERACTIVE_BROKERS_BROKERAGE, LEAN automatically applies the specific commission structure (e.g., $0.005 per share with min/max) and margin requirements (Reg T or Portfolio Margin) associated with IB.
    • If you choose a crypto exchange like BrokerageName.BINANCE, it will switch to percentage-based fees and crypto-specific settlement rules.
  2. BrokerageModelSecurityInitializer:

    • Standard AddEquity calls might default to generic models if not explicitly connected to the brokerage model. This initializer forces every new security to look at self.brokerage_model and adopt its specific traits (leverage, fees, etc.).
    • FuncSecuritySeeder(self.get_last_known_prices): This looks up the most recent historical price for the asset and sets it immediately. Without this, your algorithm might think the price is $0 until the first data point arrives, which can cause SetHoldings to fail or margin calculations to be wrong in the first moments of trading.

Q&A

Q: What happens if I don't set a brokerage model?
A: LEAN defaults to the DefaultBrokerageModel. This usually implies $0 fees, no slippage, and a standard leverage (often 1x or 2x depending on asset type). This is useful for theoretical research but will produce unrealistic results compared to live trading.

Q: Can I mix brokerage models?
A: No, an algorithm represents a single account at a single brokerage. However, you can manually override specific models for specific securities (e.g., setting a custom Fee Model for one specific Symbol) if your setup is unique, though set_brokerage_model is preferred for accuracy.

Q: Does set_brokerage_model affect the data feed?
A: No, it affects the simulation of the trade (fees, margin, fills). It does not change the historical data source. However, some brokerage models (like Bitfinex) require specific market data (e.g., Crypto) to function correctly.

Q: How do I simulate a cash account instead of a margin account?
A: Change the second parameter in set_brokerage_model. Use AccountType.CASH. This will prevent the algorithm from borrowing money (leverage) and will enforce cash settlement rules (e.g., waiting for funds to settle before buying again).