Check for elapsed time?

 

I would like to repeat a task every 20 seconds is that how to do it?

int timeToWaitInSeconds = 20;
datetime LastTimeRecorded = LONG_MIN;

int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   
   if (LastTimeRecorded == LONG_MIN)
   {
      LastTimeRecorded = TimeCurrent();
   }

   if (TimeCurrent() - LastTimeRecorded >= timeToWaitInSeconds )
   {
      LastTimeRecorded = TimeCurrent();

      /* code */
   }
   
//--- return value of prev_calculated for next call
   return(rates_total);
  }
 
  • OnCalculate. The function is called in the indicators when the Calculate event occurs for processing price data changes.

I GUESS  this won't work in closed market.

Documentation on MQL5: Constants, Enumerations and Structures / Codes of Errors and Warnings / Trade Server Return Codes
Documentation on MQL5: Constants, Enumerations and Structures / Codes of Errors and Warnings / Trade Server Return Codes
  • www.mql5.com
Trade Server Return Codes - Codes of Errors and Warnings - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
//global
datetime wait;


   if (TimeCurrent() < wait) return; //check initially and every 20 seconds
   wait=TimeCurrent()+20;

 

Is there a reason not to be doing this task with the OnTimer() event function with EventSetTimer(20) set in OnInit()?

 
Max0r847 #:
OnTimer

OnTimer only works for EAs not indicators.

 
Yashar Seyyedin #:

OnTimer only works for EAs not indicators.

False!!!!!!!!

 
Yashar Seyyedin #:

OnTimer only works for EAs not indicators.

Forum on trading, automated trading systems and testing trading strategies

Performance implications of multiple chart object updating indicators on a chart

Alain Verleyen, 2023.05.28 17:34

Of course not. OnTimer() works perfectly with indicators, except when invoked with iCustom().

Reason: