MT5 Lab

Using AI to Evaluate an MT5 Strategy: Bollinger Bands, RSI, and Backtest Iteration

Turn a Bollinger Bands and RSI idea into an AI-ready MT5 specification, analyze backtest evidence, and use result-specific prompts to compare strategy versions.

한국어 원문 읽기

Key takeaways

The first prompt should expose missing decisions about Bollinger Bands, RSI, completed bars, execution, exits, and risk—not ask for a profitable strategy.

Give the AI the full tester context and require it to separate observed facts, plausible interpretations, and hypotheses that need another test.

Use a different follow-up for each result pattern, change one core hypothesis per version, and compare the baseline and revision under the same conditions.

Ask AI a different question for each Bollinger–RSI backtest outcome

Key takeaways

  • Do not supply only the names Bollinger Bands and RSI. Make the AI clarify the completed bar, band touch or break, RSI boundary, order timing, exit, and risk limits first.
  • When asking for report analysis, prohibit invented figures and causes and require a separation between observed facts, plausible interpretations, and testable hypotheses.
  • A profitable but tiny sample, high drawdown, long/short asymmetry, and out-of-sample failure are different observations and require different follow-up prompts and experiments.

How to Prompt AI to Build a Verifiable MT5 EA introduced a general structure for turning a loose idea into a testable specification. This article applies that structure to a Bollinger Bands and RSI mean-reversion hypothesis.

There is no MQL5 source listing in this article. No actual Strategy Tester report was supplied either, so the examples do not invent returns, Profit Factor, or drawdown and then claim that a revision worked. The purpose is to show what to ask first, what to ask after each type of result, and how to compare the next version.

OpenAI's prompting guidance opens in a new tab recommends supplying the goal, useful context, desired output, and boundaries for consequential work, including a direction to flag missing information instead of guessing. Applied to strategy research, that becomes hypothesis → ambiguity review → implementation request → backtest evidence → focused follow-up → one controlled change.

Freeze the strategy sentence before requesting code

“Buy at the lower Bollinger Band when RSI is oversold” may sound precise to a person, but it is not an EA specification. A low touching the band, a close outside it, and a close returning inside after a break create different signals and trade samples.

The official MQL5 iBands reference opens in a new tab takes an averaging period, shift, deviation, and applied price and exposes the base, upper, and lower bands. The iRSI reference opens in a new tab likewise requires a calculation period and applied price. Naming the indicators therefore does not finish even the calculation rules.

TermMeaning in this workflowDecision to make explicit
Middle bandThe average line around which the bands are formedExit target, direction filter, or neither
Upper and lower bandsBoundaries at the selected deviation from the baseHigh/low touch, close outside, or re-entry
RSI boundaryA candidate definition of an extreme readingEntry into the zone or return from it
Completed barThe previous bar whose OHLC no longer changesWhether the forming bar is excluded
Signal timeWhen the rule becomes trueWhether it is evaluated once per bar
Order timeWhen the EA is allowed to submit a requestNext eligible tick or another rule
BaselineThe unchanged reference for later comparisonsWhich values and test settings are frozen

Example values are a starting point, not a recommendation

The table below is an educational baseline for the AI conversation. The familiar-looking 20 and 2.0 or 14 and 30/70 values are not evidence that the setup is suitable for a particular instrument or timeframe. The bracketed fields remain human decisions.

FieldEducational baseline v0.1.0
HypothesisTest whether a short mean reversion sometimes follows a close outside a band with RSI in an extreme zone
Instrument and timeframe[enter explicitly]
Bollinger BandsClose price, period 20, deviation 2.0, shift 0
RSIClose price, period 14, lower boundary 30, upper boundary 70
Long candidatePrevious completed bar closes at or below the lower band and RSI is at or below 30
Short candidatePrevious completed bar closes at or above the upper band and RSI is at or above 70
EntryFirst eligible order point on the next bar, at most once per signal
ExitDefine precedence among middle-band exit, protective Stop Loss, and maximum holding time
Risk[define volume calculation, risk per trade, and daily loss boundary]
Concurrent exposureConsider at most one position owned by this EA as the initial constraint

Do not optimize these values yet. First establish that the baseline creates exactly the intended trades. Repeatedly changing periods and boundaries after looking at the same result can make the selected history, rather than the market hypothesis, dominate the outcome.

Make the first prompt ask questions, not write code

The first request should expose decisions that have not been made. Replace the bracketed fields with details from the intended test environment.

Act as an MT5 strategy requirements reviewer. Do not write code yet.

Goal:
- Turn a Bollinger Bands and RSI mean-reversion idea into a reproducible
  EA specification and backtest plan.

Current baseline:
- Instrument/timeframe: [enter]
- Bollinger Bands: close, period 20, deviation 2.0, shift 0
- RSI: close, period 14, boundaries 30/70
- Long candidate: previous completed bar closes at or below the lower band
  and RSI is at or below 30
- Short candidate: previous completed bar closes at or above the upper band
  and RSI is at or above 70
- Entry: first eligible order point on the next bar, at most once per signal
- Exit, Stop Loss, holding time, and position sizing: undecided

Boundaries:
- Do not fill missing values from convention or guesswork.
- Treat band touch, close outside, and return inside as different conditions.
- Distinguish the completed bar from the currently forming bar.
- Do not promise profitability or propose optimal parameters.
- Include questions about data, costs, order safety, and risk limits.

Output:
1. Questions that must be answered before implementation
2. Statements that currently permit more than one interpretation
3. Human choices and how each choice changes the experiment
4. A draft v0.1.0 specification split into confirmed and unresolved items
5. Pass, hold, and stop criteria to define before the backtest

The AI's questions should cover at least these areas.

AreaCommonly omitted question
DataWhat exact instrument, timeframe, date range, and modeling mode will be used?
SignalMust both indicators qualify on the same completed bar?
RepetitionIf the condition persists for several bars, can the EA re-enter?
ExitWhat is the precedence among middle band, opposite signal, Stop Loss, and time exit?
CostsHow are spread, commission, swap, and execution delay recorded?
RiskHow are stop distance and volume calculated, and where is loss capped?
OwnershipHow are existing positions and orders from another EA distinguished?
FailureDoes missing indicator data or a rejected request block another entry?

If the model silently decides that “20 and 2 are generally best,” reject that shortcut. Ask it to label each value as either an explicitly approved baseline or a decision supported by named evidence.

Request implementation from the approved specification

After answering the questions, freeze the specification as v0.1.0. A coding agent can then implement it. The following is the implementation prompt; the generated source is deliberately not reproduced here.

Implement the approved Bollinger-RSI strategy specification v0.1.0 as an MQL5 EA.

Context:
- The attached specification is the only strategy authority.
- The EA will be evaluated only in Strategy Tester and an isolated demo environment.

Boundaries:
- Do not add parameters or trading rules that are absent from the specification.
- Stop and ask if the specification contains a contradiction or unresolved item.
- Keep completed-bar signal evaluation separate from order timing.
- Do not submit duplicate requests for one signal.
- Do not alter positions or orders that the EA does not own.
- Log request outcomes, rejection reasons, and state transitions for verification.

Deliverables:
1. A compilable MQL5 EA
2. A traceability table from specification items to implementation locations
3. Inputs with units and meaning
4. MetaEditor compilation and Strategy Tester instructions
5. Normal, boundary, and failure test cases
6. Unimplemented or unverified assumptions

Done when:
- Every specification item maps to implementation or an explicit gap.
- Another tester can repeat the run with the same version and Inputs.
- Do not claim compilation or a backtest was completed if you could not run it.

Even if the source is difficult to review, ask the AI to reverse-explain every entry and exit in plain language and show only discrepancies from the approved specification. That does not replace MetaEditor compilation, a visual run, or Journal review. Freeze the first test with How to Backtest an Expert Advisor in MT5.

Learn the report terms before reviewing the AI's analysis

An AI analysis is not automatically correct. The user should be able to distinguish at least the terms below. The official MetaTrader 5 Testing Report reference opens in a new tab documents how these report fields are calculated.

TermWhat it describesRead it together with
Total Net ProfitThe combined financial result of all tradesInitial deposit, costs, and concentration in a few trades
Profit FactorGross profit relative to the magnitude of gross lossTrade count, stability across periods, and outlier winners
Expected PayoffThe statistically calculated average result per dealSpread, commission, dispersion, and sample size
Balance DrawdownPeak-to-trough decline based on closed resultsClosing behavior and any deposits or withdrawals
Equity DrawdownPeak-to-trough decline including open profit and lossLoss carried while positions were still open
Recovery FactorGained profit relative to the report's maximum drawdownTime to recover and the distribution of trades
Total TradesThe sample of trades that fixed a profit or lossLong/short counts and distribution through time
Consecutive LossesThe longest loss sequences and their amountVolume, daily loss controls, and operational tolerance
Balance vs Equity GraphClosed-result and open-equity paths through timePeriods where the lines separate sharply
In-sampleThe development interval used to choose or adjust the ideaHow many decisions were made after viewing it
Out-of-sampleA held-out interval not used for selection or tuningWhether it stayed untouched after inspection
OverfittingExcess adaptation to quirks and noise in historical dataCollapse after small parameter or date changes

A high Profit Factor supported by very few trades can be weak evidence. Positive net profit can coexist with an equity decline that exceeds the user's predefined risk boundary. A smooth balance line alongside volatile equity can indicate that open losses were carried for a long time. One statistic does not substitute for another.

The MQL5 Strategy Tester reference opens in a new tab distinguishes Every tick, 1 Minute OHLC, and Open prices only, which construct different tick paths. When intrabar band touches, protective stops, or exit order matter, a result from a coarse modeling mode is not the final comparison.

Give AI the complete report with an analysis contract

A single screenshot is weaker context than the specification, tester settings, Inputs, full report, Journal, and trade list together. Remove passwords, API keys, full account numbers, and personal identifiers first.

Act as an independent MT5 backtest analyst.

Inputs:
- Strategy specification: v0.1.0
- EA source version or commit: [enter]
- Tester settings: instrument, timeframe, dates, deposit, leverage,
  modeling mode, spread, commission, swap, and delay
- Inputs file or complete list
- Full Strategy Tester report
- Journal and trade list
- Explicit development and untouched holdout intervals

Analysis rules:
- Do not invent missing figures, order causes, or market regimes.
- Validate tester errors, data, costs, and settings before performance.
- Separate observed facts, plausible interpretations, and hypotheses to test.
- Do not evaluate the strategy from net profit alone.
- Split results by long/short, time interval, session, exit reason,
  and consecutive-loss cluster where the supplied data permits it.
- Do not choose improvement parameters yet.

Output:
1. Whether the run is interpretable and what information is missing
2. A core-metrics table and what each metric cannot establish
3. Contributions and loss concentrations by direction, period, time, and exit
4. Observed facts
5. Plausible interpretations
6. At most three falsifiable hypotheses for the next test
7. Current disposition: retain for observation / pause analysis / reject candidate

A useful response does not begin with “change RSI to 28.” It first establishes an observation such as “most of the result came from a small set of long trades in one interval,” then proposes a test that can distinguish a directional effect from chance.

Use a different follow-up for each result pattern

Without an actual report, universal pass figures cannot be set here. What can be prepared in advance is a question for each observed pattern. Attach the report values and trade list before using these prompts.

Observed patternPremature conclusion to avoidFollow-up focus
Net profit and Profit Factor look strong, but trades are scarce“The high Profit Factor proves the strategy”Top-trade concentration, adjacent periods, sample insufficiency
Net profit is positive, but equity drawdown is large“It recovered eventually, so the risk is acceptable”Positions, time, exits, and sizing behind the drawdown
Long results are stronger than short results“Delete short immediately”Directional samples, regimes, costs, and a separate test
Performance is concentrated in one year or month“That interval is the strategy's normal behavior”Volatility, trend, and trade distribution in other periods
In-sample is strong and out-of-sample is weak“Tune once more on the holdout”Overfitting evidence and a design that preserves untouched data
Almost no trades occur“A longer date range will automatically solve it”Over-restrictive logic versus data or indicator-readiness defects
v0.2.0 is worse than the baseline“Add several more filters to rescue it”Side effects of the one change, falsification, and a revert decision

1. When the result looks strong but the sample is small

Total Trades is only [value]. Do not treat Profit Factor as confirmed performance.
Using the deal-level data, calculate the effect of removing the top 1, 3, and 5 trades,
then split the sample by long/short and time interval.
If the required columns are absent, request them instead of estimating.
Separate what this sample can support from the additional history needed.

2. When net profit is positive but drawdown is large

Total Net Profit is [value], while Equity Drawdown is [value].
Trace the positions, directions, holding times, MAE, and exit reasons in the worst decline.
Separate entry quality, delayed exit, and position sizing into distinct hypotheses.
For each hypothesis, describe a one-change test and the likely adverse side effect.

3. When long and short results diverge

Long and short results differ within the same baseline.
Compare trade count, net result, Profit Factor, drawdown, session, and period by direction.
State what evidence would distinguish a sample-size effect from a market-regime effect.
Design the smallest comparison between the unchanged two-direction baseline
and a direction-filter version. Do not recommend deleting a direction yet.

4. When only the development interval works

v0.1.0 was stronger in-sample and weakened on the untouched out-of-sample interval.
Do not retune parameters from the holdout values.
Describe factual differences in trade count, direction, volatility, costs,
and loss concentration between the intervals.
Propose a falsification test that helps decide whether to reject or simplify the hypothesis,
and identify any change that would require a new holdout.

5. When the revision is worse

v0.2.0 added only [one change] to v0.1.0, but results worsened under the same settings.
Compare both reports and trade lists, separating the change's expected effect
from incidental sample variation.
Distinguish a falsified improvement hypothesis, an implementation mismatch,
and a need for more data.
Do not stack another change to rescue the result; select retain, revert, or retest and explain why.

AI will often propose a trend filter, ADX, ATR, and a session window at once. Adding all of them because their names sound plausible destroys attribution: the next result cannot show which idea mattered.

Candidate controlFailure hypothesis it could testPossible changePossible cost
Trend filterMean-reversion entries repeatedly fail in persistent trendsFewer counter-trend entriesFewer trades and later turning-point entries
ADX conditionHigh trend-strength intervals are unfavorable regardless of directionExclude a defined strength regimeAnother threshold that can be overfit
Bollinger BandwidthSignals behave differently when bands are unusually narrow or wideSeparate volatility regimesAdds a width definition and boundary
ATR-based distanceA fixed stop has different meaning across instruments or volatilityScale distance with observed rangeCash risk still needs separate position sizing
Session filterLosses cluster when spread or price behavior changes by timeAvoid the observed time windowSmaller sample and server-time complexity
Spread capEntry cost consumes the expected moveBlock expensive entriesMore valid signals without a fill
CooldownRe-entry on the same excursion creates loss clustersReduce repeated exposureMiss a fast second mean reversion
Daily loss limitExposure continues to accumulate during a loss clusterBound additional daily lossCan also block later recovery trades

The official MQL5 iADX opens in a new tab and iATR opens in a new tab references describe how to access those indicators. Availability is not evidence that either improves this strategy. A control needs a direct link to an observed failure and a separate version test.

Use this prompt to narrow an unfocused list of suggestions:

Based only on confirmed failure patterns in the attached analysis,
propose at most three candidate controls.

For each candidate, provide:
- the observed fact it addresses
- a causal hypothesis
- the expected change
- metrics or situations that could worsen
- additional data required
- a test that changes only this one core condition

Rank one candidate for a v0.2.0 experiment because it has the most direct evidence.
Explain the ranking, but do not modify code until a human approves it.
Keep parameter fine-tuning as a separate candidate.

Compare v0.1.0 and v0.2.0 on the same test

Do not overwrite the baseline. Preserve the specification, source commit, Inputs, tester configuration, report, Journal, and decision record for each version. Copy actual report values into the table and do not let the AI infer blank cells.

Comparisonv0.1.0 baselinev0.2.0 one changeReview question
Core changeNone[for example, cooldown only]Did only one core hypothesis change?
Tester configuration[record][record whether identical]Are data, costs, and modeling the same?
Total Net Profit[report value][report value]Is the difference concentrated in a few trades?
Profit Factor[report value][report value]Did it change alongside an adequate sample?
Equity Drawdown[report value][report value]Which loss cluster disappeared or grew?
Recovery Factor[report value][report value]What is the net-result/drawdown trade-off?
Total Trades[report value][report value]Did the filter remove too much evidence?
Long / Short[split values][split values]Does one direction dominate the difference?
Consecutive Losses[report value][report value]Did operational loss clustering change?
Out-of-sample[report value][report value]Does the effect appear on untouched data?
Compare the v0.1.0 and v0.2.0 specifications, identical tester settings,
reports, and trade lists.

Rules:
- Do not assume every result difference was caused by the code change.
- Identify trades that were actually affected by the changed condition.
- Show improved and degraded metrics together.
- Separate in-sample from untouched out-of-sample results.
- Include sample reduction and concentration in a few trades.
- Do not estimate missing values.

Output:
1. Configuration-equivalence check
2. Observed differences
3. Evidence for and against the change hypothesis
4. New side effects
5. Retain / revert / additional test, with the reason
6. If another version is justified, propose only one core change

Version control is not a place to keep only favorable outcomes. Retaining a rejected version and its reason prevents the same experiment from returning under a different name. If rules are changed after inspecting the out-of-sample result, that interval is no longer untouched. The official MetaTrader 5 forward optimization workflow opens in a new tab separates the development and forward periods for this reason.

Frequently asked questions

Is a screenshot of the report enough for AI analysis?

It can help explain visible UI, but figures may be cropped and tester settings, the trade list, or Journal may be absent. Where possible, supply the report file, configuration, Inputs, and deal-level data and require the AI to mark unreadable or missing fields.

Which single backtest metric matters most?

There is no universal one. First validate the run through the Journal and settings, then read net result, equity drawdown, sample size, payoff distribution, consecutive losses, and held-out evidence together. They answer different questions.

If v0.2.0 has better figures, did the strategy improve?

Not necessarily. A change selected after inspecting the same interval may simply fit that interval more closely. Compare it with the unchanged baseline under the same setup, then inspect untouched data, sample size, and adverse side effects.

Can the 20 and 2.0 or 14 and 30/70 values be changed?

Yes, but do not sweep many values before establishing the baseline. A parameter change is a new hypothesis and version: record why it is being tested and what could worsen before viewing the result.

Risk note

An AI analysis is constrained by the quality and completeness of its input report. A plausible explanation is not proof of causation, and compilation or historical performance does not establish future results. Automated software can repeat an incorrect rule, while leveraged products can produce rapid and substantial losses.

This article is educational information, not a recommendation of Bollinger Bands and RSI, a parameter set, AI product, broker, instrument, or trade. Do not include passwords, API keys, or identifying account data in AI inputs. Evaluate any implementation in Strategy Tester and an isolated demo environment first.

Up next

Next, we will use one actual MT5 Strategy Tester report as the input. The practical record will ask AI to audit every trade, split performance by period and direction, locate drawdown clusters, select one evidence-linked failure hypothesis for v0.2.0, and rerun the comparison against the baseline under the same conditions.