MT5 Lab

Build a Testable MT5 EA with AI: MQL5 Specs and Prompts for Codex or Claude

Turn an MT5 strategy idea into a testable MQL5 specification for Codex or Claude Code, with risk limits, recovery rules, evidence, and validation gates.

한국어 원문 읽기

Key takeaways

Before asking AI for an EA, define the market hypothesis, execution environment, trading rules, risk limits, and validation gates.

Make the coding agent surface ambiguity before implementation, then trace every requirement into code, tests, and observable logs.

Compilation and a profitable backtest are not completion criteria; the human decides whether to adopt, revise, or reject a version from reproducible evidence.

Give AI a testable MT5 EA specification, not a request for profit

Key takeaways

  • “Build me a profitable EA” omits the market, timeframe, entry and exit definitions, costs, loss limits, and failure policy required for a reproducible test.
  • The human owns the hypothesis and acceptable risk. AI can surface ambiguity, implement MQL5, draft test scenarios, and review the resulting change.
  • The success criterion is not a long source file or an attractive backtest. It is an evidence chain that connects a frozen specification to code, signals, requests, orders, deals, and test results.

How to Recover MT5 EA State After Restart or Reconnect addressed what an EA should do after its process state disappears: reconcile server-side exposure, block duplicate entries, and lock when account state cannot be explained. This lab moves one step earlier and asks a different question: what exactly should you ask an AI coding agent to build?

Codex and Claude Code can help inspect a repository, produce changes, and use available commands or tests. They cannot decide which market hypothesis you are willing to test, what loss is acceptable for your account, or which backtest failure should end the experiment.

OpenAI's Codex best-practices guide opens in a new tab recommends giving important tasks a goal, relevant context, constraints, and a definition of done. Anthropic's Claude Code best practices opens in a new tab similarly emphasize exploring and planning before implementation and giving the agent a concrete way to verify its work. For an MT5 EA, those general ideas become a strategy specification, order-safety constraints, Strategy Tester configuration, and stop criteria.

“Use Bollinger Bands and RSI” leaves the strategy undefined

The following request communicates an idea, but not an implementation contract.

Build a profitable MT5 EA that trades with the
upper and lower Bollinger Bands together with RSI.

An AI can fill the gaps and produce plausible code. The hidden choices are the problem: an unapproved Bollinger period, RSI threshold, current-bar read, or stop rule can quietly become part of the program. A backtest of that program may produce numbers, but you still cannot state which hypothesis was tested.

Missing questionPossible choicesFailure created by silence
Market hypothesisMean reversion after a band excursion, or trend continuationThe same indicators can produce opposite strategies
Signal priceHigh/low touch, close outside, or close back insideEntry timing and trade count change materially
RSI rule30/70, 20/80, threshold entry, or threshold exitThe agent invents a value and comparison direction
Bar boundaryForming bar or last completed barA forming-bar signal can change or disappear
Submission timeSignal-bar close or first eligible tick of the next barBacktest and live execution use different price boundaries
ExitMiddle band, opposite band, time limit, or SL/TPPosition duration can dominate the result
RiskFixed volume or stop-distance risk budgetThe same Inputs create different account risk
EnvironmentSymbol, timeframe, netting/hedging, and costsThe same source behaves differently across servers

Asking the agent to find “the best values” does not fix this. Repeatedly testing many combinations on one historical interval and retaining the highest result can fit that interval's accidents rather than a durable market behavior. Freeze one falsifiable hypothesis and one baseline before optimization.

Separate the responsibilities of the human, AI, and MT5

If the same AI is treated as strategist, implementer, tester, and final approver, there is no clear point of responsibility. A useful boundary looks like this.

ActorResponsible forNot responsible for
HumanMarket hypothesis, acceptable loss, prohibited behavior, pass and stop criteriaAutomatically approving assumptions that are not understood
AI coding agentAmbiguity review, requirements structure, MQL5 implementation, test scenarios, code reviewProving future performance or choosing tolerable loss for the operator
MetaEditor and MT5Compiler output, Strategy Tester report, Journal, order/deal/position evidenceDeciding the economic meaning of the result
Separate reviewMissing requirements, spec-to-code mismatch, regression riskTreating agreement between two models as completed validation

You can implement with Codex and review with Claude Code, reverse those roles, or start a clean review session with the same tool. The brand order is less important than giving the reviewer the original specification, the actual diff, and execution evidence. “The code looks correct” is not evidence that an MT5 order path ran correctly.

Write a one-page EA contract first

The specification does not need to be long. It needs to use statements that can pass or fail. Requirement IDs make it easier to trace each decision into a function, log field, and test.

IDHuman decisionExample evidence
ENV-01Demo account, exact symbol, timeframe, and account modeRuntime log and Tester settings
HYP-01Market behavior being tested and explicit non-goalsFrozen spec version and prior hypothesis
SIG-01Completed-bar entry rule and evaluations per boundarySignal timestamp and bar time
EXIT-01Normal exit, SL/TP, and maximum holding periodOrder, deal, and position history
RISK-01Volume calculation, per-trade/daily loss limits, maximum exposureSizing log and requested volume
GUARD-01Prohibited behavior under spread, permission, or data failuresLog explaining why no request was sent
STATE-01Restart, existing exposure, and duplicate-runtime policyRECOVERING, READY, and LOCKED transitions
LOG-01Fields connecting a signal to request, retcode, deal, and positionEvidence tied to one observation ID
TEST-01Backtest/demo pass, hold, and immediate-stop conditionsDecision table written before results

A threshold such as “maximum drawdown below 10%” is not meaningful by itself. The date range, initial deposit, costs, sizing rule, and test data must be frozen with it. Separate software-safety gates from performance gates as well. A profitable run with a duplicate request or a missing required Stop Loss is still a functional failure.

Make the first prompt prohibit coding

At the idea stage, the first useful deliverable is a question list—not an .mq5 file. The prompt below uses a Bollinger Bands and RSI idea, but the same structure can be adapted to another signal family.

Act as an MQL5 EA requirements reviewer, not as an implementer yet.

Goal:
- Turn a Bollinger Bands plus RSI idea for an educational MT5 EA
  into a reproducible strategy specification and test plan.
- Do not write code in this step.

Current idea:
- Combine the upper/lower Bollinger Bands with RSI overbought/oversold states.
- Validate only in Strategy Tester and an isolated demo account.
- Do not target a promised return or live-account deployment.

Areas you must resolve:
1. Market hypothesis and trade direction
2. Indicator periods, applied price, buffer shift, and completed-bar boundary
3. Entry, exit, SL/TP, and maximum holding time
4. Position sizing and per-trade/daily loss limits
5. Symbol, timeframe, account mode, and trading costs
6. Prohibited behavior under high spread, missing data, denied permissions,
   or pre-existing exposure
7. Restart behavior, duplicate signals, Magic Number scope, and reconciliation
8. Logs and pass/stop criteria for backtest and demo forward test

Rules:
- Do not fill missing values from convention or guesswork.
- Do not promise profitability or optimize parameters yet.
- Flag platform behavior that must be checked against official MetaTrader/MQL5 docs.
- Stop before implementation if two answers conflict.

Output:
A. Questions that require a human answer
B. Current assumptions and unverified items
C. Draft ENV/HYP/SIG/EXIT/RISK/GUARD/STATE/LOG/TEST requirements
D. Normal, boundary, and failure test scenarios
E. Human decisions needed for pass and stop criteria

Do not approve the first option merely because the agent suggested it. A lower-band “touch” can mean low <= lowerBand, close <= lowerBand, or a re-entry condition such as close > lowerBand after an excursion. Those are different strategies. The final signal statement should be precise enough to become one MQL5 boolean expression.

Freeze the answers before requesting implementation

Once the ambiguity review is complete, do not leave the chat transcript as the only source of truth. Write a short, versioned specification.

spec_version: 0.1.0
purpose: educational mean-reversion hypothesis test
environment: [demo server / symbol / timeframe / account mode]
hypothesis: [one falsifiable sentence]
signal: [exact completed-bar boolean condition]
entry: [submission boundary and permitted direction]
exit: [normal exit, SL/TP, time exit]
risk: [volume calculation, maximum exposure, loss limits]
guards: [conditions under which no request is allowed]
state: [position ownership, restart behavior, duplicate prevention]
logging: [fields linking signal/request/order/deal/position]
test: [normal/failure scenarios and decision gates]

The implementation prompt can now name the input document, constraints, outputs, and completion criteria.

Implement the attached EA specification v0.1.0 in MQL5.

Before implementation:
- Report contradictions, missing decisions, and requirements that cannot be
  implemented directly in MQL5.
- If any item remains unresolved, ask questions and do not write code yet.

Implementation constraints:
- This is educational code for Strategy Tester and demo use only.
- Calculate every signal only at the completed-bar boundary named in the spec.
- Submit at most one request for a signal boundary.
- Never modify or close a position or order that the EA does not own.
- Validate symbol properties and request preconditions before submission.
- Do not treat a trade function's boolean return as proof of a completed fill.
- Log retcode, order, deal, position, and the reason for every rejected path.
- After restart, block new requests until account reconciliation succeeds.

Deliverables:
1. Complete compilable .mq5 source
2. Traceability table from requirement ID to function, log, and test
3. Inputs list with units
4. MetaEditor compilation and Strategy Tester procedure
5. Normal, boundary, and failure scenarios
6. Known limitations and unverified assumptions

Done when:
- Every requirement is linked to code or an explicit unimplemented item.
- The procedure shows how to confirm 0 errors and 0 warnings.
- Another tester can repeat the run with the same source version and Inputs.

The official OrderSend reference opens in a new tab notes that a true return does not by itself mean that a market request has completed as a fill. The server retcode must be inspected, and later state should be tracked through order, deal, and position events described in OnTradeTransaction opens in a new tab. Putting that constraint in the prompt helps prevent an implementation from ending its proof at if(trade.Buy(...)) success.

Keep compilation, function, and strategy performance as separate gates

A compiled EA has passed a language and build check. It has not yet passed order-safety or market-hypothesis validation.

GateQuestionPassing evidence
SpecificationDoes every condition have one interpretation?Approved spec version with no unresolved items
CompilationDoes the source build in the recorded MetaEditor?Terminal build record and 0 errors, 0 warnings
FunctionDo signal, order, exit, and risk limits follow the rules?Normal, boundary, and failure logs
StateDoes restart or existing exposure avoid a duplicate request?Reconciliation and runtime-state evidence
BacktestWhat happened on the frozen historical setup?Settings, report, Journal, and source version
Forward demoDoes the current demo environment reveal an operational defect?Forward-test observation record
DecisionIs there enough evidence to retain, revise, or reject the hypothesis?Human decision and next test

The official MQL5 Strategy Tester reference opens in a new tab distinguishes Every tick, 1 Minute OHLC, and Open prices only modeling. A quick new-bar logic check and a test where intrabar band contact or stop ordering matters do not require the same fidelity. Record the modeling mode and why it was selected instead of writing only “backtest complete.”

If the coding agent cannot access an environment with MT5 installed, do not let it claim to have compiled or backtested the EA. Ask for exact manual steps, execute them in MetaEditor and Strategy Tester, and return the real report and Journal to the review loop.

Keep code, Inputs, and evidence in one version bundle

Overwriting final.mq5 removes the ability to explain which change affected the result. Even a small experiment benefits from a complete bundle.

v0.1.0-baseline/
  strategy-spec.md
  BollingerRsiEA.mq5
  baseline.set
  tester-config.md
  tester-report.html
  journal.txt
  decision.md

Names such as v0.2.0-trend-filter and v0.3.0-risk-cap can preserve the purpose of later revisions. If one version changes the indicator periods, entry rule, stop, and session at once, the cause of the result is no longer attributable. Change one central hypothesis per version and keep the remaining test setup fixed.

Use a prompt like this when requesting a revision.

Compare baseline v0.1.0 with the approved improvement requirement.

- State the causal hypothesis connecting the observed failure to this change.
- Modify only the minimum scope required by that requirement.
- Map changed requirement IDs to code locations.
- Add the new scenario and retain the existing regression scenarios.
- State both the metrics that may improve and the conditions that may worsen.
- Provide rerun steps using the previous Tester configuration.
- Do not describe performance as improved before seeing the new result.

Version control is not a method for retaining only successful runs. Preserve failed versions and rejection reasons so the same idea is not repeated later under a different filename.

Ask AI to find evidence, not make the final decision

“Did you build this correctly?” invites the implementer to repeat its own explanation. A review request should include the approved specification, source diff, compiler output, and test evidence, then ask for requirement violations first.

This is a review task. Do not modify files.

Inputs:
- Approved EA specification and requirement IDs
- Diff between baseline and current source
- MetaEditor compiler result
- Strategy Tester configuration, report, and Journal

Review order:
1. Trace each requirement to implementation and identify omissions.
2. Find forming-bar reads, duplicate-signal paths, and ownership errors.
3. Check request preconditions, retcodes, partial fill/timeout handling,
   and restart reconciliation.
4. Check whether normal, boundary, and failure scenarios have real evidence.
5. Do not infer performance or causes absent from the report.

Output:
- Severity / requirement ID / code or log evidence / reproduction / fix direction
- Items that could not be verified
- Questions the human must answer before adoption

An issue reported by AI is another hypothesis until a code location, official reference, reproduction log, or new test confirms it. Conversely, a review that finds no issue does not establish that the EA is safe.

Prepare the complete backtest package for the next AI turn

A profit number or a graph screenshot is not enough context for backtest analysis.

Evidence to provideWhy it matters
Spec, source, and Inputs versionsFreezes which strategy was tested
MT5 terminal build and operating systemRecords execution-environment differences
Broker/server context, account mode, symbol specificationExposes contract and position-accounting differences
Timeframe, date range, and modeling modeDefines the data and simulation boundary
Spread, commission, and swap assumptionsPrevents a cost-free interpretation
Full report and JournalConnects performance, drawdown, trade distribution, and errors

Tell the analyst not to invent missing figures or causes and to separate observed facts, plausible interpretations, and hypotheses that require another test. A strong net result or Profit Factor may still be weak evidence when the trade count is small, a few trades dominate the outcome, or performance exists only in one interval. The reading order in How to Read an MT5 Strategy Tester Report applies unchanged.

Frequently asked questions

Is Codex or Claude Code better for an MT5 EA?

The product name is not enough to decide. Give each tool the same specification, repository context, permissions, and verification criteria, then compare omissions, compiler results, detected defects, and the resulting diff. One tool can implement and another can review, but the MT5 run remains the evidence.

Can AI propose the strategy idea first?

It can help generate candidate hypotheses and counter-hypotheses. The human still selects the data boundary, acceptable risk, and validation gate and freezes the baseline before inspecting results. A model proposal is not market evidence.

Does a detailed prompt remove implementation bugs?

No. A precise specification reduces ambiguity and makes review easier, but logic defects, platform differences, and data problems remain possible. Compilation, scenario tests, historical tests, and demo forward tests are separate checks.

Can I use an AI-generated EA without knowing MQL5?

AI can help create and explain educational source, but you should at least be able to state the entry and exit rules, volume and Stop Loss policy, Magic Number scope, result logs, and stop procedure. Unexplained behavior is a reason not to advance to live-account review.

Can I adopt an improvement as soon as its backtest is better?

If the same historical interval was used to propose, implement, and score the change, the revision may be adapted to that interval. Recheck a held-out period and a demo forward test, and compare against the unchanged baseline under the same setup.

Risk note

AI-generated or AI-reviewed MQL5 can contain logic errors, request-handling defects, incorrect units, and missing market conditions. Compilation, a historical backtest, and a demo run do not establish future performance. Automated software can repeat a faulty rule or request, and leveraged products can generate rapid and substantial losses.

This lab is educational and does not recommend an AI product, broker, instrument, indicator combination, parameter set, or trade. Do not put account passwords, API keys, identity documents, or complete account numbers in prompts, repositories, or logs. Validate code in Strategy Tester and an isolated demo environment first.

Up next

Continue with Using AI to Evaluate an MT5 Strategy: Bollinger Bands, RSI, and Backtest Iteration. It omits the source listing and focuses on the prompts that freeze a baseline and the follow-up question for each type of backtest result.

The guide covers AI-assisted analysis of Profit Factor, equity drawdown, sample size, and long/short asymmetry, then narrows trend, volatility, session, and spread controls into one-change experiments for comparing v0.1.0 with v0.2.0.