Advanced Divergence Oscillator
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Credit to Larry Williams and TradingView

//@version=5
indicator(title="Advanced Divergence Oscillator", shorttitle="ADO", format=format.price, precision=2, timeframe="", timeframe_gaps=true)

// Welcome to the Advanced Divergence Oscillator
// This tool is an enhancement of the Ultimate Oscillator, offering traders
// more control and deeper insight into price action.

// User Input Section
// -------------------
// These inputs allow users to fine-tune the oscillator to their specific trading strategy.

length1 = input.int(3, minval = 1, title = "Primary Length")
length2 = input.int(8, minval = 1, title = "Secondary Length")
length3 = input.int(13, minval = 1, title = "Tertiary Length")
length4 = input.int(10, minval = 1, title = "Gaussian Smoothing")


// Calculation of price averages based on different lengths

average(bp, tr_, length) => math.sum(bp, length) / math.sum(tr_, length)
high_ = math.max(high, close[1])
low_ = math.min(low, close[1])
bp = close - low_
tr_ = high_ - low_
avg7 = average(bp, tr_, length1)
avg14 = average(bp, tr_, length2)
avg28 = average(bp, tr_, length3)

// Divergence Detection and Plotting
// ----------------------------------
// Enhanced logic for detecting and plotting divergences in market price movements.

lbR = input(title="Pivot Right", defval = 2)
lbL = input(title="Pivot Left", defval = 2)
rangeUpper = input(title="Max Lookback", defval = 30)
rangeLower = input(title="Min Lookback", defval = 2)
plotBull = input(title="Plot Bullish", defval = true)
plotHiddenBull = input(title = "Plot Hidden Bullish", defval = true)
plotBear = input(title = "Plot Bearish", defval = true)
plotHiddenBear = input(title="Plot Hidden Bearish", defval = true)
bearColor = color.new(color.red, 25)
bullColor = color.new(color.green, 25)
hiddenBullColor = color.new(color.green, 50)
hiddenBearColor = color.new(color.red, 50)
textColor = color.white
noneColor = color.new(color.white, 100)

// Final Configuration

oscAvg = 100 * (4*avg7 + 2*avg14 + avg28)/7
osc = ta.alma(oscAvg, length4, 0.85, 6)
plot(osc, color=#d8f436, title="Oscillator")

// Divergence Detection and Plotting
// ----------------------------------
// Enhanced logic for detecting and plotting divergences in market price movements.
// Utilized from TradingView Divergence RSI

plFound = na(ta.pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(osc, lbL, lbR)) ? false : true
_inRange(cond) =>
	bars = ta.barssince(cond == true)
	rangeLower <= bars and bars <= rangeUpper

//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low

oscHL = osc[lbR] > ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])

// Price: Lower Low

priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bullCondAlert = priceLL and oscHL and plFound
bullCond = plotBull and bullCondAlert

plot(
     plFound ? osc[lbR] : na,
     offset=-lbR,
     title="Regular Bullish",
     linewidth=2,
     color=(bullCond ? bullColor : noneColor)
     )

//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low

oscLL = osc[lbR] < ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])

// Price: Higher Low

priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
hiddenBullCondAlert = priceHL and oscLL and plFound
hiddenBullCond = plotHiddenBull and hiddenBullCondAlert

plot(
	 plFound ? osc[lbR] : na,
	 offset=-lbR,
	 title="Hidden Bullish",
	 linewidth=2,
	 color=(hiddenBullCond ? hiddenBullColor : noneColor)
	 )

//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High

oscLH = osc[lbR] < ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])

// Price: Higher High

priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)

bearCondAlert = priceHH and oscLH and phFound
bearCond = plotBear and bearCondAlert

plot(
	 phFound ? osc[lbR] : na,
	 offset=-lbR,
	 title="Regular Bearish",
	 linewidth=2,
	 color=(bearCond ? bearColor : noneColor)
	 )

//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High

oscHH = osc[lbR] > ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])

// Price: Lower High

priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)

hiddenBearCondAlert = priceLH and oscHH and phFound
hiddenBearCond = plotHiddenBear and hiddenBearCondAlert

plot(
	 phFound ? osc[lbR] : na,
	 offset=-lbR,
	 title="Hidden Bearish",
	 linewidth=2,
	 color=(hiddenBearCond ? hiddenBearColor : noneColor)
	 )

// Additional Alert Configurations
// -------------------------------
// Users can customize alert conditions to match their trading strategies.


alertcondition(bullCondAlert, title='Regular Bullish Divergence', message="Found a new Regular Bullish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar")
alertcondition(hiddenBullCondAlert, title='Hidden Bullish Divergence', message='Found a new Hidden Bullish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar')
alertcondition(bearCondAlert, title='Regular Bearish Divergence', message='Found a new Regular Bearish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar')
alertcondition(hiddenBearCondAlert, title='Hidden Bearisn Divergence', message='Found a new Hidden Bearisn Divergence, `Pivot Lookback Right` number of bars to the left of the current bar')

// Script Summary
// --------------
// This section provides a brief overview of what the script does,
// serving as a quick reference for users.

// The ADO is a versatile tool for identifying potential price reversals
// through divergence analysis. It combines multiple average calculations
// to create a smoothed oscillator, which is then used to detect bullish and bearish divergences.