Indicator · Pine Script v6 · On the chart

ATR Percentile Bands [TradingFinder] Dynamic Extremes

by theonetrade· code credited to TradingFinder

ATR Percentile Bands [TradingFinder] Dynamic Extremes calculates dynamic volatility bands around a selected baseline moving average (EMA, SMA, RMA, WMA, or HMA).

View on GitHub

GitHub stars34on the repository
Pine versionv6current
Lines of code193
Settings13inputs
LicenceMIT
Last update2 weeks ago8 Nov 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

193 lines of Pine Script v6 from assets/indicator/bit-exact/atr_percentile_bands_tradingfinder_dynamic_extremes_kEI4Kzlt.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

atr_percentile_bands_tradingfinder_dynamic_extremes_kEI4Kzlt.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradingFinder

//@version=6

indicator("ATR Percentile Bands [TradingFinder] Dynamic Extremes", "Dynamic Percentile", overlay = true, behind_chart = true, max_labels_count = 200)

movingAverageType = input.string("EMA", "Moving Average Type", options = ["EMA", "SMA", "RMA", "WMA", "HMA"], group = "Logical Settings")
movingAveragePeriod = input.int(50, "Moving Average Period", minval = 2, maxval = 500, group = "Logical Settings")
atrPeriod = input.int(14, "ATR Period", minval = 2, maxval = 500, group = "Logical Settings")
atrMultiplier = input.float(2.8, "ATR Multiplier", minval = 0.5, maxval = 10.0, step = 0.1, group = "Logical Settings")
smoothPeriod = input.int(5, "Smooth Period", minval = 1, maxval = 100, group = "Logical Settings")
signalGap = input.int(10, "Signal Gap", minval = 0, maxval = 500, group = "Logical Settings")

showMovingAverage = input.bool(true, "Moving Average", group = "Display Settings")
showSignals = input.bool(true, "Signals", group = "Display Settings")

showTable = input.bool(true, "Show Table", group = "Table Settings")
tableSizeInput = input.string(size.small, "Table Size", options = [size.tiny, size.small, size.normal, size.large], group = "Table Settings")
tablePositionInput = input.string(position.top_right, "Table Position", options = [position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right], group = "Table Settings")

alertEnabled = input.bool(true, "Alert", group = "Alert Settings")
messageFrequency = input.string("Once Per Bar Close", "Message Frequency", options = ["All", "Once Per Bar", "Once Per Bar Close"], group = "Alert Settings")



movingAverage(float source, int period, string averageType) =>
    averageType == "EMA" ? ta.ema(source, period) : averageType == "SMA" ? ta.sma(source, period) : averageType == "RMA" ? ta.rma(source, period) : averageType == "WMA" ? ta.wma(source, period) : ta.hma(source, period)


average = movingAverage(close, movingAveragePeriod, movingAverageType)
atr = ta.ema(ta.atr(atrPeriod), smoothPeriod)
atrDistance = atr * atrMultiplier


priceDeviation = math.abs(close - average)
percentileDistance = ta.percentile_linear_interpolation(priceDeviation, 200,  95)
rawOuterDistance = math.max(atrDistance, nz(percentileDistance, atrDistance))
outerDistance = ta.ema(rawOuterDistance, smoothPeriod)
innerDistance = outerDistance * 0.62
volatilityRank = ta.percentrank(atr, 200)

upperInnerBand = average + innerDistance
upperOuterBand = average + outerDistance
lowerInnerBand = average - innerDistance
lowerOuterBand = average - outerDistance


upperStop1 = upperInnerBand + (upperOuterBand - upperInnerBand) * 0.25
upperStop2 = upperInnerBand + (upperOuterBand - upperInnerBand) * 0.50
upperStop3 = upperInnerBand + (upperOuterBand - upperInnerBand) * 0.75
lowerStop1 = lowerInnerBand + (lowerOuterBand - lowerInnerBand) * 0.25
lowerStop2 = lowerInnerBand + (lowerOuterBand - lowerInnerBand) * 0.50
lowerStop3 = lowerInnerBand + (lowerOuterBand - lowerInnerBand) * 0.75


longSetup = low <= lowerInnerBand and close > lowerInnerBand and close > open
shortSetup = high >= upperInnerBand and close < upperInnerBand and close < open

var int pendingDirection = 0
var int confirmationCount = 0
var int lastPublishedSignal = na

longSignal = false
shortSignal = false
signalGapQualified = na(lastPublishedSignal) or bar_index - lastPublishedSignal >= signalGap

if barstate.isconfirmed
    if pendingDirection == 0
        if signalGapQualified and longSetup
            pendingDirection := 1
            confirmationCount := 1
        else if signalGapQualified and shortSetup
            pendingDirection := -1
            confirmationCount := 1
    else if pendingDirection == 1
        if shortSetup
            pendingDirection := -1
            confirmationCount := 1
        else if close > lowerInnerBand and close > open
            confirmationCount += 1
        else
            pendingDirection := 0
            confirmationCount := 0
    else if pendingDirection == -1
        if longSetup
            pendingDirection := 1
            confirmationCount := 1
        else if close < upperInnerBand and close < open
            confirmationCount += 1
        else
            pendingDirection := 0
            confirmationCount := 0

    if pendingDirection == 1 and confirmationCount >= 3
        longSignal := true
        lastPublishedSignal := bar_index
        pendingDirection := 0
        confirmationCount := 0
    else if pendingDirection == -1 and confirmationCount >= 3
        shortSignal := true
        lastPublishedSignal := bar_index
        pendingDirection := 0
        confirmationCount := 0


upperInnerPlot = plot(upperInnerBand, "Upper Band Inner", color = color.new(#E91E63, 82), linewidth = 1)
upperStop1Plot = plot(upperStop1, "Upper Band Gradient 1", color = color.new(#E91E63, 100), editable = false)
upperStop2Plot = plot(upperStop2, "Upper Band Center", color = color.new(#E91E63, 12), linewidth = 1)
upperStop3Plot = plot(upperStop3, "Upper Band Gradient 3", color = color.new(#E91E63, 100), editable = false)
upperOuterPlot = plot(upperOuterBand, "Upper Band Outer", color = color.new(#E91E63, 4), linewidth = 1)

lowerInnerPlot = plot(lowerInnerBand, "Lower Band Inner", color = color.new(#00C6A2, 82), linewidth = 1)
lowerStop1Plot = plot(lowerStop1, "Lower Band Gradient 1", color = color.new(#00C6A2, 100), editable = false)
lowerStop2Plot = plot(lowerStop2, "Lower Band Center", color = color.new(#00C6A2, 12), linewidth = 1)
lowerStop3Plot = plot(lowerStop3, "Lower Band Gradient 3", color = color.new(#00C6A2, 100), editable = false)
lowerOuterPlot = plot(lowerOuterBand, "Lower Band Outer", color = color.new(#00C6A2, 4), linewidth = 1)

plot(showMovingAverage ? average : na, "Moving Average", color = color.new(#A8B0BE, 55), linewidth = 1)

fill(upperInnerPlot, upperStop1Plot, color = color.new(#E91E63, 94), title = "Upper Band Layer 1")
fill(upperStop1Plot, upperStop2Plot, color = color.new(#E91E63, 86), title = "Upper Band Layer 2")
fill(upperStop2Plot, upperStop3Plot, color = color.new(#E91E63, 73), title = "Upper Band Layer 3")
fill(upperStop3Plot, upperOuterPlot, color = color.new(#E91E63, 53), title = "Upper Band Layer 4")

fill(lowerInnerPlot, lowerStop1Plot, color = color.new(#00C6A2, 94), title = "Lower Band Layer 1")
fill(lowerStop1Plot, lowerStop2Plot, color = color.new(#00C6A2, 86), title = "Lower Band Layer 2")
fill(lowerStop2Plot, lowerStop3Plot, color = color.new(#00C6A2, 73), title = "Lower Band Layer 3")
fill(lowerStop3Plot, lowerOuterPlot, color = color.new(#00C6A2, 53), title = "Lower Band Layer 4")

plotshape(showSignals and longSignal, "Long Signal", shape.triangleup, location.belowbar, #00c600, 0, "Long Signal", #00c600, true, size.small)
plotshape(showSignals and shortSignal, "Short Signal", shape.triangledown, location.abovebar, #e91e1e, 0, "Short Signal", #e91e1e, true, size.small)


marketState = longSignal ? "Buy Signal" : shortSignal ? "Sell Signal" : pendingDirection == 1 ? "Buy Setup" : pendingDirection == -1 ? "Sell Setup" : "No Signal"
marketStateColor = longSignal or pendingDirection == 1 ? #26D6AD : shortSignal or pendingDirection == -1 ? #F16B82 : #B5C3D8

extremeZone = close > upperOuterBand ? "Above Upper Band" : close >= upperInnerBand ? "Upper Band" : close < lowerOuterBand ? "Below Lower Band" : close <= lowerInnerBand ? "Lower Band" : close >= average ? "Above Average" : "Below Average"
extremeZoneColor = close >= upperInnerBand ? #F16B82 : close <= lowerInnerBand ? #26D6AD : #56CFE0

bullishTrend = close > average and average > average[1]
bearishTrend = close < average and average < average[1]
trendState = bullishTrend ? "Bullish" : bearishTrend ? "Bearish" : "Sideways"
trendStateColor = bullishTrend ? #26D6AD : bearishTrend ? #F16B82 : #FFBF69

bandsReady = not na(upperInnerBand) and not na(lowerInnerBand)
distanceToUpperPercent = bandsReady and close != 0 ? math.abs(upperInnerBand - close) / math.abs(close) * 100 : na
distanceToLowerPercent = bandsReady and close != 0 ? math.abs(close - lowerInnerBand) / math.abs(close) * 100 : na
upperBandIsNearest = bandsReady and distanceToUpperPercent <= distanceToLowerPercent
nearestBand = not bandsReady ? "Loading" : close >= upperInnerBand ? "At Upper Band" : close <= lowerInnerBand ? "At Lower Band" : upperBandIsNearest ? str.tostring(distanceToUpperPercent, "#.##") + "% to Upper" : str.tostring(distanceToLowerPercent, "#.##") + "% to Lower"
nearestBandColor = not bandsReady ? #B5C3D8 : close >= upperInnerBand ? #F16B82 : close <= lowerInnerBand ? #26D6AD : upperBandIsNearest ? #F16B82 : #26D6AD

volatilityState = na(volatilityRank) ? "Loading" : volatilityRank >= 80 ? "High" : volatilityRank <= 20 ? "Low" : "Normal"
volatilityStateColor = na(volatilityRank) ? #B5C3D8 : volatilityRank >= 80 ? #F16B82 : volatilityRank <= 20 ? #56CFE0 : #26D6AD

nextStep = longSignal ? "Buy Confirmed" : shortSignal ? "Sell Confirmed" : pendingDirection == 1 ? "Wait for Buy" : pendingDirection == -1 ? "Wait for Sell" : close >= upperInnerBand ? "Look for Sell" : close <= lowerInnerBand ? "Look for Buy" : "Wait"
nextStepColor = longSignal or pendingDirection == 1 or close <= lowerInnerBand ? #26D6AD : shortSignal or pendingDirection == -1 or close >= upperInnerBand ? #F16B82 : #B5C3D8

var table decisionTable = table.new(tablePositionInput, 6, 3, bgcolor = #0D1A3F, frame_color = #1C306D, frame_width = 1, border_color = #1C306D, border_width = 1)

if barstate.isfirst
    table.merge_cells(decisionTable, 0, 0, 5, 0)

if barstate.islast
    if showTable
        table.cell(decisionTable, 0, 0, "♦ TradingFinder ♦", bgcolor = #0D1A3F, text_color = #56CFE0, text_size = tableSizeInput)

        A = array.from("Signal", "Price Zone", "Trend", "Nearest Band", "Volatility", "Next Action")
        for column = 0 to 5
            table.cell(decisionTable, column, 1, array.get(A, column), bgcolor = #1C306D, text_color = color.white, text_size = tableSizeInput)

        table.cell(decisionTable, 0, 2, marketState, bgcolor = color.new(marketStateColor, 84), text_color = marketStateColor, text_size = tableSizeInput)
        table.cell(decisionTable, 1, 2, extremeZone, bgcolor = #0D1732, text_color = extremeZoneColor, text_size = tableSizeInput)
        table.cell(decisionTable, 2, 2, trendState, bgcolor = color.new(trendStateColor, 88), text_color = trendStateColor, text_size = tableSizeInput)
        table.cell(decisionTable, 3, 2, nearestBand, bgcolor = #0D1732, text_color = nearestBandColor, text_size = tableSizeInput, tooltip = "Shows which inner band is closest and the remaining distance as a percentage of price.")
        table.cell(decisionTable, 4, 2, volatilityState, bgcolor = color.new(volatilityStateColor, 90), text_color = volatilityStateColor, text_size = tableSizeInput)
        table.cell(decisionTable, 5, 2, nextStep, bgcolor = color.new(nextStepColor, 86), text_color = nextStepColor, text_size = tableSizeInput)
    else
        table.clear(decisionTable, 0, 0, 5, 2)


longAlert = alertEnabled and longSignal
shortAlert = alertEnabled and shortSignal

alertcondition(longAlert, " Long Signal", " Long Signal on {{ticker}} after three consecutive confirmations.")
alertcondition(shortAlert, " Short Signal", " Short Signal on {{ticker}} after three consecutive confirmations.")
alertcondition(longAlert or shortAlert, " Any Signal", " confirmed signal on {{ticker}}.")

alertFrequency = messageFrequency == "All" ? alert.freq_all : messageFrequency == "Once Per Bar" ? alert.freq_once_per_bar : alert.freq_once_per_bar_close
if longAlert
    alert("LONG SIGNAL " + syminfo.ticker + " 3 consecutive confirmations", alertFrequency)
if shortAlert
    alert("SHORT SIGNAL " + syminfo.ticker + " 3 consecutive confirmations", alertFrequency)

Overview

The band width combines smoothed Average True Range with a percentile calculation of price deviation over a historical lookback window. It plots inner and outer volatility bands directly on the price chart and flags potential long and short setup signals when prices test the inner dynamic threshold levels. Inputs allow adjusting average types, periods, multipliers, and toggling an on-screen table showing volatility rank.

Details

Published by

theonetrade on GitHub

Code credit

TradingFinder, as written in the script's header

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

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

algorithmic-tradingbacktestingbitcoinccxtcrypto-tradingllm-agentoffline-backtestingopen-source-tradingpine-scriptpine-to-pythonpinescriptpynecorepythonquantquantitative-financestrategy-backtestingtechnical-analysistrading-indicatorstrading-strategiestradingview

Settings

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

SettingTypeDefaultVariable
Moving Average TypestringEMAmovingAverageType
Moving Average Periodint50movingAveragePeriod
ATR Periodint14atrPeriod
ATR Multiplierfloat2.8atrMultiplier
Smooth Periodint5smoothPeriod
Signal Gapint10signalGap
Moving AveragebooltrueshowMovingAverage
SignalsbooltrueshowSignals
Show TablebooltrueshowTable
Table Sizestringsize.smalltableSizeInput
Table Positionstringposition.top_righttablePositionInput
AlertbooltruealertEnabled
Show all 13 settings
SettingTypeDefaultVariable
Message FrequencystringOnce Per Bar ClosemessageFrequency
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

20 stars

This indicator calculates a base moving average (EMA, SMA, WMA, or HMA) and projects multiple symmetrical envelope bands around it directly on the price chart. Users can adjust the length, source, moving average type, and initial envelope multiplier. Additiona

Indicator v5 Moving averagesVolatility & bands
Updated 1 year ago · None stated GitHub repository of Multiple Moving Average Envelope

Bottom Level Finder

by chris-c-thomas
13 stars

Bottom Level Finder is a support identification indicator designed to locate correction and re-entry zones directly on the price chart. It calculates horizon-adaptive Fibonacci retracements, drawdown percentage levels, moving averages, and integrated VIX volat

Indicator v6 Support & resistanceMoving averages
Updated 7 months ago · MIT GitHub repository of Bottom Level Finder
9 stars

Calculates volume-weighted average price anchored to automatically detected swing pivots, period starts, or a custom manual timestamp. It plots volume-weighted standard deviation bands with configurable multiples and measures price distance from VWAP in standa

Indicator v6 Moving averagesVolatility & bands Repaints
Updated 4 weeks ago · MIT GitHub repository of Anchored VWAP [WavesUnchained]
7 stars

This indicator plots standard Bollinger Bands alongside scaled Average True Range (ATR) bands directly on the price chart. It is designed to assist traders in identifying price consolidation zones, potential breakout levels, dynamic stops, and take-profit targ

Indicator v5 Moving averagesVolatility & bands
Updated 1 year ago · MPL-2.0 GitHub repository of Bollinger and ATR Bands

ATR Based Stoploss

by rubystar0512
5 stars

ATR Based Stoploss is an overlay indicator that calculates dynamic stop loss and take profit bands around a central simple moving average. It uses standard Average True Range or an ATR Surge Average derived from volatility spikes to offset profit and loss boun

Indicator v5 Volatility & bandsMoving averages
Updated 2 years ago · None stated GitHub repository of ATR Based Stoploss

This overlay indicator plots a Supertrend from an ATR length and factor, four exponential moving averages, and a selectable VWAP or TWAP taken from a chosen timeframe on the price chart. It also shows MACD and stochastic with adjustable lengths, smoothing, ver

Indicator v5 Oscillators & momentumMoving averages
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup: Vijay Thakare Option Buying Scalping Setup

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