BreakEven & Trailing Profit: complete function
Forums › ProRealTime English forum › ProOrder support › BreakEven & Trailing Profit: complete function
- This topic has 119 replies, 22 voices, and was last updated 7 months ago by robertogozzi.
Tagged: BreakEven, Profit, stop, trailing, trailingstop
-
-
11/25/2020 at 5:55 PM #151590
I added lines 9 and 10 for settings, then lines 29-32 and lines 49-52 for the code to manage the additional percentage.
1 user thanked author for this post.
11/25/2020 at 8:37 PM #15164111/28/2020 at 5:45 PM #152033Thank you Roberto for the kind help! I have just updated my code with this and trimmed some parameters so now it is up in the Demo, will be interesting to see the result in the coming weeks. Thanks!
1 user thanked author for this post.
12/15/2020 at 12:58 PM #153839a try to cover a position on the trailingstop of robertogozzi
Basically it uses the levels of Donchian if the trade is triggered. If the trailing stop is not triggered, it uses previous determined lows before the trade to exit, with in consideration to a minimum distance to the tradeprice.
Also has a second exit method if above is not triggered and the lines are narrow. If it crosses the top line for a long and retraces back to the lowest it exits too, again with in consideration of a minimum distance between max & min levels
With this, most likely with mistakes, I hope that if the market reverse there is an alternative way to exit the trade before going to the stoploss.
Instead of a fixed amount to start the trailingstop, it uses now a %. Pipsize is left out on the part I added. I’am unsure if it is * or /. What I added can be disabled.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155once trailingstop=1once useDonchian =1 // if breakeven is not triggeredif trailingstop thenif ts2sensitivity=1 thents2sensitivitylong=closets2sensitivityshort=closeelsif ts2sensitivity=2 thents2sensitivitylong=hights2sensitivityshort=lowendifonce hdp1=closeonce ldp1=closeonce hdp2=closeonce ldp2=closeonce hdp3=closeonce ldp3=close// below; 0 = disable minimumdistance criteramdist=((tradeprice(1)/100)*0.09)mdist2=((tradeprice(1)/100)*0.09)if longonmarket and (shortonmarket[1] or not onmarket[1]) or shortonmarket and (longonmarket[1] or not onmarket[1]) thenonce flag=0hdp1=highest[7](high)[1]ldp1=lowest[7](low)[1]hdp2=highest[14](high)[1]ldp2=lowest[14](low)[1]hdp3=highest[21](high)[1]ldp3=lowest[21](low)[1]maxrun=max(hdp1,hdp2)maxrun2=max(maxrun,hdp3)minrun=min(ldp1,ldp2)minrun2=min(minrun,ldp3)endifif not onmarket or ((longonmarket and shortonmarket[1]) or (longonmarket[1] and shortonmarket)) thentrailstart2 = 0.1 //% start trailing profits from this pointbasepercent = 0.2 //20.0% profit percentage to keep when setting berakevenstepsize = 2 //10 pip chunks to increase percentagepercentinc = 0.1 //10.0% percent increment after each stepsize chunkbarnumber = 10 //10 add further % so trades don't keep running too longbarpercent = 0.1 //10% add this additional percentage every barnumber barsroundto = 0 //-0.5 rounds lower, +0.4 higher, 0 defaults prt behaviourpricedistance = 10 * pipsize //7 minimun distance from current pricey1 = 0 //reset to 0y2 = 0 //reset to 0profitpercent = basepercent //reset to desired default valuetradebar = barindextrailstart = ((close/100)*trailstart2)ts2sensitivity= 2elsif longonmarket thenif ts2sensitivitylong > (tradeprice(1) + (y1 * pipsize)) thenx1 = (ts2sensitivitylong - tradeprice(1)) / pipsizeif x1 >= trailstart thendiff1 = abs(trailstart - x1)chunks1 = max(0,round((diff1 / stepsize) + roundto))profitpercent = basepercent + (basepercent * (chunks1 * percentinc))barcount = barindex - tradebarif barcount mod barnumber = 0 thenprofitpercent = profitpercent + barpercentendifprofitpercent = max(profitpercent[1],min(100,profitpercent))y1 = max(x1 * profitpercent, y1)endifelseif useDonchian thenif (tradeprice(1)-ldp1)>mdist and close crosses under ldp1 thensell at marketendifif (tradeprice(1)-ldp2)>mdist and close crosses under ldp2 thensell at marketendifif (tradeprice(1)-ldp3)>mdist and close crosses under ldp3 thensell at marketendifif high crosses over maxrun2 thenflag=1endifif flag=1 and low crosses under minrun2 and maxrun2-minrun2>mdist2 thensell at marketendifendifendifelsif shortonmarket thenif ts2sensitivityshort < (tradeprice(1) - (y2 * pipsize)) thenx2 = (tradeprice(1) - ts2sensitivityshort) / pipsizeif x2 >= trailstart thendiff2 = abs(trailstart - x2)chunks2 = max(0,round((diff2 / stepsize) + roundto))profitpercent = basepercent + (basepercent * (chunks2 * percentinc))barcount = barindex - tradebarif barcount mod barnumber = 0 thenprofitpercent = profitpercent + barpercentendifprofitpercent = max(profitpercent[1],min(100,profitpercent))y2 = max(x2 * profitpercent, y2)endifelseif useDonchian thenif hdp1-tradeprice(1)>mdist and close crosses over hdp1 thenexitshort at marketendifif hdp2-tradeprice(1)>mdist and close crosses over hdp2 thenexitshort at marketendifif hdp3-tradeprice(1)>mdist and close crosses over hdp3 thenexitshort at marketendifif low crosses under minrun2 thenflag=1endifif flag=1 and high crosses over maxrun2 and maxrun2-minrun2>mdist2 thenexitshort at marketendifendifendifendifif y1 thensellprice = tradeprice(1) + (y1 * pipsize)if abs(ts2sensitivitylong - sellprice) > pricedistance thenif ts2sensitivitylong >= sellprice thensell at sellprice stopelsesell at sellprice limitendifelsesell at marketendifendifif y2 thenexitprice = tradeprice(1) - (y2 * pipsize)if abs(ts2sensitivityshort - exitprice) > pricedistance thenif ts2sensitivityshort <= exitprice thenexitshort at exitprice stopelseexitshort at exitprice limitendifelseexitshort at marketendifendifendifgraphonprice hdp1graphonprice ldp1graphonprice hdp2graphonprice ldp2graphonprice hdp3graphonprice ldp34 users thanked author for this post.
12/22/2020 at 4:53 PM #154903I am running this on a 5min strategy. My trailing has started but every 50 min (barnumber 10×5(min) the stop does not move up additional 10% (barpercent). Why though?
1234567891011TrailStart = 11 //30 Start trailing profits from this pointBasePerCent = 0.07 //20.0% Profit percentage to keep when setting BerakEvenStepSize = 10 //10 Pip chunks to increase PercentagePerCentInc = 0.07 //10.0% PerCent increment after each StepSize chunkBarNumber = 10 //10 Add further % so that trades don't keep running too longBarPerCent = 0.100 //10% Add this additional percentage every BarNumber barsRoundTO = -0.5 //-0.5 rounds always to Lower integer, +0.4 rounds always to Higher integer, 0 defaults PRT behaviourPriceDistance = 7 * pipsize //7 minimun distance from current pricey1 = 0 //reset to 0y2 = 0 //reset to 0ProfitPerCent = BasePerCent //reset to desired default value12/22/2020 at 5:09 PM #15490412/23/2020 at 1:37 AM #154936This works correctly with your settings:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115defparam cumulateorders = falsep = 100t = 0if close crosses over average[p,t](close) thenbuy at marketelsif close crosses under average[p,t](close) thensellshort at marketendifset target pprofit 500//IF Not OnMarket THEN//// when NOT OnMarket reset values to default valuesTrailStart = 11 //30 Start trailing profits from this pointBasePerCent = 0.07 //20.0% Profit percentage to keep when setting BerakEvenStepSize = 10 //10 Pip chunks to increase PercentagePerCentInc = 0.07 //10.0% PerCent increment after each StepSize chunkBarNumber = 10 //10 Add further % so that trades don't keep running too longBarPerCent = 0.100 //10% Add this additional percentage every BarNumber barsRoundTO = -0.5 //-0.5 rounds always to Lower integer, +0.4 rounds always to Higher integer, 0 defaults PRT behaviourPriceDistance = 7 * pipsize //7 minimun distance from current pricey1 = 0 //reset to 0y2 = 0 //reset to 0ProfitPerCent = BasePerCent //reset to desired default valueTradeBar = BarIndex + 1ELSIF LongOnMarket AND close > (TradePrice + (y1 * pipsize)) THEN //LONG positions//// compute the value of the Percentage of profits, if any, to lock in for LONG trades//x1 = (close - tradeprice) / pipsize //convert price to pipsIF x1 >= TrailStart THEN // go ahead only if N+ pipsDiff1 = abs(TrailStart - x1) //difference from current profit and TrailStartChunks1 = max(0,round((Diff1 / StepSize) + RoundTO)) //number of STEPSIZE chunksProfitPerCent = BasePerCent + (BasePerCent * (Chunks1 * PerCentInc)) //compute new size of ProfitPerCent// compute number of bars elapsed and add an additionl percentage// (this percentage is different from PerCentInc, since it's a direct percentage, not a Percentage of BasePerCent)// (if BasePerCent is 20% and this is 10%, the whole percentage will be 30%, not 22%)BarCount = BarIndex - TradeBarIF BarCount MOD BarNumber = 0 THENProfitPerCent = ProfitPerCent + BarPerCentENDIF//ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent)) //make sure ProfitPerCent doess not exceed 100%y1 = max(x1 * ProfitPerCent, y1) //y1 = % of max profitENDIFELSIF ShortOnMarket AND close < (TradePrice - (y2 * pipsize)) THEN //SHORT positions//// compute the value of the Percentage of profits, if any, to lock in for SHORT trades//x2 = (tradeprice - close) / pipsize //convert price to pipsIF x2 >= TrailStart THEN // go ahead only if N+ pipsDiff2 = abs(TrailStart - x2) //difference from current profit and TrailStartChunks2 = max(0,round((Diff2 / StepSize) + RoundTO)) //number of STEPSIZE chunksProfitPerCent = BasePerCent + (BasePerCent * (Chunks2 * PerCentInc)) //compute new size of ProfitPerCent// compute number of bars elapsed and add an additionl percentage// (this percentage is different from PerCentInc, since it's a direct percentage, not a Percentage of BasePerCent)// (if BasePerCent is 20% and this is 10%, the whole percentage will be 30%, not 22%)BarCount = BarIndex - TradeBarIF BarCount MOD BarNumber = 0 THENProfitPerCent = ProfitPerCent + BarPerCentENDIF//ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent)) //make sure ProfitPerCent doess not exceed 100%y2 = max(x2 * ProfitPerCent, y2) //y2 = % of max profitENDIFENDIFIF y1 THEN //Place pending STOP order when y1 > 0 (LONG positions)SellPrice = Tradeprice + (y1 * pipsize) //convert pips to price//// check the minimun distance between ExitPrice and current price//IF abs(close - SellPrice) > PriceDistance THEN//// place either a LIMIT or STOP pending order according to current price positioning//IF close >= SellPrice THENSELL AT SellPrice STOPELSESELL AT SellPrice LIMITENDIFELSE////sell AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price//SELL AT MarketENDIFENDIFIF y2 THEN //Place pending STOP order when y2 > 0 (SHORT positions)ExitPrice = Tradeprice - (y2 * pipsize) //convert pips to price//// check the minimun distance between ExitPrice and current price//IF abs(close - ExitPrice) > PriceDistance THEN//// place either a LIMIT or STOP pending order according to current price positioning//IF close <= ExitPrice THENEXITSHORT AT ExitPrice STOPELSEEXITSHORT AT ExitPrice LIMITENDIFELSE////ExitShort AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price//EXITSHORT AT MarketENDIFENDIFgraph BasePerCentgraph ProfitPerCentgraph BarCount//(barIndex - tradeindex)graph close - TradePricegraphonprice SellPrice coloured(255,0,0,255)graphonprice ExitPrice coloured(0,255,0,255)graph BarPerCent1 user thanked author for this post.
01/07/2021 at 10:32 AM #156726I was tired that day, Thanks Roberto!
I like the trailing and it works well. I get the best results in backtest from having a low PerCentInc it mostly depends on some trades which have ran over 5% (1000 euro), meaning I dont run the strategy with a TP. MFE is in most of the times therefor very far away from the actual Abs Perf.
The conclusion I have came with is that this trailing would be better if I added some more exits with it for example positions ends when trend is not so strong anymore or others and there for end its position.
Maybe this can save someones time. Good luck!
01/07/2021 at 1:10 PM #156740Hi
apologies if this is obvious to the pros out there, but im still getting to grips with trailing stops.
lets say I usually have a fixed TP of 75 pips.
However, instead of closing at 75, im happy to let it run, up to say…. 150 pips (or some other indicator) but I want to make sure I take a minimum of 50 pips profit if it reverses… can I use this code for that and what settings would I need?Thanks!
01/07/2021 at 1:29 PM #156742In your case you’d better use the code snippet at https://www.prorealcode.com/blog/trading/complete-trailing-stop-code-function/ (linesd 17 – 56) replacing lines 19 and 20 with, say, 75 and 50.
1 user thanked author for this post.
01/07/2021 at 1:47 PM #15674601/20/2021 at 4:45 PM #158701Ciao Roberto, would this work with cumulative orders? by changing tradeprice to positionprice? or does it need more than that?
01/21/2021 at 1:21 PM #158822nonetheless, it’s actually a bit more complex, because each new bar it might have accumulated more or less positions, so the previous trailing exit, if any, needs to be adjusted. It will keep the older one if it grants greater profits.
This is the new code dealing with accumulation of positions. I suggest that it be used in ANY case, though, since it will operate correctly even when not accumulating, it will simply never detect different position sizes and PositionPrice will match TradePrice:
Trailing Stop with accumulation of positions123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109DirectionSwitch = (LongOnMarket AND ShortOnMarket[1]) OR (LongOnMarket[1] AND ShortOnMarket) //True when there's been a change in the direction (likely to be due to a Stop & Reverse)IF Not OnMarket OR DirectionSwitch THEN//// when NOT OnMarket or thare's been a change in direction, reset values to their default settings//TrailStart = 30 //30 Start trailing profits from this pointBasePerCent = 0.200 //20.0% Profit percentage to keep when setting BerakEvenStepSize = 10 //10 Pip chunks to increase PercentagePerCentInc = 0.100 //10.0% PerCent increment after each StepSize chunkRoundTO = -0.5 //-0.5 rounds always to Lower integer, +0.4 rounds always to Higher integer, 0 defaults PRT behaviourPriceDistance = 7 * pipsize //7 minimun distance from current pricey1 = 0 //reset to 0y2 = 0 //reset to 0ProfitPerCent = BasePerCent //reset to desired default valuePositionCount = 0SellPrice = 0ExitPrice = 9999999ELSE//------------------------------------------------------// --- Update Stop Loss after accumulating new positions//------------------------------------------------------PositionCount = max(PositionCount,abs(CountOfPosition))//// update Stop Loss only when PositionCount has changed (actually when increased, we don't move it if there's been some positions exited)//IF PositionCount <> PositionCount[1] AND (ExitPrice + SellPrice) <> 9999999 THEN //go on only if Trailing Stop had already started trailingIF LongOnMarket THENq1 = PositionPrice + ((close - PositionPrice) * ProfitPerCent) //calculate new SLSellPriceX = max(max(SellPriceX,SellPrice),q1)SellPrice = max(max(SellPriceX,SellPrice),PositionPrice + (y1 * pipsize)) //set exit price to whatever grants greater profits, comopared to the previous oneELSIF ShortOnMarket THENr1 = ((PositionPrice - close) * ProfitPerCent) //calculate new SLExitPriceX = min(min(ExitPriceX,ExitPrice),r1)ExitPrice = min(min(ExitPriceX,ExitPrice),PositionPrice - (y2 * pipsize)) //set exit price to whatever grants greater profits, comopared to the previous oneENDIFENDIF// --- Update ENDENDIF//IF LongOnMarket AND close > (TradePrice + (y1 * pipsize)) THEN //LONG positions//// compute the value of the Percentage of profits, if any, to lock in for LONG trades//x1 = (close - tradeprice) / pipsize //convert price to pipsIF x1 >= TrailStart THEN // go ahead only if N+ pipsDiff1 = abs(TrailStart - x1) //difference from current profit and TrailStartChunks1 = max(0,round((Diff1 / StepSize) + RoundTO)) //number of STEPSIZE chunksProfitPerCent = BasePerCent + (BasePerCent * (Chunks1 * PerCentInc)) //compute new size of ProfitPerCentProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent)) //make sure ProfitPerCent doess not exceed 100%y1 = max(x1 * ProfitPerCent, y1) //y1 = % of max profitENDIFELSIF ShortOnMarket AND close < (TradePrice - (y2 * pipsize)) THEN //SHORT positions//// compute the value of the Percentage of profits, if any, to lock in for SHORT trades//x2 = (tradeprice - close) / pipsize //convert price to pipsIF x2 >= TrailStart THEN // go ahead only if N+ pipsDiff2 = abs(TrailStart - x2) //difference from current profit and TrailStartChunks2 = max(0,round((Diff2 / StepSize) + RoundTO)) //number of STEPSIZE chunksProfitPerCent = BasePerCent + (BasePerCent * (Chunks2 * PerCentInc)) //compute new size of ProfitPerCentProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent)) //make sure ProfitPerCent doess not exceed 100%y2 = max(x2 * ProfitPerCent, y2) //y2 = % of max profitENDIFENDIF//------------------------------------------------------------------------------// manage actual Exit, if needed//------------------------------------------------------------------------------IF y1 THEN //Place pending STOP order when y1 > 0 (LONG positions)SellPrice = max(SellPrice,Tradeprice + (y1 * pipsize)) //convert pips to price//// check the minimun distance between ExitPrice and current price//IF abs(close - SellPrice) > PriceDistance THEN//// place either a LIMIT or STOP pending order according to current price positioning//IF close >= SellPrice THENSELL AT SellPrice STOPELSESELL AT SellPrice LIMITENDIFELSE////sell AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price//SELL AT MarketENDIFENDIFIF y2 THEN //Place pending STOP order when y2 > 0 (SHORT positions)ExitPrice = min(ExitPrice,Tradeprice - (y2 * pipsize)) //convert pips to price//// check the minimun distance between ExitPrice and current price//IF abs(close - ExitPrice) > PriceDistance THEN//// place either a LIMIT or STOP pending order according to current price positioning//IF close <= ExitPrice THENEXITSHORT AT ExitPrice STOPELSEEXITSHORT AT ExitPrice LIMITENDIFELSE////ExitShort AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price//EXITSHORT AT MarketENDIFENDIF2 users thanked author for this post.
01/21/2021 at 3:07 PM #158832Roberto, you are a megastar. I was just in the middle of trying to work it out for myself but it was making my head hurt.
Hugely appreciate all the work you put in here!
1 user thanked author for this post.
01/21/2021 at 3:17 PM #158836BTW, I have been using this to make it work as a % trailing start:
12n = (tradeprice*ts)/100 // ts = % trailing startTrailStart = n // Start trailing profits from this pointSo presumably I now change tradeprice to positionprice ?
-
AuthorPosts
Find exclusive trading pro-tools on