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?

 
William Roeder #:
GetLastBusinessDay returns previous calendar day. Does not handle market holidays. Assumes broker's time zone includes Sunday.

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

I have modified and simplified the code to debug the issue. In this version I can see that `HistoryDealsTotal()` is returning the correct count but `HistoryDealGetTicket(i)` inside the loop is always returning 0. Can you tell why?

int OnInit()
{
   // Get the start of today (00:00:00)
    datetime day_start;
    MqlDateTime dt;
    TimeCurrent(dt);  // Get current time
    Print("Current:", TimeCurrent(dt));
    dt.hour = 0;      // Reset time to 00:00:00
    dt.min = 0;
    dt.sec = 0;
    day_start = StructToTime(dt);
    Print("START:", day_start);

    double closed_profit = 0.0;

    //--- Select trade history from today
    if (!HistorySelect(day_start, TimeCurrent()))
    {
        Print("❌ Failed to select trade history.");
        return(INIT_SUCCEEDED);;
    }

    int totalDeals = HistoryDealsTotal();  // Get total number of deals
    PrintFormat("🔍 Total deals found: %d", totalDeals);
    
    if (totalDeals == 0)
    {
        Print("❌ No closed deals today.");
        return(INIT_SUCCEEDED);;
    }

    //--- Iterate through all the deals
    for (int i = 0; i < totalDeals; i++)
    {
        ulong deal_ticket = HistoryDealGetTicket(i);  // Get deal ticket
        Print("Deal:", deal_ticket, " INDEX:", i);
        if (!HistoryDealSelect(deal_ticket))  // Select deal by ticket
            continue;

        Print("Selected deal_ticket:", deal_ticket);
        
        // Get the deal time and check if it's from today
        datetime deal_time = (datetime)HistoryDealGetInteger(deal_ticket, DEAL_TIME);
        if (deal_time < day_start)  // Only consider deals from today
            continue;
        Print("deal_ticket:", deal_ticket, " deal_time:", deal_time);

        // Retrieve profit from the deal
        double profit = HistoryDealGetDouble(deal_ticket, DEAL_PROFIT);
        if (profit != 0)
        {
            closed_profit += profit;  // Add the profit of this deal to the total
        }
    }

    // Output the total closed profit today
    //PrintFormat("✅ Net Profit from Closed Deals Today: %.2f USD", closed_profit); 
    
   return(INIT_SUCCEEDED);
}


I have also tried reversing the loop order, and in that case only the latest (highest index) deal is selected.

UPDATE:

`HistoryDealSelect(deal_ticket)` statement fails with 4755 error code.

 

I fixed my issue by removing the below line. This was unnecessary in my snippet.


if (!HistoryDealSelect(deal_ticket))