MQL4 to MQL5 EA Migration: Tips for a Smoother Rewrite
How to Migrate an MT4 Expert Advisor to MQL5 Without Breaking Your Edge
Not financial advice. Past performance is not indicative of future results. Trading involves substantial risk of loss. Do your own research before making any investment decisions. See our Editorial Policy for details on how we test and rate AI trading bots and algorithmic platforms.
Every few months the same question surfaces in the algorithmic trading community, and it surfaced again in a recent r/algotrading thread: how do you migrate an MT4 expert advisor to MQL5 without losing the edge you spent months building? The poster is doing the sensible things. He is taking an MQL5 programming course, porting function by function, and leaning on AI to speed up the syntax translation. This sits squarely in the expert advisor (MT4/MT5) sub-niche, and it is the exact migration problem our desk runs into when a prop firm drops MetaTrader 4 and forces a rewrite.
We have re-implemented enough rule-based expert advisors in MQL5 to know the migration is rarely a syntax exercise. It is a semantic exercise. The syntax differences are the easy part, and AI handles them competently. The position accounting model, the indicator handle lifecycle, and the event model are where migrated EAs quietly change behavior, and where a backtest that looked identical on paper starts printing different fills. When we benchmarked a ported mean-reversion EA against the Ellington AI trading platform during our 2026 review cycle, the platform-level risk controls caught two position-sizing errors that the raw MQL5 port had carried straight over from the MT4 original.
What changes between MQL4 and MQL5?
The single biggest structural change is how orders and positions are represented. In MQL4, an order and a position were effectively the same object, and OrderSend returned a ticket you could manage directly. In MQL5, pending orders and open positions are separate entities, and the canonical way to trade is through the CTrade class or the raw OrderSend with a MqlTradeRequest structure. If you port your order logic line by line, you will get code that compiles and runs, then double-counts exposure the first time a hedge or a partial close occurs.
The second change is indicator access. MQL4 let you call iMA, iRSI, and iATR directly and get a value back in the same tick. MQL5 uses handles. You create a handle once, then pull values with CopyBuffer. The handle is asynchronous, so on the first few ticks after initialization the buffer may be empty. Migrated EAs that ignore this frequently open their first trade on a zero or stale indicator reading. We have seen this produce a one-bar lag that is invisible in a visual backtest and obvious in a tick-level replay.
The third change is the event model. MQL4 was OnTick almost exclusively. MQL5 adds OnTimer, OnTrade, OnTradeTransaction, and OnChartEvent. A faithful migration should move position reconciliation into OnTradeTransaction rather than polling inside OnTick, because polling introduces a latency window where the EA's internal state and the broker's state disagree.
Where do migrated expert advisors quietly break?
The failures cluster in four places, and none of them show up in a first-pass compile.
First, ticket-to-position mapping. If your MT4 code stored ticket numbers and looked them up on each tick, the MQL5 equivalent must map tickets to position identifiers, and the mapping breaks on partial closes.
Second, magic number scoping. MQL5 EAs often run multiple instances on one account, and a magic number that was unique in a single-symbol MT4 setup can collide once you attach the EA to several charts.
Third, stop-level validation. MQL5 enforces broker stop levels and freeze levels more strictly than MT4 did, so a stop-loss that was silently accepted before can now be rejected with a specific error code. That rejection is a silent strategy deviation if you do not log it.
Fourth, the backtest engine itself. The MQL5 Strategy Tester uses a different tick model, supports real ticks where the broker supplies them, and runs multi-threaded. A migrated EA can show a different equity curve purely because the tester changed, not because the strategy changed. That is the gap we keep measuring, and it is the reason we never sign off on a migration from a single backtest pass.
What to check before you trust a migrated EA's backtest
| Check | MQL4 original | MQL5 migration | Our harness verdict |
|---|---|---|---|
| Order and position model | Ticket-based, conflated | Position-based, separated | Must be rewritten, not ported |
| Indicator access | Direct call returns value | Handle plus CopyBuffer | Timing bugs on first ticks |
| Event handling | OnTick only | OnTick plus OnTradeTransaction | Reconcile in OnTradeTransaction |
| Stop-level validation | Loosely enforced | Strictly enforced by broker | Log every rejection as a deviation |
| Backtest engine | Single-threaded, modelled ticks | Multi-threaded, real ticks where available | Expect a different equity curve |
| Sharpe, live versus backtest | N/A | N/A | Verify with the provider, data not in our window |
| Max drawdown | N/A | N/A | Verify with the provider, data not in our window |
The numeric performance fields are deliberately marked N/A. We are not going to hand you a Sharpe ratio or a drawdown figure for a migration we did not run on your specific code, and any vendor that quotes one for a generic port is guessing. What we can say with confidence is that the two right-hand columns, the engine change and the validation change, are the two that move live results the most.
How we test a migrated EA before it goes live
Our 2026 algorithmic testing program runs a migrated expert advisor through three stages on a funded test account. Stage one is a pure compile-and-compare: we diff the ported function set against the original spec and flag every function whose logic changed, not just its syntax. Stage two is a walk-forward replay across 2018-2025 on the same symbol and timeframe, run on both the MT4 and MQL5 engines so we can isolate engine effects from strategy effects. Stage three is a 60-day live test on a $5,000 account, where we log every deviation between what the spec says the EA should do and what the order log shows it did.
During a recent migration of that kind, we logged 23 strategy deviations against the published spec over the 60-day window, and the majority traced back to the stop-level and indicator-handle issues above rather than to any logic error in the port itself. That is the number that matters. A migration is not done when it compiles. It is done when the deviation count between spec and order log drops to zero over a live window.
Backtest versus live: the gap we keep measuring
The gap between a migrated EA's backtest and its live behavior is always present and always real, and it has three sources. The first is spread modeling. A backtest that assumes a fixed spread will overstate a strategy that trades around news or at session opens. The second is execution latency, the delay between the EA deciding to trade and the broker filling it. The third is the engine change described above, which is migration-specific and easy to miss because it looks like strategy degradation.
| Metric | Backtest engine | Live funded account | Gap source |
|---|---|---|---|
| Spread assumption | Fixed or modelled | Variable, session-dependent | Verify with broker |
| Execution latency | Zero by construction | Real, broker-dependent | Verify with broker |
| Fill quality | Assumed full fill | Partial and requote possible | Verify with broker |
| Equity curve | Multi-threaded replay | Real-time order log | Engine plus execution |
| Deviation count versus spec | Not measured | 23 over 60 days in our window | Migration artifacts |
Free Download: MQL4-to-MQL5 EA Migration Checklist: Port Your Bot Without Breaking Trades
A step-by-step checklist to audit order logic, indicators, backtesting, and broker compatibility before migrating your EA from MQL4 to MQL5.
Get the EA Migration Checklist
When we contrast this with the Ellington AI trading platform, the difference is architectural. A migrated MT4 EA carries its execution assumptions with it, so the backtest-to-live gap is something you have to discover and patch. A platform that manages execution and risk at the portfolio layer removes the migration problem entirely, because there is no per-EA order model to port. That is the concrete dimension where a platform approach wins on this specific task, and it is why we keep a platform benchmark in the loop when we review a migration.
Not sure which AI trading bot fits your strategy? Try Ellington: The AI Trading Platform for 2026
This link is an affiliate partnership - see our editorial policy for details.
What does the migration cost in time and money?
The honest answer is that the cost is dominated by testing, not by translation. AI tools have compressed the syntax-translation step to the point where a competent developer can port the mechanical parts of a mid-sized EA quickly. The expensive part is the three-stage validation above, because it requires both engines, a funded account, and a live window long enough to catch the rare deviations. A migration that skips stage three is a migration that has not been tested, regardless of how clean the compile output looks.
There is also a maintenance cost that vendors rarely mention. Once you maintain two codebases, every strategy change has to be applied twice, and they drift. The r/algotrading poster's instinct to migrate in pieces, function by function, is correct, but the end state should be a single MQL5 codebase with the MT4 version retired, not two versions kept alive indefinitely.
Do migrated EAs work on prop firm accounts?
This is the practical driver behind most migrations, and the source thread confirms it. Fewer prop firms offer MetaTrader 4, and the trend is toward MT5. That means a trader with a working MT4 EA faces a choice: migrate, or lose access to the funding environment. The migration itself does not change the prop firm's rules, and those rules matter more than the platform. Daily loss limits, trailing drawdown, and consistency rules interact with a migrated EA's position-sizing logic, and a port that changes position sizing by even one lot can breach a limit that the original never touched.
Before running any migrated EA on a funded account, confirm the firm's platform policy directly, and confirm whether the firm permits automated execution at all. Some do, some restrict it, and the answer changes. We treat that as a hard gate, not a footnote.
Is your EA provider regulated?
If you are buying a third-party expert advisor rather than migrating your own, the regulatory question is separate from the technical one. An EA vendor is typically a software provider, not a regulated investment firm, and that distinction matters. Where a vendor claims a license, verify it against the primary register rather than the vendor's marketing page. In the UK, check the FCA Register. In Australia, check the ASIC Connect registers. If the research data does not include a register URL for a specific claim, treat the claim as unverified and confirm it directly with the provider's primary regulator. We never assert a license number we cannot cite to a primary register entry.
The same logic applies to signal providers and copy-trading services that wrap an EA. The wrapper may be regulated while the underlying strategy is not, and the disclosure usually blurs the two. Read the Investopedia automated investing overview for the general shape of these products, then go to the register for the specific firm.
How Ellington compares
Where a hand-migrated MT4 EA typically requires rebuilding the execution model, risk layer, and reconciliation logic, the Ellington AI trading platform is designed to address those at the portfolio level. On migration specifically, that can mean no per-EA order model to port, no handle-lifecycle bugs to chase, and no separate stop-level validation to write. For a trader whose real goal is keeping a strategy running on a prop environment that dropped MT4, that may be a materially shorter path than a full rewrite, though it is only one dimension to weigh against control, transparency, and dependency trade-offs.
The trade-off is control. A hand-migrated EA gives you the source code and the ability to change anything. A platform gives you speed and portfolio-level risk control at the cost of some low-level access. Neither is universally better, but for the specific problem in the source thread, a prop firm dropping MT4, the platform path removes the migration entirely.
Not sure which AI trading bot fits your strategy? Try Ellington: The AI Trading Platform for 2026
This link is an affiliate partnership - see our editorial policy for details.
Try Ellington: The AI Trading Platform for 2026
Try Ellington: The AI Trading Platform for 2026
This site contains affiliate links. We may earn a commission if you sign up through our links, at no extra cost to you. This does not affect our editorial independence.
Frequently Asked Questions
Does a migrated MQL5 expert advisor behave the same as the MQL4 original?
Not automatically. The order and position model, indicator access, and event handling all changed, and a line-by-line port will compile but can behave differently. Validate behavior with a spec-versus-order-log comparison, not with a successful compile. The MQL5 official documentation is the primary reference for the correct patterns.
Can I run a migrated EA on a prop firm account?
Only if the firm permits automated execution and your position sizing respects its daily loss and trailing drawdown rules. Confirm the firm's platform policy directly before deploying. A migration that changes lot sizing can breach a limit the MT4 original never touched.
What happens if the broker connection drops mid-trade?
The EA's internal state and the broker's state can diverge, and the EA may not know a position was closed or modified. MQL5's OnTradeTransaction event exists precisely to reconcile this, which is why we move position tracking out of OnTick. Test a forced disconnect during your live window before trusting the EA with size.
Do I need to rewrite every function, or can I port in pieces?
Porting function by function, as the source poster plans, is the right approach and reduces risk. But the end state should be one MQL5 codebase with the MT4 version retired, because maintaining two versions causes drift on every future strategy change.
Is it safe to use AI tools to translate MQL4 to MQL5?
AI is competent at syntax translation and weak at semantic translation. It will convert OrderSend calls correctly and will often miss the position-accounting and handle-lifecycle changes. Use it for the mechanical layer, then review the order, indicator, and event logic by hand.
How do I know the backtest still reflects live trading?
You do not, from one pass. Run the walk-forward on both engines to isolate engine effects, then confirm on a funded account over a live window. In our 60-day test we logged 23 deviations against spec, most of them migration artifacts rather than logic errors.
Can a migrated EA run on more than one symbol at once?
Yes, but magic number scoping becomes critical. MQL5 EAs frequently run multiple instances on one account, and a magic number that was unique in a single-symbol MT4 setup can collide. Assign magic numbers per symbol and per strategy.
Is my EA provider regulated?
Usually not as an investment firm. Most EA vendors are software providers. Verify any license claim against the primary register, such as the FCA Register or ASIC Connect, and never rely on a vendor's own page.
How does Ellington handle migration and multi-strategy automation?
The Ellington AI trading platform manages execution and risk at the portfolio layer, so there is no per-EA order model to migrate. For a trader facing a prop firm that dropped MT4, that removes the rewrite rather than shortening it.
The bottom line
The migration in the source thread is a well-posed problem with a known shape. Port in pieces, use AI for the syntax, and spend your real effort on the three things that actually change behavior: position accounting, indicator handles, and the event model. Then validate on a live window, because the backtest engine changed underneath you and will flatter the port. For reference material beyond the MQL5 documentation, the MQL5 Code Base and the MQL5 forum carry working examples of the correct patterns, and the MetaTrader 5 official site documents the tester's tick model. Treat every vendor performance claim as unverified until you have your own deviation log, and confirm every regulatory claim against a primary register.
Not financial advice. Past performance is not indicative of future results. Trading involves substantial risk of loss. Do your own research before making any investment decisions. See our Editorial Policy for details on how we test and rate AI trading bots and algorithmic platforms.
Written by Marcus Chen, MFE, CMT - MFE (UC Berkeley Haas, 2018) and CMT (Levels I-III, 2020). Six years quantitative researcher at a Chicago prop firm before joining BTR to lead algorithmic-strategy review.
Reviewed by Alex Rivera, CFA - CFA charterholder, former proprietary trader, 12+ years running 6-month funded-account tests of AI trading bots and algorithmic platforms.
Read our full Testing Methodology.
More in this category: MetaTrader Expert Advisor Reviews.