import numpy as np
import pandas as pd
from scipy import stats
from math import floor
from datetime import timedelta
import datetime
class SpreadTrading(QCAlgorithm):
def Initialize(self):
self.SetTimeZone('Europe/Berlin')
self.SetCash(50000) # Set Strategy Cash
self.SetStartDate(2018, 8, 1) # Set Start Date
self.SetEndDate(2019, 9, 30) # Set End Date
self.training_period = 50
self.threshold = 3
self.offset = 3
# add used assets
tickers = ['EUR_USD', 'XAU_USD']
self.assets = []
for i in tickers:
self.assets.append(self.AddSecurity(SecurityType.Cfd, i, Resolution.Minute).Symbol)
# data used to train de algo to generate signals
for i in self.assets:
i.hist_window = RollingWindow[QuoteBar](self.training_period)
def OnData(self, data):
if not (data.ContainsKey('EUR_USD') and data.ContainsKey('XAU_USD')):
return
# add the new data to de history
for sym in self.assets:
sym.hist_window.Add(data[sym])
price_x = pd.Series([float(i.Close) for i in self.assets[0].hist_window], index = [i.Time for i in self.assets[0].hist_window])
price_y = pd.Series([float(i.Close) for i in self.assets[1].hist_window], index = [i.Time for i in self.assets[1].hist_window])
if len(price_x) < self.training_period:
return
spread_price = 1000 * price_x - 1* price_y
if (spread_price[-self.offset] - spread_price) < -self.threshold:
self.MarketOrder(self.assets[1], -2)
self.MarketOrder(self.assets[0], -1)
elif (spread_price[-self.offset] - spread_price) > self.threshold:
self.MarketOrder(self.assets[1], 2)
self.MarketOrder(self.assets[0], 1)
else:
self.Liquidate(self.assets[0])
self.Liquidate(self.assets[1])
I am trying to get the above code to work.
For given thresholds, I want to take simultaneous positions in both instruments.
After opening the trades, I want to close them after a certain amount of time (baseline timestamp of position opening) or a certain threshold of running pnl (on the spread). [This has so far not been implemented in the code, as I am unsure how best to do it].
Yet, the code, as is, is not working either,
It seems like the OnData() handler is not being executed.
I, on my part, am out of ideas so far, though.
Any help and hints would be greatly appreciated.
I would also be willing to collaborate on this project as well as further ones.
Can I trade that through OANDA?
Rahul Chowdhury
Hey Max,
OnData isn't being called because the securities haven't been properly added.First, the tickers for XAUUSD and EURUSD don't contain an underscores.
You can add Cfds with the AddCfd method.
self.AddCfd("XAUUSD", Resolution.Minute, Market.Oanda).Symbol
You can enable the Oanda brokerage model, which determines the fees and leverage associated with that brokerage for backtesting. Live trading with Oanda is also available.
Also, since EURUSD is a forex symbol you need to add it using AddForex.
self.AddForex("EURUSD", Resolution.Minute, Market.Oanda).Symbol
We noticed that you also asked this question in support. Please try not to duplicate questions.
Max Amir
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!