Tutorial

Williams %R in Pine Script v6: Build and Alert on It

Build Williams %R in Pine Script v6 by hand, check it against ta.wpr, and add crossings and alerts that only fire on closed bars.

•11 min read

Williams %R looks like the simplest oscillator on the menu, and that is why people stop reading about it too early. It is a single line that swings between 0 and -100, with a dashed line near the top and another near the bottom, and most guides hand you the same two numbers and leave. The part that causes trouble is not the formula. It is what the line does in a strong trend, how it behaves on a bar that has not closed yet, and what happens to your alert when the window has no range at all. This guide builds the indicator in Pine Script v6 from scratch, checks it against the built-in function, and then turns it into a version you can leave on a chart without surprises.

What Williams %R measures

Williams %R, created by Larry Williams, answers one question: where is the current close inside the highest-high to lowest-low range of the last N bars? With the default length of 14, it looks at the highest high and lowest low of the last 14 bars and places the close somewhere between them.

The scale runs from 0 at the top to -100 at the bottom. A reading of 0 means the close sits exactly on the highest high of the window. A reading of -100 means it sits on the lowest low. A reading of -50 means it is halfway through the range. Because it only uses the close and the window extremes, it ignores everything that happened between them. Two charts with completely different paths can print the same %R as long as they end at the same spot in the same range.

The conventional reference lines are -20 and -80. Readings above -20 are described as overbought and readings below -80 as oversold. Those words describe position inside the recent range and nothing more. They do not say price will turn, and they are not instructions. If you want a deeper look at the same family, the Stochastic Oscillator guide covers the cousin of this indicator in the same detail.

The formula, and how it relates to Stochastic

The formula is short:

text
%R = -100 * (highest high - close) / (highest high - lowest low)

Read it as the distance from the close down to the top of the range, divided by the whole range, flipped to a negative scale. If the close equals the highest high, the numerator is zero and %R is 0. If the close equals the lowest low, the numerator equals the range and %R is -100.

This is the Stochastic Oscillator turned upside down on a different axis. The raw (fast) %K of Stochastic is 100 * (close - lowest low) / (highest high - lowest low), so Williams %R is exactly fast %K minus 100. The two indicators carry the same information. The difference is cosmetic: %R is drawn from 0 to -100, and the usual levels are written as -20 and -80 instead of 80 and 20. If you already use one, switching to the other changes how it looks, not what it tells you.

Two details matter for code. First, the range can be zero. If the highest high and the lowest low in the window are the same number, which can happen on a very quiet market or with a length of 1, the division fails. Second, the indicator has no smoothing of its own. Every bar's value comes directly from the close and the window, so it is jumpy by design.

Build it by hand in Pine Script v6

The two functions you need are ta.highest() and ta.lowest(). Each takes a source series and a length and returns the extreme over that many bars, including the current one. Here is the whole indicator written out in the open, so every step is visible:

pine
//@version=6
indicator("Williams %R (manual)", shorttitle="%R manual", overlay=false)

length = input.int(14, "Length", minval=1)

highestHigh = ta.highest(high, length)
lowestLow   = ta.lowest(low, length)
range_      = highestHigh - lowestLow

// A zero range would divide by zero, so return na instead of a made-up number.
wr = range_ == 0 ? na : -100 * (highestHigh - close) / range_

plot(wr, "%R", color=color.new(color.purple, 0), linewidth=2)
hline(-20, "Overbought", color=color.gray, linestyle=hline.style_dashed)
hline(-50, "Midline",    color=color.gray, linestyle=hline.style_dotted)
hline(-80, "Oversold",   color=color.gray, linestyle=hline.style_dashed)

Three choices in this block are worth explaining. The minval=1 on the input stops anyone from entering zero or a negative length, which would make the window meaningless. The variable is named range_ with a trailing underscore because it avoids confusion with any built-in name while staying readable. And the zero-range case returns na on purpose. Pine Script does not invent a value for you there, and a gap in the line is more honest than a fake -50. For more on why na spreads quietly through later calculations, see how Pine Script handles na.

The three hline() calls draw the reference lines. They are plain horizontal levels, not plots, so they cost nothing per bar and do not appear in the data window.

Use ta.wpr and prove they match

Pine Script v6 has the indicator built in as ta.wpr(length). It returns the same number as the manual version, so for everyday use you can write one line and move on. The reason to still do the manual version once is trust: when you can reproduce a built-in on your own, you know exactly what it does at the edges.

This script plots the difference between the two, so you can confirm they agree on every bar:

pine
//@version=6
indicator("Williams %R check", shorttitle="%R check", overlay=false)

length = input.int(14, "Length", minval=1)

highestHigh = ta.highest(high, length)
lowestLow   = ta.lowest(low, length)
manual      = highestHigh == lowestLow ? na : -100 * (highestHigh - close) / (highestHigh - lowestLow)
builtIn     = ta.wpr(length)

plot(manual,  "Manual",   color=color.new(color.purple, 0))
plot(builtIn, "ta.wpr",   color=color.new(color.orange, 60), linewidth=4)
plot(manual - builtIn, "Difference", color=color.red, display=display.data_window)
hline(-20)
hline(-80)

The difference line is sent to the data window only, so it does not clutter the pane. It should read zero wherever both lines exist. If you want to check a single value by hand without Pine at all, the free Williams %R calculator takes a list of highs, lows, and closes and shows the result next to the code that computes it.

Reading the levels without fooling yourself

The textbook reading is that -20 and -80 mark the edges, but a more useful way to read the line is as a description of where the close sits in its own recent range. Three habits keep that reading honest.

First, remember how the window moves. %R does not only change when price changes. It also changes when an old extreme drops out of the window. If the highest high of the last 14 bars was 12 bars ago and is about to age out, the denominator and numerator both shift on the next bar, and the line can jump even if price barely moved. When a reading surprises you, look at what is leaving the window, not only what is arriving.

Second, remember that in a strong trend %R can stay near 0 or near -100 for a long stretch. A close that keeps making new highs keeps the line pinned at the top, because every new high resets the window's top to the current close. Staying at "overbought" in that situation is not a malfunction of the indicator. It is the indicator correctly saying the close is at the top of its range, bar after bar. Treating the first touch of -20 as a reversal marker is the most common misreading, and the data does not require you to do it.

Third, match the length to the question. A short length such as 5 makes the line fast and noisy and fills it with extremes. A long length such as 50 makes it slow and rarely reaches the edges. The default of 14 is a convention, not a law. Try two or three lengths on the same chart and notice which crossings of the levels change; the ones that disappear when you nudge the length were fragile.

Crossings, and the repainting trap

Most scripts do not care where the line is. They care when it crosses a level. The two usual events are the line rising back above -80 (leaving the lower zone) and falling back below -20 (leaving the upper zone). In Pine Script that is ta.crossover(wr, -80) and ta.crossunder(wr, -20).

The trap is the bar that has not closed yet. On a live chart, the current bar's close is just the latest price, and %R is recomputed on every tick. A crossing can appear mid-bar and be gone by the close. If you draw a marker or fire an alert from that raw condition, it can show up and vanish, which is the pattern people call repainting. The fix is to act only on bars that have closed, using barstate.isconfirmed. The post on barstate.isconfirmed goes through the details, and the one-line version is that you combine your condition with it using and:

ta.crossover(wr, -80) and barstate.isconfirmed

The cost is one bar of delay, since you now learn about the crossing when the bar closes instead of while it forms. That is the honest price of a condition that does not change its mind, and it is why alerts built this way look the same on a reload as they did live. If an alert fires on a bar you did not expect, why a Pine Script alert fires on the wrong bar explains the usual causes.

A full indicator with zones, markers, and alerts

Here is the complete version, with an optional smoothing line, shaded zones, confirmed-bar markers, and alert conditions. Everything in it is a description of where the close sits and when the line crossed a level; it makes no claim about what happens next.

pine
//@version=6
indicator("Williams %R with confirmed crossings", shorttitle="%R", overlay=false)

length    = input.int(14, "Length", minval=1)
upperLvl  = input.float(-20.0, "Upper level", minval=-100.0, maxval=0.0)
lowerLvl  = input.float(-80.0, "Lower level", minval=-100.0, maxval=0.0)
smoothLen = input.int(1, "Smoothing (1 = off)", minval=1)

wrRaw = ta.wpr(length)
wr    = smoothLen > 1 ? ta.sma(wrRaw, smoothLen) : wrRaw

upperLine = hline(upperLvl, "Upper level", color=color.gray, linestyle=hline.style_dashed)
lowerLine = hline(lowerLvl, "Lower level", color=color.gray, linestyle=hline.style_dashed)
hline(-50, "Midline", color=color.gray, linestyle=hline.style_dotted)
fill(upperLine, lowerLine, color=color.new(color.purple, 92), title="Neutral zone")

plot(wr, "%R", color=color.new(color.purple, 0), linewidth=2)

leftLower = ta.crossover(wr, lowerLvl)  and barstate.isconfirmed
leftUpper = ta.crossunder(wr, upperLvl) and barstate.isconfirmed

plotshape(leftLower, "Left lower zone", shape.triangleup,   location.bottom, color.teal,   size=size.tiny)
plotshape(leftUpper, "Left upper zone", shape.triangledown, location.top,    color.maroon, size=size.tiny)

alertcondition(leftLower, "%R left the lower zone", "Williams %R crossed back above the lower level")
alertcondition(leftUpper, "%R left the upper zone", "Williams %R crossed back below the upper level")

A few notes on the choices. The smoothing input defaults to 1 so the indicator matches the plain definition until you change it, and ta.sma over %R is a simple way to calm the line if the raw version is too twitchy. The levels are inputs, so you can move them without editing code. The markers are named for what happened, "left the lower zone", not for a trade you should make, which keeps the labels factual. The alertcondition messages are plain descriptions for the same reason.

Check it on a chart before you trust it

Reading code is not the same as seeing the line do its work. Before you keep a version, look at it on real data, and look at the awkward cases on purpose: a long trend where %R sits pinned near 0, a choppy range where it swings from edge to edge, and a quiet stretch where the window range gets small.

PineScripter's chart runs your script on real crypto spot market data inside the app, so you can see the plots and markers without pasting the script into TradingView first. The data covers 308 crypto spot markets across 14 timeframes, up to 5,000 bars per run. Switch timeframe and watch which markers survive; a crossing that exists on one timeframe and disappears on the next is telling you something about how fragile it is.

Replay is the most useful check for the repainting point above. It steps through the run one bar at a time, so you can watch exactly when a marker appears: on the bar that closed, not before. If you describe the indicator to the AI editor in plain English, it writes Pine Script v6, checks the code for compile errors the way TradingView does, and fixes errors itself. Asking it to "add a smoothing input and make the markers fire only on closed bars" edits the lines that change instead of rewriting the script. You can find the whole workflow in what you can do with PineScripter.

If you want to hear about a crossing without keeping a chart open, the free email alerts guide shows how to pick a trigger in your own indicator and get an email each time a bar closes with it active. The alert log can also record what a TradingView alert did and when.

Common mistakes with Williams %R

A handful of problems account for most of the confusion.

Treating the levels as orders. -20 and -80 are descriptions of position. A script that treats them as automatic actions will stay "overbought" through an entire rally.

Forgetting the zero-range case. A flat window divides by zero. Using ta.wpr handles this for you; a hand-written version should return na the way the manual script above does.

Alerting on unconfirmed bars. Without barstate.isconfirmed, a crossing can appear and disappear before the bar closes. Confirmed-only conditions are one bar slower and far more repeatable.

Comparing across markets without comparing lengths. A 14-bar window on a one-minute chart and a 14-bar window on a daily chart cover completely different amounts of time. The same number does not mean the same thing.

Expecting a zero-lag indicator. The window is a lookback. It can only tell you where the close is relative to the past N bars, so by construction it reacts after the move, not before. Pivot indicators have the same property for a related reason, which is why pivot signals arrive late.

Where to go from here

Once the plain version is on your chart and you trust it, there are natural extensions: a second %R with a much longer length to give context to the short one, a smoothing line, or a combination with a different kind of indicator so you are not reading one oscillator in isolation. Each extension is a small, testable change, which is the right size for a change to a script you rely on.

Williams %R is a good indicator to learn on because the whole thing fits in your head: a window, a close, a ratio. Everything that makes it tricky (the moving window, the unconfirmed bar, the empty range) shows up in larger indicators too, and it is easier to learn those lessons here.

This post is educational. PineScripter is a Pine Script coding tool, not a trading platform or financial adviser, and nothing here is a recommendation to buy or sell. Past behavior of an indicator says nothing about future results.

Back to Blog

Frequently asked questions

What is the formula for Williams %R?

Williams %R equals -100 times (highest high minus close) divided by (highest high minus lowest low), over a chosen window, usually 14 bars. It runs from 0 (close at the highest high) to -100 (close at the lowest low).

Is Williams %R the same as the Stochastic Oscillator?

They carry the same information. Williams %R equals the raw (fast) Stochastic %K minus 100, so it is the same ratio drawn on a 0 to -100 scale. Only the presentation and the usual levels (-20 and -80 instead of 80 and 20) differ.

How do I add Williams %R in Pine Script v6?

Use the built-in ta.wpr(length), for example wr = ta.wpr(14), then plot(wr) and add hline() calls for -20 and -80. You can also compute it by hand with ta.highest() and ta.lowest().

Why does my Williams %R alert fire and then disappear?

The current bar's close is only the latest price until the bar closes, so a crossing can appear mid-bar and vanish. Combine the condition with barstate.isconfirmed so it only fires on closed bars.

What length should I use for Williams %R?

14 is the common default, but it is a convention. Shorter lengths make the line faster and noisier, and longer lengths make it slower and less likely to reach the extremes. Try a few lengths on the same chart and note which crossings change.

Does staying below -80 or above -20 mean price will reverse?

No. It only says the close is near the edge of its recent range. In a strong trend the line can stay there for a long time, so the levels describe position and not a forecast.

Run your script on real market data and see what it plots →


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.