---
title: "Shorting"
description: "Short positions let you profit when a security's price decreases while you have the position open, but there are risks involved."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/us-equity/shorting
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/us-equity/shorting.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/03%20Securities/99%20Asset%20Classes/01%20US%20Equity/07%20Shorting
modified: 2026-10-30
index: https://www.quantconnect.com/llms.txt
---

# Shorting

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Writing Algorithms](https://www.quantconnect.com/docs/v2/writing-algorithms.md) > Securities > [Asset Classes](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes.md) > [US Equity](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/us-equity.md) > Shorting

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

## Introduction

In a regular long position, you buy shares and then sell them later to close the trade. In a short position, you borrow shares, sell them, and then buy the shares back later to close the trade. Short positions let you profit when a security's price decreases while you have the position open, but there are risks involved. For example, you can get a margin call and you may incur borrowing costs.

## Holdings Accounting

If you have an open long position, your portfolio has a positive quantity of shares for that security. In contrast, if you have an open short position, your portfolio has a negative quantity of shares for that security.

## Short Availability

To short sell, you need to borrow the shares from another investor or your brokerage. The **short availability** is the number of shares available for you to borrow. If you don't model the short availability in backtests, you could have a strategy that performs well in backtesting but doesn't trade in live mode because the shares aren't available to borrow. If you assume your short orders are successful in backtests, your backtesting results likely won't represent the true performance of actually trading the strategy during the backtest period. To get the short availability in your algorithms, use the [US Equities Short Availability dataset](https://www.quantconnect.com/datasets/us-equities-short-availability). For more information about this topic, see [Short Availability](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/short-availability/key-concepts.md).

## Borrowing Costs

In live trading, your brokerage charges an interest fee when you borrow shares to short a security. In backtesting, use the [ShortMarginInterestRateModel](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/margin-interest-rate/supported-models.md#03-Short-Equity-Model).

To get valid borrowing rates, use the [InteractiveBrokersShortableProvider](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/short-availability/supported-providers.md#05-Interactive-Brokers-Provider).

```python
def initialize(self) -> None:
    security = self.add_equity("SPY")
    # For US Equity, use the ShortMarginInterestRateModel with IB data
    security.set_shortable_provider(InteractiveBrokersShortableProvider())
    security.margin_interest_rate_model = ShortMarginInterestRateModel()
```

## Examples

The following examples demonstrate some common practices for shorting US Equities:

### Example 1: Shorting Penny Stock Top Gainers

The following algorithm adds a [universe](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/equity/fundamental-universes.md) of penny stocks that have experienced the greatest upward momentum over the last two trading days. For each asset in the universe, it monitors an hourly [Bollinger Bands](https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/supported-indicators/bollinger-bands.md) indicator. When an asset breaks above the upper band, it shorts the asset. It exits each position when the asset drops 10% from the entry price or when the price reverts back below the middle Bollinger Band.

```python
class USEquityShortingExampleAlgorithm(QCAlgorithm):

    _roc_by_symbol = {}

    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        # Enable automatic indicator warm-up.
        self.settings.automatic_indicator_warm_up = True
        # Add a universe of low-cap penny stocks that have high upward momentum.
        self.add_universe(self._select_assets)

    def _select_assets(self, fundamentals: List[Fundamental]) -> List[Symbol]:
        # Select all the penny stocks that have a momentum score.
        penny_stocks = []
        for f in fundamentals:
            # Create a RateOfChange indicator for each asset.
            self._roc_by_symbol[f.symbol] = self._roc_by_symbol.get(f.symbol, RateOfChange(1))
            # Update the indicator an ensure it's ready.
            # Filter out assets above $5M market cap or $1 share price.
            if not self._roc_by_symbol[f.symbol].update(f.end_time, f.price) or f.market_cap > 5e6 or f.price > 1:
                continue
            penny_stocks.append(f.symbol)

        # Select the 20 penny stocks with the greatest momentum.
        return sorted(penny_stocks, key=lambda symbol: self._roc_by_symbol[symbol].current.value)[-20:]

    def on_securities_changed(self, changes: SecurityChanges) -> None:
        # Iterate through the assets that entered the universe.
        for security in changes.added_securities:
            # Set the shortable provider of the asset to ensure realistic short availability.
            security.set_shortable_provider(InteractiveBrokersShortableProvider())
            # Create a BollingerBand indicator for this asset.
            security.bbands = self.bb(security.symbol, 20, 2, resolution=Resolution.HOUR)
            # Attach an event handler to the indicator to track its updates.
            security.bbands.updated += self.on_bb_updated

        # Liquidate and remove the indicator updates for assets that leave the universe.
        for security in changes.removed_securities:
            self.deregister_indicator(security.bbands)
            self.liquidate(security.symbol)

    def on_bb_updated(self, bb: object, _: IndicatorDataPoint) -> None:
        # When the indicator updates, ensure it's ready.
        if not bb.is_ready:
            return
        security = self.securities[bb.current.symbol]
        # Short the asset if the price is above the upper band.
        if not security.holdings.invested and security.price > bb.upper_band.current.value:
            # Get the number of shares avaiable for shorting.
            shortable_quantity = security.shortable_provider.shortable_quantity(security.symbol, self.time)
            # Calculate the target quantity.
            quantity = max(self.calculate_order_quantity(security.symbol, -0.1), -shortable_quantity if shortable_quantity else 0)
            if quantity == 0: return
            # Short the asset.
            self.market_order(security.symbol, quantity)
            # Place a take-profit order 10% below the current price.
            self.limit_order(security.symbol, -quantity, 0.9 * security.bid_price)
        # If the limit order isn't hit before the price drops below the middle band,
        # exit the position and cancel the limit order.
        elif security.holdings.invested and security.price < bb.middle_band.current.value:
            self.liquidate(security.symbol)
```
