Hi Guys,
Alex you gave me some code on Friday, that correctly performed a buy on open and sell on close.
I want to modify it so that, it buys on open, and puts a stop below yesterday's low. And will exit for a loss if stop hit, if stop not hit will exit on close as normal.
The code should be easy just I've spent a couple of hours on it and not getting anywhere. The error I'm getting is ordertype is not recognised, yet it comes up in the complier autotype feature.
I tried to find documentation examples but can't find,
1) What am I doing wrong?!
2) I've added a couple of other lines, e.g. self.rWindow.Add(data["SPY"]) in OnData, so I can access yesterday's low. Is this the correct place to put it?
Kind Regards Alex
#
# QuantConnect Basic Template:
# Fundamentals to using a QuantConnect algorithm.
#
# You can view the QCAlgorithm base class on Github:
# https://github.com/QuantConnect/Lean/tree/master/Algorithm
#
import numpy as np
from datetime import timedelta
class BasicTemplateAlgorithm(QCAlgorithm):
def Initialize(self):
# Set the cash we'd like to use for our backtest
# This is ignored in live trading
self.SetCash(100000)
# Start and end dates for the backtest.
# These are ignored in live trading.
self.SetStartDate(2017,1,1)
self.SetEndDate(2017,2,1)
# Add assets you'd like to see
self.spy = self.AddEquity("SPY", Resolution.Minute).Symbol
self.rWindow = RollingWindow[TradeBar](2)
consolidator = TradeBarConsolidator(timedelta(1))
consolidator.DataConsolidated += self.OnDailyData
self.SubscriptionManager.AddConsolidator(self.spy, consolidator)
def OnDailyData(self, sender, bar):
self.rWindow.Add(bar) # I added, so can view previous bars..
# Place open orders:
self.MarketOnOpenOrder(bar.Symbol, 100, "hello")
self.Log("OnDailyData triggered")
def OnData(self, data):
self.rWindow.Add(data["SPY"])
pass
def OnOrderEvent(self, orderEvent):
# Wait for window to be ready..
if not self.rWindow.IsReady: return
# First check order filled.. else no need to do anything..
if orderEvent.Status == OrderStatus.Filled:
# Get this order..
order = self.Transactions.GetOrderById(orderEvent.OrderId)
self.Log("ORDER EVENT")
# If MarketOnOpen, set two orders; 1) StopMarketOrder 2) MarketOnClose
if (order.Type == OrderType.MarketOnOpen): # and (self.Portfolio.Invested == True):
self.Log("Market On Open")
# Set a stop below yesterday low..
# Bug could be here 'stop
self.StopMarketOrder(order.Symbol, -100, self.rWindow[1].Low, "Stop order goodbye")
# Set market on close also
self.MarketOnCloseOrder(order.Symbol, -100, "goodbye")
# If Stop Market Order..
elif (order.Type == OrderType.StopMarketOrder): ## Not sure why this MarketOnCloseOrder not working..
self.Log("StopMarketOrder order")
# Cancel all open orders (i.e. remaining MOC order)..
self.Transactions.CancelOpenOrders("SPY")
# If Market on Close..
elif (order.Type == OrderType.MarketOnCloseOrder): ## Not sure why this MarketOnCloseOrder not working..
self.Log("Market close order")
# Cancel all open orders (i.e. remaining SM order)..
self.Transactions.CancelOpenOrders("SPY")
Hi, I can't add te backtest for some reason, because it doesn't show the bug I'm seeing and the code shows old code and not newest code with bug? (perhaps this only allows you to select working code? I tried restarting, no difference).. Please ignore backtest as code is not complete code, please see code snippet above. Thankyou
Alexandre Catarino
There is some typos, since the OrderType enum is defined as:
enum OrderType { Market, Limit, StopMarket, StopLimit, MarketOnOpen, MarketOnClose, OptionExercise }
And you have OrderType.StopMarketOrder and OrderType.MarketOnCloseOrder in your code.
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!