Pine Script Williams %R

Master this essential momentum oscillator in TradingView's Pine Script for identifying overbought/oversold conditions, potential reversals, and trend strength.

Last Updated on: Expertise: Intermediate

What is Williams %R?

Williams %R (often shortened to Williams Percent Range), developed by Larry Williams, is a momentum oscillator that measures the current closing price relative to the high-low range over a specified number of past periods. It's similar to the Stochastic Oscillator but is inverted, typically ranging from 0 to -100. Williams %R is primarily used to identify overbought and oversold conditions, helping traders spot potential turning points in price action.

In Pine Script, Williams %R is a popular tool for gauging the strength of price momentum and anticipating market reversals, offering insights into whether price is closing near the top or bottom of its recent range.

Components and Calculation

The calculation of Williams %R involves the following components over a look-back period (e.g., 14 bars):

  1. Highest High (HH): The highest price recorded over the look-back period.
  2. Lowest Low (LL): The lowest price recorded over the look-back period.
  3. Current Close (C): The most recent closing price.
  4. Williams %R Formula:
    `%R = ((Highest High - Current Close) / (Highest High - Lowest Low)) * -100`
    This formula means that when price closes near the high of the range, %R will be close to 0 (overbought). When price closes near the low of the range, %R will be close to -100 (oversold).

While some platforms may scale it from 0 to 100, the original Williams %R calculation typically results in values between 0 and -100.

Basic Williams %R Implementation in Pine Script

Pine Script v5 provides a straightforward built-in function `ta.williamsR()` for calculating Williams %R.


//@version=5
indicator("My Williams %R Indicator", overlay=false) // overlay=false to plot in a separate pane

// Input for Williams %R length
length = input.int(14, title="%R Length", minval=1)

// Calculate Williams %R value using the built-in function
williamsRValue = ta.williamsR(length)

// Plot the Williams %R line
plot(williamsRValue, title="%R", color=color.purple, linewidth=2)

// Plot horizontal lines for overbought and oversold levels
// Note: Overbought is near 0, Oversold is near -100
h_overbought = hline(-20, "Overbought (-20)", color=color.red)
h_oversold = hline(-80, "Oversold (-80)", color=color.green)

// Fill background between Williams %R and levels for visual clarity
fill(h_overbought, h_oversold, color.new(color.gray, 90))
Standard Levels: The conventional overbought level is -20 and the oversold level is -80.

Practical Williams %R Trading Strategies

1. Overbought and Oversold Conditions

This is the primary use of Williams %R. When %R crosses above -20, it's considered overbought, suggesting a potential pullback or reversal. When %R crosses below -80, it's considered oversold, indicating a potential bounce or reversal.


//@version=5
strategy("Williams %R Overbought/Oversold Strategy", overlay=true)

// Inputs for Williams %R
length = input.int(14, title="%R Length", minval=1)
overboughtLevel = input.int(-20, title="Overbought Level")
oversoldLevel = input.int(-80, title="Oversold Level")

// Calculate Williams %R
williamsRValue = ta.williamsR(length)

// Define conditions for entries and exits
// Buy when %R crosses above oversold level
longEntry = ta.crossover(williamsRValue, oversoldLevel)

// Sell when %R crosses below overbought level
shortEntry = ta.crossunder(williamsRValue, overboughtLevel)

// Strategy entries/exits
if (longEntry)
    strategy.entry("Long", strategy.long)

if (shortEntry)
    strategy.entry("Short", strategy.short)

// Optional: Plot Williams %R in a separate pane for visualization
// plot(williamsRValue, "%R", color.purple)
// hline(overboughtLevel, "Overbought", color.red)
// hline(oversoldLevel, "Oversold", color.green)

2. Williams %R Centerline (-50) Crossover

The -50 level can act as a centerline for momentum shifts. Crossing above -50 indicates increasing bullish momentum, while crossing below -50 suggests increasing bearish momentum.


//@version=5
strategy("Williams %R Centerline Crossover", overlay=true)

// Inputs for Williams %R
length = input.int(14, title="%R Length", minval=1)
centerLine = input.int(-50, title="Centerline")

// Calculate Williams %R
williamsRValue = ta.williamsR(length)

// Define conditions for entries
longSignal = ta.crossover(williamsRValue, centerLine)
shortSignal = ta.crossunder(williamsRValue, centerLine)

// Strategy entries/exits
if (longSignal)
    strategy.entry("Long", strategy.long)

if (shortSignal)
    strategy.entry("Short", strategy.short)

// Optional: Plot Williams %R in a separate pane
// plot(williamsRValue, "%R", color.purple)
// hline(centerLine, "Centerline", color.gray)

3. Williams %R Divergence Strategy

Divergence occurs when price and Williams %R move in opposite directions, often signaling a potential trend reversal. This suggests that the current trend is losing conviction.


//@version=5
indicator("Williams %R Divergence Scanner", overlay=true)

// Inputs for Williams %R
length = input.int(14, title="%R Length", minval=1)
overboughtLevel = input.int(-20, title="Overbought Level")
oversoldLevel = input.int(-80, title="Oversold Level")

// Calculate Williams %R
williamsRValue = ta.williamsR(length)

// Plot Williams %R in a separate pane
plot(williamsRValue, "%R", color=color.purple)
hline(overboughtLevel, "Overbought (-20)", color=color.red)
hline(oversoldLevel, "Oversold (-80)", color=color.green)
hline(-50, "Centerline", color=color.gray)

// Simple divergence detection (conceptual, robust detection requires advanced pivot logic)
// This is a simplified example and might need refinement for actual trading.

// Bullish Divergence (Price lower low, %R higher low)
bullishDivergence = close[2] > close[1] and close[1] > close and williamsRValue[2] < williamsRValue[1] and williamsRValue[1] < williamsRValue

// Bearish Divergence (Price higher high, %R lower high)
bearishDivergence = close[2] < close[1] and close[1] < close and williamsRValue[2] > williamsRValue[1] and williamsRValue[1] > williamsRValue

plotshape(bullishDivergence, title="Bullish Divergence", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
plotshape(bearishDivergence, title="Bearish Divergence", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)

alertcondition(bullishDivergence, "Bullish %R Divergence", "Potential bullish reversal based on Williams %R divergence.")
alertcondition(bearishDivergence, "Bearish %R Divergence", "Potential bearish reversal based on Williams %R divergence.")

Optimizing Williams %R Performance

To get the most from Williams %R in Pine Script:

Williams %R vs. Stochastic: Williams %R is very similar to Stochastic, but it measures the close relative to the high-low range on an inverted scale. Some traders prefer its visual representation for overbought/oversold conditions.

Common Williams %R Pitfalls

Conclusion

Williams %R (Williams Percent Range) is a fundamental and highly versatile momentum oscillator in Pine Script for TradingView. Its ability to show the current closing price relative to its recent range makes it invaluable for identifying overbought and oversold conditions, assessing momentum, and spotting potential reversals through divergence. By understanding its calculation, thoughtfully tuning its parameters, and integrating it strategically with other technical analysis tools, you can leverage Williams %R to gain deeper insights into market dynamics and enhance your trading decisions.