Brokerages
Key Concepts
Introduction
Brokerages provide you with a connection to the market so you can fill trades. Brokerage models simulate the live behavior of a real brokerage. To avoid sending invalid orders for execution in live trading, the brokerage model validates your orders before LEAN sends them to the real brokerage. Brokerage models combine together all of the models relevant for a brokerage. If you set the appropriate brokerage model, the supported order types, default markets, and some of the security-level models are appropriately set in your algorithm.
Set Models
To set a brokerage model, in the Initialize
initialize
method, call the SetBrokerageModel
set_brokerage_model
method with a BrokerageName
and an AccountType
. If you set a brokerage model, it overrides any security level models you manually set in your algorithm.
public override void Initialize() { // Set the brokerage model to backtest with the most realistic scenario to handle the order validity, margin rate and transaction fee SetBrokerageModel(BrokerageName.OandaBrokerage); // Defaults to margin account SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Margin); // Overrides the default account type, which is AccountType.Cash }
def initialize(self) -> None: # Set the brokerage model to backtest with the most realistic scenario to handle the order validity, margin rate and transaction fee self.set_brokerage_model(BrokerageName.OANDA_BROKERAGE) # Defaults to margin account self.set_brokerage_model(BrokerageName.BITFINEX, AccountType.MARGIN) # Overrides the default account type, which is AccountType.Cash
In live trading, LEAN doesn't ignore your SetBrokerageModel
set_brokerage_model
method calls. LEAN uses some of the brokerage model rules to catch invalid orders before they reach your real brokerage.
To view all the pre-built brokerage models, see Supported Models.
Default Behavior
The default brokerage model is the DefaultBrokerageModel
, but LEAN has many other brokerage models you can use in your algorithms. For more information about the DefaultBrokerageModel
, see QuantConnect Paper Trading.
Model Structure
Brokerage models should extend the DefaultBrokerageModel
class. Extensions of the DefaultBrokerageModel
class should implement the following methods:
public class CustomBrokerageModelExampleAlgorithm : QCAlgorithm { public override void Initialize() { // In the Initialize method, set the custom brokerage model SetBrokerageModel(new MyBrokerageModel()); } } // Define the custom brokerage model outside of the algorithm class MyBrokerageModel : DefaultBrokerageModel { public override decimal RequiredFreeBuyingPowerPercent { get; } public new IReadOnlyDictionary<SecurityType, string> DefaultMarkets = new Dictionary<SecurityType, string> { {SecurityType.Equity, Market.USA} }.ToReadOnlyDictionary(); public MyBrokerageModel(AccountType accountType = AccountType.Margin) : base(accountType) { } public override bool CanSubmitOrder(Security security, Order order, out BrokerageMessageEvent message) { return base.CanSubmitOrder(security, order, out message); } public override bool CanUpdateOrder(Security security, Order order, UpdateOrderRequest request, out BrokerageMessageEvent message) { return base.CanUpdateOrder(security, order, request, out message); } public override bool CanExecuteOrder(Security security, Order order) { return base.CanExecuteOrder(security, order); } public override void ApplySplit(List<OrderTicket> tickets, Split split) { base.ApplySplit(tickets, split); } public override decimal GetLeverage(Security security) { return base.GetLeverage(security); } public override IBenchmark GetBenchmark(SecurityManager securities) { return base.GetBenchmark(securities); } public override IFillModel GetFillModel(Security security) { return base.GetFillModel(security); } public override IFeeModel GetFeeModel(Security security) { return base.GetFeeModel(security); } public override ISlippageModel GetSlippageModel(Security security) { return base.GetSlippageModel(security); } public override ISettlementModel GetSettlementModel(Security security) { return base.GetSettlementModel(security); } public override IBuyingPowerModel GetBuyingPowerModel(Security security) { return base.GetBuyingPowerModel(security); } public override IMarginInterestRateModel GetMarginInterestRateModel(Security security) { return base.GetMarginInterestRateModel(security); } public override IShortableProvider GetShortableProvider(Security security) { return base.GetShortableProvider(security); } }
class CustomBrokerageModelExampleAlgorithm(QCAlgorithm): def initialize(self) -> None: # In the Initialize method, set the custom brokerage model self.set_brokerage_model(MyBrokerageModel()) # Define the custom brokerage model outside of the algorithm class MyBrokerageModel(DefaultBrokerageModel): default_markets = {SecurityType.EQUITY: Market.USA} required_free_buying_power_percent = 0 def __init__(self, accountType: account_type = account_type.margin): self.account_type = accountType def can_submit_order(self, security: Security, order: Order, message: BrokerageMessageEvent) -> bool: return super().can_submit_order(security, order, message) def can_update_order(self, security: Security, order: Order, request: UpdateOrderRequest, message: BrokerageMessageEvent) -> bool: return super().can_update_order(security, order, request, message) def can_execute_order(self, security: Security, order: Order) -> bool: return super().can_execute_order(security, order) def apply_split(self, tickets: List[OrderTicket], split: Split) -> None: super().apply_split(tickets, split) def get_leverage(self, security: Security) -> float: return super().get_leverage(security) def get_benchmark(self, securities: SecurityManager) -> IBenchmark: return super().get_benchmark(securities) def get_fill_model(self, security: Security) -> IFillModel: return super().get_fill_model(security) def get_fee_model(self, security: Security) -> IFeeModel: return super().get_fee_model(security) def get_slippage_model(self, security: Security) -> ISlippageModel: return super().get_slippage_model(security) def get_settlement_model(self, security: Security) -> ISettlementModel: return super().get_settlement_model(security) def get_buying_power_model(self, security: Security) -> IBuyingPowerModel: return super().get_buying_power_model(security) def get_margin_interest_rate_model(self, security: Security) -> IMarginInterestRateModel: return super().get_margin_interest_rate_model(security) def get_shortable_provider(self, security: Security) -> IShortableProvider: return super().get_shortable_provider(security)
For a full example algorithm, see this backtestthis backtest.
Custom brokerage models give you enormous control over your algorithm behavior and allow you to model virtually any brokerage in the world.