Indicator · Pine Script v5 · On the chart

Daily ATR Levels

by sbtnc

Plots horizontal levels above and below the daily open based on the Average True Range, drawn on the price chart.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code356
Settings6inputs
LicenceMPL-2.0
Last update9 months ago28 Jan 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

356 lines of Pine Script v5 from ATR Daily Levels.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

ATR Daily Levels.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sbtnc
// Created: 2020-09-06
// Last modified: 2023-11-19
// Version 6.0

// @version=5
indicator("Daily ATR Levels", "D ATR", true)


//--------------------------------------------------------------------
//                             Constants
//--------------------------------------------------------------------

var DEFAULT_OFFSET_START    = 1
var DEFAULT_LINE_LENGTH     = 8
var DEFAULT_LINE_STYLE      = line.style_dotted
var DEFAULT_LINE_WIDTH      = 2
var DEFAULT_LABEL_COLOR     = color(na)
var DEFAULT_LABEL_STYLE     = label.style_label_left
var DEFAULT_NOTIF_POSITION  = position.bottom_right
var DEFAULT_NOTIF_TEXTCOLOR = chart.fg_color
var DEFAULT_NOTIF_BGCOLOR   = color.new(color.gray, 90)


//--------------------------------------------------------------------
//                               Inputs
//--------------------------------------------------------------------

// Groups

var g1                  = "ATR"
var g2                  = "Style"
var g3                  = "Preferences"


// Tooltips

var t_value             = "Calculate the levels using yesterday's ATR or today's ATR."
var t_overflowColor     = "Coloring after the price reached or exceeded the ATR boundary."
var t_showStartOffset   = "Draw levels on the right side of the price only.\n\n" +
                             "When disabled, draw levels from the start of the day."
var t_showNext          = "Plot the next day's ATR levels when the market is closed.\n\n" +
                             "Use this option if you like to plan your trades ahead of the next day or prepare on the weekend for Monday."


// Inputs

var i_period            = input.int     (20,                        "Length", 1,                                                group=g1)
var i_value             = input.string  ("Yesterday",               "Reference", ["Today", "Yesterday"],                        group=g1)
var i_color             = input         (color.gray,                "Color",                                                    group=g2)
var i_overflowColor     = input         (color.new(#50535e, 50),    "Overflow Color",                       t_overflowColor,    group=g2)
var i_showStartOffset   = input         (true,                      "Show Start Offset",                    t_showStartOffset,  group=g3)
var i_showNextDay       = input         (false,                     "Show Next ATR Levels",                 t_showNext,         group=g3)


//--------------------------------------------------------------------
//                              Functions 
//--------------------------------------------------------------------

// @function Return the number of decimals from a given number
// @return int
f_countDecimals(float _n) =>
    _str    = str.tostring(_n)
    _count  = 0

    // Number is a decimal
    if str.contains(_str, ".")
        _split = str.split(_str, ".")
        _count := str.length(array.get(_split, 1))

    _count


// @function Return a number rounded to the precision of the symbol's mintick (different than `math.round_to_mintick`)
// @return float
f_roundToMinPrecision(float _n) =>
    var minPrecision = f_countDecimals(syminfo.mintick)
    math.round(_n, minPrecision)


// @function Check if the market is closed
// @return bool
f_isMarketClosed() => 
    barstate.islast and barstate.islastconfirmedhistory


// @function Check if the indicator should display the next session ATR
// return bool
f_canShowNextATR() =>
    i_showNextDay and f_isMarketClosed()


// @function Return the ATR value used as a reference
// @return float
f_getRefAtr(float _current, float _previous) =>
    switch i_value
        "Today"     => _current
        "Yesterday" => _previous


// @function Return the "true" high price (considering gaps volatility)
// @return float
f_getTopPrice(_prevClose, float _high) =>
    math.max(_prevClose, _high)


// @function Return the "true" low price (considering gaps volatility)
// @return float
f_getBottomPrice(float _prevClose, float _low) =>
    math.min(_prevClose, _low)


// @function Calculate the upside ATR level
// @return float
f_calculateAtrHigh(float _bottom, float _atr) =>
    _bottom + _atr


// @function Calculate the downside ATR level
// @return float
f_calculateAtrLow(float _top, float _atr) =>
    _top - _atr


// @function Draw a level's line
// @return void
f_drawLine(int _x1, int _x2, float _y, color _c) =>
    var _l = line.new(na, na, na, na, style=DEFAULT_LINE_STYLE, width=DEFAULT_LINE_WIDTH)

    if barstate.islast
        line.set_xy1(_l, _x1, _y)
        line.set_xy2(_l, _x2, _y)
        line.set_color(_l, _c)


// @function Draw a level's label and tooltips
// @return void
f_drawLabel(int _x, float _y, string _t, color _textColor, string _tooltip) =>
    var _l = label.new(na, na, style=DEFAULT_LABEL_STYLE, color=DEFAULT_LABEL_COLOR)

    if barstate.islast
        label.set_xy(_l, _x, _y)
        label.set_text(_l, _t)
        label.set_textcolor(_l, _textColor)
        label.set_tooltip(_l, _tooltip)


// @function Draw the table showing the indicator notifications
// return int
f_drawNotificationTable(array<bool> _conditions, array<string> _texts, array<string> _tooltips) =>
    // For the implementation purpose, throw an error when missing an element
    
    _conditionsSize = array.size(_conditions)
    _textsSize      = array.size(_texts)
    _tooltipsSize   = array.size(_tooltips)

    if _conditionsSize != _textsSize or _conditionsSize != _tooltipsSize
        runtime.error("Notification error: missing element in arrays.")

    // Create the notification table
    
    var table _t    = na
    var _columns    = _conditionsSize
    var _rows       = 1

    if barstate.isfirst
        _t := table.new(DEFAULT_NOTIF_POSITION, _columns, _rows)

    if barstate.islast
        // Clear previous notifications
        table.clear(_t, 0, 0, _columns - 1, _rows - 1)

        // Count the number of active notifications
        _active = 0
        
        for [index, _condition] in _conditions
            if _condition
                _text       = array.get(_texts, index)
                _tooltip    = array.get(_tooltips, index)

                table.cell(_t, _active, 0, _text, text_color=DEFAULT_NOTIF_TEXTCOLOR, bgcolor=DEFAULT_NOTIF_BGCOLOR, tooltip=_tooltip)

                _active += 1 


// @function Returns the indicator strings
// @return [string, string, string]
f_getStrings(float _upperLevel, float _lowerlevel, float _atr) =>
    [
     str.tostring(f_roundToMinPrecision(_upperLevel)),
     str.tostring(f_roundToMinPrecision(_lowerlevel)),
     str.tostring(f_roundToMinPrecision(_atr))
     ]


//--------------------------------------------------------------------
//                        Variables declarations
//--------------------------------------------------------------------

var float dayHigh       = na
var float dayLow        = na
var float prevDayClose  = na
var int dayBarIndex     = na
var float bottomPrice   = na
var float topPrice      = na

[dayAtr, prevDayAtr] = request.security(
     syminfo.tickerid,
     'D',
     [ta.atr(i_period), ta.atr(i_period)[1]],
     lookahead = barmerge.lookahead_on)

// For avoiding unexpected behaviors, don't display the indicator when requesting daily data on higher time frames
canDisplay = timeframe.in_seconds() <= timeframe.in_seconds("D")

atr = f_getRefAtr(dayAtr, prevDayAtr)


//--------------------------------------------------------------------
//                                Logic
//--------------------------------------------------------------------

// *
// * For the historical values
// *

// Track the day's high and low on runtime instead of fetching them from a security call
// This aims to avoid the `future leak` from the "jump" when using the bar replay function


// 1/ Init on the first bar of the chart
// 2/ Reset on new day change (condition should cover the extended sessions bars)

if timeframe.change("D") or barstate.isfirst
    dayHigh         := high
    dayLow          := low
    prevDayClose    := close[1]
    dayBarIndex     := bar_index


// Track the new higher high and lower low

dayHigh     := math.max(high, dayHigh)
dayLow      := math.min(low, dayLow)


// Get the top and bottom anchor prices for calculating the levels (gap minded)

bottomPrice := f_getBottomPrice (prevDayClose, dayLow)
topPrice    := f_getTopPrice    (prevDayClose, dayHigh)


// Compute the ATR levels prices

atrHigh     = f_calculateAtrHigh(bottomPrice, atr)
atrLow      = f_calculateAtrLow (topPrice, atr)


// Handle the condiditional coloring

c_atrHigh   = dayHigh >= atrHigh    ? i_overflowColor : i_color
c_atrLow    = dayLow <= atrLow      ? i_overflowColor : i_color


// *
// * For the levels
// *

// Normally showing the current/last ATR levels

upperLevel      = atrHigh
lowerLevel      = atrLow

c_upperLevel    = c_atrHigh
c_lowerLevel    = c_atrLow


// Except when showing the next ATR levels
// In this case, we override values

if f_canShowNextATR()
    atr             := dayAtr
    upperLevel      := f_calculateAtrHigh(close, atr)
    lowerLevel      := f_calculateAtrLow (close, atr)

    c_upperLevel    := i_color
    c_lowerLevel    := i_color


//--------------------------------------------------------------------
//                          Plotting & styling
//--------------------------------------------------------------------

// Draw the upper and lower levels (lines and labels)

if canDisplay

    //  Get all the strings

    [_atrHighStr, _atrLowStr, _atrStr] = f_getStrings(upperLevel, lowerLevel, atr)


    // Composes labels and tooltips' texts

    upperLabelText      = str.format("{0} ({1})", _atrHighStr, _atrStr)
    lowerLabelText      = _atrLowStr

    upperLabelTooltip   = str.format("{0} (D ATR: {1})", _atrHighStr, _atrStr)
    lowerLabelTooltip   = str.format("{0} (D ATR: {1})", _atrLowStr, _atrStr)


    // Draw lines and labels

    _offset     = bar_index + DEFAULT_OFFSET_START
    _start      = i_showStartOffset ? _offset : dayBarIndex
    _end        = _offset + DEFAULT_LINE_LENGTH

    f_drawLine  (_start, _end, upperLevel, c_upperLevel)
    f_drawLine  (_start, _end, lowerLevel,  c_lowerLevel)

    f_drawLabel (_end, upperLevel, upperLabelText, c_upperLevel,   upperLabelTooltip)
    f_drawLabel (_end, lowerLevel,  lowerLabelText, c_lowerLevel,   lowerLabelTooltip)


// Plot the levels' labels on the price scale
// (as well as providing generic alert conditions)

plot(canDisplay ? upperLevel    : na,   "Upper Level",  c_upperLevel,       editable=false, show_last=1,    display=display.price_scale)
plot(canDisplay ? lowerLevel    : na,   "Lower Level",  c_lowerLevel,       editable=false, show_last=1,    display=display.price_scale)


// Plot all historical values on the status line and data window
// (as well as providing generic alert conditions)

plot(canDisplay ? atrHigh       : na,   "ATR High",     c_atrHigh,          editable=false,                 display=display.status_line + display.data_window)
plot(canDisplay ? atrLow        : na,   "ATR Low",      c_atrLow,           editable=false,                 display=display.status_line + display.data_window)
plot(canDisplay ? atr           : na,   "ATR",          i_overflowColor,    editable=false,                 display=display.status_line + display.data_window)


// Draw the notification table

notifications           = array.from(
                             f_canShowNextATR() and canDisplay,
                             not canDisplay
                             )
notificationMessages    = array.from(
                             "»",
                             "▽"
                             )
notificationsTooltips   = array.from(
                             "The D ATR is currently displaying how the levels would look at the next session's open.",
                             "The D ATR is currently not displayed. Please select a higher timeframe on the indicator's settings."
                             )

f_drawNotificationTable(notifications, notificationMessages, notificationsTooltips)

Overview

The ATR length defaults to 20, and the reference can be yesterday's ATR or today's. Levels change colour once price reaches or passes them. Options start the lines at the current bar or the day's start, and show the next day's levels when the market is closed.

Details

Published by

sbtnc on GitHub

Draws

On the price chart

Markets

Any symbol

Timeframes

M15-H1

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

pine-scriptpinescriptpinescript-indicators

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Lengthint20i_period
ReferencestringYesterdayi_value
Colorcolorcolor.grayi_color
Overflow Colorcolorcolor.new(#50535e, 50)i_overflowColor
Show Start Offsetbooltruei_showStartOffset
Show Next ATR Levelsboolfalsei_showNextDay
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

ICT Liquidity Void Fill

by ArunKBhaskar
575 stars

This overlay indicator marks ICT liquidity void fills on the price chart and can show long and short signals. It places a Fibonacci level inside a displacement candle, defaulting to the midpoint, and draws lines in a chosen style. Optional filters limit the fi

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Liquidity Void Fill

[RS]Donchian Fans

by ricardosantos79
261 stars

This indicator plots Donchian Channel boundary lines along with dynamic fan projections directly on the price chart. It calculates the highest high, lowest low, and median price over a customizable lookback period. Whenever price establishes a new channel high

Indicator v4 Support & resistanceTrend
Updated 4 years ago · None stated GitHub repository of [RS]Donchian Fans

Lux Trailing

by dearvn
257 stars

Plots kernel-smoothed price zones on the price chart using a Rational Quadratic kernel from an imported library. It builds an inner and an outer high-low zone from 15-minute highs and lows, plus a smoothed close and a midline, and marks bullish or bearish bars

Indicator v5 Support & resistanceVolatility & bands Repaints
Updated 7 weeks ago · None stated GitHub repository of Lux Trailing

Dynamic Linear Regression

by TradersPost
228 stars

Dynamic Linear Regression calculates and plots linear regression trendlines and standard deviation channels directly on the price chart over a user-selected time period. Traders can configure static channels locked at the end time, dynamic channels that contin

Indicator v6 TrendSupport & resistance
Updated 3 months ago · None stated GitHub repository of Dynamic Linear Regression

Candlestick Patterns

by harryguiacorn
220 stars

This indicator plots optional candlestick pattern signals on the price chart. It detects engulfing bars, inside bars, HOLP and LOHP, kicker patterns, body-mass extremes, higher highs and lower lows, ATR warnings, and four-bar fractals. Optional pivot marks use

Indicator v5 Candlestick patternsVolatility & bands
Updated 1 year ago · None stated GitHub repository of Candlestick Patterns

More Volatility & bands scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers