Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()

like image 365
Nitin Avatar asked Nov 15 '25 02:11

Nitin


1 Answers

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();
    }
}
like image 170
Joseph Lee Avatar answered Nov 17 '25 18:11

Joseph Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!