I am trying to create an algo that trades breakouts. If the 5min bar closes above the set resistance point (just using arbitrary highs as of now) then I buy. I keep getting an error on the rolling window. It will not let me save the backtest but the error is:
During the algorithm initialization, the following exception has occurred: TypeError : type(s) expected
at Initialize
self.rollingWindow = RollingWindow[TradeBar][1]
===
at Python.Runtime.PyObject.Invoke(PyTuple args in main.py: line 17
TypeError : type(s) expected
# notes
# for charts. the charts lag to it might not be beneficial to actually use this information.
from System.Drawing import Color
class ParticleTachyonCompensator(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2020, 1, 1)
self.SetEndDate(2020, 2, 1)
self.SetCash(100000) # Set Strategy Cash
# add stock with 1min bars
self.symbol = self.AddEquity("MSFT", Resolution.Minute).Symbol
# rolling window for 5min bars (we only want to trade if the 5min bar closes above the breakout)
self.rollingWindow = RollingWindow[TradeBar][1]
# create consolidator
self.Consolidate(self.symbol, timedelta(minutes=5), self.FiveMinuteBarHandler)
# which high do we want to use?
self.high = self.MAX(self.symbol, 30, Resolution.Minute, Field.High)
# order tickets
self.entryTicket = None
self.stoplossTicket = None
self.profit1Ticket = None
self.profit2Ticket = None
#captital risk
self.riskCaptial = self.Portfolio.TotalPortfolioValue * 0.05
# charts
stockPlot = Chart("Trade Plot")
stockPlot.AddSeries(Series("Buy", SeriesType.Scatter, "$", Color.Green, ScatterMarkerSymbol.Triangle))
stockPlot.AddSeries(Series("Sell 1", SeriesType.Scatter, "$", Color.Green, ScatterMarkerSymbol.TriangleDown))
stockPlot.AddSeries(Series("Sell 2", SeriesType.Scatter, "$", Color.Green, ScatterMarkerSymbol.TriangleDown))
stockPlot.AddSeries(Series("Stop", SeriesType.Scatter, "$", Color.Red, ScatterMarkerSymbol.TriangleDown))
stockPlot.AddSeries(Series("Price", SeriesType.Line, "$", Color.White))
self.AddChart(stockPlot)
def OnData(self, data):
# see if the high is ready
if not self.high.IsReady:
return
# see if rolling window (5 min bar) is complete
if not self.rollingWindow.IsReady:
return
# we want to start trading after first bar is complete
if not (self.Time.hour == 9 and self.Time.minute == 36):
return
# chart for current price of the stock
self.Plot('Trade Plot', 'Price', data.Bars["MSFT"].Close)
# stop/limit parameters (to be optimized)
bp = int(self.GetParameter("breakout_percent"))
sp = int(self.GetParameter("stop_percent"))
pp1 = int(self.GetParameter("profit_percent1"))
pp2 = int(self.GetParameter("profit_percent2"))
if self.entryTicket == None:
# next 5min candle closes above the breakout area
if self.rollingWindow[0].Close > self.high:
self.stopBuyPrice = data["MSFT"].Close * (bp / 1000)
self.stopLossPrice = self.stopBuyPrice * (sp / 1000)
self.profitTarget1 = self.stopBuyPrice * (pp1 / 1000)
self.profitTarget2 = self.stopBuyPrice * (pp2 / 1000)
# position sizing
#self.quantity = int(self.riskCaptial / self.stopBuyPrice)
# order entry
self.entryTicket = self.StopMarketOrder("MSFT", 100, self.stopBuyPrice)
def OnOrderEvent(self, orderevent):
if orderevent.Status != OrderStatus.Filled:
return
# sales entry ticket tells us if we currently have a position.
# references orders below to verfiy
if self.entryTicket != None and self.entryTicket.OrderId == orderevent.OrderId:
# plots entry fill price
self.Plot('Trade Plot', 'Buy', orderevent.FillPrice)
# Enter stop loss order
self.stoplossTicket = self.StopMarketOrder("MSFT", -100, self.stopLossPrice)
# Enter limit order 1
self.profit1Ticket = self.LimitOrder("MSFT", -50, self.profitTarget1)
# Enter limit order 2
self.profit2Ticket = self.LimitOrder("MSFT", -50, self.profitTarget2)
# tells us if the first profit order was triggered
if self.profit1Ticket != None and self.profit1Ticket.OrderId == orderevent.OrderId:
# plots first limit sell price
self.Plot('Trade Plot', 'Sell 1', orderevent.FillPrice)
# updates stop loss quantity
self.stoplossTicket.UpdateQuantity(-50)
# tells us if the stop order was sent
if self.stoplossTicket != None and self.stoplossTicket.OrderId == orderevent.OrderId:
# plots stop loss fill price
self.Plot('Trade Plot', 'Stop', orderevent.FillPrice)
# cancels limit profit orders
self.profit1Ticket.Cancel()
self.profit2Ticket.Cancel()
# only one entry ticket, needs to be adjusted for trding multiple stocks
self.entryTicket = None
# tells us if second profit order was triggered
if self.profit2Ticket != None and self.profit2Ticket.OrderId == orderevent.OrderId:
# plots stop loss fill price
self.Plot('Trade Plot', 'Sell 2', orderevent.FillPrice)
# cancels stop loss order (no more stocks left)
self.stoplossTicket.Cancel()
# only one entry ticket, needs to be adjusted for trding multiple stocks
self.entryTicket = None
# converting 1min to 5min bars
def FiveMinuteBarHandler(self, bar):
self.rollingWindow.Add(bar)
Brady Murakami
Figured it out. Brackets were the issue.
Brady Murakami
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!