---
title: "Brokerages"
description: "Brokerages provide you with a connection to the market so you can fill trades. Brokerage models flag invalid orders before they reach your brokerage."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/live-trading/brokerages
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/live-trading/brokerages.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/40%20Live%20Trading/02%20Brokerages
modified: 2026-10-29
index: https://www.quantconnect.com/llms.txt
---

# Brokerages

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Writing Algorithms](https://www.quantconnect.com/docs/v2/writing-algorithms.md) > [Live Trading](https://www.quantconnect.com/docs/v2/writing-algorithms/live-trading.md) > Brokerages

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

## Introduction

Brokerages provide you with a connection to the market so you can fill trades. To avoid placing invalid orders for execution in live trading, LEAN validates your orders before sending them to the real brokerage. To view all of the integrated brokerages, see [Brokerages](https://www.quantconnect.com/docs/v2/cloud-platform/live-trading/brokerages.md).

## Portfolio

In live trading, LEAN populates the [`portfolio`](https://www.quantconnect.com/docs/v2/writing-algorithms/portfolio/key-concepts.md) object with your account holdings and the [`transactions`](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/order-management/transaction-manager.md) object with your open positions. If you don't manually subscribe to the assets in your account, LEAN subscribes to them with the lowest resolution of the subscriptions in your algorithm. For example, say you hold AAPL shares in your account and create the following subscriptions in your algorithm:

```python
self.add_equity("SPY", Resolution.HOUR)
self.add_equity("MSFT", Resolution.SECOND)
```

In this case, LEAN subscribes to second-resolution data for AAPL since the lowest resolution in your algorithm is

`Resolution.SECOND`.

## Deposits and Withdrawals

You can deposit and withdraw cash from your brokerage account while you run an algorithm that's connected to the account. We sync the algorithm's cash holdings with the cash holdings in your brokerage account every day at 7:45 AM Eastern Time (ET).

## 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 `on_brokerage_disconnect` event handler.

```python
def on_brokerage_disconnect(self) -> None:
    self.debug("Brokerage connection lost")
```

### Restored Connections

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

```python
def on_brokerage_reconnect(self) -> None:
    self.debug("Brokerage connection restored")
```

When LEAN reconnects with your brokerage, it synchronizes the state of your live orders. For example, say the brokerage fills your limit order during the period of disconnection. When the connection restores, LEAN updates the state of your portfolio and orders to reflect the filled order, but you won't receive an [order event](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/order-events.md).

### Example Algorithm

For a full example algorithm that implements the `on_brokerage_disconnect` and `on_brokerage_reconnect` methods, see the [BrokerageActivityEventHandlingAlgorithm](https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/BrokerageActivityEventHandlingAlgorithm.py) in the LEAN GitHub repository.

## Monitor Brokerage Messages

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

```python
def on_brokerage_message(self, message_event: BrokerageMessageEvent) -> None:
    self.debug(f"Brokerage message received: {message_event.message}")
```

`BrokerageMessageEvent` objects have the following attributes:

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

For a full example algorithm that implements the `on_brokerage_message` method, see the [BrokerageActivityEventHandlingAlgorithm](https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/BrokerageActivityEventHandlingAlgorithm.py) in the LEAN GitHub repository.

To handle brokerage messages outside of your algorithm class, create and set a `BrokerageMessageHandler`. For a more information example, see the [Reality Modeling > Brokerage Message Handler](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/brokerage-message-handler.md).

## Brokerage Models

Brokerage features and limitations are realistically modelled with Brokerage Models. These reality models set the supported order and asset types for the brokerage. To learn how to set your specific brokerage, see [Supported Models](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/brokerages/supported-models.md).

## Get Deployment Id

The deployment Id identifies a live deployment of your project. To get it in your algorithm, use the `algorithm_id` property. In live trading, it's the Id of the current deployment, for example `L-6bf91128391608d0728ff90b81bfca41`. In backtests, it's the backtest Id.

```python
self.log(f'Deployment Id: {self.algorithm_id}')
```

Use it to label the data your algorithm saves, so you can tell the results of successive deployments apart.

```python
self.object_store.save(f'{self.algorithm_id}/equity', str(self.portfolio.total_portfolio_value))
```

To get the deployment Id outside of your algorithm, see [Get Deployment Id](https://www.quantconnect.com/docs/v2/cloud-platform/live-trading/getting-started.md#11-Get-Deployment-Id).

## Get Deployment Details

Deployment details are the key-value pairs that your brokerage shares about the live deployment, like the account it trades. The keys depend on the brokerage. To see which details a brokerage shares, see the Deployment Details section of its [brokerage documentation](https://www.quantconnect.com/docs/v2/cloud-platform/live-trading/brokerages.md). The dictionary is empty in backtests because no brokerage is connected.

The `deployment_details` property of your algorithm is a read-only dictionary of the details. LEAN populates it before it calls the `initialize` method, so you can read it anywhere in your algorithm.

```python
deployment_details = [f'{kvp.key}:{kvp.value}' for kvp in self.deployment_details]
self.log(f'deployment_details: {deployment_details}')
```

The [/live/read](https://www.quantconnect.com/docs/v2/cloud-platform/api-reference/live-management/read-live-algorithm/live-algorithm-statistics.md) API endpoint also returns the details in its `deploymentDetails` field, so you can read them outside of the algorithm.

To read a single detail, use its key.

```python
account = self.deployment_details.get('ib-account')
if account:
    self.log(f'Trading account: {account}')
```

## Examples

The following examples demonstrate common practices for handling live brokerage messages.

### Example 1: Pre-Open Order Error

The following algorithm simulate extended market hour trading on [Tradier Brokerage](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/brokerages/supported-models/tradier.md). We place a market-on-open order at 7:30am and expect the order cannot submit to the broker since it is not supported, resulting into an error.

```python
class OrderErrorsAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        # Simulate Tradier brokerage, which does not support the market-on-open orders.
        self.set_brokerage_model(BrokerageName.TRADIER_BROKERAGE, AccountType.CASH)

        # Request extended market hour SPY data for trading.
        self.spy = self.add_equity("SPY", extended_market_hours=True).symbol

        # Set a scheduled event to trade 2 hours pre-open to place the market-on-open-order.
        self.schedule.on(
            self.date_rules.every_day(self.spy),
            self.time_rules.before_market_open(self.spy, 120),
            self.open_position
        )

    def open_position(self) -> None:
        # Buy on market open will result in an error since Tradier does not support it.
        self.market_on_open_order(self.spy, 10)

    # It will be triggered on live trading.
    def on_brokerage_message(self, message: BrokerageMessageEvent) -> None:
        if message.type == BrokerageMessageType.ERROR:
            self.log(f"{self.time}: {message.type}: Message: {message.message}")
```
