Complete trailing stop code function

 

A lot of people on forums asked for an alternative to the embedded trailing stop instruction of Probacktest. So I decided to code a complete function that can be implemented to any trading strategy.

When trades go well, we often need to protect gain against market turnaround. To do this, we need to move progressively our stoploss to safer zones, a trailing stop can achieve this functionality.

Also, because there is some difference between the embedded trailing stop of the platform in backtest in comparison of real time trading, a hard coded trailing stop is a better option I believe, to make backtest more accurate to what would happen in live trading.

First step, setting our variables

Firstly, we need to activate the trailing stop functionality of our function. So we need to set a profit level where we’ll begin to move our stoploss.

We set a variable “trailingstart” :

Indeed, trailing will start when trade will be in profit of at least 20 points in our example.

Then, we need to set a step of profit to continuously move the stoploss accordingly to the price movement:

Each time the price move in favour of the trade, the stoploss will move of “trailingstep” to protect more profit.

So now, in order to exit a position at defined price level, we use a new variable called “newSL” that will settled a pending stop order. This variable will be calculated on the fly each time the price has moved favourably.

When we are not in market, this variable is reset:

 

Set our trades to breakeven, at first good move

For this example, we only consider long positions.

If “newSL” is 0 (no move before) and the price went up at least “trailingstart” points from our price entry, we set our new stoploss at price entry + “trailingstep” points.

For our long position to exit at that level, we need to set now a sell position order with a pending stop one:

That’s it, we have set our trade to breakeven.

 

Next moves, trailing stop the position

Now that our trade is safe, we’ll move our stoploss of “trailingstep” each time price move of “trailingstep” too.

We add the “next moves” lines into our previous code:

Trailing stop coded!

 

What to expect with a trailing stop in a trading strategy?

Trailing stop can be a profit shower or a profit cutter, it depends of your strategy, the instrument traded and time horizon of your trade. Nevertheless it can improve a lot simple trend following strategy and prevent loss because of market whipsaws, especially in volatile market and short timeframe.

In the next paragraph, you’ll find the whole code to use for your own strategy. In this picture below the test of a simple SELL condition trading (close<close[1]):

trailing stop code prorealtimeSo it’s up to you to improve your already made strategies or to create new ones! I count on you to share them on ProRealCode! 🙂

 

Trailing stop, the complete ProRealTime code

ITF file is attached too. Enjoy and ask questions in comments if you need better explanation.

 

Share this

  1. sylvess • 05/11/2016 #

    Hi Nicolas,
    Love your postings, great work. Tested this and found it necessary to use ElSIF after “//first move” to prevent execution of the next IF. Otherwise, there is a possibility newSL will get computed again, bringing the trailing stop closer then intended

    • Nicolas • 05/11/2016 #

      Hi and thanks sylvess. I’m not sure to understand, because newSL is only compute once if its value is equal to 0.

    • ALEALE • 05/11/2016 #

      HELLO NICOLAS ,
      IT IS CORRECT THIS CODE?:
      TRAILINGSTOPLONG= 47TRAILINGSTOPLOSS= 41
      //resetting variables when no trades are on marketif not onmarket thenMAXPRICE = 0MINPRICE = closepriceexit = 0endif
      //case SHORT orderif shortonmarket thenMINPRICE = MIN(MINPRICE,close) //saving the MFE of the current tradeif tradeprice(1)-MINPRICE>=TRAILINGSTOPLOSS*pointsize then //if the MFE is higher than the TRAILINGSTOPLOSS thenpriceexit = MINPRICE+TRAILINGSTOPLOSS*pointsize //set the exit price at the MFE + trailing stop price levelendifendif
      //case LONG orderif longonmarket thenMAXPRICE = MAX(MAXPRICE,close) //saving the MFE of the current tradeif MAXPRICE-tradeprice(1)>=TRAILINGSTOPLONG*pointsize then //if the MFE is higher than the trailingstop thenpriceexit = MAXPRICE-TRAILINGSTOPLONG*pointsize //set the exit price at the MFE – trailing stop price levelendifendif
      //exit on trailing stop price levelsif onmarket and priceexit>0 thenEXITSHORT AT priceexit STOPSELL AT priceexit STOPendif
      TKS
      ALE

    • Nicolas • 05/11/2016 #

      Seems OK to me.

    • anthuvan • 05/11/2016 #

      Hi Nicolas, modified your code and tried running it however the strategy is not getting triggered when the condition that I set was true.
      For example I have set the CCI to be below 0 to trigger the short order however it didnt get triggered. Suspect the order command which i have changed to amount instead of LOT. could you please debug this code for me.

      defparam cumulateorders = false

      //order launch (example) would be set to any other entry conditions
      //c1 = close>close[1]
      c2 = close=trailingstart*pipsize THEN
      newSL = tradeprice(1)+trailingstep*pipsize
      ENDIF
      //next moves
      IF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
      newSL = newSL+trailingstep*pipsize
      ENDIF
      ENDIF

      //manage short positions
      IF SHORTONMARKET THEN
      //first move (breakeven)
      IF newSL=0 AND tradeprice(1)-close>=trailingstart*pipsize THEN
      newSL = tradeprice(1)-trailingstep*pipsize
      ENDIF
      //next moves
      IF newSL>0 AND newSL-close>=trailingstep*pipsize THEN
      newSL = newSL-trailingstep*pipsize
      ENDIF
      ENDIF

      //stop order to exit the positions
      IF newSL>0 THEN
      SELL AT newSL STOP
      EXITSHORT AT newSL STOP
      ENDIF
      //************************************************************************

    • Nicolas • 05/11/2016 #

      Your code is not complete, please open a new topic in the ProOrder forum, and please respect the posting rules: good title, description, etc.

  2. Dymjohn • 05/11/2016 #

    Hi Nicolas,
    I much prefer this method but as a newbie to proreal time I don’t know how to link to the strategy I’ve written attached. Can you help please?
    // Definition of code parameters
    DEFPARAM CumulateOrders = False // Cumulating positions deactivated
    //DEFPARAM NOCASHUPDATE = True //cash not updated with gains
    DEFPARAM FLATBEFORE = 081000 //cancels and closes all trades before this time
    DEFPARAM FLATAFTER = 162000 //prevents new orders after 16:15 closes out orders
    // prices to enter trade
    BuyPrice = High[0]+ 2*PointSize
    SellPrice = Low[0] - 2*PointSize
    //ProfTarget = ROUND(AverageTrueRange[5](close))*2

    // Conditions to enter long positions

    indicator1,ignored,ignored,ignored = CALL \"MY MACD\"
    indicator2 = close
    indicator3 = Average[50](close)
    c1 = (indicator1 > 4)
    c2 = (indicator2 > indicator3)

    IF c1 AND c2 THEN
    BUY 1 SHARES AT BuyPrice STOP
    ENDIF

    // Conditions to exit long positions
    indicator4 = Average[14](Momentum[14](close))
    indicator5 = Momentum[14](close)
    c3 = (indicator4 CROSSES OVER indicator5)
    c11 = (indicator1 < 0)
    IF c3 OR c11 THEN
    SELL AT MARKET

    ENDIF

    // Conditions to enter short positions
    indicator6 = close
    indicator7 = Average[50](close)
    c4 = (indicator6 < indicator7)

    indicator8, ignored, ignored, ignored = CALL \"MY MACD\"
    c5 = (indicator8 < -1)

    IF c4 AND c5 THEN
    SELLSHORT 1 SHARES AT SellPrice STOP
    ENDIF

    // Conditions to exit short positions
    indicator9 = Average[14](Momentum[14](close))
    indicator10 = Momentum[14](close)
    indicator11 = Average[50](close)
    indicator12 = close
    c6 = (indicator9 CROSSES UNDER indicator10)
    c12 = (indicator11 CROSSES OVER indicator12)

    IF c6 OR c12 THEN
    EXITSHORT AT MARKET

    SET TARGET pPROFIT 150
    //trailing stop function

    trailingstart = 200 //trailing will start @trailinstart points profit
    trailingstep = 50 //trailing step to move the \"stoploss\"

    //reset the stoploss value
    IF NOT ONMARKET THEN
    newSL=0
    ENDIF

    //manage long positions
    IF LONGONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND close-tradeprice(1)>=trailingstart*pipsize THEN
    newSL = tradeprice(1)+trailingstep*pipsize
    ENDIF
    //next moves
    IF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
    newSL = newSL+trailingstep*pipsize
    ENDIF
    ENDIF

    //manage short positions
    IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND tradeprice(1)-close>=trailingstart*pipsize THEN
    newSL = tradeprice(1)-trailingstep*pipsize
    ENDIF
    //next moves
    IF newSL>0 AND newSL-close>=trailingstep*pipsize THEN
    newSL = newSL-trailingstep*pipsize
    ENDIF
    ENDIF

    //stop order to exit the positions
    IF newSL>0 THEN
    SELL AT newSL STOP
    EXITSHORT AT newSL STOP
    ENDIF
    //************************************************************************

    GRAPH newSL as \"trailing\"
    ENDIF

     

    • Nicolas • 05/11/2016 #

      It should work in your strategy.But you need to make the trailing start before your target profit otherwise the trailing stop will never start.

    • pcorbeij • 05/11/2016 #

      Nicolas
       
      I have written the below code but i dont know how to insert your amazing code for my system I would be so grateful if you would be able to help me with this
      kind regards
      paul
      // Definition of code parameters
      DEFPARAM CumulateOrders = False // Cumulating positions deactivated

      QTY=2
      ONCE M=500
      BANK=100

      ONCE PQTYADJUST=0

      QTYADJUST = ROUND(STRATEGYPROFIT /M)

      IF QTYADJUST > 0 THEN

      QTY=QTY+QTYADJUST

      IF QTYADJUST < PQTYADJUST THEN
      M=M+BANK
      PQTYADJUST=QTYADJUST
      ENDIF
      IF QTYADJUST > PQTYADJUST THEN
      PQTYADJUST=QTYADJUST
      ENDIF

      ELSE
      QTY=2
      //PQTYADJUST=QTYADJUST
      ENDIF
      // Conditions to enter long positions
      indicator1 = Average[20](close)
      indicator2 = Average[50](close)
      c1 = (indicator1 > indicator2)

      indicator3 = Stochastic[5,3](close)
      indicator4 = Average[3](Stochastic[5,3](close))
      c2 = (indicator3 > indicator4)

      indicator5 = MACDline[12,26,9](close)
      indicator6 = ExponentialAverage[9](MACDline[12,26,9](close))
      c3 = (indicator5 > indicator6)

      IF c1 AND c2 AND c3 THEN
      BUY QTY PERPOINT AT MARKET
      ENDIF

      // Conditions to exit long positions
      indicator7 = Stochastic[5,3](close)
      indicator8 = Average[3](Stochastic[5,3](close))
      c4 = (indicator7 < indicator8)

      IF c4 THEN
      SELL AT MARKET
      ENDIF

      // Conditions to enter short positions
      indicator9 = Average[50](close)
      indicator10 = Average[20](close)
      c5 = (indicator9 > indicator10)

      indicator11 = Average[3](Stochastic[5,3](close))
      indicator12 = Stochastic[5,3](close)
      c6 = (indicator11 > indicator12)

      indicator13 = ExponentialAverage[9](MACDline[12,26,9](close))
      indicator14 = MACDline[12,26,9](close)
      c7 = (indicator13 > indicator14)

      IF c5 AND c6 AND c7 THEN
      SELLSHORT QTY PERPOINT AT MARKET
      ENDIF

      // Conditions to exit short positions
      indicator15 = Stochastic[5,3](close)
      indicator16 = Average[3](Stochastic[5,3](close))
      c8 = (indicator15 > indicator16)

      IF c8 THEN
      EXITSHORT AT MARKET
      ENDIF

      // Stops and targets
      set stop ploss 100
      SET STOP pTRAILING 5
      SET TARGET pPROFIT 50

       

    • Nicolas • 05/11/2016 #

      Hi, it’s almost copy/paste of my code into yours.

  3. Dymjohn • 05/11/2016 #

    Thanks Nicolas I’ll give it a go.
    Many thanks

  4. Dymjohn • 05/11/2016 #

    Hi Nicolas,
    Tried this having put a hard stop before the trail code and putting limit after your trail code. Also tried not putting a hard stop before your code but in both instances the following example from the test occurred:-
    Short entry 9511, best profit point 9413.5 (97.5 pts) stopped out several bars later at 9533
    Any help would be appreciated

    • Nicolas • 05/11/2016 #

      Please change the values of these lines accordingly to your needs:
      trailingstart = 200 //trailing will start @trailinstart points profit
      trailingstep = 50 //trailing step to move the \"stoploss\"
       

  5. Dymjohn • 05/11/2016 #

    hI Nicolas
    I changed to 20 and 5 and still not running the code yet it will run the limit which I’ve entered after your coding. I know the rest of my code works its just ignoring the stop code for some reason. Is it anything to do with ENDIF statements? 

  6. Dymjohn • 05/11/2016 #

    Hi Nicolas,
    Thought with all our correspondence its starting to become confusing so I’ve attached the updated version at this time.
    // Definition of code parametersDEFPARAM CumulateOrders = False // Cumulating positions deactivated//DEFPARAM NOCASHUPDATE = True //cash not updated with gainsDEFPARAM FLATBEFORE = 081000 //cancels and closes all trades before this timeDEFPARAM FLATAFTER = 162000 //prevents new orders after 16:15 closes out orders// prices to enter tradeBuyPrice = High[0]+ 2*PointSizeSellPrice = Low[0] – 2*PointSize//ProfTarget = ROUND(AverageTrueRange[5](close))*2
    // Conditions to enter long positions
    indicator1,ignored,ignored,ignored = CALL “MY MACD”indicator2 = closeindicator3 = Average[50](close)c1 = (indicator1 > 1)c2 = (indicator2 > indicator3)
    IF c1 AND c2 THENBUY 1 SHARES AT BuyPrice STOPENDIF
    // Conditions to exit long positionsindicator4 = Average[14](Momentum[14](close))indicator5 = Momentum[14](close)c3 = (indicator4 CROSSES OVER indicator5)c11 = (indicator1 < 0)IF c3 OR c11 THENSELL AT MARKET
    ENDIF
    // Conditions to enter short positionsindicator6 = closeindicator7 = Average[50](close)c4 = (indicator6 < indicator7)
    indicator8, ignored, ignored, ignored = CALL “MY MACD”c5 = (indicator8 < -1)
    IF c4 AND c5 THENSELLSHORT 1 SHARES AT SellPrice STOPENDIF
    // Conditions to exit short positionsindicator9 = Average[14](Momentum[14](close))indicator10 = Momentum[14](close)indicator11 = Average[50](close)indicator12 = closec6 = (indicator9 CROSSES UNDER indicator10)c12 = (indicator11 CROSSES OVER indicator12)
    IF c6 OR c12 THENEXITSHORT AT MARKET
    //SET STOP PLOSS 38//trailing stop function
    trailingstart = 20 //trailing will start @trailinstart points profittrailingstep = 5 //trailing step to move the “stoploss”
    //reset the stoploss valueIF NOT ONMARKET THENnewSL=0ENDIF
    //manage long positionsIF LONGONMARKET THEN//first move (breakeven)IF newSL=0 AND close-tradeprice(1)>=trailingstart*pipsize THENnewSL = tradeprice(1)+trailingstep*pipsizeENDIF//next movesIF newSL>0 AND close-newSL>=trailingstep*pipsize THENnewSL = newSL+trailingstep*pipsizeENDIFENDIF
    //manage short positionsIF SHORTONMARKET THEN//first move (breakeven)IF newSL=0 AND tradeprice(1)-close>=trailingstart*pipsize THENnewSL = tradeprice(1)-trailingstep*pipsizeENDIF//next movesIF newSL>0 AND newSL-close>=trailingstep*pipsize THENnewSL = newSL-trailingstep*pipsizeENDIFENDIF
    //stop order to exit the positionsIF newSL>0 THENSELL AT newSL STOPEXITSHORT AT newSL STOPENDIF// target profitSET TARGET pPROFIT 200ENDIF//************************************************************************
    GRAPH newSL as “trailing”

  7. verygrubby • 05/11/2016 #

    I’ve tried this but it doesn’t seem to be moving SL to breakeven….
    Cant get my head around why  your code (your comment below) should move stop to breakeven:
     
    “Set our trades to breakeven:
    If “newSL” is 0 (no move before) and the price went up at least “trailingstart” points from our price entry, we set our new stoploss at price entry + “trailingstep” points.\"
    Surely, by definition, this would not set stop at breakeven.. but a stop level that is the entry + trailing step? e.g. if we bought at 100p and our trailing step is 5 points, wouldn’t the stop be 105? 
    Im very confused!
     
    thanks
     
    geoff

    • Nicolas • 05/11/2016 #

      Lines 30 and 42 : When “newSL” variable is still at 0, it means that we are still at the first time we move our stoploss. So yes, the first time the price has moved in our favor of “trailingstart”, the stop level is set at entry price + “trailing step” points.

  8. verygrubby • 05/11/2016 #

    …but that stop will never be hit will it? e.g. if we bought at 100 and the trailing start is 20 and trailing step is 5, the stop would be 105 wouldn’t it?

    • Nicolas • 05/11/2016 #

      Yes you are right. When price reach 120, the stop is set to 105. If price retrace to 105, position exit in profit of 5 points.

    • Nicolas Castro • 05/11/2016 #

      Y si el precio llega a 140, el nuevo stop o precio de salida cambia a 110. Lo probé y no entiendo el cambió de stops a medida que el precio evoluciona favorablemente.

      Gracias

  9. verygrubby • 05/11/2016 #

    I think I’m so used to using the IG app, that I was think that the 105 was the stop distance, rather than the actual stop price.
    thanks Nicolas

  10. verygrubby • 05/11/2016 #

     
    ..one other question… IG only has an option of a trailing stop step of 5+… will your code work fully with IG? e.g. would a step of 1 in the code actually be executed by IG? ta

    • Nicolas • 05/11/2016 #

      Yes it should be executed because we don’t use here stoploss information but pending contrarian stop order to close position. But you should do your own test on your preferred instrument and timeframe to confirm this behaviour.

  11. verygrubby • 05/11/2016 #

    I’ll give it a go. Thanks 

  12. gutta11 • 05/11/2016 #

    Hello guys! I have tried the “built in” trailing stop but it works not good in real trading.So i heard I need something like the code above. Is it correct that the “bulit in” trailing stop doesn’t work very well?Maybe I’m doing something wrong…
    However, I made a back test with the code above with DAX and some forex in mixed time frames. Every test failed hard..Do some of you nice guys have a clue what is happening?Take care!// Martin

    • Nicolas • 05/11/2016 #

      What is the problem with the trailing stop code? Where does it fail?

  13. gutta11 • 05/11/2016 #

    Hi Nicolas, Every test I made ended up with like -60% and so on. With all kind of time frames…
    Maybe I have missed something. Is it just to copy paste the code below my system code and set the parameters Start and Stop?// Martin

    • Nicolas • 05/11/2016 #

      It should work as a plug and play function, but your own strategy may already deal differently with your orders. You can open a forum thread in ProOrder support section, if you want me to have a look.

  14. gutta11 • 05/11/2016 #

    Thank you, 
    I’ve done that. I am very thankful for your help.

  15. dwgfx • 05/11/2016 #

    Nicolas, I would like to use this with the: floatingprofit = (((close-positionprice)*pointvalue)*countofposition)/pipsize 
    Would you mind confirming from my understanding the only change required is:
    //manage short positions
    IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND floatingprofit>=trailingstart*pipsize THEN // replaced tradeprice(1)-close with floatingprofit
    newSL = floatingprofit-trailingstep*pipsize // replaced tradeprice(1) with floatingprofit
    ENDIF
    //next moves
    IF newSL>0 AND newSL-close>=trailingstep*pipsize THEN
    newSL = newSL-trailingstep*pipsize
    ENDIF
    ENDIF
     

    • Nicolas • 05/11/2016 #

      You are trying to compare money with points, you should also replace trailingstart and trailingstep value with money thresholds and delete the “pipsize” instruction in all the lines.

  16. absent1980 • 05/11/2016 #

    Hi, can anyone advise on how to move stop to the entry level when profit reached certain point ? Just once, no trailing required. I tried to adapt a code posted by Nicolas but it does not work for some reasons.  Thank you.

  17. Willievs • 05/11/2016 #

    Hi
    The code above works fine. The only flaw is that it only moves at the end of a candle and not like a trailing stop. 
    I have tried to replace the 
    SELL AT newSL STOPEXITSHORT AT newSL STOP
    with 
    SET STOP pTRAILING  trailingstart
    Looking at the docs:
    SET STOP pTRAILING y: Sets a trailing stop y points from average position price
    I don’t want to set it to the average position price, I need to set it from the current / close price.
    Is there a way to set the trailing on the current price?
    Thanks in advance.
    Willie

    • Nicolas • 05/11/2016 #

      Hi, yes you are right. Until the next release of the platform and the ability to have code executed between candles, it is the only flaw 🙂
      About the “average position price”, I think you don’t have well understood what it means. It doesn’t refer to the price level of the candle, but the average of the whole open price of current orders on the market.

  18. Leon • 05/11/2016 #

    Hello Guys,
    thanks for the workaround so far Nicolas. I started working with your code to get a trailing stop which is moving in long positions 1 point after another up in a distance like 5 Points to the actual point level . Position @ DAX ist 10,000 points, trailingstop at 9,995 – DAX moves to 10,004, trailings moves to 9,999 and so on (same for short). As soon as the trade is in market the trailing stop should be triggered at each point in the long direction to move also.
    For Backtesting with trialing stops to get a more reliable result to trust in for using a strategy in real market situations.
    This is what I came up with after seeing your code:
    //**** Code starts here ****
    realtrailing = 5
     
    IF NOT ONMARKET THEN
    STLS = 0
    ENDIF
     
    If LONGONMARKET THEN
    IF STLS = 0 then
    STLS = close – realtrailing * pipsize
    ENDIF
    IF close>=close [1] THEN
    STLS = close – realtrailing * pipsize
    ENDIF
     
    ENDIF
     
    If SHORTONMARKET THEN
    IF STLS=0 then
    STLS = close + realtrailing * pipsize
    ENDIF
    IF close<=close [1] THEN
    STLS = close + realtrailing * pipsize
    ENDIF
    ENDIF
     
    IF STLS>0 THEN
    SELL AT STLS STOP
    EXITSHORT AT STLS STOP
    ENDIF
    //**** Code ends here **************
     
     
    BUT instead of stopping at 5 points behind the max level it stops like ~ 10 points behind (sometimes less, sometime more).
    I just started coding a few days ago – that’s why I’m still trying to figure out if every command is really doing what I think it is its job. So maybe it is not working because I’m not 100% sure of the definitions yet.
    Does anybody got a suggestion what is missing that it works like I want it to do?
    I hope in the end it works and everybody with the same purpose as me can use this code for backtesting.
     
    Thanks and Best Regards
    Leon

    • Nicolas • 05/11/2016 #

      The issue you have about tight difference of trailing stop is because ProBacktest don’t test every price movement (ticks) between 2 bars.

  19. traderoli • 05/11/2016 #

    hello nicolas! thanks for the code. it works really good!
    do u have an idea, how to implement an initial stop loss , in case the traded develops not in the right direction?
    i have tried several things, but nothing worked well..
    tks in advance, best regards,
    oliver

  20. Kenneth Kvistad • 05/11/2016 #

    Is there any posibilety to make the trailstep only move if there is a 9pip gap between price and were the trailstep will move to. 
    Problem I have is that the trailstep sooner or later moves to close to the instruments minimum stop distance and this makes the automated system stop since 9pip minimun distance is not clear

    • Nicolas • 05/11/2016 #

      Because we already test this gap of “trailingstep” to place the newSL, you should expand this variable to make sure you are far enough. Adding the spread value to the trailing step should help also.

  21. Hans Christian Lande • 05/11/2016 #

    Hi Nicolas, I have done some modifications to the trail-stop code.  I have added minimum pip for stop as Kenneth requested. I did also add a “leap step” because I noticed that if the price makes a peak the trailing does not follow quickly enough and I would loose some profit.  would appreciate if you would have look at the code and let me know if I made any f*ck ups.  Seems to work in backtesting tho..   
     
    //trailing stop function
    trailingstart = 34 //trailing will start @trailinstart points profit
    trailingstep = 1 //trailing step to move the \"stoploss\"
    minstop = 9 //minimum allowed stop
    priceleap = 70 //if price moves rapidly the stop will move till the set leapstop from close.
    leapstop = 15 //if price moves rapidly the stop will move till the set leapstop from close.
    //reset the stoploss value
    IF NOT ONMARKET THEN
    newSL=0
    ENDIF

    //manage long positions
    IF LONGONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND close-tradeprice(1)>=trailingstart*pipsize THEN
    newSL = tradeprice(1)+trailingstep*pipsize
    ENDIF
    //next moves
    IF newSL>0 AND close-newSL>=trailingstep*pipsize AND close-newSL>=minstop*pipsize THEN
    if close-newSL>=priceleap*pipsize then
    newSL = close - leapstop
    else
    newSL = newSL+trailingstep*pipsize
    endif
    ENDIF
    ENDIF

    //manage short positions
    IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND tradeprice(1)-close>=trailingstart*pipsize THEN
    newSL = tradeprice(1)-trailingstep*pipsize
    ENDIF
    //next moves
    IF newSL>0 AND newSL-close>=trailingstep*pipsize AND newSL-close>= minstop*pipsize THEN
    if newSL-close>=priceleap*pipsize then
    newSL = close + leapstop
    else
    newSL = newSL-trailingstep *pipsize
    endif
    ENDIF
    ENDIF

    //stop order to exit the positions
    IF newSL>0 THEN
    SELL AT newSL STOP
    EXITSHORT AT newSL STOP
    ENDIF
    //************************************************************************

     

  22. dillongr • 05/11/2016 #

    Hi,
    I am very new to coding and am trying to implement your trailing stop code, I am assuming that I have done it correctly, but the actual defined stop gets triggered more often than the trailing stop.  If i back test  with “set stop ploss 80 ptrailing 20 ” if works fantastically.  Am I missing something?
     
    thanks
    //-------------------------------------------------------------------------
    // Main code : the one
    //-------------------------------------------------------------------------
    DEFPARAM CumulateOrders = false

    // Conditions to enter positions
    indicator1 = Average[5](close)
    indicator2 = Average[13](close)
    c1 = (indicator1 > indicator2)
    c3 = (indicator1 < indicator2)
    indicator3 = MACDline[5,15,4](close)
    indicator4 = ExponentialAverage[4](MACDline[5,15,4](close))
    c2 = (indicator3 > indicator4)
    c4 = (indicator3 > indicator4)c5 = close>close[1]c6 = close<close[1]

    //long position
    IF time < 173000 and time > 083000 and c1 AND c2 and c5 THEN
    BUY 2 contract AT MARKET

    ENDIF

    //short position
    IF time < 173000 and time > 083000 and c3 AND c4 and c6 THEN
    sellshort 2 contracts AT MARKET

    endif

    // stop loss details
    set stop ploss 80

    //************************************************************************
    //trailing stop function
    trailingstart = 20 //trailing will start @trailinstart points profit
    trailingstep = 5 //trailing step to move the \"stoploss\"

    //reset the stoploss value
    IF NOT ONMARKET THEN
    newSL=0
    ENDIF

    //manage long positions
    IF LONGONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND close-tradeprice(1)>=trailingstart*pipsize THEN
    newSL = tradeprice(1)+trailingstep*pipsize
    ENDIF
    //next moves
    IF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
    newSL = newSL+trailingstep*pipsize
    ENDIF
    ENDIF

    //manage short positions
    IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND tradeprice(1)-close>=trailingstart*pipsize THEN
    newSL = tradeprice(1)-trailingstep*pipsize
    ENDIF
    //next moves
    IF newSL>0 AND newSL-close>=trailingstep*pipsize THEN
    newSL = newSL-trailingstep*pipsize
    ENDIF
    ENDIF

    //stop order to exit the positions
    IF newSL>0 THEN
    SELL AT newSL STOP
    EXITSHORT AT newSL STOP
    ENDIF
    //************************************************************************

     

    • Nicolas • 05/11/2016 #

      The “set stop ploss 80 ptrailing 20 ” cannot be in live trading (ProOrder), that’s one of the reasons I made this function. If your SL is much triggered than the trailing stop, it is surely because you are backtesting in a large timeframe.

  23. dillongr • 05/11/2016 #

    Hi Nicolas, yes I am aware of that.   This is why I thought to try your code.  I have back tested from 3 min to 8 hours, nothing seems to work, the best I get is if I just set a trailing stop to 80 (80 in the min stop for the South african top 40 cash index).  Idealy I am trying set a stop of 80, but then use a trailing stop of 20

  24. dillongr • 05/11/2016 #

    Spread is 10 points 

  25. arcane • 05/11/2016 #

    hello,
    in the original code, I do not understand the following:
    trailingstep = 5 // trailing step to move the “stoploss”
    If I change the number 5, it does not change the results of the backtest.
    Only the line trailingstart = 20 // trailing dots will start @trailinstart profit change the result.
    Why. Thank you for your help.

    • Nicolas • 05/11/2016 #

      Surely because of the non inside-bar look, so the backtest can’t test how many times the price has moved 5 points between the Open and Close of the current bar.

  26. arcane • 05/11/2016 #

    Good evening,
    Nicolas thank you for your answers.
    I try to change your trailing stop program.
    Your stopprofit is set up when the market goes up if you buy
    I would do the opposite.
    Stoptraining trigger if the market goes down on a purchase.
    The dax = 10000
    If dax falls in 9500, the trailing stop is triggered with a stop at 9450. If the market rises, the stop back by 5 points.
    Can you tell me the elements to change in the code.
    Thank you very much.

    • Nicolas • 05/11/2016 #

      You should open a new forum thread for this specific modification please. Much easier to talk there about it. Thanks.

  27. Bin • 05/11/2016 #

    Hi Nicolas
    If I want change trailingstart from point to 0.2% of entry price, below command is correct? 
    trailingstart = round(tradeprice*(0.2/100)) 

  28. Nacho • 05/11/2016 #

    ¿Hay alguna manera de conbinar un stop fijo y un trailing en la misma estrategia? Me refiero empezar con un stop de 40 ptos y cuando lleves 100 ptos a favor que se active un trailing stop a 100 ptos de distancia del precio
     

  29. jonjon • 05/11/2016 #

    Hi Nicolas. Great bit of code. I’ve made a change so that the TS trails the low of 3 bars back. Just made changes to the “//next moves” section. It looks like it works but thought I would check it out with you and also share it with everyone.
    Long position:
    IF newSL>0 AND close>Low[2] AND (BarIndex - TradeIndex) >=3 THEN
    newSL = Low[2]
     Short:
    IF newSL>0 AND close<High[2] AND (BarIndex - TradeIndex) >=3 THEN
    newSL = High[2]
    Thanks 

    • Nicolas • 05/11/2016 #

      Seems ok to me, thanks for sharing it here.

  30. Madrosat • 05/11/2016 #

    Bonjour
    où trouve t on les valeurs minimum à indiquer dans
    Set stop ploss  ??
    trailingstart ??
    trailingstep??
    pour que cela fonctionne bien sur la plateforme ig automatique?  
    Pour  eur usd ,  gbp usd , dax mini ?
    Bonne journée
    Madrosat
     

    • Nicolas • 05/11/2016 #

      Tout est inclus dans le fichier ITF à télécharger à la fin de l’article, merci. 

  31. robdav • 05/11/2016 #

    Hi
    It’s my first day of using this trailing stop code live and it doesn’t seem to be working. It appears to work fine in back test but not live unless I have misunderstood something which is quite possible.
    I have set:
    trailingstart = 15 //trailing will start @trailinstart points profit
    trailingstep = 5 //trailing step to move the “stoploss”
    So what I was expecting to happen is that when the trade gets over 15 points in profit direction it would reset the stop loss and add 15 points to it, is that not correct? So far, I’ve had two trades that have gone over 16 points in the right direction but nothing happened.
    Have I missed something please? It seems to work find in back test but not live with IG.
    Thanks
    Robert

    • Nicolas • 05/11/2016 #

      the first move of the trailing will be at entry price + trailingstep. Next moves will be previous trailing level + trailingstep each time a new trailingstep occured.

  32. robdav • 05/11/2016 #

    Hi Nicolas
    But it wouldn’t start trailing until the price had closed 15 points above opening price?
    Thanks
    Robert

    • Nicolas • 05/11/2016 #

      Yes, the “trailingstart” variable is the threshold for the trailing stop function to begin its job.

  33. robdav • 05/11/2016 #

    Got it. Thanks you.

  34. Inertia • 05/11/2016 #

    Thank you Nicolas. Nice piece of code. 

  35. tob107 • 05/11/2016 #

    Hi,

    This has been in the back of my mind for quite some time, and I finally got around to work on it.

    I have changed the way that the SL is updated after first being initialized. Instead of moving in increments of TrailingStep, the newSL is now based on the close of the highest candle since the trade was entered.

    So imagine if a trade goes our way, with 5 30 pip candles (!) after the SL was first initialized. Then, to use TrailingStep of 5 (as above), the SL would move 5*5 (=25) pips in the original version. If we instead base the SL on the previously closed candle and we use the TrailingStart of 20 as above, we lock in 130 out of the 150 pips.

    Since I’m working on pretty short time frames, this suits me better. Hopefully some one else can make use of it as well.

    I had to introduce the variable CAND to find the highest/lowest close from the time the trade was entered.

    No offence, Nicolas – I’m just trying to improve it!

    Comments are more than welcome!

    Tobias

  36. Nicolas • 05/11/2016 #

    A modified version can be find there: https://www.prorealcode.com/topic/updated-version-of-trailing-sl/#post-44305

  37. avatar
    fabioerliam • 05/11/2016 #

    Hi Nicolas! great and thanks for this code of trailing…
    got a question…with this code I have to cancel my stop lost and take profit that I set before, right?
    Many thanks
    Fabio

  38. avatar
    fabioerliam • 05/11/2016 #

    I think I should insert it at the end of my code replacing sl and tp….right?

    • Nicolas • 05/11/2016 #

      Yes, just copy/paste it at the end of your automatic trading strategy code. And you don’t have to replace your stoploss and takeprofit, you can still use at the same time.

    • avatar
      fabioerliam • 05/11/2016 #

      Thanks:)

  39. Pere • 05/11/2016 #

    Thanks a lot for this system Nicolas, it really is a good job!
    However I just want to solve 2 things that are not working as I want.
    1. Until the system starts with the breakeven stop, I am really unprotected without stop loss. I tried with a normal STOP pLOSS, but it doesn’t work because I cumulate orders. I also tried to modify the IF NOT ONMARKET THEN ->newSL=0 writing instead newSL=close-30 and changing also the other lines where newSL=0, but it also does not work.
    2. It is supposed that the trade should stop in the momento that the Price just touches the value of the newSL, but in many cases (without cumulate orders) it’s not true. For example, i put the code GRAPH for low and trailing stop on the backtests, and in one case trailing was 2156,6 and low 2136,5 and the trade didn’t stop but continued trading 6 more candles, some of them also with higher trailing tan low. I cannot upload a photo here, otherwise you could see it. If I cumulate orders, the situation is even worst.
    Could you please tell me how to achieve the correct work of this trailing stop, or at least, explain why it happens so?

  40. Pere • 05/11/2016 #

    Well, for those that have the same problems, I already solved the first one, adding following code:

    emer=50
    IF newSL=0 THEN
    sl=emer
    ELSE
    sl=0
    ENDIF

    SET STOP pLOSS sl

    Now it would be nice to solve the second one.

  41. Marlon • 05/11/2016 #

    First of all nice work! I’ve searched for a long time for a coded version of a trailing stop because of the new limited risk accounts.
    But I have a question.

    I created my own strategy an set a trailing stop with a distance of 20.
    I backtested it and everything works fine.

    After that I replaced the “Trailing-function” (SET STOP pTRAILING 20)
    with your coded TrailingStop-Version.
    Of course, I replaced the parameter variables, so that the trailingstar begins at 20.

    What did I wrong?

    Thank you for your answer.

    • Marlon • 05/11/2016 #

      Sorry I missed to add:
      The performance with the coded TrailingStop-Version wasn’t as good as with the function “SET STOP pTRAILING 20”

  42. beppe8949 • 05/11/2016 #

    Ciao Nicolas, ma lo stop loss e il take profit non vanno inseriti giusto?

    • Nicolas • 05/11/2016 #

      Puoi aggiungerlo anche alla tua strategia, è tutto su di te ..

    • beppe8949 • 05/11/2016 #

      Il problema è che se inserisco tp e sl mi da delle variabili di tp che automaticamente non fanno partire il ts perché troppo ridotte a confronto al ts.. sto davvero degenerando credimi non riesco a trovare delle variabili che siano perfette sul dax e su nessun altro mercato.. incredibile..

    • Nicolas • 05/11/2016 #

      Se stai cercando la perfezione, dovresti rinunciare al trading 🙂

    • beppe8949 • 05/11/2016 #

      No be ne sono certo che la perfezione non esiste, però almeno avere una strategia di autotrading funzionante, quello si 🙂
      Perchè usando questo codice senza tp e sl mi da tutti risultati negativi, se li inserisco, mi da dei valori di tp troppo bassi e di trailing troppo alti, quindi non si attiva e prende il take profit.. Un disastro! Ci sto impazzendo da ieri.. Se puoi aiutarmi te ne sono davvero grato.. 🙁

  43. JanWd • 05/11/2016 #

    Dear Nicolas,

    maybe I have missed the explanation, but why should we use this extended code instead of using the generic PRT commando “PLOSS” ?
    And more general: is there a possibilitiy to search within this platform, through everything, for topics ? Like a Google search on PLOSS which give me all the forum-responses to this topic ? (It would be nice, and avoids “simple stupid” questions already being answered somewhere on the platform)
    Kind regards, Jan

  44. JanWd • 05/11/2016 #

    I just found an answer to my second question “And more general: is there a possibilitiy to search within this platform, through everything, for topics ? “, search on topics is possible at clicking on your Avatar, right top and filling the topic at the topline with greyed Search in it.
    Remains my first question: why should we use this extended code instead of using the generic PRT commando “PLOSS” ?

    • Nicolas • 05/11/2016 #

      We could use ploss instead of a pending order, that’s right.

  45. TempusFugit • 05/11/2016 #

    Hi,

    Thanks, very useful, I will defenetly use it. Just want to share that I think I found a little error in it. The way is coded if you set for instance “trailingstar=50” and “trailingstep=25”, you expect that when the close price reach more than 50 pips in your favor the stop will be set 25 pips in the same direction, isn´t it? Well it doesn´t, it put the stop at 50 points instead of 25 when close price go beyond the 50 pips. It´s easy to check, just try this example and see that the closed trades are from 50 points in your favor to more, no 25.

    To make the code as intended it´s necesary to change this lines:

    IF LONGONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND close-tradeprice(1)>=trailingstart*pipsize THEN
    newSL = tradeprice(1)+trailingstep*pipsize
    ENDIF
    //next moves
    IF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
    newSL = newSL+trailingstep*pipsize
    ENDIF
    ENDIF

    To:

    IF LONGONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND close-tradeprice(1)>=trailingstart*pipsize THEN
    newSL = tradeprice(1)+trailingstep*pipsize
    //next moves
    ELSIF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
    newSL = newSL+trailingstep*pipsize
    ENDIF
    ENDIF

    The same with the shortside.

    The whole code would be:

  46. TempusFugit • 05/11/2016 #

    //************************************************************************
    //trailing stop function
    trailingstart = 50 //trailing will start @trailinstart points profit
    trailingstep = 25 //trailing step to move the “stoploss”

    //reset the stoploss value
    IF NOT ONMARKET THEN
    newSL=0
    ENDIF

    //manage long positions
    IF LONGONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND close-tradeprice(1)>=trailingstart*pipsize THEN
    newSL = tradeprice(1)+trailingstep*pipsize
    ELSIF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
    newSL = newSL+trailingstep*pipsize
    ENDIF
    ENDIF

    //manage short positions
    IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND tradeprice(1)-close>=trailingstart*pipsize THEN
    newSL = tradeprice(1)-trailingstep*pipsize
    ELSIF newSL>0 AND newSL-close>=trailingstep*pipsize THEN
    newSL = newSL-trailingstep*pipsize
    ENDIF
    ENDIF

    //stop order to exit the positions
    IF newSL>0 THEN
    SELL AT newSL STOP
    EXITSHORT AT newSL STOP
    ENDIF
    //************************************************************************

    • Nicolas • 05/11/2016 #

      The first move set the stoploss to break even. So 50 points away from the current price in your example.

  47. JanWd • 05/11/2016 #

    Dear Nicolas,

    I developed an alternative Trailing stop code, with slightly different principles, see below.
    Principles of this trailing stop: (for a long position)
    1. Inital stop is set xx pips below the open buy price, next bar after opening (if long onmarket)
    2. If the price drops in a long position, the stopless remains the same,
    3. if the price increases above the opening buy price, the stop loss increases as well, not in steps, but in pips .
    3. the stoploss is being reduced by the number of bars on the market, multiplied with a factor, to further reduce risk (example initial trailing stop loss 77 pips, after 5 trading bars 57 pips, reduction 5 bars x factor 4)
    4. If the trailing stop loss appears to be smaller than the minimal stop distance of 30, than exit the market.

    The PRT code I have added into the box behind the button “ADD PRT CODE” (why can it not be seen after adding , under review ?)
    Kind regards Jan

    • TempusFugit • 05/11/2016 #

      I don´t understand your reply, 50 points away from the tradeprice is not breakeven.

      //first move (breakeven)
      IF newSL=0 AND close-tradeprice(1)>=trailingstart*pipsize THEN
      newSL = tradeprice(1)+trailingstep*pipsize
      ENDIF

      With this code the first move is supposed to be set at 25 points from the tradeprice (the trailing step in my example)

      But the next lines in the original code makes that useless because they overwrite the previous newSL in the first move also (from 25 to 50)

      //next moves
      IF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
      newSL = newSL+trailingstep*pipsize

      The result of this is that when the price just reach 50 points the code set the stoploss in 50 points LOT of trades will be stopped in those 50 points because it just need a little pullback to activate the stop, just check the results and you will see lots of trades with 50 points benefit (and none with 25). That cannot be good for the system, the stop needs a little more space.

    • Nicolas • 05/11/2016 #

      Try to reduce the steps and you’ll find a difference. You’re right because 25 points is half the way between trailing start and the newSL.

    • TempusFugit • 05/11/2016 #

      Nicolas, I don´t understand your replies, maybe we are expecting different things from that trailing stop 😉

      Anyway I am using now a different version of this trailing stop. It sets the stop in breakeven-tradeprice the first time the close reachs the “trailingstart” and from there it keeps that “trailingstart” difference with the last higher/lower close, so it will increase/decrease as the price goes up/down in the same amount. I think that´s the traditional trailing stop as most people understand it. Code in the next message

    • TempusFugit • 05/11/2016 #

      JanWd, your idea sounds very interesting. I had the same problem trying to add the code, I just put the code in a new message with copy/paste. Can you do the same. Thank you

    • Nicolas • 05/11/2016 #

      Sorry for the button’s malfunction..you can paste your code here directly into your comment. Thanks

  48. TempusFugit • 05/11/2016 #

    //************************************************************************
    //trailing stop function
    trailingstart = 3*AverageTrueRange[10](close) //When the trailing stop starts and the distance the stop keeps from the last higher/lower close

    //reset the stoploss value
    IF NOT ONMARKET THEN
    newSL=0
    ENDIF

    //manage long positions
    IF LONGONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND close-tradeprice(1)>=trailingstart THEN
    newSL = tradeprice(1)
    ELSIF newSL>0 AND close-newSL>=trailingstart THEN
    newSL = close-trailingstart
    ENDIF
    ENDIF

    //manage short positions
    IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND tradeprice(1)-close>=trailingstart THEN
    newSL = tradeprice(1)
    ELSIF newSL>0 AND newSL-close>=trailingstart THEN
    newSL = close+trailingstart
    ENDIF
    ENDIF

    //stop order to exit the positions
    IF newSL>0 THEN
    SELL AT newSL STOP
    EXITSHORT AT newSL STOP
    ENDIF
    //************************************************************************

  49. JanWd • 05/11/2016 #

    Dear Nicolas and TempusFugit, again my post, now with the PRT-code below

    I developed an alternative Trailing stop code, with slightly different principles, see below.
    Principles of this trailing stop: (for a long position)
    1. Inital stop is set xx pips below the open buy price, next bar after opening
    2. If the price drops below the opening price, the stopless remains the same,
    3. if the price increases above the opening price, the stop loss level increases, not in steps, but in pips .
    3. the stoploss is being reduced by the number of bars on the market, multiplied with a factor, to further reduce risk (example initial trailing stop loss 77 pips, after 5 trading bars 57 pips, reduction 5 bars x factor 4)
    4. If the trailing stop loss appears to be smaller than the minimal stop distance of 30, than exit the market.

    See below the PRT code , if you have questions, let me know.

    Kind regards Jan

    //———–TRAILING STOP LOSS—-with comments behind the code to clarify——————————————————
    PIniStop = 77/10000 * close //initial stop in pips, FOR CURRENCIES PInistop = 77 * CLOSE (in pips )
    MinStopDist = 30/10000 * close // min stop distance FOR CURRENCIES MinStopDist = 30 * CLOSE (in pips )
    LengthBars = 0 // Nr of bars trading, initial setting
    FactB = 3 // Factor to multiply the lenght of bars with the aim to reduce the stoploss during trade (to be optimized)
    if not onmarket then
    NewSL = 0 // stoploss, dynamicly expressed in a price when on market.
    endif
    // reducing the trailing stop distance during the current trade to reduce risk
    if longonmarket then //works only after first bar, set stop ploss advicable for the first bar at opening
    LengthBars = Barindex – Tradeindex //nr of bars in current position
    if close > Positionprice then
    NewSL = round(Close – PIniStop * pipsize + FactB * LengthBars * pipsize) //DO NOT ROUND FOR CURRENCIES
    else //if the long trade moves against you, keep the initial stoploss level, reduced by the length of the trade x factor
    NewSL = Positionprice – PIniStop * pipsize + FactB * LengthBars * pipsize //DO NOT ROUND FOR CURRENCIES
    endif
    if Close – NewSL >= MinStopDist * pipsize then // garantuee min stop distance
    SELL AT newSL STOP //only set new stop when greater or equal then min stop distance
    else
    SELL at market // when less then min distance for stop loss , then exit market
    endif // otherwise no stop is set, and stop order only last one bar
    endif

    if shortonmarket then //works only after first bar, set stop ploss still needed
    LengthBars = Barindex – Tradeindex //nr of bars in current position
    if close = MinStopDist * pipsize then // garantuee min stop distance
    EXITSHORT AT newSL STOP
    else
    EXITSHORT AT market // when less then min distance for stop loss , then exit market
    endif // otherwise no stop is set, and stop order only last one bar
    endif

  50. Daniel_H • 05/11/2016 #

    Thanks for the trailing stop code Nicolas.

    I found a problem that occures pretty often and it’s when the step is triggered and the new stop is set, then the price just have to move down very little to stop you out. I’ve updated the code with a third variable that set how far below the step the stop will be set. So then the price has some room to move. The code between the lines:

    ———————————————–
    trailingstart = 4 // Trailing will start @trailinstart points profit
    trailingstep = 4 // Trailing step to move the “stoploss”
    trailingroom = 2 // Instead of the trailing stop starting exactly at the start or step, the stop is set x.y pips below the trigger to get the price some room to move.

    IF NOT ONMARKET THEN
    newSL = 0 // Reset first target stop loss
    newStep = 0 // Reset next trailing step
    ENDIF

    // Manage long positions
    IF LONGONMARKET THEN
    // First move (breakeven)
    IF newSL=0 AND close-tradeprice(1)>=trailingstart*pipsize THEN
    newStep = tradeprice(1)+trailingstep*pipsize
    newSL = tradeprice(1)+trailingroom*pipsize
    ENDIF
    // Next moves (trailing stop)
    IF newStep>0 AND close-newStep>=trailingstep*pipsize THEN
    newStep = newStep+trailingstep*pipsize
    newSL = newStep+trailingroom*pipsize
    ELSE
    IF newStep>0 AND close0 AND close-newStep>=trailingstep*pipsize THEN
    newStep = close+trailingstep*pipsize
    newSL = close+trailingroom*pipsize
    ELSE
    IF newStep>0 AND close<=newSL then
    SELL AT newSL STOP
    ENDIF
    ENDIF

    /Daniel

  51. Daniel_H • 05/11/2016 #

    Something went wrong when I posted my reply, the code:

    trailingstart = 4 // Trailing will start @trailinstart points profit
    trailingstep = 4 // Trailing step to move the “stoploss”
    trailingroom = 2 // Instead of the trailing stop starting exactly at the start or step, the stop is set x.y pips below the trigger to get the price some room to move.

    IF NOT ONMARKET THEN
    newSL = 0 // Reset first target stop loss
    newStep = 0 // Reset next trailing step
    ENDIF

    // Manage long positions
    IF LONGONMARKET THEN
    // First move (breakeven)
    IF newSL=0 AND close-tradeprice(1)>=trailingstart*pipsize THEN
    newStep = tradeprice(1)+trailingstep*pipsize
    newSL = tradeprice(1)+trailingwiggle*pipsize
    ENDIF
    // Next moves (trailing stop)
    IF newStep>0 AND close-newStep>=trailingstep*pipsize THEN
    newStep = newStep+trailingstep*pipsize
    newSL = newStep+trailingwiggle*pipsize
    ELSE
    IF newStep>0 AND close<=newSL then
    SELL AT newSL STOP
    ENDIF
    ENDIF
    ENDIF
    ———————————————–

    /Daniel

  52. DariusPaulsen • 05/11/2016 #

    Thank you for this hard coded trailing stop. But if I understand well, since the the stop is readjusted at each code execution, it is in fact readjusted at each new bar, and not in real time tick by tick ? Am I right ?
    I say that because I have run many strategies in backtest that perform pretty well with short trailing stop values (4 to 6 points on Dax) on 15-30mn timeframes, at the condition that there is no trailing step (trailing step = tick variation). No pb in PRT probacktest, but with IG it’s a different story, because their minimum trailing step on DAX is set at 5 points, and not only it is harder to trade like this, but I haven’t found how to simulate this in probacktest.

    • Albert FX • 05/11/2016 #

      Dear DariusPaulsen, have You any update about this issue ?
      I note that the system has to wait the open price of the next candle in order to know and calculate if it has to move the trailing or if it has to close the current open position. How we can do this in real time ? We only have to use Multi Time Frame and switching, for example, to 1 minute tf io order to check quikly when the system has to move the trailing or it is also possible in other ways ? This problem has stopped my strategy and now I am trying to find a solution because I can not trade without a trailing stop. Please help me. Thanks.

  53. VN • 05/11/2016 #

    Hi Nicolas,

    I am trying to implement a tiered stop loss, and I tried to use this code you have shared but somehow it doesn’t produce the expected results.

    If I can illustrate what I am thinking at with an example on daily DAX.

    I open a SHORT at 13,300 with an initial STOP LOSS = 10, so I will get stopped if price rises to 13,010.

    But then I want to say, IF price moves down to 12,990, then move the stop level from 13,010 down to 13,000.

    I then want to introduce a tiered approach such that, if
    1) Price reaches 12,950 (or any other variable X below initial open price), move the stop loss down to 12,970 (any other variable Y)

    2) Price reaches 12,930 (or any other variable X), set stop loss at 12,960 (or any other variable Y)

    I thought the SET STOP pLOSS X pTRAILING Y command would do this, but it didn’t work as expected either.

    Would be grateful if you could let me know how its best to code this logic.

    Thanks!

    • Nicolas • 05/11/2016 #

      Would be better to create a topic in the forum in order to code this particular trailing stop logic.

  54. VN • 05/11/2016 #

    Hi Nicolas, there is something I posted for this here, but then I saw your post: https://www.prorealcode.com/topic/dynamic-stop-loss-code-help/#post-115118

  55. Vincent 3555 • 05/11/2016 #

    Hello Nicolas

    If I’ ve well understood , the code which generates the trailing stop is executed at each new bar, base on the data of the last bar. It seems to me such coded trailing stops are indeed more adjustable stop losses than really real time trailing stops. These are very different tools.
    Perhaps I’m missing something ?

    • Nicolas • 05/11/2016 #

      This is correct, and there are many forks/variants of this code in forums and in library.

  56. Guibourse • 05/11/2016 #

    I am sorry but can you tell me what I have to enter in the code we are talking about to replace the order ” Set stop ploss 27 p trailing 5 ” Thanks a lot !

    • Guibourse • 05/11/2016 #

      Because I really can’t find where to enter the variable in the code to get the same results as with the Set stop ploss 27 ptrailing 5…Thank you so much for your help

    • Nicolas • 05/11/2016 #

      Please open a new topic in the ProOrder section in order to give you the full details of a code that could simulate the same behavior. Please respect the posting rules.

  57. telleston • 05/11/2016 #

    Hey Nicolas,
    Trying to get this all to work together with GBP/USD, on a 15 min period, but I keep getting a few massive losses which I think are totally over the trailing stop.
    I’ve got 20 contracts in my code.
    I’ve not put any stop loss code against the long or short.
    I’ve put the trailingstart = 5 and trailingstep = 1
    Not sure how to limit the loss to a specific amount (if that’s possible)…

    But, no matter what those values are, it always seems to generate a few trades with +$1000 losses on them – working on a 15min interval with 1 months worth of data. And my “a” and “b” is fixed at 8.1 and 23 respectively.

    Here’s my code – any assistance would be hugely appreciated (I’m a newbie to this).

    • Nicolas • 05/11/2016 #

      If you are not using stoploss, the trailing code provided will not put it for you until your order is at least in profit of “trailingstart” at Close of a bar.

  58. macdopa • 05/11/2016 #

    Nicolas, you are a savior of ProOrder.
    This Trailing Stop-Loss code works wonderfully on any strategy; you just have to re-adjust the 2 variables: trailingStart and trailingStep.
    NB: 1) The 1st loss is generally recorded with the 1st position order.
    2) The more we increase the value of trailingStart, the greater the loss will be; but offset by a large gain throughout auto trading. That is, the small value of trailingStart gives a small loss with a small gain over the long one. “If the hedge funds are large and so desired, the risk is allowed with great profit in the long run.”

  59. macdopa • 05/11/2016 #

    Improve the “Trailing Stop” and continue to benefit
    Here is one of the ways to perfect this code for trailingstop:
    1) For buy orders, add this:
    IF (……) * pipsize AND (RSI [2] (Close) <= 80) THEN …
    NB: We should continue to profit, buying, as long as the RSI rises to around 80-90.

    2) For sell orders, add this:
    IF (……) * pipsize AND (RSI [2] (Close) >= 20) THEN …
    NB: We should continue to profit, by selling, as long as the RSI goes down to around 30-20.

    Test and thank us.
    M.D.K

  60. Ciccarelli Franco • 05/11/2016 #

    Per usarlo, faccio copia e incolla o utilizzo il file

  61. rmhandel • 05/11/2016 #

    Hallo liebe PRT Community . Ich wollte mal generell fragen. Habe Hier seit Jahren Erfahrung gesammelt mit einigen Codes und Programmen jedoch wenn es konkret ins eingemachte geht kann ich mir nicht wirklich weiterhelfen und es gibt nur dieses Forum denke ich um überhaupt an eine Lösung zu kommen. Dafür bin ich sehr dankbar. Dennoch interessiert mich – gibt es nicht irgendeinen guten Hinweis wo ich mein Wissen wirklich vertiefen kann besonders wenn die Codierung kompliziert wird und manche Fehler einfach nicht rauszufinden sind. Oft weicht die Syntax einfach von der Praxis ab da kann man schon teilweise verzweifeln. Kann man den nicht irgendwo eine profunde Schulung machen und das hier perfekt zu erlernen. Das wäre mein unbedingtes Anliegen um hier auch wirklich proffessionell zu werden. Vielen Dank für Hinweise.

    • Nicolas • 05/11/2016 #

      Hallo, ich denke, alle Fehler haben ihre Ursachen und nur Erfahrung kann in diesem Fall helfen 🙂 Hast du schon die Programmierkurse auf der Website besucht?

  62. Demon • 291 days ago #

    BOnjour,
    j’essaie de coder un stop suiveur qui est basé sur les pauses du marchés (retracements). Cela peut etre fait avec le Supertrend ou le 3bars trailing stop de william, jai pris le retour dans la tendance du SMI court vers le SMI long. Je veux que après la prise de position, s’il y a un petit retracement qui ne change pas la tendance, le stop soit remonté sur le bas de ce retracement.
    J’ai codé à partir de votre code bien sur. Comme on peut le voir sur l’image jointe, j’ai fait tracer le stop en rouge et le trailing stop en bleu. Le stop fonctionne, mais pas le trailing stop, pouvez vous m’aider?
    Merci d’avance.

    // Définition des paramètres du code
    DEFPARAM CumulateOrders = False // Cumul des positions désactivé

    // Conditions pour ouvrir une position acheteuse
    //a = SMI[70,15,10](typicalprice)
    //b = SMI[14,3,4](typicalprice)
    //c = 40
    //d = -40
    //return a as “Tendance”,b as “Impulsion”,c as “zone SA”,d as “Zone SV”
    ignored, indicator1, ignored, ignored = CALL “Puissance Relative”
    c1 = (indicator1[2] > indicator1[1])
    ignored, indicator2, ignored, ignored = CALL “Puissance Relative”
    c2 = (indicator2 > indicator2[1])
    indicator3, ignored, ignored, ignored = CALL “Puissance Relative”
    c3 = (indicator3 > indicator3[1])

    IF NOT ONMARKET THEN
    TrailStop = 0
    ENDIF

    //Entrée en position
    IF c1 AND c2 AND c3 AND NOT ONMARKET THEN
    SA= Close-low[1]
    SB=low[1]
    BUY 1 SHARES AT High stop
    ENDIF
    If LONGONMARKET then
    SET stop loss SA
    GRAPHONPRICE SB coloured(255,8,8)
    ENDIF

    //Démarage du TRAILING STOP
    IF LONGONMARKET THEN
    IF TrailStop = 0 AND c1 AND c2 AND c3 THEN
    TrailStop = Close – Low[1]
    TS = Close – TrailStop
    SELL AT TraiLStop STOP
    GRAPHONPRICE TS coloured(255,0,0)
    ENDIF
    ENDIF

    //Déplacements suivants du TRAILING STOP
    IF LONGONMARKET THEN
    IF TrailStop > 0 AND c1 AND c2 AND c3 THEN
    TrailStop = Close – Low[1]
    TS = Close – TrailStop
    SELL AT TrailStop STOP
    GRAPHONPRICE TS coloured(0,0,255)
    ENDIF
    ENDIF

    // Conditions pour fermer une position acheteuse
    indicator4, ignored, ignored, ignored = CALL “Puissance Relative”
    c4 = (indicator4 < indicator4[1])

    IF c4 THEN
    SELL AT MARKET
    ENDIF

    PS: je n’arrive pas à inserer une image d’écran.

  63. Demon • 291 days ago #

    OUPS
    Sorry,
    Forum English
    Good morning,
    I am trying to code a trailing stop that is based on market breaks (retracements). This can be done with the Supertrend or William’s 3bar trailing stop, I took the return in the trend from the short SMI to the long SMI. I want that after taking a position, if there is a small retracement that does not change the trend, the stop will be moved up to the low of that retracement.
    I coded from your code of course. As you can see in the attached image, I drew the stop in red and the trailing stop in blue. The stop works, but not the trailing stop, can you help me?
    Thanks in advance.

    // Code Parameter
    DEFPARAM CumulateOrders = False // Cumul des positions désactivé

    // Conditions To open a buy condition
    //Program of the call indicator “Puissance Relative”
    //a = SMI[70,15,10](typicalprice)
    //b = SMI[14,3,4](typicalprice)
    //c = 40
    //d = -40
    //return a as “Tendance”,b as “Impulsion”,c as “zone SA”,d as “Zone SV”

    ignored, indicator1, ignored, ignored = CALL “Puissance Relative”
    c1 = (indicator1[2] > indicator1[1])
    ignored, indicator2, ignored, ignored = CALL “Puissance Relative”
    c2 = (indicator2 > indicator2[1])
    indicator3, ignored, ignored, ignored = CALL “Puissance Relative”
    c3 = (indicator3 > indicator3[1])

    //Reset the stoploss vale
    IF NOT ONMARKET THEN
    TrailStop = 0
    ENDIF

    //Enter long position
    IF c1 AND c2 AND c3 AND NOT ONMARKET THEN
    SA= Close-low[1]
    SB=low[1]
    BUY 1 SHARES AT High stop
    ENDIF
    If LONGONMARKET then
    SET stop loss SA
    GRAPHONPRICE SB coloured(255,8,8)
    ENDIF

    //Manage long position
    IF LONGONMARKET THEN
    IF TrailStop = 0 AND c1 AND c2 AND c3 THEN
    TrailStop = Close – Low[1]
    TS = Close – TrailStop
    SELL AT TraiLStop STOP
    GRAPHONPRICE TS coloured(255,0,0)
    ENDIF
    ENDIF

    // Next moves
    IF LONGONMARKET THEN
    IF TrailStop > 0 AND c1 AND c2 AND c3 THEN
    TrailStop = Close – Low[1]
    TS = Close – TrailStop
    SELL AT TrailStop STOP
    GRAPHONPRICE TS coloured(0,0,255)
    ENDIF
    ENDIF

    // Stop order to exit the position
    indicator4, ignored, ignored, ignored = CALL “Puissance Relative”
    c4 = (indicator4 < indicator4[1])

    IF c4 THEN
    SELL AT MARKET
    ENDIF

  64. Demon • 291 days ago #

    PS: I can’t insert a screenshot.
    I saw it was intentional

  65. Demon • 290 days ago #

    Hi,
    I see another problem on this backtest.
    On oil (Lignt crude oil,) he buys not the day after the signal and in accordance with my program, he buys at the high of the day of the signal, which is totally impossible. I will report this discrepancy to PRT. I will attach a screenshot to them.

  66. Demon • 290 days ago #

    Hi,
    After verification, the activated position signal and the position entry arrow and triangle are positioned on the day of the signal, but in the list of positions, the date is the next day!!! (On oil) not on futures or forex

  67. MetalStorm • 11 days ago #

    Hello Nicolas and everybody
    I have try your code trailing-stop-4.itf, I have understand this code and it’s a good code but it doesn’t work and I don’t know why, I have try it on FCE CAC40, with entry on the higest of the day in order to folow the stop but stop level not respected, I have big problem with trailing stop and I thinked solved this problem with this code, but but nothing helps.
    Please help me!

    The code is:
    defparam cumulateorders = false

    //order launch (example) would be set to any other entry conditions
    //c1 = close>close[1]
    c2 = high=8236 //plus haut CAC40 FCE 1 minute du vendredi 15/03 16h31
    //graph c2
    //if c1 then
    //BUY 1 LOT AT MARKET
    //SET STOP PLOSS 50
    //endif

    if c2 then
    SELLSHORT 1 CONTRACTS AT MARKET
    SET STOP PLOSS 20
    endif

    //graph tradeprice(0)coloured(250,0,0)
    //graph tradeprice(1)coloured(0,250,0)
    //************************************************************************
    //trailing stop function
    trailingstart = 5 //trailing will start @trailinstart points profit
    trailingstep = 2 //trailing step to move the “stoploss”

    //reset the stoploss value
    IF NOT ONMARKET THEN
    newSL=0
    ENDIF

    //manage long positions
    IF LONGONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND close-tradeprice(1)>=trailingstart*pipsize THEN
    newSL = tradeprice(1)+trailingstep*pipsize
    ENDIF
    //next moves
    IF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
    newSL = newSL+trailingstep*pipsize
    ENDIF
    ENDIF

    //manage short positions
    IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND tradeprice(1)-close>=trailingstart*pipsize THEN
    newSL = tradeprice(1)-trailingstep*pipsize
    ENDIF
    //next moves
    IF newSL>0 AND newSL-close>=trailingstep*pipsize THEN
    newSL = newSL-trailingstep*pipsize
    ENDIF
    ENDIF

    //stop order to exit the positions
    IF newSL>0 THEN
    SELL AT newSL STOP
    EXITSHORT AT newSL STOP
    ENDIF
    //************************************************************************
    //graph tradeprice(1)coloured(0,250,0)
    GRAPH newSL as “trailing”

    Thanks in advance.

avatar
Register or

Top