book
Checkout our new book! Hands on AI Trading with Python, QuantConnect, and AWS Learn More arrow

CFD

Handling Data

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 QuoteBars DataDictionary is made up of QuoteBar objects. To access individual data points in the dictionary, you can index the dictionary with the CFD ticker or symbol, but we recommend you use the symbol.

To view the resolutions that are available for CFD data, see Resolutions.

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

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

Select Language:
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.

Select Language:
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 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 CFD. A quote tick is an offer to buy or sell the CFD 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 CFD doesn't actively trade or you are in the same time step as when you added the CFD subscription, the Slice may not contain data for your symbol. To avoid issues, check if the Slice contains data for your CFD before you index the Slice with the CFD symbol.

Select Language:
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.

Select Language:
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:

Examples

The following examples demonstrate common practices for handling CFD data.

Example 1: Buy And Hold

The following algorithm is a buy-and-hold strategy on the DE30EUR CFD contract. We only place orders when quote data is available to avoid stale fills. Also, we set the algorithm time zone to Berlin and the account currency to Euros for a more convenient comparison.

Select Language:
class CfdExampleAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 1, 1)
        self.set_end_date(2025, 1, 1)
        # Set the timezone as Berlin to conveniently compare the data.
        self.set_time_zone(TimeZones.BERLIN)
        # Set the account currency to EUR to trade the DAX CFD.
        self.set_account_currency("EUR", 10000)
        # Request the CFD data to trade.
        self._dax = self.add_cfd("DE30EUR").symbol

    def on_data(self, slice: Slice) -> None:
        # Trade based on updated data; CFDs only have quote data.
        bar = slice.quote_bars.get(self._dax)
        if bar:
            # Buy and hold DAX CFD.
            if not self.portfolio[self._dax].is_long:
                self.set_holdings(self._dax, 0.5)

Example 2: Global Indices

The following algorithm buys and holds various Index CFDs that trade in different market hours and currencies during their opening hours.

Select Language:
class CfdExampleAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 1, 1)
        self.set_end_date(2025, 1, 1)
        
        # Request the CFD data to trade.
        # We include CFD contracts that trade in different market hours to stay in the market.
        self._dax = self.add_cfd("DE30EUR").symbol
        self._sgx = self.add_cfd("SG30SGD").symbol
        self._dow = self.add_cfd("US30USD").symbol

        # Set scheduled events to hold each CFD contract in their market opening hours.
        # Buy and hold after the market opens.
        self.schedule.on(
            self.date_rules.every_day(self._dax),
            self.time_rules.after_market_open(self._dax, 1),
            lambda: self.set_holdings(self._dax, 0.3)
        )
        self.schedule.on(
            self.date_rules.every_day(self._sgx),
            self.time_rules.after_market_open(self._sgx, 1),
            lambda: self.set_holdings(self._sgx, 0.3)
        )
        self.schedule.on(
            self.date_rules.every_day(self._dow),
            self.time_rules.after_market_open(self._dow, 1),
            lambda: self.set_holdings(self._dow, 0.3)
        )
        # Liquidate before market close.
        self.schedule.on(
            self.date_rules.every_day(self._dax),
            self.time_rules.before_market_close(self._dax, 1),
            lambda: self.liquidate(self._dax)
        )
        self.schedule.on(
            self.date_rules.every_day(self._sgx),
            self.time_rules.before_market_close(self._sgx, 1),
            lambda: self.liquidate(self._sgx)
        )
        self.schedule.on(
            self.date_rules.every_day(self._dow),
            self.time_rules.before_market_close(self._dow, 1),
            lambda: self.liquidate(self._dow)
        )

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: