// Downloaded From https://www.WiseStockTrader.com
/****
   Converted by Kelvinhand @20160123
   From: https://jp.tradingview.com/script/ng...-Tops-Bottoms/ 

 ****/

pctile = Param("Percentile Threshold Extreme Value, Exceeding Creates Colored Histogram", 90, 1, 999);
wrnpctile = Param("Percentile Threshold Warning Value, Exceeding Creates Colored Histogram", 70, 1,999);
pmShort = Param("PPO Setting - Short", 0.4, 0.1, 100, 0.1);
pmLong = Param("PPO Setting - Long",0.8, 0.1, 100, 0.1);

lkbT = Param("Look Back Period for 'Tops' %Rank is based off of?", 200, 3, 999);
lkbB = Param("Look Back Period For 'Bottoms' %Rank is based off of?", 200, 3, 999);

sl=ParamToggle("Show Threshold Line?", "No|Yes", 1);
swl=ParamToggle("Show Warning Threshold Line?", "No|Yes", 1);


//Laguerre PPO Code from TheLark
function lag(g,p) 
{

f[0]=L0[0] = L1[0] = L2[0] = L3[0] = 0;

    for(i=1;i<BarCount;i++)
    {
        L0[i] = (1-g)*p[i]+g*L0[i-1];
        L1[i] = -g*L0[i]+L0[i-1]+g*L1[i-1];
        L2[i] = -g*L1[i]+L1[i-1]+g*L2[i-1];
        L3[i] = -g*L2[i]+L2[i-1]+g*L3[i-1];
        f[i] = (L0[i]+2*L1[i]+ 2*L2[i] + L3[i])/6;
    }

    return f;

}


hl2 = (H+L)/2;

lmas = lag(pmShort, hl2);
lmal = lag(pmLong,  hl2);


pctileB = -1*pctile;
wrnpctileB = -wrnpctile;

//PPO Plot
ppoT = 100*(lmas - lmal)/lmal;
ppoB = 100*(lmal - lmas)/lmal;

//PercentRank of PPO 
pctRankT = percentrank(ppoT, lkbT);
pctRankB = -1*percentrank(ppoB, lkbB);

//Color Definition of Columns
colT = IIf(pctRankT >= pctile, colorred, IIf(pctRankT >= wrnpctile and pctRankT < pctile,  colororange , colorgrey50));
colB = IIf(pctRankB <= pctileB, colorlime, IIf(pctRankB <= wrnpctileB and pctRankB < pctileB,  colorgreen , colorgrey50));

//Plot Statements.        
SetBarFillColor(colT);
plot(pctRankT,"Tops %Rank Columns", colorLightGrey, styleArea|styleThick, Null, Null, 0, -1);
PlotGrid(IIf(sl and pctile , pctile, Null), colorred, 10,4);
PlotGrid(IIf(swl and wrnpctile , wrnpctile, Null), colorOrange, 10,4);  

SetBarFillColor(colB);
plot(pctRankB,"Bottoms %Rank Columns", colorLightGrey, styleArea|styleThick, Null, Null, 0, -1);
PlotGrid(IIf(sl and pctileB, pctileB, Null), colorlime, 10,4);
PlotGrid(IIf(swl and wrnpctileB, wrnpctileB, Null), colorGreen, 10,4);  
  
plotGrid(0, colorGrey40,9, 5);