Discussing the article: "Learn how to deal with date and time in MQL5"

 

Check out the new article: Learn how to deal with date and time in MQL5.

A new article about a new important topic which is dealing with date and time. As traders or programmers of trading tools, it is very crucial to understand how to deal with these two aspects date and time very well and effectively. So, I will share some important information about how we can deal with date and time to create effective trading tools smoothly and simply without any complicity as much as I can.

It is not hidden by anyone in the financial market field, the importance of time, and how it can affect trading decisions and results. MQL5 (MetaQuotes Language 5) offers an amazing solution to deal with date and time effectively and this is what we will learn in this article because we will see how we can deal with this important topic through many applications that can be coded as a part of our trading system after understanding the most important aspects of this topic in the MQL5 programming language.


Author: Mohamed Abdelmaaboud

 

It should be mentioned that StructToTime, TimeToStruct and especially TimeToString and StringToTime are rather "expensive" operations and in time-critical situations they can sometimes be replaced by simpler ones.

In particular, it is very much not recommended to get the beginning of the day in a directive way:

StringToTime(TimeToString(TimeCurrent(),TIME_DATE))

better do:

TimeCurrent() / 86400 * 86400

Because of integer arithmetic, the remainder from division will be discarded.


Or, sometimes it is enough to know the time elapsed from the beginning of the day, and the year, month, number, day of the week are not important (or can be obtained once at the onset of a new day).

In seconds: time % 86400

Hours: time % 86400 / 3600

Minutes: time % 3600 / 60

Seconds: time % 60

 

When solving the problem of assigning unique names to objects (of ARROW type) we use time in seconds:

//+------------------------------------------------------------------+

int TimeInSec(datetime date)
{
MqlDateTime tm;
TimeToStruct(date, tm);
int sec_int = tm.day * 24 *3600 + tm.hour * 3600 + tm.min * 60 + tm.sec * 1;
return(sec_int);
}

//+------------------------------------------------------------------+

int TimeMinute(datetime date)
{
MqlDateTime tm;
TimeToStruct(date, tm);
return(tm.min);
}

 
gerien #:

When solving the problem of assigning unique names to objects (of ARROW type) we use time in seconds:

I think it is much cheaper to organise a global incremental counter.

 
gerien #:
int TimeMinute(datetime date)
{
MqlDateTime tm;
TimeToStruct(date, tm);
return(tm.min);
}

This is exactly what I was talking about. Inefficient use of the "expensive" TimeToStruct function.

Just this one is enough:

int TimeMinute(datetime date)
  {
   return((int)(date % 3600 / 60));
  } 
 
gerien TimeToStruct(date, tm);
int sec_int = tm.day * 24 *3600 + tm.hour * 3600 + tm.min * 60 + tm.sec * 1;
return(sec_int);
}

//+------------------------------------------------------------------+

int TimeMinute(datetime date)
{
MqlDateTime tm;
TimeToStruct(date, tm);
return(tm.min);
}

everything is much simpler - datetime is seconds. It doesn't need to be parsed through TimeToStruct to multiply and add the fields afterwards

long timeIsSeconds = (long)TimeCurrent();

if your algorithm guarantees the absence of two arrows in one second, it will work.

 
Maxim Kuznetsov #:

It takes seconds from the beginning of the month, apparently, to make the number shorter.

Although with almost (if you don't need to recalculate the object name to the day of the month) the same result you can take the remainder of dividing TimeCurrent() by a number close to the average number of seconds in the month.

 
JRandomTrader #:

He's taking seconds from the beginning of the month to make the number shorter.

Although with almost (if you don't need to recalculate the object name to the day of the month) the same result you can take the remainder of dividing TimeCurrent() by a number close to the average number of seconds in the month.

and subtract from one date another date (the beginning of the month) does not allow some cunning religion ? :-)

In practice - if somewhere inside you need to know the exact beginning of the month, day, week, they are counted and memorised once. So that you don't have to recalculate them for every sneeze.

datetime thisDayTime, nextDayTime;
datetime thisYearTime,thisMonTime;
int thisYear, thisMon;

// вызывать внутри всех обработчиков OnXXX терминала- это прототип службы времени
void TimeService() {
    datetime now=TimeCurrent();
    if (now>=nextDayTime) {
        MqlDateTime dt; TimeToStruct(dt,now);
        dt.hour=dt.min=dt.sec=0;
        thisDayTime=StructToTime(dt);
        nextDayTime=thisDayTime+24*60*60;
        OnDay();  /// обработчик "начало дня"
        if (dt.month!=thisMon|| dt.year!=thisYear) {
               thisMon=dt.month;
               dt.day=0; thisMon=StructToTime(dt);
               OnMon();   /// обработчик "начало месяца"
        }

        if ( dt.year!=thisYear ) {
               thisYear=dt.year; 
               dt.month=0; thisYearTime=StructToTime(dt);
               OnYear();  /// обработчик "начало года"
        }
    }
}

 

Sorry, I just thought of something on the subject:

Фредерик Браун
Конец начал

Профессор Джонс долгое время работал над теорией времени.
- И сегодня я нашел ключевое уравнение, - сказал он своей дочери как-то утром.
- Время это поле. Я создал  машину, которая способна управлять этим полем.
Он протянул руку и, нажимая кнопку, сказал:
- Это заставит время идти назад идти время заставит это
- :сказал, кнопку нажимая, и руку протянул он.
- Полем этим управлять способна которая, машину создал я. Поле это время,
- утром как-то дочери своей он сказал. - Уравнение ключевое нашел я сегодня и.
Времени теорией над работал время долгое Джонс профессор.

Начал конец
Браун Фредерик
 
JRandomTrader #:

Sorry, I just thought of something on the subject:

Probably should have reversed not only the word order, but also the letter order ;)
 
JRandomTrader #:

Sorry, I just thought of something on the subject:

I remembered a Soviet sci-fi story where the daughter kept telling him "ukponk imzhan" before her father's experiment at the time institute, and he didn't understand her childish pampering.

And she saved him with it.

Reason: