lib_Indicators_DT
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dturkuler
// library includes indicators, snippets from tradingview library , user  @RodrigoKazuma indicator

//@version=5

// @description This library functions returns some Moving averages and indicators. Created it to feed  my indicator/strategy "INDICATOR & CONDITIONS COMBINATOR FRAMEWORK v[x] [DTU]" 
library("lib_Indicators_DT", overlay = false)
 
//--------------------------
//--------Constants---------
//--------------------------
fastlength =    5
slowlength =    34
mult =          2.0
PI =            3.14159265
AlmaOffset =    0.85  //Defaut is 0.5 or 0.85
AlmaSigma =     6  //Defaut is 1 or 6
LAPercLen =     5  //input(title="Lag Adapt: Perc length_", type=integer, defval=5, minval=1)
FPerc =         50  //input(title="Percntl: Percentile", type=float, defval=50.0, minval=0.0, maxval=100.0)
LOffset =       1  //input(title="Offset", type=integer, defval=0, minval=0)

//--------------------------
len =           14
useSimpleLog =  false
plotSWMA =      false
plotingType =   input.string('Original', options=['Original', 'Stochastic', 'PercentRank'])
stochlen =      50
smaFunction =   true

//--------------------------
//--------Functions---------
//--------------------------
plotFunction(src_) =>
    plotingType == 'Stochastic' ? ta.stoch(src_, src_, src_, stochlen) / 50 - 1 : plotingType == 'PercentRank' ? ta.percentrank(src_, stochlen) / 50 - 1 : src_

PlotFunction(float src_, simple string plotingType_="Original", simple int stochlen_=50) =>
    plotingType_ == 'Stochastic' ? ta.stoch(src_, src_, src_, stochlen_) / 50 - 1 : plotingType_ == 'PercentRank' ? ta.percentrank(src_, stochlen_) / 50 - 1 : src_

simpleLog(src_) =>
    useSimpleLog ? math.log(src_) : src_

plotting(src_) =>
    srcP = plotFunction(src_)
    plotSWMA ? ta.swma(srcP) : srcP

// @function Prepare Indicator Plot Type
// @param src_ Source
// @param src_ plotingType_  "Original, Stochastic, Percent"
// @param src_ stochlen_     Stochasting plottingtype length        
// @param src_ plotSWMA_     Use SWMA for the output
// @returns Return the prepared indicator
export f_plotPrep(float src_, simple string plotingType_="Original", simple int stochlen_=50, bool plotSWMA_ = false) =>
    srcP = PlotFunction(src_, plotingType_, stochlen_)
    plotSWMA_ ? ta.swma(srcP) : srcP


//bollinger %%
bbr(src_, length_) =>
    dev = mult * ta.stdev(src_, length_)
    (src_ - ta.sma(src_, length_) + dev) / (2 * dev)

kcr(src_, length_) =>
    range_1 = mult * ta.ema(ta.tr, length_)
    (src_ - ta.ema(src_, length_) - range_1) / (2 * range_1)

count(src_, length_) =>
    red_count = 0
    red_src = 0.0
    green_count = 0
    green_src = 0.0
    for i = 0 to length_ by 1
        if close[i] < open[i]
            red_count := red_count + 1
            red_src := red_src + src_[i]
            red_src
        if close[i] > open[i]
            green_count := green_count + 1
            green_src := green_src + src_[i]
            green_src
    green_ave = green_src / green_count
    red_ave = red_src / red_count
    green_ave - red_ave

dema(src_, length_) =>
    ema1 = ta.ema(src_, length_)
    ema2 = ta.ema(ema1, length_)
    2 * ema1 - ema2


tema(src_, length_) =>
    ema1 = ta.ema(src_, length_)
    ema2 = ta.ema(ema1, length_)
    ema3 = ta.ema(ema2, length_)
    3 * (ema1 - ema2) + ema3


cctbbo(src_, length_) =>
    deviation = ta.stdev(src_, length_)
    smooth = ta.sma(src_, length_)
    (src_ + 2 * deviation - smooth) / (4 * deviation) - 0.4


//Ehler's super smoother, 2 pole
super2(src_, length_) =>
    y = float(na)
    a1 = math.exp(-math.sqrt(2) * PI / length_)
    b1 = 2 * a1 * math.cos(math.sqrt(2) * PI / length_)
    coef2 = b1
    coef3 = -math.pow(a1, 2)
    coef1 = 1 - coef2 - coef3
    y := coef1 * (src_ + nz(src_[1], src_)) / 2 + coef2 * nz(y[1]) + coef3 * nz(y[2])
    y



//Ehler's super smoother, 3 pole
super3(src_, length_) =>
    y = float(na)
    a1 = math.exp(-PI / length_)
    b1 = 2 * a1 * math.cos(1.738 * PI / length_)
    c1 = math.pow(a1, 2)
    coef2 = b1 + c1
    coef3 = -c1 * (1 + b1)
    coef4 = c1 * c1
    coef1 = 1 - coef2 - coef3 - coef4
    y := coef1 * (src_ + nz(src_[1], src_)) / 2 + coef2 * nz(y[1]) + coef3 * nz(y[2]) + coef4 * nz(y[3])
    y


willprc(src_, length_) =>
    masrcP = ta.highest(src_, length_)
    minP = ta.lowest(src_, length_)
    100 * (src_ - masrcP) / (masrcP - minP)


trix(src_, length_) =>
    10000 * ta.change(ta.ema(ta.ema(ta.ema(math.log(src_), length_), length_), length_))


copcurve(src_, length_) =>
    ta.wma(ta.roc(src_, slowlength) + ta.roc(src_, fastlength), length_)


smiSignal(src_, length_) =>
    erg = ta.tsi(src_, fastlength, slowlength)  //indicaot
    sig = ta.ema(erg, length_)  //Signal
    sig


smiOscillator(src_, length_) =>
    erg = ta.tsi(src_, fastlength, slowlength)  //indicaot
    sig = ta.ema(erg, length_)  //Signal
    osc = erg - sig  //Oscillator
    osc


//lowest exponential expanding moving line
lexp(src_, length_) =>
    y = float(na)
    y := na(y[1]) ? src_ : src_ <= y[1] ? src_ : y[1] + (src_ - y[1]) / length_
    y


//Ehler's Adaptive Laguerre filter
lagAdapt(src_, length_) =>
    y = float(na)
    alpha = float(na)
    error = math.abs(src_ - nz(y[1]))
    range_2 = ta.highest(error, length_) - ta.lowest(error, length_)
    perc = range_2 != 0 ? (error - ta.lowest(error, length_)) / range_2 : nz(alpha[1])
    alpha := ta.percentile_nearest_rank(perc, LAPercLen, FPerc)
    L0 = 0.0
    L0 := alpha * src_ + (1 - alpha) * nz(L0[1])
    L1 = 0.0
    L1 := -(1 - alpha) * L0 + nz(L0[1]) + (1 - alpha) * nz(L1[1])
    L2 = 0.0
    L2 := -(1 - alpha) * L1 + nz(L1[1]) + (1 - alpha) * nz(L2[1])
    L3 = 0.0
    L3 := -(1 - alpha) * L2 + nz(L2[1]) + (1 - alpha) * nz(L3[1])
    y := (L0 + 2 * L1 + 2 * L2 + L3) / 6
    y


//Ehler's Adaptive Laguerre filter variation
lagAdaptV(src_, length_) =>
    y = float(na)
    alpha = float(na)
    error = math.abs(src_ - nz(y[1]))
    range_3 = ta.highest(error, length_) - ta.lowest(error, length_)
    perc = range_3 != 0 ? (error - ta.lowest(error, length_)) / range_3 : nz(alpha[1])
    alpha := ta.percentile_linear_interpolation(perc, LAPercLen, FPerc)
    L0 = 0.0
    L0 := alpha * src_ + (1 - alpha) * nz(L0[1])
    L1 = 0.0
    L1 := -(1 - alpha) * L0 + nz(L0[1]) + (1 - alpha) * nz(L1[1])
    L2 = 0.0
    L2 := -(1 - alpha) * L1 + nz(L1[1]) + (1 - alpha) * nz(L2[1])
    L3 = 0.0
    L3 := -(1 - alpha) * L2 + nz(L2[1]) + (1 - alpha) * nz(L3[1])
    y := (L0 + 2 * L1 + 2 * L2 + L3) / 6
    y


//Ehler's Laguerre filter
laguerre(src_, length_) =>
    y = float(na)
    alpha = math.exp((1 - length_) / 20)  // map length_ to alpha
    L0 = 0.0
    L0 := alpha * src_ + (1 - alpha) * nz(L0[1])
    L1 = 0.0
    L1 := -(1 - alpha) * L0 + nz(L0[1]) + (1 - alpha) * nz(L1[1])
    L2 = 0.0
    L2 := -(1 - alpha) * L1 + nz(L1[1]) + (1 - alpha) * nz(L2[1])
    L3 = 0.0
    L3 := -(1 - alpha) * L2 + nz(L2[1]) + (1 - alpha) * nz(L3[1])
    y := (L0 + 2 * L1 + 2 * L2 + L3) / 6
    y


//lowest exponential esrcpanding moving line
lesrcp(src_, length_) =>
    y = float(na)
    y := na(y[1]) ? src_ : src_ <= y[1] ? src_ : y[1] + (src_ - y[1]) / length_
    y

//---Smoothed Moving Average (SMMA)
calc_smma(src,l)=>
    smmaMA = 0.0
    smmaMA := na(smmaMA[1]) ? ta.sma(src, l) : (smmaMA[1] * (l - 1) + src) / l
    smmaMA

//---Sine-Weighted Moving Average (SW-MA)
calc_swma(src,l) =>
    PI = 2 * math.asin(1)
    sum = 0.0
    weightSum = 0.0
    for i = 0 to l - 1
        weight = math.sin((i + 1) * PI / (l + 1))
        sum := sum + nz(src[i]) * weight
        weightSum := weightSum + weight
    sineWeightMA = sum / weightSum
    sineWeightMA
    
//---Triangular Moving Average (TMA)
calc_tma(src,l) =>
    triMA = ta.sma(ta.sma(src, math.ceil(l / 2)), math.floor(l / 2) + 1)
    triMA

//Geometric Mean Moving Average (GMMA)
calc_gmma(src,l) =>
    lmean = math.log(src)
    smean = math.sum(lmean,l)
    geoMA = math.exp(smean/l)
    geoMA

//---Variable Index Dynamic Average (VIDA)
calc_vida(src,l) =>
    mom = ta.change(src)
    upSum = math.sum(math.max(mom, 0), l)
    downSum = math.sum(-math.min(mom, 0), l)
    cmo = math.abs((upSum - downSum) / (upSum + downSum))
    F = 2/(l+1)
    vida = 0.0
    vida := src * F * cmo + nz(vida[1]) * (1 - F * cmo)
    vida
    
//---Corrective Moving average (CMA)
calc_cma(src,l) =>
    sma = ta.sma(src, l)
    cma = sma
    v1 = ta.variance(src, l)
    v2 = math.pow(nz(cma[1], cma) - sma, 2)
    v3 = v1 == 0 or v2 == 0 ? 1 : v2 / (v1 + v2)
    
    var tolerance = math.pow(10, -5)
    float err = 1
    
    // Gain Factor
    float kPrev = 1
    float k = 1
    
    for i = 0 to 5000
        if err > tolerance
            k := v3 * kPrev * (2 - kPrev)
            err := kPrev - k
            kPrev := k
    
    cma := nz(cma[1], src) + k * (sma - nz(cma[1], src))
    cma
    
//---Ramnge EMA (REMA)
calc_range_ema (src,l) =>
    alpha = 2/(1 + l)
    weight = high-low
    weight:= weight==0? syminfo.pointvalue:weight
    num = 0.0
    den = 0.0
    num := na(num[1])?weight*src:num[1]+alpha*(weight*src -num[1]) 
    den := na(den[1])?weight:den[1]+alpha*(weight-den[1]) 
    ma = num/den
    ma    

f_func(string f, float src_, simple int length_) =>
    float y = switch f
        'Hide'			=>   	src_    
        'alma'			=>   	ta.alma(src_, length_, AlmaOffset, AlmaSigma)
		'bbr'			=>    	bbr(src_, length_)
		'bbw'			=>    	ta.bbw(src_, length_, mult)
		'cci'			=>    	ta.cci(src_, length_)
		'cctbbo'		=>    	cctbbo(src_, length_)
		'change'		=>    	ta.change(src_, length_)
		'cmo'			=>    	ta.cmo(src_, length_)
		'cog'			=>    	ta.cog(src_, length_)
		'count'		    =>    	count(src_, length_)
		'dev'			=>    	ta.dev(src_, length_)
		'stdev'		    =>    	ta.stdev(src_, length_)
		'sma'			=>    	ta.sma(src_, length_)
		'ema'			=>    	ta.ema(src_, length_)
		'dema'			=>    	dema(src_, length_)
		'rma'			=>    	ta.rma(src_, length_)
		'super2'		=>    	super2(src_, length_)
		'super3'		=>    	super3(src_, length_)
		'hull'			=>    	ta.wma(2 * ta.wma(src_, length_ / 2) - ta.wma(src_, length_), math.round(math.sqrt(length_)))
		'kcr'			=>    	kcr(src_, length_)
		'kcw'			=>    	ta.kcw(src_, length_, mult)
		'linreg'		=>    	ta.linreg(src_, length_, LOffset)
		'mfi'			=>    	ta.mfi(src_, length_)
		'roc'			=>    	ta.roc(src_, length_)
		'rsi'			=>    	ta.rsi(src_, length_) * 10
		'variance'	    => 		ta.variance(src_, length_)
		'vwma'			=>    	ta.vwma(src_, length_)
		'wma'			=>    	ta.wma(src_, length_)
		'willprc'		=>   	willprc(src_, length_)
		'trix'			=>    	trix(src_, length_)
		'copcurve'	    => 		copcurve(src_, length_)
		'smi_sig'		=>    	smiSignal(src_, length_)
		'smi_Osc'		=>    	smiOscillator(src_, length_)
		'correl'		=>    	ta.correlation(src_, src_[1], length_)
		'hl2ma'		    =>    	(ta.highest(src_, length_) + ta.lowest(src_, length_)) / 2
		'lagAdapt'	    =>  	lagAdapt(src_, length_)
		'lagAdaptV'	    => 		lagAdaptV(src_, length_)
		'laguerre'	    =>  	laguerre(src_, length_)
		'lesrcp'		=>    	lesrcp(src_, length_)
		'percntl'		=>   	ta.percentile_nearest_rank(src_, length_, FPerc)
		'percntli'	    =>  	ta.percentile_linear_interpolation(src_, length_, FPerc)
		'tsi'			=>    	ta.tsi(src_, fastlength, slowlength)
		'macd'			=>    	ta.sma(src_, length_) - ta.sma(src_, 2 * length_)
		'lexp'			=>    	lexp(src_, length_)
		'smma'			=>    	calc_smma(src_, length_)
		'swma'			=>    	calc_swma(src_, length_)
		'tma'			=>    	calc_tma(src_, length_)
		'gmma'			=>    	calc_gmma(src_, length_)
		'vida'			=>    	calc_vida(src_, length_)
		'cma'			=>    	calc_cma(src_, length_)
		'rema'			=>    	calc_range_ema(src_, length_)
		'tema'          =>      tema(src_, length_)
    y

// @function            f_funcPlot(string f, float src_, simple int length_, string plotingType_ = "Original", simple int stochlen_=50, bool plotSWMA=false)  Return selected indicator value with different parameters
// @param string        f               indicator-> options=['Hide'
//                                                           '▼▼▼ MOV AVGs ▼▼▼',
//                                                           'alma', 'cma','dema', 'ema', 'gmma','hl2ma','hull','lagAdapt', 'lagAdaptV', 'laguerre', 'lesrcp','linreg', 'lexp', 'percntl', 
//                                                           'percntli', 'rema','rma','sma','smma','super2', 'super3','swma','tema', 'tma','vida','vwma', 'wma', 
//                                                           '▼▼▼ INDICATORS ▼▼▼',
//                                                           'bbr', 'bbw', 'cci', 'cctbbo', 'change', 'cmo', 'cog', 'copcurve', 'correl',   'count', 'dev', 'kcr', 'kcw', 
//                                                           'macd', 'mfi', 'roc', 'rsi', 'smi_Oscillator', 'smi_signal', 'stdev','trix' , 'tsi', 'variance',  'willprc']
// @param float         src_            close,open.....
// @param simple int    length_         indicator length
// @param string        plotingType     return param-> options=['Original', 'Stochastic', 'PercentRank')
// @param simple int    stochlen_       length for return Param
// @param bool          plotSWMA        Use SWMA on Plot
// @returns float       [series]
export f_funcPlot(string f, float src_, simple int length_, string plotingType_ = "Original", simple int stochlen_=50, bool plotSWMA=false) =>
    fPlotSrc_=f_func(f, src_, length_)
    srcP = plotingType_ == 'Stochastic' ? ta.stoch(fPlotSrc_, fPlotSrc_, fPlotSrc_, stochlen_) / 50 - 1 : plotingType_ == 'PercentRank' ? ta.percentrank(fPlotSrc_, stochlen_) / 50 - 1 : fPlotSrc_
    plotSWMA ? ta.swma(srcP) : srcP


////USAGE
////@version=5
//indicator("My Script")
//import dturkuler/lib_Indicators_DT/1 as ind // library includes indicators, snippets from tradingview library , @03.freeman ("All MAs displayed") indicator... 
//
//ind_src=        input.string(   defval='ema',           title='IND:', options=['Hide',
//                                                                             '▼▼▼ MOV AVGs ▼▼▼',
//                                                                             'alma', 'cma','dema', 'ema', 'gmma','hl2ma','hull','lagAdapt', 'lagAdaptV', 'laguerre', 'lesrcp','linreg', 'lexp', 'percntl', 
//                                                                             'percntli', 'rema','rma','sma','smma','super2', 'super3','swma','tema', 'tma','vida','vwma', 'wma', 
//                                                                             '▼▼▼ OTHER INDICATORS ▼▼▼',
//                                                                             'bbr', 'bbw', 'cci', 'cctbbo', 'change', 'cmo', 'cog', 'copcurve', 'correl',   'count', 'dev', 'kcr', 'kcw', 
//                                                                             'macd', 'mfi', 'roc', 'rsi', 'smi_Oscillator', 'smi_signal', 'stdev','trix' , 'tsi', 'variance',  'willprc']
//                                                         ,         group="════════════ INDICATORS ════════════", inline="ind")
//ind_len   =     input.int(      defval=48,              title='',  group="════════════ INDICATORS ════════════", inline="ind")
//ind_pType =     input.string(   defval="Original",      title="",  group="════════════ INDICATORS ════════════", inline="ind", options=['Original', 'Stochastic', 'PercentRank'])
//ind_color =     input(          defval=color.green,     title="",  group="════════════ INDICATORS ════════════", inline="ind")
//ind_pSWMA=      input.bool(     defval=false,           title="Smooth",  group="════════════ INDICATORS ════════════", inline="ind")
//
//indicator=ind.f_funcPlot(ind_src, close, length_=ind_len, plotingType_=ind_pType, plotSWMA=ind_pSWMA)
//plot(ind_src!="Hide" ? indicator:na, "INDICATOR",ind_color) 

