Momentum Reversal [AngelAlgo]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

//@version=5
indicator("Momentum Reversal [AngelAlgo]", overlay = false)

// Inputs
momentumLength = input(14,"Period")
trendLength = input(50,"Trend length")
signalsType = input.string("Contrarian",options=["Contrarian","Trend"], title="Signals type")
signalsSmoothed = input(true,"Smothed signals")

// Internal variables
momentum = ta.change(close, momentumLength)
trend = ta.sma(momentum, trendLength)
hist = momentum - trend
threshold = ta.sma(math.abs(hist),500)

// Calculating conditional colors
colorHist = hist > 0 ? color.new(color.green,50) : color.new(color.red,50)
colorHistSmoothed = hist > 0 ? color.new(color.green,0) : color.new(color.red,0)

// Plotting the indicator histogram
plot(hist, "Momentum Reversal", color = colorHist, style = plot.style_columns)

// Adjusting max and min threshold levels
min = -1.3*threshold 
max = 1.3*threshold 

// Calculating the smoothed indicator line
histSmoothed = ta.hma(hist,10)

// Chossing the input data for signals calculation
histType = signalsSmoothed ? histSmoothed : hist

// Determining the choosen signal type
TrendSignals = signalsType == "Trend" ? true : false
ContrarianSignals = signalsType == "Contrarian" ? true : false

//Trading sginals conditions
ContrarianBuy = ta.crossunder(histType, min) and ContrarianSignals and barstate.isconfirmed
ContrarianSell = ta.crossover(histType, max) and ContrarianSignals and barstate.isconfirmed
TrendBuy = ta.crossover(histType, max) and TrendSignals and barstate.isconfirmed
TrendSell = ta.crossunder(histType, min) and TrendSignals and barstate.isconfirmed

// Plotting the signal arrows
//Contrarian signals
plotshape(ContrarianSell ? histType: na, style=shape.triangledown, color = color.red, size = size.small, location = location.absolute)
plotshape(ContrarianBuy ? histType: na, style=shape.triangleup, color = color.green, size = size.small, location = location.absolute)
// Trend signals
plotshape(TrendBuy ? histType: na, style=shape.triangleup, color = color.green, size = size.small, location = location.absolute)
plotshape(TrendSell ? histType: na, style=shape.triangledown, color = color.red, size = size.small, location = location.absolute)

// Plotting the smoothed indicator line
plot(histSmoothed ,color=colorHistSmoothed)

// Plotting the dynamic threshold levels
plot(min, style = plot.style_circles)
plot(max, style = plot.style_circles)