Implementing ATR-Based Trailing and Breakeven Stops in Trading Strategies

25 Jun 2022
0 comment
0 attachment

This code snippet demonstrates how to implement ATR (Average True Range) based trailing and breakeven stop mechanisms in trading strategies using the ProBuilder language. These stops are crucial for managing risk and protecting profits in trading systems.


atr trailing stop & atr breakeven stop. Both can be used.
// breakeven stop atr once breakevenstoptype = 1
// breakeven stop - 0 off, 1 on
once breakevenstoplong = 1
// breakeven stop atr relative distance
once breakevenstopshort = 1
// breakeven stop atr relative distance
once pointstokeep = 5
// positive or negative
once atrperiodbreakeven = 14
// atr parameter value
once minstopbreakeven = 10
// minimum breakeven stop distance
//----------------------------------------------
atrbreakeven = averagetruerange[atrperiodbreakeven]((close/10)*pipsize)/1000
//atrbreakeven=averagetruerange[atrperiodbreakeven]((close/1)*pipsize) // (forex)
bestopl = round(atrbreakeven*breakevenstoplong)
bestops = round(atrbreakeven*breakevenstopshort)
if breakevenstoptype = 1 then
    // if not onmarket or ((longonmarket and shortonmarket[1]) or (longonmarket[1] and shortonmarket)) then
    maxpricebe = 0
    minpricebe = close
    newslbe = 0
    endif
    // if longonmarket then
    maxpricebe = max(maxpricebe,close)
    if maxpricebe-tradeprice(1)>=bestopl*pointsize then
        if maxpricebe-tradeprice(1)>=minstopbreakeven then
            newslbe=tradeprice(1)+pointstokeep*pipsize
        else
            newslbe=tradeprice(1)- minstopbreakeven*pointsize
        endif
    endif
    endif
    // if shortonmarket then
    minpricebe = min(minpricebe,close)
    if tradeprice(1)-minpricebe>=bestops*pointsize then
        if tradeprice(1)-minpricebe>=minstopbreakeven then
            newslbe = tradeprice(1)-pointstokeep*pipsize
        else
            newslbe = tradeprice(1) + minstopbreakeven*pointsize
        endif
    endif
    endif
    // if longonmarket then
    if newslbe>0 then
        sell at newslbe stop
    endif
    if newslbe>0 then
        if low < newslbe then
            sell at market
        endif
    endif
    endif
    // if shortonmarket then
    if newslbe>0 then
        exitshort at newslbe stop
    endif
    if newslbe>0 then
        if high > newslbe then
            exitshort at market
        endif
    endif
    endif
    //graphonprice newslbe coloured(255,165,0) as "breakevenstop atr"
    endif
    // trailing stop atr
    once trailingstoptype = 1
    // trailing stop - 0 off, 1 on
    once trailingstoplong = 3
    // trailing stop atr relative distance
    once trailingstopshort = 3
    // trailing stop atr relative distance
    once atrtrailingperiod = 14
    // atr parameter value
    once minstop = 10
    // minimum trailing stop distance
    //----------------------------------------------
    atrtrail = averagetruerange[atrtrailingperiod]((close/10)*pipsize)/1000
    //atrtrail=averagetruerange[atrtrailingperiod]((close/1)*pipsize) (forex)
    tgl = round(atrtrail*trailingstoplong)
    tgs = round(atrtrail*trailingstopshort)
    if trailingstoptype = 1 then
        // if not onmarket or ((longonmarket and shortonmarket[1]) or (longonmarket[1] and shortonmarket)) then
        maxprice = 0
        minprice = close
        newsl = 0
        endif
        // if longonmarket then
        maxprice = max(maxprice,close)
        if maxprice-tradeprice(1)>=tgl*pointsize then
            if maxprice-tradeprice(1)>=minstop then
                newsl = maxprice-tgl*pointsize
            else
                newsl = maxprice - minstop*pointsize
            endif
        endif
        endif
        // if shortonmarket then
        minprice = min(minprice,close)
        if tradeprice(1)-minprice>=tgs*pointsize then
            if tradeprice(1)-minprice>=minstop then
                newsl = minprice+tgs*pointsize
            else
                newsl = minprice + minstop*pointsize
            endif
        endif
        endif
        // if longonmarket then
        if newsl>0 then
            sell at newsl stop
        endif
        if newsl>0 then
            if low < 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 > newsl then
                exitshort at market
            endif
        endif
        endif
        //graphonprice newsl coloured(0,0,255,255) as "trailingstop atr"
        endif

Explanation of the Code:

  • The code starts by setting up parameters for both breakeven and trailing stops, including the type of stop, ATR period, and minimum stop distances.
  • It calculates the ATR values for both breakeven and trailing stops, adjusting for the market’s pip size.
  • Conditional checks determine if the market conditions meet the criteria for setting or adjusting the stops based on the calculated ATR values.
  • For long positions, the code checks if the current maximum price minus the trade price is greater than the calculated stop distance. If true, it adjusts the stop level accordingly.
  • Similarly, for short positions, it adjusts the stop level based on the minimum price and the trade price.
  • The code includes conditions to execute trades at the stop level or at the market price if the price crosses the stop level.
  • Finally, graphical representations of the stop levels are plotted on the price chart for visual reference.

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.
paul New
This author is like an anonymous function, present but not directly identifiable. More details on this code architect as soon as they exit 'incognito' mode.
Author’s Profile

Comments

Search Snippets

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

Snippets Categories

global
35
indicator
133
strategy
171

Recent Snippets

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 [...]
How to Build a Step-Based Trailing Stop That Moves to Break-Even First
strategy
This snippet implements a step trailing stop that advances in fixed increments once price reaches predefined profit [...]
Utilizing Arrays to Track and Compare Indicator Values Within the Same Bar in ProBuilder
indicator
This ProBuilder code snippet demonstrates how to use arrays to compare the values of an indicator (RSI in this case) [...]
Logo Logo
Loading...