Help with Accumulating Profit in Monthly Summary Based on Trades

 

Hello MQL5 Community,

I’m working on a function to calculate and display the profit summary for specific periods (weekly or monthly) based on trades with a particular magic number. However, I’m encountering an issue where the profit summary shows individual profits for each month but does not correctly accumulate the total profit from multiple trades opened within the same period.

The Current Issue:

  1. Problem: Instead of accumulating the profit for trades opened during the same month or week, the profit is being calculated individually per trade. This results in multiple totals for the same period (one per trade, rather than one for the entire period).
  2. Expected Outcome: I want the function to group trades by the month in which they were opened, summing the profits (and losses) of all trades within that period and displaying a single profit total.


sample of my terminal log for the monthly period:


2024.05.15 21:00:00 Symbol.fs,H1: Profit Summary

Period Start : 2024.05.01 00:00

Total Profit : 69.55

2024.06.12 21:00:00 Symbol.fs,H1: Profit Summary

Period Start : 2024.06.01 00:00

Total Profit : 348.25


As seen from the log, only the start of new month profits are shown though there were 11 total trades.

/*Static variables week and month*/

static int lastProcessedWeek = -1;
static int lastProcessedMonth = -1;

/* Function to retrieve the profit summary*/

string ProfitSummary(int magicNumber) {
    string msg_ProfitSummary = "";

/* Total number of historical orders*/

    int hstTotal = OrdersHistoryTotal();  
    double profittotal = 0.0;
    datetime starttime = 0;

    /* Determine start time*/
    if (periodType == PERIOD_MONTHLY) {

         /* Start of the current calendar month*/
        starttime = iTime(Symbol(), PERIOD_MN1, 0);

    } else if (periodType == PERIOD_WEEKLY) {

         /*Start of the current calendar week*/
        starttime = iTime(Symbol(), PERIOD_W1, 0);

        /* start of the week (Monday)*/

        starttime -= (TimeDayOfWeek(starttime) - 1) * 24 * 3600;  //* Move to Monday*/
    }
    Print("Total Orders: ", hstTotal);
    /*Calculate total profit*/

    for (int i = 0; i < hstTotal; i++) {
        if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY) == TRUE) {
            if (OrderMagicNumber() == magicNumber && OrderOpenTime() >= starttime && 
                (OrderType() == OP_BUY || OrderType() == OP_SELL)) {

                /* profit is calculated*/
                /*Add to profit total*/
                profittotal += OrderProfit() + OrderSwap() + OrderCommission();
            }
        }
    }

    /*the current period (month or week) based on the periodType*/

    bool newPeriod = false;
    if (periodType == PERIOD_MONTHLY) {
        int currentMonth = TimeMonth(TimeCurrent());
        if (lastProcessedMonth != currentMonth) {
            newPeriod = true;
            lastProcessedMonth = currentMonth;  /*Update last processed month*/
        }
    } else if (periodType == PERIOD_WEEKLY) {
        int currentWeek = TimeDayOfYear(TimeCurrent()) / 7;  /*Week number*/
        if (lastProcessedWeek != currentWeek) {
            newPeriod = true;
            lastProcessedWeek = currentWeek;  /*processed week*/
        }
    }

    /*Prepare and send summary message*/

    if (newPeriod) {
        msg_ProfitSummary = "Profit Summary\n"
                            "========================================\n"
                            "Period Start : " + TimeToStr(starttime, TIME_DATE | TIME_MINUTES) + "\n"
                            "----------------------------------------\n"
                            "Total Profit : " + DoubleToStr(profittotal, 2) + "\n"
                            "========================================";
        SendMyMessage(msg_ProfitSummary);  /*Send summary message*/
    }
    return msg_ProfitSummary;
}
  1. How can I accumulate profits from multiple trades that were opened within the same period (week/month) instead of treating them as individual profits?
  2. Am I correctly identifying and grouping trades by their opening time for each period?
  3. Are there any optimizations or improvements that I should consider in my approach?

Thank you for your time and any help or suggestions you can provide.

Regards,

Benjamin

Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Position Properties
Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Position Properties
  • www.mql5.com
Execution of trade operations results in the opening of a position, changing of its volume and/or direction, or its disappearance. Trade operations...
 
Your topic has been moved to the section: Expert Advisors and Automated Trading
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
 
Fernando Carreiro #:
Your topic has been moved to the section: Expert Advisors and Automated Trading
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893

Thanks, @Fernando Carreiro

I believe it would be more appropriate in the MQL4 and MetaTrader 4 section.

Can you please help by having it moved to that section?

 
OTMT Howard #: Thanks, @Fernando Carreiro. I believe it would be more appropriate in the MQL4 and MetaTrader 4 section. Can you please help by having it moved to that section?
Done!