Pine Script ATR Calculator & Code Generator

Generate professional Average True Range (ATR) indicators for volatility analysis in TradingView. Our free Pine Script code generator creates ATR indicators with bands, stop-loss tools, and position sizing features. Perfect for risk management and breakout strategies.

Pine Script ATR Code Generator
Configure your ATR parameters below and get instant Pine Script code for your TradingView volatility indicator.

Note: This generated code is a basic indicator template. Always test scripts thoroughly before using them in a live trading environment. Read our disclaimer for more information.

What is ATR and How Does it Measure Volatility?

The Average True Range (ATR) is a volatility indicator developed by J. Welles Wilder Jr. that measures the average range of price movement over a specified period. Unlike other indicators that focus on price direction, ATR exclusively measures volatility - how much prices typically move, regardless of direction.

ATR is calculated using the True Range (TR), which captures the largest of three values: current high minus current low, absolute value of current high minus previous close, or absolute value of current low minus previous close. This ensures that gaps and limit moves are properly accounted for in volatility calculations.

The ATR then applies RMA (Relative Moving Average) smoothing to these True Range values: ATR = RMA(True Range, length). In Pine Script, this is simply ta.atr(length), which handles all the complex calculations automatically while providing accurate, non-repainting volatility measurements.

How to Calculate ATR in Pine Script

Method 1: Using the Built-in `ta.atr()` Function (Recommended)

//@version=5
indicator("Simple ATR", overlay=false)

length = input.int(14, title="ATR Length")

// Calculate ATR using built-in function
atr_value = ta.atr(length)

// Plot the result
plot(atr_value, title="ATR", color=color.orange, linewidth=2)

// Optional: Show ATR as percentage of price
atr_percent = (atr_value / close) * 100
plot(atr_percent, title="ATR %", color=color.blue, display=display.data_window)

Method 2: Manual ATR Calculation (Educational)

//@version=5
indicator("Manual ATR", overlay=false)

length = input.int(14, title="ATR Length")

// Calculate True Range manually
tr1 = high - low                    // Current high - low
tr2 = math.abs(high - close[1])     // Current high - previous close
tr3 = math.abs(low - close[1])      // Current low - previous close
true_range = math.max(tr1, math.max(tr2, tr3))

// Apply RMA smoothing (same as SMMA)
atr_manual = ta.rma(true_range, length)

// Compare with built-in function
atr_builtin = ta.atr(length)

plot(atr_manual, title="Manual ATR", color=color.red, linewidth=2)
plot(atr_builtin, title="Built-in ATR", color=color.blue, linewidth=1)

// They should be identical
plot(atr_manual - atr_builtin, title="Difference", color=color.yellow, display=display.data_window)

How to Use ATR in Trading Strategies

ATR's primary strength lies in risk management and position sizing. Since it measures volatility rather than direction, it helps traders adapt their strategies to current market conditions and maintain consistent risk across different instruments and time periods.

ATR-Based Stop Loss System

//@version=5
strategy("ATR Stop Loss System", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)

// Input parameters
atr_length = input.int(14, title="ATR Length")
atr_multiplier = input.float(2.0, title="ATR Multiplier for Stops", minval=0.5, maxval=5.0)
ema_length = input.int(20, title="EMA Length for Trend")

// Calculate indicators
atr_value = ta.atr(atr_length)
ema_trend = ta.ema(close, ema_length)

// Entry conditions
long_condition = ta.crossover(close, ema_trend)
short_condition = ta.crossunder(close, ema_trend)

// Calculate stop levels
long_stop = close - (atr_value * atr_multiplier)
short_stop = close + (atr_value * atr_multiplier)

// Execute trades
if long_condition
    strategy.entry("Long", strategy.long)
    strategy.exit("Long Exit", "Long", stop=long_stop)

if short_condition
    strategy.entry("Short", strategy.short)
    strategy.exit("Short Exit", "Short", stop=short_stop)

// Plot levels
plot(ema_trend, title="EMA Trend", color=color.blue, linewidth=2)
plot(strategy.position_size > 0 ? long_stop : na, title="Long Stop", color=color.red, style=plot.style_circles)
plot(strategy.position_size < 0 ? short_stop : na, title="Short Stop", color=color.red, style=plot.style_circles)

ATR Position Sizing Calculator

//@version=5
indicator("ATR Position Sizing", overlay=true)

// Input parameters
atr_length = input.int(14, title="ATR Length")
risk_per_trade = input.float(100, title="Risk Per Trade ($)", minval=1)
atr_multiplier = input.float(2.0, title="Stop Distance (ATR Multiplier)", minval=0.1)

// Calculate ATR and position size
atr_value = ta.atr(atr_length)
stop_distance = atr_value * atr_multiplier
position_size = risk_per_trade / stop_distance

// Create table to display information
var table info_table = table.new(position.top_right, 2, 6, bgcolor=color.white, border_width=1)

if barstate.islast
    table.cell(info_table, 0, 0, "ATR Value:", text_color=color.black, bgcolor=color.gray)
    table.cell(info_table, 1, 0, str.tostring(atr_value, "#.##"), text_color=color.black)
    
    table.cell(info_table, 0, 1, "Stop Distance:", text_color=color.black, bgcolor=color.gray)
    table.cell(info_table, 1, 1, str.tostring(stop_distance, "#.##"), text_color=color.black)
    
    table.cell(info_table, 0, 2, "Position Size:", text_color=color.black, bgcolor=color.gray)
    table.cell(info_table, 1, 2, str.tostring(position_size, "#"), text_color=color.black)
    
    table.cell(info_table, 0, 3, "Risk Amount:", text_color=color.black, bgcolor=color.gray)
    table.cell(info_table, 1, 3, "$" + str.tostring(risk_per_trade, "#"), text_color=color.black)
    
    table.cell(info_table, 0, 4, "ATR %:", text_color=color.black, bgcolor=color.gray)
    table.cell(info_table, 1, 4, str.tostring((atr_value/close)*100, "#.##") + "%", text_color=color.black)

// Plot ATR bands for reference
upper_band = close + stop_distance
lower_band = close - stop_distance
plot(upper_band, title="Upper ATR Band", color=color.red, linewidth=1)
plot(lower_band, title="Lower ATR Band", color=color.green, linewidth=1)

ATR Volatility Breakout System

//@version=5
indicator("ATR Volatility Breakout", overlay=true)

// Input parameters
atr_length = input.int(14, title="ATR Length")
volatility_threshold = input.float(1.5, title="High Volatility Threshold", minval=1.0, maxval=3.0)
lookback = input.int(20, title="ATR Average Lookback")

// Calculate ATR and its average
atr_current = ta.atr(atr_length)
atr_average = ta.sma(atr_current, lookback)

// Identify volatility conditions
high_volatility = atr_current > (atr_average * volatility_threshold)
low_volatility = atr_current < (atr_average / volatility_threshold)
normal_volatility = not high_volatility and not low_volatility

// Plot ATR levels
plot(atr_current, title="Current ATR", color=color.blue, linewidth=2)
plot(atr_average, title="Average ATR", color=color.gray, linewidth=1)
plot(atr_average * volatility_threshold, title="High Vol Threshold", color=color.red, linewidth=1, style=plot.style_line)

// Background coloring based on volatility
bgcolor(high_volatility ? color.new(color.red, 90) : 
        low_volatility ? color.new(color.green, 90) : 
        color.new(color.yellow, 95))

// Alerts for volatility changes
alertcondition(ta.crossover(atr_current, atr_average * volatility_threshold), 
               title="High Volatility Alert", message="ATR indicates high volatility period")
alertcondition(ta.crossunder(atr_current, atr_average / volatility_threshold), 
               title="Low Volatility Alert", message="ATR indicates low volatility period")

Frequently Asked Questions about ATR in Pine Script

Explore More Pine Script Calculators

RMA

RMA Calculator

Generate RMA indicators that ATR uses internally for smoothing True Range values.

SMMA

SMMA Calculator

Create SMMA indicators using the same smoothing method as ATR (identical to RMA).

EMA

EMA Calculator

Build EMA trend indicators to combine with ATR for complete trading systems.