Indicator · Pine Script v5 · Own pane

Historical Volatility Percentile and Rank

by Teerth1· code credited to balipour

Computes historical volatility from log returns and shows either its percentile or its rank over a long window, selected by a mode input.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code140
Settings6inputs
LicenceNone statedfile: MPL-2.0
Last update6 months ago10 Apr 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

140 lines of Pine Script v5 from deal-api/src/main/resources/PineScript/Historical Volatility Percentile & Rank.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Historical Volatility Percentile & Rank.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © balipour
//@version=5

// Function to find the minimum value in an array over a lookback period
f_min(x, n) =>
    min = nz(x[1]), c = 0.0
    while n > c
        if min > x[c]
            min := x[c]
        c := c + 1
    min

// Function to find the maximum value in an array over a lookback period
f_max(x, n) =>
    max = nz(x[1]), c = 0.0
    while n > c
        if max < x[c]
            max := x[c]
        c := c + 1
    max

// Function to calculate the percentile of a value in an array over a lookback period
f_percentile(x, n) =>
    p = 0, c = 0
    while n > c
        if x > x[c + 1]
            p := p + 1
        c := c + 1
    per = 100 * (p / n)

// Function to calculate the rank of a value in an array over a lookback period
f_rank(x, n) =>
    l = f_min(x, n), h = f_max(x, n)
    rank = 100 * ((x - l) / (h - l))

// Function to calculate the moving average
f_m(x, n) =>
    m = 0.0
    m := ((n - 1) / n) * nz(m[1]) + x / n

// Function to calculate the standard deviation
f_sd(x, n) =>
    s = f_m(x * x, n)
    m = f_m(x, n)
    sd = math.sqrt(s - m * m)

// Function to calculate the normalized moving average
f_nm(x, n) =>
    nm = 0.0
    nm := nz(nm[1]) + (x - nz(x[n])) / n

// Function to calculate the normalized standard deviation
f_nsd(x, n) =>
    s = f_nm(x * x, n)
    m = f_nm(x, n)
    sd = math.sqrt(s - m * m)

// Function to determine color based on percentile value
f_color0(x) =>
    c = color.rgb(26, 112, 178)
    if x >= 70 and x < 80
        c := color.rgb(255, 230, 0)
    else if x >= 80 and x < 90
        c := color.rgb(210, 126, 0)
    else if x >= 90
        c := color.rgb(255, 0, 0)
    c

// Function to determine color based on rank value
f_color1(x) =>
    c = #545454
    if x >= 70 and x < 80
        c := color.rgb(255, 230, 0)
    else if x >= 80 and x < 90
        c := color.rgb(210, 126, 0)
    else if x >= 90
        c := color.rgb(255, 0, 0)
    c

// Indicator settings and input options
indicator("💤 HV(P&R)©️ [TEP™️]")

op0 = input(true, "Closes Only?")
x0 = op0 ? close : open < close ? high : close < open ? low : close
op1 = input.string("HVP©️", title="Mode? ", options=["HVP©️", "HVR©️"]) == "HVP©️"

n0 = input.int(30, title="Lookback for Volatility: ")
n1 = input.int(365, title="Lookback for Percentile/Rank: ")
n2 = input.int(30, "Lookback for MA: ")

op2 = input(true, "Enable Background")

// Calculate log returns
r = math.log(x0 / nz(x0[1]))

// Color settings for background
c0 = color.new(#38b624, 70)
c1 = color.new(#32ab20, 60)
c2 = color.new(#31ff12, 50)

// Calculate historical volatility
hv = f_sd(r, n0)

// Calculate historical volatility percentile and rank
hvp = f_percentile(hv, n1)
hvr = f_rank(hv, n1)

// Calculate moving average and standard deviation for percentile and rank
hvp_m = math.exp(f_m(math.log(hvp), n2))
hvp_sd = math.exp(f_sd(math.log(hvp), n2))
hvp_se = math.exp(f_sd(math.log(hvp), n2) / math.sqrt(n2))

hvr_m = math.exp(f_m(math.log(hvr), n2))
hvr_sd = math.exp(f_sd(math.log(hvr), n2))
hvr_se = math.exp(f_sd(math.log(hvr), n2) / math.sqrt(n2))

// Determine color gradients based on percentile and rank values
c4 = color.from_gradient(hvp, 0, hvp_m / hvp_sd, color.rgb(13, 255, 0), color.rgb(0, 145, 0)) 
con0 = hvp < hvp_m / hvp_sd

c5 = color.from_gradient(hvr, 0, hvr_m / hvr_sd, color.rgb(13, 255, 0), color.rgb(0, 145, 0)) 
con1 = hvr < hvr_m / hvr_sd

// Plot settings for HVP and HVR
plot(op1 ? con0 ? hvp : na : na, style=plot.style_columns, color=c4, title="Local Extreme Low")
plot(op1 ? hvp : na, style=plot.style_histogram, color=f_color0(hvp), title="HVP©️", linewidth=2)
plot(op1 ? hvp_m : na, style=plot.style_line, color=color.white, title="MA", linewidth=2)
plot(op1 ? hvp_m * hvp_se : na, style=plot.style_line, color=color.white, title="+SE")
plot(op1 ? hvp_m / hvp_se : na, style=plot.style_line, color=color.white, title="-SE")

plot(not op1 ? con1 ? hvr : na : na, style=plot.style_columns, color=c5, title="Local Extreme Low")
plot(not op1 ? hvr : na, style=plot.style_histogram, color=f_color1(hvr), title="HVR©️", linewidth=2)
plot(not op1 ? hvr_m : na, style=plot.style_line, color=color.white, title="MA", linewidth=2)
plot(not op1 ? hvr_m * hvr_se : na, style=plot.style_line, color=color.white, title="+SE")
plot(not op1 ? hvr_m / hvr_se : na, style=plot.style_line, color=color.white, title="-SE")

// Background color settings based on HVP and HVR values
bgcolor(op1 ? op2 ? hvp <= 5 and hvp > 3 ? c0 : hvp <= 3 and hvp > 1 ? c1 : hvp <= 1 ? c2 : na : na : na)
bgcolor(not op1 ? op2 ? hvr <= 5 and hvr > 3 ? c0 : hvr <= 3 and hvr > 1 ? c1 : hvr <= 1 ? c2 : na : na : na)

Overview

Separate lookbacks control the volatility calculation, the percentile or rank window and a smoothing average. Colours change as the reading moves into higher bands, and a background shading can be enabled. It plots in a separate pane and is a volatility context tool without entry or exit rules.

Details

Published by

Teerth1 on GitHub

Code credit

balipour, as written in the script's header

Draws

Separate pane below the 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.

Settings

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

SettingTypeDefaultVariable
Closes Only?booltrueop0
Mode? stringHVP©️op1
Lookback for Volatility: int30n0
Lookback for Percentile/Rank: int365n1
Lookback for MA: int30n2
Enable Backgroundbooltrueop2
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 indicator calculates the distribution of close-to-close percentage changes using rate of change on closing prices. It bins percentage changes into intervals of 0.25 percent increments from negative to positive values and plots a normalized cumulative hist

Indicator v4 Volatility & bands
Updated 12 days ago · GPL-3.0 GitHub repository of Close-to-Close % Change Distribution

This indicator plots a Supertrend-based trend-following setup in a separate pane and skips conditions it treats as a sideways market. A volatility range is built from an ATR value, with RMA, SMA, EMA, or WMA smoothing, or from a fixed point distance. Optional

Indicator v5 TrendVolatility & bands
Updated 1 year ago · MPL-2.0 GitHub repository of Trend Following Setup - Sideways Market Skipper
330 stars

This indicator plots candle range and open-to-close movement as percentages in a separate pane. Range is the high-low difference divided by the low, and change is the close-open difference divided by the open. Both series draw as columns. Teal columns show ran

Indicator v5 Volatility & bands
Updated 2 months ago · None stated GitHub repository of Percent & Volatility [Alorse]

Mojito v3 Strategy

by namuan
318 stars

The Mojito v3 Strategy indicator evaluates volatility term structure by calculating the ratio between front-month and second-month VIX futures contracts. It smooths this ratio using a configurable median filter and compares the result against user-defined uppe

Indicator v5 Volatility & bands
Updated 2 months ago · MIT GitHub repository of Mojito v3 Strategy

Function - Logistic Equation

by ricardosantos79
261 stars

Calculates dynamic modeling values by applying a mathematical logistic differential equation to price change over a specified lookback length. It measures price momentum relative to the recent high-low price range. The script plots positive and negative logist

Indicator v5 Oscillators & momentumVolatility & bands
Updated 4 years ago · None stated GitHub repository of Function - Logistic Equation
228 stars

This indicator detects a Bollinger Band squeeze when the bands sit inside Keltner Channels, marking low volatility. It plots red dots during a squeeze and green dots when the bands are outside, in a separate pane. An optional histogram shows momentum as the cl

Indicator v6 Volatility & bandsOscillators & momentum
Updated 3 months ago · None stated GitHub repository of Bollinger Band Squeeze Detector

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