Technical & Risk GuidesAdvanced12 min read

EXPERT ADVISOR CODING IN MQL4 & MQL5: ARCHITECTURE, RISK GUARDS & COMPILATION

Learn Expert Advisor coding in MQL4 and MQL5: OnInit/OnTick event lifecycle, OrderSend vs CTrade, new-bar guards, spread filters, compiling in MetaEditor, and AI coding pitfalls.

By YoForexEA Research Desk

Quick Summary

Expert Advisor coding uses MQL4 for MetaTrader 4 (.mq4 to .ex4) and MQL5 for MetaTrader 5 (.mq5 to .ex5). Reliable EAs structure logic cleanly across OnInit(), OnTick(), and OnDeinit(), read confirmed closed candles, filter spread and broker stops levels, normalize lot steps, and compile cleanly in MetaEditor without warnings.

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 user input values, set Magic Numbers (trade.SetExpertMagicNumber(InpMagic) in MQL5), initialize indicator handles, and return INIT_SUCCEEDED (or INIT_PARAMETERS_INCORRECT if invalid).
  • void OnTick(): Fires on every incoming quote tick. Keep OnTick() 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 with IndicatorRelease() 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 bare Ask/Bid identifiers inside an .mq5 file.
  • Wrong Buffer Order in CopyBuffer(): Forgetting ArraySetAsSeries(buf, true) causes bar index 1 to 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) and AccountInfoDouble(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_LEVEL or 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

  1. Create a new EA template in MetaEditor: Open MetaEditor (F4) and use File > New > Expert Advisor (template) to scaffold OnInit, OnDeinit, and OnTick.
  2. Define clear input parameters: Expose Magic Number, fixed or % risk sizing, Stop Loss, Take Profit, and MaxSpread points cleanly as input variables.
  3. 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.
  4. 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.
  5. Compile cleanly in MetaEditor: Press F7 to compile the .mq4/.mq5 file into .ex4/.ex5 and resolve zero-error, zero-warning diagnostics.
  6. Verify in Visual Strategy Tester: Attach the compiled EA in Strategy Tester Visual Mode to confirm accurate signals, stops, and clean Experts logs.

FREQUENTLY ASKED QUESTIONS

Should I learn MQL4 or MQL5 for Expert Advisor coding?

Learn MQL5 if you are starting fresh. MQL5 supports multi-asset instruments, 64-bit multi-threaded optimization, built-in real-tick backtesting, and modern object-oriented trade classes via CTrade, while MT4 remains maintenance-focused.

Can an .mq4 source file be compiled directly for MetaTrader 5?

No. MQL4 uses different order management functions and indicator calls than MQL5. You must adapt order placement to CTrade/PositionSelect and indicator reads to handles plus CopyBuffer().

What causes an EA to open dozens of trades on the exact same candle?

Because OnTick() runs on every incoming price quote, omitting a new-bar check or forgetting to filter existing open trades by Magic Number and Symbol makes the EA re-trigger on every tick.

What is the #1 bug in AI-generated MQL5 Expert Advisors?

AI code frequently forgets ArraySetAsSeries(buffer, true) after CopyBuffer() or mixes MQL4 OrderSelect/Ask variables into MQL5, reading wrong candle indices or failing compilation.

EXPLORE RELATED EA HUBS

MT5 Expert Advisors →MT4 Expert Advisors →AI Trading EAs →

CONTINUE READING

EXPLORE VERIFIED EXPERT ADVISORS

Browse MT4 and MT5 bots, indicators, and setup resources across YoForexEA.

Browse EAsAll 18 Guides