TradingView Closed-Bar Range Percentile: Detecting Volatility Expansion
Advanced Trading Tutorial
Why use a percentile?
A fixed range threshold in points is difficult to transfer across instruments. This indicator compares the current high-low range against the preceding N ranges. It measures the proportion of historical observations less than or equal to the current range. It describes relative volatility, not direction. A large red candle and a large green candle can have identical readings.
A numerical example
Suppose the previous five ranges are 2, 4, 6, 8 and 10, and the current range is 8. Four observations are less than or equal to 8, so the score is 80. Ties count toward the numerator; identical ranges therefore produce 100 rather than 50. The illustration shows six confirmed percentile readings of 30, 55, 80, 45, 20 and 65. The upper red reference is 80 and the lower green reference is 40.

Figure: six confirmed range percentile observations.
Implementation details
Pine Script v6 uses a bounded loop over historical ranges, excluding the current observation. The default window is 50, requiring at least 51 bars. The confirmed-bar condition suppresses output on the open realtime bar. Historical bars are confirmed. No future data is used, although data corrections, adjustments and timeframe changes may alter historical results. The score is deliberately not carried forward into the open bar, so an empty column is expected.
//@version=6
indicator("Closed Bar Range Percentile", overlay=false)
n = input.int(50, "Lookback", minval=2, maxval=500)
r = high - low
// Compare the current range with earlier ranges only.
float score = na
if bar_index >= n and barstate.isconfirmed
int count = 0
for i = 1 to n
count += r[i] <= r ? 1 : 0
score := 100.0 * count / n
plot(score, "Range percentile", color=color.blue, style=plot.style_columns)
hline(80, "Expansion", color=color.red)
hline(40, "Quiet", color=color.green)
Installation and testing
Open Pine Editor, paste the complete source, save it and add it to a chart. Set the lookback to five and manually compare six consecutive ranges to reproduce the example. Use Bar Replay to inspect when the output appears, and observe a live bar to verify the confirmation behavior. Test ties, zero ranges and insufficient history. With five observations the score moves in increments of twenty; with fifty it moves in increments of two. Compare several instruments and timeframes without assuming that identical percentile values imply identical risk.
Limitations and risk
High-low range excludes overnight gaps and does not capture volume or execution costs. A high percentile does not predict continuation or reversal. Thresholds are descriptive references, not validated trading signals. The loop has a computational cost proportional to the lookback. This source has not been compiled or tested on the platform. This tutorial is educational, not investment advice; trading involves risk of loss.