Crypto Futures
Handling Data
Introduction
LEAN passes the data you request to the OnData
on_data
method so you can make trading decisions. The default OnData
on_data
method accepts a Slice
object, but you can define additional OnData
on_data
methods that accept different data types. For example, if you define an OnData
on_data
method that accepts a TradeBar
argument, it only receives TradeBar
objects. The Slice
object that the OnData
on_data
method receives groups all the data together at a single moment in time. To access the Slice
outside of the OnData
on_data
method, use the CurrentSlice
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
symbol
, but we recommend you use the Symbol
symbol
.
To view the resolutions that are available for Crypto 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.
To get the TradeBar
objects in the Slice
, index the Slice
or index the Bars
bars
property of the Slice
with the security Symbol
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
symbol
. To avoid issues, check if the Slice
contains data for your security before you index the Slice
with the security Symbol
symbol
.
public override void OnData(Slice slice) { if (slice.Bars.ContainsKey(_symbol)) { var tradeBar = slice.Bars[_symbol]; } }
def on_data(self, slice: Slice) -> None: 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.
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 on_data(self, slice: Slice) -> None: for symbol, trade_bar in slice.bars.items(): close_price = trade_bar.close
TradeBar
objects have the following properties:
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
open
, High
high
, Low
low
, and Close
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
open
, High
high
, Low
low
, and Close
close
properties of the QuoteBar
copy the values of either the Bid
bid
or Ask
ask
instead of taking their mean.
To get the QuoteBar
objects in the Slice
, index the QuoteBars
property of the Slice
with the security Symbol
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
symbol
. To avoid issues, check if the Slice
contains data for your security before you index the Slice
with the security Symbol
symbol
.
public override void OnData(Slice slice) { if (slice.QuoteBars.ContainsKey(_symbol)) { var quoteBar = slice.QuoteBars[_symbol]; } }
def on_data(self, slice: Slice) -> None: 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.
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 on_data(self, slice: Slice) -> None: 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 to make backtest results more realistic.
QuoteBar
objects have the following properties:
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
quantity
and Price
price
properties, but they have a zero value for the BidPrice
bid_price
, BidSize
bid_size
, AskPrice
ask_price
, and AskSize
ask_size
properties. Quote ticks have non-zero values for BidPrice
bid_price
and BidSize
bid_size
properties or have non-zero values for AskPrice
ask_price
and AskSize
ask_size
properties. To check if a tick is a trade or a quote, use the TickType
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
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
symbol
. To avoid issues, check if the Slice
contains data for your security before you index the Slice
with the security Symbol
symbol
.
public override void OnData(Slice slice) { if (slice.Ticks.ContainsKey(_symbol)) { var ticks = slice.Ticks[_symbol]; foreach (var tick in ticks) { var price = tick.Price; } } }
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>
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 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:
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 MarginInterestRates
margin_interest_rates
property of the Slice
with the Crypto Future Symbol
.
The MarginInterestRates
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
.
public override void OnData(Slice slice) { if (slice.MarginInterestRates.TryGetValue(_symbol, out var marginInterestRate)) { var interestRate = marginInterestRate.InterestRate; } }
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 MarginInterestRates
margin_interest_rates
dictionary. The keys of the dictionary are the Symbol
objects and the values are the MarginInterestRate
margin_interest_rate
objects.
public override void OnData(Slice slice) { foreach (var (symbol, marginInterestRate) in slice.MarginInterestRates) { var interestRate = marginInterestRate.InterestRate; } }
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:
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.
public class CryptoFutureAlgorithm : QCAlgorithm { private Symbol _symbol; private decimal _lotSize; private int _day = -1; public override void Initialize() { SetStartDate(2020, 4, 1); SetEndDate(2024, 10, 1); // Set brokerage and account type to match your brokerage environment for accurate fee and margin behavior. SetBrokerageModel(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. SetAccountCurrency("USDT", 1000000); // Subscribe to the BTCUSDT perpetual Future contract. var btcusdt = AddCryptoFuture("BTCUSDT"); _symbol = btcusdt.Symbol; // Save the lot size to avoid order errors. _lotSize = btcusdt.SymbolProperties.LotSize; // Set the starting BTC balance to 10. btcusdt.BaseCurrency.SetAmount(10); } public override void OnData(Slice slice) { // Only place orders when the market is open since market on open orders aren't supported. if (!Portfolio.Invested && IsMarketOpen(_symbol)) { // Open a long position in the perpetual Crypto Future. MarketOrder(_symbol, 10); } // Only run the following logic once per day. if (_day == Time.Day) { return; } // Get the current margin interest rate. MarginInterestRate interestRate; if (!slice.MarginInterestRates.TryGetValue(_symbol, out interestRate)) { return; } // Calculate the funding payment. var holding = Portfolio[_symbol]; var positionValue = holding.GetQuantityValue(holding.Quantity).Amount; var funding = interestRate.InterestRate * positionValue / holding.Price; // Increase/decrease the position size based on the funding payment. var quantity = -(int)(funding / _lotSize) * _lotSize; if (quantity != 0) { MarketOrder(_symbol, quantity); // Plot the portfolio state. Plot("CashBook", "USDT", Portfolio.CashBook["USDT"].Amount); Plot("CashBook", "BTC", Portfolio.CashBook["BTC"].Amount); Plot("Quantity", "BTCUSDT", Portfolio[_symbol].Quantity); } _day = Time.Day; } }
class CryptoFutureAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2020, 4, 1) self.set_end_date(2024, 10, 1) # 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 Arbitration
Long-short arbitrage involves simultaneously trading BTCUSD in the spot market and BTCUSD futures with the same size. If the spot price exceed the front-month future price by a threshold, we short the spot and buy the future, assuming their discrepancies will be wiped out within a short period due to market efficiency. Vice versa for the other way around. Positions will be closed after the price gap bounced back.
public class CryptoFutureAlgorithm : QCAlgorithm { private Symbol _spot; private Symbol _future; public override void Initialize() { // Set brokerage and account type to match your brokerage environment for accurate fee and margin behavior. SetBrokerageModel(BrokerageName.Binance, AccountType.Margin); // In Binance brokerage, USD is not a valid currency to trade or automatically convertable. // Thus, we need to set account currency as USDT and add the starting cash. SetAccountCurrency("USDT", 1000); // Add subscription of BTC-USD Futures and spot crypto with specific market to ensure the correct securities are selected. _future = AddCryptoFuture("BTCUSDT", market: Market.Binance).Symbol; _spot = AddCrypto("BTCUSDT", market: Market.Binance).Symbol; } public override void OnData(Slice slice) { // Only compare the most updated price if both spot and future are available to ensure fair comparison for arbitration. if (slice.Bars.ContainsKey(_spot) && slice.Bars.ContainsKey(_future)) { var spotPrice = slice.Bars[_spot].Price; var futurePrice = slice.Bars[_future].Price; // To provide sufficient profit margin to overcome fee and slippage, a threshold of 0.5% is set. // Buy low sell high: if one's price is above another by the set threshold, sell it and buy the other security. if (spotPrice >= futurePrice * 1.005m) { SetHoldings(_spot, -0.25m); SetHoldings(_future, 0.25m); } else if (spotPrice * 1.005m <= futurePrice) { SetHoldings(_spot, 0.25m); SetHoldings(_future, -0.25m); } // When the mispricing converges, close both positions to earn the spread. else if ((Portfolio[_spot].Quantity < 0 && spotPrice < futurePrice) || (Portfolio[_spot].Quantity > 0 && spotPrice > futurePrice)) { Liquidate(); } } } }
class CryptoFutureAlgorithm(QCAlgorithm): def initialize(self) -> None: # 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 Binance brokerage, USD is not a valid currency to trade or automatically convertable. # Thus, we need to set account currency as USDT and add the starting cash. self.set_account_currency("USDT", 1000) # Add subscription of BTC-USD Futures and spot crypto with specific market to ensure the correct securities are selected. self._future = self.add_crypto_future("BTCUSDT", market=Market.BINANCE).symbol self._spot = self.add_crypto("BTCUSDT", market=Market.BINANCE).symbol def on_data(self, slice: Slice) -> None: # Only compare the most updated price if both spot and future are available to ensure fair comparison for arbitration. if self._spot in slice.bars and self._future in slice.bars: spot_price = slice.bars[self._spot].price future_price = slice.bars[self._future].price # To provide sufficient profit margin to overcome fee and slippage, a threshold of 0.5% is set. # Buy low sell high: if one's price is above another by the set threshold, sell it and buy the other security. if spot_price >= future_price * 1.005: self.set_holdings(self._spot, -0.25) self.set_holdings(self._future, 0.25) elif spot_price * 1.005 <= future_price: self.set_holdings(self._spot, 0.25) self.set_holdings(self._future, -0.25) # When the mispricing converges, close both positions to earn the spread. elif (self.portfolio[self._spot].quantity < 0 and spot_price < future_price)\ or (self.portfolio[self._spot].quantity > 0 and spot_price > future_price): self.liquidate()