BreakEven & Trailing Profit: complete function

Viewing 15 posts - 1 through 15 (of 138 total)
  • Author
    Posts
  • #93959 quote
    robertogozzi
    Moderator
    Master

    The purpose of this code is to:

    • set BreakEven after TRAILSTART profit (in Pips)
    • add a Percentage (BASEPERCENT) to lock in some profits
    • increase that Percentage each STEPSIZE chunk of pips (20% will increase BASEPERCENT by a factor of 0.20, thus, say 30%, would become 36% after the first step, then 43.2 on the second step and so on…) to lock in more profits as they move towards TP
    • make sure the exit price meets the broker’s minimun distance requirements to avoid unpredictable exits
    IF Not OnMarket THEN
       //
       // when NOT OnMarket reset values to default values
       //
       TrailStart    = 30          //30     Start trailing profits from this point
       BasePerCent   = 0.200       //20.0%  Profit percentage to keep when setting BerakEven
       StepSize      = 10          //10     Pip chunks to increase Percentage
       PerCentInc    = 0.100       //10.0%  PerCent increment after each StepSize chunk
       RoundTO       = -0.5        //-0.5   rounds always to Lower integer,   +0.4 rounds always to Higher integer,     0 defaults PRT behaviour
       PriceDistance = 7 * pipsize //7      minimun distance from current price
       y1            = 0           //reset to 0
       y2            = 0           //reset to 0
       ProfitPerCent = BasePerCent //reset to desired default value
    ELSIF 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 pips
       IF x1 >= TrailStart THEN                                                //    go ahead only if N+ pips
          Diff1         = abs(TrailStart - x1)                                 //difference from current profit and TrailStart
          Chunks1       = max(0,round((Diff1 / StepSize) + RoundTO))           //number of STEPSIZE chunks
          ProfitPerCent = BasePerCent + (BasePerCent * (Chunks1 * PerCentInc)) //compute new size of ProfitPerCent
          ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent))         //make sure ProfitPerCent doess not exceed 100%
          y1 = max(x1 * ProfitPerCent, y1)                                     //y1 = % of max profit
       ENDIF
    ELSIF 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 pips
       IF x2 >= TrailStart THEN                                                //      go ahead only if N+ pips
          Diff2         = abs(TrailStart - x2)                                 //difference from current profit and TrailStart
          Chunks2       = max(0,round((Diff2 / StepSize) + RoundTO))           //number of STEPSIZE chunks
          ProfitPerCent = BasePerCent + (BasePerCent * (Chunks2 * PerCentInc)) //compute new size of ProfitPerCent
          ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent))         //make sure ProfitPerCent doess not exceed 100%
          y2 = max(x2 * ProfitPerCent, y2)                                     //y2 = % of max profit
       ENDIF
    ENDIF
    IF 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 THEN
             SELL AT SellPrice STOP
          ELSE
             SELL AT SellPrice LIMIT
          ENDIF
       ELSE
          //
          //sell AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price
    	  //
          SELL AT Market
       ENDIF
    ENDIF
    IF 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 THEN
             EXITSHORT AT ExitPrice STOP
          ELSE
             EXITSHORT AT ExitPrice LIMIT
          ENDIF
       ELSE
          //
    	  //ExitShort AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price
    	  //
          EXITSHORT AT Market
       ENDIF
    ENDIF
    Nicolas, Paul, Francesco and 7 others thanked this post
    #130423 quote
    nonetheless
    Participant
    Master

    Ciao Roberto, thanks for linking to this – looks really interesting, wish I’d seen it months ago.

    If I wanted to convert both the trailing start and step to %, does this look right? not sure if it should be done onmarket or not onmarket?

    IF Not OnMarket THEN
    //
    // when NOT OnMarket reset values to default values
    trailingPercent = .15
    stepPercent = .01//
    TrailStart    = tradeprice(1)*(trailingpercent/100)         //%    Start trailing profits from this point
    StepSize      = tradeprice(1)*(stepPercent/100)         //% step
    #130442 quote
    robertogozzi
    Moderator
    Master

    No, it changes the logic, other lines need to be changed.

    I will try to do it asss asap.

    #130605 quote
    nonetheless
    Participant
    Master

    it changes the logic

    yes, I see that now – both TrailStart and Stepsize are used in the calculation. I didn’t look at it that closely. Never mind, I can use it as is with fixed values. Thanks again.

    #130664 quote
    nonetheless
    Participant
    Master

    Astonishing result – is this even possible? to change one component and double the profit? Kills the %win but who cares. Left is with Nicolas’s %TS, right is yours with these settings:

    TrailStart    = 24          //30     Start trailing profits from this point
    BasePerCent   = 10       //20.0%  Profit percentage to keep when setting BerakEven
    StepSize      = 2.5          //10     Pip chunks to increase Percentage
    PerCentInc    = 2       //10.0%  PerCent increment after each StepSize chunk

    Scarcely believable. Unfortunately I’ve not seen this kind of improvement on other algos, but there is always an improvement (and always at the cost of reduced %win).

    Sei un genio, grazie mille!

    #130668 quote
    robertogozzi
    Moderator
    Master

    Did you change the logic?

    Because the logic I used when I wrote it was such that

    BasePerCent   = 10

    assigns BasePerCent a percentage of 1000%, which means that any trade will be exited as soon as it reaches 24 pips.

    10%, as I wrote it, should be 0.1.

    But this may be positive if it yields more profits, provided drawdown doesn’t increase much.

    #130671 quote
    nonetheless
    Participant
    Master

    Ah, that would explain a few things. I saw the 20% rem’d out and overlooked that you had already calculated the % as a decimal. Same with PerCentInc. Strange though, that the optimiser was happy to work with integer values for both of those. I’ll run it again with decimal values.

    #130672 quote
    nonetheless
    Participant
    Master

    Ok, sanity is restored, all’s right with the world. A modest improvement of every metric – this is much better.

    TrailStart    = 25        //30     Start trailing profits from this point
    BasePerCent   = .05       //20.0%  Profit percentage to keep when setting BerakEven
    StepSize      = 6          //10     Pip chunks to increase Percentage
    PerCentInc    = .02       //10.0%  PerCent increment after each StepSize chunk
    swedshare, Razz and Midlanddave thanked this post
    #132382 quote
    stefou102
    Participant
    Veteran

    Hello Roberto,

    trying your code, I have found that in the following case, the code is bugging.

    Case: if you have one big candle where your profit jump in one shot, and you use a small Stepsize parameter, then ProfitPerCent becomes huge and so does the sellprice/exitprice vs latest price

    #132388 quote
    robertogozzi
    Moderator
    Master

    That’s what I intended to do, just increase the percentage as chunks (lines 20-23 and 32-35) of StepSize profits show.

    I understand what you mean, you can address it by decreasing PerCentInc or  increasing StepSize or, say, halving chunks (adding a line between 21 and 22):

    Chunks1       = max(1,Chunks1 * 0.50)    //no need to round it

    the same between lines 33-34 with Chunks2.

    #132389 quote
    robertogozzi
    Moderator
    Master

    You could also add a check that this adjustment be done only when chunks are more than N or when a candle’s body is, say, twice its 20-period average.

    There’s no limit to further development and customization.

    stefou102 thanked this post
    #141006 quote
    christofferR
    Participant
    Average

    Hi,

    Will this code overwrite a stop loss sett at opening of a position?

    Or is it possible to modify this so a stop loss is created at opening and then starts trailing if the position is plus?

     

    Best,

    Christoffer

    #141010 quote
    robertogozzi
    Moderator
    Master

    You should also use SET STOP LOSS, since they are different and can be used together.

    This code deals only with trailing stop, not the stop itself.

    #151457 quote
    FKNO
    Participant
    New

    Hello Roberto,

    Thank you for this very nice piece of code! I’m very new into this and have used this code in one of my first algos that I’m testing in Demo with good results. I’m very happy with the entry criterias for my algo but I find it to be in the market for too long to “keep the edge” of the entry and would therefore like to try a thought that I have to add a function so that the Trailing Stop slowly increases (for a long order) even if the market lose momentum and the close price is not moving.

    For example by counting bars since starting the trailing and increase the Breakeven x% per bar that pass.

    I have not managed to solve this in a good way on my own, so I’m now turning to you. Any thoughts of a good way to add such a feature to this code?

    THX!

    #151589 quote
    robertogozzi
    Moderator
    Master

    I added a number of bars to add an additional percentage, so that the trade will exit shorter:

    IF Not OnMarket THEN
       //
       // when NOT OnMarket reset values to default values
       //
       TrailStart    = 30          //30     Start trailing profits from this point
       BasePerCent   = 0.200       //20.0%  Profit percentage to keep when setting BerakEven
       StepSize      = 10          //10     Pip chunks to increase Percentage
       PerCentInc    = 0.100       //10.0%  PerCent increment after each StepSize chunk
       BarNumber     = 10          //10     Add further % so that trades don't keep running too long
       BarPerCent    = 0.100       //10%    Add this additional percentage every BarNumber bars
       RoundTO       = -0.5        //-0.5   rounds always to Lower integer,   +0.4 rounds always to Higher integer,     0 defaults PRT behaviour
       PriceDistance = 7 * pipsize //7      minimun distance from current price
       y1            = 0           //reset to 0
       y2            = 0           //reset to 0
       ProfitPerCent = BasePerCent //reset to desired default value
       TradeBar      = BarIndex
    ELSIF 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 pips
       IF x1 >= TrailStart THEN                                                //    go ahead only if N+ pips
          Diff1         = abs(TrailStart - x1)                                 //difference from current profit and TrailStart
          Chunks1       = max(0,round((Diff1 / StepSize) + RoundTO))           //number of STEPSIZE chunks
          ProfitPerCent = 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 - TradeBar
          IF BarCount MOD BarNumber = 0 THEN
             ProfitPerCent = ProfitPerCent + BarPerCent
          ENDIF
          //
          ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent))         //make sure ProfitPerCent doess not exceed 100%
          y1 = max(x1 * ProfitPerCent, y1)                                     //y1 = % of max profit
       ENDIF
    ELSIF 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 pips
       IF x2 >= TrailStart THEN                                                //      go ahead only if N+ pips
          Diff2         = abs(TrailStart - x2)                                 //difference from current profit and TrailStart
          Chunks2       = max(0,round((Diff2 / StepSize) + RoundTO))           //number of STEPSIZE chunks
          ProfitPerCent = 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 - TradeBar
          IF BarCount MOD BarNumber = 0 THEN
             ProfitPerCent = ProfitPerCent + BarPerCent
          ENDIF
          //
          ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent))         //make sure ProfitPerCent doess not exceed 100%
          y2 = max(x2 * ProfitPerCent, y2)                                     //y2 = % of max profit
       ENDIF
    ENDIF
    IF 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 THEN
             SELL AT SellPrice STOP
          ELSE
             SELL AT SellPrice LIMIT
          ENDIF
       ELSE
          //
          //sell AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price
    	  //
          SELL AT Market
       ENDIF
    ENDIF
    IF 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 THEN
             EXITSHORT AT ExitPrice STOP
          ELSE
             EXITSHORT AT ExitPrice LIMIT
          ENDIF
       ELSE
          //
    	  //ExitShort AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price
    	  //
          EXITSHORT AT Market
       ENDIF
    ENDIF
Viewing 15 posts - 1 through 15 (of 138 total)
  • You must be logged in to reply to this topic.

BreakEven & Trailing Profit: complete function


ProOrder support

New Reply
Author
Summary

This topic contains 137 replies,
has 23 voices, and was last updated by Wim
5 months, 1 week ago.

Topic Details
Forum: ProOrder support
Language: English
Started: 03/18/2019
Status: Active
Attachments: 25 files
Logo Logo
Loading...