Hi, I've been looking through the help section and have not found much that relates to setting SL/TP levels in market execution orders. I've tried to come up with solutions to this problem and heres what I have brainstormed so far http://imgur.com/a/FpsJl I know right now that the SL/TP is based off the close, how can I base it off of the price of an executed order?
Jonathan Evans
Actually, QuantConnect has LimitOrders and StopLoss orders built in. I use them like this, when placing an order:
LimitOrder(symbol, -quantity, currentPrice * (1m + profitTargetPercent))
StopMarketOrder(symbol, -quantity, currentPrice * (1m - stopLossPercent))
Brennan Neeley
Sorry if this sounds like a dumb question, but how do I set the currentPrice parameter to mirror real time live price?
Jonathan Evans
I create LimitOrders and StopMarketOrders at the same time that I make a purchase. Thus, currentPrice is the purchase price, and I set the stop loss or profit target relative the purchase price, exactly like what you are doing in your code example.
Jonathan Evans
Maybe some sample code will help. Here's an example algo that buys stock, sets a StopLoss, then updates the StopLoss.
Brennan Neeley
Thanks for the code, just another question. Based on the code that I'm reading does the stop loss mimic a "trailing stop" or is it hard set (static and non moving)? http://imgur.com/levofQV
Jonathan Evans
The stop loss created in this line of code is a "hard set":
StopLoss = StopMarketOrder(Symbol, -quantity, currentPrice * (1m - StopLossPercent));
If you want to mimic a trailing stop, you have to manually update the stop loss order ticket like I did in the line of code you highlighted:StopLoss.Update(new UpdateOrderFields{ StopPrice = currentPrice * (1m - StopLossPercent) });
Brennan Neeley
Once I put the code you suggested into my program, my algorithm kept buying every second it was on instead of buying on a moving average cross. Heres a sample of my code. http://imgur.com/yDdtrd0
Michael Handschuh
It's typically easier for others to help if you attach the full project, then we can edit it directly and re-attach the fixed project (you need to attach backtest as well). In response to your question, I see a couple things immediately. First, I think your buy/sell logic should be an if/else block so they can never fire on the same timestep. Secondly, it looks like you perform your market order via the Order function, but then you also call SetHoldings which will also submit a market order. Likewise, in your sell function you call Liquidate and then SetHoldings(0.0). The SetHoldings function tries to set your current holdings to the targeted percent of portfolio value (1 = 100% TotalPortfolioValue). So if you liquidate (close everything) and then call SetHoldings(0.0), then nothing will happen. Another thing, when submitting your stop loss/take profit orders (via StopMarketOrder and LimitOrder) you need to set the quantity to negative, since you want those orders to close your position.
Brennan Neeley
Heres the project that I'm working on Michael
Jonathan Evans
Here's my fixes for your algo with StopMarketOrder and LimitOrder. I put some descriptions in the comments.
Ian Worthington
Hold up everyone. Question time:
What about this situation during backtesting.
CloseHour 1) I made a stopLoss order now: StopLoss@165
CloseHour 2) Price drops to 168
CloseHour 3) Price drops to 10.
Now because of the way our system works, it seems to be my stop loss will now be called, WAY too late - I have gone way past my stoploss. So this means any kind of attemplt to Liquidate orders could happen way too late if done inside OnData.
How does QuantConnect deal with the concept of brokers taking care of StopLosses for us? If I am trying to set my risk at 1% its basically impossible because this is happening. Unless I decide to use tick data it seems impossible to emulate how stop losses will really work.
Alexandre Catarino
In backtest, order fills depend on resolution, simply because there is no higher resolution data points between two data points of the selected resolution. This is not an issue in live mode using QuantConnect paper trading account, because limit and stop orders are filled with the ticks that arrive in the live stream.
When we are trading with a real brokerage paper or real account, QuantConnect's order types are converted into the correspondent brokerage order type and placed. Their fills are, then, managed by the brokerage and, once they are filled, their API notifies our algorithm in QuantConnect.
Jared Broad
example above was it an overnight gap or intraday move?
What brokerage you are using will impact whether the brokerage will honor
stop loss levels - from what I know most of the time they don't guarantee a
price.
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.
Ian Worthington
Alex explained it well, it is as I suspected.
I supposed it would be a lot to ask for some better broker emulation. For example if we are only feeding hourly data, the system could calculate and emulate a straight line of "tick" data between the 2 hourly points. It's extreme, but would take care of this problem - perhaps as some kind of option.
Or I supposed we should only be downloading tick data.
Jared Broad
Ian Worthington, you just need to request higher resolution data and you'll get a real fill price. You can use custom fill models if you'd like to mock up a fake data point between two bars but the fill won't be realistic.
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.
Jared Broad
Levitikon made this gem a few months ago; I think it might help others in this thread:
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.
Larry Smith
Jared Broad, is there any document that briefly describes how this application may be used as a robo-trader or exchange which may include data flow and/or sequence diagrams?
Alexandre Catarino
Larry Smith, please open a new discussion, since your question is offtopic in this thread and other new users may want to look into the answer later.
Bao Huynh
Thanks Jon,
I tried to implement something similar with your code and combined it with top gainers data. I tried to run the backtest again and never got the same results. I'm quite new but I wanna focus on the risk portion correctly. I noticed my trailing stop might've never implemented a sell off.
I'll look into Jared's suggestion of a stop loss & limit order cancelation when one or the other is executed.
Christian sandven
Regarding Jonathan Evans fixes to  StopMarketOrder and LimitOrder.Â
This line gives me an error :Â
if (!orderEvent.Status.IsClosed()) Â Is there a way around this ? Â Also I am using objective programming, and are having problems whith bringing these parameters into the OnOrderEvent function: Â private OrderTicket CurrentOrder; private OrderTicket StopLoss; private OrderTicket ProfitTarget;import pandas import numpy as np ### <summary> ### Simple RSI Strategy intended to provide a minimal algorithm example using ### one indicator ### </summary> class RSIAlgorithm(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.''' # Set our main strategy parameters self.SetStartDate(2013,1, 1) # Set Start Date self.SetEndDate(2014,1,1) # Set End Date self.SetCash(10000) # Set Strategy Cash RSI_Period = 14 # RSI Look back period self.RSI_OB = 60 # RSI Overbought level self.RSI_OS = 40 # RSI Oversold level self.Allocate = 2 # Percentage of captital to allocate self.tolerance = 0.00015 self.spread = 20/10000 self.first_stg_up = 0 self.first_stg_down = 0 self.trend = 0 self.trend_n = 0 self.symbol = "EURUSD" self.tp = 20/10000 self.sl = 10/10000 self.holdings = 0 self.quant = 10000 # Find more symbols here: http://quantconnect.com/data self.AddForex("EURUSD", Resolution.Hour) self.RSI_Ind = self.RSI("EURUSD", RSI_Period) self.bb_ind = self.BB("EURUSD", 20, 1, MovingAverageType.Simple); self.slow = self.SMA("EURUSD", 20, Resolution.Hour) self.fast = self.SMA("EURUSD", 7, Resolution.Hour) # Ensure that the Indicator has enough data before trading,. self.SetWarmUp(20) def OnData(self, data): trend =1 if not self.Portfolio.Invested: # If not, we check the RSI Indicator if self.trend == 1 : # #self.SetHoldings("EURUSD", self.Allocate) order = self.MarketOrder(self.symbol, self.quant) sl = self.StopMarketOrder(self.symbol, -self.quant, fxClose - self.sl) tp = self.LimitOrder(self.symbol, -self.quant, fxClose + self.tp) #if self.RSI_Ind.Current.Value < self.RSI_OS: # Buy Apple # self.SetHoldings("EURUSD", self.Allocate) else: if self.trend_n == -1: # Sell Apple self.Liquidate("EURUSD") def OnOrderEvent(self, orderEvent): if (orderEvent.Status == 'Filled'): return if tp == null or sl == null: return filledOrderid = orderEvent.OrderId if tp == filledOrderId: sl.Cancel() if sl == filledOrderId: tp.Cancel()
 ÂBrennan Neeley
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!