Futures

Handling Data

Introduction

LEAN passes the data you request to the OnDataon_data method so you can make trading decisions. The default OnDataon_data method accepts a Slice object, but you can define additional OnDataon_data methods that accept different data types. For example, if you define an OnDataon_data method that accepts a TradeBar argument, it only receives TradeBar objects. The Slice object that the OnDataon_data method receives groups all the data together at a single moment in time. To access the Slice outside of the OnDataon_data method, use the CurrentSlicecurrent_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.

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

TradeBar objects have the following properties:

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.

public override void OnData(Slice slice)
{
    if (slice.Bars.ContainsKey(_contractSymbol))
    {
        var tradeBar = slice.Bars[_contractSymbol];
    }
}
def OnData(self, slice: Slice) -> None:
    if self.contract_symbol in slice.Bars:
        trade_bar = slice.Bars[self.contract_symbol]

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

public override void OnData(Slice slice)
{
    foreach (var kvp in slice.Bars)
    {
        var symbol = kvp.Key;
        var tradeBar = kvp.Value;
        var closePrice = tradeBar.Close;
    }
}
def OnData(self, slice: Slice) -> None:
    for symbol, trade_bar in slice.Bars.items():
        close_price = trade_bar.Close

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

QuoteBar objects have the following properties:

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.

public override void OnData(Slice slice)
{
    if (slice.QuoteBars.ContainsKey(_contractSymbol))
    {
        var quoteBar = slice.QuoteBars[_contractSymbol];
    }
}
def OnData(self, slice: Slice) -> None:
    if self.contract_symbol in slice.QuoteBars:
        quote_bar = slice.QuoteBars[self.contract_symbol]

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

public override void OnData(Slice slice)
{
    foreach (var kvp in slice.QuoteBars)
    {
        var symbol = kvp.Key;
        var quoteBar = kvp.Value;
        var askPrice = quoteBar.Ask.Close;
    }
}
def OnData(self, slice: Slice) -> None:
    for symbol, quote_bar in slice.QuoteBars.items():
        ask_price = quote_bar.Ask.Close

QuoteBar objects let LEAN incorporate spread costs into your simulated trade fills to make backtest results more realistic.

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. Tick objects have the following properties:

Trade ticks have a non-zero value for the Quantity and Price properties, but they have a zero value for the BidPrice, BidSize, AskPrice, and AskSize properties. Quote ticks have non-zero values for BidPrice and BidSize properties or have non-zero values for AskPrice and AskSize 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.

public override void OnData(Slice slice)
{
    if (slice.Ticks.ContainsKey(_contractSymbol))
    {
        var ticks = slice.Ticks[_contractSymbol];
        foreach (var tick in ticks)
        {
            var price = tick.Price;
        }
    }
}
def OnData(self, slice: Slice) -> None:
    if self.contract_symbol in slice.Ticks:
        ticks = slice.Ticks[self.contract_symbol]
        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>list[Tick] objects.

public override void OnData(Slice slice)
{
    foreach (var kvp in slice.Ticks)
    {
        var symbol = kvp.Key;
        var ticks = kvp.Value;
        foreach (var tick in ticks)
        {
            var price = tick.Price;
        }
    }
}
def OnData(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.

Futures Chains

FuturesChain objects represent an entire chain of contracts for a single underlying Future. They have the following properties:

To get the FuturesChain, index the FuturesChains property of the Slice with the continuous contract Symbol.

public override void OnData(Slice slice)
{
    if (slice.FuturesChains.TryGetValue(_contractSymbol.Canonical, out var chain))
    {
        var contracts = chain.Contracts;
    }
}
def OnData(self, slice: Slice) -> None:
    chain = slice.FuturesChains.get(self.contract_symbol.Canonical)
    if chain:
        contracts = chain.Contracts

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

public override void OnData(Slice slice)
{
    foreach (var kvp in slice.FuturesChains)
    {
        var continuousContractSymbol = kvp.Key;
        var chain = kvp.Value;
        var contracts = chain.Contracts;
    }
}

public void OnData(FuturesChains futuresChains)
{
    foreach (var kvp in futuresChains)
    {
        var continuousContractSymbol = kvp.Key;
        var chain = kvp.Value;
        var contracts = chain.Contracts;
    }
}
def OnData(self, slice: Slice) -> None:
    for continuous_contract_symbol, chain in slice.FuturesChains.items():
        contracts = chain.Contracts

Futures Contracts

FuturesContract objects represent the data of a single Futures contract in the market. They have the following properties:

To get the Futures contracts in the Slice, use the Contracts property of the FuturesChain.

public override void OnData(Slice slice)
{
    if (slice.FuturesChains.TryGetValue(_contractSymbol.Canonical, out var chain))
    {
        if (chain.Contracts.TryGetValue(_contractSymbol, out var contract))
        {
            var price = contract.LastPrice;
        }
    }
}

public void OnData(FuturesChains futuresChains)
{
    if (futuresChains.TryGetValue(_contractSymbol.Canonical, out var chain))
    {
        if (chain.Contracts.TryGetValue(_contractSymbol, out var contract))
        {
            var price = contract.LastPrice;
        }
    }
}
def OnData(self, slice: Slice) -> None:
    chain = slice.FuturesChains.get(self.contract_symbol.Canonical)
    if chain:
        contract = chain.Contracts.get(self.contract_symbol)
        if contract:
            price = contract.LastPrice

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 OpenInterest property of the Future or FutureContract.

public override void OnData(Slice slice)
{
    if (slice.FuturesChains.TryGetValue(_contractSymbol.Canonical, out var chain))
    {
        if (chain.Contracts.TryGetValue(_contractSymbol, out var contract))
        {
            var openInterest = contract.OpenInterest;
        }
    }
}

def OnData(self, slice: Slice) -> None:
    chain = slice.FuturesChains.get(self.contract_symbol.Canonical)
    if chain:
        contract = chain.Contracts.get(self.contract_symbol)
        if contract:
            open_interest = contract.OpenInterest

Symbol Changes

When the continuous contract rolls over, LEAN passes a SymbolChangedEvent to your OnDataon_data method, which contains the old contract Symbol and the new contract Symbol. SymbolChangedEvent objects have the following properties:

To get the SymbolChangedEvent, use the SymbolChangedEvents property of the Slice. You can use SymbolChangedEvents to roll over contracts.

public override void OnData(Slice slice)
{
    foreach (var (symbol, changedEvent) in slice.SymbolChangedEvents)
    {
        var oldSymbol = changedEvent.OldSymbol;
        var newSymbol = changedEvent.NewSymbol;
        var tag = $"Rollover - Symbol changed at {Time}: {oldSymbol} -> {newSymbol}";
        var quantity = Portfolio[oldSymbol].Quantity;
        // Rolling over: to liquidate any position of the old mapped contract and switch to the newly mapped contract
        Liquidate(oldSymbol, tag: tag);
        if (quantity != 0) MarketOrder(newSymbol, quantity, tag: tag);
        Log(tag);
    }
}
def OnData(self, slice: Slice) -> None:
    for symbol, changed_event in  slice.SymbolChangedEvents.items():
        old_symbol = changed_event.OldSymbol
        new_symbol = changed_event.NewSymbol
        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(old_symbol, tag = tag)
        if quantity != 0: self.MarketOrder(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.

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: