How to code Buy or Sell in Bollinger Band EA ?

 

Please see this Photo :-

https://charts.mql5.com/38/78/audusd-s-m5-jm-technologies-ltd.png


Code :-

int iBB_handle;
double BB_Upper[], BB_Lower[];

int OnInit()
  {
//---
    iBB_handle = iBands(Symbol(),PERIOD_CURRENT,23,0,2,PRICE_CLOSE);
//---
   return(INIT_SUCCEEDED);
  }

void OnTick()
  {
//---
   ArraySetAsSeries(BB_Upper,true);
   ArraySetAsSeries(BB_Lower,true);
   
   CopyBuffer(iBB_handle,UPPER_BAND,0,1,BB_Upper);
   CopyBuffer(iBB_handle,LOWER_BAND,0,1,BB_Lower);
   
   if(BB_Lower[0] > BB_Upper[0])
   {
    Comment("Buy");
   }
   else
   {
    Comment("Sell");
   }
  }

 I have wronged this if & else statement in source code

I have confused "BB_Lower[0] > BB_Upper[0] && BB_Lower[0] < BB_Upper[0]"  or "BB_Lower[0] > BB_Upper[0]" ....

How to get simple Buy & Sell in source code ?

How to get idea in source code ?

How to check value to this indicator  ?

 

@ Vik 3001

Maybe this video will help you.

I'm sharing with you the code I've retyped here myself, which you can use to tweak something decent for yourself. If even that doesn't work, come back to this post.

//+------------------------------------------------------------------+
//|                                    07-Bollinger bands EA MT5.mq5 |
//|                                  Copyright 2023, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

//+------------------------------------------------------------------+
//|                           Include                                |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>

//+------------------------------------------------------------------+
//|                        Input Variables                           |
//+------------------------------------------------------------------+
static input long   InpMagicNumber  = 837462;
static input double InpLotSize      = 0.01;
input int           InpPeriod       = 21;  
input double        InptDeviation   = 2.0;
input int           InpStopLoss     = 100;          // 0 = OFF
input int           InpTakeProfit   = 200;          // 0 = OFF

//+------------------------------------------------------------------+
//|                       Global Variables                           |
//+------------------------------------------------------------------+
int     handle;
double  upperBuffer[];
double  baseBuffer[];
double  lowerBuffer[];
MqlTick currentTick;
CTrade trade;
datetime openTimeBuy  = 0;
datetime openTimeSell = 0;

//+------------------------------------------------------------------+
//|                            On Init                               |
//+------------------------------------------------------------------+
int OnInit()
{
    //--- 
    // Controle des Input Et affichage d'un message d'erreur
    if (InpMagicNumber <= 0){
        Alert("Magic Number <= 0");
        return INIT_PARAMETERS_INCORRECT;
    }
    if (InpLotSize <= 0){
        Alert("Lot Size <= 0");
        return INIT_PARAMETERS_INCORRECT;
    }
    if (InpPeriod <= 1){
        Alert("Period <= 0");
        return INIT_PARAMETERS_INCORRECT;
    }
    if (InptDeviation <= 0.1){
        Alert("Deviation <= 0,1");
        return INIT_PARAMETERS_INCORRECT;
    }    
    if (InpStopLoss <= 0){
        Alert("Stop Loss <= 0");
        return INIT_PARAMETERS_INCORRECT;
    }   
    if (InpTakeProfit <= 0){
        Alert("Take Profit <= 0");
        return INIT_PARAMETERS_INCORRECT;
    }  

    trade.SetExpertMagicNumber(InpMagicNumber);

    handle = iBands(_Symbol, PERIOD_CURRENT, InpPeriod, 1, InptDeviation, PRICE_CLOSE);
    if (handle == INVALID_HANDLE){
        Alert("Failed to Create Indicator Handle");
        return INIT_FAILED;
    }  
    
    ArraySetAsSeries(upperBuffer, true);
    ArraySetAsSeries(baseBuffer,  true);
    ArraySetAsSeries(lowerBuffer, true);

    return(INIT_SUCCEEDED);
} // On Init End

//+------------------------------------------------------------------+
//|                            On Deinit                             |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    if(handle != INVALID_HANDLE){ 
        IndicatorRelease(handle);
    }
} // On Deinit End

//+------------------------------------------------------------------+
//|                            On Tick(                              |
//+------------------------------------------------------------------+
void OnTick()
{
    if(!IsNewBar()){ return; } //F01
    if(!SymbolInfoTick(_Symbol, currentTick)){
        Print("Failed to get tick");
        return;
    }

    int values  = CopyBuffer(handle,0, 0, 1, baseBuffer)
                + CopyBuffer(handle,1, 0, 1, upperBuffer)
                + CopyBuffer(handle,2, 0, 1, lowerBuffer);

    if(values != 3){
        Print("Erreur dans l obtention des valeur des BB");
        return;
    }
    
    Comment("BB Up : "      , upperBuffer[0], "\n",
            "BB Midle : "   , baseBuffer[0],  "\n",
            "BB Down : "    , lowerBuffer[0]
    );

    int cntBuy, cntSell;
    if(!CountOpenPositions(cntBuy, cntSell)){ return; }

    bool C1 = cntBuy == 0 && currentTick.ask <= lowerBuffer[0] && openTimeBuy != iTime(_Symbol, PERIOD_CURRENT, 0);
    if(C1){
        openTimeBuy = iTime(_Symbol, PERIOD_CURRENT, 0);
        double sl   = currentTick.bid - InpStopLoss * _Point;
        double tp   = InpTakeProfit == 0 ? 0 : currentTick.ask + InpTakeProfit * _Point;
        if(!NormalizePrice(sl, sl)) { Print("Erreur Normalisation Stop Loss-Long Position"); return; }
        if(!NormalizePrice(tp, tp)) { Print("Erreur Normalisation Take Profit-Long Position"); return; }

        trade.PositionOpen(_Symbol, ORDER_TYPE_BUY, InpLotSize, currentTick.ask, sl, tp, "Bollinger Band EA-Long");

    }

    bool C2 = cntSell == 0 && currentTick.bid >= upperBuffer[0] && openTimeSell != iTime(_Symbol, PERIOD_CURRENT, 0);
    if(C2){
        openTimeSell = iTime(_Symbol, PERIOD_CURRENT, 0);
        double sl   = currentTick.ask + InpStopLoss * _Point;
        double tp   = InpTakeProfit == 0 ? 0 : currentTick.bid - InpTakeProfit * _Point;
        if(!NormalizePrice(sl, sl)) { Print("Erreur Normalisation Stop Loss-Short Position"); return; }
        if(!NormalizePrice(tp, tp)) { Print("Erreur Normalisation Take Profit-Short Position"); return; }

        trade.PositionOpen(_Symbol, ORDER_TYPE_SELL, InpLotSize, currentTick.bid, sl, tp, "Bollinger Band EA-Short");

    }

    if(!CountOpenPositions(cntBuy, cntSell)){ return; }

    //---
    // C3 : Cloture du Long si le prix traverse la bande du milieux à la hausse
    bool C3 = cntBuy > 0 && currentTick.bid >= baseBuffer[0];
    if(C3){ ClosePosition(1); }

    //---
    // C4 : Cloture du Short si le prix traverse la bande du milieux à la baisse
    bool C4 = cntSell > 0 && currentTick.ask <= baseBuffer[0];
    if(C4){ ClosePosition(2); }    


} // On Tick End

//+------------------------------------------------------------------+
//|                           My FonctionS                           |
//+------------------------------------------------------------------+

bool IsNewBar(){ //F01
    static datetime previousTime = 0;                           
    datetime currentTime = iTime(_Symbol, PERIOD_CURRENT, 0);   
    if(previousTime != currentTime) {                           
        previousTime = currentTime;                             
        return true;                                           
                                                               
    }
    return false;
}

bool CountOpenPositions(int &countBuy,int &countSell){
    countBuy  = 0;
    countSell = 0;
    int total = PositionsTotal();
    for (int i = total - 1 ; i >= 0; i--){
        ulong positionTicket = PositionGetTicket(i);
        if(positionTicket <= 0){ 
            Print("Impossible de récuper le Ticket-COP"); 
            return  false;
        }
        if(!PositionSelectByTicket(positionTicket)){
            Print("Impossible de selectionée la Positiion-COP");
            return false;
        }
        long magic;
        if(!PositionGetInteger(POSITION_MAGIC, magic)){
            Print("Impossible d'obtenir le numéro magique-COP");
            return false;
        }
        if(magic == InpMagicNumber){
            long type;
            if(!PositionGetInteger(POSITION_TYPE, type)){
                Print("Impossible de récuperer le type de la position-COP");
                return false;
            }
            if(type == POSITION_TYPE_BUY) { countBuy++; }
            if(type == POSITION_TYPE_SELL){ countSell++; }
        }
    }

    return true;
}

//---

bool NormalizePrice(double price, double &normalizedPrice){
    double tickSize = 0;
    if(!SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE, tickSize )){
        Print("Erreur Récupération de la valeur du Tick"); 
        return false;
    }
    normalizedPrice = NormalizeDouble(MathRound(price / tickSize) * tickSize, _Digits);
    return true;
}

bool ClosePosition(int all_buy_sell){
    int total = PositionsTotal();
    for (int i = total - 1 ; i >= 0; i--){
        ulong positionTicket = PositionGetTicket(i);
        if(positionTicket <= 0){ 
            Print("Impossible de récuper le Ticket-CP"); 
            return  false;
        }
        if(!PositionSelectByTicket(positionTicket)){
            Print("Impossible de selectionée la Positiion-CP");
            return false;
        }
        long magic;
        if(!PositionGetInteger(POSITION_MAGIC, magic)){
            Print("Impossible d'obtenir le numéro magique-CP");
            return false;
        }
        if(magic == InpMagicNumber){
            long type;
            if(!PositionGetInteger(POSITION_TYPE, type)){
                Print("Impossible de récuperer le type de la position-CP");
                return false;
            }

            if(all_buy_sell == 1 && type == POSITION_TYPE_SELL) { continue; }
            if(all_buy_sell == 2 && type == POSITION_TYPE_BUY)  { continue; }
            trade.PositionClose(positionTicket);
            if(trade.ResultRetcode() != TRADE_RETCODE_DONE){
                Print("Erreur lors de la fermeture de la position avec le Ticket : ", (string)positionTicket,
                    " Resultat : ", (string)trade.ResultRetcode(), " : ", trade.CheckResultRetcodeDescription()
                );
                return false;
            }
        }
    }
    // Voila
    return true;
}
//+------------------------------------------------------------------+

Best Reguards

Bollinger bands EA MT5 Programming
Bollinger bands EA MT5 Programming
  • 2022.11.28
  • www.youtube.com
Today I will show you how to code a simple Bollinger bands EA for Metatrader 5. If you are new to mql5, just follow my steps and we will create a fully work...
 
ZeroCafeine #:

@ Vik 3001

Maybe this video will help you.

I'm sharing with you the code I've retyped here myself, which you can use to tweak something decent for yourself. If even that doesn't work, come back to this post.

Best Reguards

Thank you replied to me Sir,

I will Practice in this Source code..