---
title: "Handling Data"
description: "LEAN passes the data you request to the OnData method so you can make trading decisions. The Slice object groups the data together with a timestamp."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/futures/handling-data
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/futures/handling-data.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/03%20Securities/99%20Asset%20Classes/06%20Futures/02%20Handling%20Data
modified: 2026-10-30
index: https://www.quantconnect.com/llms.txt
---

# Handling Data

[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) > Handling Data

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

## Introduction

LEAN passes the data you request to the `on_data` method so you can make trading decisions. The `Slice` object that the `on_data` method receives groups all the data together at a single moment in time. To access the `Slice` outside of the `on_data` method, use the `current_slice` property of your algorithm.

All the data formats use `DataDictionary` objects to group data by `Symbol` and provide easy access to information. The plural of the type denotes the collection of objects. For instance, the `TradeBars` `DataDictionary` is made up of `TradeBar` objects. To access individual data points in the dictionary, you can index the dictionary with the contract ticker or `symbol`, but we recommend you use the `symbol`.

To view the resolutions that are available for Futures data, see [Resolutions](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/futures/requesting-data/individual-contracts.md#03-Resolutions).

## Trades

`TradeBar` objects are price bars that consolidate individual trades from the exchanges. They contain the open, high, low, close, and volume of trading activity over a period of time.

![Tradebar decomposition](https://cdn.quantconnect.com/docs/i/dataformat-tradebar.png)

To get the `TradeBar` objects in the `Slice`, index the `Slice` or index the `bars` property of the `Slice` with the contract `symbol`. If the contract doesn't actively trade or you are in the same time step as when you added the contract subscription, the `Slice` may not contain data for your `symbol`. To avoid issues, check if the `Slice` contains data for your contract before you index the `Slice` with the contract `symbol`.

```python
def on_data(self, slice: Slice) -> None:
    # Obtain the mapped TradeBar of the symbol if any
    trade_bar = slice.bars.get(self._contract_symbol)   # None if not found
```

You can also iterate through the `TradeBars` dictionary. The keys of the dictionary are the `Symbol` objects and the values are the `TradeBar` objects.

```python
def on_data(self, slice: Slice) -> None:
    # Iterate all received Symbol-TradeBar key-value pairs
    for symbol, trade_bar in slice.bars.items():
        close_price = trade_bar.close
```

`TradeBar` objects have the following properties:

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

## Quotes

`QuoteBar` objects are bars that consolidate NBBO quotes from the exchanges. They contain the open, high, low, and close prices of the bid and ask. The `open`, `high`, `low`, and `close` properties of the `QuoteBar` object are the mean of the respective bid and ask prices. If the bid or ask portion of the `QuoteBar` has no data, the `open`, `high`, `low`, and `close` properties of the `QuoteBar` copy the values of either the `bid` or `ask` instead of taking their mean.

![Quotebar decomposition](https://cdn.quantconnect.com/docs/i/dataformat-quotebar.png)

To get the `QuoteBar` objects in the `Slice`, index the `QuoteBars` property of the `Slice` with the contract `symbol`. If the contract doesn't actively get quotes or you are in the same time step as when you added the contract subscription, the `Slice` may not contain data for your `symbol`. To avoid issues, check if the `Slice` contains data for your contract before you index the `Slice` with the contract `symbol`.

```python
def on_data(self, slice: Slice) -> None:
    # Obtain the mapped QuoteBar of the symbol if any
    quote_bar = slice.quote_bars.get(self._contract_symbol)   # None if not found
```

You can also iterate through the `QuoteBars` dictionary. The keys of the dictionary are the `Symbol` objects and the values are the `QuoteBar` objects.

```python
def on_data(self, slice: Slice) -> None:
    # Iterate all received Symbol-QuoteBar key-value pairs
    for symbol, quote_bar in slice.quote_bars.items():
        ask_price = quote_bar.ask.close
```

`QuoteBar` objects let LEAN incorporate spread costs into your [simulated trade fills](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/trade-fills/key-concepts.md) to make backtest results more realistic.

`QuoteBar` objects have the following properties:

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

## Ticks

`Tick` objects represent a single trade or quote at a moment in time. A trade tick is a record of a transaction for the contract. A quote tick is an offer to buy or sell the contract at a specific price.

Trade ticks have a non-zero value for the `quantity` and `price` properties, but they have a zero value for the `bid_price`, `bid_size`, `ask_price`, and `ask_size` properties. Quote ticks have non-zero values for `bid_price` and `bid_size` properties or have non-zero values for `ask_price` and `ask_size` properties. To check if a tick is a trade or a quote, use the `ticktype` property.

In backtests, LEAN groups ticks into one millisecond buckets. In live trading, LEAN groups ticks into ~70-millisecond buckets. To get the `Tick` objects in the `Slice`, index the `Ticks` property of the `Slice` with a `symbol`. If the contract doesn't actively trade or you are in the same time step as when you added the contract subscription, the `Slice` may not contain data for your `symbol`. To avoid issues, check if the `Slice` contains data for your contract before you index the `Slice` with the contract `symbol`.

```python
def on_data(self, slice: Slice) -> None:
    ticks = slice.ticks.get(self._contract_symbol, [])   # Empty if not found
    for tick in ticks:
        price = tick.price
```

You can also iterate through the `Ticks` dictionary. The keys of the dictionary are the `Symbol` objects and the values are the `list[Tick]` objects.

```python
def on_data(self, slice: Slice) -> None:
    for symbol, ticks in slice.ticks.items():
        for tick in ticks:
            price = tick.price
```

Tick data is raw and unfiltered, so it can contain bad ticks that skew your trade results. For example, some ticks come from dark pools, which aren't tradable. We recommend you only use tick data if you understand the risks and are able to perform your own online tick filtering.

`Tick` objects have the following properties:

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

## Futures Chains

`FuturesChain` objects represent an entire chain of contracts for a single underlying Future. To get the `FuturesChain`, index the `futures_chains` property of the `Slice` with the continuous contract `Symbol`.

```python
def on_data(self, slice: Slice) -> None:
    # Try to get the FutureChain using the canonical symbol (None if no FutureChain return)
    chain = slice.futures_chains.get(self._contract_symbol.canonical)
    if chain:
        # Get all contracts if the FutureChain contains any member
        contracts = chain.contracts
```

You can also loop through the `futures_chains` property to get each `FuturesChain`.

```python
def on_data(self, slice: Slice) -> None:
    # Iterate all received Canonical Symbol-FutureChain key-value pairs
    for continuous_contract_symbol, chain in slice.futures_chains.items():
        contracts = chain.contracts
```

### Filter Chains

`FuturesChain` objects provide the same filter methods as [Futures universe selection](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/futures.md#13-Filter-Contracts), with the same names and the same behavior. Each method returns a new `FuturesChain` and leaves the source chain unchanged, so you can chain the calls together.

```python
# Select the front contract that expires at least 90 days out.
contract = next(iter(chain.expiring_after(self.time + timedelta(days=90)).front_month()), None)

# Select the quarterly contracts.
quarterlies = chain.contract_months(FutureExpirationCycles.MARCH)
```

To filter the chain with your own predicate, call the `where` method.

```python
liquid_contracts = chain.open_interest(100000, sys.maxsize).where(lambda contract: contract.volume > 0)
```

The `standards_only` and `weeklys_only` methods of a chain apply to the contracts the chain already holds, so you can combine them with the expiration filters in any order. In universe selection, these two filters always run last.

### Properties

`FuturesChain` objects have the following properties:

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

## Futures Contracts

`FuturesContract` objects represent the data of a single Futures contract in the market. To get the Futures contracts in the `Slice`, use the `contracts` property of the `FuturesChain`.

```python
def on_data(self, slice: Slice) -> None:
    # Try to get the FutureChain using the canonical symbol
    chain = slice.future_chains.get(self._contract_symbol.canonical)
    if chain:
        # Get individual contract data (None if not contained)
        contract = chain.contracts.get(self._contract_symbol)
        if contract:
            price = contract.last_price
```

Open interest is the number of outstanding contracts that haven't been settled. It provides a measure of investor interest and the market liquidity, so it's a popular metric to use for contract selection. Open interest is calculated once per day. To get the latest open interest value, use the `open_interest` property of the `Future` or `future_contract`.

```python
def on_data(self, slice: Slice) -> None:
    # Try to get the futures_chains using the canonical symbol
    chain = slice.futures_chains.get(self._contract_symbol.canonical)
    if chain:
        # Get individual contract data
        contract = chain.contracts.get(self._contract_symbol)
        if contract:
            # Get the open interest of the selected contracts
            open_interest = contract.open_interest
```

`FuturesContract` objects have the following properties:

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

## Symbol Changes

When the [continuous contract](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/futures.md#12-Continous-Contracts) rolls over, LEAN passes a `SymbolChangedEvent` to your `on_data` method, which contains the old contract `Symbol` and the new contract `Symbol`. To get the `SymbolChangedEvent`, use the `symbol_changed_events` property of the `Slice`. You can use the `SymbolChangedEvent` to roll over contracts.

```python
def on_data(self, slice: Slice) -> None:
    for symbol, changed_event in  slice.symbol_changed_events.items():
        old_symbol = changed_event.old_symbol
        new_symbol = changed_event.new_symbol
        tag = f"Rollover - Symbol changed at {self.time}: {old_symbol} -> {new_symbol}"
        quantity = self.portfolio[old_symbol].quantity

        # Rolling over: to liquidate any position of the old mapped contract and switch to the newly mapped contract
        self.liquidate(symbol=old_symbol, tag=tag)
        if quantity: self.market_order(new_symbol, quantity, tag=tag)
        self.log(tag)
```

LEAN passes a `SymbolChangedEvent` to your `on_symbol_changed_events` method as well. LEAN only invokes this method when the [continuous contract](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/futures.md#12-Continous-Contracts) rolls over.

```python
def on_symbol_changed_events(self, symbol_changed_events: SymbolChangedEvents) -> None:
    for symbol, changed_event in symbol_changed_events.items():
        old_symbol = changed_event.old_symbol
        new_symbol = changed_event.new_symbol
        tag = f"Rollover - Symbol changed at {self.time}: {old_symbol} -> {new_symbol}"
        quantity = self.portfolio[old_symbol].quantity

        # Rolling over: to liquidate any position of the old mapped contract and switch to the newly mapped contract
        self.liquidate(symbol=old_symbol, tag=tag)
        if quantity: self.market_order(new_symbol, quantity, tag=tag)
        self.log(tag)
```

In backtesting, the `SymbolChangedEvent` occurs at midnight Eastern Time (ET). In live trading, the live data for continuous contract mapping arrives at 6/7 AM ET, so that's when it occurs.

`SymbolChangedEvent` objects have the following properties:

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

## Examples

The following examples demonstrate some common practices for handling Futures data.

### Example 1: Rollovers

Spot Future is referred to as the continuous Future contract, which is usually mapped by the front month contract or the contract with the most open interest. When a contract expires or is very close to expiring, traders usually rollover from the current contract to the next contract to avoid price settlement and remain invested. The following algorithm demonstrates rolling over with [limit orders](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/order-types/limit-orders.md).

```python
class FutureExampleAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        # Add the E-mini Futures and set the continuous contract mapping criteria for the rollovers.
        self._future = self.add_future(
            Futures.Indices.SP_500_E_MINI,
            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):
        # Place the initial order so you can start rolling over contracts later.
        if not self.portfolio.invested and not self.transactions.get_open_orders():
            # Buy the contract that's currently selected in the continous contract series.
            self.market_order(self._future.mapped, 1)

    # Track rollover events.
    def on_symbol_changed_events(self, symbol_changed_events):
        for symbol, changed_event in symbol_changed_events.items():
            old_symbol = changed_event.old_symbol
            new_symbol = changed_event.new_symbol
            # The quantity to roll over should be consistent.
            quantity = self.portfolio[old_symbol].quantity
            # Rolling over: Liquidate the old mapped contract and switch to the newly mapped contract.
            tag = f"Rollover: {old_symbol} -> {new_symbol}"
            self.liquidate(old_symbol, tag=tag)
            if quantity:
                # Place a limit order to avoid extreme quote filling.
                new_contract = self.securities[new_symbol]
                self.limit_order(
                    new_symbol, quantity,
                    # To avoid warnings, round the target limit price to a price that respects
                    # the minimum price variation for the Future.
                    self._get_limit_price(new_contract, new_contract.price),
                    tag=tag
                )

    def _get_limit_price(self, security, target_limit_price, round_up=True):
        parameters = GetMinimumPriceVariationParameters(security, target_limit_price)
        pip = security.price_variation_model.get_minimum_price_variation(parameters)
        return (int(target_limit_price / pip) + int(round_up)) * pip
```

### Example 2: Micro Gold vs Gold

The following example demonstrates how to use the `SymbolPropertiesDatabase` to obtain the contract multipliers of both Micro Gold and Gold Future contracts. The algorithm uses it to invest $500k of nominal value into each contract.

```python
class FutureNominalBuysAlgorithm(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)
        # Set the continuous contract mapping criteria for both Futures
        # since we want to trade the most liquid contracts.
        self._futures = []
        for ticker in [Futures.Metals.GOLD, Futures.Metals.MICRO_GOLD]:
            future = self.add_future(
                ticker,
                extended_market_hours=True,
                data_mapping_mode=DataMappingMode.OPEN_INTEREST,
                data_normalization_mode=DataNormalizationMode.BACKWARDS_RATIO,
                contract_depth_offset=0
            )
            future.set_filter(0, 180)
            self._futures.append(future)

    def on_data(self, slice: Slice) -> None:
        # Wait until we aren't invested and we have bars for all Futures.
        if (not self.portfolio.invested and
            all(future.symbol in slice.bars for future in self._futures)):
            for future in self._futures:
                # Calculate the order size for $500k. Get the quotient
                # after dividing by the contract multiplier since the
                # order size must be whole number.
                quantity = (
                    500_000
                    / future.price
                    // future.symbol_properties.contract_multiplier
                )
                if not quantity:
                    continue
                self.market_order(future.mapped, quantity)
```
