S2BU2 Stochastic Momentum Convergence Divergence
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sucks2bu2

//@version=5
indicator(title = 'S2BU2 Stochastic Momentum Convergence Divergence', shorttitle = 'S2BU2 StocMCD', overlay = false, precision = 2, timeframe = '', timeframe_gaps = false)

//==================================define Inputs==================================//
periodSlow = input.int(defval = 10, minval = 1, title = 'Period Slow')
periodFast = input.int(defval = 5,minval = 1,  title = 'Period Fast')
periodSmooth = input.int(defval = 3, minval = 1, title = 'Period Smooth')


//=================================define Functions================================//
getDiff(period) => 
    float lowerLow = ta.lowest(low, period)
    float higherHigh = ta.highest(high, period)
    float diff = higherHigh - lowerLow
    diff
    
getRDiff(period) => 
    float lowerLow = ta.lowest(low, period)
    float higherHigh = ta.highest(high, period)
    float diff = higherHigh - lowerLow
    float rdiff = close - (higherHigh+lowerLow)/2
    rdiff

getSMI(avgRel, avgDiff) => 
    avgDiff != 0 ? (avgRel/(avgDiff/2)*100) : 0



//=========================calculate Helper Variables==============================//
//slow
float avgRelSlow = ta.ema(ta.ema(getRDiff(periodSlow),periodSmooth),periodSmooth)
float avgDiffSlow = ta.ema(ta.ema(getDiff(periodSlow),periodSmooth), periodSmooth)

//fast
float avgRelFast = ta.ema(ta.ema(getRDiff(periodFast),periodSmooth),periodSmooth)
float avgDiffFast = ta.ema(ta.ema(getDiff(periodFast),periodSmooth), periodSmooth)



//==========================calculate Plot Variables===============================//
float smiFast = getSMI(avgRelFast, avgDiffFast)
float signalFast = ta.ema(smiFast, periodSmooth)
float smiSlow = getSMI(avgRelSlow, avgDiffSlow)

//conditionals
float trendCross = ta.cross(smiSlow, signalFast) ? 200 : na
trendColor = smiSlow > signalFast ? color.green : color.red
trendEndColor = if ta.crossunder(smiSlow, signalFast) and nz(smiSlow[0]) < nz(smiSlow[1])
    color.red
else
    if ta.crossover(smiSlow, signalFast) and nz(smiSlow[0]) > nz(smiFast[1])
        color.green
    else
        color.yellow


//====================================plot=========================================//
//graphs
plot(smiSlow, title = 'Trend', color = trendColor, linewidth = 2)
plot(smiFast, title = 'SMI', color = color.orange, linewidth = 2)
plot(signalFast, title = 'Signal', color = color.gray, linewidth = 2)

//lines
hline(40, title = 'OverBought', color = color.white, linestyle = hline.style_solid)
hline(-40, title = 'OverSold', color = color.white, linestyle = hline.style_solid)
hline(0, title = 'ZeroLine', color = color.white, linestyle = hline.style_dashed)

//crossover Bars
plot ( trendCross, title = 'TrendEnd',   color = trendEndColor, linewidth = 1, style = plot.style_histogram, histbase=-100, editable=false )