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

video
play-sharp-fill

In this video, we will be crafting an Expert Advisor using MQL4 that calculates the elapsed time since the start of the Expert Advisor in seconds, minutes, and hours. This information will then be displayed on the chart in a readable format.

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

Code Description:

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

  • CurrentTime: This variable is designated to store the current time.
  • StartTime: This variable will hold the start time when the Expert Advisor was initiated.
  • PassedTimeInSeconds: This variable will store the elapsed time in seconds.
  • TimeWithSeconds and StartTimeWithSeconds: These two string variables will store the current time and the start time in a readable format, which includes both the date and the seconds.

Within the OnTick function, which is invoked on every market tick:

  • We check if the StartTime variable is uninitialized (has a value of 0). If true:
    • We assign it the current local time using the TimeLocal() function. This function fetches the current time of the computer where the client terminal is operational.
    • We then convert the start time into a readable format using the TimeToStr function with the flags TIME_DATE and TIME_SECONDS. This ensures the output includes both the date and the seconds.
  • Subsequently, we calculate the current time and the elapsed time in seconds by subtracting the start time from the current time.
  • We also convert the current time into a readable format, similar to what we did for the start time.

Lastly, we employ the Comment function to display various time-related details on the chart:

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

Code Execution:

When you run the Expert Advisor, it will exhibit the elapsed time since its initiation on the chart. You’ll be able to observe the seconds, minutes, and potentially hours ticking up in real-time.

To wrap up, in this video, you’ve learned how to compute the elapsed time since the start of an Expert Advisor in MQL4 and how to display it in a user-friendly format.

Thank you for tuning in, and we’ll see you in the next tutorial!