mql4mql5metatrader5mt4

How to get current milliseconds in MetaTrader4 Terminal?


How can I get current milliseconds from MQL4 using an Expert Advisor.

i.e.: in Java we can get current milliseconds using system.currenttimemillis()


Solution

  • This MT4 "Get millisecond" problem has been around for ages. This is a hack I created to solve this problem.

    //+------------------------------------------------------------------+
    //|                                                     timeInMs.mq4 |
    //|                                       Copyright 2017, Joseph Lee |
    //+------------------------------------------------------------------+
    #property copyright "Copyright 2017, Joseph Lee"
    #property link      "https://www.facebook.com/joseph.fhlee"
    #property version   "1.00"
    #property strict
    
    int     prevSecondTime      = 0;
    uint    prevSecondTick      = 0;
    
    
    int OnInit()    {
        // Create an Event that triggers every 1 millisecond.
        // **NOTE: GetTickCount() is accurate to 16ms only, so
        // in practice, no need to trigger every 1ms.
        EventSetMillisecondTimer(1);
        return(INIT_SUCCEEDED);
    }
    
    void OnTick() {
        Comment( "Now: " + TimeLocal() + " :: " + getCurrentMs() + " ms. +- 16ms accuracy.");
    }
    
    int getCurrentMs() {
        return(GetTickCount() - prevSecondTick);
    }
    
    // This is an EVENT function that will be called every
    // x milliseconds [see EventSetMillisecondTimer() in OnInit()]
    void OnTimer() {
        // If a new "second" occurs, record GetTickCount()
        if(TimeLocal() > prevSecondTime) {
            prevSecondTick  = GetTickCount();
            prevSecondTime  = TimeLocal();
        }
    }