Bolinger and RSI

Author: Copyright 2020, Zakhvatkin Aleksandr
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
0 Views
0 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;

           }

     }

 

  }



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

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---