EA sending multiple emails instead of one

 

Good Day,

I'm trying to create an EA that checks the number of open trades per currency pair then sends an email if the number of open trades is greater than or equal to set number. With the help of ChatGPT I've made some progress but the code sends 100s or 1000s of emails when th condition is meet. What could be causing this? 

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

//|                                        TradesPerCurrencyPairs.mq4 |

//|                        Copyright 2024, MetaQuotes Software Corp. |

//|                                             https://www.mql5.com |

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

#property strict



// Input parameters

input int maxTrades = 5;  // Maximum number of trades allowed per currency pair

input string emailAddress = "your_email@example.com";  // Email address to send notifications

input string currencyPairs = "EURUSD,GBPUSD,USDJPY"; // Comma-separated list of currency pairs to monitor



bool initialEmailSent[]; // Array to track whether initial email has been sent for each currency pair



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

//| Expert initialization function                                   |

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

int OnInit()

  {

   EventSetTimer(60);  // Check every minute

   ArrayResize(initialEmailSent, StringLen(currencyPairs) / 7 + 1); // Resize array to track initial email sent status for each currency pair

   ArrayInitialize(initialEmailSent, false); // Initialize array elements to false

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

   EventKillTimer();  // Stop the timer on deinitialization

  }

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

//| Expert tick function                                            |

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

void OnTick()

  {

   CheckTrades();  // Call the function to check trades

  }

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

//| Check number of trades per specified currency pairs             |

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

void CheckTrades()

  {

   string pairs[]; // Declare an array to store the currency pairs

   ArrayResize(pairs, StringLen(currencyPairs) / 7 + 1); // Assuming each currency pair is 7 characters long (e.g., "EURUSD,")



   int pairIndex = 0; // Index to track the position in the pairs array



   // Extract currency pairs from the input string

   for(int i = 0, len = StringLen(currencyPairs); i < len; i += 7)

   {

      string pair = StringSubstr(currencyPairs, i, 6); // Extract a currency pair

      pairs[pairIndex++] = pair; // Store the currency pair in the array

   }



   for(int i = 0; i < ArraySize(pairs); i++)

     {

      string currency = pairs[i];  // Get the currency pair

      int totalTrades = 0;  // Variable to count total trades for the currency pair



      // Loop through all orders to count trades for the current currency pair

      for(int j = OrdersTotal() - 1; j >= 0; j--)

        {

         if(!OrderSelect(j, SELECT_BY_POS)) continue;  // Select the order



         // Check if the order matches the current currency pair

         if(OrderType() <= OP_SELL && OrderType() >= OP_BUY && OrderSymbol() == currency)

           {

            totalTrades++;  // Increment the total trades

           }

        }



      // If the total trades exceed or equal the set value and initial email has not been sent, send an initial email notification

      if(totalTrades >= maxTrades && !initialEmailSent[i])

        {

         SendNotification(currency, totalTrades);

         initialEmailSent[i] = true; // Update initial email sent status to true

        }

      // If the total trades exceed or equal the set value and initial email has been sent, send a subsequent email notification

      else if (totalTrades >= maxTrades && initialEmailSent[i])

        {

         SendSubsequentNotification(currency, totalTrades);

        }

     }

  }

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

//| Send initial email notification                                 |

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

void SendNotification(string currency, int totalTrades)

  {

   string message = currency + " - Number of trades: " + IntegerToString(totalTrades);

   SendMail(emailAddress, "Initial Trades Per Currency Alert", message);  // Send initial email notification

  }

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

//| Send subsequent email notification                              |

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

void SendSubsequentNotification(string currency, int totalTrades)

  {

   string message = currency + " - Another trade met the condition. Total trades: " + IntegerToString(totalTrades);

   SendMail(emailAddress, "Subsequent Trades Per Currency Alert", message);  // Send subsequent email notification

  }

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


 

You'd want to use the MQL5 event-based system instead of relying solely on timers.

#include <ExpertAdvisorBase.mqh>

input int maxTrades = 5;   // Maximum number of trades allowed per currency pair
input string emailAddress = "your_email@example.com";   // Email address to send notifications
input string currencyPairs = "EURUSD,GBPUSD,USDJPY";  // Comma-separated list of currency pairs to monitor

bool initialEmailSent[];  // Array to track whether initial email has been sent for each currency pair

//+------------------------------------------------------------------+
int OnInit() {
   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason) {}

void OnTick(){}

void EMA_OnEvent ( const EA_EVENTS event, const EA_EVENT_DATA &data ){ 
   if ((event == EA_ONSTART) || (event == EA_ONRESUME)){
      EventSetTimer(60);    // Check every minute
   } else if (event == EA_ONTICK){
       CheckTrades();   // Call the function to check trades
   } 
}
//+------------------------------------------------------------------+
void CheckTrades() {
    string pairs[];  ArrayResize(pairs, StringLen(currencyPairs)/7 + 1);

    int pairIndex = 0;
     for (int i=0, len=StringLen(currencyPairs); i<len ;i+=7){
       string pair = StringSubstr(currencyPairs, i , 6 ); pairs[pairIndex++] = pair; }

      for ( int j = 0 ; j < ArraySize(pairs) ; ++j ) {
          string currency = pairs[j];   // Get the currency pair
          int totalTrades = 0;

          for (int k=OrdersTotal()-1; k>=0; --k){
              if (!OrderSelect(k, SELECT_BY_POS)) continue;  // Select the order
              
              if ((OrderType() <= OP_SELL) && (OrderType() >= OP_BUY) && (OrderSymbol() == currency)) {
                ++totalTrades;} }
          
          if ((totalTrades >= maxTrades) && (!initialEmailSent[j])){
             SendNotification(currency, totalTrades); initialEmailSent[j] = true; }
           
           else  if ((totalTrades>=maxTrades)&& (initialEmailSent[j])) {
              SendSubsequentNotification(currency ,totalTrades );}
       }
     EventKillTimer(); // Stop the timer on deinitialization
}
//+------------------------------------------------------------------+
void SendNotification(string currency, int totalTrades){ 
   string message = currency + " - Number of trades: " + IntegerToString(totalTrades); 
   
   SendEmailAlert("Initial Trades Per Currency Alert",message ); }

//+------------------------------------------------------------------+
void SendSubsequentNotification(string currency, int totalTrades ){ 
    string message = currency +" - Another trade met the condition. Total trades: "  + IntegerToString(totalTrades);
    
   SendEmailAlert("Subsequent Trades Per Currency Alert",message ); }
//+------------------------------------------------------------------+
Discover new MetaTrader 5 opportunities with MQL5 community and services
Discover new MetaTrader 5 opportunities with MQL5 community and services
  • 2024.06.04
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions