7 Moving Averages [Plus]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OskarGallard

//@version=5
indicator(title="7 Moving Averages [Plus]",  shorttitle="7MA[+]", overlay=true, precision = 4, linktoseries = true, max_bars_back = 500, max_lines_count = 500)

// Function to select the type of source
get_src(Type) =>
    switch Type
        "VWAP" => ta.vwap
        "Close" => close
        "Open" => open
        "HL2" => hl2
        "HLC3" => hlc3
        "OHLC4" => ohlc4
        "HLCC4" => hlcc4
        "High" => high
        "Low" => low
        "vwap(Close)" => ta.vwap(close)
        "vwap(Open)" => ta.vwap(open)
        "vwap(High)" => ta.vwap(high)
        "vwap(Low)" => ta.vwap(low)
        "AVG(vwap(H,L))" => math.avg(ta.vwap(high), ta.vwap(low))
        "AVG(vwap(O,C))" => math.avg(ta.vwap(open), ta.vwap(close))
        "OBV" => ta.obv // On Balance Volume
        "AccDist" => ta.accdist // Accumulation Distribution
        "PVT" => ta.pvt // Price Volume Trend
//_________________________________________________________________________________________
// Based on "Fancy Triple Moving Averages [BigBitsIO]" - Author: @BigBitsIO
// https://www.tradingview.com/script/7emR6ckb-Fancy-Triple-Moving-Averages-BigBitsIO/
// https://www.tradingview.com/script/UQAv1U0c-MA-Study-Different-Types-and-More-NeoButane/
//_________________________________________________________________________________________
MA_0Visible  = input.bool(false,    "⮩ Average (WMA21 + EMA20)") 

MA_1Visible  = input.bool(true,    "⮩ MA1", inline ="MA1") 
MA_1Period   = input.int(21,       "Period", minval=1, step=1, inline ="MA1")
MA_1Type     = input.string("WMA", "Type", options=["SMA", "EMA", "WMA", "DWMA", "NWMA", "VAMA", "VWMA", "DVWMA", "HMA", "ALMA", "LSMA", "Wilder", "RSS_WMA", "JMA", "COVWMA", "FRAMA", "ADX MA", "RSI EMA", "Zero Lag", "Tillson T3", "VIDYA", "KAMA", "CTI", "DEMA", "TEMA", "SWMA"], inline ="MA1")

MA_2Visible = input.bool(true,    "⮩ MA2", inline ="MA2") 
MA_2Period  = input.int(55,       "Period", minval=1, step=1, inline ="MA2")
MA_2Type    = input.string("EMA", "Type", options=["SMA", "EMA", "WMA", "DWMA", "NWMA", "VAMA", "VWMA", "DVWMA", "HMA", "ALMA", "LSMA", "Wilder", "RSS_WMA", "JMA", "COVWMA", "FRAMA", "ADX MA", "RSI EMA", "Zero Lag", "Tillson T3", "VIDYA", "KAMA", "CTI", "DEMA", "TEMA", "SWMA"], inline ="MA2")

MA_3Visible = input.bool(true,    "⮩ MA3", inline ="MA3") 
MA_3Period  = input.int(200,      "Period", minval=1, step=1, inline ="MA3")
MA_3Type    = input.string("SMA", "Type", options=["SMA", "EMA", "WMA", "DWMA", "NWMA", "VAMA", "VWMA", "DVWMA", "HMA", "ALMA", "LSMA", "Wilder", "RSS_WMA", "JMA", "COVWMA", "FRAMA", "ADX MA", "RSI EMA", "Zero Lag", "Tillson T3", "VIDYA", "KAMA", "CTI", "DEMA", "TEMA", "SWMA"], inline ="MA3")

Source1 = input.string("Close", "MA1 SRC", options=["VWAP", "Close", "Open", "HL2", "HLC3", "HLCC4", "OHLC4", "High", "Low", "vwap(Close)", "vwap(Open)", "vwap(High)", "vwap(Low)", "AVG(vwap(H,L))", "AVG(vwap(O,C))", "OBV", "AccDist", "PVT"], inline = "g1")
Source2 = input.string("Close", "MA2 SRC", options=["VWAP", "Close", "Open", "HL2", "HLC3", "HLCC4", "OHLC4", "High", "Low", "vwap(Close)", "vwap(Open)", "vwap(High)", "vwap(Low)", "AVG(vwap(H,L))", "AVG(vwap(O,C))", "OBV", "AccDist", "PVT"], inline = "g1")
Source3 = input.string("Close", "MA3 SRC", options=["VWAP", "Close", "Open", "HL2", "HLC3", "HLCC4", "OHLC4", "High", "Low", "vwap(Close)", "vwap(Open)", "vwap(High)", "vwap(Low)", "AVG(vwap(H,L))", "AVG(vwap(O,C))", "OBV", "AccDist", "PVT"], inline = "g1")

MA_1Strategy = input.string("3-MA", "▷ MA1 ⮩ Strategy Color", options=["None", "3-MA", "SuperTrend", "IchimokuTrend"], inline ="strag")
MA_abc_Type  = input.string("EMA",  "Type", options=["SMA", "EMA", "WMA", "DWMA", "NWMA", "VAMA", "VWMA", "DVWMA", "HMA", "ALMA", "LSMA", "Wilder", "RSS_WMA", "JMA", "COVWMA", "FRAMA", "Zero Lag", "Tillson T3", "VIDYA", "KAMA", "CTI", "DEMA", "TEMA", "SWMA"], inline ="strag")
MA_a_Period  = input.int(4,  "Fast",   minval=1, step=1, inline ="MA")
MA_b_Period  = input.int(9,  "Middle", minval=1, step=1, inline ="MA")
MA_c_Period  = input.int(18, "Slow",   minval=1, step=1, inline ="MA")
 
MA_2Strategy = input.string("SuperTrend", "▷ MA2 ⮩ Strategy Color", options=["None", "3-MA", "SuperTrend"], inline ="strag2")
MA_abc2_Type = input.string("EMA",        "Type", options=["SMA", "EMA", "WMA", "DWMA", "NWMA", "VAMA", "VWMA", "DVWMA", "HMA", "ALMA", "LSMA", "Wilder", "RSS_WMA", "JMA", "COVWMA", "FRAMA", "Zero Lag", "Tillson T3", "VIDYA", "KAMA", "CTI", "DEMA", "TEMA", "SWMA"], inline ="strag2")
MA_a2_Period = input.int(3,   "Fast",   minval=1, step=1, inline ="M2")
MA_b2_Period = input.int(13,  "Middle", minval=1, step=1, inline ="M2")
MA_c2_Period = input.int(144, "Slow",   minval=1, step=1, inline ="M2")

MA_4Visible    = input.bool(false,   "⮩ MA4", inline ="MA4")
MA_4Period     = input.int(20,       "Period", minval=1, step=1, inline ="MA4")
MA_4Type       = input.string("EMA", "Type", options=["SMA", "EMA", "WMA", "DWMA", "NWMA", "VAMA", "VWMA", "DVWMA", "HMA", "ALMA", "LSMA", "Wilder", "RSS_WMA", "JMA", "COVWMA", "FRAMA", "ADX MA", "RSI EMA", "Zero Lag", "Tillson T3", "VIDYA", "KAMA", "CTI", "DEMA", "TEMA", "SWMA"], inline ="MA4")

MA_5Visible    = input.bool(false,   "⮩ MA5", inline ="MA5")
MA_5Period     = input.int(50,       "Period", minval=1, step=1, inline ="MA5")
MA_5Type       = input.string("SMA", "Type", options=["SMA", "EMA", "WMA", "DWMA", "NWMA", "VAMA", "VWMA", "DVWMA", "HMA", "ALMA", "LSMA", "Wilder", "RSS_WMA", "JMA", "COVWMA", "FRAMA", "ADX MA", "RSI EMA", "Zero Lag", "Tillson T3", "VIDYA", "KAMA", "CTI", "DEMA", "TEMA", "SWMA"], inline ="MA5")

MA_6Visible    = input.bool(false,   "⮩ MA6", inline ="MA6")
MA_6Period     = input.int(30,       "Period", minval=1, step=1, inline ="MA6")
MA_6Type       = input.string("WMA", "Type", options=["SMA", "EMA", "WMA", "DWMA", "NWMA", "VAMA", "VWMA", "DVWMA", "HMA", "ALMA", "LSMA", "Wilder", "RSS_WMA", "JMA", "COVWMA", "FRAMA", "ADX MA", "RSI EMA", "Zero Lag", "Tillson T3", "VIDYA", "KAMA", "CTI", "DEMA", "TEMA", "SWMA"], inline ="MA6")

Source4 = input.string("Close", "MA4 SRC", options=["VWAP", "Close", "Open", "HL2", "HLC3", "HLCC4", "OHLC4", "High", "Low", "vwap(Close)", "vwap(Open)", "vwap(High)", "vwap(Low)", "AVG(vwap(H,L))", "AVG(vwap(O,C))", "OBV", "AccDist", "PVT"], inline = "g2")
Source5 = input.string("Close", "MA5 SRC", options=["VWAP", "Close", "Open", "HL2", "HLC3", "HLCC4", "OHLC4", "High", "Low", "vwap(Close)", "vwap(Open)", "vwap(High)", "vwap(Low)", "AVG(vwap(H,L))", "AVG(vwap(O,C))", "OBV", "AccDist", "PVT"], inline = "g2")
Source6 = input.string("Close", "MA6 SRC", options=["VWAP", "Close", "Open", "HL2", "HLC3", "HLCC4", "OHLC4", "High", "Low", "vwap(Close)", "vwap(Open)", "vwap(High)", "vwap(Low)", "AVG(vwap(H,L))", "AVG(vwap(O,C))", "OBV", "AccDist", "PVT"], inline = "g2")
MA_1Source = get_src(Source1)
MA_2Source = get_src(Source2)
MA_3Source = get_src(Source3)
MA_4Source = get_src(Source4)
MA_5Source = get_src(Source5)
MA_6Source = get_src(Source6)
MA_4Resolution = input.string("11 1D", "MA4 Res", options=["00 Current", "01 1m", "02 3m", "03 5m", "04 15m", "05 30m", "06 45m", "07 1h", "08 2h", "09 3h", "10 4h", "11 1D", "12 1W", "13 1M"], inline = "g2r")
MA_5Resolution = input.string("11 1D", "MA5 Res", options=["00 Current", "01 1m", "02 3m", "03 5m", "04 15m", "05 30m", "06 45m", "07 1h", "08 2h", "09 3h", "10 4h", "11 1D", "12 1W", "13 1M"], inline = "g2r")
MA_6Resolution = input.string("12 1W", "MA6 Res", options=["00 Current", "01 1m", "02 3m", "03 5m", "04 15m", "05 30m", "06 45m", "07 1h", "08 2h", "09 3h", "10 4h", "11 1D", "12 1W", "13 1M"], inline = "g2r")
MA_4off = input.int(0, "4 Offset", minval=-200, maxval=200, inline = "g2off")
MA_5off = input.int(0, "5 Offset", minval=-200, maxval=200, inline = "g2off")
MA_6off = input.int(0, "6 Offset", minval=-200, maxval=200, inline = "g2off")

// Input - Bollinger Bands
BB_Visible = input.bool(false,     "⮩ Visible", group ="Bollinger Bands")
length_BB  = input.int(20,         "Length", minval=1, inline ="bb", group ="Bollinger Bands")
BB_Type    = input.string("SMA",   "Type", inline ="bb", group ="Bollinger Bands", options=["SMA", "EMA", "WMA", "DWMA", "NWMA", "VAMA", "VWMA", "DVWMA", "HMA", "ALMA", "LSMA", "Wilder", "RSS_WMA", "JMA", "COVWMA", "FRAMA", "ADX MA", "RSI EMA", "Zero Lag", "Tillson T3", "VIDYA", "KAMA", "CTI", "DEMA", "TEMA", "SWMA"])
Source_BB  = input.string("Close", "Source", inline ="bb", group ="Bollinger Bands", options=["VWAP", "Close", "Open", "HL2", "HLC3", "HLCC4", "OHLC4", "High", "Low", "vwap(Close)", "vwap(Open)", "vwap(High)", "vwap(Low)", "AVG(vwap(H,L))", "AVG(vwap(O,C))", "OBV", "AccDist", "PVT"])
src_BB     = get_src(Source_BB)
mult_BB    = input.float(2.0,  "Multiplier", minval=0.001, maxval=50, inline ="mx", group ="Bollinger Bands")
show_bands = input.bool(false, "▷ Show Extra Bands", inline ="mx", group ="Bollinger Bands")
mult_KC    = input.float(1.25, "Keltner\'s Channel MultFactor", step=0.25, inline ="kc", group ="Bollinger Bands")
True_Range = input.bool(true,  "Use TrueRange", inline ="kc", group ="Bollinger Bands")
show_disp  = input.bool(false, "Show dispersion", inline="disp", group ="Bollinger Bands")
dispersion = input.float(0.1,  "", minval=0.01, maxval=1, step=0.01, inline="disp", group ="Bollinger Bands")

// Input - Parabolic SAR
PSAR_Visible = input.bool(false,  "⮩ Visible",  group ="Parabolic SAR")
start        = input.float(0.02,  "Start",     step=0.001, inline ="sar", group ="Parabolic SAR")
increment    = input.float(0.02,  "Increment", step=0.001, inline ="sar", group ="Parabolic SAR")
maximum      = input.float(0.2,   "Maximum",   step=0.01,  inline ="sar", group ="Parabolic SAR")
showsignals  = input.bool(true,   "Show Signals", inline ="Opc SAR", group ="Parabolic SAR")
highlighting = input.bool(true,   "Highlighter",  inline ="Opc SAR", group ="Parabolic SAR")

// Volume Weighted Colored Bars
VBCB_Visible  = input.bool(false, "⮩ Visible", group ="Volume Weighted Colored Bars")
vbcbLength    = input.int(21,     "Volume MA Length", minval=1, inline ="v1", group ="Volume Weighted Colored Bars")
v_show_last   = input.int(233,    "Plotting Length", inline ="v1", group ="Volume Weighted Colored Bars")
vwcbUpper     = input.float(1.5,    "Upper Theshold", minval = 0.1, step = .1, inline ="v2", group ="Volume Weighted Colored Bars")
vwcbLower     = input.float(.5,   "Lower Theshold", minval = 0.1, step = .1, inline ="v2", group ="Volume Weighted Colored Bars")

// Input - Linear Regression (Logarithmic)
LR_Visible  = input.bool(false,   "⮩ Visible", group ="Linear Regression (log)")
lenLR       = input.int(100,      "Count", minval=10, maxval=300, inline ="lr", group ="Linear Regression (log)")
sourceLR    = input.source(close, "Source", inline ="lr", group ="Linear Regression (log)")
upperMult   = input.float(2.0,    "Upper Deviation", inline ="devi", group ="Linear Regression (log)")
lowerMult   = input.float(-2.0,   "Lower Deviation", inline ="devi", group ="Linear Regression (log)")
useUpperDev = input.bool(true,    "Use Upper Deviation", group ="Linear Regression (log)")
useLowerDev = input.bool(true,    "Use Lower Deviation", group ="Linear Regression (log)")
showPearson = input.bool(false,   "Show Pearson`s R", group ="Linear Regression (log)")
extendLines = input.bool(false,   "Extend Lines", group ="Linear Regression (log)")

// Input - Laguerre Average
LMA_Visible   = input.bool(false,   "⮩ Visible", group ="Laguerre Average")
src_LMA       = input.string("HL2", "Source", options=["VWAP", "Close", "Open", "HL2", "HLC3", "HLCC4", "OHLC4", "High", "Low", "vwap(Close)", "vwap(Open)", "vwap(High)", "vwap(Low)", "AVG(vwap(H,L))", "AVG(vwap(O,C))"], inline ="L1", group ="Laguerre Average")
src_L         = get_src(src_LMA)
Gamma         = input.float(0.77, inline ="L1", group ="Laguerre Average")
useCurrentRes = input.bool(true,    "▷ Use Current Chart Resolution?", inline ="L2", group ="Laguerre Average")
resCustom     = input.timeframe("", "Time Frame", inline ="L2", group ="Laguerre Average")
res_LMA       = useCurrentRes ? timeframe.period : resCustom
sd            = input.bool(true, "Show dots?", inline ="L3", group ="Laguerre Average")
ccol          = input.bool(true, "Change Color?", inline ="L3", group ="Laguerre Average")
//______________________________________________________________________________
//______________________________________________________________________________
// ALMA - Arnaud Legoux Moving Average of @kurtsmock
enhanced_alma(_series, _length, _offset, _sigma) =>
    length      = int(_length) // Floating point protection
    numerator   = 0.0
    denominator = 0.0 
    m = _offset * (length - 1)
    s = length / _sigma
    for i=0 to length-1
        weight       = math.exp(-((i-m)*(i-m)) / (2 * s * s))
        numerator   := numerator   + weight * _series[length - 1 - i]
        denominator := denominator + weight
    numerator / denominator

// Kaufman's Adaptive Moving Average
kama(x, t)=>
    fast = 0.666  // KAMA Fast End
    slow = 0.0645 // KAMA Slow End
    dist   = math.abs(x[0] - x[1])
    signal = math.abs(x - x[t])
    noise  = math.sum(dist, t)
    effr   = noise!=0 ? signal/noise : 1
    sc     = math.pow(effr*(fast - slow) + slow,2)
    KAma   = x
    KAma  := nz(KAma[1]) + sc*(x - nz(KAma[1]))

// Jurik Moving Average of @everget
jma(src, length, power, phase) => 
    phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : phase / 100 + 1.5
    beta = 0.45 * (length - 1) / (0.45 * (length - 1) + 2)
    alpha = math.pow(beta, power)
    Jma = 0.0
    e0 = 0.0
    e0 := (1 - alpha) * src + alpha * nz(e0[1])
    e1 = 0.0
    e1 := (src - e0) * (1 - beta) + beta * nz(e1[1])
    e2 = 0.0
    e2 := (e0 + phaseRatio * e1 - nz(Jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
    Jma := e2 + nz(Jma[1])
    Jma

cti(sm, src, cd) =>
    di = (sm - 1.0) / 2.0 + 1.0
    c1 = 2 / (di + 1.0)
    c2 = 1 - c1
    c3 = 3.0 * (cd * cd + cd * cd * cd)
    c4 = -3.0 * (2.0 * cd * cd + cd + cd * cd * cd)
    c5 = 3.0 * cd + 1.0 + cd * cd * cd + 3.0 * cd * cd
    i1 = 0.0
    i2 = 0.0
    i3 = 0.0
    i4 = 0.0
    i5 = 0.0
    i6 = 0.0
    i1 := c1*src + c2*nz(i1[1])
    i2 := c1*i1 + c2*nz(i2[1])
    i3 := c1*i2 + c2*nz(i3[1])
    i4 := c1*i3 + c2*nz(i4[1])
    i5 := c1*i4 + c2*nz(i5[1])
    i6 := c1*i5 + c2*nz(i6[1])
    bfr = -cd*cd*cd*i6 + c3*(i5) + c4*(i4) + c5*(i3)
    bfr

T3ma(src,Len) =>
    a = 0.618
    e1 = ta.ema(src, Len)
    e2 = ta.ema(e1, Len)
    e3 = ta.ema(e2, Len)
    e4 = ta.ema(e3, Len)
    e5 = ta.ema(e4, Len)
    e6 = ta.ema(e5, Len)
    C1 = -a*a*a
    C2 = 3*a*a+3*a*a*a
    C3 = -6*a*a-3*a-3*a*a*a
    C4 = 1+3*a+a*a*a+3*a*a
    C1*e6+C2*e5+C3*e4+C4*e3

VIDYA(src,Len) =>
    mom = ta.change(src)
    upSum = math.sum(math.max(mom, 0), Len)
    downSum = math.sum(-math.min(mom, 0), Len)
    out = (upSum - downSum) / (upSum + downSum)
    cmo = math.abs(out)
    alpha = 2 / (Len + 1)
    vidya = 0.0
    vidya := src * alpha * cmo + nz(vidya[1]) * (1 - alpha * cmo)
    vidya

// ZLEMA: Zero Lag
zema(_src, _len) =>
    _alpha = (_len - 1) / 2
    _zlema0 = (_src + (_src - _src[_alpha]))
    _zlemaF = ta.ema(_zlema0, _len)

// EMA RSI Adaptive of @glaz
rsi_ema(src, period) =>
    RsiPeriod = 14
    ema = 0.0
    RSvoltl = math.abs(ta.rsi(close, RsiPeriod)-50)+1.0
    multi   = (5.0+100.0/RsiPeriod) / (0.06+0.92*RSvoltl+0.02*math.pow(RSvoltl,2))
    pdsx    = multi*period
    alpha   = 2.0 /(1.0+pdsx)
    ema     := nz(ema[1])+alpha*(ta.sma(close, period)-nz(ema[1]))
    ema

// ADX Weighted Moving Average of @Duyck 
adx_weighted_ma(_src, _period) =>
    [_diplus, _diminus, _adx] = ta.dmi(17, 14)
    _vol_sum  = 0.0
    _adx_sum  = 0.0
    for i = 0 to _period
        _vol_sum  := _src[i] * _adx[i] + _vol_sum
        _adx_sum  := _adx[i] + _adx_sum 
    _volwma   = _vol_sum / _adx_sum

// COVWMA - Coefficient of Variation Weighted Moving Average of @DonovanWall
covwma(a, b) =>
    cov    = ta.stdev(a, b) / ta.sma(a, b)
    cw     = a*cov
    covwma = math.sum(cw, b) / math.sum(cov, b)

// FRAMA - Fractal Adaptive Moving Average of @DonovanWall
frama(a, b) =>
    w = -4.6 // Coefficient
    frama = 0.0
    n3    = (ta.highest(high, b) - ta.lowest(low, b))/b
    hd2   = ta.highest(high, b/2)
    ld2   = ta.lowest(low, b/2)
    n2    = (hd2 - ld2)/(b/2)
    n1    = (hd2[b/2] - ld2[b/2])/(b/2)
    dim   = (n1 > 0) and (n2 > 0) and (n3 > 0) ? (math.log(n1 + n2) - math.log(n3))/math.log(2) : 0
    alpha = math.exp(w*(dim - 1))
    sc    = (alpha < 0.01 ? 0.01 : (alpha > 1 ? 1 : alpha))
    frama := ta.cum(1)<=2*b ? a : (a*sc) + nz(frama[1])*(1 - sc)
    frama

// VAMA - Volume Adjusted Moving Average of @allanster
vama(_src,_len,_fct,_rul,_nvb) =>                             // vama(source,length,factor,rule,sample)
    tvb = 0, tvb := _nvb == 0 ? nz(tvb[1]) + 1 : _nvb         // total volume bars used in sample            
    tvs = _nvb == 0 ? ta.cum(volume) : math.sum(volume, _nvb) // total volume in sample
    v2i = volume / ((tvs / tvb) * _fct)                       // ratio of volume to increments of volume                                                  
    wtd = _src*v2i                                            // weighted prices 
    nmb = 1                                                   // initialize number of bars summed back               
    wtdSumB = 0.0                                             // initialize weighted prices summed back
    v2iSumB = 0.0                                             // initialize ratio of volume to increments of volume summed back
    for i = 1 to _len * 10                                    // set artificial cap for strict to VAMA length * 10 to help reduce edge case timeout errors
        strict = _rul ? false : i == _len                     // strict rule N bars' v2i ratios >= vama length, else <= vama length
        wtdSumB := wtdSumB + nz(wtd[i-1])                     // increment number of bars' weighted prices summed back
        v2iSumB := v2iSumB + nz(v2i[i-1])                     // increment number of bars' v2i's summed back
        if v2iSumB >= _len or strict                          // if chosen rule met
            break                                             // break (exit loop)
        nmb := nmb + 1                                        // increment number of bars summed back counter
    nmb                                                       // number of bars summed back to fulfill volume requirements or vama length
    wtdSumB                                                   // number of bars' weighted prices summed back
    v2iSumB                                                   // number of bars' v2i's summed back
    vama = (wtdSumB - (v2iSumB - _len) * _src[nmb]) / _len    // volume adjusted moving average

// New WMA
NWMA(_src, _n1) =>
    fast   = int(_n1 / 2)
    lambda = _n1 / fast
    alpha  = lambda * (_n1 - 1) / (_n1 - lambda)
    ma1    = ta.wma(_src, _n1)
    ma2    = ta.wma(ma1, fast)
    nwma   = (1 + alpha) * ma1 - alpha * ma2

// VWMA with Tick Volume
enhanced_vwma(_series, _length) =>
    tick     = syminfo.mintick
    rng      = close - open
    tickrng  = tick
    tickrng := math.abs(rng) < tick ? nz(tickrng[1]) : rng
    tickvol  = math.abs(tickrng)/tick
    vol = nz(volume) == 0 ? tickvol : volume    
    vmp  = _series * vol
    VWMA = math.sum(vmp, _length) / math.sum(vol, _length)
    VWMA

// RSS_WMA of @RedKTrader
f_LazyLine(_data, _length) =>
    w1 = 0,     w2 = 0,     w3 = 0
    L1 = 0.0,   L2 = 0.0,   L3 = 0.0
    w = _length / 3

    if _length > 2
        w2 := math.round(w)
        w1 := math.round((_length - w2) / 2)
        w3 := int((_length - w2) / 2)

        L1 := ta.wma(_data, w1)
        L2 := ta.wma(L1, w2)
        L3 := ta.wma(L2, w3)
        
    else
        L3 := _data
        
    L3 

ma(MAType, MASource, MAPeriod) =>
    switch MAType
        "SMA" => ta.sma(MASource, MAPeriod)
        "EMA" => ta.ema(MASource, MAPeriod)
        "WMA" => ta.wma(MASource, MAPeriod)        
        "HMA" => ta.hma(MASource, MAPeriod)
        "DEMA" => e = ta.ema(MASource, MAPeriod), 2 * e - ta.ema(e, MAPeriod)
        "TEMA" => e = ta.ema(MASource, MAPeriod), 3 * (e - ta.ema(e, MAPeriod)) + ta.ema(ta.ema(e, MAPeriod), MAPeriod)
        "VWMA" => enhanced_vwma(MASource, MAPeriod) //ta.vwma(MASource, MAPeriod)
        "ALMA" => enhanced_alma(MASource, MAPeriod, .85, 6) //ta.alma(MASource, MAPeriod, .85, 6)
        "CTI" => cti(MAPeriod, MASource, 0)
        "KAMA" => kama(MASource, MAPeriod)
        "SWMA" => ta.swma(MASource)
        "JMA" => jma(MASource, MAPeriod, 2, 50)
        "LSMA" => ta.linreg(MASource, MAPeriod, 0) // Least Squares
        "Wilder" => wild = MASource, wild := nz(wild[1]) + (MASource - nz(wild[1])) / MAPeriod
        "Tillson T3" => T3ma(MASource, MAPeriod)
        "VIDYA" => VIDYA(MASource, MAPeriod)
        "DWMA" => ta.wma(ta.wma(MASource, MAPeriod), MAPeriod) // Double Weighted Moving Average
        "DVWMA" => ta.vwma(ta.vwma(MASource, MAPeriod), MAPeriod) // Double Volume-Weighted Moving Average            
        "Zero Lag" => zema(MASource, MAPeriod)
        "RSI EMA" => rsi_ema(MASource, MAPeriod)
        "ADX MA" => adx_weighted_ma(MASource, MAPeriod)
        "COVWMA" => covwma(MASource, MAPeriod)
        "FRAMA" => frama(MASource, MAPeriod)
        "VAMA" => vama(MASource, MAPeriod, 0.67, true, 0)
        "NWMA" => NWMA(MASource, MAPeriod)
        "RSS_WMA" => f_LazyLine(MASource, MAPeriod)

res(MAResolution) =>
    switch MAResolution
        "00 Current" => timeframe.period
        "01 1m" => "1"
        "02 3m" => "3"
        "03 5m" => "5"
        "04 15m" => "15"
        "05 30m" => "30"
        "06 45m" => "45"
        "07 1h" => "60"
        "08 2h" => "120"
        "09 3h" => "180"
        "10 4h" => "240"
        "11 1D" => "1D"
        "12 1W" => "1W"
        "13 1M" => "1M"

color_lavender     = #8080FF 
color_coral        = #FF8080 
color_black        = color.new(color.black, 10)
color_fuchsia      = #FF00FF // Color MA 4
color_hanpurple    = #6600FF // Color MA 5
color_chartreuse   = #80FF00 // Color MA 6
color_redorange    = #FF4000 

// Strategy 3-MA
// When the color is green, this is a bullish zone. 
// When the color is red, this is a bearish zone. 
// When the color is red, this is a bearish zone. 
f_color_3ma(Type, Period1, Period2, Period3) =>
    ma_v = ma(Type, close, Period1) 
    ma_a = ma(Type, close, Period2) 
    ma_r = ma(Type, close, Period3)
    bulls = ma_v >= ma_a and ma_a > ma_r 
    bears = ma_v < ma_a and ma_a < ma_r
    color_3 = bulls ? color.lime : bears ? color.red : color.yellow   
 
color_3ma_m1 = f_color_3ma(MA_abc_Type, MA_a_Period, MA_b_Period, MA_c_Period)     
color_3ma_m2 = f_color_3ma(MA_abc2_Type, MA_a2_Period, MA_b2_Period, MA_c2_Period)

//______________________________________________________________________________
// Based on "Pivot Point Supertrend" - Author: @LonesomeTheBlue
// https://www.tradingview.com/script/L0AIiLvH-Pivot-Point-Supertrend/
//______________________________________________________________________________
prd    = 2   // Pivot Point Period
Factor = 3   // ATR Factor
Pd     = 10  // ATR Period
// Get Pivot High/Low
float ph = ta.pivothigh(prd, prd)
float pl = ta.pivotlow(prd, prd)
// Calculate the Center line using pivot points
var float center = na
float lastpp = ph ? ph : pl ? pl : na
if lastpp
    if na(center)
        center := lastpp
    else
        center := (center * 2 + lastpp) / 3 // Weighted calculation
// Upper/Lower bands calculation
Up = center - (Factor * ta.atr(Pd))
Dn = center + (Factor * ta.atr(Pd))
// Get the trend
float TUp   = na
float TDown = na
Trend = 0
TUp   := close[1] > TUp[1]   ? math.max(Up, TUp[1])   : Up
TDown := close[1] < TDown[1] ? math.min(Dn, TDown[1]) : Dn
Trend := close > TDown[1]    ? 1 : close < TUp[1] ? -1 : nz(Trend[1], 1)
Trailingsl = Trend == 1 ? TUp : TDown
color_SuperTrend = Trend == 1 and nz(Trend[1]) == 1 ? #00C0FF : Trend == -1 and nz(Trend[1]) == -1 ? #FF4000 : color.yellow

// Ichimoku Trend and MFI
conversionLine = math.avg(ta.lowest(9), ta.highest(9))
baseLine       = math.avg(ta.lowest(26), ta.highest(26))
ssa            = math.avg(conversionLine, baseLine)
ssb            = math.avg(ta.lowest(52), ta.highest(52))
valor_mfi  = math.avg(ta.mfi(hlc3, 14), ta.rsi(close, 14))
bull_Ichi  = close > ssa[26] and close > ssb[26] and valor_mfi >= 50
bear_Ichi  = close < ssa[26] and close < ssb[26] and valor_mfi < 50
color_Ichi = bull_Ichi ? color.lime : bear_Ichi ? color.red : color.yellow

// Color MA 1
color_MA1 = color_redorange 
if MA_1Strategy == "None"
    na
else if MA_1Strategy == "3-MA"
    color_MA1 := color_3ma_m1
else if MA_1Strategy == "SuperTrend"
    color_MA1 := color_SuperTrend
else if MA_1Strategy == "IchimokuTrend"
    color_MA1 := color_Ichi

// Color MA 2
color_MA2 = color_coral 
if MA_2Strategy == "None"
    na
else if MA_2Strategy == "3-MA"
    color_MA2 := color_3ma_m2
else if MA_2Strategy == "SuperTrend"
    color_MA2 := color_SuperTrend

// Color MA 3
color_MA3 = color_lavender

// PLOT - MA
// Average (WMA21 + EMA20)
MA_0 = (ta.wma(close, 21) + ta.ema(close, 20))/2
color_MA0 = MA_0 > MA_0[1] ? #15FF00 : #2C6C2F
plot(MA_0Visible ? MA_0 : na, "Average(WMA+EMA)", color_MA0, 2)

MA_1 = ma(MA_1Type, MA_1Source, MA_1Period)
plot(MA_1Visible ? MA_1 : na, color=color_MA1, linewidth=2, title="MA1")
plot(MA_1Visible ? MA_1[MA_1Period-1] : na, color=color_black, linewidth=2, title="MA1 Trail", offset=((MA_1Period-1)*-1))

MA_2 = ma(MA_2Type, MA_2Source, MA_2Period)
plot(MA_2Visible ? MA_2 : na, color=color_MA2, linewidth=1, title="MA2")
plot(MA_2Visible ? MA_2[MA_2Period-1] : na, color=color_black, linewidth=2, title="MA2 Trail", offset=((MA_2Period-1)*-1))

MA_3 = ma(MA_3Type, MA_3Source, MA_3Period)
plot(MA_3Visible ? MA_3 : na, color=color_MA3, linewidth=1, title="MA3")
plot(MA_3Visible ? MA_3[MA_3Period-1] : na, color=color_black, linewidth=2, title="MA3 Trail", offset=((MA_3Period-1)*-1))

// https://www.tradingview.com/pine-script-reference/#fun_security
MA_4 = request.security(syminfo.tickerid, res(MA_4Resolution), ma(MA_4Type, MA_4Source, MA_4Period))
plot(MA_4Visible ? MA_4 : na, color=color_fuchsia, linewidth=2, title="MA4", offset=MA_4off)

MA_5 = request.security(syminfo.tickerid, res(MA_5Resolution), ma(MA_5Type, MA_5Source, MA_5Period))
plot(MA_5Visible ? MA_5 : na, color=color_hanpurple, linewidth=2, title="MA5", offset=MA_5off)

MA_6 = request.security(syminfo.tickerid, res(MA_6Resolution), ma(MA_6Type, MA_6Source, MA_6Period))
plot(MA_6Visible ? MA_6 : na, color=color_chartreuse, linewidth=2, title="MA6", offset=MA_6off)

// Forecasting - forcasted prices are calculated using our MAType and MASource for the MAPeriod - the last X candles.
//              it essentially replaces the oldest X candles, with the selected source * X candles
MAForecast1 = MA_1Period > 1 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_1Type, MA_1Source, MA_1Period - 1)) * (MA_1Period - 1) + ((MA_1Source * 1) )) / MA_1Period : na
MAForecast2 = MA_1Period > 2 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_1Type, MA_1Source, MA_1Period - 2)) * (MA_1Period - 2) + ((MA_1Source * 2) )) / MA_1Period : na
MAForecast3 = MA_1Period > 3 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_1Type, MA_1Source, MA_1Period - 3)) * (MA_1Period - 3) + ((MA_1Source * 3) )) / MA_1Period : na
MAForecast4 = MA_1Period > 4 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_1Type, MA_1Source, MA_1Period - 4)) * (MA_1Period - 4) + ((MA_1Source * 4) )) / MA_1Period : na
MAForecast5 = MA_1Period > 5 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_1Type, MA_1Source, MA_1Period - 5)) * (MA_1Period - 5) + ((MA_1Source * 5) )) / MA_1Period : na

plot( MA_1Visible ? MAForecast1 : na, color=color_MA1, linewidth=1, style=plot.style_circles, title="MA1 F1", offset=1, show_last=1)
plot( MA_1Visible ? MAForecast2 : na, color=color_MA1, linewidth=1, style=plot.style_circles, title="MA1 F2", offset=2, show_last=1)
plot( MA_1Visible ? MAForecast3 : na, color=color_MA1, linewidth=1, style=plot.style_circles, title="MA1 F3", offset=3, show_last=1)
plot( MA_1Visible ? MAForecast4 : na, color=color_MA1, linewidth=1, style=plot.style_circles, title="MA1 F4", offset=4, show_last=1)
plot( MA_1Visible ? MAForecast5 : na, color=color_MA1, linewidth=1, style=plot.style_circles, title="MA1 F5", offset=5, show_last=1)

MA2Forecast1 = MA_2Period > 1 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_2Type, MA_2Source, MA_2Period - 1)) * (MA_2Period - 1) + ((MA_2Source * 1) )) / MA_2Period : na
MA2Forecast2 = MA_2Period > 2 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_2Type, MA_2Source, MA_2Period - 2)) * (MA_2Period - 2) + ((MA_2Source * 2) )) / MA_2Period : na
MA2Forecast3 = MA_2Period > 3 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_2Type, MA_2Source, MA_2Period - 3)) * (MA_2Period - 3) + ((MA_2Source * 3) )) / MA_2Period : na
MA2Forecast4 = MA_2Period > 4 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_2Type, MA_2Source, MA_2Period - 4)) * (MA_2Period - 4) + ((MA_2Source * 4) )) / MA_2Period : na
MA2Forecast5 = MA_2Period > 5 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_2Type, MA_2Source, MA_2Period - 5)) * (MA_2Period - 5) + ((MA_2Source * 5) )) / MA_2Period : na

plot( MA_2Visible ? MA2Forecast1 : na, color=color.gray, linewidth=1, style=plot.style_circles, title="MA2 F1", offset=1, show_last=1)
plot( MA_2Visible ? MA2Forecast2 : na, color=color.gray, linewidth=1, style=plot.style_circles, title="MA2 F2", offset=2, show_last=1)
plot( MA_2Visible ? MA2Forecast3 : na, color=color.gray, linewidth=1, style=plot.style_circles, title="MA2 F3", offset=3, show_last=1)
plot( MA_2Visible ? MA2Forecast4 : na, color=color.gray, linewidth=1, style=plot.style_circles, title="MA2 F4", offset=4, show_last=1)
plot( MA_2Visible ? MA2Forecast5 : na, color=color.gray, linewidth=1, style=plot.style_circles, title="MA2 F5", offset=5, show_last=1)

MA3Forecast1 = MA_3Period > 1 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_3Type, MA_3Source, MA_3Period - 1)) * (MA_3Period - 1) + ((MA_3Source * 1) )) / MA_3Period : na
MA3Forecast2 = MA_3Period > 2 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_3Type, MA_3Source, MA_3Period - 2)) * (MA_3Period - 2) + ((MA_3Source * 2) )) / MA_3Period : na
MA3Forecast3 = MA_3Period > 3 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_3Type, MA_3Source, MA_3Period - 3)) * (MA_3Period - 3) + ((MA_3Source * 3) )) / MA_3Period : na
MA3Forecast4 = MA_3Period > 4 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_3Type, MA_3Source, MA_3Period - 4)) * (MA_3Period - 4) + ((MA_3Source * 4) )) / MA_3Period : na
MA3Forecast5 = MA_3Period > 5 ? (request.security(syminfo.tickerid, timeframe.period, ma(MA_3Type, MA_3Source, MA_3Period - 5)) * (MA_3Period - 5) + ((MA_3Source * 5) )) / MA_3Period : na

plot( MA_3Visible ? MA3Forecast1 : na, color=color.gray, linewidth=1, style=plot.style_circles, title="MA3 F1", offset=1, show_last=1)
plot( MA_3Visible ? MA3Forecast2 : na, color=color.gray, linewidth=1, style=plot.style_circles, title="MA3 F2", offset=2, show_last=1)
plot( MA_3Visible ? MA3Forecast3 : na, color=color.gray, linewidth=1, style=plot.style_circles, title="MA3 F3", offset=3, show_last=1)
plot( MA_3Visible ? MA3Forecast4 : na, color=color.gray, linewidth=1, style=plot.style_circles, title="MA3 F4", offset=4, show_last=1)
plot( MA_3Visible ? MA3Forecast5 : na, color=color.gray, linewidth=1, style=plot.style_circles, title="MA3 F5", offset=5, show_last=1)

//_____________________________________________________________________________________________
//                                      Parabolic SAR 
//_____________________________________________________________________________________________
htclose = request.security(syminfo.tickerid, timeframe.period, close)

psar      = ta.sar(start, increment, maximum)
Trend_SAR = psar < htclose ? 1 : -1

//Plot line and fill
upPlot = plot(PSAR_Visible and Trend_SAR == 1  ? psar : na, title='Uptrend',   style=plot.style_circles, color=#12DA00, linewidth=1)
dnPlot = plot(PSAR_Visible and Trend_SAR == -1 ? psar : na, title='Downtrend', style=plot.style_circles, color=#FF0000, linewidth=1)
mPlot  = plot(PSAR_Visible ? ohlc4 : na, title="", style=plot.style_circles, linewidth=0, editable = false)
fillColor = PSAR_Visible and highlighting ? (Trend_SAR == 1  ? color.new(#12DA00, 90) : color.new(#CC0000, 90)) : na
fill(mPlot, upPlot, title="UpTrend Highligter",   color=fillColor)
fill(mPlot, dnPlot, title="DownTrend Highligter", color=fillColor)

//Plot Long Signal
buySignal = Trend_SAR == 1 and Trend_SAR[1] == -1
plotshape(PSAR_Visible and buySignal and showsignals ? psar : na, title="PSAR Buy", text="B", location=location.absolute, style=shape.labelup, size=size.tiny, color=#0EAE00, textcolor=color.white)

//Plot Short Signal
sellSignal = Trend_SAR == -1 and Trend_SAR[1] == 1
plotshape(PSAR_Visible and sellSignal and showsignals ? psar : na, title="PSAR Sell", text="S", location=location.absolute, style=shape.labeldown, size=size.tiny, color=#CC0000, textcolor=color.white)
 
//_____________________________________________________________________________________________
//                                       Bollinger Bands
//_____________________________________________________________________________________________
basis    = ma(BB_Type, src_BB, length_BB) 
stdDevBB = ta.stdev(src_BB, length_BB)
devBase  = mult_BB * stdDevBB
upperBB  = basis + devBase
lowerBB  = basis - devBase

disp_up   = basis + ((upperBB - lowerBB) * dispersion) 
disp_down = basis - ((upperBB - lowerBB) * dispersion)

devInc1 = (mult_BB + 0.5) * stdDevBB
devInc2 = (mult_BB + (0.5 * 2)) * stdDevBB

[_, upperKC, lowerKC] = ta.kc(src_BB, length_BB, mult_KC, True_Range)
sqzOn  = lowerBB > lowerKC and upperBB < upperKC
sqzOff = lowerBB < lowerKC and upperBB > upperKC
noSqz  = sqzOn == false and sqzOff == false

rojo   = color.new(#FF5500, 0)
rojo85 = color.new(#FF5500, 85)
rojo80 = color.new(#FF5500, 80)
azul   = color.new(#004EF7, 0)
azul85 = color.new(#004EF7, 85)
azul80 = color.new(#004EF7, 80)
color_Squeeze = sqzOn  or  noSqz ? #00FFBB : #88A7FE
color_Squeeze2 = sqzOn  or  noSqz ? color.new(#00FFBB, 90) : color.new(#88A7FE, 95)

plot(BB_Visible ? basis : na, "Basis", color_Squeeze, 2)
plot(BB_Visible ? basis[length_BB-1] : na, "Basis Trail", color_black, 2, offset=((length_BB-1)*-1))
p1 = plot(BB_Visible ? upperBB : na, "Upper", rojo)
p2 = plot(BB_Visible ? lowerBB : na, "Lower", azul)
fill(p1, p2, title = "BB Background", color = color_Squeeze2)
plot(BB_Visible ? upperBB[length_BB-1] : na, "Upper Trail", color_black, offset=((length_BB-1)*-1))
plot(BB_Visible ? lowerBB[length_BB-1] : na, "Lower Trail", color_black, offset=((length_BB-1)*-1))

plot(show_bands ? (basis + devInc1) : na, "Upper - Middle Band", rojo85, 2)
plot(show_bands ? (basis + devInc2) : na, "Upper - Top Band",    rojo80, 2)
plot(show_bands ? (basis - devInc1) : na, "Lower - Middle Band", azul85, 2)
plot(show_bands ? (basis - devInc2) : na, "Lower - Low Band",    azul80, 2)

p3 = plot(show_disp ? disp_up   : na, color=color_black)
p4 = plot(show_disp ? disp_down : na, color=color_black)
fill(p3, p4, title = "Dispersion Background", color = color.new(#FEDF88, 97))

BBForecast1 = length_BB > 1 ? (request.security(syminfo.tickerid, timeframe.period, ma(BB_Type, src_BB, length_BB - 1)) * (length_BB - 1) + ((src_BB * 1) )) / length_BB : na
BBForecast2 = length_BB > 2 ? (request.security(syminfo.tickerid, timeframe.period, ma(BB_Type, src_BB, length_BB - 2)) * (length_BB - 2) + ((src_BB * 2) )) / length_BB : na
BBForecast3 = length_BB > 3 ? (request.security(syminfo.tickerid, timeframe.period, ma(BB_Type, src_BB, length_BB - 3)) * (length_BB - 3) + ((src_BB * 3) )) / length_BB : na

plot(BB_Visible ? BBForecast1 : na, "BB F1", #9A9EEC, 1, plot.style_circles, offset=1, show_last=1)
plot(BB_Visible ? BBForecast2 : na, "BB F2", #9A9EEC, 1, plot.style_circles, offset=2, show_last=1)
plot(BB_Visible ? BBForecast3 : na, "BB F3", #9A9EEC, 1, plot.style_circles, offset=3, show_last=1)

//______________________________________________________________________________
// Volume Weighted Colored Bars by KIVANÇ ÖZBİLGİÇ
// https://www.tradingview.com/script/8RPiMMmn-Volume-Based-Coloured-Bars/
//______________________________________________________________________________
volMA = ta.sma(volume, vbcbLength)

vwcbColor = if close < open
    if      volume > volMA * vwcbUpper
        #FF0000 // Red
    else if volume < volMA * vwcbLower
        #820000 // Dark Red
else
    if      volume > volMA * vwcbUpper
        #3FFF5E // Screamin' Green
    else if volume < volMA * vwcbLower
        #208230 // Forest Green

barcolor(VBCB_Visible and nz(volume) ? vwcbColor : na, title = "Volume Weighted Colored Bars", show_last = v_show_last)

//______________________________________________________________________________________
// LMA (Laguerre) v2 - multi timeframe by TheLark
// https://www.tradingview.com/script/u3irwHjc-TheLark-LMA-Laguerre-v2-multi-timeframe/
//______________________________________________________________________________________
lag(g) =>
    L0 = 0.0
    L1 = 0.0
    L2 = 0.0
    L3 = 0.0
    L0 := (1 - g) * src_L + g * nz(L0[1])
    L1 := -g * L0 + nz(L0[1]) + g * nz(L1[1])
    L2 := -g * L1 + nz(L1[1]) + g * nz(L2[1])
    L3 := -g * L2 + nz(L2[1]) + g * nz(L3[1])
    f = (L0 + 2 * L1 + 2 * L2 + L3) / 6
    f

lma = request.security(syminfo.tickerid, res_LMA, lag(Gamma))
col = 0.0
col := ccol ? lma == lma[1] and col[1] == 1 ? 1 : 
   lma == lma[1] and col[1] == 2 ? 2 : lma > lma[1] ? 1 : 2 : 2

color_lag  = col < 2 ? #00CC96 : #FF3571
color_dots = col < 2 ? color.new(#00CC96, 60) : color.new(#FF3571, 60)
up = col < col[1] ? 1 : 0
down = col > col[1] ? 1 : 0

plot(LMA_Visible ? lma : na, title = "MT Laguerre", color = color_lag, linewidth = 2)
plot(LMA_Visible and sd and ta.cross(up, down) ? lma : na, style=plot.style_circles, linewidth = 7, color = color_dots)

//_____________________________________________________________________________________________
// Based on "Linear Regression (Log Scale)" - Author: @Forza
// https://www.tradingview.com/script/cxcEYTkE-Linear-Regression-Log-Scale/
//_____________________________________________________________________________________________
srcLR  = request.security(syminfo.tickerid, timeframe.period, math.log(sourceLR))
extend = extendLines ? extend.right : extend.none

calcSlope(src, len) =>
	if not barstate.islast or len <= 1
		[float(na), float(na), float(na)]
	else
		sumX = 0.0
		sumY = 0.0
		sumXSqr = 0.0
		sumXY = 0.0
		for i = 0 to len - 1
			val = src[i]
			per = i + 1.0
			sumX := sumX + per
			sumY := sumY + val
			sumXSqr := sumXSqr + per * per
			sumXY := sumXY + val * per
		slope = (len * sumXY - sumX * sumY) / (len * sumXSqr - sumX * sumX)
		average = sumY / len
		intercept = average - slope * sumX / len + slope
		[slope, average, intercept]

[s, aa, i] = calcSlope(srcLR, lenLR)
startPrice = i + s * (lenLR - 1)
endPrice = i
var line baseLineR = na
if LR_Visible and na(baseLineR) and not na(startPrice)
	baseLineR := line.new(bar_index - lenLR + 1, math.exp(startPrice), bar_index, math.exp(endPrice), width=2, extend=extend, color = rojo)
else
	line.set_xy1(baseLineR, bar_index - lenLR + 1, startPrice)
	line.set_xy2(baseLineR, bar_index, endPrice)
	na

calcDev(src, len, slope, average, intercept) =>
	upDev = 0.0
	dnDev = 0.0
	stdDevAcc = 0.0
	dsxx = 0.0
	dsyy = 0.0
	dsxy = 0.0
	periods = len - 1
	daY = intercept + (slope * periods) / 2
	val = intercept
	for i = 0 to periods
		price = high[i] - val
		if (price > upDev)
			upDev := price
		price := val - low[i]
		if (price > dnDev)
			dnDev := price
		price := src[i]
		dxt = price - average
		dyt = val - daY
		price := price - val
		stdDevAcc := stdDevAcc + price * price
		dsxx := dsxx + dxt * dxt
		dsyy := dsyy + dyt * dyt
		dsxy := dsxy + dxt * dyt
		val := val + slope
	stdDev = math.sqrt(stdDevAcc / (periods == 0 ? 1 : periods))
	pearsonR = dsxx == 0 or dsyy == 0 ? 0 : dsxy / math.sqrt(dsxx * dsyy)
	[stdDev, pearsonR, upDev, dnDev]

[stdDev, pearsonR, upDev, dnDev] = calcDev(srcLR, lenLR, s, aa, i)
upperStartPrice = startPrice + (useUpperDev ? upperMult * stdDev : upDev)
upperEndPrice = endPrice + (useUpperDev ? upperMult * stdDev : upDev)
var line upper = na
lowerStartPrice = startPrice + (useLowerDev ? lowerMult * stdDev : -dnDev)
lowerEndPrice = endPrice + (useLowerDev ? lowerMult * stdDev : -dnDev)
var line lower = na
if LR_Visible and na(upper) and not na(upperStartPrice)
	upper := line.new(bar_index - lenLR + 1, math.exp(upperStartPrice), bar_index, math.exp(upperEndPrice), width=1, extend=extend, color = azul)
else
	line.set_xy1(upper, bar_index - lenLR + 1, upperStartPrice)
	line.set_xy2(upper, bar_index, upperEndPrice)
	na
if LR_Visible and na(lower) and not na(lowerStartPrice)
	lower := line.new(bar_index - lenLR + 1, math.exp(lowerStartPrice), bar_index, math.exp(lowerEndPrice), width=1, extend=extend, color = azul)
else
	line.set_xy1(lower, bar_index - lenLR + 1, lowerStartPrice)
	line.set_xy2(lower, bar_index, lowerEndPrice)
	na
// Pearson`s R
var label r = na
transparent = color.new(color.white, 100)
label.delete(r[1])
if LR_Visible and showPearson and not na(pearsonR)
    r := label.new(bar_index - lenLR + 1, math.exp(lowerStartPrice), str.tostring(pearsonR, "#.#####"), color=transparent, textcolor = azul, size=size.normal, style=label.style_label_up)

//______________________________________________________________________________
// Based on "Volume Profile" - Author: @kv4coins
// https://www.tradingview.com/script/r3VrWAO4-Volume-Profile/ 
//______________________________________________________________________________
//// INPUTS 
VP_Visible    = input.bool(false, "⮩ Visible", group ="Volume Profile")
vp_lookback   = input.int(defval = 220, 
                     title   = "Volume Lookback Depth [10-500]", 
                     minval  = 10, 
                     maxval  = 500, group="Volume Profile")

vp_max_bars   = input.int(defval = 500, 
                     title   = "Number of Bars [10-500]",
                     minval  = 10, 
                     maxval  = 500, group="Volume Profile")

vp_bar_mult   = input.int(defval = 50, 
                     title   = "Bar Length Multiplier [10-100]",
                     minval  = 10, 
                     maxval  = 100, group="Volume Profile")

vp_bar_offset = input.int(defval = 55, 
                     title   = "Bar Horizontal Offset [0-100]", 
                     minval  = 0, 
                     maxval  = 100, group="Volume Profile")

vp_bar_width  = input.int(defval = 2, 
                     title   = "Bar Width [1-20]", 
                     minval  = 1, 
                     maxval  = 20, group="Volume Profile")

vp_delta_type = input.string(defval = "Both",
                     title   = "Delta Type",
                     options = ['Both', 'Bullish', 'Bearish'], group="Volume Profile")

vp_poc_show   = input.bool(defval = true, 
                     title   = "Show POC Line", 
                     group="Volume Profile")
 
vp_bar_color  = input.color(defval = color.new(#EFEFBF, 80) , 
                     title   = "Area Color", 
                     inline ="colVP", group="Volume Profile")

vp_poc_color  = input.color(defval = color.new(#B71C1C, 0), 
                     title   = "POC Color", 
                     inline ="colVP", group="Volume Profile")

//// VARIABLES
float vp_Vmax = 0.0
int vp_VmaxId = 0
int vp_N_BARS = vp_max_bars

var int vp_first = time

vp_a_P = array.new_float((vp_N_BARS + 1), 0.0)
vp_a_V = array.new_float(vp_N_BARS, 0.0)
vp_a_D = array.new_float(vp_N_BARS, 0.0)
vp_a_W = array.new_int(vp_N_BARS, 0)

//// CALCULATIONS
float vp_HH = ta.highest(high, vp_lookback)
float vp_LL = ta.lowest(low, vp_lookback)

if barstate.islast and VP_Visible
	float vp_HL = (vp_HH - vp_LL) / vp_N_BARS
    for j = 1 to (vp_N_BARS + 1)
        array.set(vp_a_P, (j-1), (vp_LL + vp_HL * j))
	for i = 0 to (vp_lookback - 1)
		int Dc = 0
		array.fill(vp_a_D, 0.0)
		for j = 0 to (vp_N_BARS - 1)
			float Pj = array.get(vp_a_P, j)
			if low[i] < Pj and high[i] > Pj and (vp_delta_type == "Bullish" ? 
			 close[i] >= open[i] : (vp_delta_type == "Bearish" ? close[i] <= open[i] : true))
				float Dj = array.get(vp_a_D, j)
				float dDj = Dj + nz(volume[i])
				array.set(vp_a_D, j, dDj)
				Dc := Dc + 1
		for j = 0 to (vp_N_BARS - 1)
			float Vj = array.get(vp_a_V, j)
			float Dj = array.get(vp_a_D, j)
			float dVj = Vj + ((Dc > 0) ? (Dj / Dc) : 0.0)
			array.set(vp_a_V, j, dVj)
	vp_Vmax := array.max(vp_a_V)
    vp_VmaxId := array.indexof(vp_a_V, vp_Vmax)
    for j = 0 to (vp_N_BARS - 1)
        float Vj = array.get(vp_a_V, j)
        int Aj = math.round(vp_bar_mult * Vj / vp_Vmax)
        array.set(vp_a_W, j, Aj)

//// PLOTING
if barstate.isfirst and VP_Visible
    vp_first := time
vp_change = ta.change(time)
vp_x_loc = timenow + math.round(vp_change * vp_bar_offset)

if barstate.islast and VP_Visible
    for ind = 0 to (vp_N_BARS - 1) by 1
        x1 = ((vp_VmaxId == ind) and vp_poc_show) ? math.max(time[vp_lookback], vp_first) : 
		 (timenow + math.round(vp_change * (vp_bar_offset - array.get(vp_a_W, ind))))
	    ys = array.get(vp_a_P, ind)
        line.new(x1     = x1, 
             y1     = ys, 
             x2     = vp_x_loc, 
             y2     = ys, 
             xloc   = xloc.bar_time, 
             extend = extend.none, 
             color  = (vp_VmaxId == ind ? vp_poc_color : vp_bar_color), 
             style  = line.style_solid, 
             width  = vp_bar_width)