Hi,
I think the code is doing something wrong because is not doing what I need. First I want to calculate the number of shares to buy in order to place the stop loss and Take profit and win or lose the same amount, in this case, $1000.
The code is not calculating well the # of shares and it seems the algo is doing the order, then the stop loss and then the take profit, this is wrong because what I need is one or the other, not the 2. Meaning either Stop Loss or Take Profit for any given order. Hope someone can help.
Is just a simple mean-reverting strategy.
import clr
clr.AddReference("System")
clr.AddReference("QuantConnect.Algorithm")
clr.AddReference("QuantConnect.Indicators")
clr.AddReference("QuantConnect.Common")
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
class KeltnerMeanReversionAlgorithm(QCAlgorithm):
def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.SetStartDate(2018, 1, 1) #Set Start Date
#self.SetEndDate(2015, 1, 1) #Set End Date
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.AddEquity("SPY")
# create the 20 EMA
self.mean = self.EMA("SPY", 20, Resolution.Daily)
# create the ATR
self.atr = self.ATR("SPY", 20, Resolution.Daily)
self.previous = None
def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
# a couple things to notice in this method:
# 1. We never need to 'update' our indicators with the data, the engine takes care of this for us
# 2. We can use indicators directly in math expressions
# 3. We can easily plot many indicators at the same time
# wait for our ema to fully initialize
if not self.mean.IsReady:
return
# only once per day
if self.previous is not None and self.previous.date() == self.Time.date():
return
risk_per_trade = 100
holdings = self.Portfolio["SPY"].Quantity
# If there is no trades
if holdings == 0:
quantity = round(risk_per_trade / self.atr.Current.Value)
# Mean reversion when price is too low
if self.Securities["SPY"].Price < self.mean.Current.Value - 2 * self.atr.Current.Value:
self.Log("BUY >> {0}".format(self.Securities["SPY"].Price))
marketTicket = self.MarketOrder("SPY", quantity)
limitTicket = self.LimitOrder("SPY", -self.Portfolio['SPY'].Quantity, self.Securities["SPY"].Price + self.atr.Current.Value)
stopTicket = self.StopMarketOrder("SPY", -self.Portfolio['SPY'].Quantity, self.Securities["SPY"].Price - self.atr.Current.Value)
# Mean reversion when price is too high
if self.Securities["SPY"].Price > self.mean.Current.Value + 2 * self.atr.Current.Value:
self.Log("SELL >> {0}".format(self.Securities["SPY"].Price))
marketTicket = self.MarketOrder("SPY", -quantity)
limitTicket = self.LimitOrder("SPY", self.Portfolio['SPY'].Quantity, self.Securities["SPY"].Price - self.atr.Current.Value)
stopTicket = self.StopMarketOrder("SPY", self.Portfolio['SPY'].Quantity, self.Securities["SPY"].Price + self.atr.Current.Value)
self.previous = self.Time
Rahul Chowdhury
Hey Cristian,
You can store the order tickets in class variables. This lets you keep track of the different orders in the OnOrderEvent method. If either the stop loss or limit order fills, we cancel the other and reset our tickets.
One thing to watch out for is the fact that your position sizing doesn't take into account your buying power. If you place a market order for a position which you cannot afford, it will become an invalid order. I increased your initial SetCash to $250,000 to avoid this.
Cristian correa
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!