---
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/crypto-futures/handling-data
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/crypto-futures/handling-data.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/03%20Securities/99%20Asset%20Classes/04%20Crypto%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) > [Crypto Futures](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/crypto-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 security ticker or `symbol`, but we recommend you use the `symbol`.

To view the resolutions that are available for Crypto Futures data, see [Resolutions](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/crypto-futures/requesting-data.md#04-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 security `symbol`. If the security doesn't actively trade or you are in the same time step as when you added the security subscription, the `Slice` may not contain data for your `symbol`. To avoid issues, check if the `Slice` contains data for your security before you index the `Slice` with the security `symbol`.

```python
def on_data(self, slice: Slice) -> None:
    # Obtain the mapped TradeBar of the symbol if any
    trade_bar = slice.bars.get(self._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 security `symbol`. If the security doesn't actively get quotes or you are in the same time step as when you added the security subscription, the `Slice` may not contain data for your `symbol`. To avoid issues, check if the `Slice` contains data for your security before you index the `Slice` with the security `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._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 security. A quote tick is an offer to buy or sell the security 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 security doesn't actively trade or you are in the same time step as when you added the security subscription, the `Slice` may not contain data for your `symbol`. To avoid issues, check if the `Slice` contains data for your security before you index the `Slice` with the security `symbol`.

```python
def on_data(self, slice: Slice) -> None:
    ticks = slice.ticks.get(self._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*

## Margin Interest Rates

`MarginInterestRate` objects contain the margin interest rate, which is a cost associated with trading on margin. To get the `MarginInterestRate` objects in the `Slice`, index the `margin_interest_rates` property of the `Slice` with the Crypto Future `Symbol`. The `margin_interest_rates` property of the `Slice` may not contain data for your `Symbol`. To avoid issues, check if the property contains data for your Crypto Future before you index it with the Crypto Future `Symbol`.

```python
def on_data(self, slice: Slice) -> None:
    margin_interest_rate = slice.margin_interest_rates.get(self._symbol)
    if margin_interest_rate:
        interest_rate = margin_interest_rate.interest_rate
```

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

```python
def on_data(self, slice: Slice) -> None:
    for symbol, margin_interest_rate in slice.margin_interest_rates.items():
        interest_rate = margin_interest_rate.interest_rate
```

`MarginInterestRate` objects have the following properties:

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

## Examples

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

### Example 1: Adjust Holdings on Margin Payments

Perpetual futures have a mechanism called **funding** , where if you're holding a position at certain times (the funding timestamp), you might have to pay or receive funding based on the difference between the perpetual contract price and the spot price. This example demonstrates how to adjust your position in Crypto Future based on the funding rate. The funding is settled in the quote currency, which is USDT in this case. When you receive USDT, the algorithm increases its position size in BTCUSDT. When you pay USDT, the algorithm decreases its position size.

```python
class CryptoFutureAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        # Set brokerage and account type to match your brokerage environment for accurate fee and margin behavior.
        self.set_brokerage_model(BrokerageName.BINANCE, AccountType.MARGIN)
        # In the Binance brokerage, you can't trade with USD.
        # Set the account currency as USDT and add the starting cash.
        self.set_account_currency("USDT", 1000000)
        # Subscribe to the BTCUSDT perpetual Future contract.
        btcusdt = self.add_crypto_future("BTCUSDT")
        self._symbol = btcusdt.symbol
        # Save the lot size to avoid order errors.
        self._lot_size = btcusdt.symbol_properties.lot_size
        # Set the starting BTC balance to 10.
        btcusdt.base_currency.set_amount(10)
        # Create a member to track the current day.
        self._day = -1

    def on_data(self, slice: Slice) -> None:
        # Only place orders when the market is open since market on open orders aren't supported.
        if not self.portfolio.invested and self.is_market_open(self._symbol):
            # Open a long position in the perpetual Crypto Future.
            self.market_order(self._symbol, 10)
        # Only run the following logic once per day.
        if self._day == self.time.day:
            return
        # Get the current margin interest rate.
        interest_rate = slice.margin_interest_rates.get(self._symbol)
        if not interest_rate:
            return
        # Calculate the funding payment.
        holding = self.portfolio[self._symbol]
        position_value = holding.get_quantity_value(holding.quantity).amount
        interest_rate = slice.margin_interest_rates[self._symbol].interest_rate
        funding = interest_rate * position_value / holding.security.price
        # Increase/decrease the position size based on the funding payment.
        quantity = -funding // self._lot_size * self._lot_size
        if quantity:
            self.market_order(self._symbol, quantity)
            # Plot the portfolio state.
            self.plot("CashBook", "USDT", self.portfolio.cash_book['USDT'].amount)
            self.plot("CashBook", "BTC", self.portfolio.cash_book['BTC'].amount)
            self.plot("Quantity", "BTCUSDT", self.portfolio[self._symbol].quantity)
        self._day = self.time.day
```

### Example 2: Future-Spot Arbitrage

Long-short arbitrage involves simultaneously trading BTCUSDT in the spot market and BTCUSDT Futures with the same size but in the opposite direction. The following algorithm monitors the spread between these markets. If the spot price exceeds the Future price by a threshold, it shorts the spot market and buys the Future contract (and vice vera for the other way around), assuming their discrepancies will be wiped out within a short period due to market efficiency. It closes the positions after the spread inverts.

```python
class CryptoFutureArbitrageAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        # Set brokerage and account type to match your brokerage
        # environment for accurate fee and margin behavior.
        self.set_brokerage_model(BrokerageName.BINANCE, AccountType.MARGIN)
        # In the Binance brokerage, you can't trade with USD.
        # Set the account currency to USDT and add the starting cash.
        self.set_account_currency("USDT", 50_000_000)
        # Add the BTCUSDT spot and Futures markets.
        self._spot = self.add_crypto(
            "BTCUSDT", fill_forward=False, market=Market.BINANCE
        )
        self._future = self.add_crypto_future(
            "BTCUSDT", fill_forward=False, market=Market.BINANCE
        )
        self._multiplier = self._future.symbol_properties.contract_multiplier
        self._threshold = 1.005  # 0.5%

    def on_data(self, slice: Slice) -> None:
        # Wait for there to be a TradeBar for each asset, so we know
        # the prices are up-to-date.
        for security in [self._spot, self._future]:
            if security.symbol not in slice.bars:
                return
        spot = self._spot.price
        future = self._future.price
        # Buy low sell high: If one's price is above another by the
        # set threshold, sell it and buy the other security. The
        # threshold ensures there is enough profit potential to overcome
        # the fees and slippage. Make sure to equalize the actual order
        # size with the contract multiplier.
        if not self._spot.invested:
            if spot >= future * self._threshold:
                self._enter(-1, 1)
            elif future >= spot * self._threshold:
                self._enter(1, -1)
            return
        # When the mispricing converges, close both positions to earn
        # the spread.
        if ((self._spot.holdings.is_short and spot < future) or
            (self._spot.holdings.is_long and spot > future)):
            # Liquidate the spot position.
            quantity = min(
                self._spot.holdings.quantity,
                self._spot.base_currency.amount
            )
            if quantity < 0:
                quantity /= (1 - 0.001)  # To cover the taker fees.
            lot_size = self._spot.symbol_properties.lot_size
            quantity = -round(quantity / lot_size) * lot_size
            self.market_order(self._spot.symbol, quantity, tag='Liquidate Spot')
            # Liquidate the Future position.
            self.liquidate(self._future.symbol, tag='Liquidate Future')

    def _enter(self, spot_sign, future_sign):
        quantity = self.calculate_order_quantity(self._future.symbol, 0.5)
        if not quantity:
            return
        # Enter the spot position.
        spot_quantity = spot_sign * quantity * self._multiplier
        self.market_order(self._spot.symbol, spot_quantity, tag='Spot')
        # Enter the Future position.
        self.market_order(self._future, future_sign * quantity, tag='Future')
```
