Core Event Handlers in MQL4: Key Functions for EAs, Scripts, and Indicators

Watch on YouTube: MQL4 Event Handlers: Building Dynamic Trading Tools

In MQL4, event handlers are foundational to controlling the behavior of Expert Advisors (EAs), indicators, and scripts. Each MQL4 program must include at least one event handler; otherwise, the program will not execute when loaded. Here’s an expanded look at key event handlers and their applications:

1. OnInit (Initialization Event)

OnInit is called once when an EA, indicator, or script is activated. It’s typically used for setting up initial configurations, like defining variables, setting trading parameters, or loading external files. Proper initialization helps ensure that the program functions smoothly from the start.

The OnInit() function should be declared with either a void or int return type, and it must not include parameters.

int OnInit() {
   Print("Expert Advisor Initialized");
   return INIT_SUCCEEDED;  // Confirms successful setup
}

Example Use Case: In an EA, OnInit might set risk levels or load custom indicators that will be used in later calculations.

2. OnDeinit (Deinitialization Event)

OnDeinit triggers when the program is removed or MetaTrader shuts down. It’s useful for cleanup tasks such as saving logs, releasing resources, or storing trade data. This handler uses a reason parameter to indicate the cause, like platform shutdown or manual removal.

The OnDeinit function must be declared as void type. This event handler is used in Expert Advisors, indicators, and scripts.

void OnDeinit(const int reason) {
   Print("EA Terminated, reason:", reason);  // Logs reason for removal
}

Example Use Case: An EA might use OnDeinit to store performance metrics to a file or release any allocated memory.

3. OnTick (New Price Tick Event)

OnTick is exclusive to EAs and is triggered whenever a new price tick arrives. This function is central to EAs because it’s where the trading logic resides—analyzing price data and executing trades. Given its high frequency, code here must be optimized to avoid slowing down performance.

The OnTick function must be declared as void type.

void OnTick() {
   double price = Ask;
   Print("New tick received at price:", price);
   // Additional trade logic goes here
}

Example Use Case: In OnTick, an EA may check if certain indicators meet entry or exit conditions and initiate trades accordingly.

4. OnStart (Script Event)

OnStart is the core function in scripts and runs once when a script is launched. Unlike EAs or indicators, scripts execute a one-time operation, which can be useful for tasks like sending alerts or closing all trades.

The OnStart() function can be declared with either void or int as its return type.

void OnStart() {
   Print("Script Started");
   // Execute a single task, like closing all trades
}

Example Use Case: A script could be used to close all open positions, freeing up resources without waiting for further ticks.

5. OnCalculate (Indicator Calculation Event)

For custom indicators, OnCalculate handles recalculations as new price data arrives. It’s efficient, recalculating only when necessary, and supports tracking historical data, making it ideal for technical analysis indicators.

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[]) {
   Print("Indicator recalculated");
   // Custom indicator logic
   return rates_total;
}

Parameters Explained: rates_total is the number of price data points available, while prev_calculated tells how many points were calculated before, so it can avoid recalculating unchanged data.

Example Use Case: An RSI indicator recalculating and updating its display on each new candle.

Conclusion

Understanding OnInit, OnDeinit, OnTick, OnStart, and OnCalculate helps MQL4 developers create responsive and efficient automated tools. These event handlers allow EAs, indicators, and scripts to interact dynamically with market data and perform tasks automatically, paving the way for comprehensive algorithmic trading solutions.

Other specialized event handlers will be introduced in complete code examples and detailed as they become relevant.

Next: Timeseries and Indicator Data

Previous: Code Compilation