Indicator · Pine Script v6 · On the chart

Volatility Regime Lab

by jayadevrana

Volatility Regime Lab ranks the current ATR against its own recent history and labels the market Quiet, Normal, or Wild.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code115
Settings6inputs
LicenceMPL-2.0
Last update4 days ago26 Oct 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

115 lines of Pine Script v6 from scripts/volatility-regimes.pine.txt, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

volatility-regimes.pine.txt
//@version=6
indicator("Volatility Regime Lab", overlay = true)

// 1. Settings
atrLen  = input.int(14, "ATR length", minval = 2)
rankLen = input.int(200, "Bars used to rank today's volatility", minval = 50)
fwd     = input.int(24, "Forward return measured over N bars", minval = 1)
loCut   = input.int(33, "Quiet below this percentile",
  minval = 5, maxval = 45)
hiCut   = input.int(66, "Wild above this percentile",
  minval = 55, maxval = 95)
shade   = input.bool(true, "Shade the background by regime")

// 2. How volatile is now, compared with its own recent history?
// An ATR of 500 dollars means nothing alone. Its percentile rank means a lot.
atrNow = ta.atr(atrLen)
rank   = ta.percentrank(atrNow, rankLen)

// 3. Three states. This is the entire regime model, and that is the point:
// the value is in conditioning on it, not in making it complicated.
regime = rank < loCut ? 0 : rank < hiCut ? 1 : 2
regCol = regime == 0 ? color.teal : regime == 1 ? color.gray : color.red
bgcolor(shade ? color.new(regCol, 88) : na, title = "Regime")

// 4. The forward return of the bar that is now N bars old, attributed to the
// regime that bar was in. Measured on closed data only, so nothing repaints.
past  = close[fwd]
ret   = past > 0 ? (close - past) / past * 100 : na
wasIn = regime[fwd]

// 5. One accumulator per regime: count, sum, sum of squares, best and worst
var array<float> cnt  = array.new_float(3, 0)
var array<float> sum  = array.new_float(3, 0)
var array<float> sumsq = array.new_float(3, 0)
var array<float> best = array.new_float(3, -1e9)
var array<float> wrst = array.new_float(3, 1e9)
var array<float> bars = array.new_float(3, 0)
if not na(regime)
    array.set(bars, regime, array.get(bars, regime) + 1)
if not na(ret) and not na(wasIn) and bar_index > rankLen + fwd
    array.set(cnt,  wasIn, array.get(cnt,  wasIn) + 1)
    array.set(sum,  wasIn, array.get(sum,  wasIn) + ret)
    array.set(sumsq, wasIn, array.get(sumsq, wasIn) + ret * ret)
    array.set(best, wasIn, math.max(array.get(best, wasIn), ret))
    array.set(wrst, wasIn, math.min(array.get(wrst, wasIn), ret))

// 6. The table, and a bar drawn out of block characters
var table t = table.new(position.bottom_left, 6, 5, border_width = 1)
head(c, s) =>
    table.cell(t, c, 0, s, text_color = color.white, text_size = size.normal,
      bgcolor = color.new(color.blue, 20))
put(c, r, s, bg) =>
    table.cell(t, c, r, s, text_color = color.white, text_size = size.normal,
      bgcolor = bg)
bar(v, pk) =>
    w = int(math.round(14.0 * math.abs(v) / math.max(pk, 0.0001)))
    s = ""
    // a Pine for-loop with a start above its end counts DOWNWARDS,
    // so an empty bin would print two blocks instead of none
    if w > 0
        for i = 1 to w
            s += "█"
    s

// 7. Report, on the last bar
if barstate.islast
    total = array.sum(bars)
    names = array.from("QUIET", "NORMAL", "WILD")
    cols  = array.from(color.teal, color.gray, color.red)
    // the biggest average move, so the bars can share a scale
    pk = 0.0
    for i = 0 to 2
        n = array.get(cnt, i)
        if n > 0
            pk := math.max(pk, math.abs(array.get(sum, i) / n))
    head(0, "REGIME")
    head(1, "% of time")
    head(2, "avg " + str.tostring(fwd) + "-bar move")
    head(3, "")
    head(4, "typical swing")
    head(5, "worst / best")
    for i = 0 to 2
        n    = array.get(cnt, i)
        avg  = n > 0 ? array.get(sum, i) / n : 0.0
        varc = n > 0 ? array.get(sumsq, i) / n - avg * avg : 0.0
        sd   = math.sqrt(math.max(varc, 0))
        share = 100.0 * array.get(bars, i) / math.max(total, 1)
        live = regime == i
        put(0, i + 1, array.get(names, i) + (live ? "  <- now" : ""),
          color.new(array.get(cols, i), live ? 10 : 45))
        put(1, i + 1, str.tostring(share, "#.0") + "%", color.new(color.gray, 25))
        put(2, i + 1, str.tostring(avg, "#.00") + "%",
          avg >= 0 ? color.new(color.teal, 25) : color.new(color.red, 25))
        table.cell(t, 3, i + 1, bar(avg, pk),
          text_color = avg >= 0 ? color.teal : color.red,
          bgcolor = color.new(color.black, 0), text_halign = text.align_left,
          text_size = size.normal)
        put(4, i + 1, "+/- " + str.tostring(sd, "#.00") + "%",
          color.new(color.gray, 25))
        put(5, i + 1, str.tostring(array.get(wrst, i), "#.0") + "% / " +
          str.tostring(array.get(best, i), "#.0") + "%", color.new(color.gray, 25))
    put(0, 4, "ATR percentile now", color.new(color.blue, 20))
    put(1, 4, str.tostring(rank, "#.0"), color.new(regCol, 20))
    put(2, 4, "same ATR, in dollars", color.new(color.gray, 25))
    put(3, 4, str.tostring(atrNow, format.mintick), color.new(color.gray, 25))
    put(4, 4, "samples per regime", color.new(color.gray, 25))
    put(5, 4, str.tostring(array.get(cnt, 0), "#") + " / " +
      str.tostring(array.get(cnt, 1), "#") + " / " +
      str.tostring(array.get(cnt, 2), "#"), color.new(color.gray, 25))

// 8. Alerts on a regime change, which is usually what you actually want to know
alertcondition(regime != regime[1] and regime == 2, "Entered wild volatility",
  "{{ticker}} volatility regime is now WILD")
alertcondition(regime != regime[1] and regime == 0, "Entered quiet volatility",
  "{{ticker}} volatility regime is now QUIET")

Overview

Volatility Regime Lab shades the price-chart background by that regime. On the last bar it shows a table of how often each regime occurred, the average N-bar price change that followed closed bars in that regime, a typical-swing measure, and the worst and best of those moves. ATR length, ranking window, forward horizon, and the two percentile cuts are inputs. It is an overlay study, not a trade signal, and it does not place entries or exits.

Details

Published by

jayadevrana on GitHub

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-tradingbacktestingema-crossoverpine-scriptpine-script-v6pinescriptrsitechnical-analysistrading-automationtrading-indicators

Settings

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

SettingTypeDefaultVariable
ATR lengthint14atrLen
Bars used to rank today's volatilityint200rankLen
Forward return measured over N barsint24fwd
Quiet below this percentileint33loCut
Wild above this percentileint66hiCut
Shade the background by regimebooltrueshade
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

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
330 stars

This multi-symbol indicator evaluates a combined trading condition across up to 40 user-defined symbols. It processes MACD bullish crossovers, RSI thresholds, Bollinger Band boundaries, and DMI/ADX trend filters using security calls. When buy or sell criteria

Indicator v5 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of Multi MACD + BB + RSI [Alorse]

Pricing Table

by namuan
318 stars

This indicator calculates theoretical options contract values and in-the-money probabilities using historical realized volatility across multiple standard deviations. It displays these metrics in a table overlay directly on the price chart. Users can adjust th

Indicator v4 Volatility & bandsScreeners & dashboards
Updated 2 months ago · MIT GitHub repository of Pricing Table
228 stars

This indicator maps market structure and supply and demand zones on the price chart. It marks validated and optional unvalidated swing highs and lows using a pivot length and extra confirmation bars. Consolidation and impulse moves are measured against ATR to

Indicator v6 SMC / ICT / price actionSupport & resistance Repaints
Updated 3 months ago · None stated GitHub repository of Market Structure + Supply/Demand
200 stars

Storm Gauge calculates annualized realized volatility and compares it against a historical percentile lookback window to classify market volatility regimes into calm, normal, or storm conditions. Based on a target volatility input, it calculates dynamic positi

Indicator v5 Volatility & bandsScreeners & dashboards
Updated 3 months ago · MIT GitHub repository of Storm Gauge — Vol Regime + Position Size

8zz反指標v2

by hansai-art
121 stars

The 8zz Contrarian Indicator plots reverse sentiment trading signals directly on the price chart based on tracked retail post activity. It generates bullish signals during retail panic and bearish signals during market euphoria. The indicator features adjustab

Indicator v6 Moving averagesOscillators & momentum
Updated 3 months ago · None stated GitHub repository of 8zz反指標v2

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