Module 01 · How an EA works · Lesson 02
OnInit, OnTick, OnDeinit: how an EA runs
MetaTrader calls your code at set moments. Knowing which moment is which prevents most beginner bugs.
6 minute read
Event-driven, not a loop
An EA does not run from top to bottom like a script. MetaTrader calls specific functions when something happens. You fill those functions in; the terminal decides when they run.
int OnInit()
{
// Runs once: when the EA is attached, or the chart/settings change.
// Create indicator handles, check inputs, set the magic number.
return(INIT_SUCCEEDED); // or INIT_FAILED / INIT_PARAMETERS_INCORRECT
}
void OnTick()
{
// Runs on every new price (tick) for the chart's symbol.
// Keep it fast: decide, act, return.
}
void OnDeinit(const int reason)
{
// Runs once when the EA is removed or the terminal closes.
// Release indicator handles, clean up chart objects.
}
OnInit: prepare, validate, refuse
Create indicator handles here (iMA, iRSI, iATR return a handle number, not a value). Check that the inputs make sense — a fast average longer than the slow one, a risk of 0% — and return INIT_PARAMETERS_INCORRECT so the EA refuses to start instead of trading nonsense.
OnTick: the heartbeat
On a busy market OnTick can fire many times a second; on a quiet one, rarely. If your EA must act at a fixed time even without ticks, use OnTimer with EventSetTimer. To react to fills and closures, MQL5 also offers OnTradeTransaction.
OnDeinit: leave nothing behind
The reason code tells you why the EA stopped (removed, recompiled, chart closed, account changed). Release handles with IndicatorRelease. Note that removing an EA does not close its open trades — they stay with the broker.
Takeaways
- OnInit prepares and can refuse to start.
- OnTick runs per price change, so keep it light.
- Removing an EA does not close its positions.
Your rules, our teaching. MarketPanda provides no strategy, no settings that “work” and no signals. Everything here is education; nothing is a recommendation to trade.
Content source: Bundled MarketPanda content.