---
title: "Universes"
description: "Request Futures data in your algorithm to receive a feed of contract prices in the OnData method."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/futures/requesting-data/universes
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/futures/requesting-data/universes.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/03%20Securities/99%20Asset%20Classes/06%20Futures/01%20Requesting%20Data/01%20Universes
modified: 2026-10-30
index: https://www.quantconnect.com/llms.txt
---

# Universes

[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) > [Futures](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/futures.md) > [Requesting Data](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/futures/requesting-data.md) > Universes

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

## Introduction

The `add_future` method enables you to select a basket of Future contracts for an underlying Future. To form your universe of contracts, you can filter them down by their expiry. If you want to subscribe to individual contracts one-by-one instead of a set of contracts, see [Individual Contracts](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/futures/requesting-data/individual-contracts.md).

LEAN subscribes to every contract that passes your filter, so you don't need to call the `add_future_contract` method for them. To trade a specific contract, such as when you manage the rollover with your own rule, select it from the [FuturesChain](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/futures/handling-data.md#05-Futures-Chains) in the `Slice` and place your orders with its `Symbol`. Set the filter wide enough to include the next contract on the date you plan to roll. For example, a week before the front-month contract expires, the next quarterly contract is about 98 days away, so a filter of 0 to 92 days excludes it.

## Create Universes

To add a universe of Future contracts, in the `initialize` method, call the `add_future` method. This method returns an `Future` object, which has a `set_filter` method you can call to filter the set of tradable contract down to just the contracts you want.

```python
class BasicFutureAlgorithm(QCAlgorithm):

    def initialize(self):
        self.future = self.add_future(
            Futures.Indices.SP_500_E_MINI,
            Resolution.DAILY,
            extended_market_hours=True,
            data_mapping_mode=DataMappingMode.OPEN_INTEREST,
            data_normalization_mode=DataNormalizationMode.BACKWARDS_RATIO,
            contract_depth_offset=0
        )
        self.future.set_filter(0, 182)

    def on_data(self, data):
        for continuous_symbol, chain in data.future_chains.items():
            for symbol, contract in chain.contracts.items():
                expiry = contract.expiry
```

For more information about the `add_future` method, see [Create Universes](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/futures.md#11-Create-Universes).

## Continous Contracts

By default, LEAN only subscribes to the continuous Future contract. A continuous Future contract represents a series of separate contracts stitched together to form a continuous price. If you need a lot of historical data to warm up an indicator, apply the indicator to the continuous contract price series. The `Future` object has a `symbol` property and a `mapped` property. The price of the `symbol` property is the adjusted price of the continuous contract. The price of the `mapped` property is the raw price of the currently selected contract in the continuous contract series.

```python
# Get the adjusted price of the continuous contract.
adjusted_price = self.securities[self._future.symbol].price

# Get the raw price of the currently selected contract in the continuous contract series.
raw_price = self.securities[self._future.mapped].price
```

The continuous Futures contract isn't a [tradable security](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/key-concepts.md#05-Tradable-Status). You must place orders for a specific Futures contract. To access the currently selected contract in the continuous contract series, use the `mapped` property of the `Future` object.

```python
# Place a market order for the currently selected contract in the continuous contract series.
self.market_order(self._future.mapped, 1)
```

For more information, see [Continous Contracts](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/futures.md#12-Continous-Contracts).

## Filter by Contract Properties

To set a contract filter, in the `initialize` method, call the `set_filter` method of the `Future` object. The following table describes the available filter techniques:

`set_filter(minExpiry: int, maxExpiry: int)`

Selects the contracts that expire within the range you set. This filter runs [asynchronously](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/settings.md#09-Asynchronous-Selection) by default.

```python
# Select the contracts that expire within 182 days.
self._future.set_filter(0, 182)

# Select the front month contract.
self._future.set_filter(lambda future_filter_universe: future_filter_universe.front_month())
```

The following table describes the filter methods of the `FutureFilterUniverse` class:

`standards_only()`

Selects standard contracts

`weeklys_only()`

Selects weekly contracts

`front_month()`

Selects the front month contract

`back_months()`

Selects the non-front month contracts

`back_month()`

Selects the back month contracts

`farthest_expiration()`

Selects the contracts with the farthest expiration date

`expiration(min_expiry: timedelta, max_expiry: timedelta)`

Selects contracts that expire within a range of dates relative to the current day

`expiration(min_expiry_days: int, max_expiry_days: int)`

Selects contracts that expire within a range of dates relative to the current day

`expiration(expiries: list[datetime])`

Selects the contracts that expire on any of the given dates. The time of day is ignored

`expiring_after(date: datetime)`

Selects the contracts that expire after the given date. The date itself is excluded and the time of day is ignored

`expiring_before(date: datetime)`

Selects the contracts that expire before the given date. The date itself is excluded and the time of day is ignored

`zero_dte()`

Selects the contracts that expire today

`expiration_cycle(months: list[int])`

Selects the contracts that expire in any of the given months of the year. The `FutureExpirationCycles` class defines the common cycles. For example, `FutureExpirationCycles.MARCH` is March, June, September, and December

`contract_months(months: list[int])`

Selects the contracts whose contract month, the month the contract is named after, is any of the given months of the year. Some products, like crude oil, expire the month before their contract month, so this filter and `expiration_cycle` can select different contracts

`oi(min: int, max: int)`
`open_interest(min: int, max: int)`

Selects the contracts with open interest in the given range

`volume(min: int, max: int)`

Selects the contracts with volume in the given range

`contracts(contracts: list[Symbol])`

Selects a list of contracts

`contracts(contractSelector: Callable[[list[Symbol]], list[Symbol]])`

Selects contracts that a selector function selects

The preceding methods return an `FutureFilterUniverse`, so you can chain the methods together.

```python
# Select the front month standard contracts
self._future.set_filter(lambda future_filter_universe: future_filter_universe.standards_only().front_month())
```

```python
# Select the quarterly contracts with at least 10,000 contracts of open interest
self._future.set_filter(lambda future_filter_universe: future_filter_universe.contract_months(FutureExpirationCycles.MARCH).open_interest(10000, sys.maxsize))
```

You can also define an isolated filter method.

```python
# In Initialize
self._future.set_filter(self._contract_selector)

def _contract_selector(self,
    future_filter_universe: Callable[[FutureFilterUniverse], FutureFilterUniverse]) -> FutureFilterUniverse:
    return future_filter_universe.standards_only().front_month()
```

The same filter methods are available on [`FuturesChain`](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/futures/handling-data.md#05-Futures-Chains) objects, so you can reuse them to narrow down a chain you receive during the algorithm.

## Default Filter

By default, LEAN doesn't add any contracts to the [FuturesChain](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/futures/handling-data.md#05-Futures-Chains) it passes to the `on_data` method.

## Historical Data

To get historical data for a Futures universe, see [Historical Data](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/futures.md#15-Historical-Data).

## Examples

The following examples demonstrate some common practices for requesting Futures universe data.

### Example 1: Rollover

Future contracts expire monthly or quarterly in most cases. Hence, if we hold Future position in month or quarter end, we must consider rolling over to the mapped contract. The following algorithm shows how to buy and roll over to the next front month Future contract. We make use of the universe selection filter to select the front month contract and order the next mapped contract during the previous one expires.

```python
class FutureExampleAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        # Seed the price with last known price to ensure the contract price data is available for the limit order.
        self.settings.seed_initial_prices = True
        future = self.add_future(Futures.Indices.SP_500_E_MINI, extended_market_hours=True)
        self._future = future.symbol
        # We only want to hold position of the front month contract.
        future.set_filter(lambda u: u.front_month())

    def on_securities_changed(self, changes: SecurityChanges) -> None:
        # Liquidate if expired (or not being the front month contract anymore) and exit universe.
        for removed in changes.removed_securities:
            self.liquidate(removed.symbol)

        for added in changes.added_securities:
            # Make sure the newly added contract is an actual mapped tradable contract.
            if not added.symbol.is_canonical():
                # Roll over by ordering the same quantity.
                # Use limit order since market on open order is not supported on Future and avoid extreme quote filling.
                self.limit_order(added.symbol, 1, added.price)
```

### Example 2: Continuous Future Indicator

One of the major applications of [Continuous Futures](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/futures.md#12-Continous-Contracts) is to obtain a smooth price series to feed into indicators. This technique ensures the indicator gets the price data that is comparable to the current contract in the continuous contract series. This example demonstrates a [Exponential Moving Average](https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/supported-indicators/exponential-moving-average.md) crossover strategy based on the continuous ES contract data.

```python
class FutureEMACrossAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(1_000_000)
        # Seed the price of each asset with its last known price to
        # avoid trading errors.
        self.settings.seed_initial_prices = True
        # Define a threshold for the EMA crossover.
        self._threshold = 0.01  # 1% above/below the EMA.
        # Use backward ratio normalization for the continuous contract
        # so the indicator receives a smooth price series.
        self._future = self.add_future(
            Futures.Indices.SP_500_E_MINI,
            data_normalization_mode=DataNormalizationMode.BACKWARDS_RATIO,
        )
        # Only add the front-month contract.
        self._future.set_filter(lambda u: u.front_month())
        # Create a 252-day EMA indicator as a trend estimator.
        self._future.ema = self.ema(self._future.symbol, 252, Resolution.DAILY)
        # Warm up the EMA indicator to so we can trade right away.
        self.warm_up_indicator(self._future.symbol, self._future.ema)

    def on_data(self, slice: Slice) -> None:
        # Ensure the TradeBar data is available for the Future before
        # placing trades.
        bar = slice.bars.get(self._future.symbol)
        if not bar:
            return
        # Buy the mapped contract if the trend is estimated to go up
        # (price above the EMA).
        if bar.close >= self._future.ema.current.value * (1+self._threshold):
            self.set_holdings(self._future.mapped, 0.1)
        # Short the mapped contract if the trend is estimated to go down
        # (price below the EMA).
        elif bar.close <= self._future.ema.current.value * (1-self._threshold):
            self.set_holdings(self._future.mapped, -0.1)

    def on_securities_changed(self, changes: SecurityChanges) -> None:
        # Liquidate the contract when it is no longer the front-month
        # contract (expired).
        for contract in changes.removed_securities:
            self.liquidate(contract.symbol)
```

### Example 3: Contango

In Future trading, contango refers to the far-to-expiry Future contract price is higher than the spot price due to various reasons, such as storage fee and insurance of the commodities. The following example shows a contango trading by shorting the far contract that the price is above a threshold compared to the front month contract price and buying the front month contract to earn the premium in between.

```python
class FutureExampleAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        # Add Gold Futures.
        future = self.add_future(Futures.Metals.GOLD)
        self._future = future.symbol
        # Limit the expiration to within 6 months, as the longer the expiration, the higher the price uncertainty.
        future.set_filter(lambda u: u.expiration(0, 183))

    def on_data(self, slice: Slice) -> None:
        # Get Future chain only for the selected Future contract.
        chain = slice.future_chains.get(self._future)
        if not self.portfolio.invested and chain:
            # It takes 2 contracts with different expiries to form a horizontal spread arbitration to earn price difference in contango.
            if len(list(chain)) < 2:
                return
            sorted_by_expiry = sorted(chain, key=lambda x: x.expiry)
            far_contract = sorted_by_expiry[-1]
            near_contract = sorted_by_expiry[0]

            # Check if the far contract price is 1% higher than the near one.
            # If so, short the far contract and buy the near one to earn the horizontal spread premium.
            if far_contract.bid_price >= near_contract.ask_price * 1.01:
                self.market_order(far_contract.symbol, -1)
                self.market_order(near_contract.symbol, 1)

    def on_securities_changed(self, changes: SecurityChanges) -> None:
        # Liquidate if expired (or not being the front month contract anymore) and exit universe.
        for removed in changes.removed_securities:
            self.liquidate()
```
