Algorithmic trading bot expectancy: a formula for system robustness
An algorithmic trading bot with an 80% win rate can lose money. The condition is simple: its average loss exceeds four average wins. Win rate is not a robustness metric. It is one input in an arithmetic model.
Evan Hayes·Updated: August 02, 2026·15 min read

The relevant measure is expectancy. It estimates the average net outcome produced by one completed trade under a defined execution model. For a two-outcome system:
E = (p × W) − ((1 − p) × L)
Where:
- p is the probability of a winning trade.
- W is the average win.
- L is the average loss, expressed as a positive number.
- E is the expected result per trade.
An algorithmic trading bot has positive arithmetic expectancy only if \(E > 0\). That result is necessary. It is not sufficient. The estimate must also survive realistic spreads, commissions, slippage, latency, parameter variation, and data separation.
The Arithmetic of Survival: Beyond the Win Rate Trap
The trading bot expectancy formula converts a set of historical trades into an expected average outcome. It does not predict the next trade. It measures whether the observed distribution of wins and losses has produced a positive mean after costs.
Consider two forex Expert Advisors.
| Parameter | EA A | EA B |
|---|---|---|
| Win rate | 80% | 45% |
| Average win | 5 pips | 18 pips |
| Average loss | 25 pips | 10 pips |
| Gross expectancy | -1 pip | 2.6 pips |
| Classification | Negative expectancy | Positive expectancy |
For EA A:
\[
E = (0.80 \times 5) - (0.20 \times 25)
\]
\[
E = 4 - 5 = -1
\]
The system wins frequently. The distribution remains unprofitable. Four points of average gain are offset by five points of average loss.
For EA B:
\[
E = (0.45 \times 18) - (0.55 \times 10)
\]
\[
E = 8.1 - 5.5 = 2.6
\]
The lower win rate is irrelevant by itself. EA B produces a positive gross expectancy because its average payoff relative to its average loss is sufficient.
The break-even condition follows directly from the formula:
\[
p \times W = (1-p) \times L
\]
Rearranging gives the minimum win probability required for a given payoff ratio:
\[
p = \frac{L}{W+L}
\]
If average wins and losses are equal, the break-even win rate is 50%. If the average loss is twice the average win, the required win rate rises to 66.7%. If the average win is twice the average loss, the system can break even near 33.3%.
This is not a market view. It is arithmetic.
A high win rate measures frequency. Expectancy measures whether the full payoff distribution survives.
The calculation should use completed trades after the system’s actual exit logic. Partial closes, trailing stops, scale-outs, averaging procedures, and recovery baskets require additional care. A bot that treats five entries as one basket while the tester reports five independent deals can create a distorted trade sample. The unit of analysis must match the unit of risk.
For a grid or martingale structure, average loss requires particular scrutiny. Many such systems report a high win rate because losses are deferred rather than removed. The sample may contain thousands of small gains and no full loss event. In that case, the observed average loss is not an estimate of the system’s actual tail loss. It is a missing observation.
Gross Expectancy Is Not Net Expectancy
A reported expectancy without trading costs is incomplete. In spot forex, the gap between gross and net results can determine whether an automated system is tradeable.
A practical calculation begins with normalized net outcomes. Each completed trade should include:
- Spread paid at entry and, where applicable, exit.
- Commission by lot or by notional value.
- Swap or rollover for positions held across the broker’s financing boundary.
- Slippage relative to the requested or modeled price.
- Execution delay between order generation and fill.
- Requotes or rejected execution paths where the broker model supports them.
- Currency conversion effects when account currency differs from the symbol’s profit currency.
The net formula does not change. The inputs change.
\[
E_{net} = (p \times W_{net}) - ((1-p) \times L_{net})
\]
A scalping system is particularly sensitive. If an EA targets a small intraday movement, a one-pip change in effective transaction cost can remove most or all of its expected value. A swing system with a wider average trade range may be less sensitive to spread, but it can carry larger swap exposure and wider adverse movement.
The distinction can be shown without adding unsupported precision.
| Component | Effect on a long-only or mixed-direction bot |
|---|---|
| Wider spread | Reduces realized win size and increases effective entry cost |
| Commission | Reduces every completed trade result |
| Negative swap | Reduces expectancy on overnight holdings |
| Slippage | Degrades entry or exit price relative to the signal |
| Latency | Increases the probability that the tested signal price is unavailable |
| Requotes or rejection | Changes fill probability and can alter the trade distribution |
The error is not merely omitting a cost field. The deeper error is assuming that costs are constant across all conditions. They are not. EUR/USD during liquid periods and a cross during thin rollover conditions do not produce identical execution behavior. The broker, account type, symbol, position size, session, and execution protocol determine the relevant model.
A forex bot reliability check should therefore state the tested environment. “Positive expectancy” is not portable unless the trading conditions are specified. A result obtained under one commission schedule, leverage setting, and spread regime is an observation about that configuration.
High-Fidelity Modeling With Real Ticks and Execution Delays
MetaTrader 5 provides several testing modes. They do not have the same evidential value.
| MT5 testing mode | Price representation | Suitable use | Primary limitation |
|---|---|---|---|
| Open prices only | Bar opening prices | Systems acting only at a new-bar open | Cannot validate intrabar logic, stop behavior, or pending-order execution |
| 1 minute OHLC | Four prices per one-minute bar | Coarse preliminary analysis | Omits the sequence of intrabar price movement |
| Every tick | Generated ticks from available bar data | Detailed testing where real-tick data is unavailable | Tick sequence remains modeled |
| Every tick based on real ticks | Broker-accumulated tick data | Highest available historical fidelity in MT5 | Historical quality does not reproduce future live execution |
The 1-minute OHLC mode models only Open, High, Low, and Close for each minute. It cannot establish which of the High or Low occurred first. That distinction is material for an algorithmic trading bot using a stop loss, take profit, break-even rule, trailing stop, pending order, or intrabar indicator trigger.
A system can appear stable in a rough model because the tester resolves an ambiguous price path in a way that benefits the strategy. This is common in short-horizon systems. It is also common in EAs whose entry and exit conditions depend on a few points of movement.
Open-prices-only testing has a narrower role. It can be appropriate when the code enters and manages positions exclusively at the opening of a new bar and contains no intrabar dependencies. That condition must be verified in the execution logic, not assumed from the strategy description.
Every-tick testing is slower. That is not a defect. It reflects a larger state space. Real-tick mode uses broker-accumulated ticks and provides the stronger historical test for price-sensitive systems. It still does not replicate the complete live environment. Tick history does not guarantee the same queue position, liquidity, fill rate, rejection handling, or network path.
MetaTrader 5 can model a delay between trade request and execution. That setting is relevant for automated execution systems that depend on rapid fills. During the modeled delay, the price can change. Under instant-execution conditions, the tester can also evaluate the Expert Advisor’s response to a requote.
This changes the object being tested. Without delay, the backtest evaluates signal generation against an assumed fill. With delay, it evaluates the combined signal-and-execution process.
A backtest that ignores execution latency measures a different system from the one deployed on a VPS.
The distinction matters most when the strategy’s expected profit per trade is small relative to the expected movement during its execution window. A mean-reversion bot entering after a short deviation may be profitable at the signal timestamp and unprofitable at the fill timestamp. The signal has not changed. The available price has.
Test the Code Path, Not Only the Strategy Idea
An automated system performance report is valid only if the tested code path matches the deployed code path.
This requires a direct audit of the EA or trading script:
1. Confirm the signal timeframe. An EA may calculate an indicator on H1 while managing stops on ticks. Testing it as if it were a pure H1 open-price system is incorrect.
2. Identify all intrabar dependencies. Stop loss, take profit, trailing logic, pending orders, break-even rules, news filters, spread filters, and session exits can all require tick-level behavior.
3. Check indicator indexing. A strategy using an unclosed bar can generate a historical signal that was not stable in real time. The tester may correctly calculate the indicator while the strategy logic remains structurally exposed to bar-state changes.
4. Separate order request from order fill. Signal timestamps, requested prices, confirmed fill prices, and exit prices should be recorded separately where the platform permits. This identifies whether expectancy originates in the model or in execution assumptions.
5. Align lot-sizing logic with the account specification. Minimum volume, volume step, margin rules, leverage, trading limits, and symbol contract details affect whether the theoretical position size can exist in the tested account.
6. Retain failed order handling. A live Expert Advisor must define its behavior after a rejected request, a requote, or an unavailable price. Removing these branches during testing produces a cleaner result and a weaker model.
MetaTrader 5 allows account and trading-condition settings including initial deposit, leverage, margin parameters, trading limits, and commissions. Those settings should be fixed before optimization. Changing them after finding profitable parameters is not validation. It is a second optimization pass.
The platform also loads preceding bars to prepare the test environment. This supports indicator initialization, but it does not remove the need to inspect warm-up behavior. A moving-average or volatility filter can produce materially different early results if its initialization state is not controlled.
Validating Robustness Through Out-of-Sample Forward Testing
In-sample optimization answers a limited question: which parameter set performed best on the data used to select it? It does not answer whether the parameter set will retain positive expectancy on later data.
MetaTrader 5 forward testing separates the selected history into an optimization portion and a later forward portion. The platform can reserve one half, one third, one quarter, or a custom later segment for this purpose.
The procedure should be sequential.
1. Define the strategy rules before inspecting optimization output. This includes entries, exits, symbol set, timeframe, position sizing, cost assumptions, and maximum concurrent exposure.
2. Select a historical interval for adaptation. Run parameter optimization only within that interval.
3. Rank parameter sets using net metrics, not win rate alone. Net expectancy, drawdown, distribution of returns, and stability across nearby parameter values should be examined together.
4. Freeze the selected parameters. No manual adjustment should occur after the forward period has been viewed.
5. Run the later forward segment under the same execution assumptions. Compare the distribution, not only final profit.
6. Investigate degradation. A lower forward result is not automatically failure. A sign reversal in expectancy, a large drawdown expansion, or dependence on a single parameter combination requires further examination.
There is no universal minimum number of trades, universal Sharpe threshold, mandatory profit factor, or maximum acceptable drawdown that establishes robustness across all forex strategies. A low-frequency carry system, an intraday trend system, and a tick-sensitive scalper produce different sample structures and different cost sensitivity.
The useful comparison is internal consistency.
| Diagnostic | More stable observation | Weaker observation |
|---|---|---|
| Net expectancy | Remains positive across adaptation and later data | Positive only during optimized history |
| Parameter response | Broad area of similar results | Isolated peak at one setting |
| Drawdown | Comparable scale across samples | Forward drawdown expands sharply |
| Trade distribution | No single event dominates total result | One trade or one month explains most profit |
| Cost sensitivity | Remains viable under less favorable assumptions | Turns negative after modest cost changes |
| Market-data sensitivity | Similar logic survives real-tick retest | Result depends on coarse bar modeling |
A broad parameter plateau is not proof of future performance. It is evidence against one narrow form of curve fitting. If only one moving-average length, stop distance, or entry threshold produces a positive result, the system may be fitting historical noise. If a range of nearby settings remains viable, the signal is less dependent on a single arbitrary value.
The same principle applies to symbols and sessions. A bot that produces positive net expectancy only on one pair, in one historical interval, during one narrow session, requires a causal explanation. Without one, the concentration is a model risk.
Stress-Testing the Break-Even Condition Against Costs
The break-even equation provides a direct way to test fragility.
Assume a system has estimated gross values:
- Win probability: 52%.
- Average gross win: 12 units.
- Average gross loss: 10 units.
Its gross expectancy is:
\[
E = (0.52 \times 12) - (0.48 \times 10)
\]
\[
E = 6.24 - 4.80 = 1.44
\]
The system has a gross buffer of 1.44 units per trade. If total average trading friction exceeds that buffer, the net system is negative.
This is why the average cost is not an accounting footnote. It is part of the payoff distribution. Costs can reduce average wins, deepen average losses, and alter the win probability if stops or limits are affected by the execution path.
A useful stress process changes one variable at a time, then several together:
- Increase effective spread assumptions.
- Add commission at the intended account schedule.
- Apply adverse fill assumptions to market exits and entries.
- Increase modeled execution delay.
- Test periods with wider historical ranges and different volatility states.
- Recalculate expectancy after removing the largest winning trade.
- Recalculate after isolating overnight trades, high-impact session trades, or thin-liquidity periods where relevant.
The objective is not to produce a worst-case fantasy. It is to identify the point at which the expected value crosses zero.
That threshold defines operational sensitivity. A system that remains positive after reasonable deterioration in its execution assumptions has a larger margin. A system that fails after a minor increase in friction has limited deployment tolerance.
Drawdown must be read alongside expectancy. Two systems can have similar expected value per trade and radically different loss paths. A positive mean does not prevent clustered losses. Standard deviation, maximum observed drawdown, losing streak distribution, and position correlation affect capital requirements and sizing decisions.
An EA trading several correlated currency pairs may report many positions while holding a single directional macro exposure. EUR/USD long, GBP/USD long, and USD/CHF short can be distinct tickets but related USD risk. Trade-level expectancy does not remove portfolio concentration.
The Reality Gap Between Historical and Live Execution
Hypothetical results are prepared with hindsight. They do not involve financial risk. They cannot fully account for live liquidity conditions, slippage, execution changes, or the operational response required during drawdown.
This is a structural limit, not a platform-specific defect.
A historical test uses known data. The algorithm follows rules against a completed price record. A live system operates with uncertain future prices, changing liquidity, evolving spreads, broker-side execution conditions, connection failures, VPS interruptions, and software state.
Forward testing inside historical data is useful because it prevents direct parameter selection on the later segment. It is still historical. It is not equivalent to live forward testing on a demo or funded account.
The next validation stage should therefore preserve the same reporting fields:
- Signal time and execution time.
- Requested and filled price.
- Spread at request and fill.
- Commission and swap.
- Slippage by order type and session.
- Rejected, modified, and cancelled orders.
- Net outcome per completed trade.
- Equity drawdown and exposure by correlated symbol.
The comparison should not be reduced to whether live profit equals backtest profit. That standard is too crude. The audit should compare fill behavior, average win, average loss, win probability, trade frequency, and drawdown distribution against the tested assumptions.
A mismatch does not automatically invalidate the logic. It identifies the component that changed. If entries occur less frequently, the filter or data feed may differ. If average losses expand, stops may be exposed to execution conditions not represented in the model. If positive expectancy disappears after commissions, the prior result was gross, not net.
Regulators correctly note that automation can enforce discipline. It cannot consistently predict currency prices. The broader retail forex loss rate remains a reminder that mechanical execution does not repair a negative distribution.
The Required Conclusion
The algorithmic trading bot expectancy formula is the first arithmetic filter:
\[
E = (p \times W) - ((1-p) \times L)
\]
A positive result establishes only that the tested trade sample had positive average value under its stated assumptions. It does not establish future profitability. It does not establish live forex bot reliability. It does not establish robustness.
Robustness requires a stricter chain:
- Net expectancy after modeled costs.
- Testing mode aligned with the code path.
- Real-tick retesting for intrabar-dependent logic.
- Execution-delay and requote handling where applicable.
- Fixed broker and account assumptions.
- Out-of-sample forward analysis.
- Cost and latency stress testing.
- Ongoing live comparison against the tested distribution.
The practical risk-reward summary is narrow. A system with negative net expectancy should not proceed to deployment. A system with positive but cost-fragile expectancy requires limited exposure and further testing. A system with positive results across separated samples and adverse execution assumptions has passed a stronger filter, not a guarantee.
Backtests measure a historical model. Live trading measures the model, the broker, the infrastructure, and the market at the same time.