// Downloaded From https://www.WiseStockTrader.com
// Adaptive Stochastic RSI
// by Albert Lyubarsky


//
// Internally RSI is implemented as follows
//
function BuiltInRSIEquivalent( period )
{
P = N = 0;

result = Null;

for( i = 1; i < BarCount; i++ )
{
diff = C[ i ] - C[ i - 1 ];
W = S = 0;
if( diff > 0 ) W = diff;
if( diff < 0 ) S = -diff;

P = ( ( period[i] -1 ) * P + W ) / period[i];
N = ( ( period[i] -1 ) * N + S ) / period[i];

if( i >= period[i] )
result[ i ] = 100 * P / ( P + N );
}
return result;
} 

function StochKCust(Series, Period)
{
		return (Series- LLV(Series,Period)) / (HHV(Series,Period) - LLV(Series,Period)) * 100;

}

Lo_limit = 5;
Hi_limit = 20;
spansize = ParamList( "SpanSize", "24|48|96|192", defaultval = 1 );
smooth = Param("Smooth",8,2,25,1);
CFB = JurikCFB( Close, smooth , StrToNum(spansize) );

CFB_max = 0;
CFB_min = 99999;
ADP_Length = C - C;
for (i=0; i<BarCount; i++)
{
	if (CFB[i] > CFB_max)
	{
	 	CFB_max = CFB[i];
	}
	else if (CFB[i] < CFB_min)
	{
		CFB_min = CFB[i];
	}
	
	denominator = CFB_max - CFB_min;
	if (denominator > 0)
	{
		stoch_ratio = (CFB[i] - CFB_min) / denominator ;
	}
	else
	{
		stoch_ratio = 0.5;
	}
	
	ADP_Length[i] = ceil(Lo_limit + stoch_ratio * (Hi_limit - Lo_limit));	
}
 
Plot(StochKCust(BuiltInRSIEquivalent(ADP_Length), ADP_Length), "AdaptiveStochRSI", colorWhite);
Plot(StochKCust(C, 9), "StochRSI", colorYellow);