Function to calculate TODAY's profit

 

Why did you post your coding question in the MT5 General section (a miscellaneous catch-all category) instead of the MT5 EA section (non-indicator coding)?
          General rules and best pratices of the Forum. - General - MQL5 programming forum? (2017)
Next time, post in the correct place. I have moved this thread.

I wrote the below MQL5 function to calculate today's profit for my EA. This is not working as expected and I cannot spot the bug. Can someone help me?

double TodayProfit()
{
   double totalProfit = 0;
   int todaysClosedCounter = 0, todaysOpenCounter = 0;
   
   // Loop through all closed trades
   HistorySelect(GetLastBusinessDay(), TimeCurrent());

   for (int i = 0; i < HistoryDealsTotal(); i++)
   {
      ulong ticket = HistoryDealGetTicket(i);
      
      if(HistoryDealGetInteger(ticket, DEAL_TYPE) == DEAL_TYPE_BUY || HistoryDealGetInteger(ticket, DEAL_TYPE) == DEAL_TYPE_SELL)
      {
         // Check if the order was closed today
         MqlDateTime today;
         TimeCurrent(today);
         MqlDateTime STime;
         TimeToStruct((datetime)HistoryDealGetInteger(ticket, DEAL_TIME), STime);

         if (STime.day == today.day)
         {
            totalProfit += HistoryDealGetDouble(ticket, DEAL_PROFIT);
            todaysClosedCounter++;
         }
      }
   }
   //Print("CLOSED PROFIT:", totalProfit);
   double temp = 0;

   // Loop through all open (running) trades
   for (int i = 0; i < PositionsTotal(); i++)
   {
      ulong ticket = PositionGetTicket(i);
      
      if (PositionSelectByTicket(ticket))
      {
         temp += PositionGetDouble(POSITION_PROFIT);
         totalProfit += PositionGetDouble(POSITION_PROFIT);
         todaysOpenCounter++;
      }
   }
   //Print("OPEN PROFIT:",temp);
   //Print("todaysClosedCounter:", todaysClosedCounter, " todaysOpenCounter:", todaysOpenCounter);

   return totalProfit;
}

datetime GetLastBusinessDay()
{
    datetime currentTime = TimeCurrent();
    MqlDateTime dt;
    TimeToStruct(currentTime, dt);

    // Subtract the necessary number of days to get to the last business day
    switch (dt.day_of_week)
    {
        case 0: // Sunday
            return currentTime - 2 * 86400;
        case 1: // Monday
            return currentTime - 3 * 86400;
        default: // Tuesday to Saturday
            return currentTime - 1 * 86400;
    }
}

Basically I want my EA to print the NET profit for today only, including both close and open positions.

 
GetLastBusinessDay returns previous calendar day. Does not handle market holidays. Assumes broker's time zone includes Sunday.
Nabeel Bashir: Basically I want my EA to print the NET profit for today only, including both close and open positions.

Then why are you selecting the previous day, not today?