Volume Risk Avoidance Indicator
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//
// Name:    VRAI  - Volume Risk Avoidance Indicator [Sherwin Shao]
// Created: 2022/01/07 - from VCO928

//@version=5
indicator(title='Volume Risk Avoidance Indicator', shorttitle='VRAI', format=format.inherit)
 
// Inputs
vco_short = input.int(3, title='Short Period', minval=1)
vco_long = input.int(10, title='Long Period', minval=2)
vco_showFill = input(true, title='Apply Filling') 
vco_normalizeLookback = input(25, title='Normalization look-back period')
vco_reverseColor = input(false, title='Reverse Color') 

kNeutralColor = color.rgb(245,220,0,0)
kBearColor = color.red
kBullColor = color.rgb(0,160,0,0) // color.green

// Functionality 

isFlat(sig) =>
    not(sig>0.5 or sig<-0.5 or math.abs(sig)>math.abs(sig[1])) //? color.gray :   //    sig == sig[1]

vco_color(sig) =>
    isFlat(sig) ? color.gray : sig > 0 ? kBullColor : kBearColor

osc_color(sig) =>
    sig == 0 ? kNeutralColor : sig > 0 ? kBullColor : kBearColor

momo_color(sig) =>
    sig > math.max(sig[1],0) ? color.new(kBullColor,0) : sig < math.min(sig[1],0) ? color.new(kBearColor,60) : color.new(kNeutralColor,60)

smooth(sig, len) =>
    ma = float(sig)  // None
    ma := ta.wma(sig, len)
    ma

calc_vco(sig, short, long) =>
    src = sig
    vt = ta.cum(close == high and close == low or high == low ? 0 : (close - low / 4 - high / 4 - open / 2) / (high - low) * nz(volume, 1))  // from Accum/Dist
    sh = smooth(vt, short)
    lg = smooth(vt, long)
    sh - lg
 
maxAbs(series, len) =>
    max = float(0)
    for i = 0 to len - 1 by 1
        max := math.max(max, math.abs(series[i]))
        max
    max
 

raw_vco = calc_vco(close, vco_short, vco_long)
maxAbs_vco = maxAbs(raw_vco, vco_normalizeLookback)
range_vco = 1.0  // range to fit values into
value_vco = raw_vco / maxAbs_vco * range_vco

color_vco = vco_color(value_vco)
color_stall = vco_color(-value_vco[1])
color_osc = vco_showFill ? osc_color(value_vco) : na
  
fill_color = math.abs(value_vco)<0.5 and math.abs(value_vco)<math.abs(value_vco[1]) ? 85 : 75
plot_vco = plot(value_vco, title='VCO', color=momo_color(value_vco), linewidth=1, style=plot.style_histogram)   // green-yellow-red
plot_fill = plot(0, color=color.new(color_osc, fill_color), editable=false)
fill(plot_vco, plot_fill, title='Oscillator Fill', color=color.new(color_vco, fill_color)) 