I want to add 2 conditions to generate buy signal

. i want to give two condition to enter a trade like when macd cross signal then only look only for MA cross over and enter trade
but my code generate buy signal even when macd does't generate signal

_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) Vol " +WriteVal( V, 1.0 ) +" {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 )) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 

ma1= MA(Close,20);

condi2= Cross(MACD(), Signal());
sell1= Cross(ma2,ma1);

atr1= ATR(14);

Buy= Sell = Null;
bflag= sflag=0;

for( i = 1; i < BarCount; i++ ) 
   if ( condi2[ i ]  AND bflag == 0)
      //Buy[i] = 1;
      Buy= condi1;
      bflag = 1;
      BuyPrice[ i ] =Close[ i ]; 
    if( sell1[i]  AND bflag == 1)
        //Sell[i] = 1;
        Sell= sell1;
        SellPrice[i]= Close[i];
        bflag = 0;
    //if(Buy[i])PlotText("buy @" +BuyPrice[i], i, L[i]-atr1[i],colorGreen,colorBlack,-55);
    //if(Sell[i])PlotText("sell @" +SellPrice[i], i, H[i]+atr1[i], colorRed, colorBlack,40);

Plot(ma1, "ma1", colorGreen, styleThick);
Plot(ma2, "ma2", colorRed, styleLine);
GfxTextOut("MACD MA  ",10,20);

PlotShapes(IIf(Buy, shapeUpArrow, shapeNone), colorGreen, 0, L, -35);
PlotShapes(IIf(Sell, shapeCircle, shapeNone), colorBlue, 0, H, 15);

First, get rid of your for loop. You don't need that, and should not be using it unless you can't achieve your goal using AB built-in array processing.

If you want a Buy signal to occur only when the MACD crossover and the MA crossover occur on the same bar, you can simply do this:

Buy = Condi1 AND Condi2;

If you want a Buy signal to occur any time on or after the MACD has crossed above the signal line, then you should use something more like this:

Buy  = condi1 AND MACD() > Signal();

If this doesn't make sense to you yet, read about "state" signals versus "impulse" signals.


@mayank since, for now, you spent a little time in this forum (welcome!), I strongly recommend you to follow the @mradtke suggestion and take your time to read the previous threads with references to the *"state" vs. "pulse" signals.


You can easily find them simply entering "state pulse" in the search box of the forum (or just click the above icon).

1 Like

Thank you mradtke and beppe, i removed the loop and changed it to" Buy = condi1 AND MACD() > Signal();" And i m looking forward to read "state" vs. "pulse" signals.