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

Watch on YouTube: Mastering Core Event Handlers in MQL5: Key Functions for Your Trading Programs

In MQL5, event handlers are crucial for managing the behavior of Expert Advisors (EAs), indicators, and scripts. These handlers ensure your program responds dynamically to market data and user actions. Below is a more detailed explanation of key event handlers:

OnInit (Initialization Event)

OnInit is called when an EA or indicator is initialized. It’s used to set up the environment by defining key parameters, initializing variables, or loading external resources. This function is executed only once when the program is first launched. If initialization is successful, the OnInit function returns INIT_SUCCEEDED.

int OnInit() {
   Print("Initialization Complete");
   return INIT_SUCCEEDED;  // Confirms initialization success
}

Example Use Case: In an EA, you might use OnInit to set initial trading parameters such as risk management levels or load custom libraries.

OnDeinit (Deinitialization Event)

Triggered when the EA or indicator is removed or MetaTrader is shut down. This event is useful for performing cleanup tasks like saving logs, releasing resources, or saving trade data. It can help ensure that no important data is lost and that resources are properly freed. The OnDeinit function provides the reason for deinitialization, such as REASON_REMOVE when the program is removed from a chart.

void OnDeinit(const int reason) {
   Print("Deinitialized, reason: ", reason);
}

Example Use Case: An EA could store performance metrics to a file or release memory allocated for data during the execution of the program.

OnTick (New Price Tick Event)

Exclusive to EAs, OnTick is called whenever a new price tick arrives. This event is at the heart of trading logic—calculating entry and exit conditions, managing open positions, and executing trades. Because it’s called frequently, efficient coding is critical to avoid performance issues.

void OnTick() {
   double price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   Print("New tick received at price: ", price);
}

Example Use Case: You could use OnTick to implement a trading strategy or check indicator conditions to open or close trades.

OnStart (Script Event)

The OnStart function is used in scripts and runs only once when a script is launched. Scripts execute a one-time operation such as placing a trade, sending an alert, or managing open positions.

void OnStart() {
   Print("Script Started");
   // Example: Close all open trades
}

Example Use Case: A script could be used to automate tasks like closing all open positions or sending a specific notification when a condition is met.

OnCalculate (Indicator Calculation Event)

The OnCalculate function is triggered in custom indicators whenever new price data is available. It’s optimized to only recalculate when necessary, helping maintain performance. This function provides the core logic for calculating indicator values based on historical and real-time data.

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");
   return rates_total;
}

Example Use Case: A custom RSI indicator will update its value every time a new price tick arrives and can be used to signal overbought or oversold conditions.

We’ll explore each of these event handlers in detail, focusing on their applications within Expert Advisors (EAs), indicators, and other script types.

Conclusion

Mastering the core event handlers in MQL5—OnInit, OnDeinit, OnTick, OnStart, and OnCalculate—is essential for building responsive, efficient trading algorithms. These functions enable EAs, indicators, and scripts to interact dynamically with the market, automate trading decisions, and perform necessary tasks automatically.

Next: Timeseries and Indicators

Previous: Compilation