Guide

ta.percentrank in Pine Script: Rank Values Over a Lookback

How ta.percentrank ranks a value against its own past in Pine Script v6, how to verify it by hand, and how it differs from the percentile functions.

•9 min read

You have an ATR reading of 312 on a four hour chart and no idea whether that is a quiet market or a wild one. The number alone says nothing, because "high" depends entirely on what the last few hundred bars looked like. That is the problem ta.percentrank solves: it turns a raw value into a rank against its own recent history, so a reading of 312 becomes "higher than 90 percent of the last 200 bars". This guide covers exactly what the function measures, the one detail that trips people up, how it differs from the two percentile functions that sit beside it, and how to build and verify a rank-based indicator.

What ta.percentrank actually returns

The signature is ta.percentrank(source, length). It returns a series float between 0 and 100. For each bar it looks at the length values of source that came before the current bar, counts how many of them are less than or equal to the current value, and reports that count as a percentage of length.

Two details matter. First, the window is the previous length bars, not including the current bar. The current value is the thing being ranked, so it is compared against history rather than against itself. Second, the comparison is "less than or equal", so ties count in the reader's favour: if the current value equals the highest value in the window, the rank is 100 and not something slightly below it.

A rank of 50 means the current value sits at the median of its recent past. A rank of 95 means only about 5 percent of the lookback was higher. A rank near 0 means nearly everything in the window was higher. The function says nothing about what happens next. It describes where the present value sits relative to the past, which is all a rank can do.

Why a rank beats a raw threshold

Raw thresholds age badly. An RSI above 70 is a fixed line, but the distribution of RSI readings changes from market to market and from year to year. A volatility reading of 312 might be the 99th percentile on one timeframe and the 20th on another. Hard-coding "ATR above 300" into a script bakes in a single market's history.

A rank is self-calibrating. Ask "is the current ATR in the top 10 percent of the last 200 bars" and the question means the same thing on a one hour chart and a daily chart, on a quiet market and a busy one. That is why percent rank is popular for volatility regimes, volume spikes, and any oscillator whose scale you do not want to tune by hand. The cost is that the answer depends on the window. A 50 bar window and a 500 bar window can disagree about the same bar, and neither is wrong. They answer different questions.

A first indicator: where is volatility right now

Start with the smallest useful script. It ranks ATR against the previous 200 bars and plots the rank in its own pane with two reference lines.

pine
//@version=6
indicator("ATR Percent Rank", overlay = false)

atrLen  = input.int(14, "ATR length", minval = 1)
rankLen = input.int(200, "Rank lookback", minval = 2)

atrValue = ta.atr(atrLen)
atrRank  = ta.percentrank(atrValue, rankLen)

hline(90, "High", color = color.new(color.orange, 40))
hline(10, "Low",  color = color.new(color.teal, 40))
plot(atrRank, "ATR rank", color = color.blue, linewidth = 2)

Read the pane as a ranking, not a prediction. When the line is above 90, the current ATR is higher than at least 90 percent of the previous 200 readings. When it is below 10, volatility is compressed relative to that window. Because the function needs rankLen prior bars, the first stretch of the chart returns na, which is correct behaviour and not a bug. If you are unsure how na flows through later calculations, the post on how Pine Script handles na covers it.

The self-comparison trap and how to check yourself

The most common mistake is ranking a series that is already a rolling statistic and then being surprised by the result. ATR is smoothed, so neighbouring bars have similar values. A smoothed series changes slowly, which means its rank also changes slowly and tends to sit at extremes for many bars in a row. That is not wrong, but it is different from ranking a raw series such as the bar range, which jumps around.

The other mistake is assuming the window includes the current bar. You can verify the definition for yourself with a loop that counts the previous values directly and compares the count to the built-in. If the definition is as described, the difference is zero on every bar.

pine
//@version=6
indicator("Percent Rank Check", overlay = false)

len = input.int(50, "Lookback", minval = 2)
src = ta.rsi(close, 14)

builtIn = ta.percentrank(src, len)

float manual = na
if bar_index >= len + 14
    int count = 0
    for i = 1 to len
        if src[i] <= src
            count += 1
    manual := 100.0 * count / len

plot(builtIn, "Built-in", color = color.blue)
plot(manual,  "Manual",   color = color.orange)
plot(builtIn - manual, "Difference", color = color.red)

The loop starts at i = 1, so it compares the current value with each of the len bars before it. Run it on any chart and watch the red difference line sit at zero. If you change the loop to start at i = 0, the current value is compared with itself, the count is always at least one, and the difference stops being zero. That small experiment is more convincing than any description, and it is a good habit for any ta.* function whose edge behaviour you are unsure about. The same habit is behind the debugging approach in how to debug Pine Script when there is no error message.

percentrank versus the two percentile functions

Pine Script v6 also has ta.percentile_nearest_rank(source, length, percentage) and ta.percentile_linear_interpolation(source, length, percentage). They are the inverse operation. Where ta.percentrank takes a value and tells you its percentile, these take a percentile and tell you the value that sits there.

Use ta.percentrank when you want a normalised 0 to 100 reading to compare across markets or to feed into a threshold. Use the percentile functions when you want a level in the units of the series, for example "the ATR value that 90 percent of recent bars stayed below", which you can then plot directly on top of ATR. The nearest rank version returns an actual value from the window. The linear interpolation version can return a value between two observations, which gives a smoother line.

pine
//@version=6
indicator("ATR With Percentile Band", overlay = false)

atrLen = input.int(14, "ATR length", minval = 1)
lookback = input.int(200, "Lookback", minval = 2)
pct = input.float(90, "Percentile", minval = 1, maxval = 99)

atrValue = ta.atr(atrLen)
upper = ta.percentile_linear_interpolation(atrValue, lookback, pct)
lower = ta.percentile_linear_interpolation(atrValue, lookback, 100 - pct)

plot(atrValue, "ATR", color = color.blue, linewidth = 2)
plot(upper, "Upper percentile", color = color.orange)
plot(lower, "Lower percentile", color = color.teal)

Here the band is in ATR units, so you can see at a glance how far the current reading is from its own historical band. The rank version and the band version carry the same information in different clothes. Pick whichever the rest of your script needs.

Choosing the lookback

There is no correct length, only a trade-off. A short window such as 50 bars adapts quickly but makes every reading look extreme after a regime change. A long window such as 500 bars is stable but slow to recognise that conditions have genuinely shifted. For intraday charts, a window that spans a few days of bars keeps the rank meaningful. For daily charts, 250 bars is roughly one trading year on a market that trades five days a week, which is a natural reference point, though crypto trades every day.

A practical approach is to expose the length as an input and compare two values on the same chart. If a reading is extreme under both a 100 bar and a 400 bar window, it is extreme in a way that does not depend on your choice. If it is extreme under one and ordinary under the other, you have learned that the answer is sensitive to the window, and you should say so in how you use it.

Since the PineScripter chart runs on 308 crypto spot markets across 14 timeframes with up to 5,000 bars per run, it is a convenient place to try the same script on several markets and timeframes and see how stable the ranks are. The chart is for looking at what a script plots, not for forecasting.

Using the rank inside a script

The rank is most useful as a filter or as a regime label. The script below colours the background when volume is unusually high compared with its own history and plots a simple flag on the bars where that happens. It is a way to mark where something unusual occurred, which you can then inspect.

pine
//@version=6
indicator("Volume Rank Highlight", overlay = true)

lookback = input.int(100, "Lookback", minval = 2)
threshold = input.float(95, "Rank threshold", minval = 50, maxval = 100)

volRank = ta.percentrank(volume, lookback)
unusual = volRank >= threshold and barstate.isconfirmed

bgcolor(unusual ? color.new(color.orange, 85) : na)
plotshape(unusual, "Unusual volume", shape.triangleup, location.belowbar, color.orange, size = size.tiny)

Note the use of barstate.isconfirmed. A rank computed on the live bar changes with every tick because the current volume is still growing, so a bar can pass the threshold mid-bar and fail it at the close. Gating on the confirmed bar keeps the history and the live behaviour consistent. The post on barstate.isconfirmed and repainting explains the mechanism in detail.

Also think about what you are ranking. Volume on a market with a strong daily rhythm will rank high at the same hours every day. If that rhythm is not what you want to detect, rank the volume against the same time of day, or compare with a longer window that smooths over the cycle. A rank is only as informative as the question you ask of it.

Pitfalls worth knowing

A few failure patterns show up repeatedly.

The first is ranking across a series with many equal values. Because ties count as "less than or equal", a series that is flat for long stretches will rank at or near 100 whenever it matches its plateau. Ranking something like a stepped value or a session level produces readings that look dramatic and mean little.

The second is reading the rank as a probability. A rank of 95 does not mean there is a 95 percent chance of anything. It is a description of where today's value sits in its own recent past.

The third is mixing timeframes. If you compute the rank on a higher timeframe through request.security, the usual rules about lookahead and repainting apply to the rank as well. The post on how request.security works walks through them.

The fourth is forgetting the warm-up. The first length bars return na, so a condition such as volRank >= threshold is simply false there. That is fine for a flag, but if you later combine the rank with arithmetic, wrap it with nz() deliberately and not by habit.

Build it from a plain-English description

If you would rather describe the indicator than type it, PineScripter's AI editor writes Pine Script v6 from plain English, checks the code for compile errors and fixes them itself, and edits only the lines that change when you ask for a follow-up. A request such as "rank ATR over the last 200 bars, plot it in its own pane with lines at 10 and 90, and let me change both lengths" produces something close to the first script above. You can then run it on the chart against real market data and read what it plots, ask for the lookback to become an input, or swap ATR for volume without the rest of the script being rewritten. The Code Changes view shows exactly which lines moved, so you can compare the result with the definition in this post. You can find it at PineScripter, and plans are on the pricing page.

Whatever tool wrote the code, check it the way this post checked the built-in: compare against a manual count, try two window lengths, and confirm the first bars are na.

Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.

Frequently asked questions

Does ta.percentrank include the current bar in its window?

No. It compares the current value with the previous length values, so the current bar is ranked against history and not against itself.

What range does ta.percentrank return?

A float from 0 to 100. Ties count as less than or equal, so a value equal to the window maximum ranks 100.

Why is the start of my rank plot empty?

The function needs length prior bars, so the first bars return na. That is expected warm-up behaviour.

What is the difference between percentrank and percentile_nearest_rank?

percentrank takes a value and returns its percentile. The percentile functions take a percentile and return the value at that level, in the series' own units.

What lookback should I use?

There is no single right length. Compare a short and a long window; if a reading is extreme under both, it does not depend on your choice.

Describe your indicator in plain English and get Pine Script that compiles →


Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.