Logo
OFFLINEPIXEL
/ pinescript-strategies / pine-script-williams-r

$ Pinescript Williams %R

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

500+ Clients Helped
100% Satisfaction
Live Trading Ready
⚠️
Trading financial markets carries risk. All content (PineScript code, indicators, strategies) on this website is for educational purposes only. Past performance is not indicative of future results. By using any code or information from this site, you agree that you are solely responsible for your trading decisions. The author disclaims all liability for any losses incurred. To gain from experts experiences, You can always try our Invite Only Scripts
01

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 Pinescript, 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.

02

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).
03

Basic Williams %R Implementation in Pinescript

pine-script@terminal
//@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.red)
h_oversold = hline(-80, "Oversold (-80)", color.green)

// Fill background between Williams %R and levels for visual clarity
fill(h_overbought, h_oversold, color.new(color.gray, 90))
$ ✓ Compiled successfully
04

Standard Levels

Standard Levels

The conventional overbought level is -20 and the oversold level is -80.

05

Practical Williams %R Trading Strategies

06

1. Overbought and Oversold Conditions

pine-script@terminal
//@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)
$ ✓ Compiled successfully
07

2. Williams %R Centerline (-50) Crossover

pine-script@terminal
//@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)
$ ✓ Compiled successfully
08

3. Williams %R Divergence Strategy

pine-script@terminal
//@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.purple)
hline(overboughtLevel, "Overbought (-20)", color.red)
hline(oversoldLevel, "Oversold (-80)", color.green)
hline(-50, "Centerline", 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.")
$ ✓ Compiled successfully
09

Optimizing Williams %R Performance

To get the most from Williams %R in Pinescript:

  • Parameter Tuning: The `length` parameter is crucial. While 14 is standard, shorter lengths (e.g., 7 or 9) make %R more sensitive but prone to noise, while longer lengths (e.g., 21 or 28) smooth it more but add lag. Experiment to find optimal settings for your specific asset and timeframe.
  • Adjust Levels: For very volatile assets or shorter timeframes, you might consider adjusting the overbought/oversold levels (e.g., -10/-90 instead of -20/-80) to filter out less significant signals.
  • Combine with Trend Filters: Williams %R performs best in trending markets or within range-bound markets where price reverses predictably from boundaries. In choppy markets, it can generate numerous false signals. Use a trend filter (like a moving average or ADX) to confirm a clear trend before relying on %R signals.
  • Multi-Timeframe Analysis: Confirm Williams %R signals on a higher timeframe before acting on signals from a lower timeframe for added reliability. For example, if the daily %R is oversold, a 4-hour %R oversold signal might be more reliable.
  • Confluence with Price Action: Always look for %R signals to be confirmed by price action, such as candlestick patterns, breaks of support/resistance, or chart patterns.
10

Williams %R vs. Stochastic

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.

11

Common Williams %R Pitfalls

  • False Overbought/Oversold Signals: In strong, sustained trends, Williams %R can remain at extreme overbought (near 0) or oversold (near -100) levels for extended periods. Blindly fading these extremes can lead to significant losses.
  • Whipsaws in Ranging Markets: In choppy or consolidating markets, %R can oscillate frequently between -20 and -80, leading to many false signals.
  • Divergence Can Be Early: While divergence is powerful, it can appear early, and a trend might continue for some time after the divergence signal, leading to premature entries.
  • Not a Standalone Indicator: Williams %R should always be used as part of a broader trading system, combined with other indicators (e.g., volume, trend-following indicators) and price action analysis.
12

Conclusion

Conclusion

Williams %R (Williams Percent Range) is a fundamental and highly versatile momentum oscillator in Pinescript 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.

Enhance Your Trading

Get a high-performance Pinescript analysis tool for actionable market insights, designed for traders on the move.

This strategy runs in live mode on TradingView, helping you identify potential opportunities.

Get Pinescript Strategy