MQL4 vs MQL5 Architecture for EA Coding
Although MQL4 and MQL5 share C++-like syntax inside MetaEditor, their internal trading engines differ substantially. Understanding those differences early prevents common bugs when building or porting an Expert Advisor.
| Component | MQL4 (MetaTrader 4) | MQL5 (MetaTrader 5) |
|---|---|---|
| Source & Binary Files | .mq4 compiles to .ex4 |
.mq5 compiles to .ex5 |
| Account Model | Order-based hedging model only | Position-based supporting both Hedging and Netting accounts |
| Sending Orders | Direct OrderSend(), OrderModify(), OrderClose() |
CTrade wrapper class (#include <TradeTrade.mqh>) or low-level OrderSend(request, result) |
| Reading Indicators | Single call returns value directly: iMA(...) |
Create handle in OnInit(), copy array in OnTick() via CopyBuffer() |
| Predefined Market Variables | Built-in Ask, Bid, Bars, Close[] |
Fetch explicitly via SymbolInfoDouble(), SymbolInfoTick(), CopyClose() |
Core EA Event Lifecycle
Every well-structured MetaTrader robot organizes execution into three core event handlers:
int OnInit(): Executes once when attached to a chart or on timeframe change. Validate userinputvalues, set Magic Numbers (trade.SetExpertMagicNumber(InpMagic)in MQL5), initialize indicator handles, and returnINIT_SUCCEEDED(orINIT_PARAMETERS_INCORRECTif invalid).void OnTick(): Fires on every incoming quote tick. KeepOnTick()fast and deterministic—avoid heavy file I/O or full-history indicator loops on every single tick.void OnDeinit(const int reason): Fires when removed or shut down. Release indicator handles withIndicatorRelease()in MQL5 and remove chart objects created by your EA.
Essential Safety Patterns Every EA Should Implement
1. New-Bar Execution Guard
Unless your strategy genuinely requires intrabar tick triggers, evaluate indicator entries once per newly closed candle by caching the current bar timestamp (iTime(_Symbol, _Period, 0)) and reading bar index 1 (confirmed close) rather than repainting bar 0.
2. Spread & Broker Stops-Level Protection
Before submitting an order, compare live spread in points against a user-defined ceiling and check the broker's minimum stop distance so orders never trigger error 130 (INVALID_STOPS):
// MQL5 spread and stops-level safety check
int spreadPts = (int)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
int stopsLvl = (int)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
if(spreadPts > InpMaxSpreadPoints) return;
3. Volume Step & Price Normalization
Never pass unrounded floating-point lot calculations directly to an order request. Always round volume to the symbol's SYMBOL_VOLUME_STEP and clamp between SYMBOL_VOLUME_MIN and SYMBOL_VOLUME_MAX, while normalizing prices with NormalizeDouble(price, _Digits). Failing to align volume steps triggers error 131 (INVALID_VOLUME).
// Normalize calculated volume to broker step and limits
double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double lots = MathFloor(rawLots / step) * step;
lots = MathMax(minLot, MathMin(maxLot, NormalizeDouble(lots, 2)));
4. Magic Number Isolation & Hedging vs Netting Awareness
Every open-position loop, breakeven adjuster, and trailing-stop function must filter both PositionGetString(POSITION_SYMBOL) == _Symbol and PositionGetInteger(POSITION_MAGIC) == InpMagic (or OrderSymbol() + OrderMagicNumber() in MQL4) so your robot never modifies manual trades or other EAs.
When writing MQL5 bots for distribution, also inspect AccountInfoInteger(ACCOUNT_MARGIN_MODE) inside OnInit(). If your strategy opens independent long and short grids or multiple concurrent entries with distinct targets, warn the user or abort cleanly when attached to an ACCOUNT_MARGIN_MODE_RETAIL_NETTING account, because netting merges same-symbol entries into one averaged position.
Handling Trade Retcodes, Errors & Order Retries
Live broker execution is never guaranteed to succeed on the first millisecond. Robust MQL4 and MQL5 EAs inspect the server return value (trade.ResultRetcode() in MQL5 or GetLastError() in MQL4) and handle transient errors such as requotes (138 / TRADE_RETCODE_REQUOTE) or busy trade contexts cleanly, while aborting immediately on fatal configuration rejections like invalid stops (130 / 10016), invalid volume (131 / 10014), or insufficient margin (134 / 10019) instead of spamming the broker server in a tight retry loop.
Compiling in MetaEditor & Avoiding AI Coding Pitfalls
Press F4 inside MetaTrader to open MetaEditor, edit your .mq4 or .mq5 file, and press F7 (Compile). Treat every compiler warning—especially implicit type truncation or uninitialized variables—as a real bug to fix before running tests. Enable #property strict at the top of every MQL4 file so the compiler catches outdated implicit type conversions, missing return checks, and undeclared variable scope errors early.
Many traders now prototype bots using AI code generators, which routinely introduce subtle MQL errors:
- Mixing MQL4 & MQL5 Syntax: Using MQL4-only
OrderSelect()or bareAsk/Bididentifiers inside an.mq5file. - Wrong Buffer Order in
CopyBuffer(): ForgettingArraySetAsSeries(buf, true)causes bar index1to read the oldest bar in chart history instead of the most recent closed candle. - Missing Free-Margin & Terminal Trade Checks: Failing to inspect
TerminalInfoInteger(TERMINAL_TRADE_ALLOWED)andAccountInfoDouble(ACCOUNT_MARGIN_FREE)before firing entries. - Infinite Order Loops: Omitting a check for existing open positions on the current bar, causing an EA to fire dozens of duplicate market orders within one second.
- Unvalidated Stop Distances: Calculating stops purely in fixed points without checking
SYMBOL_TRADE_STOPS_LEVELor account currency pip value across cross pairs and XAUUSD.
Always run compiled code in Strategy Tester Visual Mode first and inspect the Experts log to verify every entry, stop, and exit behaves exactly as designed before attaching the EA to even a live-feed demo terminal.
ACTION CHECKLIST
- Create a new EA template in MetaEditor: Open MetaEditor (F4) and use File > New > Expert Advisor (template) to scaffold OnInit, OnDeinit, and OnTick.
- Define clear input parameters: Expose Magic Number, fixed or % risk sizing, Stop Loss, Take Profit, and MaxSpread points cleanly as input variables.
- Implement indicator handles and new-bar logic: Create MQL5 indicator handles in OnInit() and read confirmed closed bars (index 1) via ArraySetAsSeries or MQL4 iTime guards.
- Add spread, stops-level, and lot normalization guards: Validate spread, SYMBOL_TRADE_STOPS_LEVEL, volume steps, and Magic Number filtering before calling OrderSend or CTrade.
- Compile cleanly in MetaEditor: Press F7 to compile the .mq4/.mq5 file into .ex4/.ex5 and resolve zero-error, zero-warning diagnostics.
- Verify in Visual Strategy Tester: Attach the compiled EA in Strategy Tester Visual Mode to confirm accurate signals, stops, and clean Experts logs.