Reality Modeling

Brokerages

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 fee models, supported order types, and other security level models are appropriately set in your algorithm.

Set Models

To set a brokerage model, in the Initialize method, call the SetBrokerageModel 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.

SetBrokerageModel(BrokerageName.OandaBrokerage); // Defaults to margin account
SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Margin); // Overrides the default account type
self.SetBrokerageModel(BrokerageName.OandaBrokerage) # Defaults to margin account
self.SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Margin) # Overrides the default account type

In live trading, LEAN doesn't ignore your SetBrokerageModel method calls. LEAN uses some of the brokerage model rules to catch invalid orders before they reach your real brokerage.

Supported Models

The following brokerage models are available. For more information about each brokerage model, see the integration documentation for the brokerage.

Default Behavior

The default brokerage model is the DefaultBrokerageModel, but LEAN has many other brokerage models you can use in your algorithms. To check the security level models the DefaultBrokerageModel assigns to securities in your algorithm, see the following pages:

To check the margin call model that the DefaultBrokerageModel uses, see Margin Calls.

Modeled Properties

Brokerage models model that following properties:

  • Transaction fees
  • Supported asset classes
  • Account types
  • Support for extended market hours
  • Leverage for assets
  • Trade settlement rules
  • Order properties and updates

To view the properties of each brokerage model, see the integration documentation for the brokerage.

Model Structure

Brokerage models should extend the DefaultBrokerageModel class. Extensions of the DefaultBrokerageModel class should implement the following methods:

class MyBrokerageModel : DefaultBrokerageModel
{
    public static new readonly IReadOnlyDictionary<securitytype, string=""> DefaultMarketMap;

    public override decimal RequiredFreeBuyingPowerPercent { get; }

    public override IReadOnlyDictionary<securitytype, string=""> DefaultMarkets => DefaultMarketMap;

    public MyBrokerageModel(AccountType accountType = AccountType.Margin)
        : base(accountType)
    {
        ShortableProvider = new NullShortableProvider();
    }

    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 IShortableProvider GetShortableProvider()
    {
        return ShortableProvider;
    }
}
class MyBrokerageModel(DefaultBrokerageModel):
    DefaultMarkets = {}
    RequiredFreeBuyingPowerPercent = 0

    def __init__(self, accountType = AccountType.Margin: AccountType):
        self.AccountType = accountType
        self.ShortableProvider = NullShortableProvider()
    
    def CanSubmitOrder(self, security: Security, order: Order,
         message: BrokerageMessageEvent) -> bool:
        return super().CanSubmitOrder(security, order, message)

    def CanUpdateOrder(self, security: Security, order: Order,
         request: UpdateOrderRequest, message: BrokerageMessageEvent) -> bool:
        return super().CanUpdateOrder(security, order, message)

    def CanExecuteOrder(self, security: Security, order: Order) -> bool:
        return super().CanExecuteOrder(security, order)

    def ApplySplit(self, tickets: list[OrderTicket], split: Split) -> None:
        super().ApplySplit(tickets, split)

    def GetLeverage(self, security: Security) -> float:
        return super().GetLeverage(security)

    def GetBenchmark(self, securities: SecurityManager) -> IBenchmark:
        return super().GetBenchmark(securities)

    def GetFillModel(self, security: Security) -> IFillModel:
        return super().GetFillModel(security)

    def GetFeeModel(self, security: Security) -> IFeeModel:
        return super().GetFeeModel(security)

    def GetSlippageModel(self, security: Security) -> ISlippageModel:
        return super().GetSlippageModel(security)

    def GetSettlementModel(self, security: Security) -> ISettlementModel:
        return super().GetSettlementModel(security)

    def GetBuyingPowerModel(self, security: Security) -> IBuyingPowerModel:
        return super().GetBuyingPowerModel(security)

    def GetShortableProvider(self) -> IShortableProvider:
        return self.ShortableProvider

Custom brokerage models give you enormous control over your algorithm behavior and allows you to model virtually any brokerage in the world.

Monitor the Brokerage Connection

We notify your algorithm when your brokerage connection disconnects and reconnects.

Lost Connections

If the brokerage connection breaks, we notify your algorithm through the OnBrokerageDisconnect event handler.

public override void OnBrokerageDisconnect() 
{
    Debug("Brokerage connection lost");
}
def OnBrokerageDisconnect(self) -> None:
    self.Debug("Brokerage connection lost")

Restored Connections

When the brokerage connection restores after it disconnects, we notify your algorithm through the OnBrokerageReconnect event handler.

public override void OnBrokerageReconnect() 
{
    Debug("Brokerage connection restored");
}
def OnBrokerageReconnect(self) -> None:
    self.Debug("Brokerage connection restored")

Monitor Brokerage Messages

When your brokerage sends you a message, we notify your algorithm through the OnBrokerageMessage event handler.

public override void OnBrokerageMessage(BrokerageMessageEvent messageEvent) 
{
    Debug(f"Brokerage message received: {messageEvent.Message}");
}
def OnBrokerageMessage(self, message_event: BrokerageMessageEvent) -> None:
    self.Debug(f"Brokerage message received: {messageEvent.Message}")

BrokerageMessageEvent objects have the following attributes:

To handle brokerage messages outside of your algorithm class, create and set a BrokerageMessageHandler. For a full example, see the CustomBrokerageMessageHandlerAlgorithm.

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: