RobertoGozzi Trail – Stops trailing
Forums › ProRealTime English forum › ProOrder support › RobertoGozzi Trail – Stops trailing
- This topic has 14 replies, 5 voices, and was last updated 1 month ago by robertogozzi.
Tagged: stop, trailing, trailing stop
-
-
09/23/2021 at 7:17 AM #178142
Hi.
There are so many great snippets here.
I useRobertoGozzi TS with cumulative orders
but i need help.
It starts trailing until in profit but then stops trailing.Would it be posible to follow the highest candle (bar position) with X-distance.
Se my attached pictureRobertoGozzi Trail123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145IF MyCOndition THENBUY PositionSize CONTRACTS AT MARKETSET STOP %LOSS 1set target %profit 2ENDIFtrailingstopRTS=trail//RobertoGozzi TS with cumulative ordersIF trailingstopRTS thenONCE UseCLOSE = 0 //1=use CLOSE, 0=use High/LowsrcH = close //defaults to CLOSEsrcL = close //defaults to CLOSEIF UseCLOSE = 0 THENsrcH = highsrcL = lowENDIFONCE UsePerCentage = 1 //0=use Pips (default), 1=use PercentagesONCE UseEquity = 0 //0=use price (default), 1=use current Equity (initial Capital + StrategyProfit, as defined by variable MyEquity)MyEquity = 1000DirectionSwitch = (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 settingsStartPerCent = 0.25//pc //0.25 = 0.25% movement to trigger Trailing Stop (when UsePerCentage=1)StepPerCent = 50//spc //50 = 50% (of the 0.25% above) as a Trailing Step (when UsePerCentage=1) (set to 100 to make StepSize=TrailStart, set to 200 to make it twice TrailStart)TrailStart = 30 //30 Start trailing profits from this point (when UsePerCentage=0)MinStart = 10 //10 Minimum value for TrailStart (when UseEquity=1, to prevent TrailStart from dropping below ZERO when Equity turns negative)IF UsePerCentage THENTrailStart = (close / PipSize) * StartPerCent / 100 //use current price (CLOSE) for calculationsIF UseEquity THEN //alternative calculations using EQUITYTrailStart = Max(MinStart,(MyEquity / PipValue) * StartPerCent / 100) //MyEquity is the variable (feel free to use a different name) retaining your current equityENDIFENDIF//BasePerCent = 0.11 //BPC 0.08 - 0.2 Profit percentage to keep when setting BerakEvenStepSize = 10 //ss //5 - 15 Pip chunks to increase PercentageIF UsePerCentage THENStepSize = TrailStart * StepPerCent / 100ENDIFPerCentInc = 0.16 //0.16//pci //0.06 - 0.14 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 = 12 * pipsize //IG minimum stop distance: DAX = 5, DJ = 12, NAS = 4, SP500 = 1y1 = 0 //reset to 0y2 = 0 //reset to 0ProfitPerCent = BasePerCent //reset to desired default value//PositionCount = 0SellPrice = 0SellPriceX = 0ExitPrice = 9999999ExitPriceX = 9999999ELSE//------------------------------------------------------// --- Update Stop Loss after accumulating new positions//------------------------------------------------------//PositionCount = max(PositionCount,abs(CountOfPosition))//// update Stop Loss only when PositionPrice 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 PositionPrice <> PositionPrice[1] AND (ExitPrice + SellPrice) <> 9999999 THEN //go on only if Trailing Stop had already started trailingIF LongOnMarket THENq1 = PositionPrice + ((srcH - 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 - ((PositionPrice - srcL) * 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 srcH > (PositionPrice + (y1 * pipsize)) THEN //LONG positions//// compute the value of the Percentage of profits, if any, to lock in for LONG trades//x1 = (srcH - PositionPrice) / 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 srcL < (PositionPrice - (y2 * pipsize)) THEN //SHORT positions//// compute the value of the Percentage of profits, if any, to lock in for SHORT trades//x2 = (PositionPrice - srcL) / 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,PositionPrice + (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,PositionPrice - (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 MarketENDIFEndifENDIF09/23/2021 at 7:47 AM #178146Post the values that you used for MyConditions and PositionsSize and the date and time of those candles in your pics.
09/23/2021 at 8:16 AM #178153Timefrem 15
Wallstreet
Date of picture: TodayFollow the highest candle with X distance
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183DEFPARAM CUMULATEORDERS = false//=== Risk Management ===PositionSize=1//=== Max Monthly Loss ===ONCE MyProfit = 0ONCE TradeON = 1IF Month <> Month[1] THENMyProfit = STRATEGYPROFIT //store profits/losses at the beginning of each monthTradeON = 1 //enable trading each new monthENDIFIF (STRATEGYPROFIT - MyProfit) < -3500 THEN //disable trading when losing > 200 currency unitsTradeON = 0ENDIF//=== Entry Filter ===//Filter 1indicator1=average[75,7]indicator2=average[125,7]indicator3=average[150,7]F1 = indicator1>indicator2F2 = indicator2>indicator3//=== Entry Criteria ===//Entry Criteria 1entrylen = 5LowVol = round(volume[4])E1 = volume < LowVolbullish = close>lowest[entrylen](low)IF E1 AND bullish AND F1 AND F2 AND opendayofweek <> 3 AND opendayofweek <> 4 AND opendayofweek <> 0 AND opendayofweek <> 6 AND TradeON THENBUY PositionSize CONTRACTS AT MARKETSET STOP %LOSS 1set target %profit 2ENDIFtrailingstopRTS=1//RobertoGozzi TS with cumulative ordersIF trailingstopRTS thenONCE UseCLOSE = 0 //1=use CLOSE, 0=use High/LowsrcH = close //defaults to CLOSEsrcL = close //defaults to CLOSEIF UseCLOSE = 0 THENsrcH = highsrcL = lowENDIFONCE UsePerCentage = 1 //0=use Pips (default), 1=use PercentagesONCE UseEquity = 0 //0=use price (default), 1=use current Equity (initial Capital + StrategyProfit, as defined by variable MyEquity)MyEquity = 1000DirectionSwitch = (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 settingsStartPerCent = 0.25//pc //0.25 = 0.25% movement to trigger Trailing Stop (when UsePerCentage=1)StepPerCent = 50//spc //50 = 50% (of the 0.25% above) as a Trailing Step (when UsePerCentage=1) (set to 100 to make StepSize=TrailStart, set to 200 to make it twice TrailStart)TrailStart = 30 //30 Start trailing profits from this point (when UsePerCentage=0)MinStart = 10 //10 Minimum value for TrailStart (when UseEquity=1, to prevent TrailStart from dropping below ZERO when Equity turns negative)IF UsePerCentage THENTrailStart = (close / PipSize) * StartPerCent / 100 //use current price (CLOSE) for calculationsIF UseEquity THEN //alternative calculations using EQUITYTrailStart = Max(MinStart,(MyEquity / PipValue) * StartPerCent / 100) //MyEquity is the variable (feel free to use a different name) retaining your current equityENDIFENDIF//BasePerCent = 0.11 //BPC 0.08 - 0.2 Profit percentage to keep when setting BerakEvenStepSize = 10 //ss //5 - 15 Pip chunks to increase PercentageIF UsePerCentage THENStepSize = TrailStart * StepPerCent / 100ENDIFPerCentInc = 0.16 //0.16//pci //0.06 - 0.14 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 = 12 * pipsize //IG minimum stop distance: DAX = 5, DJ = 12, NAS = 4, SP500 = 1y1 = 0 //reset to 0y2 = 0 //reset to 0ProfitPerCent = BasePerCent //reset to desired default value//PositionCount = 0SellPrice = 0SellPriceX = 0ExitPrice = 9999999ExitPriceX = 9999999ELSE//------------------------------------------------------// --- Update Stop Loss after accumulating new positions//------------------------------------------------------//PositionCount = max(PositionCount,abs(CountOfPosition))//// update Stop Loss only when PositionPrice 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 PositionPrice <> PositionPrice[1] AND (ExitPrice + SellPrice) <> 9999999 THEN //go on only if Trailing Stop had already started trailingIF LongOnMarket THENq1 = PositionPrice + ((srcH - 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 - ((PositionPrice - srcL) * 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 srcH > (PositionPrice + (y1 * pipsize)) THEN //LONG positions//// compute the value of the Percentage of profits, if any, to lock in for LONG trades//x1 = (srcH - PositionPrice) / 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 srcL < (PositionPrice - (y2 * pipsize)) THEN //SHORT positions//// compute the value of the Percentage of profits, if any, to lock in for SHORT trades//x2 = (PositionPrice - srcL) / 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,PositionPrice + (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,PositionPrice - (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 MarketENDIFEndifENDIF09/23/2021 at 8:58 AM #178168The last trade was closed last Tuesday and no more trades have been opened since then.
09/23/2021 at 9:06 AM #17817009/23/2021 at 9:14 AM #17817509/23/2021 at 9:27 AM #178178Explain me what your trailing stop should do, from the start to the end of a trade.
My code was not meant to follow candlesticks. I think it’s better to code a new one.
09/23/2021 at 9:32 AM #17817909/23/2021 at 10:08 AM #178202There you go:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152DEFPARAM CUMULATEORDERS = falsePositionSize=1//=== Max Monthly Loss ===ONCE MyProfit = 0ONCE TradeON = 1IF Month <> Month[1] THENMyProfit = STRATEGYPROFIT //store profits/losses at the beginning of each monthTradeON = 1 //enable trading each new monthENDIFIF (STRATEGYPROFIT - MyProfit) < -3500 THEN //disable trading when losing > 200 currency unitsTradeON = 0ENDIF//=== Entry Filter ===//Filter 1indicator1=average[75,7]indicator2=average[125,7]indicator3=average[150,7]F1 = indicator1>indicator2F2 = indicator2>indicator3//=== Entry Criteria ===//Entry Criteria 1entrylen = 5LowVol = round(volume[4])E1 = volume < LowVolbullish = close>lowest[entrylen](low)IF E1 AND bullish AND F1 AND F2 AND opendayofweek <> 3 AND opendayofweek <> 4 AND opendayofweek <> 0 AND opendayofweek <> 6 AND TradeON THENBUY PositionSize CONTRACTS AT MARKETSET STOP %LOSS 1set target %profit 2ENDIF//trailingstopRTS=1IF trailingstopRTS thenIF Not OnMarket THENPriceDistance = 10 * PipSize //PriceDistance from price as required by the brokerStopDistance = 30 * PipSize //Distance from HIGHSellPrice = close - StopDistance //The first bar StopDistance is from CLOSEELSESellPrice = max(SellPrice,high - StopDistance)IF abs(close - SellPrice) > PriceDistance THENIF close >= SellPrice THENSELL AT SellPrice STOPELSESELL AT SellPrice LIMITENDIFELSESELL AT MarketENDIFENDIFENDIF//graphonprice SellPrice coloured(0,128,0,150)at the beginning the stoploss distance is from CLOSE (the entry price), not from HIGH obviously. From then on it starts following any higher high.
1 user thanked author for this post.
09/23/2021 at 11:25 AM #17821309/23/2021 at 11:29 AM #178214I prefer not to show all my code.
Do you really need all of it 🙂
Its just about the trail-funtion?
Is it possbile to trail with x-distance from highest canlde?
murre87 “I prefer not to show all my code” 🙂 That’s all you ask people to do on this site! Hahahaha Think you should share it to e fair
1 user thanked author for this post.
09/23/2021 at 11:35 AM #178217Shame to waste Roberto kindness, so link to above added as Log 304 here
I’ll have a go using it later on a few of my Algos. Never seen much improvement with any trailing stop.
We could do with a dedicate topic to try and bottom out what TS’s work and with what type of strategy.
2 users thanked author for this post.
09/21/2024 at 3:43 PM #237908Hello everybody,
May I ask you something please ?
12345<span class="Y2IQFc" lang="en">How to code capital protection? For example, if I have an initial capital of €5000, and after a few days I earn €1000,I must protect this new capital and put a stop for example at €1100. If my new capital subsequently drops to €800, I will leave the program.Thank you and have a good day.</span>09/21/2024 at 6:55 PM #237911Below is the post above … easier for readers …
Hello everybody,
May I ask you something please ?
How to code capital protection? For example, if I have an initial capital of €5000, and after a few days I earn €1000,I must protect this new capital and put a stop for example at €1100. If my new capital subsequently drops to €800, I will leave the program.Thank you and have a good day.09/23/2024 at 2:57 PM #237942Try this one:
1234567891011121314151617181920212223242526272829ONCE LockingPC = 20 //20% of profits to be locked inONCE TotalProfits = 0ONCE LockTreshold = 0MyLongConditions = close CROSSES OVER average[20,0](close) AND Not OnMarketIF MyLongConditions THENBUY 1 CONTRACT AT MARKETSL = close - (100 / PipSize)TP = close + (200 / PipSize)SET STOP PRICE SLSET TARGET PRICE TP//after any gain, the SL can't exceedd the locked profits tresholdIF LockTreshold > 0 THENSL = TradePrice - min(100,LockTreshold / PipValue)ENDIFSET STOP PRICE SLENDIF//check profits and set the treshold accordinglyIF (StrategyProfit - StrategyProfit[1]) THENTotalProfits = TotalProfits + (StrategyProfit - StrategyProfit[1])IF TotalProfits > 0 THENLockTreshold = max(0,max(LockTreshold,(TotalProfits * LockingPC / 100)))ENDIFENDIF//debugging instructionsgraph StrategyProfit - StrategyProfit[1]graph TotalProfits coloured("Blue")graph LockTreshold coloured("Red")graphonprice SL coloured("Red")graphonprice TP coloured("Blue") -
AuthorPosts