🚀 AI One-Click Generation of quantconnect Strategy Code

How to Simulate Brokerage Behavior like Bybit or OANDA in QuantConnect

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

Problem Description

How can I set up my backtest to mimic the conditions of a specific brokerage like Bybit?

Solution

To set up a backtest that mimics the conditions of a specific brokerage like Bybit in QuantConnect, you need to configure the Brokerage Model, Account Type, Account Currency, and ensure you are subscribing to data from that specific Market.

Here is a complete, runnable Python algorithm demonstrating how to configure a Bybit environment.

Bybit Brokerage Simulation Code

# region imports
from AlgorithmImports import *
# endregion

class BybitBrokerageExample(QCAlgorithm):

    def initialize(self):
        # 1. Set the date range and initial capital
        self.set_start_date(2023, 1, 1)
        self.set_end_date(2023, 12, 31)
        # Set strategy cash (amount of the account currency)
        self.set_cash(10000) 

        # 2. Set the Brokerage Model
        # This configures transaction fees, slippage models, and buying power 
        # models specific to Bybit.
        # Options: AccountType.CASH (Spot) or AccountType.MARGIN (Futures/Derivatives)
        self.set_brokerage_model(BrokerageName.BYBIT, AccountType.CASH)

        # 3. Set the Account Currency
        # Bybit accounts are often funded in USDT or BTC. 
        # Setting this ensures your portfolio value and cash are tracked in USDT.
        self.set_account_currency("USDT")

        # 4. Add Securities with the correct Market
        # It is critical to specify market=Market.BYBIT to get the correct price data
        # and ensure orders are routed to the correct simulated exchange.
        self.btc_symbol = self.add_crypto("BTCUSDT", Resolution.MINUTE, market=Market.BYBIT).symbol
        
        # 5. Set Security Initializer (Optional but Recommended)
        # This ensures that when the security is added, it uses the brokerage's 
        # specific models for leverage and pricing immediately.
        self.set_security_initializer(
            BrokerageModelSecurityInitializer(
                self.brokerage_model, 
                FuncSecuritySeeder(self.get_last_known_prices)
            )
        )

    def on_data(self, data: Slice):
        # Simple logic: Buy if we are not invested
        if not self.portfolio.invested:
            # This order will use Bybit's fee structure and slippage model
            self.set_holdings(self.btc_symbol, 1.0)
            self.debug(f"Purchased {self.btc_symbol} on Bybit model")

    def on_end_of_algorithm(self):
        self.debug(f"Final Portfolio Value in USDT: {self.portfolio.total_portfolio_value}")

Key Configuration Steps

  1. set_brokerage_model(BrokerageName.BYBIT, AccountType.CASH):

    • This is the most important line. It tells the LEAN engine to load the specific fee schedules, minimum order sizes, and margin requirements for Bybit.
    • Use AccountType.CASH for Spot trading.
    • Use AccountType.MARGIN if you are trading Perpetual Futures.
  2. set_account_currency("USDT"):

    • Default QuantConnect algorithms assume USD. Since Bybit is a crypto exchange, your "cash" is likely held in stablecoins (USDT/USDC) or coins (BTC). Setting this ensures your self.portfolio.cash reflects the actual settlement currency.
  3. market=Market.BYBIT:

    • When using add_crypto (or add_crypto_future), you must specify the market. If you omit this, LEAN might default to Coinbase or another exchange, which will result in different price data and potentially invalid order logic for the Bybit model.
  4. BrokerageModelSecurityInitializer:

    • This helper class ensures that any security added to your universe automatically inherits the leverage and buying power models defined by the Brokerage Model you set in step 1.

Q&A

Q: What happens if I don't set the Account Currency to USDT for Bybit?
A: If you leave the default (USD) but trade pairs quoted in USDT (like BTCUSDT), LEAN will attempt to perform currency conversions on every tick to calculate your portfolio value in USD. This can introduce "ConversionRate" errors if a conversion pair (e.g., USDTUSD) is not available in the data feed. It is best practice to match your account currency to the settlement currency of the pairs you trade.

Q: Can I trade Futures using the Bybit model?
A: Yes. To trade futures, change the account type to AccountType.MARGIN in the brokerage model settings, and use self.add_crypto_future("BTCUSDT", ...) instead of add_crypto.

Q: Does set_brokerage_model affect live trading?
A: In live trading, the brokerage model is used to validate orders before they are sent to the actual exchange API. It ensures that your algorithm doesn't attempt to send orders that violate the exchange's rules (e.g., invalid tick size or insufficient margin), preventing API rejections.

Q: How do I simulate Bybit fees accurately?
A: BrokerageName.BYBIT automatically loads the standard fee schedule for Bybit. If you have a specific VIP tier with lower fees, you can override the fee model manually using security.set_fee_model(MyCustomFeeModel()) after adding the security.