Trailing Stop and Breakeven codes

Viewing 15 posts - 1 through 15 (of 26 total)
  • Author
    Posts
  • #93285 quote
    Gianluca
    Participant
    Master

    I hope this could help, theese are the codes i use for all my algos and they are all made by Nicolas and 1 by Ale, i see that there are many post about it and sometimes could be hard for new users to found it, maybe Nicola could make 1 single post on the library with this, but i ask for a check because somethimes in my algos there is some problems with it. (sorry for my english ehehe)

    //1/TRAILING STOP//////////////////////////////////////////////////////
    once trailinstop= 0   //1 on - 0 off
    trailingstart = 140 //trailing will start @trailinstart points profit
    trailingstep = 10 //trailing step to move the "stoploss"
    ///2 BREAKEAVEN///////////
    once breakeaven = 0    //1 on - 0 off
    startBreakeven = 30 //how much pips/points in gain to activate the breakeven function?
    PointsToKeep = 5 //how much pips/points to keep in profit above of below our entry price when the breakeven is activated (beware of spread)
    //3 MFE excursion
    //trailing stop
    ONCE MFE=0
    TRAILINGMFE = 20
    //4/// logic trailing ale
    ONCE logictrailing=0
    TGL =22
    TGS=21
    
    //************************************************************************
    //1 trailing stop function
    if trailinstop>0 then
    //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
    endif
    ///////////////////////////
    
    
    
    
    
    
    
    
    
    ///2///////////////////////////////////////////////
    //reset the breakevenLevel when no trade are on market
    if breakeaven>0 then
    IF NOT ONMARKET THEN
    breakevenLevel=0
    ENDIF
    // --- BUY SIDE ---
    //test if the price have moved favourably of "startBreakeven" points already
    IF LONGONMARKET AND close-tradeprice(1)>=startBreakeven*pipsize THEN
    //calculate the breakevenLevel
    breakevenLevel = tradeprice(1)+PointsToKeep*pipsize
    ENDIF
    
    //place the new stop orders on market at breakevenLevel
    IF breakevenLevel>0 THEN
    SELL AT breakevenLevel STOP
    ENDIF
    // --- end of BUY SIDE ---
    
    IF SHORTONMARKET AND tradeprice(1)-close>startBreakeven*pipsize THEN
    //calculate the breakevenLevel
    breakevenLevel = tradeprice(1)-PointsToKeep*pipsize
    ENDIF
    //place the new stop orders on market at breakevenLevel
    IF breakevenLevel>0 THEN
    EXITSHORT AT breakevenLevel STOP
    ENDIF
    endif
    
    
    //3// MFE EXCURSION////
    
    if MFE>0 then
    //resetting variables when no trades are on market
    if not onmarket then
    MAXPRICEMFE = 0
    MINPRICEMFE = close
    priceexitMFE = 0
    endif
    
    //case SHORT order
    if shortonmarket then
    MINPRICE = MIN(MINPRICEMFE,close) //saving the MFE of the current trade
    if tradeprice(1)-MINPRICEMFE>=TRAILINGMFE*pointsize then //if the MFE is higher than the trailingstop then
    priceexitMFE = MINPRICEMFE+TRAILINGMFE*pointsize //set the exit price at the MFE + trailing stop price level
    endif
    endif
    
    //case LONG order
    if longonmarket then
    MAXPRICEMFE = MAX(MAXPRICEMFE,close) //saving the MFE of the current trade
    if MAXPRICEMFE-tradeprice(1)>=TRAILINGMFE*pointsize then //if the MFE is higher than the trailingstop then
    priceexitMFE = MAXPRICEMFE-TRAILINGMFE*pointsize //set the exit price at the MFE - trailing stop price level
    endif
    endif
    
    //exit on trailing stop price levels
    if onmarket and priceexitMFE>0 then
    EXITSHORT AT priceexitMFE STOP
    SELL AT priceexitMFE STOP
    endif
    ENDIF
    
    
    
    
    ///4 Logic trailing ale
    // LOGIC TRAILING STOP
    //RESET
    if logictrailing>0 then
    IF NOT ONMARKET THEN
    MAXPRICE = 0
    MINPRICE = CLOSE
    PREZZOUSCITA = 0
    ENDIF
    
    //SE LONG ALLORA:
    IF LONGONMARKET THEN
    MAXPRICE = MAX(MAXPRICE,CLOSE) //SAVING THE MFE OF THE CURRENT TRADE
    IF MAXPRICE-TRADEPRICE(1)>=TGL*POINTSIZE THEN //IF THE MFE IS HIGHER THAN THE TRAILINGSTOP THEN
    PREZZOUSCITA = MAXPRICE-TGL*POINTSIZE //SET THE EXIT PRICE AT THE MFE - TRAILING STOP PRICE LEVEL
    ENDIF
    ENDIF
    IF SHORTONMARKET THEN
    MINPRICE = MIN(MINPRICE,CLOSE) //SAVING THE MFE OF THE CURRENT TRADE
    IF TRADEPRICE(1)-MINPRICE>=TGS*POINTSIZE THEN //IF THE MFE IS HIGHER THAN THE TRAILINGSTOP THEN
    PREZZOUSCITA = MINPRICE+TGS*POINTSIZE //SET THE EXIT PRICE AT THE MFE + TRAILING STOP PRICE LEVEL
    ENDIF
    ENDIF
    //EXIT ON TRAILING STOP PRICE LEVELS
    IF ONMARKET AND PREZZOUSCITA>0 THEN
    EXITSHORT AT PREZZOUSCITA STOP
    SELL AT PREZZOUSCITA STOP
    ENDIF
    endif
    
    GraHal, Balmora74, bertrandpinoy and 6 others thanked this post
    #93286 quote
    GraHal
    Participant
    Master

    Great idea Gianluca … just what I needed!

    Link to above post added to here 

    Snippet Link Library

    Kovit and moustique16 thanked this post
    #93287 quote
    GraHal
    Participant
    Master

    but i ask for a check because somethimes in my algos there is some problems with it

    Do you have problems with all 4 x TS Codes or just one specific TS Code?

    #93290 quote
    Gianluca
    Participant
    Master

    only the breakeven

    GraHal thanked this post
    #93293 quote
    Paul
    Participant
    Master

    @Gianluca make sure the trailing stop is above the breakeven. Makes a difference too.

     

    Using above codes, then you have to use “not on market” as entry condition.

    However, if you have long position and get a short signal you want to reverse immediately right, but that maybe get’s skipped now since it’s waiting for the active trade to first hit a target (stoploss, trailing-stop, breakeven etc) because of “not on market” condition.

    If you use those codes, and do not use “not on market” as entry criteria, you may get unexpected results.

     

    That’s an issue and influences WF and optimisation results. I think it creates fake WF results! (but perhaps looking nicer)

    GraHal thanked this post
    #93374 quote
    Gianluca
    Participant
    Master

    If you use those codes, and do not use “not on market” as entry criteria, you may get unexpected results.

    thank you, but i put in all my codes the code

    not onmarket

    🙂 i am only intraday trader for now, stoppend all the multidays except for the pathfinder swing

    #99370 quote
    Luce
    Participant
    New

    Hi Paul, I wonder wether you can help here – I’ve coded the below as far as I can get but seem to be just missing one minor detail! I’m Still working on a way to combine a trailing stop with a trailing step that becomes a fixed stop – i.e Trade is a buy open with a 10pt stop, if it moves 2 up, your stop is now 8, if it moves another 2, it’s now 6 but when it gets to 10, so break even on a 1-1, it becomes fixed. Currently I only get a trailing to stop at breakeven, so still risking the full 10.

    I notice that with this although I’m getting the result of the trailing stop at breakeven which is great, the trailing stop still seems to be live with a step as the deal closes sometimes later at 25 or 35 or 45 etc…great problem to have but not what I want as I lose on bigger moves.

    Adding a trailing stop after the first one becomes fixed would be the next part, so if it moves another 30 pts you bank another 10 for example. I’m thinking this is a simple code tweak..? Code below, perhaps you can help me..?

    // Definition of code parameters
    DEFPARAM CumulateOrders = False // Cumulating positions deactivated
    
    // Prevents the system from creating new orders to enter the market or increase position size before the specified time
    noEntryBeforeTime = 143000
    timeEnterBefore = time >= noEntryBeforeTime
    
    // Conditions to enter long positions
    indicator1 = SuperTrend[4,90]
    c1 = (close CROSSES OVER indicator1)
    
    IF c1 AND timeEnterBefore THEN
    BUY 10 PERPOINT AT MARKET
    
    ENDIF
    
    // Conditions to exit long positions
    indicator2 = SuperTrend[4,90]
    c2 = (close CROSSES UNDER indicator2)
    
    IF c2 THEN
    SELL AT MARKET
    ENDIF
    
    // Conditions to enter short positions
    indicator3 = SuperTrend[4,90]
    c3 = (close CROSSES UNDER indicator3)
    
    IF c3 AND timeEnterBefore THEN
    SELLSHORT 10 PERPOINT AT MARKET
    
    ENDIF
    
    // Conditions to exit short positions
    indicator4 = SuperTrend[4,90]
    c4 = (close CROSSES OVER indicator4)
    
    IF c4 THEN
    EXITSHORT AT MARKET
    ENDIF
    
    //reset the breakevenLevel when no trade are on market
    IF NOT ONMARKET THEN
    breakevenLevel=0
    ENDIF
    
    // Stops and targets
    SET STOP pTRAILING 20
    
    //place the new stop orders on market at breakevenLevel
    IF breakevenLevel>0 THEN
    SELL AT breakevenLevel STOP
    ENDIF
    #99383 quote
    Paul
    Participant
    Master

    Nothing is a simple tweak or maybe it is for the experts.

    Have a look in the snippet link library for some ideas.

    i.e. Trailing Stop Loss and Trailing Take Profit from Vonasi.

    #129156 quote
    bertrandpinoy
    Participant
    Veteran

    do you use all 4 codes in the same strategy? or only 1 code in 1strategie?

    #129176 quote
    nonetheless
    Participant
    Master

    Hi @Paul — this is my preferred trailing code. Should I have ‘not onmarket’ in the entry conditions? I’ve tried it with and without but back test results are identical.

    //%trailing stop function
    trailingPercent = tst
    stepPercent = st
    if onmarket then
    trailingstart = tradeprice(1)*(trailingpercent/100) //trailing will start @trailingstart points profit
    trailingstep = tradeprice(1)*(stepPercent/100) //% step to move the stoploss
    endif
     
    //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)+trailingstep
    ENDIF
    //next moves
    IF newSL>0 AND close-newSL>trailingstep THEN
    newSL = newSL+trailingstep
    ENDIF
    ENDIF
     
    //manage short positions
    IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND tradeprice(1)-close>=trailingstart THEN
    newSL = tradeprice(1)-trailingstep
    ENDIF
    //next moves
    IF newSL>0 AND newSL-close>trailingstep THEN
    newSL = newSL-trailingstep
    ENDIF
    ENDIF
     
    //stop order to exit the positions
    IF newSL>0 THEN
    SELL AT newSL STOP
    EXITSHORT AT newSL STOP
    ENDIF
    #129187 quote
    Paul
    Participant
    Master

    Should I have ‘not onmarket’ in the entry conditions? I’ve tried it with and without but back test results are identical.

    Hi, I don’t prefer that. When optimising for good signals, all signals should have value, regardless if there’s a position in opposite direction or not.

    You could try this, made it a bit as my other trailing stops. Tested with not onmarket  and without in entry conditions and have different results.

    // %trailing stop function
    once trailingstoptype     = 1   // trailing stop - 0 off, 1 on
    
    once trailingpercent      = 0.3 //trailing will start @trailingstart points profit
    once steppercent          = 0.1 //% step to move the stoploss
    
    once sensitivityts        = 1   // [0]close;[1]high/low
    //
    if trailingstoptype then
    
    if onmarket then
    trailingstart =tradeprice(1)*(trailingpercent/100) 
    trailingstep = tradeprice(1)*(steppercent/100)
    endif
     
    //reset the stoploss value
    if not onmarket or ((longonmarket and shortonmarket[1]) or (longonmarket[1] and shortonmarket)) then
    newsl=0
    endif
    //
    if sensitivityts then
    sensitivitytslong=high
    sensitivitytsshort=low
    else
    sensitivitytslong=close
    sensitivitytsshort=close
    endif
    
    //manage long positions
    if longonmarket then
    //first move (breakeven)
    if newsl=0 and sensitivitytslong-tradeprice(1)>=trailingstart then
    newsl = tradeprice(1)+trailingstep
    endif
    //next moves
    if newsl>0 and close-newsl>trailingstep then
    newsl = newsl+trailingstep
    endif
    endif
     
    //manage short positions
    if shortonmarket then
    //first move (breakeven)
    if newsl=0 and tradeprice(1)-sensitivitytsshort>=trailingstart then
    newsl = tradeprice(1)-trailingstep
    endif
    //next moves
    if newsl>0 and newsl-close>trailingstep then
    newsl = newsl-trailingstep
    endif
    endif
     
    if longonmarket then
    if newsl>0 then
    sell at newsl stop
    endif
    if newsl>0 then
    if low crosses under newsl then
    sell at market //when stop is rejected
    endif
    endif
    endif
    //
    if shortonmarket then
    if newsl>0 then
    exitshort at newsl stop
    endif
    if newsl>0 then
    if high crosses over newsl then
    exitshort at market //when stop is rejected
    endif
    endif
    endif
    endif
    nonetheless and ginko thanked this post
    #140047 quote
    deleted23092025
    Participant
    New

    Very good post. I´ve recently worked with a low tf (2,3m) robots and I put many hours in the trailing stop code. I get really good results with OOS/IS 70/30 with kind of high trailingstep (over 1%). When I think about one low tf 2-3min bot running over 1% I feel like it gets very curve fit even tho I run it 5 times and get 50+ wfe.

    Do you guys have any tips to add in a low tf bot? Is breakeven, atr or other opitions a MUST have in the trailstop. Or should i just optimize the system with max 0.7% trailingpercent?

    I would appriceate all thoughts. Thanks!

    #141875 quote
    Gianluca
    Participant
    Master

    I think depends by the strategy 🙂

    #145404 quote
    Paul
    Participant
    Master

    small change to code above. Splitted for long & short, added one for sensitivity to see difference and used accelerator, if using bigger percentage means bigger steps.

    // trailing stop percentage
    once trailingstoptype2 = 1
    
    if trailingstoptype2 then
    //====================
    once trailingpercentlong  = 0.333 // %
    once trailingpercentshort = 0.333 // %
    once accelerator     = 1 // 1 = default; always > 0 (i.e. 0.5-3)
    once ts2sensitivity  = 1 // [0]close;[1]high/low;[2]low;high
    //====================
    once steppercentlong  = (trailingpercentlong/10)*accelerator
    once steppercentshort = (trailingpercentshort/10)*accelerator
    if onmarket then
    trailingstartlong = tradeprice(1)*(trailingpercentlong/100)
    trailingstartshort = tradeprice(1)*(trailingpercentshort/100)
    
    trailingsteplong = tradeprice(1)*(steppercentlong/100)
    trailingstepshort = tradeprice(1)*(steppercentshort/100)
    endif
    if not onmarket or ((longonmarket and shortonmarket[1]) or (longonmarket[1] and shortonmarket)) then
    newsl=0
    endif
    if ts2sensitivity=1 then
    ts2sensitivitylong=high
    ts2sensitivityshort=low
    elsif ts2sensitivity=2 then
    ts2sensitivitylong=low
    ts2sensitivityshort=high
    else
    ts2sensitivitylong=close
    ts2sensitivityshort=close
    endif
    if longonmarket then
    if newsl=0 and ts2sensitivitylong-tradeprice(1)>=trailingstartlong then
    newsl = tradeprice(1)+trailingsteplong
    endif
    if newsl>0 and ts2sensitivitylong-newsl>trailingsteplong then
    newsl = newsl+trailingsteplong
    endif
    endif
    if shortonmarket then
    if newsl=0 and tradeprice(1)-ts2sensitivityshort>=trailingstartshort then
    newsl = tradeprice(1)-trailingstepshort
    endif
    if newsl>0 and newsl-ts2sensitivityshort>trailingstepshort then
    newsl = newsl-trailingstepshort
    endif
    endif
    if barindex-tradeindex>1 then
    if longonmarket then
    if newsl>0 then
    sell at newsl stop
    endif
    if newsl>0 then
    if low crosses under newsl then
    sell at market
    endif
    endif
    endif
    if shortonmarket then
    if newsl>0 then
    exitshort at newsl stop
    endif
    if newsl>0 then
    if high crosses over newsl then
    exitshort at market
    endif
    endif
    endif
    endif
    endif
    #145405 quote
    Paul
    Participant
    Master

    edit…

Viewing 15 posts - 1 through 15 (of 26 total)
  • You must be logged in to reply to this topic.

Trailing Stop and Breakeven codes


ProOrder: Automated Strategies & Backtesting

New Reply
Author
author-avatar
Gianluca @altares Participant
Summary

This topic contains 25 replies,
has 10 voices, and was last updated by Madrosat
2 years, 10 months ago.

Topic Details
Forum: ProOrder: Automated Strategies & Backtesting
Language: English
Started: 03/10/2019
Status: Active
Attachments: 1 files
Logo Logo
Loading...