MQL4 Reference MQL4 programs Program Running

Program Running

Each script and each Expert Advisor runs in its own separate thread. All indicators work in the graphic interface thread. processing of ticks and history synchronization are also performed in graphic interface thread. Custom indicators work in the main interface thread. If a custom indicator has been called with the iCustom() function, this indicator works in the thread of the program that has called it. Library (imported) functions work in the calling program thread, as well.

When running an Expert Advisor, make sure that it has an actual trading environment and can access the history of the required symbol and period, and synchronize data between the terminal and the server. For all these procedures, the terminal provides a start delay of no more than 5 seconds, after which the Expert Advisor will be started with available data. Therefore, in case there is no connection to the server, this may lead to a delay in the start of an Expert Advisor.

The below table contains a brief summary of MQL4 programs:

Program

Running

Note

Script

A separate thread, the number of threads for scripts is equal to the number of scripts

A looped script cannot break running of other programs

Expert Advisor

A separate thread, the number of threads for Expert Advisors is equal to the number of Expert Advisors

A looped Expert Advisor cannot break running of other programs

Indicator

All indicators share the resources of graphic interface thread of the terminal

An infinite loop in one indicator will stop the work of terminal

Right after a program is attached to a chart, it is uploaded to the client terminal memory, as well as global variable are initialized. If some global variable of the class type has a constructor, this constructor will be called during initialization of global variables.

After that the program is waiting for an event from the client terminal. Each mql4-program should have at least one event-handler, otherwise the loaded program will not be executed. Event handlers have  predefined names, parameters and return types.

Type

Function name

Parameters

Application

Comment

int

OnInit

none

Expert Advisors, indicators and scripts

Init event handler. It allows to use the void return type.

void

OnDeinit

const int reason

Expert Advisors, indicators and scripts

Deinit event handler.

void

OnStart

none

scripts

Start event handler.

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 &TickVolume[],

const long &Volume[],

const int &Spread[]

indicators

Calculate event handler for all prices.

void

OnTick

none

Expert Advisors

NewTick event handler. While the event of a new tick receipt is being processed, no other events of this type are received.

void

OnTimer

none

Expert Advisors and indicators

Timer event handler.

double

OnTester

none

Expert Advisors

Tester event handler.

void

OnChartEvent

const int id,

const long &lparam,

const double &dparam,

const string &sparam

Expert Advisors and indicators

ChartEvent event handler.

A client terminal sends new events to the corresponding open charts. Events can also be generated by charts (chart events) or mql4-programs (custom events). Generation of events of creation or deletion of graphical objects on a chart can be enabled or disabled by setting CHART_EVENT_OBJECT_CREATE and CHART_EVENT_OBJECT_DELETE chart properties. Each MQL4 program and each chart has its own queue of events, where all new incoming events are added.

A program receives only events from the chart it runs on. All events are processed one after another in the order they are received. If a queue already has a NewTick event, or this event is currently being processed, then the new NewTick event is not placed in the queue of the MQL4 program. Similarly, if ChartEvent is already enqueued, or this event is being processed, no new event of this kind is enqueued. The timer events are handled the same way — if the Timer event is in the queue or being handled, the new timer event is not enqueued.

Event queues have a limited but sufficient size, so that the queue overflow for well written programs is unlikely. In case of queue overflow, new events are discarded without queuing.

It is not recommended to use infinite loops to handle events. The exception to this rule may be only scripts that process only a single Start event.

Libraries do not handle any events.

 

Functions prohibited in Indicators and Expert Advisors

Indicators, scripts and Expert Advisors are executable programs written in MQL4. They are designed for different types of tasks. Therefore there are some restrictions on the use of certain functions, depending on the type of program. The following functions are prohibited in indicators:

All functions designed for indicators are prohibited in Expert Advisors and scripts:

The library is not an independent program and is executed in the context of the MQL4 program that has called it: script, indicator or Expert Advisor. Accordingly, the above restrictions apply to the called library.

 

Loading and Unloading of Indicators

Indicators are loaded in the following cases:

  • an indicator is attached to a chart;
  • terminal start (if the indicator was attached to the chart prior to the shutdown of the terminal);
  • loading of a template (if the indicator attached to a chart is specified in the template);
  • change of a profile (if the indicator is attached to one of the profile charts);
  • change of a symbol and/or timeframe of a chart, to which the indicator is attached;
  • after the successful recompilation of an indicator (if the indicator was attached to a chart);
  • change of input parameters of the indicator.

Indicators are unloaded in the following cases:

  • when detaching an indicator from a chart;
  • terminal shutdown (if the indicator was attached to a chart);
  • loading of a template (if an indicator is attached to a chart);
  • closing of a chart, to which the indicator was attached;
  • change of a profile (if the indicator is attached to one of charts of the changed profile);
  • change of a symbol and/or timeframe of a chart, to which the indicator is attached;

 

Loading and Unloading of Expert Advisors

Expert Advisors are loaded in the following cases:

  • when attaching an Expert Advisor to a chart;
  • terminal start (if the Expert Advisor was attached to the chart prior to the shutdown of the terminal);
  • loading of a template (if the Expert Advisor attached to the chart is specified in the template);
  • change of a profile (if the Expert Advisor is attached to the one of the profile charts);
  • connection to an account, even if the account number is the same (if the Expert Advisor was attached to the chart before the authorization of the terminal on the server).

Expert Advisors are unloaded in the following cases:

  • when detaching an Expert Advisor from a chart;
  • if a new Expert Advisor is attached to a chart, if another Expert Advisor has been attached already, this Expert Advisor is unloaded.
  • terminal shutdown (if the Expert Advisor was attached to a chart);
  • loading of a template (if an Expert Advisor is attached to the chart);
  • close of a chart, to which the Expert Advisor is attached.
  • change of a profile (if the Expert Advisor is attached to one of charts of the changed profile);
  • change of the account to which the terminal is connected (if the Expert Advisor was attached to the chart before the authorization of the terminal on the server);

In case the symbol or timeframe of a chart, to which the Expert Advisor is attached, changes, Expert Advisors are not loaded or unloaded. In this case client terminal subsequently calls OnDeinit() handlers on the old symbol/timeframe and OnInit() on the new symbol/timeframe (if they are such), values of global variables and static variables are not reset. All events, which have been received for the Expert Advisor before the initialization is completed (OnInit() function) are skipped.

For a better understanding of the Expert Advisor operation we recommend to compile the code of the following Expert Advisor and perform actions of load/unload, template change, symbol change, timeframe change etc:

Example:

//+------------------------------------------------------------------+
//|                                                   TestExpert.mq5 |
//|                        Copyright 2009, MetaQuotes Software Corp. |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
 
class CTestClass
  {
public:  
   CTestClass() { Print("CTestClass constructor"); }
   ~CTestClass() { Print("CTestClass destructor"); }
  };
CTestClass global;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   Print("Initialization");
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   Print("Deinitialization with reason",reason);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
 
  }
//+------------------------------------------------------------------+

 

Loading and Unloading of Scripts

Scripts are loaded immediately after they are attached to a chart and unloaded immediately after they complete their operation.

When a program is unloaded (deleted from a chart) the client terminal performs deinitialization of global variables and deletes the events queue. In this case deinitialization means reset of all the string-type variables, deallocation of dynamical array objects and call of their destructors if they are available.

//+------------------------------------------------------------------+
//|                                                   TestScript.mq5 |
//|                        Copyright 2014, MetaQuotes Software Corp. |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2014, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
 
class CTestClass
  {
public:  
   CTestClass() { Print("CTestClass constructor"); }
   ~CTestClass() { Print("CTestClass destructor"); }
  };
CTestClass global;
//+------------------------------------------------------------------+
//| Script program initialization function                           |
//+------------------------------------------------------------------+
void OnInit()
  {
   Print(__FUNCTION__);
  }
//+------------------------------------------------------------------+
//| Script program deinitialization function                         |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   Print(__FUNCTION__," reason=",reason);
  }
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   Print(__FUNCTION__);
  }

Input Parameters and Source Code Compilation

If a source code of a program launched on a chart is successfully recompiled, its previous version is removed from the chart and the new compiled copy is executed instead.

If the set of the input parameters is not changed after the recompilation, the previously specified parameter values are applied. Otherwise, the default values are used.

The set of mql4 program input parameters is considered to be changed when editing the source code in the following cases:

  • the number of parameters has been changed;
  • the sequence order of parameters has been changed;
  • parameter names have been changed;
  • the type of one or more parameters has been changed.

Changing a default value of any of the parameters is not considered to be a change of the input parameter set.

The set of the input parameters clearly identifies the program in the terminal's execution system. If this set is unchanged, the new versions of the executable file are considered to retain the entire logic and functionality of the program.

If the set of the input parameters is changed, the terminal considers the new executable file as incompatible with the program that has been previously launched on the chart. Thus, the new recompiled program is launched with the set of the input parameters having default values.

In other cases (including the ones when a default value of any parameter is changed), the previously specified parameters are applied after the recompilation.

The OnInit() predefined function is called after any compilation. Its purpose is to correctly initialize all global and static variables of the program. The program's input parameter values should be used correctly in OnInit() event handler.

See also

Client terminal events, Event handlers