Right Way Oscillator
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © diemock

//@version=4
study("Right Way Oscillator")

Theme =    input(title="  Theme", options=["Standard", "Classic", "Lemon", "Silver Surfer", "Watermelon", "Ethereal"], defval="Watermelon")


color1 = color.new(#26a69a, 75)
color2 = color.new(#ef5350, 75)
color3 = color.new(#43ff43, 75)
color4 = color.new(#ff0d0d, 75)
color5 = color.new(#ffff00, 75)
color6 = color.new(#00ff00, 75)
color7 = color.new(color.silver, 50)
color8 = color.new(#353535, 50)
color9 = color.new(#24e828, 75)
color10 = color.new(#ff357e, 75)
color11 = color.new(color.teal, 75)
color12 = color.new(color.purple, 75)

c1 = Theme == "Standard" ? color1 : Theme == "Classic" ? color3 : Theme == "Lemon" ? color5 : Theme == "Silver Surfer" ? color7 : Theme == "Watermelon" ? color9 : Theme == "Ethereal" ? color11 : na
c2 = Theme == "Standard" ? color2 : Theme == "Classic" ? color4 : Theme == "Lemon" ? color6 : Theme == "Silver Surfer" ? color8 : Theme == "Watermelon" ? color10 : Theme == "Ethereal" ? color12 : na


//------------VSLRT----------------
vslrt_src = input(defval = close, title = "Source")
len2 = 50
len1 = 20
// get short/long-term regression slope
slope_price = linreg(vslrt_src, len1, 0) - linreg(vslrt_src, len1, 1)
slope_price_lt = linreg(vslrt_src, len2, 0) - linreg(vslrt_src, len2, 1)

// get size of top/bottom/body of the candle
tw = high - max(open, close) 
bw = min(open, close) - low 
body = abs(close - open) 

//Calculate Buy/Sell Volume
_rate(cond) =>
    ret = 0.5 * (tw + bw + (cond ? 2 * body : 0)) / (tw + bw + body) 
    ret := na(ret) ? 0.5 : ret
    ret

// Calculate Regression Slope for Buy/Sell Volumes
_get_trend(len)=>   
    deltaup =  volume * _rate(open <= close) 
    deltadown = volume * _rate(open > close)
    
    slope_volume_up = linreg(deltaup, len, 0) - linreg(deltaup, len, 1)
    slope_volume_down = linreg(deltadown, len, 0) - linreg(deltadown, len, 1)
    [slope_volume_up, slope_volume_down]


[slope_volume_up, slope_volume_down] = _get_trend(len1)
// get buy/sell volume regression slopes for long term period
[slope_volume_up_lt, slope_volume_down_lt] = _get_trend(len2)

// coloring
col_VSLRT_lt = slope_price_lt > 0 ? slope_volume_up_lt > 0 ? slope_volume_up_lt > slope_volume_down_lt ? color.aqua : #006ec5 : #024478 : 
       slope_price_lt < 0 ? slope_volume_down_lt > 0 ? slope_volume_up_lt < slope_volume_down_lt ? #fa3939 : #CE7A00 : #663d00 :
       color.gray

weight_VSLRT_lt = slope_price_lt > 0 ? slope_volume_up_lt > 0 ? slope_volume_up_lt > slope_volume_down_lt ? 1 : 0.5 : 0.25 : 
       slope_price_lt < 0 ? slope_volume_down_lt > 0 ? slope_volume_up_lt < slope_volume_down_lt ? -1 : -0.5 : -0.25 :
       0       
       
// coloring
col_VSLRT = slope_price > 0 ? slope_volume_up > 0 ? slope_volume_up > slope_volume_down ? color.aqua : #006ec5 : #024478 : 
       slope_price < 0 ? slope_volume_down > 0 ? slope_volume_up < slope_volume_down ? #fa3939 : #CE7A00 : #663d00 :
       color.gray

weight_VSLRT = slope_price > 0 ? slope_volume_up > 0 ? slope_volume_up > slope_volume_down ? 1 : 0.5 : 0.25 : 
       slope_price < 0 ? slope_volume_down > 0 ? slope_volume_up < slope_volume_down ? -1 : -0.5 : -0.25 :
       0       
//------------VSLRT END----------------

//------------ATR----------------
Periods = input(title="ATR Period", type=input.integer, defval=10)
Multiplier = input(title="ATR Multiplier", type=input.float, step=0.1, defval=1.0)
Periods1 = input(title="ATR Period", type=input.integer, defval=12)
Multiplier1 = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
Periods2 = input(title="ATR Period", type=input.integer, defval=11)
Multiplier2 = input(title="ATR Multiplier", type=input.float, step=0.1, defval=2.0)
src = input(hl2, title="Source")
changeATR= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)

make_super(Periods, src, Multiplier, changeATR) =>

    atr2 = sma(tr, Periods)
    atr= changeATR ? atr(Periods) : atr2
    up=src-(Multiplier*atr)
    up1 = nz(up[1],up)
    up := close[1] > up1 ? max(up,up1) : up
    dn=src+(Multiplier*atr)
    dn1 = nz(dn[1], dn)
    dn := close[1] < dn1 ? min(dn, dn1) : dn
    trend = 1
    trend := nz(trend[1], trend)
    trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
    changeCond = trend != trend[1]
    [trend, trend[1], up, dn]

[trend, trend1, up, dn] = make_super(Periods, src, Multiplier, changeATR)
[trend_1, trend1_1, up_1, dn_1] = make_super(Periods1, src, Multiplier1, changeATR)
[trend_2, trend1_2, up_2, dn_2] = make_super(Periods2, src, Multiplier2, changeATR)

buySignal = trend == 1 and trend1 == -1
sellSignal = trend == -1 and trend1 == 1
buySignal_1 = trend_1 == 1 and trend1_1 == -1
sellSignal_1 = trend_1 == -1 and trend1_1 == 1
buySignal_2 = trend_2 == 1 and trend1_2 == -1
sellSignal_2 = trend_2 == -1 and trend1_2 == 1


count_up = 0
count_down = 0
if trend == 1
    count_up :=count_up + 1
else
    count_down :=count_down + 1

if trend_1 == 1
    count_up :=count_up + 1
else
    count_down :=count_down + 1
    
if trend_2 == 1
    count_up :=count_up + 1
else
    count_down :=count_down + 1
    
// coloring
col_ATR = count_up > count_down ? count_up > 2 ? color.aqua : #006ec5 :
       count_down > 1 ? count_down > 2 ? #fa3939 : #CE7A00 : 
       color.gray

weight_ATR = count_up > count_down ? count_up > 2 ? 1 : 0.5 :
       count_down > 1 ? count_down > 2 ? -1 : -0.5 :
       0         
//------------ATR END----------------



//------------------WT---------------
// PARAMETERS {

// WaveTrend
wtShow = true
wtBuyShow = true
wtGoldShow = true
wtSellShow = true
wtDivShow = true
vwapShow = true
wtChannelLen = 9
wtAverageLen = 12
wtMASource = hlc3
wtMALen = 3

// WaveTrend Overbought & Oversold lines
obLevel = 53
obLevel2 = 60
obLevel3 = 100
osLevel = -53
osLevel2 = -60
osLevel3 = -75

// Divergence WT
wtShowDiv = true
wtShowHiddenDiv = false
showHiddenDiv_nl = true
wtDivOBLevel = 45
wtDivOSLevel = -65

// Divergence extra range
wtDivOBLevel_addshow = true
wtDivOBLevel_add = 15
wtDivOSLevel_add = -40

// RSI+MFI
rsiMFIShow = true
rsiMFIperiod = 60
rsiMFIMultiplier = 150
rsiMFIPosY = 2.5

// RSI
rsiShow = false
rsiSRC = close
rsiLen = 14
rsiOversold = 30
rsiOverbought = 60

// Divergence RSI
rsiShowDiv = false
rsiShowHiddenDiv = false
rsiDivOBLevel = 60
rsiDivOSLevel = 30

// RSI Stochastic
stochShow = true
stochUseLog = true
stochAvg = false
stochSRC = close
stochLen = 14
stochRsiLen = 14
stochKSmooth = 3
stochDSmooth = 3

// Divergence stoch
stochShowDiv = false
stochShowHiddenDiv = false

// Schaff Trend Cycle
tcLine = false
tcSRC = close
tclength = 10
tcfastLength = 23
tcslowLength = 50
tcfactor = 0.5

// Sommi Flag
sommiFlagShow = false
sommiShowVwap = false
sommiVwapTF = 720
sommiVwapBearLevel = 0
sommiVwapBullLevel = 0
soomiFlagWTBearLevel = 0
soomiFlagWTBullLevel = 0
soomiRSIMFIBearLevel = 0
soomiRSIMFIBullLevel =0

// Sommi Diamond
sommiDiamondShow = false
sommiHTCRes = '60'
sommiHTCRes2 = '240'
soomiDiamondWTBearLevel = 0
soomiDiamondWTBullLevel = 0

// macd Colors
macdWTColorsShow = false
macdWTColorsTF = '240'

darkMode = input(false, title = 'Dark mode', type = input.bool)


// Colors
colorRed = #ff0000
colorPurple = #e600e6
colorGreen = #3fff00
colorOrange = #e2a400
colorYellow = #ffe500
colorWhite = #ffffff
colorPink = #ff00f0
colorBluelight = #31c0ff
colorBlue = #3142ff

colorWT1 = #90caf9
colorWT2 = #0d47a1

colorWT2_ = #131722

colormacdWT1a = #4caf58
colormacdWT1b = #af4c4c
colormacdWT1c = #7ee57e
colormacdWT1d = #ff3535

colormacdWT2a = #305630
colormacdWT2b = #310101
colormacdWT2c = #132213
colormacdWT2d = #770000

// } PARAMETERS


// FUNCTIONS {
  

        
// RSI+MFI
f_rsimfi(_period, _multiplier, _tf) => security(syminfo.tickerid, _tf, sma(((close - open) / (high - low)) * _multiplier, _period) - rsiMFIPosY)
   
// WaveTrend
f_wavetrend(src, chlen, avg, malen, tf) =>
    tfsrc = security(syminfo.tickerid, tf, src)
    esa = ema(tfsrc, chlen)
    de = ema(abs(tfsrc - esa), chlen)
    ci = (tfsrc - esa) / (0.015 * de)
    wt1 = security(syminfo.tickerid, tf, ema(ci, avg))
    wt2 = security(syminfo.tickerid, tf, sma(wt1, malen))
    wtVwap = wt1 - wt2
    wtOversold = wt2 <= osLevel
    wtOverbought = wt2 >= obLevel
    wtCross = cross(wt1, wt2)
    wtCrossUp = wt2 - wt1 <= 0
    wtCrossDown = wt2 - wt1 >= 0
    wtCrosslast = cross(wt1[2], wt2[2])
    wtCrossUplast = wt2[2] - wt1[2] <= 0
    wtCrossDownlast = wt2[2] - wt1[2] >= 0
    [wt1, wt2, wtOversold, wtOverbought, wtCross, wtCrossUp, wtCrossDown, wtCrosslast, wtCrossUplast, wtCrossDownlast, wtVwap]


 
// } FUNCTIONS  

// CALCULATE INDICATORS {



// RSI + MFI Area
rsiMFI = f_rsimfi(rsiMFIperiod, rsiMFIMultiplier, timeframe.period)
mfiMAperiod = input(8, "mfi MA period")
mfiMA = sma(rsiMFI, mfiMAperiod)

//rsiMFIColor = rsiMFI > 0 ? #3ee145 : #ff3d2e
// coloring

col_MFI = rsiMFI > 0 ?rsiMFI > mfiMA ? rsiMFI > rsiMFI[1] ? color.aqua : #006ec5 : #024478 : 
       rsiMFI < 0 ? rsiMFI < mfiMA ? rsiMFI < rsiMFI[1] ? #fa3939 : #CE7A00 : #663d00 :
       color.gray

weight_MFI = rsiMFI > 0 ?rsiMFI > mfiMA ? rsiMFI > rsiMFI[1] ? 1 : 0.5 : 0.25 : 
       rsiMFI < 0 ? rsiMFI < mfiMA ? rsiMFI < rsiMFI[1] ? -1 : -0.5 : -0.25 :
       0       
// Calculates WaveTrend
[wt1, wt2, wtOversold, wtOverbought, wtCross, wtCrossUp, wtCrossDown, wtCross_last, wtCrossUp_last, wtCrossDown_last, wtVwap] = f_wavetrend(wtMASource, wtChannelLen, wtAverageLen, wtMALen, timeframe.period)
 


// Small Circles WT Cross
signalColor = wt2 - wt1 > 0 ? color.red : color.lime

// Buy signal.

buySignal_wt = wtCross and wtCrossUp  and wtOversold 
buySignalSmall_wt = wtCross and wtCrossUp  and wt2 > 0 and not wtOversold 


// Sell signal
sellSignal_wt = wtCross and wtCrossDown  and wtOverbought 
sellSignalSmall_wt = wtCross and wtCrossDown  and wt2 < 0 and not wtOverbought


// coloring
col_WT = wt1 > wt2 ? wt2 < 0 ? wtOversold ? color.aqua : #006ec5 : #024478 : 
       wt1 < wt2 ? wt2 > 0 ? wtOverbought ? #fa3939 : #CE7A00 : #663d00 :
       color.gray

weight_WT = wt1 > wt2 ? wt2 < 0 ? wtOversold ? 1 : 0.5 : 0.25 : 
       wt1 < wt2 ? wt2 > 0 ? wtOverbought ? -1 : -0.5 : -0.25 :
       0       

//------------------WT END---------------

//--------------AK TREND + MOM--------------
input1 = 3, input2 = 8 , 

fastmaa = ema(close,input1)
fastmab = ema(close,input2)

bspread = (fastmaa-fastmab)*1.001

adline = 0

m = bspread > 0 ? color.aqua : color.red


//MOM

lenmom = input(10, minval=1, title="Length Momentum")
srcMOM = input(close, title="Source")

mom = srcMOM - srcMOM[lenmom]


// coloring
col_MOM = mom > 0 ? bspread > 0 ? color.aqua : #006ec5 :
       mom < 0 ? bspread < 0 ? #fa3939 : #CE7A00 : 
       color.gray

weight_MOM = mom > 0 ? bspread > 0 ? 1 : 0.5 :
       mom < 0 ? bspread < 0 ? -1 : -0.5 :
       0

//--------------AK TREND + MOM DIV END--------------


//--------------ADX DI--------------
len = input(14)
th = input(10)
th2 = input(30)
th3 = input(20)
th4 = input(100)

TrueRange = max(max(high-low, abs(high-nz(close[1]))), abs(low-nz(close[1])))
DirectionalMovementPlus = high-nz(high[1]) > nz(low[1])-low ? max(high-nz(high[1]), 0): 0
DirectionalMovementMinus = nz(low[1])-low > high-nz(high[1]) ? max(nz(low[1])-low, 0): 0

SmoothedTrueRange = 0.0
SmoothedTrueRange := nz(SmoothedTrueRange[1]) - (nz(SmoothedTrueRange[1])/len) + TrueRange

SmoothedDirectionalMovementPlus = 0.0
SmoothedDirectionalMovementPlus := nz(SmoothedDirectionalMovementPlus[1]) - (nz(SmoothedDirectionalMovementPlus[1])/len) + DirectionalMovementPlus

SmoothedDirectionalMovementMinus = 0.0
SmoothedDirectionalMovementMinus := nz(SmoothedDirectionalMovementMinus[1]) - (nz(SmoothedDirectionalMovementMinus[1])/len) + DirectionalMovementMinus

DIPlus = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100
DIMinus = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100
DX = abs(DIPlus-DIMinus) / (DIPlus+DIMinus)*100
ADX = sma(DX, len)

trendStrong = ADX >= 20 and ADX <=30
trendReversal = ADX >= 35
diLong = DIMinus > 30 and not trendStrong
diShort = DIPlus > 30 and not trendStrong

//plusPlot = plot(DIPlus, color=color.green, title="DI+")
//minusPlot = plot(DIMinus, color=color.red, title="DI-")
//plot(ADX, color=color.white, title="ADX")
//hline(th, color=color.gray, linewidth = 1)
//hline(th2, color=color.gray, linewidth = 2)
//hline(th3, color=color.gray, linewidth = 2, linestyle = hline.style_solid)

//bgcolor(diLong ? trendReversal ? color.green: color.aqua : diShort ? trendReversal ? color.red : color.orange : na, transp = 80)
//bgcolor(cross(DIPlus,DIMinus)?color.gray:na, transp=80)

//plotchar(crossover(DIPlus,DIMinus), char='▲', location=location.bottom, color=color.green)
//plotchar(crossunder(DIPlus,DIMinus), char='▼', location=location.top, color=color.red)

// coloring
col_ADX = DIPlus > DIMinus ? ADX > 20 ? ADX > 30 and DIPlus > DIPlus[1] ? color.aqua : #006ec5 : #024478 : 
       DIPlus < DIMinus ? ADX > 20 ? ADX > 30 and DIMinus > DIMinus[1] ? #fa3939 : #CE7A00 : #663d00 :
       color.gray

weight_ADX = DIPlus > DIMinus ? ADX > 20 ? ADX > 30 and DIPlus > DIPlus[1] ? 1 : 0.5 : 0.25 : 
       DIPlus < DIMinus ? ADX > 20 ? ADX > 30 and DIMinus > DIMinus[1] ? -1 : -0.5 : -0.25 :
       0       

//--------------ADX DI END--------------

//---------------keltner--------------
keltsrc                     = input(close, type=input.source)

separatorAverage        = input(false, title="⎻⎻⎻ MA Base Setting ⎻⎻⎻")
movingAverageLength     = input(34,    minval=1, title="MA length")
movingAverageType       = input("EMA", title="MA", options=["SMA", "EMA", "WMA", "DEMA", "TEMA", "TRIMA", "KAMA", "MAMA", "T3"], type=input.string)
separatorKC             = input(false, title="⎻⎻⎻ CHANNELS  ⎻⎻⎻")
atrMultiplier        = input(2.5,   minval=0, type = input.float,  title="ATR Multiplier")

atrType                 = input("EMA", title="ATR Smoothing MA", options=["SMA", "EMA", "WMA", "DEMA", "TEMA", "TRIMA", "KAMA", "MAMA", "T3"], type=input.string)
atrLength               = input(88,   minval=1, title="ATR Smoothing Length")
kc_usePer               = input(defval = false, title = "Different Time-Period ?")
kc_res                  = input("15", type=input.resolution, title = "Time-Period")

kama(keltsrc, len)=>
    xvnoise = abs(keltsrc - keltsrc[1])
    nfastend = 0.666
    nslowend = 0.0645
    nsignal = abs(keltsrc - keltsrc[len])
    nnoise = sum(xvnoise, len)
    nefratio = iff(nnoise != 0, nsignal / nnoise, 0)
    nsmooth = pow(nefratio * (nfastend - nslowend) + nslowend, 2)
    nAMA = 0.0
    nAMA := nz(nAMA[1]) + nsmooth * (keltsrc - nz(nAMA[1]))

mama(keltsrc, len)=>
    fl=0.5
    sl=0.05
    pi = 3.1415926
    sp = (4*keltsrc + 3*keltsrc[1] + 2*keltsrc[2] + keltsrc[3]) / 10.0
    p  = 0.0
    i2 = 0.0
    q2 = 0.0
    dt = (.0962*sp + .5769*nz(sp[2]) - .5769*nz(sp[4])- .0962*nz(sp[6]))*(.075*nz(p[1]) + .54)
    q1 = (.0962*dt + .5769*nz(dt[2]) - .5769*nz(dt[4])- .0962*nz(dt[6]))*(.075*nz(p[1]) + .54)
    i1 = nz(dt[3])
    jI = (.0962*i1 + .5769*nz(i1[2]) - .5769*nz(i1[4])- .0962*nz(i1[6]))*(.075*nz(p[1]) + .54)
    jq = (.0962*q1 + .5769*nz(q1[2]) - .5769*nz(q1[4])- .0962*nz(q1[6]))*(.075*nz(p[1]) + .54)
    i2_ = i1 - jq
    q2_ = q1 + jI
    i2 := .2*i2_ + .8*nz(i2[1])
    q2 := .2*q2_ + .8*nz(q2[1])
    re_ = i2*nz(i2[1]) + q2*nz(q2[1])
    im_ = i2*nz(q2[1]) - q2*nz(i2[1])
    re = 0.0
    im = 0.0
    re := .2*re_ + .8*nz(re[1])
    im := .2*im_ + .8*nz(im[1])
    p1 = iff(im!=0 and re!=0, 2*pi/atan(im/re), nz(p[1]))
    p2 = iff(p1 > 1.5*nz(p1[1]), 1.5*nz(p1[1]), iff(p1 < 0.67*nz(p1[1]), 0.67*nz(p1[1]), p1))
    p3 = iff(p2<6, 6, iff (p2 > 50, 50, p2))
    p := .2*p3 + .8*nz(p3[1])
    spp  = 0.0
    spp := .33*p + .67*nz(spp[1])
    phase = 180/pi * atan(q1 / i1)
    dphase_ = nz(phase[1]) - phase
    dphase = iff(dphase_< 1, 1, dphase_)
    alpha_ = fl / dphase
    alpha = iff(alpha_ < sl, sl, iff(alpha_ > fl, fl, alpha_))
    mama = 0.0
    mama := alpha*keltsrc + (1 - alpha)*nz(mama[1])

t3(keltsrc, len)=>
    xe1_1 = ema(keltsrc,    len)
    xe2_1 = ema(xe1_1,  len)
    xe3_1 = ema(xe2_1,  len)
    xe4_1 = ema(xe3_1,  len)
    xe5_1 = ema(xe4_1,  len)
    xe6_1 = ema(xe5_1,  len)
    b_1 = 0.7
    c1_1 = -b_1*b_1*b_1
    c2_1 = 3*b_1*b_1+3*b_1*b_1*b_1
    c3_1 = -6*b_1*b_1-3*b_1-3*b_1*b_1*b_1
    c4_1 = 1+3*b_1+b_1*b_1*b_1+3*b_1*b_1
    nT3Average_1 = c1_1 * xe6_1 + c2_1 * xe5_1 + c3_1 * xe4_1 + c4_1 * xe3_1

variant(type, keltsrc, len) =>
    v1 = sma(keltsrc, len)                                                  // Simple
    v2 = ema(keltsrc, len)                                                  // Exponential
    v3 = 2 * v2 - ema(v2, len)                                          // Double Exponential
    v4 = 3 * (v2 - ema(v2, len)) + ema(ema(v2, len), len)               // Triple Exponential
    v5 = wma(keltsrc, len)                                                  // Weighted
    v6 = sma(sma(keltsrc, ceil(len / 2)), floor(len / 2) + 1)               // TRIMA
    v7 = kama(keltsrc, len)                                                 // KAMA
    v8 = mama(keltsrc, len)                                                 // MAMA
    v9 = t3(keltsrc, len)                                                   // T3
    type=="EMA"?v2 : type=="DEMA"?v3 : type=="TEMA"?v4 : type=="WMA"?v5 : type=="TRIMA"?v6 : type=="KAMA"?v7 : type=="MAMA"?v8 : type=="T3"?v9 : v1

//MA Base Calculation 
KeltnerChannelMid        = variant(movingAverageType, keltsrc, movingAverageLength)
KeltnerChannelRange      = variant(atrType, tr , atrLength) 
KeltnerChannelBottom  = KeltnerChannelMid - KeltnerChannelRange * atrMultiplier 

KeltnerChannelTop     = KeltnerChannelMid + KeltnerChannelRange * atrMultiplier 


resKeltnerChannelMid        = kc_usePer ? security(syminfo.tickerid, kc_res, KeltnerChannelMid) : KeltnerChannelMid
resKeltnerChannelRange      = kc_usePer ? security(syminfo.tickerid, kc_res, KeltnerChannelRange) : KeltnerChannelRange
resKeltnerChannelBottom = kc_usePer ? security(syminfo.tickerid, kc_res, KeltnerChannelBottom) : KeltnerChannelBottom

resKeltnerChannelTop     = kc_usePer ? security(syminfo.tickerid, kc_res, KeltnerChannelTop) : KeltnerChannelTop
//---------------keltner end--------------


//--------------RSI BANDS-------------------
rsi_obLevel = input(70, title="RSI Overbought")
rsi_osLevel = input(30, title="RSI Oversold")
length = input(14, title="RSI Length")
rsi_src=close
ep = 2 * length - 1
auc = ema( max( rsi_src - rsi_src[1], 0 ), ep )
adc = ema( max( rsi_src[1] - rsi_src, 0 ), ep )
x1 = (length - 1) * ( adc * rsi_obLevel / (100-rsi_obLevel) - auc)
ub = iff( x1 >= 0, rsi_src + x1, rsi_src + x1 * (100-rsi_obLevel)/rsi_obLevel )
x2 = (length - 1) * ( adc * rsi_osLevel / (100-rsi_osLevel) - auc)
lb = iff( x2 >= 0, rsi_src + x2, rsi_src + x2 * (100-rsi_osLevel)/rsi_osLevel )

ub:=(ub + resKeltnerChannelTop) /2
lb:=(lb + resKeltnerChannelBottom) /2
//--------------RSI BANDS END-------------------


// -------------------------------------
// -------------- VWAP  ----------------
// -------------------------------------
fib1 = input(title="Fibo extension 1", type=input.float, defval=1.618)
fib2 = input(title="Fibo extension 2", type=input.float, defval=2.618)
reso = input(title="Resolution VWAP", type=input.resolution, defval="W")
dev = input(title="Deviation value min.", type=input.integer, defval=150)


t = time(reso)
debut = na(t[1]) or t > t[1]

addsource = hlc3 * volume
addvol = volume
addsource := debut ? addsource : addsource + addsource[1]
addvol := debut ? addvol : addvol + addvol[1]
VWAP = addsource / addvol

sn = 0.0
sn := debut ? sn : sn[1] + volume * (hlc3 - VWAP[1]) * (hlc3 - VWAP)
sd = sqrt(sn / addvol)

Fibp2 = VWAP + fib2 * sd
Fibp1 = VWAP + fib1 * sd
Fibm1 = VWAP - fib1 * sd
Fibm2 = VWAP - fib2 * sd


// -------------------------------------
// -------------- Plots ----------------
// -------------------------------------

//plot((VWAP + avg(ub, lb))/2, title="VWAP", color=col2, linewidth = 3)
vwap_res = (VWAP + avg(ub, lb))/2

// -------------------------------------
// -------------- VWAP END--------------
// -------------------------------------


//--------------OBV M--------------
//Settings
maInput = input(title="❓ OBV-M MA Type (ENA is default - the rest experimental)", defval="EMA", options=["EMA", "SMA", "VWMA", "WMA"])
PeriodsDiv = input(7, "OVBM MA Length")
signalLengthobv = input(10, "OBV-M Signal Length")
yes1 = input(title="Enable Bar Color by Trade?", type=input.bool, defval=true)

//MA selector - Something I added
getMA(src, length) =>
    ma = 0.0
    if maInput == "EMA"
        ma := ema(src, length)
    if maInput == "SMA"
        ma := sma(src, length)
    if maInput == "VWMA"
        ma := vwma(src, length)
    if maInput == "WMA"
        ma := wma(src, length)
    ma

//OBV-M Formula
OBVM = getMA(obv, PeriodsDiv)
signalobv = getMA(OBVM, signalLengthobv)

//Signal Conditions
long = crossover(OBVM, signalobv)
short = crossunder(OBVM, signalobv)


// coloring

col_OBV = barssince(long) > barssince(short) ? close < vwap_res ? #fa3939 : #CE7A00 :
         barssince(long) <= barssince(short) ? close > vwap_res ? color.aqua : #006ec5 :
       color.gray

weight_OBV = barssince(long) < barssince(short) ? close > vwap_res ? 1 : 0.5 :
       barssince(long) > barssince(short) ? close < vwap_res ? -1 : -0.5 :
       0
//--------------OBV M END--------------

//--MFIww PART
clo=close
valueMFIWW = high-low
tt = input(4, minval=1, title="tt->sma(Volume,tt)"), 
lenmfi = input(14, minval=1,title="len-->MFI(close,len)"), 

ksmes = input(false, title="level 0 or 50")

smes=ksmes ? 0 : 50
// MFI
upper = sum(volume * (change(clo) <= 0 ? 0 : valueMFIWW), lenmfi)
lower = sum(volume * (change(clo) >= 0 ? 0 : valueMFIWW), lenmfi)
mf = rsi(upper, lower)-smes

voll=sma(volume,tt)
dmf=mf[0]-mf[1]
dvol=voll[0]-voll[1]
//col=dmf>0 and dvol>0 ? color.lime : dmf>0 and dvol<0 ? color.green : dmf<0 and dvol>0 ? color.red : dmf<0 and dvol<0 ? color.orange : color.yellow

// coloring

col_MFIWW = dmf>0 ? dvol>0 ? color.aqua : #006ec5 :
         dmf<0 ? dvol<0 ? #fa3939 : #CE7A00 : 
       color.gray
       

weight_MFIWW = dmf>0 ? dvol>0 ? 1 : 0.5 :
       dmf<0 ? dvol>0 ? -1 : -0.5 :
       0

//----MFIww PART END

//------------MACD-------------

sourceMACD = close
useCurrentRes = input(true, title="Use Current Chart Resolution?")
resCustom = input(title="Use Different Timeframe? Uncheck Box Above", type=input.resolution, defval="60")



res = useCurrentRes ? timeframe.period : resCustom

fastLengthMACD = input(12, minval=1), slowLengthMACD=input(26,minval=1)
signalLengthMACD=input(9,minval=1)

fastMA = ema(sourceMACD, fastLengthMACD)
slowMA = ema(sourceMACD, slowLengthMACD)

macd_ = fastMA - slowMA
signalMACD = sma(macd_, signalLengthMACD)
histMACD = macd_ - signalMACD


outHist = security(syminfo.tickerid, res, histMACD)

//histA_IsUp = outHist > outHist[1] and outHist > 0
//histA_IsDown = outHist < outHist[1] and outHist > 0
//histB_IsDown = outHist < outHist[1] and outHist <= 0
//histB_IsUp = outHist > outHist[1] and outHist <= 0



//plot_color = histA_IsUp ? aqua : histA_IsDown ? blue : histB_IsDown ? red : histB_IsUp ? maroon : gray

// coloring

col_MACD = outHist > 0 ? outHist > outHist[1] ? color.aqua : #006ec5 :
         outHist <= 0 ? outHist < outHist[1] ? #fa3939 : #CE7A00 : 
       color.gray
       

weight_MACD = outHist > 0 ? outHist > outHist[1] ? 1 : -0.5 :
       outHist <= 0 ? outHist < outHist[1] ? -1 : 0.5 :
       0

//plot(sh and outHist ? outHist : na, title="Histogram", color=plot_color, style=histogram, linewidth=4)



//------------MACD END-------------

//-----------AO------------------

// -Calculations ════════════════════════════════════════════════════════════════════════════════ //

f_logmap(_s, _r, _l) => _r * _s / highest(_l) * (1 - _s / highest(_l))

f_map(_s, _r, _v) =>
    mapeq = f_logmap(_s, _r, 13)
    lmap = mapeq
    for i = 0 to 29
        array.push(_v,lmap)
        lmap := _r * abs(mapeq[i]) * (1 - mapeq[i])
    lmap

r = sma(hl2, 5) / sma(hl2, 34) - 1

var v = array.new_float(0)

val   = f_map(close, r, v)


array.remove(v, 0)
aStDev = sign(array.avg(v)) * array.stdev(v)
//plot(aStDev, "Standard Deviation of Array's Elements", aStDev > 0 ? aStDev > aStDev[1] ? color.lime : color.navy : aStDev < 0 ? aStDev < aStDev[1] ? color.red:color.yellow : color.gray, 2, style = plot.style_histogram)
array.clear(v)
col_AO = aStDev > 0 ? aStDev > aStDev[1] ? color.aqua : #006ec5 :
         aStDev <= 0 ? aStDev < aStDev[1] ? #fa3939 : #CE7A00 : 
       color.gray
       

weight_AO = aStDev > 0 ? aStDev > aStDev[1] ? 1 : -0.5 :
       aStDev <= 0 ? aStDev < aStDev[1] ? -1 : 0.5 :
       0
//------------AO END--------------



//----------CHOP EXPLODE-----------

srcCHOP = close, lenCHOP = input(14, minval=1, title="Length")
upCHOP = rma(max(change(srcCHOP), 0), lenCHOP)
downCHOP = rma(-min(change(srcCHOP), 0), lenCHOP)
rsiCHOP = downCHOP == 0 ? 100 : upCHOP == 0 ? 0 : 100 - (100 / (1 + upCHOP / downCHOP))

       
// coloring
col_CHOP = close[1] < close ? rsiCHOP > 55 ? rsiCHOP > 60 ? color.aqua : #006ec5 : #024478 : 
       close[1] > close ? rsiCHOP < 45 ? rsiCHOP < 40 ? #fa3939 : #CE7A00 : #663d00 :
       color.gray

weight_CHOP = close[1] < close ? rsiCHOP > 55 ? rsiCHOP > 60 ? 1 : 0.5 : 0.25 : 
       close[1] > close ? rsiCHOP < 45 ? rsiCHOP < 40 ? -1 : -0.5 : -0.25 :
      0
//--------CHOP EXPLODE END----------


//--------AROON----------

lengthAROON = input(14, minval=1)
upperAROON = 100 * (highestbars(high, lengthAROON+1) + lengthAROON)/lengthAROON
lowerAROON = 100 * (lowestbars(low, lengthAROON+1) + lengthAROON)/lengthAROON

oscillatorAROON = upperAROON - lowerAROON


// coloring
col_AROON = oscillatorAROON > 0 ? upperAROON > 50 ? upperAROON > upperAROON[1] and lowerAROON[1] >= lowerAROON ? color.aqua : #006ec5 : #024478 : 
       oscillatorAROON < 0 ? lowerAROON > 50 ? lowerAROON > lowerAROON[1] and upperAROON[1] >= upperAROON ? #fa3939 : #CE7A00 : #663d00 :
       color.gray

weight_AROON = oscillatorAROON > 0 ? upperAROON > 50 ? upperAROON > upperAROON[1] and lowerAROON[1] >= lowerAROON ? 1 : 0.5 : 0.25 : 
       oscillatorAROON < 0 ? lowerAROON > 50 ? lowerAROON > lowerAROON[1] and upperAROON[1] >= upperAROON ? -1 : -0.5 : -0.25 :
      0

//--------AROON END----------

//------------KDJ----------
ilong = input(9, title="period")
isig = input(3, title="signal")
bcwsma(s, l, m) =>
    _bcwsma = float(na)
    _s = s
    _l = l
    _m = m
    _bcwsma := (_m * _s + (_l - _m) * nz(_bcwsma[1])) / _l
    _bcwsma
c_KDJ = close, h_KDJ = highest(high, ilong), l_KDJ = lowest(low, ilong)
RSV = 100 * ((c_KDJ - l_KDJ) / (h_KDJ - l_KDJ)), pK = bcwsma(RSV, isig, 1), pD = bcwsma(pK, isig, 1), pJ = 3 * pK - 2 * pD, KDJ = avg(pD,pJ,pK)


// coloring
col_KDJ = pJ>pD ? pD < 80 ? pD <= 20 ? color.aqua : #006ec5 : #024478 : 
       pJ < pD ? pD > 20 ? pD >= 80 ? #fa3939 : #CE7A00 : #663d00 :
       color.gray

weight_KDJ = pJ>pD ? pD < 80 ? pD <= 20 ? 1 : 0.5 : 0.25 : 
       pJ < pD ? pD > 20 ? pD >= 80 ? -1 : -0.5 : -0.25 :
       0       
//------------KDJ END----------

//----------SUMMARY WEIGHT------------------

sum_weight = weight_VSLRT + weight_ATR + weight_OBV + weight_ADX + weight_MFI + weight_MOM + weight_WT + weight_MFIWW + weight_MACD + weight_CHOP + weight_AROON + weight_KDJ + weight_AO + weight_VSLRT_lt
sum_color = sum_weight > 0 ? c1 : c2




//------------LABELS----------------

prd = input(defval = 5, title = "Pivot Period", minval = 1, maxval = 50)
showlast = input(defval = true, title = "Show Only Last Divergence")
var int maxarraysize = 20
var ph_positions = array.new_int(maxarraysize, 0)
var pl_positions = array.new_int(maxarraysize, 0)
var ph_vals = array.new_float(maxarraysize, 0.)
var pl_vals = array.new_float(maxarraysize, 0.)
float ph = pivothigh(high, prd, prd)
float pl = pivotlow(low, prd, prd)

// add PHs to the array
if ph
    array.unshift(ph_positions, bar_index)
    array.unshift(ph_vals, ph)
    if array.size(ph_positions) > maxarraysize
        array.pop(ph_positions)
        array.pop(ph_vals)

// add PLs to the array
if pl
    array.unshift(pl_positions, bar_index)
    array.unshift(pl_vals, pl)
    if array.size(pl_positions) > maxarraysize
        array.pop(pl_positions)
        array.pop(pl_vals)

var pos_div_lines = array.new_line(0)
var neg_div_lines = array.new_line(0)
var pos_div_labels = array.new_label(0)
var neg_div_labels = array.new_label(0) 

// remove old lines and labels if showlast option is enabled
delete_old_pos_div_lines()=>
    if array.size(pos_div_lines) > 0    
        for j = 0 to array.size(pos_div_lines) - 1 
            line.delete(array.get(pos_div_lines, j))
        array.clear(pos_div_lines)

delete_old_neg_div_lines()=>
    if array.size(neg_div_lines) > 0    
        for j = 0 to array.size(neg_div_lines) - 1 
            line.delete(array.get(neg_div_lines, j))
        array.clear(neg_div_lines)

delete_old_pos_div_labels()=>
    if array.size(pos_div_labels) > 0 
        for j = 0 to array.size(pos_div_labels) - 1 
            label.delete(array.get(pos_div_labels, j))
        array.clear(pos_div_labels)

delete_old_neg_div_labels()=>
    if array.size(neg_div_labels) > 0    
        for j = 0 to array.size(neg_div_labels) - 1 
            label.delete(array.get(neg_div_labels, j))
        array.clear(neg_div_labels)

// delete last creted lines and labels until we met new PH/PV 
delete_last_pos_div_lines_label(n)=>
    if n > 0 and array.size(pos_div_lines) >= n    
        asz = array.size(pos_div_lines)
        for j = 1 to n
            line.delete(array.get(pos_div_lines, asz - j))
            array.pop(pos_div_lines)
        if array.size(pos_div_labels) > 0  
            label.delete(array.get(pos_div_labels, array.size(pos_div_labels) - 1))
            array.pop(pos_div_labels)

delete_last_neg_div_lines_label(n)=>
    if n > 0 and array.size(neg_div_lines) >= n    
        asz = array.size(neg_div_lines)
        for j = 1 to n
            line.delete(array.get(neg_div_lines, asz - j))
            array.pop(neg_div_lines)
        if array.size(neg_div_labels) > 0  
            label.delete(array.get(neg_div_labels, array.size(neg_div_labels) - 1))
            array.pop(neg_div_labels)
            
// variables for Alerts
pos_reg_div_detected = false
neg_reg_div_detected = false
pos_hid_div_detected = false
neg_hid_div_detected = false

// to remove lines/labels until we met new // PH/PL
var last_pos_div_lines = 0
var last_neg_div_lines = 0
var remove_last_pos_divs = false 
var remove_last_neg_divs = false
if pl
    remove_last_pos_divs := false
    last_pos_div_lines := 0
if ph
    remove_last_neg_divs := false
    last_neg_div_lines := 0

if showlast
    delete_old_neg_div_labels()
array.push(neg_div_labels, label.new( x = bar_index+2,y = -2,text = "VSLRT",color = col_VSLRT,textcolor = color.white,style = label.style_label_left, size=size.normal))
array.push(neg_div_labels, label.new( x = bar_index+2,y = -19,text = "VSLRT lt",color = col_VSLRT_lt,textcolor = color.white,style = label.style_label_left, size=size.normal))
array.push(neg_div_labels, label.new( x = bar_index+2,y = 13,text = "ATR",color = col_ATR,textcolor = color.white,style = label.style_label_left, size=size.normal))
array.push(neg_div_labels, label.new( x = bar_index+2,y = 16,text = "AROON",color = col_AROON,textcolor = color.white,style = label.style_label_left, size=size.normal))
array.push(neg_div_labels, label.new( x = bar_index+2,y = 19,text = "AO",color = col_AO,textcolor = color.white,style = label.style_label_left, size=size.normal))
array.push(neg_div_labels, label.new( x = bar_index+2,y = 7,text = "MACD",color = col_MACD,textcolor = color.white,style = label.style_label_left, size=size.normal))
array.push(neg_div_labels, label.new( x = bar_index+2,y = 4,text = "OBV",color = col_OBV,textcolor = color.white,style = label.style_label_left, size=size.normal))
array.push(neg_div_labels, label.new( x = bar_index+2,y = 1,text = "ADX",color = col_ADX,textcolor = color.white,style = label.style_label_left, size=size.normal))
array.push(neg_div_labels, label.new( x = bar_index+2,y = -4,text = "MFI",color = col_MFI,textcolor = color.white,style = label.style_label_left, size=size.normal))
array.push(neg_div_labels, label.new( x = bar_index+2,y = -7,text = "MFI ww",color = col_MFIWW,textcolor = color.white,style = label.style_label_left, size=size.normal))
array.push(neg_div_labels, label.new( x = bar_index+2,y = 10,text = "MOM",color = col_MOM,textcolor = color.white,style = label.style_label_left, size=size.normal))
array.push(neg_div_labels, label.new( x = bar_index+2,y = -10,text = "WT",color = col_WT,textcolor = color.white,style = label.style_label_left, size=size.normal))
array.push(neg_div_labels, label.new( x = bar_index+2,y = -13,text = "CHOP",color = col_CHOP,textcolor = color.white,style = label.style_label_left, size=size.normal))
array.push(neg_div_labels, label.new( x = bar_index+2,y = -16,text = "KDJ",color = col_KDJ,textcolor = color.white,style = label.style_label_left, size=size.normal))


//----------SUMMARY WEIGHT END------------------
smoothed = input(true, "Smoothed Coloomns?")
smooth_period = input(2, "Smooth period")
plot(smoothed?sma(sum_weight,smooth_period):sum_weight, color = sum_color, style = plot.style_columns, transp=75)


bgcolor(ADX > 30?color.gray:na, transp=80)


signal_line = 8
plot(signal_line, color = color.gray)
plot(-signal_line, color = color.gray)

//bgcolor(ADX > 30 and (sum_weight>signal_line or sum_weight<-signal_line) and sma(ADX[1],2)> sma(ADX,2)?color.gray:na, transp=80)


//----------WILLIAMS %R + CCI END--------------
plusPlot = plot(ADX> 30?DIPlus/2:na, color=color.aqua, style = plot.style_linebr, linewidth = 3)
minusPlot = plot(ADX> 30?DIMinus/2:na, color=#FF266E, style = plot.style_linebr, linewidth = 3)


