Detecting the Last Day of the Month in MQL5

Detecting the Last Day of the Month in MQL5

2 August 2026, 09:37
Rahman Pavaleh
0
45

When developing Expert Advisors and trading utilities, there are many situations where we need to know whether today is the last calendar day of the current month.

Typical examples include:

  • Monthly portfolio rebalancing
  • Closing positions at month-end
  • Generating monthly reports
  • Resetting monthly statistics
  • Executing scheduled maintenance tasks

A common mistake is to manually calculate the number of days in each month. This requires handling months with 28, 29, 30 and 31 days, as well as leap years.

Fortunately, MQL5 provides date and time functions that make this much simpler.

Implementation

bool LastDayOfMonth()
{
   MqlDateTime dt, next_day;

   TimeToStruct(TimeCurrent(), dt);

   dt.hour = 23;
   dt.min  = 59;
   dt.sec  = 59;

   datetime t = StructToTime(dt) + 1;

   TimeToStruct(t, next_day);

   return (dt.mon != next_day.mon);
}

How it works

The function performs four simple steps:

  1. Gets the current server date.
  2. Changes the time to 23:59:59.
  3. Adds one second.
  4. Compares the current month with the month of the next day.

If the month changes after adding one second, then today must be the final day of the month.

Example

if(LastDayOfMonth())
{
   Print("Today is the last day of the month.");
}

Advantages

  • No month-length tables
  • Automatic leap-year support
  • Fast and lightweight
  • Easy to reuse
  • Works in Experts, Indicators and Scripts

This utility is small, but it can simplify many automation tasks and reduce unnecessary date calculations inside trading applications.

I regularly publish reusable MQL5 utility functions and trading development resources. I hope this snippet is useful in your own projects.