MQL5 & MetaTrader core
The MQL5 program structure
5 min
Every EA is built around a few event handler functions that MetaTrader calls automatically at the right moments. You do not call them yourself — the terminal does.
The three core events
- OnInit() — called once when the EA is attached or its inputs change. Validate inputs, create indicator handles, set up state. Return INIT_SUCCEEDED or fail fast.
- OnTick() — called on every incoming price tick. This is the heart of the EA: read prices, evaluate the strategy, decide whether to trade. It can fire many times per second or rarely, depending on the market.
- OnDeinit() — called once when the EA is removed or the terminal closes. Release handles and clean up.
A minimal EA skeleton
// input parameters are tunable from the terminal and the tester
input int FastPeriod = 20;
input int SlowPeriod = 50;
input double Lots = 0.10;
int OnInit()
{
if(FastPeriod >= SlowPeriod)
return(INIT_PARAMETERS_INCORRECT);
return(INIT_SUCCEEDED);
}
void OnTick()
{
// strategy logic runs here on every tick
}
void OnDeinit(const int reason)
{
// cleanup runs here
}
A crucial performance habit
OnTick can run extremely often. Doing heavy work on every tick — recalculating long indicators, re-reading history — is wasteful and can lag the EA. The common pattern is to act only when a new bar opens (detect a change in the bar's open time) rather than on every tick, unless your strategy genuinely needs tick-level reaction.
Other handlers you will meet
OnTimer() for periodic work, OnTrade() when a trade event fires, and OnChartEvent() for user interaction. Master the three core ones first; they cover most strategies.
This content is for educational and informational purposes only and is not investment, financial, tax or legal advice. Trading and investing carry risk, including the possible loss of capital. Any performance shown by third-party tools is hypothetical and not a promise of future results. Do your own research and consider professional advice before making any decision.