Reality Modeling

Brokerage Message Handler


When your brokerage sends a message, you receive this information in the algorithm and can take any actions. When you place an order through your brokerage platform instead of placing it through LEAN, you can decide whether the transaction handler should process the order. By default, the transaction handler only process orders that you place through LEAN. Custom brokerage message handlers enable you to instruct the transaction handler to process orders that you create directly through your brokerage's platform.

Set Models

To set a brokerage message handler, in the Initializeinitialize method, call the SetBrokerageMessageHandlerset_brokerage_message_handler method.

SetBrokerageMessageHandler(new MyBrokerageMessageHandler(this));

Default Behavior

The default brokerage message handler is the DefaultBrokerageMessageHandler. The following table describes how the DefaultBrokerageMessageHandler processes brokerage messages:

Brokerage Message TypeAction
BrokerageMessageType.InformationINFORMATIONSends a debug message for the algorithm.
BrokerageMessageType.WarningWARNINGSends an error message for the algorithm.
BrokerageMessageType.ErrorERRORSets the algorithm runtime error and stops it.
BrokerageMessageType.DisconnectDISCONNECTStops the algorithm after 15 minutes if the market is open. Otherwise, it stops five minutes after market open.
BrokerageMessageType.ReconnectRECONNECTCancels the disconnection process.

The default brokerage message handler rejects orders you create through the brokerage. An example of this is when you place an order using the brokerage website or a third-party software.

The following table describes the arguments the model accepts:

ArgumentData TypeDescriptionDefault Value
algorithmalgorithmIAlgorithmThe running algorithm.
initialDelayinitial_delayTimeSpan?timedelta/NoneTypeThe amount of time LEAN will wait after a brokerage disconnection message for a reconnection message. If the reconnection message doesn't arrive before the time limit, LEAN stops running. If you don't provide a value, it uses TimeSpan.FromMinutes(15)timedelta(minutes=15).nullNone
openThresholdopen_thresholdTimeSpan?timedelta/NoneTypeDefines how long before market open to re-check for brokerage reconnect message. If you don't provide a value, it uses TimeSpan.FromMinutes(5)timedelta(minutes=5).nullNone

To view the implementation of this model, see the LEAN GitHub repository.

Model Structure

Brokerage message handlers extend the IBrokerageMessageHandler interface. Extensions of the IBrokerageMessageHandler interface must define the HandleMessagehandle_message and HandleOrderhandle_order methods.

The HandleMessagehandle_message method processes the brokerage message event. It triggers any actions in the algorithm or notifications system required.

The HandleOrderhandle_order method defines whether the transaction handler should process a new order you placed directly through the brokerage's website or third-party software.

// In the Initialize method, set the brokerage message handler
SetBrokerageMessageHandler(new MyBrokerageMessageHandler(this));

// Define the custom brokerage message handler
public class MyBrokerageMessageHandler : IBrokerageMessageHandler
    private readonly IAlgorithm _algorithm;
    public MyBrokerageMessageHandler(IAlgorithm algorithm) { _algorithm = algorithm; }

    public void HandleMessage(BrokerageMessageEvent message)
        _algorithm.Debug($"{_algorithm.Time.ToStringInvariant("o")} Event: {message.Message}");

    public bool HandleOrder(NewBrokerageOrderNotificationEventArgs eventArgs)
        return false;
# In the Initialize method, set the brokerage message handler
# Define the custom brokerage message handler
class MyBrokerageMessageHandler(IBrokerageMessageHandler):
    def __init__(self, algorithm):
        self._algorithm = algorithm

    def handle_message(self, message: BrokerageMessageEvent) -> None:
        self._algorithm.debug(f"{self._algorithm.time} Event: {message.message}")

    def handle_order(self, event_args: NewBrokerageOrderNotificationEventArgs) -> bool:
        return False

The BrokerageMessageEvent class has the following properties:

The NewBrokerageOrderNotificationEventArgs class has the following properties:

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: