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?

Author