MQL5 Tutorial – Calculating Time Difference in Hours, Minutes, and Seconds



In this video, we will be creating an Expert Advisor that calculates the elapsed time since the start of the Expert Advisor in hours, minutes, and seconds, and displays it on the chart.

To begin, please click on the small button at the top in MetaTrader 5 or press the F4 key to open the MetaEditor.

Code Description:

At the start of the code, we declare several date and time variables:

  • CurrentTime: This variable stores the current time.
  • StartTime: This variable stores the start time when the Expert Advisor was initiated.
  • PassedTime: This variable will store the elapsed time.

Within the OnTick function, which gets called on every market tick:

  • We check if the StartTime variable has not been assigned a value. If it hasn’t:
    • We assign it the current local time using TimeLocal(). The TimeLocal() function returns the current time of the computer where the client terminal is running.
  • We then calculate the current time and the elapsed time by subtracting the start time from the current time.
  • A structure variable of type MqlDateTime named DateTimeStructure is declared. This structure stores information about date and time.
  • We use the TimeToStruct function to convert the elapsed time (PassedTime) into the MqlDateTime structure. This structure will allow us to extract hours, minutes, and seconds.

From this structure, we extract:

  • PassedTimeInHours: The hours since the Expert Advisor started.
  • PassedTimeInMinutes: The minutes since the start.
  • PassedTimeInSeconds: The seconds since the start.

Finally, we use the Comment function to display various time-related information on the chart:

  • The start time.
  • The current time.
  • The elapsed time in hours, minutes, and seconds.

Code Execution:

Upon running the Expert Advisor, it will display the elapsed time since the start of the Expert Advisor on the chart in real-time. You’ll observe the seconds, minutes, and potentially hours ticking up.

In conclusion, in this video, you’ve learned how to calculate the elapsed time since the start of an Expert Advisor using just a few lines of MQL5 code.

Thank you for watching, and see you in the next video!