Momentum Oscillator, Divergences & Signals [TrendAlpha]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TrendAlpha
//@version=5
indicator("Momentum Oscillator, Real Time Divergences & Signals [TrendAlpha]", "Momentum Oscillator, Divergences & Signals [TrendAlpha]")
length = input(7, "Length")
src = input(close, "Source")
show_lines = input(true, "Show Lines")
colcor = input(false, "Hide Price/Oscillator")

up = ta.highest(src, length)
dn = ta.lowest(src, length)
osc = ta.mom(ta.sma(ta.sma(src, length), length), length)
phosc = ta.crossunder(ta.change(osc), 0)
plosc = ta.crossover(ta.change(osc), 0)
bear = osc > 0 and phosc and ta.valuewhen(phosc, osc, 0) < ta.valuewhen(phosc, osc, 1) and ta.valuewhen(phosc, up, 0) > ta.valuewhen(phosc, up, 1)
bull = osc < 0 and plosc and ta.valuewhen(plosc, osc, 0) > ta.valuewhen(plosc, osc, 1) and ta.valuewhen(plosc, dn, 0) < ta.valuewhen(plosc, dn, 1)

simple_css = osc > osc[1] and osc > 0 ? color.new(color.green, 0) : osc < osc[1] and osc > 0 ? color.new(color.lime, 0) : osc < osc[1] and osc < 0 ? color.new(color.red, 0) : osc > osc[1] and osc < 0 ? color.new(color.maroon, 0) : na

plot(osc, "Osc", colcor ? color.new(color.black, 0) : simple_css, 3, plot.style_histogram)
plotshape(bull ? osc : na, "Bullish Circle", shape.circle, location.absolute, color.new(color.green, 0), size = size.tiny)
plotshape(bear ? osc : na, "Bearish Circle", shape.circle, location.absolute, color.new(color.red, 0), size = size.tiny)
plotshape(bull ? osc : na, "Bullish Label", shape.labelup, location.absolute, color.new(color.green, 0), text = "Buy", textcolor = color.white, size = size.tiny)
plotshape(bear ? osc : na, "Bearish Label", shape.labeldown, location.absolute, color.new(color.red, 0), text = "Sell", textcolor = color.white, size = size.tiny)

n = bar_index
bull_x1 = ta.valuewhen(plosc, n, 1)
bull_y1 = ta.valuewhen(plosc, osc, 1)
bear_x1 = ta.valuewhen(phosc, n, 1)
bear_y1 = ta.valuewhen(phosc, osc, 1)
var line bull_line = na
var line bear_line = na

if show_lines
    if bull
        bull_line := line.new(x1 = bull_x1, y1 = bull_y1, x2 = n, y2 = osc, color = color.new(color.green, 0), width = 1)
        line.delete(bear_line)
    else if bear
        bear_line := line.new(x1 = bear_x1, y1 = bear_y1, x2 = n, y2 = osc, color = color.new(color.red, 0), width = 1)
        line.delete(bull_line)

alertcondition(bull, title = "Bullish Divergence", message = "Bullish Divergence")
alertcondition(bear, title = "Bearish Divergence", message = "Bearish Divergence")