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 mql5-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.
A client terminal sends new events to the corresponding open charts. Events can also be generated by charts (chart events) or mql5-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 MQL5 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 MQL5 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.