VHF-Adaptive CCI [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(title="VHF-Adaptive CCI [Loxx]", 
     shorttitle="VHFACCI [Loxx]", 
     overlay = false, 
     timeframe="", 
     timeframe_gaps = true)

greencolor = #2DD204
redcolor = #D2042D 

variant(type, src, len) =>
    sig = 0.0
    if type == "SMA"
        sig := ta.sma(src, len) 
    else if type == "EMA"
        sig := ta.ema(src, len) 
    else if type == "WMA"
        sig := ta.wma(src, len)   
    else if type == "RMA"
        sig := ta.rma(src, len)  
    sig
    
_smoother(float src, len)=>
    wrk = src, wrk2 = src, wrk4 = src
    wrk0 = 0., wrk1 = 0., wrk3 = 0.
    alpha = 0.45 * (len - 1.0) / (0.45 * (len - 1.0) + 2.0)
    wrk0 := src + alpha * (nz(wrk[1]) - src)
    wrk1 := (src - wrk) * (1 - alpha) + alpha * nz(wrk1[1])
    wrk2 := wrk0 + wrk1
    wrk3 := (wrk2 - nz(wrk4[1])) * math.pow(1.0 - alpha, 2) + math.pow(alpha, 2) * nz(wrk3[1])
    wrk4 := wrk3 + nz(wrk4[1])
    wrk4
    
src = input(hlc3, title="Source", group = "Basic Settings")
cciper = input.int(25, "CCI Period", minval=1, group = "Basic Settings")
type = input.string("SMA", "Signal Smoothing Type", options = ["EMA", "WMA", "RMA", "SMA"], group = "Basic Settings")
maper = input.int(7, "Signal Period", minval=1, group = "Basic Settings")

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

vmax = ta.highest(src, cciper)
vmin = ta.lowest(src, cciper)
noise = math.sum(math.abs(ta.change(src)), cciper)

vhf = (vmax - vmin) / noise
len = nz(int(-math.log(vhf) * cciper), 1)
len := len < 1 ? 1 : len

ma = ta.sma(src, cciper)

cci = _smoother((src - ma) / (0.015 * ta.dev(src, cciper)), len)

maout = variant(type, cci, maper)

plot(0, color = bar_index % 2 ? color.gray : na)

colorout = cci > 0 ? greencolor : redcolor

plot(cci, "CCI", color=colorout , linewidth = 2)
plot(maout, "Signal", color = color.white)

barcolor(colorbars ? colorout : na)

goLong = ta.crossover(cci, 0)
goShort = ta.crossunder(cci, 0)

plotshape(goLong and showsignals, title = "Long", color = greencolor, textcolor = greencolor, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(goShort and showsignals, title = "Short", color = redcolor, textcolor = redcolor, text = "S", style = shape.triangledown, location = location.top, size = size.auto)

alertcondition(goLong, title="Long", message="VHF-Adaptive CCI [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="VHF-Adaptive CCI [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")



