{ Downloaded From https://www.WiseStockTrader.com }
method:=Input("Method (1=Cycle, 2=Volatility, 3=Combined): ", 1,3,1);

{-----Begin Cycle Method----------}

plot:=Zig(MESASineWave(70),10,%);

top:=plot<Ref(plot,-1) AND Ref(plot,-1)>Ref(plot,-2);
NumberOfPeaks:=Cum(top);
BarsBetweenPeaks:=If(top,Ref(BarsSince(top),-1),0);
TotalBarsBetPeaks:=Cum(BarsBetweenPeaks);
AvgBarsBetweenPeaks:=TotalBarsBetPeaks/NumberOfPeaks;
LookBackMethod1:=Int(Rnd(AvgBarsBetweenPeaks/2));

{-----Begin Normalized Volatility Method----------}

Volatility:=(LinRegSlope((STE(C,20)/C)*100 ,9)/If(STE((STE(C,20)/C)*100,9)=0,.0001,STE((STE(C,20)/C)*100,9))) *100;

divisor:=If(volatility<=0,1-(Abs(volatility)/1000),1+(Abs(volatility)/1000));
{the smaller the divisor(i.e., higher volatility) the shorter the lookback periods}
LookbackMethod2:=20/(1.5*divisor);


Lookbackmethod3:=LookbackMethod1/(1.5*divisor);

{-----Final Calculation and Plot------}

If(method=1,
Wilders(C, LastValue(Rnd(LookbackMethod1)+PREV-PREV)),
If(method=2,
Wilders(C, LastValue(Rnd(LookbackMethod2)+PREV-PREV)),
If(method=3,
Wilders(C, LastValue(Rnd(LookbackMethod3)+PREV-PREV)),0)))