🚀 AI One-Click Generation of quantconnect Strategy Code

How to Interpret and Use the `on_brokerage_message` Event in QuantConnect

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

Problem Description

How do I use the `on_brokerage_message` event to get information from my broker?

Solution

Using on_brokerage_message in QuantConnect

The on_brokerage_message event handler allows your algorithm to intercept and process messages sent directly from your brokerage. This is particularly useful in Live Trading for handling errors, warnings, connection status updates, or order rejections that do not trigger standard order events.

This method is triggered asynchronously whenever the brokerage API pushes a message to the LEAN engine.

Implementation Example

Below is a complete example of how to implement the on_brokerage_message method within a standard algorithm class. This example demonstrates how to categorize messages by type (Error, Warning, or Information) and log them accordingly.

# region imports
from AlgorithmImports import *
# endregion

class BrokerageMessageAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2023, 1, 1)
        self.set_cash(100000)
        self.add_equity("SPY", Resolution.MINUTE)

    def on_data(self, data: Slice):
        # Standard trading logic would go here
        pass

    def on_brokerage_message(self, message: BrokerageMessageEvent) -> None:
        """
        Event handler for all brokerage messages.
        
        Args:
            message (BrokerageMessageEvent): The object containing details 
                                             about the brokerage notification.
        """
        
        # 1. Handle Errors (e.g., Insufficient buying power, API errors)
        if message.type == BrokerageMessageType.ERROR:
            self.error(f"Brokerage Error Code {message.code}: {message.message}")
            
            # Example: Stop the algorithm if a critical error occurs
            # self.quit(f"Stopping due to brokerage error: {message.message}")

        # 2. Handle Warnings (e.g., API rate limits approaching)
        elif message.type == BrokerageMessageType.WARNING:
            self.log(f"Brokerage Warning: {message.message}")

        # 3. Handle Information/Connection messages
        elif message.type == BrokerageMessageType.INFORMATION:
            self.log(f"Brokerage Info: {message.message}")
            
        # 4. Handle Reconnection events specifically
        elif message.type == BrokerageMessageType.RECONNECT:
            self.log(f"Brokerage Reconnected at {self.time}")

        # 5. Handle Disconnection events specifically
        elif message.type == BrokerageMessageType.DISCONNECT:
            self.log(f"Brokerage Disconnected at {self.time}")

Key Object Properties

The message argument passed to the function is of type BrokerageMessageEvent. It contains the following useful properties:

Property Description
message.type An enum (BrokerageMessageType) indicating the severity: ERROR, WARNING, INFORMATION, DISCONNECT, or RECONNECT.
message.code A string code provided by the brokerage (e.g., specific error ID). Useful for programmatic handling of specific errors.
message.message The human-readable string containing the details of the notification.

Q&A

Does on_brokerage_message work in Backtesting?

Generally, no. In a standard backtest, the internal LEAN simulation does not generate brokerage messages. This event handler is primarily designed for Live Trading where real-world connectivity issues and brokerage rejections occur. However, if you are using a custom brokerage model in a backtest that explicitly emits these events, it will trigger.

What is the difference between on_order_event and on_brokerage_message?

on_order_event is strictly for updates regarding the status of a specific order (e.g., Submitted, Filled, Canceled). on_brokerage_message is for general communication from the broker that might not be tied to a specific order ID, such as "Connection Lost," "Account Maintenance," or "Invalid API Credentials."

Can I place orders inside on_brokerage_message?

Technically yes, but it is risky. Since this event is triggered asynchronously and often indicates a problem (like a disconnect or error), placing new orders immediately might result in further errors. It is better to use this event to update a state variable (e.g., self.brokerage_healthy = False) and let your on_data loop handle the trading logic based on that state.