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.
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.
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:
OnInit()
: Called when an Expert Advisor (EA) is initialized.OnDeinit()
: Called when an EA stops its operation.OnTick()
: Triggered whenever a new quote is received for the symbol the EA is attached to.OnTimer()
: Used when working with a timer.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.
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