Probability Density Function based MA MACD [Loxx]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx

//@version=5
indicator("Probability Density Function based MA MACD [Loxx]", 
     shorttitle="PDFMAMACD [Loxx]", overlay=false, max_bars_back = 3000)

greencolor = #2DD204
redcolor = #D2042D 

lightgreencolor = #96E881 
lightredcolor =  #DF4F6C

src = input.source(close, "Source", group = "Basic Settings")
fper = input.int(12, "Fast Period", group = "Basic Settings")
sper = input.int(26, "Slow Period", group = "Basic Settings")
sigper = input.int(9, "Signal Period", group = "Basic Settings")
vari = input.float(1, "Variance", step = 0.1, minval = 0.1, group = "Basic Settings") 
mean = input.float(1, "Mean", step = 0.1, minval = -1, maxval = 1, group = "Basic Settings") 

colorbars = input.bool(false, "Color bars?", group = "UI Options")

_pdf(_x, _variance, _mean)=>
    out = 
         (1.0 / math.sqrt(2 * math.pi * _variance * _variance) * 
         math.exp(-((_x - _mean) * (_x - _mean)) / (2 * _variance * _variance)))
    out

_pdfma(src, period, variance, mean)=>
    maxx = 3.5
    step = maxx / (period - 1)
    m_coeffw = 0.

    m_coeffs = array.new_float(period, 0.)
    
    for k = 0 to period - 1 
        array.set(m_coeffs, k, _pdf(k * step, variance, mean * maxx))
        m_coeffw += array.get(m_coeffs, k)
        
    pern = period
    _avg = 0.
    
    for k = 0 to period - 1 
        if (pern < 0) 
            pern += period
        _avg += nz(src[pern]) * nz(array.get(m_coeffs, k))
        pern := pern -1 
                      
    out = _avg / m_coeffw
    out
    
fasma = _pdfma(src, fper, vari, mean)
sloma = _pdfma(src, sper, vari, mean)

macd = fasma-sloma

signal= _pdfma(macd, sigper, vari, mean)

colorout = 
     macd > signal and macd > 0 ? greencolor : 
     macd < signal and macd > 0 ? lightgreencolor : 
     macd < signal and macd < 0 ? redcolor : 
     macd > signal and macd < 0 ? lightredcolor : 
     color.gray

plot(signal, color = color.new(color.gray, 10), style = plot.style_histogram)

plot(macd, color = colorout, linewidth = 2)

barcolor(colorbars ? colorout : na)










































