Search code examples
mql4

How do I to use Bollinger Bands to get a signal to open an order?


I'm trying to use the Bollinger Bands to get a signal to open orders buy or sell. To do this, I am trying to test if candle[2] and candle[1] are closing above or below MODE_UPPER and MODE_LOWER of iBands to open the order. The problem is that the order are opening next to MODE_MAIN instead of MODE_UPPER or MODE_LOWER and I don't know why it happening.

How could I do this ?

Trying

//return true if has a signal to open order 
bool bollingerBandScalper(int bs){
   int _candle = 0;
   int _period = 14;

   //double _main = iBands(_Symbol, _Period, _period, 2, 0, PRICE_CLOSE, MODE_MAIN, _candle + 1);

   double LowerBB = iBands(_Symbol, _Period, _period, 2, 0, PRICE_CLOSE, MODE_LOWER, _candle + 1);
   double UpperBB = iBands(_Symbol, _Period, _period, 2, 0, PRICE_CLOSE, MODE_UPPER, _candle + 1);

   double PrevLowerBB = iBands(_Symbol, _Period, _period, 2, 0, PRICE_CLOSE, MODE_LOWER, _candle + 2);
   double PrevUpperBB = iBands(_Symbol, _Period, _period, 2, 0, PRICE_CLOSE, MODE_UPPER, _candle + 2);

   //buy signal
   if(bs == OP_BUY){
      if((Close[_candle + 2] > PrevLowerBB) && (Close[_candle + 1] > LowerBB)){
         return true;
      }
   }

   //sell signal
   if(bs == OP_SELL){
      if((Close[_candle + 2] > PrevUpperBB) && (Close[_candle + 1] > UpperBB)){
         return true;
      }
   }


   return false;

}

Solution

  • I think you've made a mistake to find where price closes above/below BB Bands. I made some changes in your code. You can test it:

    //return true if has a signal to open order 
    bool bollingerBandScalper(int type,int period,int shift)
    {
     double LowerBB = iBands(_Symbol,_Period,period,2.0,0,PRICE_CLOSE,MODE_LOWER,shift+1);
     double UpperBB = iBands(_Symbol,_Period,period,2.0,0,PRICE_CLOSE,MODE_UPPER,shift+1);
    
     double PrevLowerBB = iBands(_Symbol,_Period,period,2,0,PRICE_CLOSE,MODE_LOWER,shift+2);
     double PrevUpperBB = iBands(_Symbol,_Period,period,2,0,PRICE_CLOSE,MODE_UPPER,shift+2);
    
     //buy signal
     if(type==OP_BUY && Close[shift+2]>PrevLowerBB && Close[shift+1]<LowerBB) return true;
    
     //sell signal
     if(type==OP_SELL && Close[shift+2]<PrevUpperBB && Close[shift+1]>UpperBB) return true;
    
     return false;
    }