It now takes a few minutes to get a working Expert Advisor (EA) out of an AI coding assistant. Describe a strategy in plain English, paste the MQL5 into MetaEditor, compile, and run it in the Strategy Tester. For many traders that is a genuine step forward: ideas that used to need a developer can be tested the same afternoon.
But "it compiles and the backtest looks good" is a very low bar. An AI assistant writes code that is plausible, not code that is proven. It can misread your rules, use functions from the wrong language version, skip the error handling that live trading needs, and still produce an equity curve that looks convincing.
This guide covers how to validate an AI-generated EA in four layers: does the code do what you meant, does it trade safely, does it behave correctly in the tester, and does the strategy hold up beyond one backtest.
One point up front: an AI assistant changes how fast you can build an EA. It does not change how much evidence you need before trusting one. If anything, the speed makes validation more important, because it is now easy to generate and test dozens of variations, and that is a fast route to overfitting.
Why AI-written EAs need extra scrutiny
Code from an AI assistant has a particular failure profile. It is usually well formatted, well commented and confident. The mistakes are not typos; they are reasonable-looking choices that happen to be wrong for your strategy, your broker or your platform.
Three things make this harder to catch than a human developer's mistakes:
- It fills gaps silently. If your description is ambiguous ("enter when price breaks the high"), the assistant picks an interpretation without telling you which one. Which high? The current bar, or the last closed bar? Break by how much? On the close, or on any tick?
- It mixes platform versions. A lot of public trading code is MQL4. Assistants sometimes mix MQL4 patterns into MQL5, or the other way round. Some mistakes fail to compile, which is the good outcome. Others compile and behave differently from what you expect.
- It optimizes for looking finished. The code will usually run. Whether it handles a rejected order, a restart, or a broker with different symbol rules is another matter.
Layer 1: Does the code do what you meant?
Start before the code. Write the strategy as a short specification, in numbered rules, with no ambiguity left:
- Entry conditions, including which bar each value is read from.
- Exit conditions: stop-loss, take-profit, trailing logic and time-based exits.
- Position sizing: fixed lots, or risk per trade and how it is calculated.
- Filters: sessions, days, spread limits, news handling.
- Trade management: how many positions at once, and what happens on a new signal while a trade is open.
Then read the generated code against that specification, rule by rule. You do not need to be a professional developer to do this. You need to find, for each rule, the lines that implement it, and check they match. Things to look for:
- Which bar is used. In MQL5, index 0 is the current, unfinished bar. A signal calculated on bar 0 can appear and disappear within the bar. Most rule-based strategies should read completed bars, index 1 and earlier.
- Array direction. Values copied with
CopyBufferorCopyRatesare ordered oldest to newest unless the array is set as a series withArraySetAsSeries. Getting this backwards silently reads the wrong bar. - Indicator handles. In MQL5, functions such as
iMAreturn a handle, not a value. The value comes fromCopyBuffer. Code that treats the handle as a price is a sign of MQL4 habits. - Pip and point size. Five-digit and three-digit quotes mean a "pip" is ten points. A stop written as
20 * _Pointis two pips on many symbols, not twenty. - Anything the specification doesn't mention. Extra filters, hidden martingale sizing or recovery logic you didn't ask for should be removed or explicitly approved.
If the code and the specification disagree, fix the code, or fix the specification and re-generate. Do not move on with a mismatch "to see what happens", because the backtest will then be testing a strategy you did not design.
Layer 2: Does it trade safely?
A live EA has to cope with things a backtest rarely shows. These are the gaps AI-generated EAs most often have.
Acting once per bar, not once per tick
OnTick runs on every price change. If the entry logic runs on every tick, a condition that is true for the whole bar can open several trades. Unless the strategy is genuinely tick-based, run the signal logic once per new bar:
bool IsNewBar()
{
static datetime last_bar = 0;
datetime current = iTime(_Symbol, _Period, 0);
if(current == last_bar)
return false;
last_bar = current;
return true;
}
Valid volumes and stop distances
Brokers set a minimum volume, a maximum volume and a volume step, plus a minimum distance between price and stop levels. Orders that break these rules are rejected. Calculated lot sizes need rounding to the step and clamping to the limits:
double NormalizeVolume(double lots)
{
double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double vmin = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double vmax = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
lots = MathFloor(lots / step) * step;
return MathMax(vmin, MathMin(vmax, lots));
}
Check stop distances against SYMBOL_TRADE_STOPS_LEVEL in the same way.
Checking every trade result
Every order request returns a result code. Code that sends an order and assumes it worked will lose track of its own state the first time an order is rejected or requoted. Look for code that checks the result (for example ResultRetcode() when using the CTrade class) and logs failures clearly.
Knowing its own positions
An EA should identify its own trades with a magic number, and filter by symbol and magic number whenever it counts or closes positions. Without this, two EAs on one account, or one EA on two charts, can close each other's trades. Also check what happens after a terminal restart: the EA should rebuild its state from open positions rather than assume it has none.
Account mode and filling rules
MT5 accounts can be netting or hedging. Code written for one can behave very differently on the other. Order filling modes (fill-or-kill, immediate-or-cancel, return) also vary by broker and symbol, and an unsupported mode means rejected orders.
Layer 3: Does it behave correctly in the tester?
Before looking at any performance statistics, check behaviour.
- Run the visual tester on a few weeks of data and watch individual trades. Do entries happen on the bar the specification says? Are stops and targets placed where they should be?
- Read the journal. Errors such as invalid stops, invalid volume or "not enough money" are often hidden in the log while the summary report looks normal.
- Export the trade list and spot-check it by hand. Pick five trades, open the chart at each entry time and confirm that the rules really were met.
- Look for impossible precision. Entries at the exact low of a bar, or a win rate that seems too good, can mean the code is reading data from a bar that had not finished. That is look-ahead bias, and it makes any backtest unreliable.
- Test in "Every tick based on real ticks" if the strategy uses intrabar stops, targets or trailing logic. Faster modes approximate price movement inside a bar.
- Use realistic costs. Spread, commission and slippage settings that are too kind can make a weak AI-generated strategy look viable.
Only once the EA behaves as specified are its backtest results worth analysing.
Layer 4: Does the strategy hold up beyond one backtest?
This layer is the same for any EA, whoever or whatever wrote it. But AI assistants add one specific risk that deserves its own section.
The prompt loop is an optimizer
A common workflow looks like this: generate an EA, backtest it, tell the assistant what went wrong, generate a new version, backtest again. Ten rounds later the equity curve looks much better.
That loop is optimization, even though no optimizer was switched on. Each round uses the backtest results to change the strategy, so the final version is fitted to the test period just as surely as if you had run a parameter sweep. The more rounds, the more fitted it becomes. The backtest of the final version is no longer an honest test, because the test data shaped the design.
Practical safeguards:
- Hold back data before the first prompt. Decide on an out-of-sample period and never show its results to yourself or the assistant until the design is frozen. Our guide to out-of-sample testing for EAs covers how to set that holdout up.
- Count your iterations. Write down how many versions you tested. Fifty variations and one survivor is very different evidence from one design that worked first time.
- Prefer simple rules. Each extra condition the assistant adds to "fix" a bad period is another way to fit noise, and a growing list of special-case filters is one of the classic signs of an overfit backtest.
- Run walk-forward testing on the frozen design, then Monte Carlo and parameter-sensitivity checks, exactly as you would for hand-written code.
Robustness checks to run
- Walk-forward analysis across several windows, looking at the trend in out-of-sample results, not only the average.
- Monte Carlo resampling of the trade list to see the plausible range of drawdowns.
- Parameter sweeps around each input, looking for plateaus rather than spikes.
- A cost stress test with wider spreads and added slippage.
- If the EA is intended for a prop-firm account, a check of its behaviour against that account's specific rules, such as daily loss limits and maximum drawdown.
Common mistakes with AI-generated EAs
- Trusting the code because it compiled. Compilation proves syntax, not logic.
- Never writing a specification. Without one, there is nothing to check the code against, and the assistant's interpretation becomes the strategy.
- Accepting extra features you didn't ask for. Hidden grid, martingale or recovery logic can change the risk profile completely.
- Fixing results instead of rules. Asking the assistant to "make the drawdown smaller" invites it to fit the test period.
- Skipping the journal and the trade list. The summary report hides errors and logic bugs that are obvious trade by trade.
- Going straight from backtest to a funded challenge. A demo forward test catches execution problems that no backtest shows.
A short validation checklist for AI-written EAs
- Written specification with numbered, unambiguous rules
- Code checked against the specification, rule by rule, with no unexplained extra logic
- Signals read from completed bars, with array direction confirmed
- Logic runs once per new bar unless the strategy is genuinely tick-based
- Volumes normalized to the broker's step and limits, stops checked against the minimum distance
- Every order result checked and logged; positions filtered by symbol and magic number
- Visual tester run and five trades spot-checked by hand against the chart
- Out-of-sample data held back from every prompt-and-test iteration
- Walk-forward, Monte Carlo, parameter and cost stress tests run on the frozen design
- Demo forward test before any funded or live account
Frequently asked questions
Can an AI assistant write a profitable EA?
It can write an EA that implements a strategy you describe. Whether that strategy has an edge is a separate question, and the assistant cannot answer it. Neither can a single backtest. Only careful out-of-sample testing gives you evidence, and even that does not guarantee future results.
Is AI-generated MQL5 code safe to run on a live account?
Not without review. The most common problems are missing error handling, incorrect volume or stop calculations, trading on every tick, and confusion between MQL4 and MQL5 patterns. Review the code against a written specification and run it on a demo account first.
Should I ask the AI to optimize my strategy's parameters?
Treat any repeated cycle of "test, ask for changes, test again" as optimization. If you do it, hold back an out-of-sample period beforehand and judge the final design only on that untouched data.
How do I check an AI-written EA if I can't read code well?
Write a clear specification, then use the visual tester and the exported trade list to confirm that real trades follow your rules. Spot-checking trades against the chart catches many logic errors without reading every line of code. For anything beyond that, an independent review is worth considering.
Does the validation process differ from a hand-coded EA?
The robustness tests are the same. The difference is emphasis: AI-generated code needs more checking of what the code actually does, and AI-assisted workflows need more discipline about how many variations were tested.
Want a second pair of eyes?
Start with our free Sample Stress-Test Report. It walks one anonymized, illustrative strategy through a full stress test, start to finish, so you can see what rigorous validation looks like before you test your own.
Read the Sample Stress-Test ReportWant your own backtest checked? The Strategy Audit + 60-minute call is a paid service at a launch price of £100, credited in full against our build and portfolio offers. You send an MT4/MT5 Strategy Tester report or trade-list CSV; what we can check depends on the files you supply, and walk-forward and parameter sweeps are not included because they need the strategy itself. It is analysis of strategy testing, not investment advice, and does not promise any trading or evaluation outcome. See the Strategy Audit
Disclaimers
CollosoTrading provides educational content and analytical services for retail and professional algorithmic traders. We do not provide regulated investment advice, financial advice, or personal recommendations. Trading derivatives, leveraged products, and CFDs carries a high level of risk and may result in losses exceeding deposits. Past performance, including any verified or unverified historical results referenced on this site, is not indicative of future results. Consult an independent regulated financial adviser before making investment decisions.
All figures are backtests or simulations unless marked LIVE. Hypothetical or backtested performance results have inherent limitations and may not reflect actual trading. No representation is made that any account will or is likely to achieve profits or losses similar to those shown. Individual results vary. This article contains no performance figures from any strategy or account. We do not guarantee the outcome of any prop firm challenge.