Logo
OFFLINEPIXEL
/ pinescript-strategies / pine-script-atr

$ Pine Script Average True Range (ATR)

Master this essential volatility indicator in TradingView's Pine Script for dynamic stop-loss placement, position sizing, and understanding market conditions.

500+ Clients Helped
100% Satisfaction
Live Trading Ready
⚠️
Trading financial markets carries risk. All content (PineScript code, indicators, strategies) on this website is for educational purposes only. Past performance is not indicative of future results. By using any code or information from this site, you agree that you are solely responsible for your trading decisions. The author disclaims all liability for any losses incurred. To gain from experts experiences, You can always try our Invite Only Scripts
01

What is the Average True Range (ATR)?

The Average True Range (ATR) is a widely used volatility indicator developed by J. Welles Wilder Jr. (also the creator of RSI, ADX, and Parabolic SAR). Unlike other indicators that measure price direction, ATR quantifies market volatility by calculating the average of true ranges over a specified period. The "true range" accounts for gaps and limits to capture the full extent of price movement within a given period. A high ATR value indicates high volatility, while a low ATR value suggests low volatility.

In Pine Script, ATR is an indispensable tool not for generating buy/sell signals directly, but for risk management, position sizing, and adapting strategies to changing market conditions. It helps traders set objective stop-loss and take-profit levels that are appropriate for the current market's swing.

02

Components and Calculation

The calculation of ATR begins with the True Range (TR) for each period. The True Range is the greatest of the following three values:

  1. The distance between the current high and the current low: High - Low
  2. The absolute distance between the current high and the previous day's close: abs(High - Close[1])
  3. The absolute distance between the current low and the previous day's close: abs(Low - Close[1])
03

Basic Average True Range (ATR) Implementation in Pine Script

pine-script@terminal
//@version=5
indicator("My Average True Range (ATR)", overlay=false, format=format.price)

// Input for ATR length
length = input.int(14, title="ATR Length", minval=1)

// Calculate ATR value using the built-in function
atrValue = ta.atr(length)

// Plot the ATR line
plot(atrValue, title="ATR", color=color.purple, linewidth=2)

// Optional: Add moving average of ATR to identify volatility trends
atrMA = ta.sma(atrValue, 20)
plot(atrMA, title="ATR MA", color=color.gray, linewidth=1, style=plot.style_line)

// Highlight background when ATR is significantly higher or lower than its average
bgcolor(atrValue > atrMA * 1.5 ? color.new(color.orange, 90) : na, title="High Volatility")
bgcolor(atrValue < atrMA * 0.7 ? color.new(color.blue, 90) : na, title="Low Volatility")
$ ✓ Compiled successfully
04

Volatility, Not Direction

Volatility, Not Direction

Remember that ATR measures *how much* price is moving, not *which direction* it's moving. A rising ATR means prices are swinging more, while a falling ATR means they are quiet.

05

Practical ATR Trading Strategies

1. Dynamic Stop Loss Placement (Primary Use)

ATR is widely used to place stop-loss orders dynamically, adapting to current market volatility.

  • Long Position Stop Loss: Entry Price - (ATR * Multiplier)
  • Short Position Stop Loss: Entry Price + (ATR * Multiplier)
  • A common multiplier is 2 or 3 (e.g., 2 * ATR from your entry).
//@version=5
strategy("ATR Dynamic Stop Loss", overlay=true)

atrLength = input.int(14, title="ATR Length", minval=1)
stopLossMultiplier = input.float(2.0, title="Stop Loss Multiplier", minval=0.1, step=0.1)

atrValue = ta.atr(atrLength)

maLength = input.int(20, title="Entry MA Length", minval=1)
maValue = ta.sma(close, maLength)

longCondition = ta.crossover(close, maValue)
shortCondition = ta.crossunder(close, maValue)

longStopLoss = strategy.position_avg_price - (atrValue * stopLossMultiplier)
shortStopLoss = strategy.position_avg_price + (atrValue * stopLossMultiplier)

if (longCondition)
    strategy.entry("Long", strategy.long)

if (shortCondition)
    strategy.entry("Short", strategy.short)

strategy.exit("Long Exit", from_entry="Long", stop=longStopLoss)
strategy.exit("Short Exit", from_entry="Short", stop=shortStopLoss)

plot(strategy.position_avg_price > 0 ? longStopLoss : na, "Long Stop Loss", color=color.red, style=plot.style_linebr, linewidth=1)
plot(strategy.position_avg_price < 0 ? shortStopLoss : na, "Short Stop Loss", color=color.red, style=plot.style_linebr, linewidth=1)

2. Position Sizing based on Volatility

ATR can be used to size positions so that the monetary risk per trade is consistent, regardless of the asset's volatility.

  • Calculate Risk per Share (RPS): ATR * Multiplier
  • Calculate Number of Shares: (Account Risk / RPS)
//@version=5
strategy("ATR Position Sizing Example", overlay=true)

atrLength = input.int(14, title="ATR Length", minval=1)
atrMultiplier = input.float(2.0, title="ATR Risk Multiplier", minval=0.1, step=0.1)
accountRiskPerTrade = input.float(1000.0, title="Max $ Risk Per Trade", minval=10)

atrValue = ta.atr(atrLength)
riskPerShare = atrValue * atrMultiplier
sharesToTrade = riskPerShare != 0 ? math.floor(accountRiskPerTrade / riskPerShare) : 0

maLength = input.int(50, title="Entry MA Length", minval=1)
maValue = ta.sma(close, maLength)

longCondition = ta.crossover(close, maValue)
shortCondition = ta.crossunder(close, maValue)

if (longCondition)
    strategy.entry("Long (Sized)", strategy.long, qty=sharesToTrade)

if (shortCondition)
    strategy.entry("Short (Sized)", strategy.short, qty=sharesToTrade)

longStopLoss = strategy.position_avg_price - (atrValue * atrMultiplier)
shortStopLoss = strategy.position_avg_price + (atrValue * atrMultiplier)

strategy.exit("Long Exit", from_entry="Long (Sized)", stop=longStopLoss)
strategy.exit("Short Exit", from_entry="Short (Sized)", stop=shortStopLoss)

plot(atrValue, "ATR", color=color.purple, display=display.pane_only)

3. Volatility Filter for Trend-Following Strategies

ATR can help filter out choppy market conditions where trend-following strategies might struggle, or identify periods ripe for breakouts.

  • Strategy Enhancement: Only activate trend-following strategies when ATR is rising or above a certain threshold.
  • Consolidation Detection: When ATR is low and relatively flat, it signals a period of consolidation.
//@version=5
strategy("ATR Volatility Filter", overlay=true)

atrLength = input.int(14, title="ATR Length", minval=1)
atrValue = ta.atr(atrLength)

atrSMA = ta.sma(atrValue, 20)
atrThreshold = input.float(1.2, title="ATR Multiplier for Trending Filter", minval=1.0, step=0.1)

isTrendingVolatility = atrValue > atrSMA * atrThreshold

fastMA = ta.ema(close, 10)
slowMA = ta.ema(close, 20)

longSignal = ta.crossover(fastMA, slowMA) and isTrendingVolatility
shortSignal = ta.crossunder(fastMA, slowMA) and isTrendingVolatility

if (longSignal)
    strategy.entry("Long Filtered", strategy.long)

if (shortSignal)
    strategy.entry("Short Filtered", strategy.short)

plot(atrValue, "ATR", color=color.purple, display=display.pane_only)
plot(atrSMA, "ATR SMA", color=color.gray, display=display.pane_only)
plot(fastMA, "Fast MA", color=color.green, overlay=true)
plot(slowMA, "Slow MA", color=color.red, overlay=true)
bgcolor(isTrendingVolatility ? color.new(color.aqua, 90) : na, title="Trending Volatility Zone")
06

Optimizing ATR Performance

To get the most from the Average True Range in Pine Script:

  • Parameter Tuning: The default `length` of 14 is a good starting point for daily charts. Shorter lengths (e.g., 7) will make ATR more reactive to recent volatility, while longer lengths (e.g., 20 or 26) will provide a smoother, less noisy measure.
  • Multiplier Calibration: The `multiplier` used for stop-loss or profit target placement is critical. Backtest different multipliers (e.g., 1.5, 2.0, 2.5, 3.0) to find what works best.
  • Timeframe Adaptability: ATR is timeframe-dependent. Ensure your `length` and `multiplier` are calibrated for the timeframe you are using.
  • Combine with Directional Indicators: ATR is not a directional indicator. Always use it with other indicators (e.g., moving averages, MACD, RSI) that tell you *which way* the market is likely to move.
  • Trailing Stop Loss: ATR can be used to create trailing stop losses, allowing you to capture more of a trend while still protecting against sharp reversals.
07

Dynamic Risk Management

Dynamic Risk Management

ATR provides a dynamic way to manage risk, making your stops and targets more intelligent by adapting to current market conditions rather than using fixed price points.

08

Common ATR Pitfalls

  • Not a Directional Signal: The biggest mistake is trying to derive buy/sell signals directly from ATR.
  • Lag: ATR is a lagging indicator. It measures *past* volatility, which may or may not continue into the future.
  • Interpretation Subjectivity: Deciding on the "correct" ATR multiplier or threshold for volatility filtering can be subjective.
  • False Signals in Extreme Conditions: Very sudden spikes in volatility can cause ATR to jump, leading to very wide stops.
  • Not a Standalone Indicator: ATR is a risk management and market condition tool. It's not a complete trading system on its own.
09

Conclusion

Conclusion

The Average True Range (ATR) is a fundamental and exceptionally useful technical indicator in Pine Script for TradingView. While it doesn't provide directional signals, its accurate measurement of market volatility is invaluable for intelligent risk management. By dynamically adjusting stop-loss levels, sizing positions appropriately, and filtering trading opportunities based on current market choppiness or trend strength, traders can significantly enhance the robustness of their strategies. By understanding its calculation, thoughtfully calibrating its parameters, and integrating it strategically with directional indicators and price action analysis, you can leverage the ATR to make more informed trading decisions and manage your risk effectively in varying market conditions.

Enhance Your Trading

Get a high-performance Pine Script analysis tool for actionable market insights, designed for traders on the move.

This strategy runs in live mode on TradingView, helping you identify potential opportunities.

Get Pine Script Strategy