class MondayForexCIIAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2007, 1, 1) # Set Start Date
self.SetCash(100000) # Set Strategy Cash
# add currency pair EUR/USD
self.symbol = self.AddForex("EURUSD", Resolution.Hour, Market.FXCM).Symbol
# parameters
self.CCIPeriod = 30 # CCI period
self.CCIupperBound = 100 # CCI upper bound line
self.CCIlowerBound = -100 # CCI lower bound line
self.stopLossLevel = -0.05 # stop loss percentage
self.stopProfitLevel = 0.01 # stop profit percentage
# Commodity Channel Index (https://en.wikipedia.org/wiki/Commodity_channel_index)
self.cci = self.CCI(self.symbol, self.CCIPeriod, MovingAverageType.Simple, Resolution.Daily)
def OnData(self, data):
# get current price of EURUSD
current_price = data[self.symbol.Value].Close
### Stop loss/profit
if self.Portfolio.Invested:
if self.isLong:
condStopProfit = (current_price - self.buyInPrice)/self.buyInPrice > self.stopProfitLevel
condStopLoss = (current_price - self.buyInPrice)/self.buyInPrice < self.stopLossLevel
if condStopProfit:
self.Liquidate(self.symbol.Value)
self.Log(f"{self.Time} Long Position Stop Profit at {current_price}")
if condStopLoss:
self.Liquidate(self.symbol.Value)
self.Log(f"{self.Time} Long Position Stop Loss at {current_price}")
else:
condStopProfit = (self.sellInPrice - current_price)/self.sellInPrice > self.stopProfitLevel
condStopLoss = (self.sellInPrice - current_price)/self.sellInPrice < self.stopLossLevel
if condStopProfit:
self.Liquidate(self.symbol.Value)
self.Log(f"{self.Time} Short Position Stop Profit at {current_price}")
if condStopLoss:
self.Liquidate(self.symbol.Value)
self.Log(f"{self.Time} Short Position Stop Loss at {current_price}")
### On Monday
if self.Time.weekday() == 0 and not self.Portfolio.Invested:
# get current value of CCI
CCI = self.cci.Current.Value
# enter long position if CCI is over UpperBound
if CCI > self.CCIupperBound:
self.SetHoldings(self.symbol.Value, 1)
# get buy-in price for trailing stop loss/profit
self.buyInPrice = current_price
# entered long position
self.isLong = True
self.Log(f"{self.Time} Entered Long Position at {current_price}")
# enter short position if CCI is under LowerBound
if CCI < self.CCIlowerBound:
self.SetHoldings(self.symbol.Value, -1)
# get sell-in price for trailing stop loss/profit
self.sellInPrice = current_price
# entered short position
self.isLong = False
self.Log(f"{self.Time} Entered Short Position at {current_price}")