Indicator TutorialPine Script 6

TradingView ATR: settings, units and risk rules

ATR measures smoothed price range, including gaps. It does not predict direction or the maximum size of the next move.

Add Average True Range from TradingView Indicators and start by checking Length 14 and RMA smoothing. ATR uses the price units of the chart: an ATR of 2.50 on a dollar-priced stock means $2.50 per share, not 2.50%. This guide explains the calculation and provides a copyable Pine v6 indicator with a hypothetical stock-sizing estimate.

Add ATR and read its units

  1. Open Indicators on a TradingView chart and search for Average True Range.
  2. Select the built-in indicator, which plots in a separate pane.
  3. Open Settings. Match the length, smoothing, chart timeframe, symbol and session before comparing it with another script.

TradingView documents RMA as the default smoothing, with SMA, EMA and WMA alternatives. The Pine function ta.atr(length) always uses RMA; choosing another average requires a separate calculation.

Price units, ticks and percentages

These are hypothetical conversions, not current market readings. Use the same timeframe and session when comparing observations.

InstrumentExample readingMeaning and constraint
Dollar-priced stockATR 2.50$2.50 per share. At a $100 close, ATR / Close × 100 is 2.5%.
EUR/USDATR 0.007575 pips if one pip is 0.0001. Dividing by minimum tick gives ticks, which may differ from pips.
Dollar-quoted cryptoATR 500 at a 50,000 close500 quote units per coin and 1% of price. A derivative contract may have a different payout rule.
FuturesATR 10 pointsConvert points with the contract point value before estimating cash exposure. Margin is a separate constraint.

ATR% removes the price scale but does not equalize liquidity, leverage or tail risk. For related studies, use the TradingView indicators directory. The Pine Script True Range reference explains the variable and function forms.

Why Traders Use This Indicator

  • Describe changes in recent price-range volatility on one instrument and timeframe.
  • Express a hypothetical entry-to-stop distance as a multiple of recent ATR.
  • Estimate nominal position size after converting that distance into cash per unit.
ParameterDefaultDescription
Length14 barsA shorter length puts more weight on the latest range; a longer length responds more slowly. Fourteen bars means fourteen chart observations, not necessarily fourteen days. No length is established here as best.
SmoothingRMAta.atr() uses Wilder RMA with alpha = 1 / length. The built-in chart indicator can use other averages; match this setting before comparing values.
Timeframe and sessionCurrent chart in this exampleChanging bar duration or session changes the high, low and preceding close used in True Range. Extended-hours data can change which bar precedes the cash-session open.
Distance multiplier2.0 in this exampleScales the hypothetical stop distance, not ATR itself. It is an illustrative input, not an optimized value. A larger distance reduces the nominal size for the same cash budget.

True Range, Wilder smoothing and nominal risk

1. True Range includes the preceding close

TR = max(High - Low, abs(High - Close[1]), abs(Low - Close[1])).

For a bar with high 105, low 103 and preceding close 100, the candidates are 2, 5 and 3, so TR is 5. This measures observed range, not the probability of a future move. In Pine's built-ins documentation, ta.tr(true) falls back to high - low when the preceding close is missing. The ta.tr variable does not provide that fallback.

2. RMA smooths the True Range series

After initialization, ATR = (previous ATR × (n - 1) + current TR) / n. RMA initializes from an SMA of the first n available observations. For n = 14, previous ATR = 2 and current TR = 5, the next ATR is 31 / 14 ≈ 2.2143.

For a manual comparison with ta.atr(n), use ta.rma(ta.tr(true), n). Omitting the true fallback can shift initialization. Both need sufficient history; do not treat an unavailable value as zero.

3. A distance is not an executed stop

Distance = multiplier × ATR. A hypothetical long stop is entry - distance; a short stop is entry + distance. Specify whether ATR is frozen at entry or recalculated. Recalculating can widen a stop as volatility increases. A trailing stop that must only tighten needs stored state and an explicit reset rule.

4. Stock-sizing arithmetic with stated assumptions

Assume a $50,000 account, a hypothetical 1% budget ($500), ATR of $5 and a 2× distance. Distance is $10; floor(500 / 10) = 50 whole shares. At an assumed $125 entry, the long stop reference is $115 and the position costs $6,250. These figures are invented for arithmetic, not a recommendation or live quote.

The $500 is the modeled price loss if all shares fill at that stop price. Gaps, slippage and fees can increase realized loss. TradingView explains why intended and actual fill prices differ. For linear contracts, the denominator also needs cash value per price point per contract and any account-currency conversion. Check lot increments, available capital and margin separately. Inverse contracts need their own payout formula. This is educational calculation, not investment advice.

Signal Interpretation

Rising ATR means the smoothed observed range is increasing; falling ATR means it is decreasing. Neither reading identifies trade direction, institutional activity or an upcoming reversal. A quiet period does not establish when a breakout will occur.

On an open bar, high and low can change, so ATR and the sizing estimate update. ATR% also changes with close. barstate.isconfirmed identifies the closing update for a chart-bar condition. Waiting for that update reduces intrabar changes but does not protect against revised source data or changed settings.

Combining with Other Indicators

A moving average can supply a separate direction rule while ATR supplies a distance. ATR envelopes and Keltner-style channels are not statistical confidence intervals. A channel touch does not establish a likely reversal.

For a custom rule, write down the entry, ATR snapshot, stop update policy, fees and fill assumptions separately. See ta.tr and missing preceding closes before replacing the built-in calculation.

Writing Pine Script Manually

Challenges of Manual Coding

Match ta.atr initialization by using ta.tr(true) in a manual RMA comparison.

Keep price points, tick counts, forex pips and cash per contract separate.

Distinguish a plotted reference level from an order, and a rolling level from a stateful trailing stop.

Pine Script 6
//@version=6
indicator("ATR units and nominal stock sizing", overlay=false)

length = input.int(14, "ATR length", minval=1)
multiplier = input.float(2.0, "Hypothetical distance multiplier", minval=0.1, step=0.1)
stockQuoteBudget = input.float(500.0, "Stock risk budget (quote currency)", minval=0.0)
showTrueRange = input.bool(false, "Show unsmoothed True Range")

trueRange = ta.tr(true)
atrValue = ta.atr(length)
manualAtr = ta.rma(trueRange, length)
atrPercent = close > 0 ? 100.0 * atrValue / close : na
stopDistance = multiplier * atrValue
// Whole shares only: one quote-currency unit per price point per share.
nominalShares = not na(stopDistance) and stopDistance > 0 ? math.floor(stockQuoteBudget / stopDistance) : na

plot(atrValue, "ATR (price units)", color=color.blue, linewidth=2)
plot(showTrueRange ? trueRange : na, "True Range", color=color.new(color.gray, 60))
plot(manualAtr - atrValue, "Manual RMA minus ATR", display=display.data_window)

var table summary = table.new(position.top_right, 2, 5, border_width=1)
if barstate.islast
    table.cell(summary, 0, 0, "Observation")
    table.cell(summary, 1, 0, barstate.isconfirmed ? "Closed bar" : "Open bar: changing")
    table.cell(summary, 0, 1, "ATR (price units)")
    table.cell(summary, 1, 1, str.tostring(atrValue, format.mintick))
    table.cell(summary, 0, 2, "ATR % of close")
    table.cell(summary, 1, 2, str.tostring(atrPercent, "#.##"))
    table.cell(summary, 0, 3, "Hypothetical distance")
    table.cell(summary, 1, 3, str.tostring(stopDistance, format.mintick))
    table.cell(summary, 0, 4, "Nominal stock shares")
    table.cell(summary, 1, 4, str.tostring(nominalShares, "#"))

Maintenance Note: The indicator plots ATR in a separate pane and shows a whole-share estimate in the stock quote currency. The budget is not an account connection. It does not place orders, create alerts, check buying power, account for fees or implement a trailing stop. The estimate updates during the open bar and is not suitable for futures, forex lots or crypto derivatives without unit-specific changes. Check the Data Window difference against zero after warm-up; this is a reproducible comparison method, not a reported market-data test.

Build with Pineify Visual Editor

Pineify lets you configure supported indicators and export Pine Script. Available settings and plan requirements vary by indicator. Compare the generated rules with the example before using its signals.

FeatureManual Pine ScriptPineify Visual Editor
ATR inputsDefine length and use ta.atr() or an explicit True Range average.The Visual Pine Script Editor has an ATR component with Length and MA Type inputs.
Custom risk arithmeticWrite the units, rounding and snapshot rules in Pine Script.Describe those rules to the Pine Script AI Coding Agent and review the generated calculation.
VerificationCompile, match closed-bar values and inspect execution assumptions.Review exported code and perform the same chart and execution checks.

Configure the existing ATR component through the Visual Pine Script Editor.

Use the Pine Script AI Coding Agent to draft custom calculations from explicit requirements.

Inspect generated source before using it on a TradingView chart.

Step-by-Step Tutorial

1

Open the Visual Pine Script Editor

Create an indicator project for a separate-pane volatility study.

2

Add Average True Range

Set Length to 14 and MA Type to RMA for the initial comparison.

3

Review the generated source

Inspect the inputs and plotted ATR output before copying the code.

4

Compare in TradingView

Compile in Pine Editor and match the built-in ATR on the same symbol, session, timeframe and closed bar.

Trading Strategies & Pro Tips

Entry-time ATR distance

Snapshot ATR when an entry rule occurs and use its multiple as a fixed reference distance. Define the entry price and tick rounding before estimating quantity.

Pro Tip: Keep a fixed initial distance separate from any later stop adjustment. Increasing the distance after entry increases modeled exposure at the same size.

Nominal stock-sizing study

Compare how changing the multiplier changes whole-share quantity for a fixed quote-currency budget. Quantity may be zero if one share exceeds that budget.

Pro Tip: An estimate can exceed buying power when ATR is small. Cap quantity using separate capital constraints and model execution costs.

Rolling bands versus trailing stops

Highest high over a lookback minus ATR × multiplier is a rolling reference. It can decline when an old high leaves the window or ATR rises.

Pro Tip: To require a long stop to only rise, retain the prior stop and take the maximum with the new candidate while the position is active; define when that state resets.

Common Mistakes to Avoid

  • Reading ATR as a directional signal, next-bar forecast or maximum possible loss.
  • Comparing raw readings across prices and timeframes without checking units.
  • Dividing by syminfo.mintick and calling the result pips rather than ticks.
  • Applying a stock share formula to contracts without point value or currency conversion.
  • Calling a rolling high-minus-ATR line a stop that can never move backward.
  • Claiming an optimal length or profitable multiplier without a defined test.

Frequently Asked Questions

Open Indicators, search Average True Range and select the built-in indicator. Check Length and Smoothing in Settings. It appears in a separate pane; this tutorial uses 14 bars and RMA.

There is no best setting established by this guide. A shorter length responds more strongly to new ranges; a longer length responds more slowly. Choose a testable rule and evaluate it on the intended symbol, timeframe and session with costs included.

Raw ATR uses chart price units. Convert to pips using the instrument-specific pip size, or to ticks using syminfo.mintick. ATR / Close × 100 gives a percentage when close is positive; it is a range-to-price measure, not a return standard deviation.

Yes. The current high and low can change during an open bar. ATR% also uses the changing close. Closed-bar values are stable for unchanged source data and settings, but data revisions, session choices and available history can affect recalculation.

No. An ATR multiple defines a distance. The estimated loss assumes a particular fill price and position size. Gaps, slippage, fees and contract conversion can produce a different realized loss. The example is an indicator and places no orders.

A raw rolling highest-high-minus-ATR calculation can move down. A long stop that only tightens needs stored state, a maximum with the prior stop, and an explicit reset on exit or a new position. This page does not implement that trailing-stop system.

The tutorial and source can be read and copied without buying Pineify. Pineify product access and TradingView plan limits are separate. Compiling the script does not establish that a trading rule is profitable.

Build an ATR rule you can inspect

  • Set ATR length and smoothing in the Visual Pine Script Editor
  • Describe custom units and stop-update rules to the Pine Script AI Coding Agent
  • Review the output and compare it with TradingView before using it

Disclaimer: Trading involves significant risk. The indicators, code, and strategies provided are for educational purposes only and do not constitute financial advice. Past performance is not indicative of future results.