Discussing the article: "Implementing a Bollinger Bands Trading Strategy with MQL5: A Step-by-Step Guide"

 

Check out the new article: Implementing a Bollinger Bands Trading Strategy with MQL5: A Step-by-Step Guide.

A step-by-step guide to implementing an automated trading algorithm in MQL5 based on the Bollinger Bands trading strategy. A detailed tutorial based on creating an Expert Advisor that can be useful for traders.

Traders may build an Expert Advisor (EA) that uses Bollinger Bands to execute buy and sell orders based on particular market conditions by following this step-by-step tutorial. Important topics including configuring the Bollinger Bands indicator, controlling trading positions, and addressing order execution and error management will all be covered. Regardless of your level of experience with development or familiarity with algorithmic trading, this tutorial will give traders a solid basis on which to design and improve their trading methods.

This journey will cover the following topics:

  1. Definition of Bollinger Bands strategy
  2. Bollinger Bands strategy description
  3. Step-by-step Implementation with MQL5
  4. Conclusion


Results:

From 2016 to 2019, the strategy executed 1425 trades, 857 closed with trades which is 20.28% more than the loss trades.

    Author: Kikkih25

     

    We are in 2024 and your backtest stops in 2019.

    Is it because it does not work after 2019?

     
    The EA has numerous compilation errors.
     

    Here is one code that at least compiles in MT5 :)

    Files:
     

    That code has too many errors. I've fixed the errors and I am posting the updated code here. You are welcome! 

    //+------------------------------------------------------------------+
    //|                                               BollingerBands.mq5 |
    //|                                  Copyright 2024, MetaQuotes Ltd. |
    //|                                             https://www.mql5.com |
    //+------------------------------------------------------------------+
    #property copyright "Copyright 2024, MetaQuotes Ltd."
    #property link      "https://www.mql5.com"
    #property version   "1.00"
    
    #include <Trade\Trade.mqh> // Include the trade library
    CTrade trade; // Create an instance of the CTrade class  
    
    // Input parameters for the Bollinger Bands strategy
    input int BandPeriod = 30;
    input double BandDeviation = 2.0;
    input double LotSize = 0.2;
    input int Slippage = 3;
    input double StopLoss = 70;
    input double TakeProfit = 140;
    
    int Bb_Handle; // Handle for the Bollinger Bands indicator 
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
       // Create the Bollinger Bands indicator handle
       Bb_Handle = iBands(_Symbol, PERIOD_CURRENT, BandPeriod, 0, BandDeviation, PRICE_CLOSE);
       
       if(Bb_Handle == INVALID_HANDLE)
       {
          Print("Error creating Bollinger Bands indicator"); 
          return(INIT_FAILED);
       }
       return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
    {
       // Release the Bollinger Bands indicator handle
       IndicatorRelease(Bb_Handle);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
       double upperBand[], lowerBand[], middleBand[];
       
       // Copy the Bollinger Bands values into arrays
       if(CopyBuffer(Bb_Handle, 0, 0, 1, upperBand) <= 0 ||
          CopyBuffer(Bb_Handle, 1, 0, 1, middleBand) <= 0 ||
          CopyBuffer(Bb_Handle, 2, 0, 1, lowerBand) <= 0)
       {
          Print("Error copying band values");
          return;
       }
       
       double upper = upperBand[0];
       double lower = lowerBand[0];
       double middle = middleBand[0];
       double price = SymbolInfoDouble(_Symbol, SYMBOL_LAST);
       double Ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
       double Bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
       
       // Buy signal: price is below the lower band and no open positions 
       if(price < lower && !IsPositionOpen(_Symbol))
       {
          double sl, tp;
          CalculateSLTP(sl, tp, Ask, true);
          if(trade.Buy(LotSize, _Symbol, Ask, sl, tp, "Buy Order"))
             Print("Buy order opened at price: ", Ask);
          else
             Print("Error opening BUY order:", trade.ResultRetcode());
       }
       // Sell signal: price is above the upper band and no open positions
       else if(price > upper && !IsPositionOpen(_Symbol))
       {
          double sl, tp;
          CalculateSLTP(sl, tp, Bid, false);
          if(trade.Sell(LotSize, _Symbol, Bid, sl, tp, "Sell Order"))
             Print("Sell order opened at price:", Bid);
          else
             Print("Error opening SELL order:", trade.ResultRetcode());
       }
    }
    
    //+------------------------------------------------------------------+
    //| Check if there's an open position for a symbol                   |
    //+------------------------------------------------------------------+
    bool IsPositionOpen(string symbol)
    {
       for(int i = 0; i < PositionsTotal(); i++)
       {
          if(PositionGetSymbol(i) == symbol)
             return true;
       }
       return false;
    }
    
    //+------------------------------------------------------------------+
    //| Close all positions for a symbol                                 |
    //+------------------------------------------------------------------+
    void CloseAllPositions(string symbol)
    {
       for(int i = PositionsTotal() - 1; i >= 0; i--)
       {
          if(PositionGetSymbol(i) == symbol)
          {
             ulong ticket = PositionGetTicket(i);
             if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                trade.PositionClose(ticket, Slippage);
             else if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                trade.PositionClose(ticket, Slippage);
             // Wait for order to be processed before continuing
             Sleep(1000);
          }
       }
    }
    
    //+------------------------------------------------------------------+
    //| Calculate Stop Loss and Take Profit levels                       |
    //+------------------------------------------------------------------+
    void CalculateSLTP(double &sl, double &tp, double price, bool isBuy)
    {
       if(isBuy)
       {
          sl = price - StopLoss * _Point;
          tp = price + TakeProfit * _Point;
       }
       else 
       {
          sl = price + StopLoss * _Point;
          tp = price - TakeProfit * _Point;
       }
    }