Implementing Various Trailing Stop Strategies in ProBuilder

17 Jun 2015
0 comment
0 attachment

This code snippet demonstrates how to implement various trailing stop strategies using the ProBuilder language. Trailing stops are a type of stop-loss order that adjusts automatically to the price movements of a stock. The code includes four different trailing stop mechanisms: a basic trailing stop, a breakeven stop, a maximum favorable excursion (MFE) based trailing stop, and a logic-based trailing stop.


//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

Explanation of the Code:

  • The code starts by defining several variables and conditions for different types of trailing stops.
  • Each section of the code handles a specific type of trailing stop:
    • Basic Trailing Stop: Adjusts the stop loss as the price moves in favor of the trade.
    • Breakeven Stop: Moves the stop loss to a breakeven point once a certain profit is reached.
    • MFE Based Trailing Stop: Uses the maximum favorable excursion to adjust the stop loss dynamically based on the best price achieved during the trade.
    • Logic Based Trailing Stop: Uses a logic-based approach to determine when to adjust the stop loss.
  • Each trailing stop type includes conditions to handle both long and short positions.
  • The code uses conditional statements to check the market conditions and adjust the stop loss accordingly.

Related Post

Check out this related content for more information:

https://www.prorealcode.com/topic/trailing-stop-and-breakeven-codes/#post-93285

Visit Link
What is a Snippet? A snippet is a small, reusable chunk of code designed to solve specific tasks quickly. Think of it as a shortcut that helps you achieve your coding goals without reinventing the wheel. How to Use: Simply copy the snippet and paste it into your project where needed. Don't forget to tweak it to fit your context. Snippets are not just time-savers; they're also learning tools to help you become a more efficient coder.
Nicolas Legend
I created ProRealCode because I believe in the power of shared knowledge. I spend my time coding new tools and helping members solve complex problems. If you are stuck on a code or need a fresh perspective on a strategy, I am always willing to help. Welcome to the community!
Author’s Profile

Comments

Search Snippets

Showing some results...
Sorry, no result found!

Snippets Categories

global
35
indicator
135
strategy
171

Recent Snippets

A multi indicator Dashboard for ProRealTime
indicator
This snippet creates a compact on-chart dashboard that aggregates multiple indicator states into a single, readable [...]
How to Track Up/Down Cumulative Volume Inside Each Candle (Tick Volume Delta)
indicator
This snippet separates the real-time, intra-candle volume into up-volume and down-volume based on whether the last [...]
How to Create a Simple MTF Trend Dashboard with EMA and SMA
indicator
This indicator builds a compact multi-timeframe (MTF) dashboard that shows whether price is trading above or below a [...]
How to Display Per-Bar Volume Accumulation in Real Time (Intrabar Updates)
global
This snippet tracks and displays the current bar’s accumulated volume while the bar is still forming, instead of only [...]
Ticks Counter: Count Tick Updates Per Bar on Tick or Time Charts
global
This snippet counts how many tick updates have occurred for the current bar by incrementing a per-bar counter on each [...]
Logo Logo
Loading...