Logo
OFFLINEPIXEL
/ pinescript-strategies / pine-script-ultimate-oscillator

$ Pinescript Ultimate Oscillator

Master this unique momentum oscillator in TradingView's Pinescript that combines multiple timeframes for more reliable overbought/oversold signals and divergence detection.

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 the Ultimate Oscillator?

The Ultimate Oscillator (UO), developed by Larry Williams in 1976, is a momentum oscillator designed to measure buying and selling pressure across three different timeframes (typically 7, 14, and 28 periods). Its unique construction aims to correct the shortcomings of other oscillators by preventing premature divergence signals and reducing whipsaws that often occur when using a single period. The UO oscillates between 0 and 100, providing signals for overbought/oversold conditions and, most notably, strong divergence patterns.

In Pinescript, the Ultimate Oscillator is a valuable tool for traders seeking a more robust momentum indicator that filters out noise and delivers more reliable signals for potential trend reversals.

02

Components and Calculation

The calculation of the Ultimate Oscillator is more complex than other oscillators, involving three weighted averages of "Buying Pressure" and "True Range" over short, medium, and long timeframes:

  1. Buying Pressure (BP): `Close - Minimum(Low, Close[1])`
  2. True Range (TR): `Maximum(High, Close[1]) - Minimum(Low, Close[1])`
  3. Raw Ultimate Oscillator: For each of the three lengths (e.g., 7, 14, 28):
    • Calculate `Average Buying Pressure (ABP) = Sum(BP, length) / Sum(TR, length)`
  4. Weighted Average: The final UO value is a weighted sum of these three averages:
    `UO = ((4 * ABP(length1)) + (2 * ABP(length2)) + ABP(length3)) / (4 + 2 + 1) * 100`
    Typical lengths are 7, 14, and 28. The weights (4, 2, 1) prioritize the shorter periods while still incorporating information from longer ones.
03

Basic Ultimate Oscillator Implementation in Pinescript

pine-script@terminal
//@version=5
indicator("My Ultimate Oscillator", overlay=false) // overlay=false to plot in a separate pane

// Inputs for Ultimate Oscillator lengths
length1 = input.int(7, title="Length 1 (Short)", minval=1)
length2 = input.int(14, title="Length 2 (Medium)", minval=1)
length3 = input.int(28, title="Length 3 (Long)", minval=1)

// Calculate Ultimate Oscillator using the built-in function
uoValue = ta.uo(length1, length2, length3)

// Plot the Ultimate Oscillator line
plot(uoValue, title="Ultimate Oscillator", color=color.blue, linewidth=2)

// Plot horizontal lines for overbought and oversold levels
h_overbought = hline(70, "Overbought (70)", color.red, linestyle=hline.style_dashed)
h_oversold = hline(30, "Oversold (30)", color.green, linestyle=hline.style_dashed)
hline(50, "Centerline", color.gray, linestyle=hline.style_dotted)

// Fill background between UO 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 70 and the oversold level is 30.

05

Practical Ultimate Oscillator Trading Strategies

06

1. Overbought and Oversold Conditions

pine-script@terminal
//@version=5
strategy("Ultimate Oscillator Overbought/Oversold Strategy", overlay=true)

// Inputs for Ultimate Oscillator
length1 = input.int(7, title="Length 1", minval=1)
length2 = input.int(14, title="Length 2", minval=1)
length3 = input.int(28, title="Length 3", minval=1)
overboughtLevel = input.int(70, title="Overbought Level")
oversoldLevel = input.int(30, title="Oversold Level")

// Calculate Ultimate Oscillator
uoValue = ta.uo(length1, length2, length3)

// Define conditions for entries and exits
// Buy when UO moves below oversold and then crosses back above it
longCondition = ta.crossunder(uoValue, oversoldLevel) // UO goes oversold
longExitCondition = ta.crossover(uoValue, oversoldLevel) // UO exits oversold (potential buy)

// Sell when UO moves above overbought and then crosses back below it
shortCondition = ta.crossover(uoValue, overboughtLevel) // UO goes overbought
shortExitCondition = ta.crossunder(uoValue, overboughtLevel) // UO exits overbought (potential sell)

// Strategy entries/exits (entry upon exiting extreme zones)
if (longExitCondition)
    strategy.entry("Long", strategy.long)

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

// Optional: Plot UO in a separate pane for visualization
// plot(uoValue, "UO", color.blue)
// hline(overboughtLevel, "Overbought", color.red)
// hline(oversoldLevel, "Oversold", color.green)
$ ✓ Compiled successfully
07

2. Ultimate Oscillator Divergence (Key Strategy)

pine-script@terminal
//@version=5
indicator("Ultimate Oscillator Divergence Scanner", overlay=true)

// Inputs for Ultimate Oscillator
length1 = input.int(7, title="Length 1", minval=1)
length2 = input.int(14, title="Length 2", minval=1)
length3 = input.int(28, title="Length 3", minval=1)
overboughtLevel = input.int(70, title="Overbought Level")
oversoldLevel = input.int(30, title="Oversold Level")
centerLine = input.int(50, title="Centerline")

// Calculate Ultimate Oscillator
uoValue = ta.uo(length1, length2, length3)

// Plot UO in a separate pane
plot(uoValue, "Ultimate Oscillator", color.blue)
hline(overboughtLevel, "Overbought (70)", color.red)
hline(oversoldLevel, "Oversold (30)", color.green)
hline(centerLine, "Centerline (50)", color.gray)

// Simple divergence detection (conceptual, robust detection requires advanced pivot logic)
// This is a simplified example focusing on price vs UO divergence, not specific Williams' patterns.

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

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

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 UO Divergence", "Potential bullish reversal based on Ultimate Oscillator divergence.")
alertcondition(bearishDivergence, "Bearish UO Divergence", "Potential bearish reversal based on Ultimate Oscillator divergence.")
$ ✓ Compiled successfully
08

3. Failure Swings

pine-script@terminal
// Implementing failure swings in Pinescript is more complex as it requires robust peak/trough detection within the oscillator itself, often combined with price action. The simplified strategy examples above focus on direct signals.
$ ✓ Compiled successfully
09

Optimizing Ultimate Oscillator Performance

To get the most from the Ultimate Oscillator in Pinescript:

  • Parameter Tuning: The default lengths (7, 14, 28) are widely used and often perform well. However, for extremely fast or slow-moving assets, you might experiment with slightly different multiples, ensuring the three lengths maintain their 1:2:4 ratio (or similar relative spacing).
  • Focus on Divergence: The UO is particularly designed for reliable divergence signals. Prioritize these over simple overbought/oversold crossovers, especially when looking for major reversals.
  • Combine with Trend Filters: While UO uses multiple timeframes to reduce noise, it's still an oscillator. Using a longer-term trend filter (like a long-period moving average or Ichimoku Cloud) can help avoid false signals against the primary trend.
  • Confluence with Price Action: Always seek confirmation from price action. For instance, a bullish divergence signal from UO is stronger if it's accompanied by a bullish engulfing pattern or a break above local resistance on the price chart.
  • Adjust Levels for Strong Trends: In very strong trends, UO can remain at extreme levels for extended periods. Consider using the 40/60 levels as a "trend range" instead of 30/70 for entry/exit within a strong trend.
10

Unique Construction

Unique Construction

Remember UO's strength lies in its multi-timeframe calculation which inherently smooths out noise without adding significant lag, making its divergence signals particularly noteworthy.

11

Common Ultimate Oscillator Pitfalls

  • Complexity of Calculation: While Pinescript simplifies it, understanding the underlying BP, TR, and weighted averages is important for advanced tuning.
  • Whipsaws in Extreme Consolidation: Even with its design, very flat or extremely volatile non-trending markets can still produce choppy UO signals.
  • Over-Reliance on Overbought/Oversold: Blindly trading simple overbought/oversold signals without divergence or other confirmations can lead to losses, especially in strong trends.
  • Divergence Can Be Early: While UO aims to mitigate this, divergence can still appear before a reversal fully manifests, requiring patience and additional confirmation.
  • Not a Standalone Indicator: The Ultimate Oscillator should always be used as part of a broader trading strategy, complementing other technical analysis tools.
12

Conclusion

Conclusion

The Ultimate Oscillator is a sophisticated and highly effective momentum indicator in Pinescript for TradingView. Its innovative construction, incorporating multiple timeframes and weighted averages, allows it to provide more reliable overbought/oversold signals and, crucially, robust divergence patterns than many single-period oscillators. By understanding its unique calculation, thoughtfully tuning its parameters, and integrating it strategically within your comprehensive trading approach, you can leverage the Ultimate Oscillator to gain deeper insights into market momentum 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