// Downloaded From https://www.WiseStockTrader.com
_SECTION_BEGIN("Adaptive BB");

Color = ParamColor("Color", colorLightGrey );
Style = ParamStyle("Style") | styleNoRescale;

top20 = BBandTop(C, 20, 2);
bot20 = BBandBot(C, 20, 2);
top21 = BBandTop(C, 20, 2.1);
bot21 = BBandBot(C, 20, 2.1);
top22 = BBandTop(C, 20, 2.2);
bot22 = BBandBot(C, 20, 2.2);
top23 = BBandTop(C, 20, 2.3);
bot23 = BBandBot(C, 20, 2.3);
top24 = BBandTop(C, 20, 2.4);
bot24 = BBandBot(C, 20, 2.4);
top25 = BBandTop(C, 20, 2.5);
bot25 = BBandBot(C, 20, 2.5);

top19 = BBandTop(C, 20, 1.9);
bot19 = BBandBot(C, 20, 1.9);
top18 = BBandTop(C, 20, 1.8);
bot18 = BBandBot(C, 20, 1.8);
top17 = BBandTop(C, 20, 1.7);
bot17 = BBandBot(C, 20, 1.7);
top16 = BBandTop(C, 20, 1.6);
bot16 = BBandBot(C, 20, 1.6);
top15 = BBandTop(C, 20, 1.5);
bot15 = BBandBot(C, 20, 1.5);

function getBBBot(SD)
{
	switch(SD)
	{
		case 1.5:
			ret = bot15;
		case 1.6:
			ret =  bot16;
		case 1.7:
			ret =  bot17;
		case 1.8:
			ret =  bot18;
		case 1.9:
			ret =  bot19;
		case 2.0:
			ret =  bot20;
		case 2.1:
			ret =  bot21;
		case 2.2:
			ret =  bot22;
		case 2.3:
			ret =  bot23;
		case 2.4:
			ret =  bot24;
		case 2.5:
			ret =  bot25;
	}
	return ret;
}

function getBBTop(SD)
{
	switch(SD)
	{
		case 1.5:
			ret =  top15;
		case 1.6:
			ret =  top16;
		case 1.7:
			ret =  top17;
		case 1.8:
			ret =  top18;
		case 1.9:
			ret =  top19;
		case 2.0:
			ret =  top20;
		case 2.1:
			ret =  top21;
		case 2.2:
			ret =  top22;
		case 2.3:
			ret =  top23;
		case 2.4:
			ret =  top24;
		case 2.5:
			ret =  top25;
	}
	return ret;
}

LookBack = 100;
threshold = 0.05;
StdDevs = 2;
CurrStdDev = 2;
for(i = LookBack; i < BarCount; i++)
{
	Count = 0;
	top = getBBTop(CurrStdDev);
	bot = getBBBot(CurrStdDev);
	for(j = i - LookBack; j < i; j++)
	{
		if(H[j] > top[j]) Count++;
		if(L[j] < bot[j]) Count++;
	}

	if(Count >= (LookBack * threshold))
	{
		CurrStdDev += 0.1;
		if(CurrStdDev > 2.5) CurrStdDev = 2.5; 
		StdDevs[i] = CurrStdDev;
	}
	else
	{
		CurrStdDev -= 0.1;
		if(CurrStdDev < 1.5) CurrStdDev = 1.5;
		StdDevs[i] = CurrStdDev;
	}
}

EMAPrice = EMA(C, 20);
StdDevPrice = StDev(C, 20);
bandUpper = EMAPrice + StdDevPrice * StdDevs;
bandLower = EMAPrice - StdDevPrice * StdDevs;

Plot(bandUpper, "BBTop" + _PARAM_VALUES(), Color, Style ); 
Plot(bandLower, "BBBot" + _PARAM_VALUES(), Color, Style ); 

_SECTION_END();