Showing posts with label Expert Advisor Alerts. Show all posts
Showing posts with label Expert Advisor Alerts. Show all posts

Monday, November 25, 2024

Before we start discussing how to create a program to detect whether a new bar has appeared or not on MT5 and MT4, it's a good idea to know the benefits of detecting new bars.

How to detect new bars on Expert Advisors in MT4 and MT5

Detecting new bars in MT4 or MT5 has several important benefits for traders, especially in increasing the efficiency and effectiveness of their trading strategies and the use of automated trading like expert advisor.. Here are some of the main benefits:

  • 1. Faster Decision-Making: Detecting new bars helps you get instant updates on price changes, allowing you to make quick decisions based on the latest data.
  • 2. Less Data Clutter: By focusing on new bars, you avoid unnecessary data and concentrate on the most important information for your strategy.
  • 3. Increased Efficiency: You don't need to manually check charts all the time. This frees you up to focus on deeper analysis or other activities.
  • 4. Automation: Integrate new bar detection with automation tools for sending messages or placing orders automatically when certain conditions are met.
  • 5. Better Monitoring: Keep a closer eye on market trends and detect trend changes faster by watching for new bars.
  • 6. Reduced Stress: You don't have to constantly monitor charts, which helps reduce stress and improves your concentration.
  • 7. Improved Trading Strategies: With quicker and more accurate information, you can develop and optimize your trading strategies more effectively.

Overall, detecting new bars in MT4 or MT5 helps traders be more efficient, make better decisions, and manage their trading activities more effectively. It can be clearly said that detecting new bars is very important in using automatic trading or expert advisors.

Example of a simple program in MQL5


//+------------------------------------------------------------------+
//|                                                   TestNewBar.mq5 |
//|        Copyright 2024, Roberto Jacobs (3rjfx) ~ Date: 2024-11-24 |
//|                              https://www.mql5.com/en/users/3rjfx |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, Roberto Jacobs (3rjfx) ~ Date: 2024-11-24"
#property link      "https://www.mql5.com/en/users/3rjfx"
#property version   "1.00"
#property strict
//--
//+------------------------------------------------------------------+
//|                             Include                              |
//+------------------------------------------------------------------+
#include <trade rade.mqh="">
#include <trade ositioninfo.mqh="">
#include <trade ymbolinfo.mqh="">
#include <trade ccountinfo.mqh="">
//--
CTrade              mc_trade;
CSymbolInfo         mc_symbol;
CPositionInfo       mc_position; 
CAccountInfo        mc_account;
//---
//--
input ENUM_TIMEFRAMES  Timeframe = PERIOD_H1;     // Select Expert TimeFrame, default PERIOD_H1

//--
datetime         
   PrevbarBuy,
   TimebarBuy,
   PrevbarSell,
   TimebarSell;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
     // Initialization code here
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   Comment("");
   PrintFormat("%s: Deinitialization reason code=%d",__FUNCTION__,reason);
   //--
   return;
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
     //- For Open Order Buy
     if(IFNewBarsB()) { OpenBuy(); PrevbarBuy=TimebarBuy; }
     //--
     //- For Open Order Sell
     if(IFNewBarsB()) { OpenSell(); PrevbarSell=TimebarSell; }
    //--
    return;
//---
  }
//+------------------------------------------------------------------+

bool IFNewBarsB(void) // New bar check buy order
  {
//---
    bool Nb=false;
    //--
    TimebarBuy=iTime(Symbol(),Timeframe,0);
    if(TimebarBuy!=PrevbarBuy) Nb=true;
    //--
    return(Nb);
//---
  } //-end IFNewBarsB()
//---------//

bool IFNewBarsS(void) // New bar check sell order
  {
//---
    bool Nb=false;
    //--
    TimebarSell=iTime(Symbol(),Timeframe,0);
    if(TimebarSell!=PrevbarSell) Nb=true;
    //--
    return(Nb);
//---
  } //-end IFNewBarsS()
//---------//

bool OpenBuy(void) 
  {
//---
    ResetLastError();
    //--
    bool buyopen      = false;
    //--
    MqlTradeRequest req={};
    MqlTradeResult  res={};
    MqlTradeCheckResult check={};
    //-- structure is set to zero
    ZeroMemory(req);
    ZeroMemory(res);
    ZeroMemory(check);
    //--
    double Lot=0.01;
    double SL=0.0;
    double TP=0.0;
    //--
    buyopen=mc_trade.Buy(Lot,Symbol(),mc_symbol.Ask(),SL,TP,"Your Comment");
    //--
    int error=GetLastError();
    if(buyopen||error==0)
      {
        string bsopen="Open BUY Order for "+Symbol()+" ~ Ticket= ["+(string)mc_trade.ResultOrder()+"] successfully..!";
        PrevbarBuy=iTime(Symbol(),Timeframe,0);
      }
    else
      {
        mc_trade.CheckResult(check);
        return(false);   
      }
    //--
    return(buyopen);
    //--
//---
  } //-end OpenBuy
//---------//

bool OpenSell(void) 
  {
//---
    ResetLastError();
    //--
    bool selopen      = false;
    //--
    MqlTradeRequest req={};
    MqlTradeResult  res={};
    MqlTradeCheckResult check={};
    //-- structure is set to zero
    ZeroMemory(req);
    ZeroMemory(res);
    ZeroMemory(check);
    //--
    double Lot=0.0;
    double SL=0.0;
    double TP=0.0;
    //--
    selopen=mc_trade.Sell(Lot,Symbol(),mc_symbol.Bid(),SL,TP,"Your Comment");
    //--
    int error=GetLastError();
    if(selopen||error==0)
      {
        string bsopen="Open SELL Order for "+Symbol()+" ~ Ticket= ["+(string)mc_trade.ResultOrder()+"] successfully..!";
        PrevbarSell=iTime(Symbol(),Timeframe,0);
      }
    else
      {
        mc_trade.CheckResult(check);
        return(false);   
      }
    //--
    return(selopen);
    //--
//---
  } //-end OpenSell
//---------//

Includes and Declarations.


#include <trade rade.mqh="">
#include <trade ositioninfo.mqh="">
#include <trade ymbolinfo.mqh="">
#include <trade ccountinfo.mqh="">

CTrade              mc_trade;
CSymbolInfo         mc_symbol;
CPositionInfo       mc_position; 
CAccountInfo        mc_account;

input ENUM_TIMEFRAMES  Timeframe = PERIOD_H1;     // Select Expert TimeFrame, default PERIOD_H1

datetime         
   PrevbarBuy,
   TimebarBuy,
   PrevbarSell,
   TimebarSell;
  • Includes: Importing trade, position, symbol, and account information classes.
  • Declarations: Creating instances of trade, symbol, position, and account classes. Defining the input parameter for selecting the timeframe and datetime variables for buy and sell bars.

int OnInit()
{
   // Initialization code here
   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
{
   Comment("");
   PrintFormat("%s: Deinitialization reason code=%d",__FUNCTION__,reason);
   return;
}
  • OnInit: Runs once when the expert advisor is initialized. It returns INIT_SUCCEEDED to indicate successful initialization.
  • OnDeinit: Runs once when the expert advisor is removed or the terminal is shut down. It clears any comments and prints the deinitialization reason.

void OnTick()
{
   // For Open Order Buy
   if(IFNewBarsB()) { OpenBuy(); PrevbarBuy = TimebarBuy; }
   
   // For Open Order Sell
   if(IFNewBarsB()) { OpenSell(); PrevbarSell = TimebarSell; }
   
   return;
}
  • OnTick: Runs on every tick (price update). It checks for new buy and sell bars and opens orders accordingly.

bool IFNewBarsB(void) // New bar check buy order
  {
//---
    bool Nb=false;
    //--
    TimebarBuy=iTime(Symbol(),Timeframe,0);
    if(TimebarBuy!=PrevbarBuy) Nb=true;
    //--
    return(Nb);
//---
  } //-end IFNewBarsB()
//---------//

bool IFNewBarsS(void) // New bar check sell order
  {
//---
    bool Nb=false;
    //--
    TimebarSell=iTime(Symbol(),Timeframe,0);
    if(TimebarSell!=PrevbarSell) Nb=true;
    //--
    return(Nb);
//---
  } //-end IFNewBarsS()
//---------//
  • IFNewBarsB and IFNewBarsS: Check if a new buy or sell bar has appeared by comparing the current bar time with the previous bar time. If they are different, a new bar is detected, and the function returns true.

bool OpenBuy(void) 
  {
//---
    ResetLastError();
    //--
    bool buyopen      = false;
    //--
    MqlTradeRequest req={};
    MqlTradeResult  res={};
    MqlTradeCheckResult check={};
    //-- structure is set to zero
    ZeroMemory(req);
    ZeroMemory(res);
    ZeroMemory(check);
    //--
    double Lot=0.01;
    double SL=0.0;
    double TP=0.0;
    //--
    buyopen=mc_trade.Buy(Lot,Symbol(),mc_symbol.Ask(),SL,TP,"Your Comment");
    //--
    int error=GetLastError();
    if(buyopen||error==0)
      {
        string bsopen="Open BUY Order for "+Symbol()+" ~ Ticket= ["+(string)mc_trade.ResultOrder()+"] successfully..!";
        PrevbarBuy=iTime(Symbol(),Timeframe,0);
      }
    else
      {
        mc_trade.CheckResult(check);
        return(false);   
      }
    //--
    return(buyopen);
    //--
//---
  } //-end OpenBuy
//---------//

bool OpenSell(void) 
  {
//---
    ResetLastError();
    //--
    bool selopen      = false;
    //--
    MqlTradeRequest req={};
    MqlTradeResult  res={};
    MqlTradeCheckResult check={};
    //-- structure is set to zero
    ZeroMemory(req);
    ZeroMemory(res);
    ZeroMemory(check);
    //--
    double Lot=0.0;
    double SL=0.0;
    double TP=0.0;
    //--
    selopen=mc_trade.Sell(Lot,Symbol(),mc_symbol.Bid(),SL,TP,"Your Comment");
    //--
    int error=GetLastError();
    if(selopen||error==0)
      {
        string bsopen="Open SELL Order for "+Symbol()+" ~ Ticket= ["+(string)mc_trade.ResultOrder()+"] successfully..!";
        PrevbarSell=iTime(Symbol(),Timeframe,0);
      }
    else
      {
        mc_trade.CheckResult(check);
        return(false);   
      }
    //--
    return(selopen);
    //--
//---
  } //-end OpenSell
//---------//
  • OpenBuy and OpenSell: These functions handle opening buy and sell orders. They use the CTrade class to place orders with specified lot sizes, stop loss, and take profit levels. If an order is successfully placed, the functions return true; otherwise, they return false.

Summary:

The improved script detects new bars on the selected timeframe and opens buy or sell orders accordingly. It includes functions to check for new bars and open orders while utilizing the powerful MQL5 trading library.

Many programmers create new bar detection functions with less than ideal considerations. They often rely on the logic: "If the opening time of the current bar is not the same as the previous bar time, then the 'New Bar' condition becomes 'TRUE'. Subsequently, the previous bar time is immediately updated to match the current bar time."

Limitations of the Conventional Logic.

This approach, while straightforward, has significant drawbacks:

  • Transient Condition: The EA (Expert Advisor) will only register the 'New Bar' condition as 'TRUE' at the exact moment the new bar opens. A few seconds later, upon rechecking, the 'New Bar' condition will revert to 'FALSE'.
  • Indicator Signals: This logic fails when EAs rely on indicators to generate signals. Indicators might not produce a signal precisely at the new bar's opening. Consequently, if the new bar condition quickly turns 'FALSE', the EA might miss potential trading opportunities.

Enhanced Algorithm Logic.

To address these issues, I propose a more robust algorithm:

  • 1. New Bar Detection: Check if the new bar condition is 'TRUE'.
  • 2. Order Function Check: Ensure that the open order function (OpenBuy() or OpenSell()) also returns 'TRUE'.
  • 3. Update Time Variables: Only if both checks are 'TRUE', update the previous bar time variable (PrevbarBuy for Buy orders or PrevbarSell for Sell orders) to match the current bar time variable (TimebarBuy or TimebarSell).

This approach guarantees that the previous bar time is updated only after a successful order placement. Thus, when the EA rechecks for a new bar, the function returns 'FALSE', preventing multiple orders from being placed within the same bar.

Handling Reversed Indicator Signals.

In my example program, I use separate time variables for Buy and Sell conditions:

  • Buy Orders: Utilize PrevbarBuy and TimebarBuy.
  • Sell Orders: Utilize PrevbarSell and TimebarSell.

This separation accounts for scenarios where indicator signals might reverse within the same bar. If both signals share a single time check variable, the EA could miss opportunities to open opposite orders due to the 'New Bar' condition being 'FALSE'.

Conclusion.

By refining the new bar detection logic, we can enhance the reliability of EAs, ensuring they act upon indicator signals accurately and timely. This approach leads to more precise trading actions and potentially better trading outcomes.

This article ends here, hopefully it can help and be useful for fellow traders.

Notes:

This code provides a basic framework for new bar detection in an EA. However, for a robust and reliable trading strategy, it needs further development to incorporate additional factors such as price movements, indicators, and risk management techniques.

Please download the Expert Advisor: TestNewBar

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

YouTube Channel: @ForexHomeExperts

YouTube Playlist: @ForexHomeExperts YouTube Playlist

Sunday, November 24, 2024

In this article I will discuss how to add alerts to indicator programs or Expert Advisors using MQL5.

The alerts that will be discussed include sound and pop-up alerts on MT5 or MT4, notification alerts and email alerts.

But before discussing the creation of the program, we need to know what the benefits of alerts in indicator or expert advisor programs actually are?

the benefits of alerts in indicator or expert advisor programs

What are the benefits of alerts in indicator or expert advisor programs in MT4 or MT5?

Alerts in MT4 and MT5 indicators and expert advisors (EAs) are invaluable tools for traders. They provide timely notifications about specific market conditions, allowing traders to react quickly and make informed decisions.

Here are the key benefits of using alerts:

1.Timely Notifications:

  • Real-time alerts: Receive immediate notifications when a specific condition is met, such as a price crossing a moving average or a support/resistance level being breached.
  • No Constant Monitoring: You don't have to constantly stare at charts to catch these opportunities. Alerts can notify you even when you're away from your computer.

2. Improved Decision-Making:

  • Quick Reaction: Alerts allow you to react promptly to market changes, potentially leading to better entry and exit points.
  • Reduced Emotional Trading: By automating notifications, you can avoid impulsive decisions based on fear or greed.

3. Enhanced Risk Management:

  • Stop-Loss and Take-Profit Alerts: Set up alerts to trigger when your positions reach predefined profit or loss levels.
  • Risk Management Strategies: Automate risk management strategies, such as trailing stop-loss orders, to protect your profits.

4. Increased Efficiency:

  • Automation: Automate repetitive tasks like monitoring indicators and placing orders.
  • Focus on Other Tasks: Spend more time on other aspects of your trading strategy, such as fundamental analysis or portfolio management.

5. Scalping and Day Trading:

  • Quick Entry and Exit: Alerts can help you capitalize on short-term price movements and scalping opportunities.

Remember:

While alerts can be a powerful tool, it's important to use them wisely. Overreliance on alerts can lead to impulsive decisions and potential losses. Always combine alerts with sound risk management practices and thorough analysis.

In this article I will demonstrate the implementation of alerts using the modified MACD indicator by adding alerts.

First of all, I will create a template that is usually used to add alerts to indicators or expert advisors in MQL5.

Template program alerts:


//+------------------------------------------------------------------+
//|                                                  MACD_Alerts.mq5 |
//|                             Copyright 2000-2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com ||
//|                              https://www.mql5.com/en/users/3rjfx |
//+------------------------------------------------------------------+
#property copyright   "Copyright 2000-2024, MetaQuotes Ltd."
#property link        "https://www.mql5.com"
#property link        "https://www.mql5.com/en/users/3rjfx"
#property description "Moving Average Convergence/Divergence"
#property version     "1.00"
#property description "Modify by: Roberto Jacobs (3rjfx) ~ Date: 2024-11-24"

#property indicator_separate_window
//---


//-- Enumeration
enum YN
 {
   No,  
   Yes
 };
//---
//--- 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)

//---Variables used in alerts
double MACDAlert[];
string AlertTxt;
string _name;
int curAlert;
int prvAlert;
//--
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   
   
   //--
   _name="Your Indicator Name";
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| 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[])
  {
//---
   
   
   
   //--
   double priceB=0.0;
   double priceS=0.0;
   datetime dtB=0;
   datetime dtS=0;
   //--
   if(alerts==Yes||UseEmailAlert==Yes||UseSendnotify==Yes)
     {
       if(curAlert==1 && curAlert!=prvAlert)
         {
           AlertTxt="Your Alerts Text here";
           Do_Alerts(AlertTxt,dtB);
           prvAlert=curAlert;
         }
       if(curAlert==-1 && curAlert!=prvAlert)
         {
           AlertTxt="Your Alerts Text here";
           Do_Alerts(AlertTxt,dtS);
           prvAlert=curAlert;
         }
     }
   //--
   
   
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+

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("MN");
       //--
     }
   return(string(period));
  }  
//---------//

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

Enumeration.

An enum (short for "enumeration") is a distinct type that consists of a set of named values called elements or members. Enums are used to represent a collection of related constants in a more readable and maintainable way.

Enums are particularly useful for representing a series of constants or actions that are related in a fixed manner, and this will make our code more readable and less error-prone.

The YN enum we've defined contains two possible values: No and Yes.

Breakdown:

  • enum YN: This defines a new enumeration type named YN.
  • { No, Yes }: These are the members of the enum, representing two possible states or values: No and Yes.

Then we use that enumeration in the indicator input properties.


//--- 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)

In order not to disturb the MACD buffer calculation, we add a buffer variable named MACDAlert. In this MACDAlert buffer we will copy all values from the MACD buffer.

Then below are some variables that will be used in the alerts that we must place on the global scope of the indicator or expert advisor.

  • string AlertTxt: For the alert text to be created.
  • string _name: Name of the indicator or program that will provide the alert.
  • int curAlert: Current alert value, with a value of 1 for an Up or Buy Alert and minus 1 for a Down or Sell Alert.
  • int prvAlert: This variable is to hold the current alert value, to prevent the alert from repeating without interruption.

Explanation

Variables Initialization:


datetime dtB=0;
datetime dtS=0;
double priceB=0.0;
double priceS=0.0;

These variables store the date and price when a Moving Average Convergence Divergence (MACD) signal occurs. dtB and dtS store the date for the Buy and Sell signals, respectively. priceB and priceS store the prices at those times.

Array Manipulation:


ArraySetAsSeries(time, true);
ArraySetAsSeries(close, true);
ArrayCopy(MACDAlert, ExtMacdBuffer, 0, 0, WHOLE_ARRAY);
ArraySetAsSeries(MACDAlert, true);

These lines set up the arrays for time, closing prices, and MACD values to be used as series (reverse the array indexing). ArrayCopy copies the ExtMacdBuffer into MACDAlert.

Loop to Detect MACD Crossings:


for (int x = calculated - 2; x >= 0; x--)
{
    if (MACDAlert[x+1] <= 0.0 && MACDAlert[x] > 0.0)
    {
        curAlert = 1;
        dtB = time[x];
        priceB = close[x];
    }
    if (MACDAlert[x+1] >= 0.0 && MACDAlert[x] < 0.0)
    {
        curAlert = -1;
        dtS = time[x];
        priceS = close[x];
    }
}

This loop iterates over the MACDAlert array to detect crossings of the MACD line over the zero line.

  • If the MACD value crosses from negative to positive (MACDAlert[x+1] <= 0.0 && MACDAlert[x] > 0.0), a buy signal is generated, and the current time and price are recorded.
  • If the MACD value crosses from positive to negative (MACDAlert[x+1] >= 0.0 && MACDAlert[x] < 0.0), a sell signal is generated, and the current time and price are recorded.

Alerts:


if (alerts == Yes || UseEmailAlert == Yes || UseSendnotify == Yes)
{
    if (curAlert == 1 && curAlert != prvAlert)
    {
        AlertTxt = "MACD cross from below to above zero : " + DoubleToString(priceB, Digits()) + " @ bar shift: " + (string)iBarShift(Symbol(), 0, dtB, false);
        Do_Alerts(AlertTxt, dtB);
        prvAlert = curAlert;
    }
    if (curAlert == -1 && curAlert != prvAlert)
    {
        AlertTxt = "MACD cross from above to below zero : " + DoubleToString(priceS, Digits()) + " @ bar shift: " + (string)iBarShift(Symbol(), 0, dtS, false);
        Do_Alerts(AlertTxt, dtS);
        prvAlert = curAlert;
    }
}

If any alerts are enabled (regular alerts, email alerts, or notifications), the code sends an alert whenever a new MACD crossing signal is detected.

  • If a buy signal is detected (curAlert == 1) and it differs from the previous signal (curAlert != prvAlert), an alert message is constructed and sent.
  • If a sell signal is detected (curAlert == -1) and it differs from the previous signal, a similar alert message is constructed and sent.

Summary:

The code primarily focuses on detecting MACD zero-line crossings and issuing alerts when these crossings occur. This is useful in trading algorithms where MACD crossings can indicate buy or sell signals.


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("MN");
       //--
     }
   return(string(period));
  }  
//---------//

This code defines a function TF2Str that converts a time period constant into a string representation. It uses a switch statement to match different period constants and returns the corresponding string.

Explanation:

  • 1. Function Signature: string TF2Str(int period): The function returns a string and takes an int parameter named period.
  • 2. Switch Statement: The switch statement evaluates the period and returns a corresponding string for each case.
  • 3. Case Statements: case PERIOD_M1: return("M1");: If period equals PERIOD_M1, the function returns the string "M1". This pattern is repeated for each predefined period constant, such as PERIOD_M2, PERIOD_M3, etc.
  • Default Case: If the period does not match any of the predefined cases, the function converts the period integer to a string and returns it. This ensures that the function always returns a valid string.

Use Case: This function is useful in scenarios where you need to convert time period constants (used in trading software or financial applications) to their string representations for display or logging purposes.

Function Alerts:

Function Definition:


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

This function, Do_Alerts, sends different types of alerts (print messages, alerts, emails, notifications) based on MACD signal crosses detected. Here's a detailed breakdown:

  • 1. Print Message: This line prints the alert message along with the time of the alert. The Symbol() function returns the current symbol (currency pair or instrument), and TimeToString converts the datetime to a human-readable string format.
  • 2. Conditional Alerts:
    • Regular Alerts: If alerts are enabled (Yes), it sends an alert message.
    • Email Alerts: If UseEmailAlert is enabled, it sends an email with the alert message. The TF2Str(Period()) function converts the period to a string representation.
    • Push Notifications: If UseSendnotify is enabled, it sends a push notification with the alert message.
  • 3. Return Statement: The function ends here. The return statement ensures the function exits after executing the necessary alert commands.

Summary:

This function is designed to handle various types of alerts based on market conditions or trading signals. It ensures that you are notified through different channels (console print, alert, email, and push notification) whenever an important event occurs in your trading strategy.

The programs and functions in the template that I show above are just examples, they can be applied to both custom indicators and expert advisors with MQL5 and MQL4.

If the function template is applied to MQL4, then you must delete the timeframe periods that do not exist in MQL4, because MQL5 uses 21 timeframes while MQL4 only uses 9 timeframes.

You can adjust and modify the handling according to your needs.

MACD_Alerts indicator test results:

MACD_Alerts indicator test results

That's all for the article How to add Alerts to MT4 and MT5 programs, hopefully it's useful.

Thank you for reading.

Please download the MACD Indicator Alert: MACD Alert

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: MACD_Alerts Indicator.

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...