Hey, i have been attempting to create a rolling window for EMA values, that i can then use to reference back to it as a condition to enter into a trade but i have been unsuccessful. i keep getting this error:
Runtime Error: TypeError : Cannot get managed object
at OnData
PEMABelowPreviousP = previousEMA < previous_price
Can someone help?
Here is the code i'm working with.
from datetime import datetime,timedelta
PriceEqual2Slow = None
SlowEqual2Price = None
PEMABelowPreviousP = None
PEMA2BelowPreviousP2 = None
PEMA3BelowPreviousP3 = None
PEMA4BelowPreviousP4 = None
PEMAOverPreviousP = None
PEMA2OverPreviousP2 = None
PEMA3OverPreviousP3 = None
PEMA4OverPreviousP4 = None
class HipsterFluorescentPinkFrog(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2019, 1, 30) # Set Start Date
self.SetEndDate(2020, 1, 30)
self.SetCash(100000) # Set Strategy Cash
self.ticker = "EURUSD" #"USDJPY","GBPUSD", "USDCAD","EURUSD".
# Rolling Windows to hold bar close data keyed by symbol
self.Data = {}
#for self.ticker in self.tickers:
symbol = self.AddForex(self.ticker , Resolution.Hour, Market.Oanda).Symbol
self.Data[symbol] = SymbolData(self, symbol)
#self.tolerance = 0.0000
self.stopLossLevel = -0.05 # stop loss percentage
self.stopProfitLevel = 0.01# stop profit percentage
self.SetWarmUp(200, Resolution.Hour)
def OnData(self, data):
if self.IsWarmingUp: #Data to warm up the algo is being collected.
return
for symbol, symbolData in self.Data.items(): #Return the dictionary's key-value pairs:
if not (data.ContainsKey(symbol) and data[symbol] is not None and symbolData.IsReady):
continue
slowEMA = symbolData.slowema.Current.Value
#slowEMA = float(symbolData.slowWindow[0])
self.Log(f"{symbolData.slowWindow[1]} ema values ")
#sWindow = symbolData.slowWindow
previousEMA = symbolData.slowWindow[1]
previous2EMA = symbolData.slowWindow[2]
previous3EMA = symbolData.slowWindow[3]
previous4EMA = symbolData.slowWindow[4]
current_price = symbolData.closeWindow[0]
previous_price = symbolData.closeWindow[1]
previous2_price = symbolData.closeWindow[2]
previous3_price = symbolData.closeWindow[3]
previous4_price = symbolData.closeWindow[4]
if self.Portfolio[symbol].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(symbol)
self.Log(f"{self.Time} Long Position Stop Profit at {current_price}")
if condStopLoss:
self.Liquidate(symbol)
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(symbol)
self.Log(f"{self.Time} Short Position Stop Profit at {current_price}")
if condStopLoss:
self.Liquidate(symbol)
self.Log(f"{self.Time} Short Position Stop Loss at {current_price}")
if not self.Portfolio[symbol].Invested:
PriceEqual2Slow = (current_price - slowEMA) == 0.0000
SlowEqual2Price = (current_price - slowEMA) == 100.0000
PEMABelowPreviousP = previousEMA < previous_price
PEMA2BelowPreviousP2 = previous2EMA < previous2_price
PEMA3BelowPreviousP3 = previous3EMA < previous3_price
PEMA4BelowPreviousP4 = previous4EMA < previous4_price
PEMAOverPreviousP = previousEMA > previous_price
PEMA2OverPreviousP2 = previous2EMA > previous2_price
PEMA3OverPreviousP3 = previous3EMA > previous3_price
PEMA4OverPreviousP4 = previous4EMA > previous4_price
if PriceEqual2Slow and PEMAOverPreviousP and PEMA2OverPreviousP2 and PEMA3OverPreviousP3 and PEMA4OverPreviousP4:
self.SetHoldings(symbol, 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}")
if SlowEqual2Price and PEMABelowPreviousP and PEMA2BelowPreviousP2 and PEMA3BelowPreviousP3 and PEMA4BelowPreviousP4:
self.SetHoldings(symbol, -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}")
class SymbolData:
def __init__(self, algorithm, symbol):
self.slowema= ExponentialMovingAverage(200)
self.slowWindow = RollingWindow[IndicatorDataPoint](10) #setting the Rolling Window for the fast MACD indicator, takes two values
algorithm.RegisterIndicator(symbol, self.slowema, timedelta(hours=1))
self.slowema.Updated += self.SlowEMAUpdated #Updating those two values
self.closeWindow = RollingWindow[float](10)
# Add consolidator to track rolling close prices
self.consolidator = QuoteBarConsolidator(1)
self.consolidator.DataConsolidated += self.CloseUpdated
algorithm.SubscriptionManager.AddConsolidator(symbol, self.consolidator)
def SlowEMAUpdated (self, sender, updated):
'''Event holder to update the MACD Rolling Window values.'''
if self.slowema.IsReady:
self.slowWindow.Add(updated)
def CloseUpdated(self, sender, bar):
'''Event holder to update the close Rolling Window values'''
self.closeWindow.Add(bar.Close)
@property
def IsReady(self):
return self.slowWindow.IsReady and self.closeWindow.IsReady
Cole S
Hi Samwel,
Change:
To this:
I would also change the closeWindow to Decimal instead of float so they are the same. If you were to use IndicatorDataPoint you would have to call .Value when doing comparisons.
-Cole
Samwel Kibet
Thank you Cole , it worked.
Samwel Kibet
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!