Event-driven Programming in MQL4

In traditional programming, the flow of the program is determined by the programmer. However, in event-driven programming, the flow is determined by external events, like user actions, sensor outputs, or trading signals. MQL4 adopts this event-driven paradigm, especially suited for the dynamic world of trading.

What is an Event in MQL4?

An event in MQL4 is an action or occurrence detected by the MetaTrader program. These can range from price changes, ticks, trade events, to timer events and more.

Handling Events

In MQL4, events are managed using special functions called event handlers. Each type of event has its associated handler. Some of the primary event handlers are:

Example: Using OnTick() Event

The OnTick() function is perhaps the most commonly used event handler in MQL4, especially for EAs that operate on every price movement.

void OnTick() {

    double currentPrice = Close[0];
    if(currentPrice > someCondition)
        // Execute a buy trade
    } else {
        // Execute a sell trade
    //The vast majority of your trading code will be within these "Ontick" brackets...


In this simple example, whenever a new tick (price quote) is received, the OnTick() function checks the current price against a predefined condition. Based on the condition's outcome, a trading action (buy/sell) is executed.

Advantages of Event-driven Programming in Trading


Event-driven programming is a foundational concept in MQL4, reflecting the dynamic nature of the Forex market. By understanding and using event handlers efficiently, traders can create robust and responsive EAs that can adapt to ever-changing market conditions.

NEXT UP: Trading Functions and Order Management in MQL4