---
title: "Liquidating Positions"
description: "The Liquidate method lets you liquidate individual assets or your entire portfolio. The method creates market orders to close positions."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/liquidating-positions
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/liquidating-positions.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/22%20Trading%20and%20Orders/06%20Liquidating%20Positions
modified: 2026-10-30
index: https://www.quantconnect.com/llms.txt
---

# Liquidating Positions

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Writing Algorithms](https://www.quantconnect.com/docs/v2/writing-algorithms.md) > Trading and Orders > Liquidating Positions

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

## Introduction

The `liquidate` method lets you liquidate individual assets or your entire portfolio. The method creates market orders to close positions and returns the [tickets](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/order-management/order-tickets.md) of the liquidation orders. If you have pending open orders for the security when you call `liquidate`, LEAN tries to cancel them. The `liquidate` method works for all asset classes, except Crypto. To liquidate Crypto positions, see [Crypto Trades](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/crypto-trades.md).

## Liquidate Individual Positions

To liquidate your holdings in an individual security, call the `liquidate` method and provide a ticker or `Symbol`.

```python
# Liquidate all IBM in your portfolio
order_tickets = self.liquidate("IBM")
```

You can pass an order [tag](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/order-properties.md#17-Tags) and [properties](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/order-properties.md) to the `liquidate` method.

```python
order_properties = OrderProperties()
order_properties.time_in_force = TimeInForce.DAY
order_tickets = self.liquidate("AAPL", tag="Liquidated", order_properties=order_properties)
```

## Liquidate All Positions

To liquidate all of the positions in your portfolio, call the `liquidate` method without any ticker of `Symbol` arguments.

```python
// Liquidate your entire portfolio
order_tickets = self.liquidate()
```

You can pass an order [tag](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/order-properties.md#17-Tags) and [properties](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/order-properties.md) to the `liquidate` method.

```python
order_properties = OrderProperties()
order_properties.time_in_force = TimeInForce.DAY
order_tickets = self.liquidate(tag="Liquidated", order_properties=order_properties)
```

## Asynchronous Liquidations

When you trade a large portfolio of assets, you may want to send orders in batches and not wait for the response of each one. To send [asynchronous orders](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/key-concepts.md#09-Asynchronous-Execution), set the `asynchronous` argument to `True`.

```python
order_tickets = self.liquidate(asynchronous=True, order_properties=order_properties);
```

The `asynchronous` parameter comes before the `tag` parameter, so pass the tag as a named argument, such as `tag="Entry"`. If you pass the tag by position, it fills the `asynchronous` parameter and the method call fails.

## Enable and Disable Liquidations

By default, the `liquidate` method is functional. To enable and disable it, set the `liquidate_enabled` [algorithm setting](https://www.quantconnect.com/docs/v2/writing-algorithms/initialization.md#10-Set-Algorithm-Settings).

```python
# Disable liquidations
self.settings.liquidate_enabled = False

# Enable liquidations
self.settings.liquidate_enabled = True
```

## Market Closed Considerations

If you liquidate your positions when the market is closed, LEAN converts the orders into market on open orders. If your brokerage doesn't support [market on open orders](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/order-types/market-on-open-orders.md), the order is invalid.

## Examples

The following examples demonstrate some common practices for liquidating positions.

### Example 1: Liquidate Universe Removal

The following algorithm holds equal positions for the top 10 liquid universe to follow their hype while updating weekly. When a stock is removed from the universe, we liquidate the position in the `on_securities_changed` method.

```python
class LiquidatingPositionsAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)

        # Update the universe weekly to allow time to capitalize on the hype.
        self.universe_settings.schedule.on(self.date_rules.week_start())
        # Filter for the 10 most popular stocks to invest the hype.
        self._universe = self.add_universe(self.universe.top(10))

        # Set a schedule event to rebalance weekly.
        self.schedule.on(
            self.date_rules.week_start("SPY"),
            self.time_rules.at(9, 31),
            self.rebalance
        )

    def rebalance(self) -> None:
        # Evenly invest in the universe members to dissipate the capital risk equally.
        count = len(self._universe.members)
        targets = [PortfolioTarget(x.key, 1 / count) for x in self._universe.members]
        self.set_holdings(targets)

    def on_securities_changed(self, changes: SecurityChanges) -> None:
        # Liquidate the ones leaving the universe since they are not the most popular.
        # Note that the liquidation will be market-on-open orders due to the time of securities removal.
        for removed in changes.removed_securities:
            self.liquidate(removed.symbol)
```

### Example 2: Liquidate Existing Positions

The example below trades the same strategy as the previous one. Still, instead of liquidating the positions when the stocks leave the universe, we liquidate the position using the `liquidate_existing_holdings` argument in the `set_holdings`. Note that the time of the liquidation will be slightly delayed due to the time of the scheduled event.

```python
class LiquidatingPositionsAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)

        # Update the universe weekly to allow time to capitalize on the hype.
        self.universe_settings.schedule.on(self.date_rules.week_start())
        # Filter for the 10 most popular stocks to invest the hype.
        self._universe = self.add_universe(self.universe.top(10))

        # Set a scheduled event to rebalance weekly.
        self.schedule.on(
            self.date_rules.week_start("SPY"),
            self.time_rules.at(9, 31),
            self.rebalance
        )

    def rebalance(self) -> None:
        # Evenly invest in the universe members to dissipate the capital risk equally.
        count = len(self._universe.members)
        targets = [PortfolioTarget(x.key, 1 / count) for x in self._universe.members]
        # We can use `liquidate_existing_holdings` arguments to liquidate the ones not in the universe anymore.
        self.set_holdings(targets, liquidate_existing_holdings=True)
```

### Example 3: Liquidate Upon Assignment

The following algorithm sells SPY ATM puts weekly to earn the premium when SPY price is rising. In the case where the price of SPY drops and the put is being assigned, we liquidate the SPY position in the `on_assignment_order_event`.

```python
class LiquidatingPositionsAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        # Seed the price with the last known price to ensure the underlying price data is available on initial option contract filtering.
        self.settings.seed_initial_prices = True

        # Request SPY data for option selection using its price.
        # Use raw data normalization mode since we need to compare the SPY price with the strike price.
        self.spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol

        # Set a scheduled event to rebalance weekly.
        self.schedule.on(
            self.date_rules.week_start(),
            self.time_rules.at(9, 31),
            self.rebalance
        )

    def rebalance(self) -> None:
        # Select the 1-week ATM put SPY option to short.
        option_chain = self.option_chain(self.spy)
        expiry = max(x.expiry for x in option_chain if x.expiry < self.time + timedelta(6))
        atm_put = sorted([x for x in option_chain if x.expiry == expiry and x.right == OptionRight.PUT],
                        key=lambda x: abs(x.strike - self.securities[self.spy].price))[0]
        atm_put_symbol = self.add_option_contract(atm_put).symbol

        # Sell the ATM put option to earn the premium.
        self.sell(atm_put_symbol, 2)

    def on_assignment_order_event(self, assignment_event: OrderEvent) -> None:
        # Liquidate any assigned positions of SPY since we only earn the premium.
        self.liquidate(self.spy)
```
