Buy on x bars retrace from peak

Hi,

I've been working on how to enter a long position x bars after the peak, where x = number of bars in the most recent zag (down).

x

The white box (Buy) sometimes appears where it's supposed to, but not always. I have tried using FILTER to check variables and they seem ok. Not sure what's happening. Any ideas appreciated.


GraphZOrder = True; 
_N( Title = StrFormat( "{{NAME}} - {{INTERVAL}} {7/06/2017} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) \n{{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ) ); 
SetBarFillColor( IIf( C > O, ParamColor( "Candle UP Color", colorbluegrey ), IIf( C <= O, ParamColor( "Candle Down Color", colorRed ), colorlightGrey ) ) ); 
Plot( C, "", IIf( C > O, ParamColor( "Wick UP Color", colorbluegrey ), IIf( C <= O, ParamColor( "Wick Down Color", colorRed ), colorLightGrey ) ), styleBar, 0, 0, 0, 0 ); 
PositionSize = 10000;

n = .1;
z = Zig(c,n );
Plot(z, "",colorWhite);

tr = C<Ref(c,-1) AND C<Ref(c,1);
pk = C>Ref(c,-1) AND C>Ref(c,1);
 
s = PeakBars(C,n,2);
ss = TroughBars(C,n,1);
x = s-ss;  // x = number of bars in last ZAG

Bi =  pk AND  C>Peak(C,n,2)  AND V*C>10000000 ;

Buy = Ref( Bi, -x );

SellPrice = c; 
Sell = C>o;
applystop(stopTypeNBar,stopModeBars,3); 

PlotShapes( Bi * shapecircle, coloryellow, 0, H+.05*ATR(3)); 
PlotShapes( Buy*shapeHollowSquare, colorWhite,0,C); 

Filter = bi ;
AddColumn(s,"s");
AddColumn(ss,"ss");
AddColumn(x,"x");

buy = ExRem( buy, sell );
sell = ExRem( sell, buy );