How to Implement ATR Stop Loss in TradingView Pine Script?

The Average True Range (ATR) is a volatility indicator widely used in trading. Implementing ATR stop loss strategies in TradingView Pine Script provides a robust way to manage risk and adapt to market dynamics.

What is Average True Range (ATR)?

ATR measures the average range a security’s price moves during a given period. It considers the true range, which accounts for gaps and limit moves. The formula involves calculating the greatest of the following:

  • Current high less the current low.
  • Absolute value of the current high less the previous close.
  • Absolute value of the current low less the previous close.

ATR is then typically calculated as an exponential moving average of the true range over a specified period (e.g., 14 periods).

Understanding ATR Stop Loss Strategy

An ATR stop loss uses the ATR value to determine the stop loss level. The stop loss is placed at a multiple of the ATR value away from the entry price. This dynamically adjusts the stop loss based on market volatility.

Benefits of Using ATR Stop Loss in TradingView

  • Volatility-Based Adjustment: Automatically adapts to changing market conditions.
  • Risk Management: Helps control potential losses by setting stops based on volatility, not arbitrary price levels.
  • Customization: Highly customizable through adjusting ATR periods and multipliers.
  • Backtesting: Easily backtestable in TradingView to optimize parameters.

Basic ATR Stop Loss Implementation in Pine Script

Calculating ATR Value in Pine Script

Pine Script has a built-in ta.atr() function for calculating ATR. You specify the period as an argument.

atrValue = ta.atr(14)

Determining Stop Loss Level Based on ATR

Multiply the ATR value by a factor to determine the stop loss distance.

atrMultiplier = 2.0
stopLossDistance = atrValue * atrMultiplier

Simple Buy and Sell Signals with ATR Stop Loss

Define buy and sell conditions, and then use the calculated stopLossDistance to set the stop loss level.

longCondition = ta.crossover(ta.sma(close, 20), ta.sma(close, 50))
shortCondition = ta.crossunder(ta.sma(close, 20), ta.sma(close, 50))

if (longCondition)
    strategy.entry("Long", strategy.long)
    strategy.exit("ExitLong", "Long", stop = close - stopLossDistance)

if (shortCondition)
    strategy.entry("Short", strategy.short)
    strategy.exit("ExitShort", "Short", stop = close + stopLossDistance)

Advanced ATR Stop Loss Techniques

Adjusting ATR Period and Multiplier

Experiment with different ATR periods and multipliers to optimize the strategy for various market conditions. Shorter periods react faster to volatility changes, while longer periods provide smoother values. The multiplier determines how far the stop loss is from the entry price.

Trailing Stop Loss with ATR

A trailing stop loss adjusts the stop loss level as the price moves in a favorable direction, locking in profits.

var float longStop = na
if (longCondition)
    longStop := close - stopLossDistance
if (strategy.position_size > 0)
    longStop := math.max(longStop, close - stopLossDistance)

strategy.exit("ExitLong", "Long", stop = longStop)

Dynamic ATR Stop Loss Based on Volatility

Use different ATR multipliers based on current volatility. For example, use a smaller multiplier during high volatility and a larger one during low volatility.

Combining ATR Stop Loss with Other Indicators

Enhance the ATR stop loss strategy by combining it with other indicators such as moving averages, RSI, or MACD to improve signal accuracy.

Implementing ATR Stop Loss for Long and Short Positions

ATR Stop Loss for Long Entries

For long entries, the stop loss is placed below the entry price.

stopLossLevel = entryPrice - (atrValue * atrMultiplier)

ATR Stop Loss for Short Entries

For short entries, the stop loss is placed above the entry price.

stopLossLevel = entryPrice + (atrValue * atrMultiplier)

Managing Risk with Different Position Sizes

Adjust position sizes based on ATR to maintain consistent risk levels. Higher ATR values would result in smaller position sizes, and vice versa.

Practical Examples and Code Snippets

Example 1: Basic ATR Stop Loss Strategy Code

//@version=5
strategy("Basic ATR Stop Loss", overlay=true)

atrLength = input.int(14, title="ATR Length")
atrMultiplier = input.float(2.0, title="ATR Multiplier")

atrValue = ta.atr(atrLength)
stopLossDistance = atrValue * atrMultiplier

longCondition = ta.crossover(ta.sma(close, 20), ta.sma(close, 50))
shortCondition = ta.crossunder(ta.sma(close, 20), ta.sma(close, 50))

if (longCondition)
    strategy.entry("Long", strategy.long)
    strategy.exit("ExitLong", "Long", stop = close - stopLossDistance)

if (shortCondition)
    strategy.entry("Short", strategy.short)
    strategy.exit("ExitShort", "Short", stop = close + stopLossDistance)

plot(close - stopLossDistance, color=color.red, title="Long Stop Loss")
plot(close + stopLossDistance, color=color.green, title="Short Stop Loss")

Example 2: Trailing ATR Stop Loss Code

//@version=5
strategy("Trailing ATR Stop Loss", overlay=true)

atrLength = input.int(14, title="ATR Length")
atrMultiplier = input.float(2.0, title="ATR Multiplier")

atrValue = ta.atr(atrLength)
stopLossDistance = atrValue * atrMultiplier

longCondition = ta.crossover(ta.sma(close, 20), ta.sma(close, 50))

var float longStop = na
if (longCondition)
    strategy.entry("Long", strategy.long)
    longStop := close - stopLossDistance

if (strategy.position_size > 0)
    longStop := math.max(longStop, close - stopLossDistance)

strategy.exit("ExitLong", "Long", stop = longStop)

plot(longStop, color=color.red, title="Trailing Stop Loss")

Testing and Optimizing ATR Stop Loss Strategies

Use TradingView’s strategy tester to evaluate the performance of ATR stop loss strategies. Optimize parameters such as ATR length and multiplier by backtesting on historical data. Consider walkforward analysis to ensure robustness of the strategy.


Leave a Reply