BreakEven & Trailing Profit: complete function

Viewing 15 posts - 106 through 120 (of 138 total)
  • Author
    Posts
  • #201803 quote
    robertogozzi
    Moderator
    Master

    Sorry for the delay, I’ll be back to you in a couple of days.

    #201842 quote
    SnorreDK
    Participant
    Junior

    Hi Roberto.

    If i understand your code correct it moves limit and stolploss.

    Would you make a version with trailing limit. Where stoploss is not part of the code at all?

    #201883 quote
    robertogozzi
    Moderator
    Master

    @SnorreDK

    This is the working strategy I created for testing:

    SL = 300
    TP = SL * 5
    Sma = average[50,0](close)
    IF close CROSSES OVER Sma and Not OnMarket THEN
    BUY at Market
    ELSIF close CROSSES UNDER Sma and Not OnMarket THEN
    SELLSHORT at Market
    ENDIF
    SET STOP   pLOSS   SL
    SET TARGET pPROFIT TP
    //
    //------------------------------------------------------------------------------------------------------------------------------------------------
    //                     Trailing Start
    //------------------------------------------------------------------------------------------------------------------------------------------------
    If 1 = 1 then
    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
    //
    StartPerCentLong  = 0.25    //0.25%  to start triggering Trailing Stop
    StartPerCentShort = 0.25
    StepPerCent       = 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 BreakEven
    PerCentInc        = 0.1     // 0.1-1    PerCent increment after each StepSize chunk
    //
     
    TrailStartLong = (close / PipSize) * StartPerCentLong / 100        //use current price (CLOSE) for calculations
    TrailStartShort = (close / PipSize) * StartPerCentShort / 100       //use current price (CLOSE) for calculations
     
    StepSizeLong   = TrailStartLong * StepPerCent / 100
    StepSizeShort   = TrailStartShort * StepPerCent / 100
     
    //
    RoundTO       = -0.5        //-0.5   rounds always to Lower integer,   +0.4 rounds always to Higher integer,     0 defaults PRT behaviour
    PriceDistance = 8 * pipsize //7      minimun distance from current price
    y1            = 0           //reset to 0
    y2            = 0           //reset to 0
    ProfitPerCent = BasePerCent //reset to desired default value
    //PositionCount = 0
    SellPrice     = 0
    SellPriceX    = 0
    ExitPrice     = 9999999
    ExitPriceX    = 9999999
    ELSE
    //------------------------------------------------------
    // --- 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 trailing
    IF PositionPrice <> PositionPrice[1] AND (ExitPrice + SellPrice) <> 9999999 THEN //go on only if Trailing Stop had already started trailing
    IF LongOnMarket THEN
    q1         = PositionPrice + ((Close - PositionPrice) * ProfitPerCent)      //calculate new SL
    SellPriceX = 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 one
    ELSIF ShortOnMarket THEN
    r1         = PositionPrice - ((PositionPrice - Close) * ProfitPerCent)      //calculate new SL
    ExitPriceX = 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 one
    ENDIF
    ENDIF
    // --- Update END
    ENDIF
    //
    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 pips
    IF x1 >= TrailStartLong THEN                                                //    go ahead only if N+ pips
    Diff1         = abs(TrailStartLong - x1)                                 //difference from current profit and TrailStart
    Chunks1       = max(0,round((Diff1 / StepSizeLong) + 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 < (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 pips
    IF x2 >= TrailStartShort THEN                                                //      go ahead only if N+ pips
    Diff2         = abs(TrailStartShort - x2)                                 //difference from current profit and TrailStart
    Chunks2       = max(0,round((Diff2 / StepSizeShort) + 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
    //------------------------------------------------------------------------------
    //                    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 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 = 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 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
    Endif
    //
    EntryPrice = TradePrice
    IF Not OnMarket THEN
    EntryPrice  = 0
    StopPrice   = 0
    TargetPrice = 0
    TrailPrice  = 0
    ENDIF
    IF LongOnMarket THEN
    StopPrice   = EntryPrice - (SL * PipSize)
    TargetPrice = EntryPrice + (TP * PipSize)
    TrailPrice  = SellPrice
    ELSIF ShortOnMarket THEN
    StopPrice   = EntryPrice + (SL * PipSize)
    TargetPrice = EntryPrice - (TP * PipSize)
    TrailPrice  = ExitPrice
    ENDIF
    IF OnMarket THEN
    graphonprice TradePrice
    graphonprice StopPrice   coloured(255,0,0,255)
    graphonprice TargetPrice coloured(0,128,0,155)
    graphonprice TrailPrice  coloured(155,48,255,255)
    ENDIF

    change 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.

    #202126 quote
    ausrod
    Participant
    New

    Hi 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 strategy
    #202299 quote
    robertogozzi
    Moderator
    Master

    As 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 🙂

    #202922 quote
    ausrod
    Participant
    New

    I 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?

    #203200 quote
    ausrod
    Participant
    New

    When 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?

    #203202 quote
    robertogozzi
    Moderator
    Master

    There’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.

    #203213 quote
    PeterSt
    Participant
    Master

    @ausrod,

    As 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 :

    // When daylight savings are equal for our side and USA :
    
    If Time >= 153000 and Time < 220000 then
      Spread = 1
    elsif Time >= 220000 and Time < 235959 then   // IG says that this is >= 230000 but this can't be correct, IMO.
      Spread = 5
    else
      Spread = 2
    endif

    This 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.

    #232660 quote
    SnorreDK
    Participant
    Junior

    Hi Roberto.

    Is TP used in this code?

    This is the same code as above (test code not included), with more comments:

    if you have more questions don’t hesitate to ask.

    Is TP really used in this code?

    #232661 quote
    robertogozzi
    Moderator
    Master

    It is used and set for sure.

    It can be triggered, or not, depending on the settings of the trailing stop.

    #232665 quote
    SnorreDK
    Participant
    Junior
    if CB  then
    BUY Positionsize CONTRACT AT MARKET
    set target %profit TP
    SET STOP %LOSS sl
    endif
    
    // 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 TP
    PerCentStart  = 0.2           //0.2%  is the Trailing Stop trigger level
    PerCentStep   = 0.2           //0.2%  is each subsequent step
    PerCentSaved  = 0.1           //0.1%  is how much profit has to be saved when trailing starts and every step
    Multiplier    = 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 TP
    PerCentStart1  = PerCentStart           //0.2           //0.2%  is the Trailing Stop trigger level
    PerCentStep1   = 0.2           //0.2%  is each subsequent step
    PerCentSaved1  = 0.1           //0.1%  is how much profit has to be saved when trailing starts and every step
    Multiplier1    = 1.5           //1.5   is how much PerCentSaved is incremented each trailing step
    
    Distance      = 4//6             //6     pip distance from current price (if required by the broker)
    MySL          = 0
    MySL1          = 0
    ProfitPerCent = 0
    ENDIF

    Hi. should i use TP like this? at 2 places in code (line 19) . and in line 3?

    #232678 quote
    robertogozzi
    Moderator
    Master

    Line 3 is OK, but lines 28-32 are never used, so why did you add them?

    #232680 quote
    SnorreDK
    Participant
    Junior
    #232762 quote
    robertogozzi
    Moderator
    Master

    I only coded  those lines once, in  lines 17-21.

Viewing 15 posts - 106 through 120 (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...