Bolinger and RSI

Download script
Author: Copyright 2020, Zakhvatkin Aleksandr
Profit factor:
0.00

This automated trading script is designed to manage trades automatically by combining two popular market analysis tools: Bollinger Bands and the Relative Strength Index (RSI). Its primary goal is to identify specific price "extremes" where a market might be overextended, signaling potential entry points for profitable trades.

Core Logic Overview

The script operates by monitoring the market in real-time and looking for "confluence"—situations where both technical indicators agree on a direction. It focuses on two main types of movements:

1. Buy Opportunities (Potential Undervaluation)

The script looks to enter a "Buy" position when it detects that the price has dropped significantly enough to be considered potentially oversold. It checks for two specific conditions simultaneously:

  • Price Position: The previous candle's closing price must be at or below the Lower Bollinger Band. This suggests the price is pushing into a statistically low zone.
  • Momentum Check: The RSI indicator must be at or below a level of 30. This confirms that the downward momentum is reaching an extreme point.

If both conditions are met, and there isn't already a buy position open, the script will automatically execute a purchase at the current market price.

2. Sell Opportunities (Potential Overvaluation)

Conversely, the script looks to enter a "Sell" position when it detects that the price has surged to an extreme high. It monitors for:

  • Price Position: The previous candle's closing price must be at or above the Upper Bollinger Band. This indicates the price is pushing into a statistically high zone.
  • Momentum Check: The RSI indicator must be at or above a level of 70. This confirms that the upward momentum is reaching a peak.

If these conditions align, the script will automatically execute a sell order.

Key Features and Safeguards

To ensure the trading process is organized and safe, the script includes several professional-grade management features:

  • Automatic Trade Protection: Every trade opened by the script is automatically equipped with a Stop Loss (to limit potential losses) and a Take Profit (to secure gains at a predetermined target).
  • Smart Execution: The script is programmed to only evaluate trades at the start of a new candle (time bar). This prevents "over-trading" or reacting to tiny price fluctuations within a single minute.
  • Safety Checks:
    • Volume Verification: It automatically checks if your requested trade size meets the minimum and maximum volume requirements of the specific broker/symbol you are trading.
    • Duplicate Prevention: The script is designed to prevent opening multiple identical positions (e.g., it won't open a second "Buy" if one is already active).
    • Broker Compatibility: It includes logic to automatically adjust stop-loss and take-profit values for different types of broker price quotes (3-digit vs. 5-digit).

Summary for the User

In simple terms, this script acts as a disciplined automated trader. It waits for the market to reach "stretched" territory (using Bollinger Bands) while simultaneously confirming that the market is exhausted in that direction (using RSI). Once it sees these two signals align, it takes action, manages the risk automatically with stops and targets, and moves on to the next opportunity.

Orders Execution
It automatically opens orders when conditions are reached
Indicators Used
Bollinger bands indicatorRelative strength index
Miscellaneous
It issuies visual alerts to the screen
17 Views
1 Downloads
0 Favorites
Bolinger and RSI
ÿþ//+------------------------------------------------------------------+

//|                                             Bolinger and RSI.mq5 |

//|                             Copyright 2020, Zakhvatkin Aleksandr |

//|                              https://www.mql5.com/ru/users/z.a.m |

//+------------------------------------------------------------------+

#property copyright "Copyright 2020, Zakhvatkin Aleksandr"

#property link      "https://www.mql5.com/ru/users/z.a.m"

#property version   "1.00"

//+------------------------------------------------------------------+

//| Input parametrs                                                  |

//+------------------------------------------------------------------+

input group "Trading settings"

input double              FixedLot    = 0.1;                  // Fixed lot 

input int                 StopLoss    = 100;                  // Stop loss

input int                 TakeProfit  = 200;                  // Take profit

input int                 EA_Magic    = 12345;                // Magic Number EA

input group "Bollinger Bands settings"

input ENUM_TIMEFRAMES      Bands_period        = PERIOD_H4;   // Bands: timeframe (working timeframe)

input int                  Bands_line_period   = 20;          // Bands: period for average line calculation

input int                  Bands_shift         = 0;           // Bands: horizontal shift of the indicator

input double               Bands_deviation     = 2.0;         // Bands: number of standard deviations

input ENUM_APPLIED_PRICE   Bands_applied_price = PRICE_CLOSE; // Bands: type of price

input group "RSI settings"

input ENUM_TIMEFRAMES      RSI_period        = PERIOD_H4;     // RSI: timeframe (working timeframe)

input int                  RSI_line_period   = 14;            // RSI: period for average line calculation

input ENUM_APPLIED_PRICE   RSI_applied_price = PRICE_CLOSE;   // RSI: type of price

//--- global variables

int    SL,TP;                      // used for values Stop loss and Take profit

int    bandsHandle,rsiHandle;      // variable for storing the handle of indicators

double bandsUP[],bandsLOW[],rsi[]; // dynamic arrays for storing numerical values of indicators for each bar

double p_close,Lot;                // variables for storing the close bar value and lot size

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit()

  {

//--- to work with brokers using 3- and 5-digit quotes, multiply the values of the stop loss and take profit by 10

   SL = StopLoss;

   TP = TakeProfit;

   if(_Digits == 5 || _Digits == 3)

      {

      SL *= 10;

      TP *= 10;

      }



//--- create handle of the indicator iBands

   bandsHandle=iBands(_Symbol,Bands_period,Bands_line_period,Bands_shift,Bands_deviation,Bands_applied_price);

//--- if the handle is not created

   if(bandsHandle==INVALID_HANDLE)

     {

      //--- tell about the failure and output the error code

      PrintFormat("Failed to create handle of the iBands indicator for the symbol %s/%s, error code %d",

                  _Symbol,

                  EnumToString(Bands_period),

                  GetLastError());

      //--- the indicator is stopped early

      return(INIT_FAILED);

     }

//--- create handle of the indicator RSI

   rsiHandle=iRSI(_Symbol,RSI_period,RSI_line_period,RSI_applied_price);

//--- if the handle is not created

   if(rsiHandle==INVALID_HANDLE)

     {

      //--- tell about the failure and output the error code

      PrintFormat("Failed to create handle of the RSI indicator for the symbol %s/%s, error code %d",

                  _Symbol,

                  EnumToString(RSI_period),

                  GetLastError());

      //--- the indicator is stopped early

      return(INIT_FAILED);

     }

//---

   return(INIT_SUCCEEDED);

  }

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

//--- clear indicator handles

   IndicatorRelease(bandsHandle);

   IndicatorRelease(rsiHandle);

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void OnTick()

  {

// --- define a new bar

   static datetime Old_Time;

   datetime New_Time[1];

   bool IsNewBar=false;



//--- Aopy the time of the current bar to the New_Time [0] element

   int copied=CopyTime(_Symbol,_Period,0,1,New_Time);

   if(copied>0) // copied successfully

     {

      if(Old_Time!=New_Time[0]) // if old time is not equal

        {

         IsNewBar=true;   // new bar

         if(MQL5InfoInteger(MQL5_DEBUGGING)) Print(">2K9 10@",New_Time[0],"AB0@K9 10@",Old_Time);

         Old_Time=New_Time[0];   // save bar time

        }

     }

   else

     {

      Alert("Time copy error:",GetLastError());

      ResetLastError();

      return;

     }



//--- check the conditions for a new trade operation only with a new bar

   if(IsNewBar==false)

     {

      return;

     }

     

//--- declare structures that will be used for trading

   MqlTick latest_price;              // for current quotes

   MqlTradeRequest mrequest;          // for sending trade requests

   MqlTradeResult mresult;            // to get the results of executing trade requests

   MqlRates mrate[];                  // contain prices, volumes and spread for each bar

   ZeroMemory(mrequest);

//--- array of quotes

   ArraySetAsSeries(mrate,true);

// an array of BolingerBands indicator values (upper line)

   ArraySetAsSeries(bandsUP,true);

// an array of BolingerBands indicator values (bottom line)

   ArraySetAsSeries(bandsLOW,true);

// an array of RSI indicator values

   ArraySetAsSeries(rsi,true);



//--- get the current quote value into a structure of the MqlTick type

   if(!SymbolInfoTick(_Symbol,latest_price))

     {

      Alert("Error getting the latest quotes:",GetLastError(),"!!");

      return;

     }

     

//--- get historical data of the last 3 bars

   if(CopyRates(_Symbol,_Period,0,3,mrate)<0)

     {

      Alert("Error copying history data:",GetLastError(),"!!");

      return;

     }

     

//--- using indicator handles, copy new values of indicator buffers to arrays

   if(CopyBuffer(bandsHandle,0,0,3,bandsUP)<0 || CopyBuffer(bandsHandle,1,0,3,bandsLOW)<0)

     {

      Alert("Bollinger Bands indicator buffer copy error:",GetLastError(),"!!");

      return;

     }

   if(CopyBuffer(rsiHandle,0,0,3,rsi)<0)

     {

      Alert("RSI indicator buffer copy error:",GetLastError());

      return;

     }

     

//--- check if there are open positions

    bool Buy_opened=false;  // variables in which information will be stored 

    bool Sell_opened=false; // on the availability of relevant open positions

    

    if (PositionSelect(_Symbol) ==true)  // there is an open position

    {

         if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)

         {

            Buy_opened = true;  // this is a long position

         }

         else if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)

         {

            Sell_opened = true; // this is a short position

         }

    }

    

//--- copy the current closing price of the previous bar (this is bar 1)

    p_close=mrate[1].close;  // previous bar close price

    

/*

  1. Checking conditions for purchase: RSI <30,

     the previous closing price of the bar is lower or touches the lower line of the Bolinger Bands

*/

//--- we declare a variable of type boolean, it will be used when checking the conditions for buying

   bool Buy_Condition = (p_close <= bandsLOW[1] && rsi[1] <= 30);



//--- check volume

   if (FixedLot<SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN)) 

      {

      Alert("The volume is less than the minimum allowable ",SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN));

      return;

      }

   if (FixedLot>SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX)) 

      {

      Alert("The volume is greater than the maximum allowable ",SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX));

      return;

      }



//--- putting it all together

   if (Buy_Condition)

     {

        // Are there any open positions at the moment?

         if (Buy_opened) 

         {

            Alert("There is already an open buy position !!!");

            return; // do not add to open buy position

         }

         mrequest.action = TRADE_ACTION_DEAL;                                  // immediate execution

         mrequest.price = NormalizeDouble(latest_price.ask,_Digits);           // last ask price

         mrequest.sl = NormalizeDouble(latest_price.ask - SL*_Point,_Digits);  // stop loss

         mrequest.tp = NormalizeDouble(latest_price.ask + TP*_Point,_Digits);  // take profit

         mrequest.symbol = _Symbol;                                            // symbol

         mrequest.volume = FixedLot;                                           // number of lots to trade

         mrequest.magic = EA_Magic;                                            // magic number

         mrequest.type = ORDER_TYPE_BUY;                                       // buy order

         mrequest.type_filling = ORDER_FILLING_FOK;                            // type of order execution - all or nothing

         mrequest.deviation=100;                                               // slippage from the current price

         //--- send a request

         if(OrderSend(mrequest,mresult)) Print("OrderSend function completed successfully!");

         else Print("OrderSend function failed with error:",GetLastError());

         // analyze the trade server return code

         if(mresult.retcode==10009 || mresult.retcode==10008) // request completed or order placed successfully

           {

            Alert("Buy order successfully placed, order ticket #:",mresult.order,"!!");

           }

         else

           {

            Alert("Request to place a Buy order failed - error code:",GetLastError());

            return;

           }

     }

/*

  2. Checking the conditions for sales: RSI> 70,

     the previous bar closing price is higher or touches the upper Bolinger Bands line

*/

//--- we declare a variable of type boolean, it will be used when checking the conditions for buying

   bool Sell_Condition = (p_close >= bandsUP[1] && rsi[1] >= 70);



//--- putting it all together

   if (Sell_Condition)

     {

        // Are there any open positions at the moment?

         if (Sell_opened) 

         {

            Alert("There is already an open sell position !!!");

            return; // do not add to open sell position

         }

         mrequest.action = TRADE_ACTION_DEAL;                                  // immediate execution

         mrequest.price = NormalizeDouble(latest_price.bid,_Digits);           // last bid price

         mrequest.sl = NormalizeDouble(latest_price.ask + SL*_Point,_Digits);  // stop loss

         mrequest.tp = NormalizeDouble(latest_price.ask - TP*_Point,_Digits);  // take profit

         mrequest.symbol = _Symbol;                                            // symbol

         mrequest.volume = FixedLot;                                           // number of lots to trade

         mrequest.magic = EA_Magic;                                            // magic number

         mrequest.type = ORDER_TYPE_SELL;                                      // sell order

         mrequest.type_filling = ORDER_FILLING_FOK;                            // type of order execution - all or nothing

         mrequest.deviation=100;                                               // slippage from the current price

         //--- send a request

         if(OrderSend(mrequest,mresult)) Print("OrderSend function completed successfully!");

         else Print("OrderSend function failed with error:",GetLastError());

         // analyze the trade server return code

         if(mresult.retcode==10009 || mresult.retcode==10008) // request completed or order placed successfully

           {

            Alert("Sell order successfully placed, order ticket #:",mresult.order,"!!");

           }

         else

           {

            Alert("Request to place a Sell order failed - error code:",GetLastError());

            return;

           }

     }

 

  }



//+------------------------------------------------------------------+

Profitability Reports

PERFORMANCE BY SYMBOL

Expected payoff

Average expected payoff across the available backtests for each symbol.

Positive Negative
3 reports
GBP/AUD Jul 2025 - Sep 2025
0.00
Total Trades 0
Won Trades 0
Lost trades 0
Win Rate 0.0 %
Expected payoff 0.00
Gross Profit 0.00
Gross Loss 0.00
Total Net Profit 0.00
-100%
-50%
0%
50%
100%
EUR/USD Jul 2025 - Sep 2025
0.00
Total Trades 29
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff 150.11
Gross Profit 4526.33
Gross Loss -173.00
Total Net Profit 4353.33
-100%
-50%
0%
50%
100%
GBP/CAD Jul 2025 - Sep 2025
0.00
Total Trades 0
Won Trades 0
Lost trades 0
Win Rate 0.0 %
Expected payoff 0.00
Gross Profit 0.00
Gross Loss 0.00
Total Net Profit 0.00
-100%
-50%
0%
50%
100%

Comments