---
title: "Brokerage Message Handler"
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/brokerage-message-handler
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/brokerage-message-handler.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/24%20Reality%20Modeling/06%20Brokerage%20Message%20Handler
modified: 2026-10-29
index: https://www.quantconnect.com/llms.txt
---

# Brokerage Message Handler

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Writing Algorithms](https://www.quantconnect.com/docs/v2/writing-algorithms.md) > Reality Modeling > Brokerage Message Handler

> Code examples are shown in Python. Append `?lang=csharp` to this URL for the C# version of this page.

## Introduction

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 `initialize` method, call the `set_brokerage_message_handler` method.

```python
def initialize(self) -> None:
    # Set a custom brokerage message handler for the algorithm in Initialize method
    # It handles different type of returned message from the broker, helping you filter or abstract for the ones you care about
    self.set_brokerage_message_handler(MyBrokerageMessageHandler(self))
```

## Default Behavior

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

| Brokerage Message Type | Action |
| --- | --- |
| `BrokerageMessageType. Information INFORMATION` | Sends a [debug message](https://www.quantconnect.com/docs/v2/writing-algorithms/logging.md#03-Debug-Messages) for the algorithm. |
| `BrokerageMessageType. Warning WARNING` | Sends an [error message](https://www.quantconnect.com/docs/v2/writing-algorithms/logging.md#04-Error-Messages) for the algorithm. |
| `BrokerageMessageType. Error ERROR` | Sets the algorithm runtime error and stops it. |
| `BrokerageMessageType. Disconnect DISCONNECT` | Stops the algorithm after 15 minutes if the market is open. Otherwise, it stops five minutes after market open. |
| `BrokerageMessageType. Reconnect RECONNECT` | Cancels 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:

| Argument | Data Type | Description | Default Value |
| --- | --- | --- | --- |
| `algorithm` | `IAlgorithm` | The running algorithm. |  |
| `initial_delay` | `timedelta/NoneType` | The 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 `timedelta(minutes=15)`. | `None` |
| `open_threshold` | `timedelta/NoneType` | Defines how long before market open to re-check for brokerage reconnect message. If you don't provide a value, it uses `timedelta(minutes=5)`. | `None` |

For more information about this model, see the [class reference](https://www.lean.io/docs/v2/lean-engine/class-reference/py/QuantConnect/Brokerages/DefaultBrokerageMessageHandler/) and [implementation](https://github.com/QuantConnect/Lean/blob/master/Common/Brokerages/DefaultBrokerageMessageHandler.cs).

## Model Structure

Brokerage message handlers extend the `DefaultBrokerageMessageHandler` class. Extensions of the `DefaultBrokerageMessageHandler` class should define the `handle_message` and `handle_order` methods.

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

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

```python
class CustomBrokerageMessageHandlerExampleAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        # In the Initialize method, set the brokerage message handler
        self.set_brokerage_message_handler(MyBrokerageMessageHandler(self))

# Define the custom brokerage message handler
class MyBrokerageMessageHandler(DefaultBrokerageMessageHandler):

    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:

*Members of `QuantConnect.Brokerages.BrokerageMessageEvent` (JSON): https://www.quantconnect.com/services/inspector?type=T:QuantConnect.Brokerages.BrokerageMessageEvent&language=python*

The `NewBrokerageOrderNotificationEventArgs` class has the following properties:

*Members of `QuantConnect.Brokerages.NewBrokerageOrderNotificationEventArgs` (JSON): https://www.quantconnect.com/services/inspector?type=T:QuantConnect.Brokerages.NewBrokerageOrderNotificationEventArgs&language=python*

## Brokerage Support

Most QuantConnect brokerage integrations don't support brokerage-side orders. If you create an order directly through your brokerage instead of through LEAN, your algorithm won't process the order because the return value of the `handle_order` method is ignored.

[Quant Bridge](https://www.quantconnect.com/docs/v2/cloud-platform/live-trading/brokerages/bloomberg-emsx.md) is the exception that can support brokerage-side orders. The following algorithm demonstrates how to implement a custom brokerage handler that accepts orders with a target `QuantBridgeOrderProperties.custom_notes_1` value.

```python
class CustomBrokerageSideOrderHandlingAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 11)
        self.set_brokerage_message_handler(CustomBrokerageMessageHandler(self))
        self.brokerage_side_order = None
        self.schedule.on(self.date_rules.every_day(), self.time_rules.every(timedelta(minutes=1)), self.check_brokerage_side_order)

    def check_brokerage_side_order(self):
        if not self.brokerage_side_order:
            return
        open_orders = self.transactions.get_open_orders()
        brokerage_order = next((x for x in open_orders if x.broker_id[0] == self.brokerage_side_order.broker_id[0]), None)
        if not brokerage_order:
            return
        if not self.securities.contains_key(brokerage_order.symbol):
            self.log(f"Security {brokerage_order.symbol} not found in algorithm's securities!")
        self.log(f"{self.time} :: Brokerage-side order found: {brokerage_order}")

class CustomBrokerageMessageHandler(DefaultBrokerageMessageHandler):
    def __init__(self, algorithm):
        super().__init__(algorithm)
        self._algorithm = algorithm

    def handle_order(self, event_args):
        order = event_args.order
        self._algorithm.brokerage_side_order = order

        # Only accept QuantBridge orders with a custom note "AcceptOrder".
        if not isinstance(order.properties, QuantBridgeOrderProperties):
            self._algorithm.log("handle_order(): order properties is not set to expected quant bridge type, skipping")
            return False
        custom_notes1 = order.properties.custom_notes1
        result = custom_notes1 and "AcceptOrder" in custom_notes1
        self._algorithm.log(f"handle_order(): returning: {result}")
        return result
```

## Examples

The following examples demonstrate common practices for implementing a custom brokerage message handler.

### Example 1: Notification

The following algorithm buys and holds SPY. It implemented a custom brokerage message handler to send notifications to users through email and SMS in cases of disconnection, reconnections, and outside trades.

```python
class CustomBrokerageMessageHandlerAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        # To simulate the connection to IB brokerage.
        self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE, AccountType.MARGIN)
        # Set the brokerage message handler to our custom model.
        self.set_brokerage_message_handler(CustomBrokerageMessageHandler(self))

        # Request SPY data for trading.
        self.spy = self.add_equity("SPY").symbol

    def on_data(self, slice: Slice) -> None:
        # Buy and hold SPY as a strategy.
        if not self.portfolio.invested:
            self.set_holdings(self.spy, 1)

class CustomBrokerageMessageHandler(DefaultBrokerageMessageHandler):
    def __init__(self, algorithm: QCAlgorithm) -> None:
        self._algorithm = algorithm

    def handle_message(self, message: BrokerageMessageEvent) -> None:
        # Notify the user by SMS of the disconnection of the algorithm instance from the brokerage.
        if message.type == BrokerageMessageType.DISCONNECT:
            self._algorithm.notify.sms(
                phone_number="<YOUR_PHONE_NUMBER>",
                message="Your QC Algorithm instance 'CustomBrokerageMessageHandlerAlgorithm' was disconnected from the IB brokerage."
            )
        # Notify the user by SMS on reconnection of the algorithm instance to the brokerage after disconnection.
        elif message.type == BrokerageMessageType.RECONNECT:
            self._algorithm.notify.sms(
                phone_number="<YOUR_PHONE_NUMBER>",
                message="Your QC Algorithm instance 'CustomBrokerageMessageHandlerAlgorithm' was reconnected to the IB brokerage."
            )

    def handle_order(self, event_args: NewBrokerageOrderNotificationEventArgs) -> bool:
        # Notify the user by email on receiving an order from outside the algorithm.
        self._algorithm.notify.email(
            address="<YOUR_EMAIL_ADDRESS@example.com>",
            subject="Outside Order",
            message="Your QC Algorithm instance 'CustomBrokerageMessageHandlerAlgorithm' detected an outside order from the IB brokerage; it has been processed to the algorithm."
        )
        # Process a new order placed through the brokerage's website or third-party software to handle it in the algorithm instance.
        return True
```

### Other Examples

For more examples, see the following algorithms:

**Demonstration Algorithms**

- [CustomBrokerageSideOrderHandlingRegressionAlgorithm.py](https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/CustomBrokerageSideOrderHandlingRegressionAlgorithm.py) (Python)
