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 6 months ago by robertogozzi.
Tagged: BreakEven, Profit, stop, trailing, trailingstop
-
-
04/01/2021 at 11:52 PM #165998
PositionPrice should be used instead of TradePrice, but the % modification suggested by nonetheless doesn’t work actually, because you should also change the lines where TrailStart is used to compare with the current price.
I coded it with pips in my mind, so the code would need some in-depth modifications to work with percentages.
04/02/2021 at 7:54 AM #166002I would have thought that
12ts = (positionprice*pc)/100 // % trailing startTrailStart = ts // Start trailing profits from this pointwould simply create a value for TrailStart, and then any further reference to TrailStart will relate to that value, no?
04/02/2021 at 8:53 AM #166008Line 56, for example, compares pips. It should be changed to compare percentages.
I think it woukd be better to convert a percentage into pips, in line 14:
1TrailStart = (close / PipSize) * pc / 100this will compute a percentage of the current price, before entering a trade, and convert it into pips.
You may also use your Equity instead of close, and change the expression:
1TrailStart = (MyEquity / PipValue) * pc / 100You can also use such expression for StepSize.
PriceDistance should be left as is, since it has no relation with risk and percentages.
With such minor modifications you will accommodate for percentages without modifying the logic of the code.
04/02/2021 at 9:19 AM #166017Sorry Roberto, I still don’t get it. 🤔
If pc = 0.25 and positionprice = 32000, then TrailStart will be 80
How is this different from simply entering TrailStart = 80 without the % calculation ?
Where Line 56 refers to TrailStart it would just read 80 and work with that … wouldn’t it?
04/02/2021 at 10:05 AM #166023Your assumption is correct because you are using SP500 o Nasdaq, or any other index with a price/pip ratio of 1. Try applying that percentage to, say, Aud/Chf which is 0.7167 with a price/pip ratio of 1/10000th!
If you want to use some code for your personal use you can do whatever you want because that suits your needs and you know what it does, but to make a code portable it must be coded so that it can be used on every instrument.
2 users thanked author for this post.
04/02/2021 at 11:06 AM #166027Ok, now I see what you’re getting at – and of course it makes total sense if you want to cross over into forex.
TBH, I mostly use the original version (from page 1), still gets great results when not using cumulative orders.
1 user thanked author for this post.
04/03/2021 at 11:46 AM #166092This is the new code with the addition of (optional) percentages as above (as suggested by nonetheless). I added a MINSTART to prevent TrailStart from dropping below ZERO when Equity (if you plan to use it) turns negative.
Define MyEquity somewhere in your code (even to ZERO if you don’t plan to use it):
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142//------------------------------------------------------------------------------------------------------------------------------------------------// Trailing Start//------------------------------------------------------------------------------------------------------------------------------------------------ONCE UseCLOSE = 1 //1=use CLOSE, 0=use High/LowsrcH = close //defaults to CLOSEsrcL = close //defaults to CLOSEIF UseCLOSE = 0 THENsrcH = highsrcL = lowENDIFONCE UsePerCentage = 0 //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)//DirectionSwitch = (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//StartPerCent = 0.25 //0.25% to start triggering Trailing Stop (when UsePerCentage=1)StepPerCent = 50 //50% (of the 0.25% above) as a Trqiling 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.200 //20.0% Profit percentage to keep when setting BerakEven//StepSize = 10 //10 Pip chunks to increase PercentageIF UsePerCentage THENStepSize = TrailStart * StepPerCent / 100ENDIF//PerCentInc = 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 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 MarketENDIFENDIF5 users thanked author for this post.
04/03/2021 at 12:07 PM #166094That’s a great addition. With forward testing it won’t matter that much whether you use % or points, but with backtesting up to 10 years ago, when index levels were a third or a quarter of what they are now, I think % is essential to get an accurate impression of past performance.
1 user thanked author for this post.
11/05/2021 at 8:59 PM #181081This one is seriously amazing. Great work!
My brain is getting fried. I was trying theoretically to come up with the solution before I tried to change the code, but I’m stuck.
What I want to achieve is to add a target at let’s say 2%. The trailing starts at 0.2%. The closer it gets to the 2%, the tighter the trailing stop is. So theoretically, when you hit 2%, it’s basically a TP.
Any ideas?
11/06/2021 at 1:36 PM #181123I decided to code a new one, instead of changing the above code (tested on DAX, Daily TF):
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394Avg = average[100,0](close)IF not OnMarket THENIF close CROSSES OVER Avg THENBUY AT MARKETELSIF close CROSSES UNDER Avg THENSELLSHORT AT MARKETENDIFSL = close / 100 * 2 //2% SLSET STOP LOSS SLENDIF//// incremental Trailing Stop (based on Percentages)//NewTrade = (OnMarket AND Not OnMarket[1]) OR (LongOnMarket AND ShortOnMarket[1]) OR (LongOnMarket[1] AND ShortOnMarket)//IF Not OnMarket OR NewTrade THEN //reset to default values when a new trade has been openedPerCentTP = 2.0 //2.0% is TPPerCentStart = 0.2 //0.2% is the Trailing Stop trigger levelPerCentStep = 0.2 //0.2% is each subsequent stepPerCentSaved = 0.1 //0.1% is how much profit has to be saved when trailing starts and every stepMultiplier = 1.5 //1.5 is how much PerCentSaved is incremented each trailing step// 1.5 is a 50% increment, so that:// 0.1% becomes 0.15%, then// 0.15% becomes 0.225%, then// 0.225% becomes 0.3375%, etc...Distance = 6 //6 pip distance from current price (if required by the broker)MySL = 0ProfitPerCent = 0ENDIFIF OnMarket THENIF MySL = 0 THENPCent = PositionPrice * PerCentTP / 100PStart = PositionPrice * PerCentStart / 100PStep = PositionPrice * PerCentStep / 100PSaved = PositionPrice * PerCentSaved / 100ENDIF//// check if Trailing Stop has to be triggered//IF MySL = 0 THENIF LongOnMarket THENIF (close - PositionPrice) >= PStart THENMySL = min(close,PositionPrice + PSaved)PSaved = PSaved * MultiplierENDIFELSIF ShortOnMarket THENIF (PositionPrice - close) >= PStart THENMySL = max(close,PositionPrice - PSaved)PSaved = PSaved * MultiplierENDIFENDIFELSE//// check if another Step has been triggered//IF LongOnMarket THENIF (close - MySL) >= PStep THENMySL = min(close,MySL + PSaved)PSaved = PSaved * MultiplierENDIFELSIF ShortOnMarket THENIF (MySL - close) >= PStep THENMySL = max(close,MySL - PSaved)PSaved = PSaved * MultiplierENDIFENDIFENDIF//// place Pending STOP orders//IF MySL > 0 THENIF (MySL = close) OR (abs(MySL - close) < Distance) THEN //exit immediately in case MySL has reached// the current price or there's not enough DISTANCESELL AT MARKETEXITSHORT AT MARKETELSESELL AT MySL STOPEXITSHORT AT MySL STOPENDIFENDIFENDIF//graphonprice PositionPrice coloured(0,0,0,255) AS "Entry"graphonprice MySL coloured(0,128,0,155) AS "Trailing Stop"IF LongOnMarket THENgraphonprice PositionPrice - SL coloured(255,0,0,255) AS "Stop Loss"ELSEgraphonprice PositionPrice + SL coloured(255,0,0,255) AS "Stop Loss"ENDIFgraph PCent coloured(0,0,0,255)graph PStart coloured(0,0,255,255)graph PStep coloured(0,128,0,155)graph PSaved coloured(255,0,0,255)graph positionperf * positionprice / pipsize AS "Gain"2 users thanked author for this post.
11/06/2021 at 1:42 PM #181124Holy smokes! You are amazing!
Will give it a try today. I think it will work great for some of the strategies that hold for longer and are in quite high profits. With the old one, the gap between the SL and current price was getting bigger and bigger, so it gave back quite a lot of the profit.
Thank you!
11/06/2021 at 2:36 PM #181127Link to code above added as Log 310 here …
1 user thanked author for this post.
11/11/2021 at 8:08 PM #18146511/12/2021 at 12:57 AM #181474This is the same code as above (test code not included), with more comments:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283// NewTrade is true whenever a new trade is opened, be it://// - a trade when there was none previously// - a trade that has changed direction due to a Stop & Reverse (it's Long and previously was Short and viceversa)//// This will be useful to reset variables to their initial values after a trade has been opened.//NewTrade = (OnMarket AND Not OnMarket[1]) OR (LongOnMarket AND ShortOnMarket[1]) OR (LongOnMarket[1] AND ShortOnMarket)//// Reset variables to their initial value when a new trade shows//IF Not OnMarket OR NewTrade THEN //reset to default values when a new trade has been opened (or none is OnMarket)PerCentTP = 2.0 //2.0% is TPPerCentStart = 0.2 //0.2% is the Trailing Stop trigger levelPerCentStep = 0.2 //0.2% is each subsequent stepPerCentSaved = 0.1 //0.1% is how much profit has to be saved when trailing starts and every stepMultiplier = 1.5 //1.5 is how much PerCentSaved is incremented each trailing step// 1.5 is a 50% increment, so that:// 0.1% becomes 0.15%, then// 0.15% becomes 0.225%, then// 0.225% becomes 0.3375%, etc...Distance = 6 //6 pip distance from current price (if required by the broker)MySL = 0ProfitPerCent = 0ENDIF//// The trailing stop can operate only when OnMarket//IF OnMarket THEN//// before the trailing stop is triggered some calculations need to be done, accordin to settings//IF MySL = 0 THENPCent = PositionPrice * PerCentTP / 100PStart = PositionPrice * PerCentStart / 100PStep = PositionPrice * PerCentStep / 100PSaved = PositionPrice * PerCentSaved / 100ENDIF//// check if Trailing Stop has to be triggered//IF MySL = 0 THENIF LongOnMarket THENIF (close - PositionPrice) >= PStart THENMySL = min(close,PositionPrice + PSaved)PSaved = PSaved * MultiplierENDIFELSIF ShortOnMarket THENIF (PositionPrice - close) >= PStart THENMySL = max(close,PositionPrice - PSaved)PSaved = PSaved * MultiplierENDIFENDIFELSE//// check if another Step has been triggered//IF LongOnMarket THENIF (close - MySL) >= PStep THENMySL = min(close,MySL + PSaved)PSaved = PSaved * MultiplierENDIFELSIF ShortOnMarket THENIF (MySL - close) >= PStep THENMySL = max(close,MySL - PSaved)PSaved = PSaved * MultiplierENDIFENDIFENDIF//// place Pending STOP orders//IF MySL > 0 THENIF (MySL = close) OR (abs(MySL - close) < Distance) THEN //exit immediately in case MySL has reached// the current price or there's not enough DISTANCESELL AT MARKETEXITSHORT AT MARKETELSESELL AT MySL STOPEXITSHORT AT MySL STOPENDIFENDIFENDIFif you have more questions don’t hesitate to ask.
11/12/2021 at 6:36 AM #181477Thanks roberto.
Is their a function abow that does:
When x% profit sl jumps to x% profit.
Exemple: When 1% profit sl jumps to 0.1% profit.
Lets call it “breakeven jump-code” 😊
Would u like to explan MyEquity and how it works and how to use it.
Sorry for asking so much ☺
-
AuthorPosts
Find exclusive trading pro-tools on