Monday, December 2, 2024

In this article, I'll explain how to create a standard and simple Expert Advisor (EA) or forex robot by applying Buy or Sell signals from the FiboPivotCandleBar indicator for MetaTrader 4.

First, let me explain that the FiboPivotCandleBar indicator for MetaTrader 4 is an indicator I created and have been sharing for free in the MQL5 Library since 2015. However, I have never applied the signals inan Expert Advisor or forex robot until now. This article won't delve into the Fibonacci and Pivot Point strategies, as they require a dedicated and lengthy discussion.

To create this Expert Advisor, I used the latest Event Handling Functions from MQL4 and several key properties and attributes that adhere to good MQL4 programming standards.

FiboPivotCandleBar Expert Advisor for MetaTrader 4

Now, I'll explain each function, the use of variables, and the algorithm's logic one by one.

Standard Include Files.

For creating this Expert Advisor, I used the standard include files (mqh files):

  • 1.- #include MovingAverages.mqh: Used for writing the MovingAverage indicator signal.
  • 2.- #include stderror.mqh: Contains standard errors returned from the trade server.
  • 3.- #include stdlib.mqh: Contains the Error Description from standard library.

You can find these three include files in the MQL4/Include folder.

Custom Enumerations.

YN Enum Function: I use this for Yes or No options. Most programmers prefer boolean variables (True or False), but I prefer using Yes or No for clarity.

MMT Enum Function: This function is used for determining the Lot Size (Money Management).

  • If FixedLot is selected, the expert advisor will use the value of the Lots variable entered by the user. By default, the Lots size variable is set to 0.01.
  • If AutoLot is selected, the expert advisor will calculate the Lot size according to the specified money management requirements.

//---
input string           grs0 = "=== Global Strategy EA Parameters ==="; // Global Strategy EA Parameter
input ENUM_TIMEFRAMES  ExTF = PERIOD_H1;      // Select Expert TimeFrame, default PERIOD_H1
input YN            SrictTF = Yes;            // Strict to Change TimeFrame (Yes) or (No)
//---
input string           grs1 = "=== Money Management Lot Size Parameters ==="; // Money Management Lot Size Parameter
input mmt             mmlot = AutoLot;        // Money Management Type
input double           Risk = 5.0;            // Percent Equity Risk to Trade (Min=1.0% / Max=50.0%)
input double           Lots = 0.01;           // If Money Management Type FixedLot, input Fixed Lot Size
//---
input string           grs2 = "=== Close Order Option ==="; // Close Order Option
input YN      Close_by_Opps = Yes;            // Close Trade By Opposite Signal (Yes) or (No)
input YN             CSexit = Yes;            // Use Close In Signal Exit (Yes) or (No)
//---
input string           grs3 = "=== Stop Loss & Take Profit Parameters ==="; // Stop Loss  && Take Profit Parameter
input YN             Use_SL = No;             // Use Order SL (Yes) or (No)
input YN             Use_TP = No;             // Use Order TP (Yes) or (No)
//---
input string           grs4 = "=== Trailing Stop Loss / Take Profit Parameters ==="; // Trailing SL / TP Parameter
input YN          use_trail = Yes;            // Use Trailing Stop / Trailing Profit (Yes) or (No)
input int            trstrt = 1;              // Input Start value for Trailing Stop in Pips
input int            trstop = 6;              // Input Trailing Stop value in Pips
//---
input string           grs5 = "=== Others Expert Advisor Parameters ==="; // Others EA Parameter
input YN             alerts = Yes;            // Display Alerts on Chart (Yes) or (No)
input YN      UseEmailAlert = No;             // Email Alert (Yes) or (No)
input YN      UseSendnotify = No;             // Send Notification (Yes) or (No)
input YN       Usechartcomm = Yes;            // Display Setting on Chart (Yes) or (No)
input int           magicEA = 20241202;        // Expert ID (Magic Number)
//---

Select Expert TimeFrame (default: PERIOD_H1): This parameter defines the Expert Timeframe for signal calculation. It prevents the EA from recalculating signals based on the chart's last changed timeframe by user, which could lead to premature order closures.

Strict to Change Timeframe (Yes or No): By default, this is set to Yes, preventing traders from changing timeframe charts directly in the MetaTrader 4 terminal. Timeframe changes can only be made through the Select Expert Timeframe input property. Set to No if the user wants to change the timeframe manually.

Money Management Lot Size Parameters.

Money Management Type: By default, this is set to AutoLot. The EA calculates the Lot Size based on the Percent Equity Risk to Trade, which is set at 5% by default (min 1.0%, max 50.0%). For trading on 20 pairs or more, consider increasing the risk to 20% or 30%. If FixedLot is selected, input the desired FixedLot Size.

Close Order Options.

Close Trade By Opposite Signal (Yes or No): By default, this is set to Yes. If there's an open BUY order and the signal reverses to SELL, the EA will close the BUY order and open a SELL order, and vice versa.

Use Close In Signal Exit (Yes or No): By default, this is set to Yes. If the BUY signal weakens but is still profitable, the EA will close the BUY order. If set to No, the EA won't close the order based on signal exit.

Stop Loss and Take Profit Parameters.

Use Order SL (Yes or No): By default, this is set to No. Despite this, the EA will automatically close orders if there's a reverse signal, thanks to the Close Trade By Opposite Signal parameter.

Use Order TP (Yes or No): By default, this is set to No, allowing for greater profits during long trends.

Trailing Stop Loss or Take Profit Parameters.

Use Trailing Stop or Trailing Profit (Yes or No): By default, this is set to Yes. If not preferred, set this parameter to No. The trailing start is set at 1 pip from the Order Open Price, with a trailing stop value of 6 pips. These values can be adjusted as desired.

Other Expert Advisor Parameters.

Display Alerts on Chart (Yes or No): By default, this is set to Yes, activating alerts, email, and push notification functions through the DoAlerts function.

Email Alert (Yes or No): By default, this is set to No. For email alerts, users must configure their email settings in MetaTrader 4:

  • 1. Click the Tools menu.
  • 2. Select Options.
  • 3. Click Email.

Configure the settings with your email identity:

  • SMTP server: e.g., smtp.gmail.com:587 for Gmail.
  • SMTP login: Your email address.
  • SMTP password: Your email password.
  • From: Your email address.
  • To: Recipient's email address (can be the same as the sender).

After configuring, click the Test button and check the Journal Tab for any errors.

Send Notification (Yes or No): By default, this is set to No. For push notifications, users must configure their MetaQuotes ID in MetaTrader 4:

  • 1. Click the Tools menu.
  • 2. Select Options.
  • 3. Click the Notifications tab.
  • 4. Check Enable Push Notification.
  • 5. Enter YOUR MetaQuotes ID.

Class Function.

In this Expert Advisor, I use a class function named "EXP", listing all main variables and functions used. This class serves as the blueprint of the Expert Advisor. However, this article won't delve into the class function's details, assuming readers are familiar with it.


//+------------------------------------------------------------------+
//| Class for working Expert Advisor                                 |
//+------------------------------------------------------------------+
class EXP 
  {
//---
    private:
    //---
    //--
    int           slip,bartotal;
    int           ldig,checkacc,cdb,cds;
    //--
    double        mSL,mTP,mPft;
    double        pip,xpip,trs;
    double        profitb,profits,floatprofit;
    //--
    double        OPEN[],HIGH[],LOW[],CLOSE[];
    double        trval,trstart,trstoptp,aapct;
    double        PvtS,POpen,PLow1,PHigh1,PClose1;
    //--
    bool          posBUY,posSELL;
    //--
    string        expname,
                  exsymbol,
                  trade_mode;
    //-- 
    long          chart_id;
    ENUM_TIMEFRAMES BnC;
    //------------
     
    //------------
    int           LotsDigit(void);
    int           DirectionMove(ENUM_TIMEFRAMES xtf,int shift);
    int           FiboPivotCB(void);
    int           AllowOpen(void);
    int           SignalCondition(void);
    //--
    string        TF2Str(int period);
    string        GetCommentForOrder(void)                  { return(expname); }    
    string        ReturnsOrderType(ENUM_ORDER_TYPE ordtype);
    string        AccountMode(void);
    //--
    double        NonZeroDiv(double val1,double val2);
    double        MLots(void);
    //--   
    void          CopyPrices(void);
    void          RefreshPrice(string symbx,ENUM_TIMEFRAMES xtf,int bars);
    //--
    bool          ModifyStopTP(double mStop,double mProfit) { return(OrderModify(OrderTicket(),OrderOpenPrice(),mStop,mProfit,0,CLR_NONE)); }
    bool          SameAs(double v1,double v2)               { if((double)v1==(double)v2) return(true); return(false); }
    bool          CloseAllOrder(void);
    //------------

    public:
    //---
    //--
    int           utr,ALO,cB,cS,checktml;
    int           oBm,oSm,hBm,hSm,tto;
    //--
    bool          IfTradeAllowed;
    //--
    datetime      PbarB,TbarB,PbarS,TbarS;
    //------------
     
    //------------
    void          FPCB_Config(void);
    void          GetOpenPosition(void);
    void          CheckOpen(void);
    void          CheckClose(void);
    void          TrailingPositionsBuy(void);
    void          TrailingPositionsSell(void);
    void          CloseBuyPositions(void);
    void          CloseSellPositions(void);
    void          Do_Alerts(string msgText);
    void          ChartComm(void);
    void          SignalExit(void);
    //--
    bool          takeBuyPositions(void);
    bool          takeSellPositions(void);
    bool          OpenBuy(void);
    bool          OpenSell(void);
    bool          CloseAllOrdersProfit(void);
    bool          IFNewBarsB(string symb);
    bool          IFNewBarsS(string symb);
    //--
    string        getUninitReasonText(int reasonCode);
    //--
    //------------
//---
  }; //-end class fxt
//---------//
 
EXP fx;

OnInit: Here, I create an algorithm where if SrictTF enumeration is set to Yes, it utilizes the Strict to Change TimeFrame parameter. This function calls "FPCBConfig" function for setting the default configuration used in the Expert Advisor.


//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit(void)
  {
//----
   Comment("");
   //--
   if(SrictTF==Yes)
     {
       if(!ChartSetSymbolPeriod(ChartID(),Symbol(),ExTF))
         {ChartSetSymbolPeriod(ChartID(),Symbol(),ExTF);}
     }
   //--
   fx.FPCB_Config();
   //--
//--- initialization done
   return(INIT_SUCCEEDED);
  }
//---------//

FPCB_Config() function.


void EXP::FPCB_Config(void)
  {
//---
   expname="@ExpFPCB-MT4";
   exsymbol=Symbol();
   //--
   slip=20;
   checktml=0;
   AccountMode();
   utr=use_trail;
   BnC=ExTF; 
   bartotal=108;
   chart_id=ChartID();
   ALO=(int)AccountInfoInteger(ACCOUNT_LIMIT_ORDERS);
   //--
   //-- Checking the Digits Point
   slip=20;
   PbarB=iTime(Symbol(),BnC,1);
   PbarS=iTime(Symbol(),BnC,1);
   double point=SymbolInfoDouble(Symbol(),SYMBOL_POINT);
   mPft=0.5;
   //--
   if(exsymbol=="XAGUSD")
     {
       xpip=4; 
       pip=point*xpip;
       if(Use_SL==Yes) mSL=100*point;
       else mSL=0.0;
       if(Use_TP==Yes) mTP=50*point;
       else mTP=0.0;
       //--
       trstart=NormalizeDouble(trstrt*pip,Digits());
       trstoptp=NormalizeDouble(trstop*pip,Digits());
       trval=NormalizeDouble(trstart+trstoptp,Digits());
     }
   if(exsymbol=="XAUUSD")
     {
       xpip=10; 
       pip=point*xpip;
       if(Use_SL==Yes) mSL=250*point;
       else mSL=0.0;
       if(Use_TP==Yes) mTP=50*point;
       else mTP=0.0;
       //--
       trstart=NormalizeDouble(trstrt*pip,Digits());
       trstoptp=NormalizeDouble(trstop*pip,Digits());
       trval=NormalizeDouble(trstart+trstoptp,Digits());
     }
   if(exsymbol=="XBRUSD")
     {
       xpip=10; 
       pip=point*xpip;
       if(Use_SL==Yes) mSL=250*point;
       else mSL=0.0;
       if(Use_TP==Yes) mTP=50*point;
       else mTP=0.0;
       //--
       trstart=NormalizeDouble(trstrt*pip,Digits());
       trstoptp=NormalizeDouble(trstop*pip,Digits());
       trval=NormalizeDouble(trstart+trstoptp,Digits());
     }
   if(exsymbol=="XTIUSD")
     {
       xpip=10; 
       pip=point*xpip;
       if(Use_SL==Yes) mSL=250*point;
       else mSL=0.0;
       if(Use_TP==Yes) mTP=50*point;
       else mTP=0.0;
       //--
       trstart=NormalizeDouble(trstrt*pip,Digits());
       trstoptp=NormalizeDouble(trstop*pip,Digits());
       trval=NormalizeDouble(trstart+trstoptp,Digits());
     }
   else
     {
       xpip=10; 
       pip=point*xpip;
       if(Use_SL==Yes) mSL=25*pip;
       else mSL=0.0;
       if(Use_TP==Yes) mTP=5*pip;
       else mTP=0.0;
       //--
       trstart=NormalizeDouble(trstrt*pip,Digits());
       trstoptp=NormalizeDouble(trstop*pip,Digits());
       trval=NormalizeDouble(trstart+trstoptp,Digits());
     }
   //--
   IfTradeAllowed=IsTradeAllowed();
   CopyPrices();
   //--
   return;
//---
  } //-end FPCB_Config()
//---------//

OnDeinit: in this function, I call the getUninitReasonText function, which provides the description of the reason Code when the Expert Advisor calls the OnDeinit function.


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   Comment("");
   //--
   PrintFormat("%s: Deinitialization reason code=%d",__FUNCTION__,reason);
   Print(fx.getUninitReasonText(reason));
   //--
   return;
  } //-end OnDeinit()
//---------//

OnTick: This is where the Expert Advisor carries out trading activities based on the settings specified in the input properties parameter.


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick(void)
  {  
//---
   //Check Trading Terminal
   if(!fx.IfTradeAllowed && fx.checktml==0)
     {
       fx.Do_Alerts("Trading at "+Symbol()+" are NOT Allowed by Setting.");
       fx.checktml=1;
       return;
     }
   //--
   RefreshRates();
   fx.CheckOpen();
   if(fx.tto==0 && fx.hBm+fx.hSm>0) fx.CheckClose();
   //--
   if(Usechartcomm==Yes) fx.ChartComm();
   //--
   fx.GetOpenPosition();
   //Buy Condition
   if(fx.takeBuyPositions())
     {
       //--
       fx.CheckOpen();
       //--
       if(fx.oBm==0 && fx.IFNewBarsB(Symbol())) {fx.cB=1; fx.OpenBuy(); fx.PbarB=fx.TbarB;}
       else if(fx.oBm==0 && fx.oSm>0) {fx.cB=2; fx.OpenBuy(); fx.PbarB=fx.TbarB;}
       fx.CheckOpen();
       if(fx.oBm>0 && Close_by_Opps==Yes && fx.oSm>0) {fx.CloseSellPositions(); fx.PbarB=fx.TbarB;}
     }
   //--
   //Sell Condition
   if(fx.takeSellPositions())
     {
       //--
       fx.CheckOpen();
       //--
       if(fx.oSm==0 && fx.IFNewBarsS(Symbol())) {fx.cS=1; fx.OpenSell(); fx.PbarS=fx.TbarS;}
       else if(fx.oSm==0 && fx.oBm>0) {fx.cS=2; fx.OpenSell(); fx.PbarS=fx.TbarS;}
       fx.CheckOpen();
       if(fx.oSm>0 && Close_by_Opps==Yes && fx.oBm>0) {fx.CloseBuyPositions(); fx.PbarS=fx.TbarS;}
     }
   //--
   if(CSexit==Yes) fx.SignalExit();
   //--
   if(OrdersTotal()>=fx.ALO) fx.CloseAllOrdersProfit();
   //---
   //Trailing Stop / Take Profit Position
   if(fx.utr==Yes)
     {
       fx.CheckOpen();
       if(fx.oBm>0) fx.TrailingPositionsBuy();
       if(fx.oSm>0) fx.TrailingPositionsSell();
     }
   //--
   return;
//---
  } //-end OnTick()
//---------//

First, the Expert Advisor checks whether automatic trading on symbols and MetaTrader 4 is allowed. If is not, it alerts that "Trading on the symbol is NOT Allowed by Setting."

Especially for novice traders:

  • 1. Check if the "AutoTrading" button is red or green. If red, click it once to turn it green.
  • 2. Check if the Expert Advisor icon in the upper right corner of the chart shows a crying or laughing face. If crying:
    • 1. Click the Tools menu.
    • 2. Select Options.
    • 3. Click the Expert Advisors tab.
    • 4. Check "Allow automated trading." The icon will show a laughing face, and the "AutoTrading" button will turn green.

After that, the Expert Advisor starts trading activities by:

  • 1. Calling the CheckOpen function to check for open orders. If none, it calls the CheckClose function to reset the open buy or sell order count to zero.
  • 2. If Display Setting on Chart is Yes, it calls the ChartComm function to display settings on the chart.

CheckOpen function.

This is a function named CheckOpen in the EXP class, which seems to be used for checking the status of open trades. Here's a step-by-step explanation:

1. Initialization:

  • oBm and oSm are set to 0. These might represent the count of Buy and Sell orders, respectively.
  • profitb and profits are set to 0.0. These variables likely store the profit from Buy and Sell orders.
  • totalorder is set to OrdersTotal(), which retrieves the total number of orders.

2. Order Checking Loop:

  • A loop iterates through all orders (totalorder). The loop runs as long as opn is less than totalorder and the IsStopped() function returns false.
  • Inside the loop, OrderSelect(opn, SELECT_BY_POS, MODE_TRADES) selects the order at position opn.

3. Order Validation:

  • It checks if the selected order's symbol matches the current symbol (OrderSymbol() == Symbol()) and its magic number matches magicEA.
  • If these conditions are met, it proceeds to check the order type.

4. Order Type Checking:

  • If the order is a Buy order (OrderType() == OP_BUY):
    • oBm and hBm are incremented.
    • profitb is calculated as the sum of OrderProfit(), OrderCommission(), and OrderSwap().
  • If the order is a Sell order (OrderType() == OP_SELL):
    • oSm and hSm are incremented.
    • profits is calculated similarly.

5.Profit Calculation:

  • floatprofit is set to the sum of profitb and profits.

6.Total Orders:

  • tto is set to the sum of oBm and oSm, which likely represents the total number of Buy and Sell orders.

7.End of Function::

  • The function ends and returns..

The CheckOpen function essentially counts the number of Buy and Sell orders, calculates their respective profits, and totals them up. It handles trades by ensuring they match specific criteria (symbol and magic number) before processing.


void EXP::CheckOpen(void) //-- function: CheckOpenTrade.
  {
//---
    oBm=0;
    oSm=0;
    profitb=0.0;
    profits=0.0;
    int totalorder=OrdersTotal();
    //--
    for(int opn=0; opn<totalorder && !IsStopped(); opn++)
      {
        if(OrderSelect(opn,SELECT_BY_POS,MODE_TRADES))
          {
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magicEA)
              {
                //--
                if(OrderType()==OP_BUY)  
                  {
                    oBm++; 
                    hBm++;
                    profitb=OrderProfit()+OrderCommission()+OrderSwap();                
                  }
                if(OrderType()==OP_SELL) 
                  {
                    oSm++; 
                    hSm++;
                    profits=OrderProfit()+OrderCommission()+OrderSwap();
                  }
                //--
                floatprofit=profitb+profits;
              }
            //--
          }
      }
    //--
    tto=oBm+oSm;
    //---
    return;
//---
  } //-end CheckOpen()
//---------//

CheckClose function.


void EXP::CheckClose(void) //-- function: CheckOrderClose.
  {
//----
    //--
    CheckOpen();
    datetime octm;
    int hyst=OrdersHistoryTotal();
    //--
    for(int b=hyst-1; b>=0; b--)
      {
        //--
        if(OrderSelect(b,SELECT_BY_POS,MODE_HISTORY))
          {
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==magicEA)
              {
                //--
                if(OrderType()==OP_BUY)
                  {
                    octm=OrderCloseTime();
                    if(hBm>0 && oBm==0 && octm>0) hBm=0;                            
                  }
                //--
                if(OrderType()==OP_SELL)
                  {
                    octm=OrderCloseTime();
                    if(hSm>0 && oSm==0 && octm>0)  hSm=0;                              
                  }
              }
          }
        //--
      }
   //--
   //---
   return;
//----
  } //-end CheckClose()
//---------//

ChartComm function.


void EXP::ChartComm() // function: write comments on the chart
  {
//---
   string opnsignal=posBUY ? "BUY" : posSELL ? "SELL" : "Not Trade";
   //--
   Comment("n     :: Server Date Time : ",(string)Year(),".",(string)Month(),".",(string)Day(), "   ",TimeToString(TimeCurrent(),TIME_SECONDS), 
      "n     ------------------------------------------------------------", 
      "n      :: Broker             :  ",TerminalCompany(), 
      "n      :: Acc. Name       :  ",AccountName(), 
      "n      :: Acc, Number    :  ",(string)AccountNumber(),
      "n      :: Acc,TradeMode :  ",AccountMode(),
      "n      :: Acc. Leverage   :  1 : ",(string)AccountLeverage(), 
      "n      :: Acc. Balance     :  ",DoubleToString(AccountBalance(),2),
      "n      :: Acc. Equity       :  ",DoubleToString(AccountEquity(),2),
      "n      :: Timeframe        :  ",TF2Str(BnC),
      "n      :: Magic Number   :  ",string(magicEA),
      "n     --------------------------------------------",
      "n      :: Currency Pair    :  ",Symbol(),
      "n      :: Current Spread  :  ",IntegerToString(SymbolInfoInteger(Symbol(),SYMBOL_SPREAD),0),
      "n      :: Signal          : ",opnsignal,
      "n      :: Position BUY  : ",string(oBm),
      "n      :: Position SELL : ",string(oSm),
      "n      :: Current Profit : ",DoubleToString(floatprofit,2));
   //---
   ChartRedraw();
   return;
//----
  } //-end ChartComm()  
//---------//

Then, the Expert Advisor calls the GetOpenPosition function, which in turn calls the SignalCondition function. This function processes signals through:

  • 1. DirectionMove function: Checks if the Close Price is above (Buy Signal) or below (Sell Signal) the Open Price.
  • 2. AllowOpen function: Checks the Open Price position against the Moving Averages period 2 (LWMA Mode, Price Weighted).
  • 3. FiboPivotCB function: Calculates signal using four Moving Average indicators, standard ZigZag indicators for M30 and H1 Timeframes, and the MACD indicator.

SignalCondition function.


int EXP::SignalCondition(void) 
  {
//---
    int rise=1,
        down=-1;
    int InTRise=3;
    int InTDown=-3;
    int cond=0;
    //--   
    CheckOpen();
    int dmove=DirectionMove(BnC,0);
    int alopn=AllowOpen();
    int fbcb3=FiboPivotCB();
    //--
    int TrendIndi=fbcb3+dmove+alopn;
    //--
    if(TrendIndi==InTRise) {cond=rise; cdb=11;}
    if(TrendIndi==InTDown) {cond=down; cds=11;}
    if(oSm>0 && TrendIndi==InTRise) {cond=rise; cdb=12;}
    if(oBm>0 && TrendIndi==InTDown) {cond=down; cds=12;}
    //--
    return(cond);
//---
  } //-end SignalCondition()
//---------//

The SignalCondition function will call 4 functions:

  • CheckOpen();
  • DirectionMove();
  • AllowOpen();
  • FiboPivotCB();

DirectionMove function.


int EXP::DirectionMove(ENUM_TIMEFRAMES xtf,int shift) // Bar Direction 
  {
//---
    int ret=0;
    int rise=1,
        down=-1;
    int br=shift+1;
    RefreshPrice(Symbol(),xtf,br);
    //--
    double diff=iClose(Symbol(),xtf,shift)-iOpen(Symbol(),xtf,shift);
    if( diff>0.0) ret=rise;
    if (diff<0.0) ret=down;
    //--
    return(ret);
//---
  } //-end DirectionMove()
//---------//

AllowOpen function.


int EXP::AllowOpen(void)
  {
//---
    int res=0;
    int rise=1,
        down=-1;
    //--
    int MAWper02=2;
    double MAFast[];
    //--
    ArrayResize(MAFast,bartotal,bartotal);
    ArraySetAsSeries(MAFast,true);
    //--
    CopyPrices();
    //--
    for(int x=bartotal-1; x>=0; x--)
      MAFast[x]=iMA(Symbol(),BnC,MAWper02,0,MODE_LWMA,PRICE_WEIGHTED,x);
    //--
    bool OpenUp=(OPEN[0]<MAFast[0]);
    bool OpenDn=(OPEN[0]>MAFast[0]);
    //--
    if(OpenUp) res=rise;
    if(OpenDn) res=down;
    //--
    //Print(Symbol()+" : AllowOpen res = "+string(res));
    //--
    return(res);
//---
  } //-end AllowOpen()
//---------//

FiboPivotCB function.


int EXP::FiboPivotCB(void) // Signal BUY / SELL Indicator FiboPivotCandleBar
  {
//---
    int res=0;
    int rise=1,
        down=-1;
    //--
    int zzh1=0;
    int zzl1=0;
    int zhm1=0;
    int zlm1=0;
    bool ArrUp=false;
    bool ArrDn=false;
    bool opsup=false;
    bool opsdn=false;
    bool opsnt=false;
    //--   
    ENUM_TIMEFRAMES
       cprz=PERIOD_M15,
       prhh=PERIOD_M30,
       prh1=PERIOD_H1;
    ENUM_MA_METHOD mmeth1=MODE_EMA;
    ENUM_MA_METHOD mmeth2=MODE_SMA;
    ENUM_APPLIED_PRICE aprice=PRICE_MEDIAN;
    //--
    double ema02m[];
    double sma20m[];
    double maon10[];
    double maon62[];
    //--
    ArrayResize(ema02m,bartotal);
    ArrayResize(sma20m,bartotal);
    ArrayResize(maon10,bartotal);
    ArrayResize(maon62,bartotal);
    ArraySetAsSeries(ema02m,true);
    ArraySetAsSeries(sma20m,true);
    ArraySetAsSeries(maon10,true);
    ArraySetAsSeries(maon62,true);
    //--
    RefreshPrice(Symbol(),cprz,bartotal);
    //--
    for(int j=bartotal-1; j>=0; j--)
      {ema02m[j]=iMA(Symbol(),cprz,2,0,mmeth1,aprice,j);}
    for(int k=bartotal-1; k>=0; k--)
      {sma20m[k]=iMA(Symbol(),cprz,20,0,mmeth2,aprice,k);}
    //--
    SimpleMAOnBuffer(bartotal,0,0,10,sma20m,maon10);
    SimpleMAOnBuffer(bartotal,0,0,62,sma20m,maon62);
    //--
    double ma10620=maon10[0]-maon62[0];
    double ma10621=maon10[1]-maon62[1];
    double ma20100=sma20m[0]-maon10[0];
    double ma20101=sma20m[1]-maon10[1];
    //--
    bool ma5xupn=(ema02m[0]>ema02m[1])&&(sma20m[0]>sma20m[1])&&(ma10620>=ma10621)&&((maon10[2]<maon62[2])&&(maon10[0]>maon62[0]));
    bool ma5xupc=(ema02m[0]>ema02m[1])&&(sma20m[0]>sma20m[1])&&(ma10620>=ma10621)&&(maon10[0]>maon62[0])&&(maon10[0]>maon10[1]);
    bool ma5xupb=(ema02m[0]>ema02m[1])&&(sma20m[0]>sma20m[1])&&(ma20100>ma20101)&&(maon62[0]>maon62[1])&&(sma20m[0]>maon10[0]);
    bool ma5xdnn=(ema02m[0]<ema02m[1])&&(sma20m[0]<sma20m[1])&&(ma10620<=ma10621)&&((maon10[2]>maon62[2])&&(maon10[0]<maon62[0]));
    bool ma5xdnc=(ema02m[0]<ema02m[1])&&(sma20m[0]<sma20m[1])&&(ma10620<=ma10621)&&(maon10[0]<maon62[0])&&(maon10[0]<maon10[1]);
    bool ma5xdna=(ema02m[0]<ema02m[1])&&(sma20m[0]<sma20m[1])&&(ma20100<ma20101)&&(maon62[0]<maon62[1])&&(sma20m[0]<maon10[0]);
    //--
    RefreshPrice(Symbol(),prhh,bartotal);
    for(int zz=bartotal-1; zz>=0; zz--) //- for(zz)
      {
        if(iHigh(Symbol(),prhh,zz)==iCustom(Symbol(),prhh,"ZigZag",12,5,3,1,1,zz))
          {zhm1=zz;}
        if(iLow(Symbol(),prhh,zz)==iCustom(Symbol(),prhh,"ZigZag",12,5,3,1,2,zz))
          {zlm1=zz;}
      } //-end for(zz m30)
    //--
    RefreshPrice(Symbol(),prh1,bartotal);
    for(int zz=bartotal-1; zz>=0; zz--) //- for(zz)
      {
        if(iHigh(Symbol(),prh1,zz)==iCustom(Symbol(),prh1,"ZigZag",12,5,3,1,zz))
          {zzh1=zz;}
        if(iLow(Symbol(),prh1,zz)==iCustom(Symbol(),prh1,"ZigZag",12,5,3,1,2,zz))
          {zzl1=zz;}
      } //-end for(zz h1)
    //--
    double macd0=iMACD(Symbol(),prh1,12,26,9,0,MODE_MAIN,0)-iMACD(Symbol(),prh1,12,26,9,0,MODE_SIGNAL,0);
    double macd1=iMACD(Symbol(),prh1,12,26,9,0,MODE_MAIN,1)-iMACD(Symbol(),prh1,12,26,9,0,MODE_SIGNAL,1);
    double mcdm0=iMACD(Symbol(),prh1,12,26,9,0,MODE_MAIN,0);
    double mcdm1=iMACD(Symbol(),prh1,12,26,9,0,MODE_MAIN,1);
    double mcds0=iMACD(Symbol(),prh1,12,26,9,0,MODE_SIGNAL,0);
    double mcds1=iMACD(Symbol(),prh1,12,26,9,0,MODE_SIGNAL,1);
    //--
    if((((zzl1<zzh1)&&(zzl1>0)&&(zzl1<4)&&(zlm1<zhm1)))||((macd0>macd1)&&(mcdm0>mcdm1))) {ArrUp=true;}
    //--
    if((((zzl1>zzh1)&&(zzh1>0)&&(zzh1<4)&&(zlm1>zhm1)))||((macd0<macd1)&&(mcdm0<mcdm1))) {ArrDn=true;}
    //--
    if(((ArrUp==true)&&(zzl1>4))||((mcdm0<mcdm1)&&(macd0<macd1))) {ArrDn=true; ArrUp=false;}
    if(((ArrDn==true)&&(zzh1>4))||((mcdm0>mcdm1)&&(macd0>macd1))) {ArrUp=true; ArrDn=false;}
    if((mcdm0>=mcdm1)&&(mcdm0>mcds0)&&(mcds0>mcds1)) {ArrUp=true; ArrDn=false;}
    if((mcdm0<=mcdm1)&&(mcdm0<mcds0)&&(mcds0<mcds1)) {ArrDn=true; ArrUp=false;}
    if(ma5xupn||ma5xupc||ma5xupb) {ArrUp=true; ArrDn=false;}
    if(ma5xdnn||ma5xdnc||ma5xdna) {ArrDn=true; ArrUp=false;}
    //--
    double fpCls0=(iHigh(Symbol(),prh1,0)+iLow(Symbol(),prh1,0)+iClose(Symbol(),prh1,0)+iClose(Symbol(),prh1,0))/4;
    double fpCls1=(iHigh(Symbol(),prh1,1)+iLow(Symbol(),prh1,1)+iClose(Symbol(),prh1,1)+iClose(Symbol(),prh1,1))/4;
    double hlcc0=fpCls0-iMA(Symbol(),prh1,20,0,mmeth2,aprice,0);
    double hlcc1=fpCls1-iMA(Symbol(),prh1,20,0,mmeth2,aprice,1);
    //--
    if((ArrUp==true)&&(hlcc0>hlcc1)) {opsup=true; opsdn=false; opsnt=false;}
    //--
    if((ArrDn==true)&&(hlcc0<hlcc1)) {opsdn=true; opsup=false; opsnt=false;}
    //--
    if((!opsup)&&(!opsdn)) {opsnt=true; opsup=false; opsdn=false;}
    //--
    //---
    if(ArrUp && opsup) res=rise;
    //--
    if(ArrDn && opsdn) res=down;
    //--
    //---
    return(res);
//---
  } //-end FiboPivotCB()
//---------//

The FiboPivotCB() that utilizes a combination of technical analysis indicators and Fibonacci Pivot Points to generate buy and sell signals.

1. Variable Declaration:

  • Various integer and boolean variables are declared to store intermediate calculations and signal flags.
  • Timeframe variables cprz, prhh, and prh1 are defined to specify different timeframes for calculations.
  • Arrays ema02m, sma20m, maon10, and maon62 are declared to store calculated moving averages.

2. Calculating Moving Averages:

  • The code calculates several moving averages using the iMA() function.
  • It also calculates differences between moving averages to identify potential trend changes.

3. Fibonacci Pivot Points:

  • The code calculates Fibonacci Pivot Points using the iHigh(), iLow(), and iClose() functions.
  • It identifies potential support and resistance levels based on these pivot points.

4. Trend Identification:

  • The code uses a combination of moving average crossovers and Fibonacci Pivot Points to identify potential uptrends and downtrends.
  • Boolean variables ArrUp and ArrDn are used to indicate upward and downward trends, respectively.

5. Signal Generation:

  • The final if conditions check the values of the trend indicators and Fibonacci Pivot Points to generate buy or sell signals.
  • res variable is set to rise for a buy signal and down for a sell signal.

Key Points to Note:

  • Timeframe Importance: The choice of timeframes (e.g., cprz, prhh, prh1) significantly impacts the sensitivity and accuracy of the signals.
  • Indicator Combination: The code combines multiple indicators to generate more robust signals, reducing the risk of false signals.

Buy Orders condition:

  • takeBuyPositions function is true.
  • No existing Buy order (one order per direction signal).
  • On a new bar (no previous Buy order or Close Buy order on that bar).
  • If a Sell order exists and Close Trade By Opposite Signal is Yes, it opens a Buy order and closes the Sell order.
  • If Close Trade By Opposite Signal is No, it opens a Buy order and leaves the Sell order open.

Sell Orders condition:

  • takeSellPositions function is true.
  • No existing Sell order (one order per direction signal).
  • On a new bar (no previous Sell order or Close Sell order on that bar).
  • If a Buy order exists and Close Trade By Opposite Signal is Yes, it opens a Sell order and closes the Buy order.
  • If Close Trade By Opposite Signal is No, it opens a Sell order and leaves the Buy order open.

If Use Close In Signal Exit is Yes, the Expert Advisor calls the SignalExit function to close orders if the signal is not significant.

If the Orders Total is greater than or equal to the ACCOUNT LIMIT ORDERS set by the broker, the Expert Advisor calls the CloseAllOrdersProfit function to close profitable orders, keeping the total open orders below the broker's limit.

If Use Trailing Stop and Trailing Profit is Yes, the Expert Advisor performs trailing stop and trailing profit using TrailingPositionsBuy for Buy orders and TrailingPositionsSell for Sell orders.

For additional functions, you can explore and learn from the Expert Advisor program it self. If you have any questions, feel free to write in the comments or email me.

I recommend testing this expert advisor directly on the trading terminal using a demo account. While you can use the StrategyTester, keep in mind that its results depend heavily on the complete history of price data in your MetaTrader 4. This expert advisor integrates multiple indicators, including a 6-period Moving Average, ZigZag indicator (two timeframes), and MACD indicator.

I've tested this expert advisor on the MT4 trading terminal using a demo account to evaluate its performance. As you can see, the expert advisor has opened orders according to the FiboPivotCandleBar for the MT4 indicator signal, which indicates that it is functioning well.

Thank you for reading this article.

See you in the next article on Expert Advisor programs or indicators for MetaTrader 4 and MetaTrader 5.

Please download the Expert Advisor: ExpFPCB-MT4 and Indicator: FiboPivotCandleBar

If you are subscribed to my YouTube Channel, and would like to receive the source program of this article, please send a request via the Contact Us form page, and I will send it to your email, source code:

Expert Advisor: ExpFPCB-MT4.mq4

Indicator: FiboPivotCandleBar.mq4

Don't forget to stop by and subscribe to Forex Home Experts YouTube Channel:

YouTube Channel: @ForexHomeExperts

YouTube Playlist: @ForexHomeExperts YouTube Playlist

Wednesday, November 27, 2024

MT5 Indicator Program Explanation and Function

Overview:

The TimeBarCloseCheck MT5 Indicator is designed to detect the bar close time and the close price in the MetaTrader 5 trading platform. This program assists traders by providing accurate timing and pricing information, which is essential for making informed trading decisions.

Functions:

1. Bar Close Time Detection:

The indicator precisely identifies when a trading bar (or candlestick) closes. This is crucial for traders who rely on closing prices to determine market trends and make trading decisions.

2. Price Close Detection:

It captures the exact price at which the bar closes. This data is vital for analyzing market conditions and planning future trades.

3. Alerts and Notifications:

The program can be configured to send alerts or notifications when a bar closes, allowing traders to stay updated without constantly monitoring the charts.

4. Customizable Settings:

Users can customize the indicator settings according to their trading strategy and preferences, making it a versatile tool for different trading styles.

Benefits:

1. Accuracy: Provides precise timing and pricing information to enhance trading strategies.

2. Convenience: Automated alerts save time and help traders stay focused on their trading goals.

3. Customization: Adaptable to various trading strategies, ensuring it meets individual needs.

How to detect Bar Close Time in MT5 and MT4

Let's go through the code section provided and explain each part:


//+------------------------------------------------------------------+
//|                                            TimeBarCloseCheck.mq5 |
//|        Copyright 2024, Roberto Jacobs (3rjfx) ~ Date: 2024-11-26 |
//|                              https://www.mql5.com/en/users/3rjfx |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, Roberto Jacobs (3rjfx) ~ Date: 2024-11-26"
#property link      "https://www.mql5.com/en/users/3rjfx"
#property version   "1.00"
#property indicator_chart_window

Code Explanation:

Metadata Section:

This section contains metadata about the indicator, including the name, author, version, and copyright information.

#property copyright specifies the copyright details.

#property link provides a link to the author's profile or website.

#property version indicates the version of the indicator.

#property indicator_chart_window tells MT5 that this indicator will be applied to the chart window.

#property indicator_plots 0
#property indicator_plots = 0, indicates that this indicator does not have any graphical plots.


//-- Enumeration
enum YN
 {
   No,  
   Yes
 };

Enumeration YN:

An enumeration defining Yes and No options. Useful for input parameters that need a binary choice.


enum corner
 {  
   LeftHand=0,
   RightHand=1
 };

Enumeration corner:

This enumeration is used to define possible positions (left or right) for text display on the chart.


enum fonts
  {
    Verdana,
    Bodoni_MT_Black
  }; 

Enumeration fonts:

An enumeration listing the font options available for text display on the chart.


input ENUM_TIMEFRAMES  Timeframe = PERIOD_H1;     // Select Expert TimeFrame, default PERIOD_H1
input corner                 cor = LeftHand;     // Corner Position Text
//--- Input parameters for alerts
input YN                  alerts = Yes;            // Display Alerts Pop-up on Chart (Yes) or (No)
input YN           UseEmailAlert = No;             // Email Alert (Yes) or (No)
input YN           UseSendnotify = No;             // Send Notification (Yes) or (No)
//--- Input text parameters
input fonts              f_model = Verdana;        // Select Font Model
input color              t_color = clrGold;        // Select Text Color

Input Parameters:

input ENUM_TIMEFRAMES Timeframe = PERIOD_H1; - Allows the user to select the timeframe for the indicator, default is 1 hour (H1).

Explanation:

The input ENUM_TIMEFRAMES Timeframe, Allowing users to select the timeframe (with the default being H1) for the TimeBarCloseCheck indicator provides significant flexibility. Even if a user is analyzing a Symbol chart on a different timeframe, such as D1, setting the indicator to H1 ensures it continues to provide information and alerts based on the H1 timeframe.

This functionality is highly advantageous for traders who prefer to monitor multiple timeframes simultaneously. For instance, a trader could keep an eye on long-term trends on a D1 chart while still receiving timely alerts and information pertinent to the H1 timeframe without switching their primary chart’s timeframe. This approach provides a comprehensive view of the market, facilitating more informed trading decisions.

input corner cor = LeftHand; - Allows the user to select the position of the text on the chart.

Alert input parameters to enable or disable different types of alerts:

  • input YN alerts = Yes; - Shows a pop-up alert on the chart.
  • input YN UseEmailAlert = No; - Enables or disables email alerts.
  • input YN UseSendnotify = No; - Enables or disables notifications.

Text input parameters to customize the appearance:

  • input fonts f_model = Verdana; - Selects the font model for the text.
  • input color t_color = clrGold; - Selects the color of the text.

Variables:

  • double CLOSE[];
  • datetime TIME[];
  • datetime TFOpenTime=0;
  • datetime TFClosTime=0;
  • datetime TFNextTime=0;
  • datetime TFprevTime=0;
  • datetime TFTimeRem=0;
  • datetime remd=0;
  • datetime tmrem=0;
  • datetime tmrem=0;
  • double tmdrem=0;
  • string txtday;
  • string font_mode;

Various global variables to store close prices (CLOSE[]), time values (TIME[], TFOpenTime, etc.), and text settings (txtday, font_mode).

Time Variables:

Variables to store different components of the time (year, month, day, hour, minute, second).

  • int x_year; // Year
  • int x_mon; // Month
  • int x_day; // Day of the month
  • int x_hour; // Hour in a day
  • int x_min; // Minutes
  • int x_sec; // Seconds

Time Constants:

Constants used for indexing time components and day information.

  • int year=0; // Year
  • int mon=1; // Month
  • int day=2; // Day
  • int hour=3; // Hour
  • int min=4; // Minutes
  • int sec=5; // Seconds
  • int dow=6; // Day of week (0-Sunday, 1-Monday, ... ,6-Saturday)
  • int doy=7; // Day number of the year (January 1st is assigned the number value of zero)

Miscellaneous Variables:

Various other global variables for specific functionalities like extime, exday, f_size, cbar, scale, garis, and alert-related variables (doalert, AlertTxt).

  • int extime=0;
  • int exday=0;
  • int f_size=9;
  • int cbar=9;
  • int scale=15;
  • int garis=12;
  • int xdis=0,ydis=90;
  • ENUM_BASE_CORNER PilCor;
  • bool doalert;
  • string AlertTxt;
  • string _pname;
  • string indiname;

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
     _pname=MQLInfoString(MQL_PROGRAM_NAME);
     indiname=_pname+" : "+TF2Str(Timeframe);
     //--
     cor==RightHand ? PilCor=ENUM_BASE_CORNER(CORNER_RIGHT_UPPER) : PilCor=ENUM_BASE_CORNER(CORNER_LEFT_UPPER);
     xdis=PilCor==(ENUM_BASE_CORNER)CORNER_RIGHT_UPPER ? 288 : 30;
     //--
     font_mode=FontsModel(f_model);
//---
   return(INIT_SUCCEEDED);
  }
//---------//

This function primarily sets up the necessary parameters for the indicator to function properly, including determining the position of text elements on the chart and setting the font style.

Explanation:

1. Function Purpose:

The OnInit function is the initialization function for the custom indicator. It sets up various parameters and prepares the indicator to run.

  • _pname=MQLInfoString(MQL_PROGRAM_NAME);
  • indiname=_pname+" : "+TF2Str(Timeframe);

_pname stores the name of the MQL program.

indiname combines the program name and the selected timeframe into a single string for display or logging purpose

2. Setting the Text Position:

cor==RightHand ? PilCor=ENUM_BASE_CORNER(CORNER_RIGHT_UPPER) : PilCor=ENUM_BASE_CORNER(CORNER_LEFT_UPPER); xdis=PilCor==(ENUM_BASE_CORNER)CORNER_RIGHT_UPPER ? 288 : 30;

This conditional (ternary) operator checks if the cor variable is set to RightHand.

If cor is RightHand, PilCor is set to CORNER_RIGHT_UPPER; otherwise, it is set to CORNER_LEFT_UPPER.

xdis is set based on the value of PilCor: 288 if CORNER_RIGHT_UPPER, otherwise 30.

Font Mode: font_mode=FontsModel(f_model);

Return Value: return(INIT_SUCCEEDED);

The function returns INIT_SUCCEEDED, indicating that the initialization was successful.


string FontsModel(int mode)
  { 
   string str_font;
   switch(mode) 
     { 
      case 0: str_font="Verdana"; break;
      case 1: str_font="Bodoni MT Black"; break; 
     }
   //--
   return(str_font);
//----
  } //-end FontsModel()
//---------//

This function helps convert the integer mode to a string representing the font name, which can then be used elsewhere in the indicator for setting text properties.

Let's break down the FontsModel function:

Explanation:

Function Name and Parameters: string FontsModel(int mode)

The function FontsModel takes an integer parameter mode.

String Variable Declaration: string str_font;

A string variable str_font is declared to hold the name of the font.

Switch Statement: The switch statement evaluates the value of mode to determine which font to select.

Case Statements:

  • case 0: str_font="Verdana"; break;
  • case 1: str_font="Bodoni MT Black"; break;

If mode is 0, str_font is set to "Verdana".

If mode is 1, str_font is set to "Bodoni MT Black".

Default Case: The default case is not explicitly provided here, meaning if mode is neither 0 nor 1, str_font will remain uninitialized.

Return Statement: return(str_font);

The function returns the value of str_font.


//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//----
    Comment("");
    PrintFormat("%s: Deinitialization reason code=%d",__FUNCTION__,reason);
    Print(getUninitReasonText(reason));
    //--
    ObjectsDeleteAll(ChartID(),0,-1);
//----
   return;
  }
//-----//

Let's dive into the OnDeinit function and break down each part.

Explanation:

1. Function Purpose: The OnDeinit function is called when the custom indicator is being removed or unloaded from the chart. It handles cleanup tasks and ensures that resources are properly released.

Function Definition: void OnDeinit(const int reason)

The function takes an integer parameter reason which indicates the reason for deinitialization. The void keyword means this function does not return any value.

Clearing Comments: Comment("");

This line clears any comments displayed on the chart.

Printing Deinitialization Reason:

PrintFormat("%s: Deinitialization reason code=%d", __FUNCTION__, reason);

Print(getUninitReasonText(reason));

PrintFormat outputs a formatted string to the log, showing the function name (__FUNCTION__) and the deinitialization reason code.

Print outputs the text returned by getUninitReasonText(reason), which provides a more descriptive reason for deinitialization.

Deleting Objects: ObjectsDeleteAll(ChartID(), 0, -1);

This line deletes all objects from the chart. ChartID() gets the current chart's ID, and the 0 and -1 parameters indicate that all objects on all subwindows of the chart should be deleted.

Returning: return;

The function ends with a return statement, which is redundant for a void function but included for clarity.

This function ensures that when the indicator is removed, all related objects and comments are cleared from the chart, and relevant information about the deinitialization reason is logged for debugging or informational purposes.


string getUninitReasonText(int reasonCode) 
  { 
//---
   string text=""; 
   //--- 
   switch(reasonCode) 
     { 
       case REASON_PROGRAM:
            text="The EA has stopped working calling by remove function."; break;
       case REASON_REMOVE: 
            text="Program "+__FILE__+" was removed from chart"; break;
       case REASON_RECOMPILE:
            text="Program recompiled."; break;    
       case REASON_CHARTCHANGE: 
            text="Symbol or timeframe was changed"; break;
       case REASON_CHARTCLOSE: 
            text="Chart was closed"; break; 
       case REASON_PARAMETERS: 
            text="Input-parameter was changed"; break;            
       case REASON_ACCOUNT: 
            text="Account was changed"; break; 
       case REASON_TEMPLATE: 
            text="New template was applied to chart"; break; 
       case REASON_INITFAILED:
            text="The OnInit() handler returned a non-zero value."; break;
       case REASON_CLOSE: 
            text="Terminal closed."; break;
       default: text="Another reason"; break;
     } 
   //--
   return text;
//---
  } //-end getUninitReasonText()
//---------//

Let's explain the getUninitReasonText function and how it works:

Explanation:

1. Function Purpose: The getUninitReasonText function converts a deinitialization reason code into a human-readable string explanation. It helps in understanding why the indicator was deinitialized.

2. Function Definition: string getUninitReasonText(int reasonCode)

String Initialization: string text="";

Initializes an empty string text to store the explanation.

Switch Statement: switch(reasonCode)

The switch statement evaluates the reasonCode and sets the text variable accordingly.

Case Statements:

Each case in the switch statement corresponds to a specific reason code:

  • case REASON_PROGRAM: text="The EA has stopped working calling by remove function."; break;
  • case REASON_REMOVE: text="Program "+__FILE__+" was removed from chart"; break;
  • case REASON_RECOMPILE: text="Program recompiled."; break;
  • case REASON_CHARTCHANGE: text="Symbol or timeframe was changed"; break;
  • case REASON_CHARTCLOSE: text="Chart was closed"; break;
  • case REASON_PARAMETERS: text="Input-parameter was changed"; break;
  • case REASON_ACCOUNT: text="Account was changed"; break;
  • case REASON_TEMPLATE: text="New template was applied to chart"; break;
  • case REASON_INITFAILED: text="The OnInit() handler returned a non-zero value."; break;
  • case REASON_CLOSE: text="Terminal closed."; break;
  • default: text="Another reason"; break;

For each possible reasonCode, the corresponding text explanation is assigned to text. The __FILE__ macro is used to include the filename in the explanation for the REASON_REMOVE case.

Default Case: default: text="Another reason"; break;

If reasonCode does not match any of the specified cases, the default text "Another reason" is assigned.

Return Statement: return text;

The function returns the text variable containing the explanation.

This function is useful for logging and debugging, providing clear reasons why the indicator was deinitialized, which can help in diagnosing issues or understanding the behavior of the indicator.


//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
     ArrayResize(TIME,cbar);
     ArrayResize(CLOSE,cbar);
     ArraySetAsSeries(TIME,true);
     ArraySetAsSeries(CLOSE,true);
     ArraySetAsSeries(time,true);
     ArraySetAsSeries(close,true);
     //--
     RefreshPrice(Timeframe);
     //--
     TFOpenTime=TIME[0];
     CheckSeconds();
     //--
     TFNextTime=TFOpenTime+extime;
     TFClosTime=TFNextTime-1;
     TFTimeRem=fabs(TimeCurrent()-TFClosTime);
     tmrem=TFClosTime-TimeCurrent();
     datetime dtB=0; 
     if(TFClosTime!=TFprevTime) doalert=false;
     string SDT=ReqDate(TimeCurrent(),ReqTime(TimeCurrent(),day),ReqTime(TimeCurrent(),hour),ReqTime(TimeCurrent(),min),ReqTime(TimeCurrent(),sec));
     //--
     if(TimeCurrent()<TFClosTime)
       {
         remd=ReqTime(TFClosTime,day)-ReqTime(TimeCurrent(),day);
         exday=int(remd);
         if(exday<=0) exday=0;
         txtday=exday==0 ? (string)ReqTime(TFTimeRem,hour)+":"+(string)ReqTime(TFTimeRem,min)+":"+(string)ReqTime(TFTimeRem,sec) :
         (string)exday+" Day ~ "+(string)ReqTime(TFTimeRem,hour)+":"+(string)ReqTime(TFTimeRem,min)+":"+(string)ReqTime(TFTimeRem,sec);
       }
     //--
     CreateChartText(0,indiname+"SDT0","Server Date Time : "+SDT,font_mode,f_size,t_color,PilCor,xdis,ydis);
     CreateChartText(0,indiname+"SDT11","------------------------------------------------------",font_mode,f_size,t_color,PilCor,xdis,ydis+garis);
     CreateChartText(0,indiname+"SDT1",_pname+" : Period "+TF2Str(Timeframe),font_mode,f_size,t_color,PilCor,xdis,ydis+garis+(1*scale));
     CreateChartText(0,indiname+"SDT2","Bar Open Time : "+
                       TimeToString(TFOpenTime,TIME_DATE|TIME_MINUTES|TIME_SECONDS),font_mode,f_size,t_color,PilCor,xdis,ydis+garis+(2*scale));
     CreateChartText(0,indiname+"SDT3","Bar Close Time : "+
                       TimeToString(TFClosTime,TIME_DATE|TIME_MINUTES|TIME_SECONDS),font_mode,f_size,t_color,PilCor,xdis,ydis+garis+(3*scale));
     CreateChartText(0,indiname+"SDT4","Next Bar Open Time : "+
                       TimeToString(TFNextTime,TIME_DATE|TIME_MINUTES|TIME_SECONDS),font_mode,f_size,t_color,PilCor,xdis,ydis+garis+(4*scale));
     CreateChartText(0,indiname+"SDT5","Time Remaining : "+txtday,font_mode,f_size,t_color,PilCor,xdis,ydis+garis+(5*scale));                         
     //--
     if(alerts==Yes||UseEmailAlert==Yes||UseSendnotify==Yes)
       {
         if(TimeCurrent()>=TFClosTime && TimeCurrent()<=TFNextTime && !doalert)
           {
             dtB=TimeCurrent();
             AlertTxt="Bar Close time triggered in Timeframe : "+TF2Str(Timeframe)+" @Price: "+DoubleToString(CLOSE[0],Digits());
             Do_Alerts(AlertTxt,dtB);
             TFprevTime=TFClosTime;
             doalert=true;
           }
       }
    //--
//--- return value of prev_calculated for next call
   return(rates_total);
  }

Let's break down the OnCalculate function of MT5 indicator. This function is called on every tick to update the indicator's values and perform calculations. Here's a detailed explanation:

Function Definition and Parameters:


int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])

1. Function Purpose: This function is responsible for calculating and updating the indicator's values on each new tick.

2. Parameters:

  • rates_total: - The total number of bars.
  • prev_calculated: - The number of bars calculated on the previous call.
  • time, open, high, low, close, tick_volume, volume, spread - Arrays containing the bar data for the symbol.

3. Code Breakdown:

  • ArrayResize(TIME, cbar);
  • ArrayResize(CLOSE, cbar);
  • ArraySetAsSeries(TIME, true);
  • ArraySetAsSeries(CLOSE, true);
  • ArraySetAsSeries(time, true);
  • ArraySetAsSeries(close, true);

Array Setup: Resizes and sets arrays to series to access data from the current bar to the oldest.

Fuction Call:

RefreshPrice(Timeframe);

Refresh Price Data: Calls a custom function to refresh price data for the specified timeframe.

  • TFOpenTime = TIME[0];
  • CheckSeconds();

Initialize Variables: Sets the opening time of the current bar and calls a custom function to check seconds.

  • TFNextTime = TFOpenTime + extime;
  • TFClosTime = TFNextTime - 1;
  • TFTimeRem = fabs(TimeCurrent() - TFClosTime);
  • tmrem = TFClosTime - TimeCurrent();
  • datetime dtB = 0;
  • if (TFClosTime != TFprevTime) doalert = false;
  • string SDT = ReqDate(TimeCurrent(), ReqTime(TimeCurrent(), day), ReqTime(TimeCurrent(), hour), ReqTime(TimeCurrent(), min), ReqTime(TimeCurrent(), sec));

Calculate Times: Calculates the next bar's opening and closing times, the remaining time until the bar closes, and other time-related variables.


//--
if(TimeCurrent()<TFClosTime)
  {
    remd=ReqTime(TFClosTime,day)-ReqTime(TimeCurrent(),day);
    exday=int(remd);
    if(exday<=0) exday=0;
    txtday=exday==0 ? (string)ReqTime(TFTimeRem,hour)+":"+(string)ReqTime(TFTimeRem,min)+":"+(string)ReqTime(TFTimeRem,sec) :
                    (string)exday+" Day ~ "+(string)ReqTime(TFTimeRem,hour)+":"+(string)ReqTime(TFTimeRem,min)+":"+   (string)ReqTime(TFTimeRem,sec);
  }
//--

Calculate Remaining Time: Determines the remaining time until the current bar closes and formats it for display.

CreateChartText Function Calls:

  • CreateChartText(0, indiname + "SDT0", "Server Date Time : " + SDT, font_mode, f_size, t_color, PilCor, xdis, ydis);
  • CreateChartText(0, indiname + "SDT11", "------------------------------------------------------", font_mode, f_size, t_color, PilCor, xdis, ydis + garis);
  • CreateChartText(0, indiname + "SDT1", _pname + " : Period " + TF2Str(Timeframe), font_mode, f_size, t_color, PilCor, xdis, ydis + garis + (1 * scale));
  • CreateChartText(0, indiname + "SDT2", "Bar Open Time : " + TimeToString(TFOpenTime, TIME_DATE|TIME_MINUTES|TIME_SECONDS), font_mode, f_size, t_color, PilCor, xdis, ydis + garis + (2 * scale));
  • CreateChartText(0, indiname + "SDT3", "Bar Close Time : " + TimeToString(TFClosTime, TIME_DATE|TIME_MINUTES|TIME_SECONDS), font_mode, f_size, t_color, PilCor, xdis, ydis + garis + (3 * scale));
  • CreateChartText(0, indiname + "SDT4", "Next Bar Open Time : " + TimeToString(TFNextTime, TIME_DATE|TIME_MINUTES|TIME_SECONDS), font_mode, f_size, t_color, PilCor, xdis, ydis + garis + (4 * scale));
  • CreateChartText(0, indiname + "SDT5", "Time Remaining : " + txtday, font_mode, f_size, t_color, PilCor, xdis, ydis + garis + (5 * scale));

Display Information:

Uses custom CreateChartText function to display various pieces of information on the chart, such as server date/time, bar open/close times, and time remaining.

Alerts:


if (alerts == Yes || UseEmailAlert == Yes || UseSendnotify == Yes)
{
  if (TimeCurrent() >= TFClosTime && TimeCurrent() <= TFNextTime && !doalert)
  {
    dtB = TimeCurrent();
    AlertTxt = "Bar Close time triggered in Timeframe : " + TF2Str(Timeframe) + " @Price: " + DoubleToString(CLOSE[0], Digits());
    Do_Alerts(AlertTxt, dtB);
    TFprevTime = TFClosTime;
    doalert = true;
  }
}

Trigger Alerts: Checks if current time is within the bar's closing period and triggers alerts if necessary.

Return Value: return(rates_total);

Return Statement: Returns the total number of rates (bars) calculated, which is used for the next call to OnCalculate.

This function ensures that the indicator updates accurately with each new tick, displaying relevant information on the chart and triggering alerts as needed.

CheckSeconds Function:

Let's explain the CheckSeconds function:

1. Purpose: The CheckSeconds function determines the number of seconds in a specific timeframe and assigns it to the extime variable. This helps to calculate the duration of each bar in the selected timeframe.

2. Code Breakdown:


int CheckSeconds(void)
  {
   //---
   switch(Timeframe)
     {
       //--
       case PERIOD_M1:   extime=PeriodSeconds(PERIOD_M1);     break;
       case PERIOD_M2:   extime=PeriodSeconds(PERIOD_M2);     break;
       case PERIOD_M3:   extime=PeriodSeconds(PERIOD_M3);     break;
       case PERIOD_M4:   extime=PeriodSeconds(PERIOD_M4);     break;
       case PERIOD_M5:   extime=PeriodSeconds(PERIOD_M5);     break;
       case PERIOD_M6:   extime=PeriodSeconds(PERIOD_M6);     break;
       case PERIOD_M10:  extime=PeriodSeconds(PERIOD_M10);    break;
       case PERIOD_M12:  extime=PeriodSeconds(PERIOD_M12);    break;
       case PERIOD_M15:  extime=PeriodSeconds(PERIOD_M15);    break;
       case PERIOD_M20:  extime=PeriodSeconds(PERIOD_M20);    break;
       case PERIOD_M30:  extime=PeriodSeconds(PERIOD_M30);    break;
       case PERIOD_H1:   extime=PeriodSeconds(PERIOD_H1);     break;
       case PERIOD_H2:   extime=PeriodSeconds(PERIOD_H2);     break;
       case PERIOD_H3:   extime=PeriodSeconds(PERIOD_H3);     break;
       case PERIOD_H4:   extime=PeriodSeconds(PERIOD_H4);     break;
       case PERIOD_H6:   extime=PeriodSeconds(PERIOD_H6);     break;
       case PERIOD_H8:   extime=PeriodSeconds(PERIOD_H8);     break;
       case PERIOD_H12:  extime=PeriodSeconds(PERIOD_H12);    break;
       case PERIOD_D1:   extime=PeriodSeconds(PERIOD_D1);     break;
       case PERIOD_W1:   extime=PeriodSeconds(PERIOD_W1);     break;
       case PERIOD_MN1:  extime=PeriodSeconds(PERIOD_MN1);    break;
       //--
     }
    //--
    return(extime);
  }

3. Explanation:

1. Function Signature: int CheckSeconds(void)

This function returns an integer value representing the number of seconds in the current timeframe.

2. Switch Statement: switch(Timeframe)

The switch statement evaluates the Timeframe variable to determine which timeframe is being used.

Case Statements:

  • case PERIOD_M1: extime=PeriodSeconds(PERIOD_M1); break;
  • case PERIOD_M2: extime=PeriodSeconds(PERIOD_M2); break;
  • case PERIOD_M3: extime=PeriodSeconds(PERIOD_M3); break;
  • case PERIOD_M4: extime=PeriodSeconds(PERIOD_M4); break;
  • case PERIOD_M5: extime=PeriodSeconds(PERIOD_M5); break;
  • case PERIOD_M6: extime=PeriodSeconds(PERIOD_M6); break;
  • case PERIOD_M10: extime=PeriodSeconds(PERIOD_M10); break;
  • case PERIOD_M12: extime=PeriodSeconds(PERIOD_M12); break;
  • case PERIOD_M15: extime=PeriodSeconds(PERIOD_M15); break;
  • case PERIOD_M20: extime=PeriodSeconds(PERIOD_M20); break;
  • case PERIOD_M30: extime=PeriodSeconds(PERIOD_M30); break;
  • case PERIOD_H1: extime=PeriodSeconds(PERIOD_H1); break;
  • case PERIOD_H2: extime=PeriodSeconds(PERIOD_H2); break;
  • case PERIOD_H3: extime=PeriodSeconds(PERIOD_H3); break;
  • case PERIOD_H4: extime=PeriodSeconds(PERIOD_H4); break;
  • case PERIOD_H6: extime=PeriodSeconds(PERIOD_H6); break;
  • case PERIOD_H8: extime=PeriodSeconds(PERIOD_H8); break;
  • case PERIOD_H12: extime=PeriodSeconds(PERIOD_H12); break;
  • case PERIOD_D1: extime=PeriodSeconds(PERIOD_D1); break;
  • case PERIOD_W1: extime=PeriodSeconds(PERIOD_W1); break;
  • case PERIOD_MN1: extime=PeriodSeconds(PERIOD_MN1); break;

For each timeframe (e.g., PERIOD_M1, PERIOD_H1, etc.), the corresponding number of seconds is calculated using the PeriodSeconds function and assigned to the extime variable.

Return Statement: return(extime);

The function returns the value of extime, which represents the duration of each bar in seconds for the selected timeframe.

This function is crucial for ensuring that the indicator can accurately calculate the time remaining until the current bar closes, regardless of the timeframe selected.

RefreshPrice Function.

1. Purpose:

The RefreshPrice function updates the price data arrays for a specified timeframe. This helps ensure that the indicator has the latest data for its calculations.

2. Code Breakdown:


void RefreshPrice(ENUM_TIMEFRAMES xtf)
  {
    //---
    MqlRates parray[]; 
    ArraySetAsSeries(parray, true); 
    int copied = CopyRates(Symbol(), xtf, 0, cbar, parray);
    //--
    int cc = CopyClose(Symbol(), xtf, 0, cbar, CLOSE);
    int ct = CopyTime(Symbol(), xtf, 0, cbar, TIME);
    //--
    return;
    //---
  } //-end RefreshPrice()
//---------//

3. Explanation:

1. Function Signature: void RefreshPrice(ENUM_TIMEFRAMES xtf)

The function takes a single parameter xtf of type ENUM_TIMEFRAMES, which specifies the timeframe to update.

2. Declare and Initialize MqlRates Array:

  • MqlRates parray[];
  • ArraySetAsSeries(parray, true);

Declares an array parray of type MqlRates to store the price data.

ArraySetAsSeries(parray, true) sets the array to be accessed as a series (with the latest data at index 0).

3. Copy Rates Data: int copied = CopyRates(Symbol(), xtf, 0, cbar, parray);

Uses CopyRates to copy the rates (OHLC and others data) for the specified symbol and timeframe into the parray array.

  • Symbol() returns the current symbol.
  • xtf is the timeframe.
  • 0 is the starting position.
  • cbar is the number of bars to copy.
  • parray is the destination array.

The function returns the number of copied rates and stores it in copied.

Copy Close Prices: int cc = CopyClose(Symbol(), xtf, 0, cbar, CLOSE);

Uses CopyClose to copy the close prices for the specified symbol and timeframe into the CLOSE array.

The function returns the number of copied close prices and stores it in cc.

Copy Time Data: int ct = CopyTime(Symbol(), xtf, 0, cbar, TIME);

Uses CopyTime to copy the time data for the specified symbol and timeframe into the TIME array.

The function returns the number of copied time values and stores it in ct.

Return Statement: return;

The function returns void, indicating it does not return any value. The return statement is used to exit the function.

This function is crucial for ensuring that the indicator always has the most up-to-date price data, which is essential for accurate calculations and display.

timehr Function

1. Purpose: The timehr function formats the given hour and minute values into a string representation of time in the "HH:MM" format.

2. Code Breakdown:


string timehr(int hr,int mn)
  {
//---
    string scon="";
    string men=mn==0 ? "00" : string(mn);
    int shr=hr==24 ? 0 : hr;
    if(shr<10) scon="0"+string(shr)+":"+men;
    else scon=string(shr)+":"+men;
    //--
    return(scon);
//---
  } //-end timehr()
//---------//

3. Explanation:

1. Function Signature: The function takes two integer parameters: hr for hours and mn for minutes. It returns a string representing the formatted time.

2. Variable Initialization:

  • string scon = "";
  • string men = mn == 0 ? "00" : string(mn);
  • int shr = hr == 24 ? 0 : hr;

scon is initialized as an empty string.

men is set to "00" if mn is 0; otherwise, it is set to the string representation of mn.

shr is set to 0 if hr is 24 (to represent midnight as "00:00"); otherwise, it is set to hr.

3. Conditional Formatting:


if (shr < 10) scon = "0" + string(shr) + ":" + men;
else scon = string(shr) + ":" + men;

If shr is less than 10, scon is formatted with a leading zero (e.g., "09:00").

If shr is 10 or greater, scon is formatted without a leading zero (e.g., "10:00").

4. Return Statement: The function returns the formatted string scon, which represents the time in "HH:MM" format.

This function is useful for ensuring that time values are consistently formatted, which is particularly important for displaying times in a readable and standardized manner on charts or logs.

ReqDate Function.

1. Purpose: The ReqDate function formats a given datetime value into a custom string representation that includes the date and time.

2. Code Breakdown:


string ReqDate(datetime reqtime,int d,int h,int m,int s) 
  { 
//---
   MqlDateTime mdt; 
   datetime t=TimeToStruct(reqtime,mdt);
   x_year=mdt.year; 
   x_mon=mdt.mon; 
   x_day=d; 
   x_hour=h; 
   x_min=m;
   x_sec=s;
   //--
   string mdr=string(x_year)+"."+string(x_mon)+"."+string(x_day)+" ~ "+timehr(x_hour,x_min)+":"+string(x_sec);
   return(mdr);
//---
  } //-end ReqDate()
//---------//

3. Explanation:

1. Function Signature: string ReqDate(datetime reqtime, int d, int h, int m, int s)

The function takes five parameters:

  • reqtime: The datetime value to be converted.
  • d: Day component to be used.
  • h: Hour component to be used.
  • m: Minute component to be used.
  • s: Second component to be used.

It returns a string representing the formatted date and time.

2. Variable Initialization:

  • MqlDateTime mdt;
  • datetime t = TimeToStruct(reqtime, mdt);

Declares an MqlDateTime structure mdt to hold the components of the datetime.

Converts reqtime into a structured datetime format using TimeToStruct and stores it in mdt.

3. Assign Date and Time Components:

  • x_year = mdt.year;
  • x_mon = mdt.mon;
  • x_day = d;
  • x_hour = h;
  • x_min = m;
  • x_sec = s;

Assigns the year and month from mdt to global variables x_year and x_mon.

Assigns the day, hour, minute, and second from the parameters d, h, m, and s to global variables x_day, x_hour, x_min, and x_sec.

4. Format String:

string mdr = string(x_year) + "." + string(x_mon) + "." + string(x_day) + " ~ " + timehr(x_hour, x_min) + ":" + string(x_sec);

Formats the date and time into a string mdr in the format "YYYY.MM.DD ~ HH:MM:SS".

Uses the timehr function to format the hour and minute components.

5. Return Statement: return(mdr);

The function returns the formatted string mdr.

This function is useful for generating a custom string representation of a datetime value, which can be displayed on the chart or used in logs.

ReqTime Function.

1. Purpose: The ReqTime function extracts a specific component of a given datetime value and returns it based on the requested mode.

2. Code Breakdown:


int ReqTime(datetime reqtime,
            const int reqmode) 
  {
    MqlDateTime tm;
    TimeToStruct(reqtime,tm);
    int valtm=0;
    //--
    switch(reqmode)
      {
        case 0: valtm=tm.year; break;        // Return Year 
        case 1: valtm=tm.mon;  break;        // Return Month 
        case 2: valtm=tm.day;  break;        // Return Day 
        case 3: valtm=tm.hour; break;        // Return Hour 
        case 4: valtm=tm.min;  break;        // Return Minutes 
        case 5: valtm=tm.sec;  break;        // Return Seconds 
        case 6: valtm=tm.day_of_week; break; // Return Day of week (0-Sunday, 1-Monday, ... ,6-Saturday) 
        case 7: valtm=tm.day_of_year; break; // Return Day number of the year (January 1st is assigned the number value of zero) 
      }
    //--
    return(valtm);
//---
  } //-end ReqTime()
//---------//

3. Explanation:

1. Function Signature: int ReqTime(datetime reqtime, const int reqmode)

The function takes two parameters:

  • reqtime: The datetime value from which to extract the component.
  • reqmode: An integer indicating which component of the datetime to return.

The function returns an integer value representing the requested component of the datetime.

2. Convert datetime to MqlDateTime:

  • MqlDateTime tm;
  • TimeToStruct(reqtime, tm);

Declares a MqlDateTime structure tm.

Converts the reqtime datetime value into the structured tm format using TimeToStruct.

3. Initialize Return Variable: int valtm = 0;

Initializes an integer variable valtm to store the value of the requested datetime component.

4. Switch Statement:


switch(reqmode)
{
  case 0: valtm = tm.year; break;        // Return Year 
  case 1: valtm = tm.mon;  break;        // Return Month 
  case 2: valtm = tm.day;  break;        // Return Day 
  case 3: valtm = tm.hour; break;        // Return Hour 
  case 4: valtm = tm.min;  break;        // Return Minutes 
  case 5: valtm = tm.sec;  break;        // Return Seconds 
  case 6: valtm = tm.day_of_week; break; // Return Day of week (0-Sunday, 1-Monday, ... ,6-Saturday) 
  case 7: valtm = tm.day_of_year; break; // Return Day number of the year (January 1st is assigned the number value of zero) 
}

The switch statement evaluates reqmode to determine which component of the datetime to return.

Each case in the switch statement corresponds to a specific component of the datetime structure:

  • 0 returns the year.
  • 1 returns the month.
  • 2 returns the day.
  • 3 returns the hour.
  • 4 returns the minutes.
  • 5 returns the seconds.
  • 6 returns the day of the week.
  • 7 returns the day number of the year.

5. Return Statement: return(valtm);

The function returns the value of valtm, which contains the requested component of the datetime.

This ReqTime function is useful for extracting specific components of a datetime value, allowing for flexible handling of date and time data.

TF2Str Function.

1.Purpose: The TF2Str function converts a given period code (representing a timeframe) into a string representation.

2. Code Breakdown:


string TF2Str(int period)
  {
   switch(period)
     {
       //--
       case PERIOD_M1:   return("M1");
       case PERIOD_M2:   return("M2");
       case PERIOD_M3:   return("M3");
       case PERIOD_M4:   return("M4");
       case PERIOD_M5:   return("M5");
       case PERIOD_M6:   return("M6");
       case PERIOD_M10:  return("M10");
       case PERIOD_M12:  return("M12");
       case PERIOD_M15:  return("M15");
       case PERIOD_M20:  return("M20");
       case PERIOD_M30:  return("M30");
       case PERIOD_H1:   return("H1");
       case PERIOD_H2:   return("H2");
       case PERIOD_H3:   return("H3");
       case PERIOD_H4:   return("H4");
       case PERIOD_H6:   return("H6");
       case PERIOD_H8:   return("H8");
       case PERIOD_H12:  return("H12");
       case PERIOD_D1:   return("D1");
       case PERIOD_W1:   return("W1");
       case PERIOD_MN1:  return("MN1");
       //--
     }
   return(string(period));
  }

3. Explanation:

1. Function Signature: string TF2Str(int period)

The function takes a single integer parameter period and returns a string representation of the timeframe.

2. Switch Statement: switch(period)

The switch statement evaluates the period variable to determine which timeframe it represents.

Case Statements:

  • case PERIOD_M1: return("M1");
  • case PERIOD_M2: return("M2");
  • case PERIOD_M3: return("M3");
  • case PERIOD_M4: return("M4");
  • case PERIOD_M5: return("M5");
  • case PERIOD_M6: return("M6");
  • case PERIOD_M10: return("M10");
  • case PERIOD_M12: return("M12");
  • case PERIOD_M15: return("M15");
  • case PERIOD_M20: return("M20");
  • case PERIOD_M30: return("M30");
  • case PERIOD_H1: return("H1");
  • case PERIOD_H2: return("H2");
  • case PERIOD_H3: return("H3");
  • case PERIOD_H4: return("H4");
  • case PERIOD_H6: return("H6");
  • case PERIOD_H8: return("H8");
  • case PERIOD_H12: return("H12");
  • case PERIOD_D1: return("D1");
  • case PERIOD_W1: return("W1");
  • case PERIOD_MN1: return("MN1");

Each case corresponds to a specific period constant (e.g., PERIOD_M1, PERIOD_H1, etc.) and returns the corresponding string representation (e.g., "M1", "H1").

Default Case: return(string(period));

If the period does not match any of the specified cases, the function converts the period integer to a string and returns it.

This TF2Str function is useful for converting timeframe constants into readable string representations, which can be displayed on the chart or used in logs.

Do_Alerts Function.

1. Purpose: The Do_Alerts function generates and sends alerts in various formats (print message, alert box, email, and notification) based on the user settings.

2. Code Breakdown:


void Do_Alerts(string msgText, datetime Altime)
  {
    //---
    // Print message in the terminal
    Print(_pname + " --- " + Symbol() + ": " + msgText +
          "\n --- at: ", TimeToString(Altime, TIME_DATE | TIME_MINUTES | TIME_SECONDS));
    //--
    if(alerts == Yes)
      {
        Alert(_pname, " --- " + Symbol() + ": " + msgText +
              " --- at: ", TimeToString(Altime, TIME_DATE | TIME_MINUTES | TIME_SECONDS));
      }
    //--
    if(UseEmailAlert == Yes) 
      SendMail(_pname, " --- " + Symbol() + " " + TF2Str(Period()) + ": " + msgText +
                       "\n--- at: " + TimeToString(Altime, TIME_DATE | TIME_MINUTES | TIME_SECONDS));
    //--
    if(UseSendnotify == Yes) 
      SendNotification(_pname + "--- " + Symbol() + " " + TF2Str(Period()) + ": " + msgText +
                      "\n --- at: " + TimeToString(Altime, TIME_DATE | TIME_MINUTES | TIME_SECONDS));
    //--
    return;
    //---
  } //-end Do_Alerts()
//---------//

3. Explanation:

1. Function Signature: void Do_Alerts(string msgText, datetime Altime)

The function takes two parameters:

  • msgText: A string containing the alert message text.
  • Altime: A datetime value indicating the alert time.

2. Print Alert in Terminal:

  • Print(_pname + " --- " + Symbol() + ": " + msgText + "\n --- at: ", TimeToString(Altime, TIME_DATE | TIME_MINUTES | TIME_SECONDS));

Prints the alert message to the terminal, including the program name (_pname), symbol, message text, and formatted alert time.

Alert Box:


if(alerts == Yes)
  {
    Alert(_pname, " --- " + Symbol() + ": " + msgText +
          " --- at: ", TimeToString(Altime, TIME_DATE | TIME_MINUTES | TIME_SECONDS));
  }

If the alerts setting is enabled (Yes), displays an alert box with the program name, symbol, message text, and formatted alert time.

Email Alert:


if(UseEmailAlert == Yes) 
  SendMail(_pname, " --- " + Symbol() + " " + TF2Str(Period()) + ": " + msgText +
                   "\n--- at: " + TimeToString(Altime, TIME_DATE | TIME_MINUTES | TIME_SECONDS));

If the UseEmailAlert setting is enabled (Yes), sends an email with the program name, symbol, timeframe, message text, and formatted alert time.

Notification Alert:


if(UseSendnotify == Yes) 
  SendNotification(_pname + "--- " + Symbol() + " " + TF2Str(Period()) + ": " + msgText +
                  "\n --- at: " + TimeToString(Altime, TIME_DATE | TIME_MINUTES | TIME_SECONDS));

If the UseSendnotify setting is enabled (Yes), sends a notification with the program name, symbol, timeframe, message text, and formatted alert time.

3. Return Statement: return;

The function returns void, indicating it does not return any value. The return statement is used to exit the function.

This Do_Alerts function provides a comprehensive alerting mechanism, ensuring that users are notified in multiple ways based on their preferences.

CreateChartText Function.

Let's break down the CreateChartText function and explain its components in detail:

1. Purpose: The CreateChartText function creates and manages a text label on the chart with specific properties, including text content, font style, size, color, and position.

2. Code Breakdown:


void CreateChartText(long   chart_id, 
                     string lable_name, 
                     string label_text,
                     string font_model,
                     int    font_size,
                     color  label_color,
                     int    chart_corner,
                     int    x_cor, 
                     int    y_cor) 
  { 
//--- 
   if(ObjectFind(chart_id,lable_name)<0)
     {
       if(ObjectCreate(chart_id,lable_name,OBJ_LABEL,0,0,0,0,0)) 
         { 
           ObjectSetString(chart_id,lable_name,OBJPROP_TEXT,label_text);
           ObjectSetString(chart_id,lable_name,OBJPROP_FONT,font_model); 
           ObjectSetInteger(chart_id,lable_name,OBJPROP_FONTSIZE,font_size);
           ObjectSetInteger(chart_id,lable_name,OBJPROP_COLOR,label_color);
           ObjectSetInteger(chart_id,lable_name,OBJPROP_CORNER,chart_corner);
           ObjectSetInteger(chart_id,lable_name,OBJPROP_XDISTANCE,x_cor);
           ObjectSetInteger(chart_id,lable_name,OBJPROP_YDISTANCE,y_cor);
         } 
       else 
          {Print("Failed to create the object OBJ_LABEL ",lable_name,", Error code = ", GetLastError());}
     }
   else
     {
       ObjectSetString(chart_id,lable_name,OBJPROP_TEXT,label_text);
       ObjectSetString(chart_id,lable_name,OBJPROP_FONT,font_model); 
       ObjectSetInteger(chart_id,lable_name,OBJPROP_FONTSIZE,font_size);
       ObjectSetInteger(chart_id,lable_name,OBJPROP_COLOR,label_color);
       ObjectSetInteger(chart_id,lable_name,OBJPROP_CORNER,chart_corner);
       ObjectSetInteger(chart_id,lable_name,OBJPROP_XDISTANCE,x_cor);
       ObjectSetInteger(chart_id,lable_name,OBJPROP_YDISTANCE,y_cor);
     }
//---
  }
//---------//

3. Explanation:

1. Function Signature:


void CreateChartText(long chart_id, 
                     string lable_name, 
                     string label_text,
                     string font_model,
                     int font_size,
                     color label_color,
                     int chart_corner,
                     int x_cor, 
                     int y_cor)

The function takes several parameters:

  • chart_id: The ID of the chart where the label will be created.
  • lable_name: The name of the label object.
  • label_text: The text content of the label.
  • font_model: The font style for the label text.
  • font_size: The font size for the label text.
  • label_color: The color of the label text.
  • chart_corner: The corner of the chart where the label will be positioned.
  • x_cor: The horizontal distance from the specified corner.
  • y_cor: The vertical distance from the specified corner.

2. Check if Label Exists:


if(ObjectFind(chart_id, lable_name) < 0)

Checks if the label object already exists on the chart.

If it does not exist (< 0), it proceeds to create a new label.

3. Create New Label:


if(ObjectCreate(chart_id, lable_name, OBJ_LABEL, 0, 0, 0, 0, 0))

Attempts to create a new label object with the specified parameters.

If the creation is successful, it sets various properties for the label:

  • ObjectSetString(chart_id, lable_name, OBJPROP_TEXT, label_text);
  • ObjectSetString(chart_id, lable_name, OBJPROP_FONT, font_model);
  • ObjectSetInteger(chart_id, lable_name, OBJPROP_FONTSIZE, font_size);
  • ObjectSetInteger(chart_id, lable_name, OBJPROP_COLOR, label_color);
  • ObjectSetInteger(chart_id, lable_name, OBJPROP_CORNER, chart_corner);
  • ObjectSetInteger(chart_id, lable_name, OBJPROP_XDISTANCE, x_cor);
  • ObjectSetInteger(chart_id, lable_name, OBJPROP_YDISTANCE, y_cor);

4. Error Handling:


else 
{
  Print("Failed to create the object OBJ_LABEL ", lable_name, ", Error code = ", GetLastError());
}

If the label creation fails, it prints an error message with the error code.

5. Update Existing Label:


else
{
  ObjectSetString(chart_id, lable_name, OBJPROP_TEXT, label_text);
  ObjectSetString(chart_id, lable_name, OBJPROP_FONT, font_model); 
  ObjectSetInteger(chart_id, lable_name, OBJPROP_FONTSIZE, font_size);
  ObjectSetInteger(chart_id, lable_name, OBJPROP_COLOR, label_color);
  ObjectSetInteger(chart_id, lable_name, OBJPROP_CORNER, chart_corner);
  ObjectSetInteger(chart_id, lable_name, OBJPROP_XDISTANCE, x_cor);
  ObjectSetInteger(chart_id, lable_name, OBJPROP_YDISTANCE, y_cor);
}

If the label already exists, it updates the properties of the existing label with the new values.

This CreateChartText function allows you to dynamically create and manage text labels on the chart, ensuring that the labels are created if they do not exist or updated if they already exist.

TimeBarCloseCheck Indicator Alerts.

Overview: The TimeBarCloseCheck indicator is designed to assist traders by providing real-time alerts when a bar (or candlestick) closes on the MetaTrader 5 platform. This feature is crucial for traders who rely on precise timing to make informed trading decisions.

Key Features:

Immediate Notifications: The indicator generates instant alerts as soon as a bar closes. This ensures that traders are always aware of the exact moment a bar closes, allowing them to respond swiftly to market changes.

Multiple Alert Options: Traders can choose from various alert types, including pop-up alerts, email notifications, and push notifications to their mobile devices. This flexibility ensures that traders never miss an important alert, regardless of where they are.

Customizable Settings: The alert settings are highly customizable, enabling traders to set up alerts according to their specific trading strategies and preferences. Whether it's adjusting the timeframe or selecting the type of alert, traders have full control.

Enhanced Decision Making: By providing timely and accurate alerts, the TimeBarCloseCheck indicator helps traders make better decisions. Knowing the precise time and price at which a bar closes can significantly improve the timing of trade entries and exits.

User-Friendly Interface: The alerts are displayed in an easy-to-read format, complete with the symbol, timeframe, and closing price. This ensures that traders can quickly understand the alert without any confusion.

Considerations:

Despite the robust features, traders should be aware of the potential delays caused by varying internet speeds and broker server delays. These factors can impact the timing accuracy of alert.

1. Internet Speed:Different traders have varying internet speeds, which can affect how quickly they receive alerts. Slower internet speeds may result in a slight delay in receiving the alert.

2. Broker Server Delay: The delay from the broker’s server when sending data to MT5 can also impact alert timing. If an alert is supposed to trigger one second before the new bar opens, and there is a server delay, the alert might not trigger at the exact time. Instead, it might trigger slightly late, or in some cases, it may miss the timing entirely because the new bar has already opened by the time the delay is resolved.

Example Alert:

Alert: TimeBarCloseCheck --- GBPJPY: Bar Close time triggered in Timeframe: M1 @Price: 192.311 --- at: 2024.11.26 20:09:59

In this example, the alert informs the trader that the GBPJPY bar on the M1 timeframe has closed at a price of 192.311. The exact time of the bar close is also provided, allowing the trader to take immediate action if necessary.

Conclusion:

The TimeBarCloseCheck indicator is an essential tool for traders who value precision and timely information. By leveraging its powerful alert features and being mindful of potential delays due to internet speed and broker server latency, traders can stay ahead of the market and make more informed trading decisions.

That's all for the article How to detect Bar Close Time in MT5 and MT4 programs, hopefully it's useful.

Thank you for reading.

Please download the Expert Advisor: TimeBarCloseCheck

If you are subscribed to my YouTube Channel, and would like to receive the source program of this article, please send a request via the Contact Us form page, and I will send it to your email, source code: TimeBarCloseCheck Expert Advisor.

Don't forget to stop by and subscribe to Forex Home Experts YouTube Channel:

YouTube Channel: @ForexHomeExperts

YouTube Playlist: @ForexHomeExperts YouTube Playlist

Featured Post

How to create a simple Multi-Currency Expert Advisor using MQL5 with Zigzag and RSI Indicators Signal

Introduction The Expert Advisor discussed in this article is a multi-currency trading robot that uses the Zigzag and RSI indicators. It fol...