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

QuantConnect

CFD Data

Introduction

The CFD Data by QuantConnect serves 51 contracts for differences (CFD). The data starts as early as May 2002 and is delivered on any frequency from tick to daily. This dataset is created by QuantConnect processing raw tick data from OANDA.

CFD data does not include ask and bid sizes.

For more information about the CFD Data dataset, including CLI commands and pricing, see the dataset listing.

About the Provider

QuantConnect was founded in 2012 to serve quants everywhere with the best possible algorithmic trading technology. Seeking to disrupt a notoriously closed-source industry, QuantConnect takes a radically open-source approach to algorithmic trading. Through the QuantConnect web platform, more than 50,000 quants are served every month.

Getting Started

The following snippet demonstrates how to request data from the CFD dataset:

self.xauusd = self.add_cfd("XAUUSD", Resolution.DAILY).symbol
_symbol = AddCfd("XAUUSD", Resolution.Daily).Symbol;

Data Summary

The following table describes the dataset properties:

PropertyValue
Start DateMixed, earliest starts May 2002
Asset Coverage51 Contracts
Data DensityDense
ResolutionTick, Second, Minute, Hour, & Daily
TimezoneMixed, in which the contract is listed*
Market HoursAlways Open, except from Friday 5 PM EST to Sunday 5 PM EST.
Index CFDs depends on the underlying market hour*

* E.g.: DE30EUR tracks DAX30 Index, which is listed in Europe/Berlin timezone.

Requesting Data

To add CFD data to your algorithm, call the AddCfdadd_cfd method. Save a reference to the CFD Symbol so you can access the data later in your algorithm.

class CfdAlgorithm (QCAlgorithm):
    def initialize(self) -> None:
        self.set_account_currency('EUR');

        self.set_start_date(2019, 2, 20)
        self.set_end_date(2019, 2, 21)
        self.set_cash('EUR', 100000)

        self.de30eur = self.add_cfd('DE30EUR').symbol

        self.set_benchmark(self.de30eur)
public class CfdAlgorithm : QCAlgorithm
{
    private Symbol _symbol;

    public override void Initialize()
    {
        SetAccountCurrency("EUR");

        SetStartDate(2019, 2, 20);
        SetEndDate(2019, 2, 21);
        SetCash("EUR", 100000);

        _symbol = AddCfd("DE30EUR").Symbol;

        SetBenchmark(_symbol);
    }
}

For more information about creating CFD subscriptions, see Requesting Data.

Accessing Data

To get the current CFD data, index the QuoteBarsquote_bars, or Ticksticks properties of the current Slice with the CFD Symbol. Slice objects deliver unique events to your algorithm as they happen, but the Slice may not contain data for your security at every time step. To avoid issues, check if the Slice contains the data you want before you index it.

def on_data(self, slice: Slice) -> None:
    if self.de30eur in slice.quote_bars:
        quote_bar = slice.quote_bars[self.de30eur]
        self.log(f"{self.de30eur} bid at {slice.time}: {quote_bar.bid.close}")

    if self.de30eur in slice.ticks:
        ticks = slice.ticks[self.de30eur]
        for tick in ticks:
            self.log(f"{self.de30eur} price at {slice.time}: {tick.price}")
public override void OnData(Slice slice)
{
    if (slice.QuoteBars.ContainsKey(_symbol))
    {
        var quoteBar = slice.QuoteBars[_symbol];
        Log($"{_symbol} bid at {slice.Time}: {quoteBar.Bid.Close}");
    }

    if (slice.Ticks.ContainsKey(_symbol))
    {
        var ticks = slice.Ticks[_symbol];
        foreach (var tick in ticks)
        {
            Log($"{_symbol} price at {slice.Time}: {tick.Price}");
        }
    }
}

You can also iterate through all of the data objects in the current Slice.

def on_data(self, slice: Slice) -> None:
    for symbol, quote_bar in slice.quote_bars.items():
        self.log(f"{symbol} bid at {slice.time}: {quote_bar.bid.close}")

    for symbol, ticks in slice.ticks.items():
        for tick in ticks:
            self.log(f"{symbol} price at {slice.time}: {tick.price}")
public override void OnData(Slice slice)
{
    foreach (var kvp in slice.QuoteBars)
    {
        var symbol = kvp.Key;
        var quoteBar = kvp.Value;
        Log($"{symbol} bid at {slice.Time}: {quoteBar.Bid.Close}");
    }

    foreach (var kvp in slice.Ticks)
    {
        var symbol = kvp.Key;
        var ticks = kvp.Value;
        foreach (var tick in ticks)
        {
            Log($"{symbol} price at {slice.Time}: {tick.Price}");
        }
    }
}

For more information about accessing CFD data, see Handling Data.

Historical Data

To get historical CFD data, call the Historyhistory method with the CFD Symbol. If there is no data in the period you request, the history result is empty.

# DataFrame
history_df = self.history(self.de30eur, 100, Resolution.MINUTE)

# QuoteBar objects
history_quote_bars = self.history[QuoteBar](self.de30eur, 100, Resolution.MINUTE)

# Tick objects
history_ticks = self.history[Tick](self.de30eur, timedelta(seconds=10), Resolution.TICK)
// QuoteBar objects 
var historyQuoteBars = History<QuoteBar>(_symbol, 100, Resolution.Minute);

// Tick objects 
var historyTicks = History<Tick>(_symbol, TimeSpan.FromSeconds(10), Resolution.Tick);

For more information about historical data, see History Requests.

Remove Subscriptions

To remove a CFD subscription, call the RemoveSecurityremove_security method.

self.remove_security(self.de30eur)
RemoveSecurity(_symbol);

The RemoveSecurityremove_security method cancels your open orders for the security and liquidates your holdings.

Supported Assets

The following table shows the available contracts:

Example Applications

The CFD price data enables you to trade CFD assets in your algorithm. Examples include the following strategies:

  • Exploring the daily worldwide news cycles with CFDs that track international indices.
  • Trading price movements of commodities with no delivery of physical goods. For example, pairs trading between gold and silver, corn and wheat, brent and crude oil, etc.

Classic Algorithm Example

The following example algorithm implements a pairs trading strategy using Gold and Silver CFDs, XAUUSD and XAGUSD, respectively. When the spread is higher than one standard deviation above its mean, the algorithm buys the spread (buy XAUUSD and sell XAGUSD). When the spread is lower than one standard deviation below its mean, it sells the spread (buy XAGUSD and sell XAUUSD).

from AlgorithmImports import *
from QuantConnect.DataSource import *

class SMAPairsTrading(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2018, 7, 1)   
        self.set_end_date(2019, 3, 31)
        self.set_cash(100000)

        # Request gold and sliver spot CFDs for trading their spread difference, assuming their spread series is cointegrated
        self.add_cfd('XAUUSD', Resolution.HOUR)
        self.add_cfd('XAGUSD', Resolution.HOUR)

        # Use 500-step mean and SD indicator on determine the spread relative difference for trading signal generation
        self.pair = [ ]
        self.spread_mean = SimpleMovingAverage(500)
        self.spread_std = StandardDeviation(500)
        
    def on_data(self, slice: Slice) -> None:
        # Update the indicator with updated spread difference, such that the an updated cointegration threshold is calculated for trade inception
        spread = self.pair[1].price - self.pair[0].price
        self.spread_mean.update(self.time, spread)
        self.spread_std.update(self.time, spread) 
        
        spread_mean = self.spread_mean.current.value
        upperthreshold = spread_mean  + self.spread_std.current.value
        lowerthreshold = spread_mean  - self.spread_std.current.value

        # If the spread is higher than upper threshold, bet their spread series will revert to mean
        if spread > upperthreshold:
            self.set_holdings(self.pair[0].symbol, 1)
            self.set_holdings(self.pair[1].symbol, -1)
        elif spread < lowerthreshold:
            self.set_holdings(self.pair[0].symbol, -1)
            self.set_holdings(self.pair[1].symbol, 1)
        # Close positions if mean reverted
        elif (self.portfolio[self.pair[0].symbol].quantity > 0 and spread < spread_mean)\
        or (self.portfolio[self.pair[0].symbol].quantity < 0 and spread > spread_mean):
            self.liquidate()
    
    def on_securities_changed(self, changes: SecurityChanges) -> None:
        self.pair = [x for x in changes.added_securities]
        
        #1. Call for 500 bars of history data for each symbol in the pair and save to the variable history
        history = self.history([x.symbol for x in self.pair], 500)
        #2. Unstack the Pandas data frame to reduce it to the history close price
        history = history.close.unstack(level=0)
        #3. Iterate through the history tuple and update the mean and standard deviation with historical data 
        for tuple in history.itertuples():
            self.spread_mean.update(tuple[0], tuple[2]-tuple[1])
            self.spread_std.update(tuple[0], tuple[2]-tuple[1])
public class GoldSilverPairsTradingAlgorithm : QCAlgorithm
{
    // Use 500-step mean and SD indicator on determine the spread relative difference for trading signal generation
    private SimpleMovingAverage _spreadMean = new SimpleMovingAverage(500);
    private StandardDeviation _spreadStd = new StandardDeviation(500);
    private Security[] _pair = new Security[2];

    public override void Initialize()
    {
        SetStartDate(2018, 7, 1);  
        SetEndDate(2019, 3, 31);  
        SetCash(100000);  

        // Request gold and sliver spot CFDs for trading their spread difference, assuming their spread series is cointegrated
        AddCfd("XAUUSD", Resolution.Hour);
        AddCfd("XAGUSD", Resolution.Hour);
    }

    public override void OnData(Slice slice) 
    {
        // Update the indicator with updated spread difference, such that the an updated cointegration threshold is calculated for trade inception
        var spread = _pair[1].Price - _pair[0].Price;
        _spreadMean.Update(Time, spread);
        _spreadStd.Update(Time, spread);
        
        var upperthreshold = _spreadMean + _spreadStd;
        var lowerthreshold = _spreadMean - _spreadStd;
        
        // If the spread is higher than upper threshold, bet their spread series will revert to mean
        if (spread > upperthreshold)
        {
            SetHoldings(_pair[0].Symbol, 1);
            SetHoldings(_pair[1].Symbol, -1);
        }
        else if (spread < lowerthreshold)
        {
            SetHoldings(_pair[0].Symbol, -1);
            SetHoldings(_pair[1].Symbol, 1);
        }
        // Close positions if mean reverted
        else if ((Portfolio[_pair[0].Symbol].Quantity > 0m && spread < _spreadMean)
        || (Portfolio[_pair[0].Symbol].Quantity < 0m && spread > _spreadMean))
        {
            Liquidate();
        }
    }
    
    public override void OnSecuritiesChanged(SecurityChanges changes)
    {    
        _pair = changes.AddedSecurities.ToArray();
        
        //1. Call for 500 days of history data for each symbol in the pair and save to the variable history
        var history = History(_pair.Select(x => x.Symbol), 500);
        
        //2. Iterate through the history tuple and update the mean and standard deviation with historical data 
        foreach(var slice in history)
        {
            var spread = slice[_pair[1].Symbol].Close - slice[_pair[0].Symbol].Close;
            _spreadMean.Update(slice.Time, spread);
            _spreadStd.Update(slice.Time, spread);
        }
    }
}

Framework Algorithm Example

The following example algorithm implements a pairs trading strategy using Gold and Silver CFDs, XAUUSD and XAGUSD, respectively. When the spread is higher than one standard deviation above its mean, the algorithm buys the spread (buy XAUUSD and sell XAGUSD). When the spread is lower than one standard deviation below its mean, it sells the spread (buy XAGUSD and sell XAUUSD).

from AlgorithmImports import *
from QuantConnect.DataSource import *

class GoldSilverPairsTradingAlgorithm (QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2018, 7, 1)   
        self.set_end_date(2019, 3, 31)
        self.set_cash(100000)
        
        self.universe_settings.resolution = Resolution.HOUR
        # Custom universe contains only gold and sliver spot CFDs for trading their spread difference, assuming their spread series is cointegrated
        self.set_universe_selection(ManualUniverseSelectionModel
        (
            [ Symbol.create(x, SecurityType.CFD, Market.OANDA) for x in ["XAUUSD", "XAGUSD"] ]
        ))
        # Custom alpha model to emit trade insights based on the gold-sliver price spread
        self.add_alpha(PairsTradingAlphaModel())
        # Equal weighting trades assuming the spread is cointegrated by 1:1 ratio
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())

class PairsTradingAlphaModel(AlphaModel):

    def __init__(self) -> None:
        # Use 500-step mean and SD indicator on determine the spread relative difference for trading signal generation
        self.pair = [ ]
        self.spread_mean = SimpleMovingAverage(500)
        self.spread_std = StandardDeviation(500)
        # Assume efficient mean reversal happens within 2 hours
        self.period = timedelta(hours=2)
        
    def update(self, algorithm: QCAlgorithm, slice: Slice) -> List[Insight]:
        # Update the indicator with updated spread difference, such that the an updated cointegration threshold is calculated for trade inception
        spread = self.pair[1].price - self.pair[0].price
        self.spread_mean.update(algorithm.time, spread)
        self.spread_std.update(algorithm.time, spread) 
        
        upperthreshold = self.spread_mean.current.value + self.spread_std.current.value
        lowerthreshold = self.spread_mean.current.value - self.spread_std.current.value

        # If the spread is higher than upper threshold, bet their spread series will revert to mean
        if spread > upperthreshold:
            return Insight.group(
                [
                    Insight.price(self.pair[0].symbol, self.period, InsightDirection.UP),
                    Insight.price(self.pair[1].symbol, self.period, InsightDirection.DOWN)
                ])
        elif spread < lowerthreshold:
            return Insight.group(
                [
                    Insight.price(self.pair[0].symbol, self.period, InsightDirection.DOWN),
                    Insight.price(self.pair[1].symbol, self.period, InsightDirection.UP)
                ])

        return []
    
    def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:
        self.pair = [x for x in changes.added_securities]
        
        #1. Call for 500 bars of history data for each symbol in the pair and save to the variable history
        history = algorithm.history([x.symbol for x in self.pair], 500)
        #2. Unstack the Pandas data frame to reduce it to the history close price
        history = history.close.unstack(level=0)
        #3. Iterate through the history tuple and update the mean and standard deviation with historical data 
        for tuple in history.itertuples():
            self.spread_mean.update(tuple[0], tuple[2]-tuple[1])
            self.spread_std.update(tuple[0], tuple[2]-tuple[1])
public class GoldSilverPairsTradingAlgorithm : QCAlgorithm
{
    public override void Initialize()
    {
        SetStartDate(2018, 7, 1);  
        SetEndDate(2019, 3, 31);  
        SetCash(100000);  

        UniverseSettings.Resolution = Resolution.Hour;
        // Custom universe contains only gold and sliver spot CFDs for trading their spread difference, assuming their spread series is cointegrated
        SetUniverseSelection(new ManualUniverseSelectionModel
        (
            new [] {"XAUUSD", "XAGUSD"}
                .Select(x => QuantConnect.Symbol.Create(x, SecurityType.Cfd, Market.Oanda))
        ));
        // Custom alpha model to emit trade insights based on the gold-sliver price spread
        AddAlpha(new PairsTradingAlphaModel());
        // Equal weighting trades assuming the spread is cointegrated by 1:1 ratio
        SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel()); 
    }
}

public partial class PairsTradingAlphaModel : AlphaModel
{
    // Use 500-step mean and SD indicator on determine the spread relative difference for trading signal generation
    private SimpleMovingAverage _spreadMean = new SimpleMovingAverage(500);
    private StandardDeviation _spreadStd = new StandardDeviation(500);
    // Assume efficient mean reversal happens within 2 hours
    private TimeSpan _period = TimeSpan.FromHours(2);
    private Security[] _pair = new Security[2];

    public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice slice) 
    {
        // Update the indicator with updated spread difference, such that the an updated cointegration threshold is calculated for trade inception
        var spread = _pair[1].Price - _pair[0].Price;
        _spreadMean.Update(algorithm.Time, spread);
        _spreadStd.Update(algorithm.Time, spread);
        
        var upperthreshold = _spreadMean + _spreadStd;
        var lowerthreshold = _spreadMean - _spreadStd;

        // If the spread is higher than upper threshold, bet their spread series will revert to mean
        if (spread > upperthreshold)
        {
            return Insight.Group( 
                Insight.Price(_pair[0].Symbol, _period, InsightDirection.Up),
                Insight.Price(_pair[1].Symbol, _period, InsightDirection.Down)
            );
        }
        else if (spread < lowerthreshold)
        {
            return Insight.Group( 
                Insight.Price(_pair[0].Symbol, _period, InsightDirection.Down), 
                Insight.Price(_pair[1].Symbol, _period, InsightDirection.Up) 
            );
        }

        return Enumerable.Empty<Insight>();
    }
    
    public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
    {    
        _pair = changes.AddedSecurities.ToArray();
        
        //1. Call for 500 days of history data for each symbol in the pair and save to the variable history
        var history = algorithm.History(_pair.Select(x => x.Symbol), 500);
        
        //2. Iterate through the history tuple and update the mean and standard deviation with historical data 
        foreach (var slice in history)
        {
            var spread = slice[_pair[1].Symbol].Close - slice[_pair[0].Symbol].Close;
            _spreadMean.Update(slice.Time, spread);
            _spreadStd.Update(slice.Time, spread);
        }
    }
}

Data Point Attributes

The CFD dataset provides QuoteBar and Tick objects.

QuoteBar Attributes

QuoteBar objects have the following attributes:

Tick Attributes

Tick objects have the following attributes:

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: