lib_Indicators_v2_DTU
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dturkuler
s_lib_version="2.1"
//Version 2.1
//This library includes indicators,  snippets from tradingview builtin library,  @Rodrigo, @midtownsk8rguy, @Lazybear Special thanks to all of the Pine wizards and others for their contribution with their indicators
//You can see the demo of the library by directly adding to the chart
//ADD:  23 new indicators added. Most of them are TR builtin indicators (see description in TV builtin Indicators). Newly added indicators are listed below
//ADD:  New Indicator  'pivothigh(src,BarsLeft,BarsRight=2)'      //Previous pivot high. src=src, BarsLeft=len, BarsRight=p1=2
//ADD:  New Indicator  'pivotlow(src,BarsLeft,BarsRight=2)'       //Previous pivot low. src=src, BarsLeft=len, BarsRight=p1=2
//ADD:  New Indicator  'ranges(src,upper=len, lower=-5)',         //ranges of the source. return -1 source<lower, return 1 source>upper otherwise return 0
//ADD:  New Indicator  'aroon(len,dir=0)',                        //aroon indicator. Aroon's major function is to identify new trends as they happen.p1 = dir: 0=mid (default), 1=upper, 2=lower
//ADD:  New Indicator  'adx(dilen=len, adxlen=14)'                //adx. The Average Directional Index (ADX) is a used to determine the strength of a trend. len=>dilen, p1=adxlen (default=14), p2=adxtype 0:ADX, 1:+DI, 2:-DI (def:0)
//ADD:  New Indicator  'awesome(fast=len=5,slow=34,type=0)'       //Awesome Oscilator (AO) is an indicator used to measure market momentum. defaults : fast=len= 5, p1=slow=34, p2=type: 0=Awesome, 1=difference
//ADD:  New Indicator  'cmf(len=20)'                              //Chaikin Money Flow Indicator used to measure Money Flow Volume over a set period of time. Default use is len=20
//ADD:  New Indicator  'eom(len=14,div=10000)',                   //Ease of Movement.It is designed to measure the relationship between price and volume.p1 = div: 10000= (default)
//ADD:  New Indicator  'efi(len)'                                 //Elder's Force Index (EFI) measures the power behind a price movement using price and volume.
//ADD:  New Indicator  'fn_fisher(len)'                           //Fisher Transform is a technical indicator that converts price to Gaussian normal distribution and signals when prices move significantly by referencing recent price data
//ADD:  New Indicator  'fn_histvol(len)',                         //Historical volatility is a statistical measure used to analyze the general dispersion of security or market index returns for a specified period of time.
//ADD:  New Indicator  'dpo(len)',                                //Detrended Price Oscilator is used to remove trend from price.   
//ADD:  New Indicator  'klinger(type=len)',                       //Klinger oscillator aims to identify money flow’s long-term trend. type=len: 0:Oscilator 1:signal
//ADD:  New Indicator  'msi(len=10)',                             //Mass Index (def=10) is used to examine the differences between high and low stock prices over a specific period of time
//ADD:  New Indicator  'mcginley(src, len)'                       //McGinley Dynamic adjusts for market speed shifts, which sets it apart from other moving averages, in addition to providing clear moving average lines
//ADD:  New Indicator  'sar(start=len, inc=0.02, max=0.02)'       //Parabolic SAR (parabolic stop and reverse) is a method to find potential reversals in the market price direction of traded goods.start=len, inc=p1, max=p2. ex: sar(0.02, 0.02, 0.02)    
//ADD:  New Indicator  'rvi(src,len)',                            //The Relative Volatility Index (RVI) is calculated much like the RSI, although it uses high and low price standard deviation instead of the RSI’s method of absolute change in price.
//ADD:  New Indicator  'ultimateOsc(len)'                         //Ultimate Oscillator indicator (UO) indicator is a technical analysis tool used to measure momentum across three varying timeframes
//ADD:  New Indicator  'volstop(src,len,atrfactor=2)'             //Volatility Stop is a technical indicator that is used by traders to help place effective stop-losses. atrfactor=p1
//ADD:  New Indicator  'vwap(src_)',                              //Volume Weighted Average Price (VWAP) is  used to measure the average price weighted by volume     
//ADD:  New Indicator  'cti(src,len)',                            //Ehler s Correlation Trend Indicator by @midtownsk8rguy.
//ADD:  New Indicator  'stc(src,len,fast=23,slow=50)',            //Schaff Trend Cycle (STC) detects up and down trends long before the MACD. Code imported from @lazybear's (thanks) Schaff Trend Cycle script.
//ADD:  New Indicator  'Original Value',                          //Return input source value as output
//UPD:  constants and inputs (ind_src) are updated with new indicators
//UPD:  indicators descriptions updated
//UPD:  function outputs with "na" converted to 0
//UPD:  input (len:) converted int to float and function codes updated accordingly 
//UPD:  calculation error on fn_factor() corrected

//@version=5


//START library Description {

//@description This library functions returns included Moving averages, indicators with factorization, functions candles, function heikinashi and more. 
//Created it to feed as backend of my other indicators/strategies and feel free the use/modify the source.
//This is replacement of  my previous indicator (lib_indicators_DT)
//Additionally library will be updated with more indicators in the future
//----------------------    
//NOTES:
//----------------------    
//Indicator functions returns only one series :-(
//plotcandle function returns candle [open,high,low,close] series
//----------------------    
//INDICATOR LIST:   
//----------------------    
//OVERLAY INDICATORS
//hide    =   'DONT DISPLAY',                            //Dont display & calculate the indicator. (For my framework usage)
//org     =   'Original Value',                          //Return input source value as output
//alma    =   'alma(src,len,offset=0.85,sigma=6)',       //Arnaud Legoux Moving Average 
//ama     =   'ama(src,len,fast=14,slow=100)',           //Adjusted Moving Average
//acdst   =   'accdist()',                               //Accumulation/distribution index. 
//cma     =   'cma(src,len)',                            //Corrective Moving average    
//dema    =   'dema(src,len)',                           //Double EMA  (Same as EMA with 2 factor)
//ema     =   'ema(src,len)',                            //Exponential Moving Average 
//gmma    =   'gmma(src,len)',                           //Geometric Mean Moving Average
//hghst   =   'highest(src,len)',                        //Highest value for a given number of bars back.   
//hl2ma   =   'hl2ma(src,len)',                          //higest lowest moving average
//hma     =   'hma(src,len)',                            //Hull Moving Average.
//lgAdt   =   'lagAdapt(src,len,perclen=5,fperc=50)',    //Ehler's Adaptive Laguerre filter
//lgAdV   =   'lagAdaptV(src,len,perclen=5,fperc=50)',   //Ehler's Adaptive Laguerre filter variation
//lguer   =   'laguerre(src,len)',                       //Ehler's Laguerre filter
//lsrcp   =   'lesrcp(src,len)',                         //lowest exponential esrcpanding moving line
//lexp    =   'lexp(src,len)',                           //lowest exponential expanding moving line 
//linrg   =   'linreg(src,len,loffset=1)',               //Linear regression
//lowst   =   'lowest(src,len)',                         //Lovest value for a given number of bars back.
//mgi     =   'mcginley(src, len)'                       //McGinley Dynamic adjusts for market speed shifts, which sets it apart from other moving averages, in addition to providing clear moving average lines
//pcnl    =   'percntl(src,len)',                        //percentile nearest rank. Calculates percentile using method of Nearest Rank.
//pcnli   =   'percntli(src,len)',                       //percentile linear interpolation. Calculates percentile using method of linear interpolation between the two nearest ranks.
//prev    =   'previous(src,len)',                       //Previous n (len) value of the source   
//pvth    =   'pivothigh(src,BarsLeft=len,BarsRight=2)'  //Previous pivot high. src=src, BarsLeft=len, BarsRight=p1=2
//pvtl    =   'pivotlow(src,BarsLeft=len,BarsRight=2)'   //Previous pivot low. src=src, BarsLeft=len, BarsRight=p1=2
//rema    =   'rema(src,len)',                           //Range EMA (REMA)   
//rma     =   'rma(src,len)',                            //Moving average used in RSI. It is the exponentially weighted moving average with alpha = 1 / length.
//sar     =   'sar(start=len, inc=0.02, max=0.02)'       //Parabolic SAR (parabolic stop and reverse) is a method to find potential reversals in the market price direction of traded goods.start=len, inc=p1, max=p2. ex: sar(0.02, 0.02, 0.02)    
//sma     =   'sma(src,len)',                            //Smoothed Moving Average
//smma    =   'smma(src,len)',                           //Smoothed Moving Average
//supr2   =   'super2(src,len)',                         //Ehler's super smoother, 2 pole 
//supr3   =   'super3(src,len)',                         //Ehler's super smoother, 3 pole
//strnd   =   'supertrend(src,len,period=3)',            //Supertrend indicator
//swma    =   'swma(src,len)',                           //Sine-Weighted Moving Average
//tema    =   'tema(src,len)',                           //Triple EMA  (Same as EMA with 3 factor)
//tma     =   'tma(src,len)',                            //Triangular Moving Average
//vida    =   'vida(src,len)',                           //Variable Index Dynamic Average   
//vstop   =   'volstop(src,len,atrfactor=2)'             //Volatility Stop is a technical indicator that is used by traders to help place effective stop-losses. atrfactor=p1
//vwap    =   'vwap(src_)',                              //Volume Weighted Average Price (VWAP) is  used to measure the average price weighted by volume     
//vwma    =   'vwma(src,len)',                           //Volume Weigted Moving Average
//wma     =   'wma(src,len)',                            //Weigted Moving Average 
//   
//NON OVERLAY INDICATORS
//adx     =   'adx(dilen=len, adxlen=14, adxtype=0)'     //adx. The Average Directional Index (ADX) is a used to determine the strength of a trend. len=>dilen, p1=adxlen (default=14), p2=adxtype 0:ADX, 1:+DI, 2:-DI (def:0)
//angle   =   'angle(src,len)',                          //angle of the series   (Use its Input as another indicator output)
//aroon   =   'aroon(len,dir=0)',                        //aroon indicator. Aroon's major function is to identify new trends as they happen.p1 = dir: 0=mid (default), 1=upper, 2=lower
//atr     =   'atr(src,len)',                            //average true range. RMA of true range.                
//awsom   =   'awesome(fast=len=5,slow=34,type=0)',      //Awesome Oscilator is an indicator used to measure market momentum. defaults : fast=len= 5, p1=slow=34, p2=type: 0=Awesome, 1=difference
//bbr     =   'bbr(src,len,mult=1)',                     //bollinger %%
//bbw     =   'bbw(src,len,mult=2)',                     //Bollinger Bands Width. The Bollinger Band Width is the difference between the upper and the lower Bollinger Bands divided by the middle band.
//cci     =   'cci(src,len)',                            //commodity channel index
//cctbb   =   'cctbbo(src,len)',                         //CCT Bollinger Band Oscilator
//chng    =   'change(src,len)',                         //A.K.A. Momentum. Difference between current value and previous, source - source[length]. is most commonly referred to as a rate and measures the acceleration of the price and/or volume of a security
//cmf     =   'cmf(len=20)',                             //Chaikin Money Flow Indicator used to measure Money Flow Volume over a set period of time. Default use is len=20
//cmo     =   'cmo(src,len)',                            //Chande Momentum Oscillator. Calculates the difference between the sum of recent gains and the sum of recent losses and then divides the result by the sum of all price movement over the same period.
//cog     =   'cog(src,len)',                            //The cog (center of gravity) is an indicator based on statistics and the Fibonacci golden ratio.
//cpcrv   =   'copcurve(src,len)',                       //Coppock Curve.  was originally developed by Edwin "Sedge" Coppock (Barron's Magazine, October 1962).
//corrl   =   'correl(src,len)',                         //Correlation coefficient. Describes the degree to which two series tend to deviate from their ta.sma values.
//count   =   'count(src,len)',                          //green avg - red avg
//cti     =   'cti(src,len)',                            //Ehler s Correlation Trend Indicator by @midtownsk8rguy.
//dev     =   'dev(src,len)',                            //ta.dev()  Measure of difference between the series and it's ta.sma
//dpo     =   'dpo(len)',                                //Detrended Price OScilator is used to remove trend from price.   
//efi     =   'efi(len)',                                //Elder's Force Index (EFI) measures the power behind a price movement using price and volume.
//eom     =   'eom(len=14,div=10000)',                   //Ease of Movement.It is designed to measure the relationship between price and volume.p1 = div: 10000= (default)
//fall    =   'falling(src,len)',                        //ta.falling() Test if the `source` series is now falling for `length` bars long. (Use its Input as another indicator output)
//fit     =   'fisher(len)',                             //Fisher Transform is a technical indicator that converts price to Gaussian normal distribution and signals when prices move significantly by referencing recent price data
//hvo     =   'histvol(len)',                            //Historical volatility is a statistical measure used to analyze the general dispersion of security or market index returns for a specified period of time.
//kcr     =   'kcr(src,len,mult=2)',                     //Keltner Channels Range  
//kcw     =   'kcw(src,len,mult=2)',                     //ta.kcw(). Keltner Channels Width. The Keltner Channels Width is the difference between the upper and the lower Keltner Channels divided by the middle channel.
//kli     =   'klinger(type=len)',                       //Klinger oscillator aims to identify money flow’s long-term trend. type=len: 0:Oscilator 1:signal
//macd    =   'macd(src,len)',                           //MACD (Moving Average Convergence/Divergence)
//mfi     =   'mfi(src,len)',                            //Money Flow Index s a tool used for measuring buying and selling pressure
//msi     =   'msi(len=10)',                             //Mass Index (def=10) is used to examine the differences between high and low stock prices over a specific period of time
//nvi     =   'nvi()',                                   //Negative Volume Index
//obv     =   'obv()',                                   //On Balance Volume
//pvi     =   'pvi()',                                   //Positive Volume Index 
//pvt     =   'pvt()',                                   //Price Volume Trend
//rangs   =   'ranges(src,upper=len, lower=-5)',         //ranges of the source. src=src, upper=len, v1:lower=upper .  returns: -1 source<lower,  1 source>=upper otherwise 0
//rise    =   'rising(src,len)',                         //ta.rising() Test if the `source` series is now rising for `length` bars long. (Use its Input as another indicator output)
//roc     =   'roc(src,len)',                            //Rate of Change
//rsi     =   'rsi(src,len)',                            //Relative strength Index
//rvi     =   'rvi(src,len)',                            //The Relative Volatility Index (RVI) is calculated much like the RSI, although it uses high and low price standard deviation instead of the RSI’s method of absolute change in price.
//smosc   =   'smi_osc(src,len,fast=5, slow=34)',        //smi Oscillator
//smsig   =   'smi_sig(src,len,fast=5, slow=34)',        //smi Signal
//stc     =   'stc(src,len,fast=23,slow=50)',            //Schaff Trend Cycle (STC) detects up and down trends long before the MACD. Code imported from @lazybear's (thanks) Schaff Trend Cycle script.
//stdev   =   'stdev(src,len)',                          //Standart deviation
//trix    =   'trix(src,len)' ,                          //the rate of change of a triple exponentially smoothed moving average.
//tsi     =   'tsi(src,len)',                            //The True Strength Index indicator is a momentum oscillator designed to detect, confirm or visualize the strength of a trend.
//ulos    =   'ultimateOsc(len)'                         //Ultimate Oscillator indicator (UO) indicator is a technical analysis tool used to measure momentum across three varying timeframes
//vari    =   'variance(src,len)',                       //ta.variance(). Variance is the expectation of the squared deviation of a series from its mean (ta.sma), and it informally measures how far a set of numbers are spread out from their mean.
//wilpc   =   'willprc(src,len)',                        //Williams %R
//wad     =   'wad()',                                   //Williams Accumulation/Distribution.
//wvad    =   'wvad()'                                   //Williams Variable Accumulation/Distribution.
//
//}
library("lib_Indicators_v2_DTU", overlay = false) 

//--------------------------
//--------Constants---------
//--------------------------{
hide    =   'DONT DISPLAY',                            //Dont display/calculate the indicator. (For my framework usage)
org     =   'Original Value',                          //Return input source value as output
ovrly   =   '▼▼▼ OVERLAY ▼▼▼',                         //(Not used as indicator, info Only)Just used to separate input options of overlayable indicators 
alma    =   'alma(src,len,offset=0.85,sigma=6)',       //Arnaud Legoux Moving Average 
ama     =   'ama(src,len,fast=14,slow=100)',           //Adjusted Moving Average
acdst   =   'accdist()',                               //Accumulation/distribution index. 
cma     =   'cma(src,len)',                            //Corrective Moving average    
dema    =   'dema(src,len)',                           //Double EMA  (Same as EMA with 2 factor)
ema     =   'ema(src,len)',                            //Exponential Moving Average 
gmma    =   'gmma(src,len)',                           //Geometric Mean Moving Average
hghst   =   'highest(src,len)',                        //Highest value for a given number of bars back.   
hl2ma   =   'hl2ma(src,len)',                          //higest lowest moving average
hma     =   'hma(src,len)',                            //Hull Moving Average.
lgAdt   =   'lagAdapt(src,len,perclen=5,fperc=50)',    //Ehler's Adaptive Laguerre filter
lgAdV   =   'lagAdaptV(src,len,perclen=5,fperc=50)',   //Ehler's Adaptive Laguerre filter variation
lguer   =   'laguerre(src,len)',                       //Ehler's Laguerre filter
lsrcp   =   'lesrcp(src,len)',                         //lowest exponential esrcpanding moving line
lexp    =   'lexp(src,len)',                           //lowest exponential expanding moving line 
linrg   =   'linreg(src,len,loffset=1)',               //Linear regression
lowst   =   'lowest(src,len)',                         //Lovest value for a given number of bars back.
mgi     =   'mcginley(src, len)'                       //McGinley Dynamic adjusts for market speed shifts, which sets it apart from other moving averages, in addition to providing clear moving average lines
pcnl    =   'percntl(src,len)',                        //percentile nearest rank. Calculates percentile using method of Nearest Rank.
pcnli   =   'percntli(src,len)',                       //percentile linear interpolation. Calculates percentile using method of linear interpolation between the two nearest ranks.
prev    =   'previous(src,len)',                       //Previous n (len) value of the source   
pvth    =   'pivothigh(src,BarsLeft=len,BarsRight=2)'  //Previous pivot high. src=src, BarsLeft=len, BarsRight=p1=2
pvtl    =   'pivotlow(src,BarsLeft=len,BarsRight=2)'   //Previous pivot low. src=src, BarsLeft=len, BarsRight=p1=2
rema    =   'rema(src,len)',                           //Range EMA (REMA)   
rma     =   'rma(src,len)',                            //Moving average used in RSI. It is the exponentially weighted moving average with alpha = 1 / length.
sar     =   'sar(start=len, inc=0.02, max=0.02)'       //Parabolic SAR (parabolic stop and reverse) is a method to find potential reversals in the market price direction of traded goods.start=len, inc=p1, max=p2. ex: sar(0.02, 0.02, 0.02)    
sma     =   'sma(src,len)',                            //Smoothed Moving Average
smma    =   'smma(src,len)',                           //Smoothed Moving Average
supr2   =   'super2(src,len)',                         //Ehler's super smoother, 2 pole 
supr3   =   'super3(src,len)',                         //Ehler's super smoother, 3 pole
strnd   =   'supertrend(src,len,period=3)',            //Supertrend indicator
swma    =   'swma(src,len)',                           //Sine-Weighted Moving Average
tema    =   'tema(src,len)',                           //Triple EMA  (Same as EMA with 3 factor)
tma     =   'tma(src,len)',                            //Triangular Moving Average
vida    =   'vida(src,len)',                           //Variable Index Dynamic Average   
vstop   =   'volstop(src,len,atrfactor=2)'             //Volatility Stop is a technical indicator that is used by traders to help place effective stop-losses. atrfactor=p1
vwma    =   'vwma(src,len)',                           //Volume Weigted Moving Average
wma     =   'wma(src,len)',                            //Weigted Moving Average 
vwap    =   'vwap(src_)',                              //Volume Weighted Average Price (VWAP) is  used to measure the average price weighted by volume     
nvrly   =   '▼▼▼ NON OVERLAY ▼▼▼'                      //(Not used as indicator, info Only)Just used to separate input options of non overlayable indicators 
adx     =   'adx(dilen=len, adxlen=14, adxtype=0)'     //adx. The Average Directional Index (ADX) is a used to determine the strength of a trend. len=>dilen, p1=adxlen (default=14), p2=adxtype 0:ADX, 1:+DI, 2:-DI (def:0)
angle   =   'angle(src,len)',                          //angle of the series   (Use its Input as another indicator output)
aroon   =   'aroon(len,dir=0)',                        //aroon indicator. Aroon's major function is to identify new trends as they happen.p1 = dir: 0=mid (default), 1=upper, 2=lower
atr     =   'atr(src,len)',                            //average true range. RMA of true range.                
awsom   =   'awesome(fast=len=5,slow=34,type=0)',      //Awesome Oscilator is an indicator used to measure market momentum. defaults : fast=len= 5, p1=slow=34, p2=type: 0=Awesome, 1=difference
bbr     =   'bbr(src,len,mult=1)',                     //bollinger %%
bbw     =   'bbw(src,len,mult=2)',                     //Bollinger Bands Width. The Bollinger Band Width is the difference between the upper and the lower Bollinger Bands divided by the middle band.
cci     =   'cci(src,len)',                            //commodity channel index
cctbb   =   'cctbbo(src,len)',                         //CCT Bollinger Band Oscilator
chng    =   'change(src,len)',                         //A.K.A. Momentum. Difference between current value and previous, source - source[length]. is most commonly referred to as a rate and measures the acceleration of the price and/or volume of a security
cmf     =   'cmf(len=20)',                             //Chaikin Money Flow Indicator used to measure Money Flow Volume over a set period of time. Default use is len=20
cmo     =   'cmo(src,len)',                            //Chande Momentum Oscillator. Calculates the difference between the sum of recent gains and the sum of recent losses and then divides the result by the sum of all price movement over the same period.
cog     =   'cog(src,len)',                            //The cog (center of gravity) is an indicator based on statistics and the Fibonacci golden ratio.
cpcrv   =   'copcurve(src,len)',                       //Coppock Curve.  was originally developed by Edwin "Sedge" Coppock (Barron's Magazine, October 1962).
corrl   =   'correl(src,len)',                         //Correlation coefficient. Describes the degree to which two series tend to deviate from their ta.sma values.
count   =   'count(src,len)',                          //green avg - red avg
cti     =   'cti(src,len)',                            //Ehler s Correlation Trend Indicator by @midtownsk8rguy.
dev     =   'dev(src,len)',                            //ta.dev()  Measure of difference between the series and it's ta.sma
dpo     =   'dpo(len)',                                //Detrended Price OScilator is used to remove trend from price.   
efi     =   'efi(len)',                                //Elder's Force Index (EFI) measures the power behind a price movement using price and volume.
eom     =   'eom(len=14,div=10000)',                   //Ease of Movement.It is designed to measure the relationship between price and volume.p1 = div: 10000= (default)
fall    =   'falling(src,len)',                        //ta.falling() Test if the `source` series is now falling for `length` bars long. (Use its Input as another indicator output)
fit     =   'fisher(len)',                             //Fisher Transform is a technical indicator that converts price to Gaussian normal distribution and signals when prices move significantly by referencing recent price data
hvo     =   'histvol(len)',                            //Historical volatility is a statistical measure used to analyze the general dispersion of security or market index returns for a specified period of time.
kcr     =   'kcr(src,len,mult=2)',                     //Keltner Channels Range  
kcw     =   'kcw(src,len,mult=2)',                     //ta.kcw(). Keltner Channels Width. The Keltner Channels Width is the difference between the upper and the lower Keltner Channels divided by the middle channel.
kli     =   'klinger(type=len)',                       //Klinger oscillator aims to identify money flow’s long-term trend. type=len: 0:Oscilator 1:signal
macd    =   'macd(src,len)',                           //MACD (Moving Average Convergence/Divergence)
mfi     =   'mfi(src,len)',                            //Money Flow Index s a tool used for measuring buying and selling pressure
msi     =   'msi(len=10)',                             //Mass Index (def=10) is used to examine the differences between high and low stock prices over a specific period of time
nvi     =   'nvi()',                                   //Negative Volume Index
obv     =   'obv()',                                   //On Balance Volume
pvi     =   'pvi()',                                   //Positive Volume Index 
pvt     =   'pvt()',                                   //Price Volume Trend
rangs   =   'ranges(src,upper=len, lower=-5)',         //ranges of the source. src=src, upper=len, v1:lower=upper .  returns: -1 source<lower,  1 source>=upper otherwise 0
rise    =   'rising(src,len)',                         //ta.rising() Test if the `source` series is now rising for `length` bars long. (Use its Input as another indicator output)
roc     =   'roc(src,len)',                            //Rate of Change
rsi     =   'rsi(src,len)',                            //Relative strength Index
rvi     =   'rvi(src,len)',                            //The Relative Volatility Index (RVI) is calculated much like the RSI, although it uses high and low price standard deviation instead of the RSI’s method of absolute change in price.
smosc   =   'smi_osc(src,len,fast=5, slow=34)',        //smi Ergodic Oscillator
smsig   =   'smi_sig(src,len,fast=5, slow=34)',        //smi Ergodic Signal
stc     =   'stc(src,len,fast=23,slow=50)',            //Schaff Trend Cycle (STC) detects up and down trends long before the MACD. Code imported from @lazybear's (thanks) Schaff Trend Cycle script.
stdev   =   'stdev(src,len)',                          //Standart deviation
trix    =   'trix(src,len)' ,                          //TRIX rate of change of a triple exponentially smoothed moving average.
tsi     =   'tsi(src,len)',                            //True Strength Index indicator is a momentum oscillator designed to detect, confirm or visualize the strength of a trend.
ulos    =   'ultimateOsc(len)'                         //Ultimate Oscillator indicator (UO) indicator is a technical analysis tool used to measure momentum across three varying timeframes
vari    =   'variance(src,len)',                       //ta.variance(). Variance is the expectation of the squared deviation of a series from its mean (ta.sma), and it informally measures how far a set of numbers are spread out from their mean.
wilpc   =   'willprc(src,len)',                        //Williams %R
wad     =   'wad()',                                   //Williams Accumulation/Distribution.
wvad    =   'wvad()'                                   //Williams Variable Accumulation/Distribution.
//-------------------------}
 
//--------------------------
//--------Functions---------
//--------------------------{


//---------------------------------------------------------------------------------------------------
//FUNCTIONS WITH EXTENDED PARAMETERS 
//---------------------------------------------------------------------------------------------------



fn_stc(src, len=10, fast=23, slow=50,factor_=0.5) => //
    float f1=0,float f2=0, float pf=0, float pff=0
    fastMA = ta.ema(src, fast)
    slowMA = ta.ema(fast, slow)
    m = fastMA - slowMA
    v1 = ta.lowest(m, len)
    v2 = ta.highest(m, len) - v1    
    f1 := (v2 > 0 ? ((m - v1) / v2) * 100 : nz(f1[1])) 
    pf := (na(pf[1]) ? f1 : pf[1] + (factor_ * (f1 - pf[1]))) 
    v3 = ta.lowest(pf, len) 
    v4 = ta.highest(pf, len) - v3     
    f2 := (v4 > 0 ? ((pf - v3) / v4) * 100 : nz(f2[1])) 
    pff := (na(pff[1]) ? f2 : pff[1] + (factor_ * (f2 - pff[1])))
    pff



fn_volStop(src, atrlen, atrfactor=2) =>
    var max     = src
    var min     = src
    var uptrend = true
    var stop    = 0.0
    atrM        = nz(ta.atr(atrlen) * atrfactor, ta.tr)
    max         := math.max(max, src)
    min         := math.min(min, src)
    stop        := nz(uptrend ? math.max(stop, max - atrM) : math.min(stop, min + atrM), src)
    uptrend     := src - stop >= 0.0
    if uptrend != nz(uptrend[1], true)
        max    := src
        min    := src
        stop   := uptrend ? max - atrM : min + atrM
//    [stop, uptrend]
    stop
    
average(bp, tr_, length) => math.sum(bp, length) / math.sum(tr_, length)
fn_ultimateOsc(len_=7)=> 
    length2 = len_*2 
    length3 = len_*3
    high_ = math.max(high, close[1])
    low_ = math.min(low, close[1])
    bp = close - low_
    tr_ = high_ - low_
    avg7 = average(bp, tr_, len_)
    avg14 = average(bp, tr_, length2)
    avg28 = average(bp, tr_, length3)
    out = 100 * (4*avg7 + 2*avg14 + avg28)/7

fn_klinger(type_=0) =>  //type: 0=klinger, 1=signal
    var cumVol = 0.
    cumVol += nz(volume)
    if barstate.islast and cumVol == 0
        runtime.error("No volume is provided by the data vendor.")
    sv = ta.change(hlc3) >= 0 ? volume : -volume
    kvo = ta.ema(sv, 34) - ta.ema(sv, 55)
    sig = ta.ema(kvo, 13)
    result=type_==0?kvo:sig


fn_eom(len=14,div=10000) =>
    var cumVol = 0.
    cumVol += nz(volume)
    if barstate.islast and cumVol == 0
        runtime.error("No volume is provided by the data vendor.")
    result = ta.sma(div * ta.change(hl2) * (high - low) / volume, len)

fn_cmf(len) =>
    var cumVol = 0.
    cumVol += nz(volume)
    if barstate.islast and cumVol == 0
        runtime.error("No volume is provided by the data vendor.")
    ad = close==high and close==low or high==low ? 0 : ((2*close-low-high)/(high-low))*volume
    mf = math.sum(ad, len) / math.sum(volume, len)

dirmov(len) =>
	up = ta.change(high)
	down = -ta.change(low)
	plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
	minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
	truerange = ta.rma(ta.tr, len)
	plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
	minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
	[plus, minus]

fn_adx(dilen_=14, adxlen_=14, adxtype_=0) =>
	[plus, minus] = dirmov(dilen_)
	sum = plus + minus
	adx_ = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen_)
    result=adxtype_==0?adx_:adxtype_==1?plus:minus
    
fn_awesome(fast_=5,slow_=34,type_=0) =>
    ao = ta.sma(hl2,5) - ta.sma(hl2,34)
    diff = ao - ao[1]
    result=type_==0?ao:diff


fn_aroon(length_,dir_=0) =>
    upper_ = 100 * (ta.highestbars(high, length_+1) + length_)/length_
    lower_ = 100 * (ta.lowestbars(low, length_+1) + length_)/length_
    mid_ = (upper_+lower_)/2-50
    float result=0.
    result:=dir_==1?upper_:dir_==2?lower_:mid_


//bollinger %%
fn_bbr(src_, length_,mult_=1) =>
    dev_ = mult_ * ta.stdev(src_, length_)
    (src_ - ta.sma(src_, length_) + dev_) / (2 * dev_)
fn_alma(src_, length_, AlmaOffset_=0.85, AlmaSigma_=6)=>
    ta.alma(src_, length_, AlmaOffset_, AlmaSigma_)
    
fn_linreg(src_, length_, LOffset_=1)=>
    ta.linreg(src_, length_, int(LOffset_))

fn_kcw(src_, length_, mult_=2)=>
    ta.kcw(src_, length_, mult_)

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

fn_bbw(src_, length_, mult_=2)=>
    ta.bbw(src_, length_, mult_)
    
fn_ama(src_, length_, fastLength_=14,slowLength_=100)=>
    fastAlpha = 2 / (fastLength_ + 1)
    slowAlpha = 2 / (slowLength_ + 1)
    hh = ta.highest(length_ + 1)
    ll = ta.lowest(length_ + 1)
    mltp = hh - ll != 0 ? math.abs(2 * src_ - ll - hh) / (hh - ll) : 0
    ssc_ = mltp * (fastAlpha - slowAlpha) + slowAlpha
    ama_ = 0.0
    ama_ := nz(ama_[1]) + math.pow(ssc_, 2) * (src_ - nz(ama_[1]))    
    
fn_supertrend(length_,atrPeriod_=3)=>
    [sp_,dir_] = ta.supertrend(length_,atrPeriod_)
    sp_
fn_smiSignal(src_, length_, fastlength_=5, slowlength_=34) =>
    erg = ta.tsi(src_, fastlength_, slowlength_)  //indicaot
    sig = ta.ema(erg, length_)  //Signal
    sig

fn_smiOscillator(src_, length_, fastlength_=5, slowlength_=34) =>
    erg = ta.tsi(src_, fastlength_, slowlength_)  //indicaot
    sig = ta.ema(erg, length_)  //Signal
    osc = erg - sig  //Oscillator
    osc

//Ehler's Adaptive Laguerre filter
fn_lagAdapt(src_, length_,LAPercLen_=5,FPerc_=50) =>
    y = float(na)
    alpha = float(na)
    error = math.abs(src_ - nz(y[1]))
    le_=ta.lowest(error, length_)
    he_=ta.highest(error, length_) 
    range_2 = he_ - le_
    perc = range_2 != 0 ? (error - le_) / range_2 : nz(alpha[1])
    alpha := ta.percentile_nearest_rank(perc, int(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
fn_lagAdaptV(src_, length_,LAPercLen_=5,FPerc_=50) =>
    y = float(na)
    alpha = float(na)
    error = math.abs(src_ - nz(y[1]))
    le_=ta.lowest(error, length_)
    he_=ta.highest(error, length_) 
    range_3 = he_- le_
    perc = range_3 != 0 ? (error - le_) / range_3 : nz(alpha[1])
    alpha := ta.percentile_linear_interpolation(perc, int(LAPercLen_), int(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

//---------------------------------------------------------------------------------------------------
//FUNCTIONS WITHOUT EXTENDED PARAMETERS 
//---------------------------------------------------------------------------------------------------


fn_VWAP(src) =>
	var float sumSrcVol = na
	var float sumVol = na
    var float sumSrcSrcVol = na
    isNewPeriod=ta.change(time("D"))
	sumSrcVol := isNewPeriod ? src * volume : src * volume + sumSrcVol[1]
	sumVol := isNewPeriod ? volume : volume + sumVol[1]
	// sumSrcSrcVol calculates the dividend of the equation that is later used to calculate the standard deviation
	sumSrcSrcVol := isNewPeriod ? volume * math.pow(src, 2) : volume * math.pow(src, 2) + sumSrcSrcVol[1]

	_vwap = sumSrcVol / sumVol
	variance = sumSrcSrcVol / sumVol - math.pow(_vwap, 2)
	variance := variance < 0 ? 0 : variance
	stDev = math.sqrt(variance)
//	lowerBand = _vwap - stDev * stDevMultiplier
//	upperBand = _vwap + stDev * stDevMultiplier
	_vwap




fn_cti(src_, length_) => // Ehler's Correlation Trend Function by @midtownsk8rguy
    period = math.max(2, int(length_))
	Ex = 0.0, Ey = 0.0, Ex2 = 0.0, Ey2 = 0.0, Exy = 0.0
	for i=0 to length_-1 
		X = nz(src_[i])
		Y = -i
		Ex  := Ex  + X
		Ex2 := Ex2 + X * X
		Exy := Exy + X * Y
		Ey2 := Ey2 + Y * Y
		Ey  := Ey  + Y
	denominator = (length_ * Ex2 - Ex * Ex) * (length_ * Ey2 - Ey * Ey)
	denominator==0.0 or bar_index==0 ? 0.0 : (length_ * Exy - Ex * Ey) / math.sqrt(denominator)



fn_massIndex(len=10)=>
    span = high - low
    mi = math.sum(ta.ema(span, 9) / ta.ema(ta.ema(span, 9), 9), len)


fn_rvi(src_, length_) =>
    len = 14
    stddev = ta.stdev(src_, length_)
    upper = ta.ema(ta.change(src_) <= 0 ? 0 : stddev, len)
    lower = ta.ema(ta.change(src_) > 0 ? 0 : stddev, len)
    rvi_ = upper / (upper + lower) * 100

fn_mcGinley(src_, length_) =>
    mg = 0.0
    mg := na(mg[1]) ? ta.ema(src_, length_) : mg[1] + (src_ - mg[1]) / (length_ * math.pow(src_/mg[1], 4))

fn_dpo(len=14) =>
    barsback = len/2 + 1
    ma = ta.sma(close, len)
    dpo_ = close - ma[barsback]


fn_histvol(length_)=>
    annual = 365
    per = timeframe.isintraday or timeframe.isdaily and timeframe.multiplier == 1 ? 1 : 7
    hv = 100 * ta.stdev(math.log(close / close[1]), length_) * math.sqrt(annual / per)


fn_round_(val) => 
    val > .99 ? .999 : val < -.99 ? -.999 : val

fn_fisher(length_=9)=>
    high_ = ta.highest(hl2, length_)
    low_ = ta.lowest(hl2, length_)
    value = 0.0
    value := fn_round_(.66 * ((hl2 - low_) / (high_ - low_) - .5) + .67 * nz(value[1]))
    fish1 = 0.0
    fish1 := .5 * math.log((1 + value) / (1 - value)) + .5 * nz(fish1[1])


fn_efi(length_=13)=>
    var cumVol = 0.
    cumVol += nz(volume)
    if barstate.islast and cumVol == 0
        runtime.error("No volume is provided by the data vendor.")
    result = ta.ema(ta.change(close) * volume, length_)

fn_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

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


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


fn_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
fn_super2(src_, length_) =>
    y = float(na)
    PI_=3.145926
    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
fn_super3(src_, length_) =>
    y = float(na)
    PI_=3.145926
    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

fn_willprc(src_, length_) =>
	max = ta.highest(length_)
	min = ta.lowest(length_)
	100 * (src_ - max) / (max - min)

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

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

//Ehler's Laguerre filter
fn_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
fn_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)
fn_smma(src,l)=>
    smmaMA = 0.0
    sma_=ta.sma(src, l)
    smmaMA := na(smmaMA[1]) ? sma_ : (smmaMA[1] * (l - 1) + src) / l
    smmaMA

//---Sine-Weighted Moving Average (SW-MA)
fn_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)
fn_tma(src,l) =>
    triMA = ta.sma(ta.sma(src, math.ceil(l / 2)), math.floor(l / 2) + 1)
    triMA

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

//---Variable Index Dynamic Average (VIDA)
fn_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)
fn_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_
    
//---Range EMA (REMA)
fn_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    


fn_angle(_src1,_src2) =>
    rad2degree=180/3.14159265359  //pi 
    float ang=(rad2degree*math.atan((_src1 - _src2)/ta.atr(14)) )
    result=ang
//--------------------------}


//--------------------------
//--------Exported Functions
//--------------------------{

// @function            f_func          Return selected indicator value with different parameters. New version. Use extra parameters for available indicators
// @param string        FuncType_       indicator from the indicator list 
// @param float         src_            close, open, high, low,hl2, hlc3, ohlc4 or any [series]
// @param simple int    length_         indicator length
// @param float         p1              extra parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) 
// @param float         p2              extra parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) 
// @param float         p3              extra parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) 
// @param simple int    version_        indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators
// @returns float       [series]        Return calculated indicator value
export f_func(simple string function_, float src_, simple float length_, simple float p1_=0, simple float p2_=0, simple float p3_=0, simple int version_=1) =>
    float a=p1_*p2_*p3_*0 //used for passing the TV error: argument is not used. All args should be used.
    int length__=int(length_)
    float y = switch function_
        stc     =>      version_!=2?fn_stc(src_, length__):fn_stc(src=src_, len=length__, fast=int(p1_), slow=int(p2_),factor_=0.5)
        cti     =>      fn_cti(src_, length__)
        vwap    =>      fn_VWAP(src_)
        vstop   =>      version_!=2?fn_volStop(src_, length__):fn_volStop(src_, length__, atrfactor=p1_)
        ulos    =>      fn_ultimateOsc(length__)
        rvi     =>      fn_rvi(src_, length__)
        sar     =>      version_!=2?ta.sar(start=length_, inc=0.02, max=0.02):ta.sar(start=length_, inc=p1_, max=p2_)
        mgi     =>      fn_mcGinley(src_, length__)
        msi     =>      fn_massIndex(len=length__)
        kli     =>      fn_klinger(type_=length__)
        dpo     =>      fn_dpo(len=length__)
        hvo     =>      fn_histvol(length__)
        fit     =>      fn_fisher(length__)
        efi     =>      fn_efi(length__)
        eom     =>      version_!=2?fn_eom(length__):fn_eom(length__,div=p1_)
        cmf     =>      fn_cmf(length__)    
        awsom   =>      version_!=2?fn_awesome(fast_=length__):fn_awesome(fast_=length__,slow_=int(p1_),type_=int(p2_))
        adx     =>      version_!=2?fn_adx(length__):fn_adx(length__,int(p1_),int(p2_))
        aroon   =>      version_!=2?fn_aroon(length__):fn_aroon(length__,p1_)
        rangs   =>      version_!=2?(src_>=length_?1:src_<length_?-1:0):(src_>=length_?1:src_<p1_?-1:0)
        pvth    =>      version_!=2?ta.pivothigh(src_,length_,2):ta.pivothigh(src_,length_,p1_)
        pvtl    =>      version_!=2?ta.pivotlow(src_,length_, 2):ta.pivotlow(src_,length_, p1_)
        acdst	=>    	ta.accdist
        alma 	=>   	version_!=2?fn_alma(src_, length__)   : fn_alma(src_,   length__,p1_, p2_)
        ama     =>    	version_!=2?fn_ama(src_, length__):fn_ama(src_, length__, int(p1_), int(p2_))
        angle   =>    	fn_angle(src_, src_[length_])
        atr  	=>    	ta.atr(length__)
        bbr  	=>    	version_!=2?fn_bbr(src_, length__):fn_bbr(src_, length__,p1_)
        bbw  	=>    	version_!=2?fn_bbw(src_, length__): fn_bbw(src_, length__, p1_) 
        cci   	=>    	ta.cci(src_, length__)
        cctbb 	=>    	fn_cctbbo(src_, length__)
        chng  	=>    	ta.change(src_, length__)
        cma   	=>    	fn_cma(src_, length__)
        cmo   	=>    	ta.cmo(src_, length__)
        cog   	=>    	ta.cog(src_, length__)
        corrl	=>    	version_!=2?ta.correlation(src_, src_[1], length__):ta.correlation(src_, src_[int(p1_)], length__)
        count   =>    	fn_count(src_, length_)
        cpcrv   => 		version_!=2?ta.wma(ta.roc(src_, 34) + ta.roc(src_, 5), length__):ta.wma(ta.roc(src_, int(p2_)) + ta.roc(src_, int(p1_)), length__)
        dema  	=>    	fn_dema(src_, length__)
        dev   	=>    	ta.dev(src_, length__)
        ema   	=>    	ta.ema(src_, length__)
        fall  	=>    	ta.falling(src_, length__)?1:-1
        gmma  	=>    	fn_gmma(src_, length__)
        hghst	=>    	ta.highest(src_,length__)
        hide 	=>   	src_ + a   
        hl2ma   =>    	(ta.highest(src_, length__) + ta.lowest(src_, length__)) / 2
        hma   	=>    	ta.hma(src_, length__)
        kcr  	=>    	version_!=2?fn_kcr(src_, length__)  : fn_kcr(src_, length__,p1_)
        kcw  	=>    	version_!=2?fn_kcw(src_, length__) : fn_kcw(src_, length__,p1_)
        lexp  	=>    	fn_lexp(src_, length_)
        lgAdV   =>  	version_!=2?fn_lagAdaptV(src_, length__):fn_lagAdaptV(src_, length__, p1_, p2_)
        lgAdt   => 		version_!=2?fn_lagAdapt(src_, length__):fn_lagAdapt(src_, length__, p1_, p2_)
        lguer   =>  	fn_laguerre(src_, length_)
        linrg	=>    	version_!=2?fn_linreg(src_, length__) : fn_linreg(src_, length__,p1_)
        lowst	=>    	ta.lowest(src_,length__)
        lsrcp 	=>    	fn_lesrcp(src_, length_)
        macd  	=>    	ta.sma(src_, length__) - ta.sma(src_, 2 * length__)
        mfi   	=>    	ta.mfi(src_, length__)
        nvi  	=>    	ta.nvi
        obv  	=>    	ta.obv
        pcnl 	=>   	version_!=2?ta.percentile_nearest_rank(src_, length__, 50):ta.percentile_nearest_rank(src_, length__, p1_)
        pcnli   =>  	version_!=2?ta.percentile_linear_interpolation(src_, length__, 50):ta.percentile_linear_interpolation(src_, length__, p1_)
        prev  	=>    	src_[length_]
        pvi  	=>    	ta.pvi
        pvt  	=>    	ta.pvt
        rema  	=>    	fn_range_ema(src_, length_)
        rise  	=>    	ta.rising(src_, length__)?1:-1
        rma   	=>    	ta.rma(src_, length__)
        roc   	=>    	ta.roc(src_, length__)
        rsi   	=>    	ta.rsi(src_, length__) 
        sma   	=>    	ta.sma(src_, length__)
        smma  	=>    	fn_smma(src_, length__)
        smosc	=>    	version_!=2?fn_smiOscillator(src_, length__):fn_smiOscillator(src_, length__, int(p1_), int(p2_))
        smsig	=>    	version_!=2?fn_smiSignal(src_, length__):fn_smiSignal(src_, length__, int(p1_), int(p2_))
        stdev   =>    	ta.stdev(src_, length__)
        strnd 	=>    	version_!=2?fn_supertrend(length_):fn_supertrend(length_,int(p1_))
        supr2 	=>    	fn_super2(src_, length_)
        supr3 	=>    	fn_super3(src_, length_)
        swma  	=>    	fn_swma(src_, length_)
        tema    =>      fn_tema(src_, length__)
        tma   	=>    	fn_tma(src_, length_)
        trix  	=>    	fn_trix(src_, length__)
        tsi  	=>    	version_!=2?ta.tsi(src_, 5, 34):ta.tsi(src_, int(p1_), int(p2_))
        vari    => 		ta.variance(src_, length__)
        vida  	=>    	fn_vida(src_, length__)
        vwma  	=>    	ta.vwma(src_, length__)
        wad  	=>    	ta.wad
        wilpc 	=>   	fn_willprc(src_, length__)
        wma   	=>    	ta.wma(src_, length__)
        wvad 	=>    	ta.wvad
        org     =>      src_
        =>      na
    y:=na(y)?0:y    
    y

// @function            fn_heikin  Return given  src data (open, high,low,close) as heikin ashi candle values
// @param float         o_              open value
// @param float         h_              high value
// @param float         l_              low value
// @param float         c_              close value
// @returns float       [series, series,series,series]  heikin ashi open, high,low,close vlues that will be used with plotcandle 
export fn_heikin(float o_=open, float h_=high, float l_=low, float c_=close)  => 
    Close  = math.avg(o_,h_,l_,c_)
    Open   = float(na)
    Open  := na(Open[1]) ? (o_ + c_) / 2 : (nz(Open[1]) + nz(Close[1])) / 2
    High   = math.max(h_, math.max(Open, Close))
    Low    = math.min(l_,  math.min(Open, Close))
    
    Open  := math.round(Open /  syminfo.mintick) * syminfo.mintick
    High  := math.round(High /  syminfo.mintick) * syminfo.mintick
    Low   := math.round(Low /   syminfo.mintick) * syminfo.mintick
    Close := math.round(Close / syminfo.mintick) * syminfo.mintick
    [Open, High, Low, Close]


// @function            fn_plotFunction Return input src data with different plotting options
// @param float         src_            indicator src_data or any other series.....
// @param string        plotingType     Ploting type of the function on the screen ['Original', 'Stochastic', 'PercentRank','Org. Range (-1,1)']
// @param simple int    stochlen_       length for plotingType for stochastic and PercentRank options
// @param bool          plotSWMA        Use SWMA for smoothing Ploting
// @returns float       [series]
export fn_plotFunction(float src_, simple string plotingType_="Original", simple int stochlen_=50, bool plotSWMA_ = false) =>
    f_plot_= switch plotingType_ 
        "Stochastic" => ta.stoch(src_, src_, src_, stochlen_) / 50 - 1 
        "PercentRank" => ta.percentrank(src_, stochlen_) / 50 - 1 
        "Original" => src_
        "Org. Range (-1,1)" => src_
        => src_
    if plotSWMA_
        f_plot_:= ta.swma(f_plot_)
    f_plot_


// @function            fn_funcPlotV2   Return selected indicator value with different parameters. New version. Use extra parameters fora available indicators
// @param string        FuncType_       indicator from the indicator list
// @param float         src_data_       close, open, high, low,hl2, hlc3, ohlc4 or any [series]
// @param simple int    length_         indicator length
// @param float         p1              extra parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) 
// @param float         p2              extra parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) 
// @param float         p3              extra parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) 
// @param simple int    version_        indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators
// @param string        plotingType     Ploting type of the function on the screen ['Original', 'Stochastic', 'PercentRank','Org. Range (-1,1)']
// @param simple int    stochlen_       length for plotingType for stochastic and PercentRank options
// @param bool          plotSWMA        Use SWMA for smoothing Ploting
// @param bool          log_            Use log on function entries
// @returns float       [series]        Return calculated indicator value
export fn_funcPlotV2(simple string FuncType_="Hide", float src_data_=close, simple float length_=14, simple float p1=0, simple float p2=0,  simple int version_=2, simple float p3=0, simple string plotingType_="Original", simple int stochlen_=50, bool plotSWMA_ = false, simple string log_="None") =>
    src_data__=log_=="Simple" ? math.log(src_data_) : 
               log_=="Log10"  ? math.log10(src_data_) :
               src_data_
    src_=f_func(FuncType_, src_data__, length_,p1,p2,p3,version_=version_) 
    f_plot_=fn_plotFunction(src_=src_, plotingType_=plotingType_, stochlen_=stochlen_, plotSWMA_ = plotSWMA_)

 
// @function            fn_factor       Return selected indicator's  factorization with given arguments 
// @param string        FuncType_       indicator from the indicator list
// @param float         src_data_       close, open, high, low,hl2, hlc3, ohlc4 or any [series]
// @param simple int    length_         indicator length
// @param float         p1              parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) 
// @param float         p2              parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) 
// @param float         p3              parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) 
// @param simple int    version_        indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators
// @param simple int    fact_           Add double triple, Quatr factor to selected  indicator (like converting EMA to 2-DEMA, 3-TEMA, 4-QEMA...)
// @param string        plotingType     Ploting type of the function on the screen ['Original', 'Stochastic', 'PercentRank','Org. Range (-1,1)']
// @param simple int    stochlen_       length for plotingType for stochastic and PercentRank options
// @param bool          plotSWMA        Use SWMA for smoothing Ploting
// @param bool          log_            Use log on function entries
// @returns float       [series]        Return result of the function
export fn_factor(simple string FuncType_="Hide", float src_data_=close, simple float  length_=14, simple float p1=0, simple float p2=0, simple float p3=0, simple int version_=2, simple int fact_=1, simple string plotingType_="Original", simple int stochlen_=50, bool plotSWMA_ = false, simple string log_="None")=>

    float result=0
    if FuncType_!=hide    
        float xIND1 = 0, float xIND2 = 0,float xIND3 = 0, float xIND4 = 0, float xIND5 = 0
        xIND1 := fn_funcPlotV2(FuncType_, src_data_,length_=length_, p1=p1, p2=p2, p3=p3, version_=version_)
        if fact_>1
            xIND2 := fn_funcPlotV2(FuncType_,xIND1, length_=length_, p1=p1, p2=p2, p3=p3, version_=version_)
        if fact_>2
            xIND3 := fn_funcPlotV2(FuncType_,xIND2, length_=length_, p1=p1, p2=p2, p3=p3, version_=version_)
        if fact_>3
            xIND4 := fn_funcPlotV2(FuncType_,xIND3, length_=length_, p1=p1, p2=p2, p3=p3, version_=version_)
            xIND5 := fn_funcPlotV2(FuncType_,xIND4, length_=length_, p1=p1, p2=p2, p3=p3, version_=version_)
    
        indfact_ = switch fact_
            1      =>  xIND1
            2      =>  (2 * xIND1) - xIND2
            3      =>  3 * (xIND1 - xIND2) + xIND3
            4      =>  5 * xIND1 - 10 * xIND2 + 10 * xIND3 - 5 * xIND4 + xIND5  

        result := fn_funcPlotV2(org, indfact_,length_=length_,  version_=1, plotingType_=plotingType_, stochlen_=stochlen_,  plotSWMA_=plotSWMA_, log_=log_)
    result

 

// @function            fn_plotCandles  Return selected indicator's candle values with different parameters also heikinashi is available
// @param string        FuncType_       indicator from the indicator list
// @param simple int    length_         indicator length
// @param float         p1              parameter-1. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) 
// @param float         p2              parameter-2. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) 
// @param float         p3              parameter-3. active on Version 2 for defining multi arguments indicator input value. ex: lagAdapt(src_, length_,LAPercLen_=p1,FPerc_=p2) 
// @param simple int    version_        indicator version for backward compatibility. V1:dont use extra parameters p1,p2,p3 and use default values. V2: use extra parameters for available indicators
// @param string        plotingType     Ploting type of the function on the screen ['Original', 'Stochastic', 'PercentRank','Org. Range (-1,1)']
// @param simple int    stochlen_       length for plotingType for stochastic and PercentRank options
// @param bool          plotSWMA        Use SWMA for smoothing Ploting
// @param bool          log_            Use log on function entries
// @param bool          plotheikin_     Use Heikin Ashi on Plot
// @returns float       [series]
export fn_plotCandles(simple string FuncType_,simple float len_, simple float p1=0, simple float p2=0, simple float p3=0, simple int version_=2,  simple int fact_=1, simple string plotingType_="Original", simple int stochlen_=50, bool plotSWMA_ = false, simple string log_="None", bool plotheikin_=false,float oIn_=open,float hIn_=high, float lIn_=low, float cIn_=close )=>
    oOut_=0.0, hOut_=0.0, lOut_=0.0, cOut_=0.0
    bool palette_=false
    if FuncType_!=hide    
        oOut_:=fn_factor(FuncType_=FuncType_, src_data_=oIn_, length_=len_, p1=p1, p2=p2, p3=p3, version_=version_, fact_=fact_, plotingType_=plotingType_, stochlen_=stochlen_,  plotSWMA_=plotSWMA_, log_=log_)
        hOut_:=fn_factor(FuncType_=FuncType_, src_data_=hIn_, length_=len_, p1=p1, p2=p2, p3=p3, version_=version_, fact_=fact_, plotingType_=plotingType_, stochlen_=stochlen_,  plotSWMA_=plotSWMA_, log_=log_)
        lOut_:=fn_factor(FuncType_=FuncType_, src_data_=lIn_, length_=len_, p1=p1, p2=p2, p3=p3, version_=version_, fact_=fact_, plotingType_=plotingType_, stochlen_=stochlen_,  plotSWMA_=plotSWMA_, log_=log_)
        cOut_:=fn_factor(FuncType_=FuncType_, src_data_=cIn_, length_=len_, p1=p1, p2=p2, p3=p3, version_=version_, fact_=fact_, plotingType_=plotingType_, stochlen_=stochlen_,  plotSWMA_=plotSWMA_, log_=log_)
  
        palette_ := cOut_[1] <= cOut_ ? true : false

        if plotheikin_
            [oOut__,hOut__,lOut__,cOut__]=fn_heikin(o_=oOut_, h_=hOut_, l_=lOut_, c_=cOut_)
            oOut_:=oOut__, hOut_:=hOut__, lOut_:=lOut__, cOut_:=cOut__

    [oOut_,hOut_,lOut_,cOut_, palette_]

//--------------------------}






//----------------------------------------------------------------------------------------------------------------------------------
//--------DEMO----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------{
 //Indicators that returned plot function values
float f_indicator1=0
float f_indicator2=0
float ext_data =      input.source(   defval=close,          title='External Indicator') 

//Function returns source values from given input
//Ex:  ind_data =input.string(defval="close", title='',options=["close", "open", "high", "low","hl2", "hlc3", "ohlc4","IND1"]) 
fn_get_source(string source_) => 
    result  =   switch source_
        "close" =>  close 
        "open"  =>  open 
        "high"  =>  high 
        "low"   =>  low 
        "hl2"   =>  hl2 
        "hlc3"  =>  hlc3 
        "ohlc4" =>  ohlc4
        "volume" =>  volume        
        "EXT"   =>  ext_data        
        "IND1"  =>  f_indicator1  //ex:return calculated indicator or another source entry for using in new calculation
        "IND2"  =>  f_indicator2  //ex:return calculated indicator or another source entry for using in new calculation
        =>na
    result
//--------------------------} 
 
 
//----------------------------------------------------------------------------------------------------------------------------------------
//INDICATOR 1-----------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------
s_grp_indicator1="════════════ INDICATOR 1 ════════════"
s_ind1_src=        input.string(   defval=ema,           title='IND1:',       options=[hide, org, ovrly, 
                                                                                     alma, ama  , acdst, cma,  dema, ema, gmma, hghst, hl2ma, hma, lgAdt, lgAdV, lguer, lsrcp, lexp, linrg, lowst, 
                                                                                     mgi,pcnl, pcnli, prev , pvth, pvtl, rema, rma, sar, sma, smma, supr2, supr3, strnd, swma, tema, tma, vida, vwma, vstop, wma, vwap, 
                                                                                     nvrly, 
                                                                                     adx, angle, aroon, atr, awsom, bbr, bbw, cci, cctbb, chng, cmf, cmo, cog, cpcrv, corrl, count, cti, dev, dpo, efi, eom, 
                                                                                     fall, fit, hvo, kcr, kcw, kli, macd, mfi, msi, nvi, obv, pvi, pvt, rangs, rise, roc, rsi, rvi, smosc, smsig, stc, stdev, trix, 
                                                                                     tsi, vari, wilpc, wad, wvad] 
                                                                          ,   group=s_grp_indicator1, inline="ind1")
s_ind1_data =      input.string(   defval="close",        title='',           options=["close", "open", "high", "low","hl2", "hlc3", "ohlc4", "volume", "EXT"]  ,  group= s_grp_indicator1, inline="ind1") 
f_ind1_len   =     input.float(    defval=14,             title='Len',        group=s_grp_indicator1, inline="ind1")
i_ind1_ver  =      input.int(      defval=1,              title='V',          group=s_grp_indicator1, inline="ind2", minval=1, maxval=2)
f_ind1_p1   =      input.float(    defval=0,              title='P1',         group=s_grp_indicator1, inline="ind2")
f_ind1_p2   =      input.float(    defval=0,              title='P2',         group=s_grp_indicator1, inline="ind2")
i_ind1_fact =      input.int(      defval=1,              title='factor',     group=s_grp_indicator1, inline="ind4", minval=1,maxval=4)
s_ind1_log =       input.string(   defval="None",         title='Log',        group=s_grp_indicator1, inline="ind4", options=['None', 'Simple', 'Log10'])
s_ind1_pType =     input.string(   defval="Original",     title="PType",      group=s_grp_indicator1, inline="ind3", options=['Original', 'Stochastic', 'PercentRank','Org. Range (-1,1)'])
i_ind1_stlen =     input.int(      defval=50,             title='St/% val',   group=s_grp_indicator1, inline="ind3")
b_ind1_pSWMA=      input.bool(     defval=false,          title="Smooth",     group=s_grp_indicator1, inline="ind3")
c_ind1_color =     input(          defval=color.green,    title="",           group=s_grp_indicator1, inline="ind3")
b_plt1_candle =    input.bool(     defval=true,           title='Plot Candle',group=s_grp_indicator1, inline="plt")
b_plt1_ind =       input.bool(     defval=true,           title='Plot Ind',   group=s_grp_indicator1, inline="plt")
b_plt1_heikin =    input.bool(     defval=false,          title='HeikinAshi', group=s_grp_indicator1, inline="plt")
//f_ind1_p3   =    input.float(    defval=0,              title='P3',         group=s_grp_indicator1, inline="ind2")  //to be activated in the future

oOut1=0.0, hOut1=0.0, lOut1=0.0, cOut1=0.0
palette1=color.green

//PLOT INDICATOR 1
if s_ind1_src!=hide and b_plt1_ind!=false 
    s_ind1_data_=fn_get_source(s_ind1_data)
    f_indicator1:=fn_factor(FuncType_=s_ind1_src, src_data_=s_ind1_data_, length_=f_ind1_len, p1=f_ind1_p1, p2=f_ind1_p2,  version_=i_ind1_ver, fact_=i_ind1_fact, plotingType_=s_ind1_pType, stochlen_=i_ind1_stlen, plotSWMA_=b_ind1_pSWMA,  log_=s_ind1_log)

plot(s_ind1_src==hide or b_plt1_ind==false ?na:f_indicator1, color=c_ind1_color, title='indicator1', linewidth=2)

//PLOT FUNCTION CANDLES 1
if s_ind1_src!=hide and b_plt1_candle!=false 
    [oOut_, hOut_, lOut_, cOut_, palette_] = fn_plotCandles(FuncType_=s_ind1_src,len_=f_ind1_len, p1=f_ind1_p1, p2=f_ind1_p2, version_=i_ind1_ver,fact_=i_ind1_fact, plotingType_=s_ind1_pType, stochlen_=i_ind1_stlen, plotSWMA_=b_ind1_pSWMA,  log_=s_ind1_log, plotheikin_=b_plt1_heikin )
    oOut1:=oOut_, hOut1:=hOut_, lOut1:=lOut_, cOut1:=cOut_
    palette1 := palette_ ? color.green : color.red


pc1_=s_ind1_src==hide or b_plt1_candle==false
plotcandle(pc1_?na:oOut1, pc1_?na:hOut1, pc1_?na:lOut1, pc1_?na:cOut1, color=palette1, title='Filter Candles 1')

//----------------------------------------------------------------------------------------------------------------------------------------
//INDICATOR 2-----------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------
s_grp_indicator2="════════════ INDICATOR 2 ════════════"
s_ind2_src=        input.string(   defval=ema,           title='IND2:',        options=[hide, org, ovrly, 
                                                                                     alma, ama  , acdst, cma,  dema, ema, gmma, hghst, hl2ma, hma, lgAdt, lgAdV, lguer, lsrcp, lexp, linrg, lowst, 
                                                                                     mgi,pcnl, pcnli, prev , pvth, pvtl, rema, rma, sar, sma, smma, supr2, supr3, strnd, swma, tema, tma, vida, vwma, vstop, wma, vwap, 
                                                                                     nvrly, 
                                                                                     adx, angle, aroon, atr, awsom, bbr, bbw, cci, cctbb, chng, cmf, cmo, cog, cpcrv, corrl, count, cti, dev, dpo, efi, eom, 
                                                                                     fall, fit, hvo, kcr, kcw, kli, macd, mfi, msi, nvi, obv, pvi, pvt, rangs, rise, roc, rsi, rvi, smosc, smsig, stc, stdev, trix, 
                                                                                     tsi, vari, wilpc, wad, wvad] 
                                                                         ,     group=s_grp_indicator2, inline="ind1")
//ind2_data =      input.source(   defval=close,           title='',           group=s_grp_indicator2, inline="ind1") 
s_ind2_data =      input.string(   defval="close",         title='',           options=["close", "open", "high", "low","hl2", "hlc3", "ohlc4", "volume", "EXT", "IND1"]  ,  group= s_grp_indicator2, inline="ind1") 
f_ind2_len   =     input.float(    defval=48,              title='Len',        group=s_grp_indicator2, inline="ind1")
i_ind2_ver  =      input.int(      defval=1,               title='V',          group=s_grp_indicator2, inline="ind2", minval=1, maxval=2)
f_ind2_p1   =      input.float(    defval=0,               title='P1',         group=s_grp_indicator2, inline="ind2")
f_ind2_p2   =      input.float(    defval=0,               title='P2',         group=s_grp_indicator2, inline="ind2")
i_ind2_fact =      input.int(      defval=1,               title='factor',     group=s_grp_indicator2, inline="ind4", minval=1,maxval=4)
s_ind2_log =       input.string(   defval="None",          title='Log',        group=s_grp_indicator2, inline="ind4", options=['None', 'Simple', 'Log10'])
s_ind2_pType =     input.string(   defval="Original",      title="PType",      group=s_grp_indicator2, inline="ind3", options=['Original', 'Stochastic', 'PercentRank','Org. Range (-1,1)'])
i_ind2_stlen =     input.int(      defval=50,              title='St/% val',   group=s_grp_indicator2, inline="ind3")
b_ind2_pSWMA=      input.bool(     defval=false,           title="Smooth",     group=s_grp_indicator2, inline="ind3")
c_ind2_color =     input(          defval=color.red,       title="",           group=s_grp_indicator2, inline="ind3")
b_plt2_candle =    input.bool(     defval=true,            title='Plot Candle',group=s_grp_indicator2, inline="plt")
b_plt2_ind =       input.bool(     defval=true,            title='Plot Ind',   group=s_grp_indicator2, inline="plt")
b_plt2_heikin =    input.bool(     defval=false,           title='HeikinAshi', group=s_grp_indicator2, inline="plt")
//ind2_p3   =     input.float(    defval=0,               title='P3',        group=s_grp_indicator2, inline="ind2")  //to be activated in the future

oOut2=0.0, hOut2=0.0, lOut2=0.0, cOut2=0.0
palette2=color.green

//PLOT INDICATOR 2

if s_ind2_src!=hide and b_plt2_ind!=false 
    s_ind2_data_=fn_get_source(s_ind2_data)
    f_indicator2:=fn_factor(FuncType_=s_ind2_src, src_data_=s_ind2_data_, length_=f_ind2_len, p1=f_ind2_p1, p2=f_ind2_p2, version_=i_ind2_ver, fact_=i_ind2_fact, plotingType_=s_ind2_pType, stochlen_=i_ind2_stlen, plotSWMA_=b_ind2_pSWMA,  log_=s_ind2_log)

plot(s_ind2_src==hide or b_plt2_ind==false ?na:f_indicator2, color=c_ind2_color, title='indicator2', linewidth=2)

//PLOT FUNCTION CANDLES 2
if s_ind2_src!=hide and b_plt2_candle!=false 
    [oOut_, hOut_, lOut_, cOut_, palette_] = fn_plotCandles(FuncType_=s_ind2_src,len_=f_ind2_len, p1=f_ind2_p1, p2=f_ind2_p2, version_=i_ind2_ver,fact_=i_ind2_fact, plotingType_=s_ind2_pType, stochlen_=i_ind2_stlen, plotSWMA_=b_ind2_pSWMA,  log_=s_ind2_log, plotheikin_=b_plt2_heikin )
    oOut2:=oOut_, hOut2:=hOut_, lOut2:=lOut_, cOut2:=cOut_
    palette2 := palette_ ? color.green : color.red


pc2_=s_ind2_src==hide or b_plt2_candle==false
plotcandle(pc2_?na:oOut2, pc2_?na:hOut2, pc2_?na:lOut2, pc2_?na:cOut2, color=palette2, title='Filter Candles 2')

//----------------------------------------------------------------------------------------------------------------------------------
//--------END DEMO------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------}
