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
-
-
10/03/2022 at 2:19 AM #201803
Sorry for the delay, I’ll be back to you in a couple of days.
10/03/2022 at 2:48 PM #20184210/04/2022 at 5:14 AM #201883This is the working strategy I created for testing:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162SL = 300TP = SL * 5Sma = average[50,0](close)IF close CROSSES OVER Sma and Not OnMarket THENBUY at MarketELSIF close CROSSES UNDER Sma and Not OnMarket THENSELLSHORT at MarketENDIFSET STOP pLOSS SLSET TARGET pPROFIT TP////------------------------------------------------------------------------------------------------------------------------------------------------// Trailing Start//------------------------------------------------------------------------------------------------------------------------------------------------If 1 = 1 thenDirectionSwitch = (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//StartPerCentLong = 0.25 //0.25% to start triggering Trailing StopStartPerCentShort = 0.25StepPerCent = 0.5 //50% (of the 0.25% above) as a Trailing Step (set to 100 to make StepSize=TrailStart, set to 200 to make it twice TrailStart)BasePerCent = 0.08 //0.1-1 Profit percentage to keep when setting BreakEvenPerCentInc = 0.1 // 0.1-1 PerCent increment after each StepSize chunk//TrailStartLong = (close / PipSize) * StartPerCentLong / 100 //use current price (CLOSE) for calculationsTrailStartShort = (close / PipSize) * StartPerCentShort / 100 //use current price (CLOSE) for calculationsStepSizeLong = TrailStartLong * StepPerCent / 100StepSizeShort = TrailStartShort * StepPerCent / 100//RoundTO = -0.5 //-0.5 rounds always to Lower integer, +0.4 rounds always to Higher integer, 0 defaults PRT behaviourPriceDistance = 8 * 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 + ((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 - ((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 > (PositionPrice + (y1 * pipsize)) THEN //LONG positions//// compute the value of the Percentage of profits, if any, to lock in for LONG trades//x1 = (Close - PositionPrice) / pipsize //convert price to pipsIF x1 >= TrailStartLong THEN // go ahead only if N+ pipsDiff1 = abs(TrailStartLong - x1) //difference from current profit and TrailStartChunks1 = max(0,round((Diff1 / StepSizeLong) + 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 < (PositionPrice - (y2 * pipsize)) THEN //SHORT positions//// compute the value of the Percentage of profits, if any, to lock in for SHORT trades//x2 = (PositionPrice - Close) / pipsize //convert price to pipsIF x2 >= TrailStartShort THEN // go ahead only if N+ pipsDiff2 = abs(TrailStartShort - x2) //difference from current profit and TrailStartChunks2 = max(0,round((Diff2 / StepSizeShort) + 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 MarketENDIFENDIFEndif//EntryPrice = TradePriceIF Not OnMarket THENEntryPrice = 0StopPrice = 0TargetPrice = 0TrailPrice = 0ENDIFIF LongOnMarket THENStopPrice = EntryPrice - (SL * PipSize)TargetPrice = EntryPrice + (TP * PipSize)TrailPrice = SellPriceELSIF ShortOnMarket THENStopPrice = EntryPrice + (SL * PipSize)TargetPrice = EntryPrice - (TP * PipSize)TrailPrice = ExitPriceENDIFIF OnMarket THENgraphonprice TradePricegraphonprice StopPrice coloured(255,0,0,255)graphonprice TargetPrice coloured(0,128,0,155)graphonprice TrailPrice coloured(155,48,255,255)ENDIFchange values in lines 1-3, then lines 22-26, according to your preferences.
Then post:
- new settings
- instrument and TF used
so that I can test it.
10/09/2022 at 5:42 AM #202126Hi one thing I notice is that you are coding for the markets allowed exit price – how do you know that for a given market?
IF y2 THEN //Place pending STOP order when y2 > 0 (SHORT positions)ExitPrice = min(ExitPrice,PositionPrice – (y2 * pipsize))I have often when manually trading on charts been able to love a guaranteed stop (now in profit) and I can see on charts how far I can move it as it wont let you place it too close. Is there a way of coding for that (to absolutely lock in profits) – I think would have to start with guaranteed stops but thats ok.Lastly – the above post which has a strategy – if I wanted to use my own entry – am I correct that I would just omit lines 1 – 10? The rest seems to be an exit strategy10/11/2022 at 10:47 AM #202299As to your last question, YES, just replace the first ten lines with your code, as the trailing stop snippet is not tied to any code (provided you name your variables differently from mine).
As to the first part of your questions, will you please post a drawing with an example of what you mean. Thanks 🙂
10/22/2022 at 12:44 PM #202922I thought I had replied. Essentially with guaranteed stops there is a high ‘gap’ you cant set it in – and with ‘standard’ it still applies but is smaller. I have had issues with trailing stops (or if trailing stops are protecting profit) with the algo being stopped as its tried to place an ‘illegal order’. On charts I can see where I can place it and it wont let me move it to anywhere not allowed as per below. Is there a way of coding for this? ie knowing for that market what the closest I can go is? I think your algo above kind of does this?
10/30/2022 at 2:09 AM #203200When I trade manually (in this case IG) there is a minimum distance for stop loss- higher if guaranteed is selected. Sometimes my algos fail as they try to set it too close to current price. The number seems to be dynamic and is certainly different on each market. Is there a way to determine and code for this?
10/30/2022 at 2:27 AM #203202There’s no way to know when it changes. You must know it when you start your strategy and can’t change it while it’s running.
You may want to add some points to (try to) accomodate for those increases.
10/30/2022 at 5:20 AM #203213As far as I can tell this is related to the changing spread. Thus, when between USA Stock market’s closing and midnight (22:00 to 00:00 Amsterdam as long as daylight savings is equal to USA (which is not so the upcoming week)) … spread is increased to crazy numbers (e.g. 5 for NasDaq). This can be incorporated in the program, so you don’t need to deal with that distance (which is what it comes down to) throughout. Example :
123456789// When daylight savings are equal for our side and USA :If Time >= 153000 and Time < 220000 thenSpread = 1elsif Time >= 220000 and Time < 235959 then // IG says that this is >= 230000 but this can't be correct, IMO.Spread = 5elseSpread = 2endifThis in itself is to be incorporated in the stop distance.
… which I don’t do myself with the below as the result (Strategy stopped).
N.b.: I merely feel this is an anomaly at IG’s because the content of the message – 289 points – can’t be correct anyway, or I just don’t get it. What solves it, is not trading during that hour (only counts for 22:00 – 23:00 Amsterdam as after that it is closed for 1 hour), but net this is not worth it because it is a volatile time (earnings) and good trades may occur.Only once in a while this error occurs and only during that time, BUT have your distance correct in the first place.
Important : When the Strategy is run in Demo (account) this goes far more often wrong (say 10 times more). So this is a bit misleading and not so comfortable.
05/15/2024 at 8:32 AM #232660Hi Roberto.
Is TP used in this code?
This 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.
Is TP really used in this code?
05/15/2024 at 8:38 AM #232661It is used and set for sure.
It can be triggered, or not, depending on the settings of the trailing stop.
05/15/2024 at 9:26 AM #2326652 TP?1234567891011121314151617181920212223242526272829303132333435363738if CB thenBUY Positionsize CONTRACT AT MARKETset target %profit TPSET STOP %LOSS slendif// 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 = TP //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...PerCentTP1 = PerCentTP //2.0 //2.0% is TPPerCentStart1 = PerCentStart //0.2 //0.2% is the Trailing Stop trigger levelPerCentStep1 = 0.2 //0.2% is each subsequent stepPerCentSaved1 = 0.1 //0.1% is how much profit has to be saved when trailing starts and every stepMultiplier1 = 1.5 //1.5 is how much PerCentSaved is incremented each trailing stepDistance = 4//6 //6 pip distance from current price (if required by the broker)MySL = 0MySL1 = 0ProfitPerCent = 0ENDIFHi. should i use TP like this? at 2 places in code (line 19) . and in line 3?
05/15/2024 at 2:41 PM #232678Line 3 is OK, but lines 28-32 are never used, so why did you add them?
05/15/2024 at 2:45 PM #23268005/17/2024 at 12:27 PM #232762I only coded those lines once, in lines 17-21.
-
AuthorPosts
Find exclusive trading pro-tools on