Why the martingale algorithm breaks in the live market
Martingale looks stable on history: rare losses are covered by a series of doublings. In the live market, it is not the idea itself that breaks, but its boundaries.
The volume of the next trade grows as 2ⁿ, and by the eighth or tenth step the required margin is dozens of times the starting margin — averaging a position against the trend runs not into the probability of a reversal, but into the account size and the leverage the broker will provide on this particular day.
The argument formulated by Nassim Taleb works literally here: a loss that zeroes out the account is not compensated by the next step — ruin is irreversible.
The second failure point is the absence of a stop condition: the algorithm includes neither a limit on the number of steps, nor a ceiling on strategy drawdown, nor a pause after a streak of unsuccessful entries.
Therefore, the question "why does martingale blow up" is answered not by the market, but by a series of trades without a limit that has no exit condition.
The third reason is execution.
Slippage on a thin order book shifts the entry point, and the multiplier no longer restores the position; manual corrections on the fly — an increased step, a missed order — break the calculation, and a connection loss at the moment of placing the next order leaves an open series uncontrolled.
Below we break down how this is closed: by calculating the maximum depth of the series, autonomous execution control, and protection from manual intervention.
What managed position-averaging logic provides
Classic martingale doubles the volume after a loss and rests on the assumption that the series will eventually reverse. The limitation is not in the math, but in the finite account size: an unclosed series spends funds faster than the reversal arrives.
Managed averaging logic replaces this assumption with a set of rules that the bot executes without a human — multiplier and volume ceiling, limit on the trade series, risk per trade and per day.
Hard limits instead of hope for a reversal
Position sizing is set by a formula with a ceiling: the series step cannot exceed the limit, and exhausted daily risk closes trading until the next trading day.
The limit on the trade series cuts off averaging at a given step — instead of waiting for a reversal, the bot fixes the series loss and starts a new calculation.
Recovery after a trading bot failure is built on a state journal: on restart, the position and open orders are reconciled with the exchange, for example Bybit, the series step is restored from the journal, and any discrepancy is treated as a close by rule.
The bot returns to operation within seconds and continues the series from the saved step rather than opening it anew.
Transparent reporting for each series
For each series, a record is kept: step number, volume, entry price, accumulated result, and exit reason — limit, target, or manual stop.
A single calculation module serves several instruments; only the parameters differ, so the strategy's behavior in a new market is predictable and does not require separate logic.
Comparison of modes: martingale, anti-martingale, combined
The operating modes of the trading algorithm differ not in entry logic, but in their reaction to a series of losing trades: how volume changes, when to average, and when the series closes.
In one core, we assemble four configurations — they are switched by a parameter, without rebuilding the code.
| Mode | When it fits | Limitations |
|---|---|---|
| Classic martingale | Sideways market, calm volatility, an instrument with clear levels | The averaging volume grows by doubling: a reserve of funds and a hard limit on the number of steps are needed |
| Anti-martingale | Trend, range breakout, sustained momentum | On reversals, short losing streaks accumulate, and entry filters cut into profit |
| Hybrid with switching | Changing market states within a session | Harder to test: a state-switching model and validation at the transition seam are needed |
| Manual mode | Debugging, a non-standard instrument, testing an idea | No automation — entry and averaging are entirely up to the operator |
How to choose a mode for your instrument
We decide the question "martingale or anti-martingale" not by taste, but by the instrument's historical series.
We calculate the distribution of losing-trade series, their maximum length, and drawdown depth under different parameters, and we take signals from an external source (TradingView or an exchange stream).
If the series are short and mean reversion is stable, averaging works; if directional movements predominate, it is safer to increase volume with the trend.
A hybrid averaging strategy is justified where the market state changes within the trading day and neither extreme approach keeps drawdown under control.
Switching modes without resending code
A mode is a set of parameters: averaging step, volume multiplier, maximum number of additional entries, volatility threshold for switching.
They reside in a settings file that the algorithm reads at startup and on a control signal, so switching between modes is a one-line edit and a restart without a build.
The averaging logic remains unchanged; only its configuration changes — this eliminates manual code-copying errors.
How we build a martingale algorithm: stages of work
Trading algorithm development begins not with code, but with examining how decisions are made now.
While the rules for adding to a position and exiting are kept in your head, a failure cannot be reproduced, and the argument "is the bot to blame or the market" is decided blindly.
Therefore, we structure the stages of trading bot implementation so that every rule is fixed before implementation and tested separately.
Formalizing rules before the first line of code
- Audit of the current logic. From trade journals, we reconstruct where manual decisions diverged from the intended plan and in which segments the averaging series went into deep drawdown.
- Entry and exit rules. Conditions for starting a series, candle interval, size of the first position, averaging step and volume growth coefficient, closing — by target, by time, or by signal.
- Risk management scheme. Maximum series drawdown as a percentage of working capital, maximum steps, pause after a losing streak, and the condition for a full stop of the algorithm.
Validation on data and in test mode
- Implementation. Strategy, risk module, and order execution layer are separated into modules, parameters are moved into configuration — behavior changes without code edits.
- Strategy backtesting. A run that accounts for commissions, execution delays, and slippage, separately on trend and sideways, with walk-forward revalidation over consecutive segments.
- Test-mode validation. Launch on a live quote stream without placing orders: we compare signals and volumes against the historical run and catch discrepancies before going live on a real account.
- Handover of the algorithm to the client. Repository, configurations, logic description, instructions for launch and rollback to the previous version, followed by support under an agreed regulation.
What is included in the delivery: code, configurations, regulations
The delivery can be accepted by a formal criterion: the code runs on the test loop, configuration changes the algorithm's behavior without code edits, and the regulation describes the operator's actions. Below is exactly what we hand over.
- Source code of the trading bot with comments: calculation of the next position volume in the series, placing and canceling orders, handling partial fills and connection losses.
- Risk parameter configuration as a separate file: base position size, multiplier and maximum number of steps, series stop, total exposure limit, trading windows.
- API access policies: keys are separated by permissions, withdrawals are disabled on the exchange side, key rotation and restrictions by address and request rate are configured.
- Module interaction diagram: the data path from the order book to the entry and exit decision, logging points, and observation metrics.
- Algorithm documentation: series logic and reset conditions, behavior under low liquidity, spread widening, and slippage.
- Emergency stop regulation: triggering signs, procedure for canceling orders and closing positions, incident recording, and root-cause analysis.
- Acceptance checklist: a run on historical data and on the exchange test loop before going live on a working account.
Documentation that another engineer can work from
A separate section is the deployment instruction, a parameter sheet with permissible ranges and a description of the consequences of exceeding them, and the procedure for rolling back to the previous configuration version.
A specialist who did not write the algorithm can bring the bot up from scratch using these materials, change risk settings, and understand where to look at the journals.
Case study: how reworking the logic changed strategy behavior
In the original version, the averaging series had no upper boundary: the bot added volume against the movement at every step and, during a prolonged trend, accumulated up to twelve positions in a row.
The step and multiplier parameters were edited manually through the interface — each edit required stopping trading, and a connection loss left an open series unattended.
The cost of such logic showed itself rarely but severely: drawdown during trending episodes reached 60–70% of the account peak, and downtime after a connection loss took from 15 to 40 minutes.
The bot traded pairs against the dollar on Binance, where a connection drop is a standard situation, and every pause meant an unmanaged position.
The reworked version introduced a hard limit on series depth and a stepped multiplier: after the fifth step, no new positions are opened, and automatic trading stop triggers at the threshold.
The bot's state is written to a journal, so after a connection loss it restores positions based on executed trades — without closing and reopening. The result is a reduction in drawdown from 60–70% to 25–30% of the account peak and restoration of monitoring within a minute.
How we calculated the result
So that the bot implementation results would not look like curve-fitting, the two versions were run on the same historical segment in three market modes: growth, decline, and sideways.
Connection loss was simulated with forced disconnections for 10, 20, and 40 minutes, and trade execution was inserted with real delays. We calculated drawdown from the account peak, time to restore monitoring, and the number of manual interventions per hundred trades.
How martingale differs from anti-martingale in practice
Martingale increases volume after a losing trade, anti-martingale after a profitable one.
This is the only but fundamental difference: the first logic goes against the series and waits for price to revert to the mean, while the second joins the movement and counts on its continuation.
In martingale, volume grows geometrically — each next entry is larger than the previous one by a set factor. Therefore, capital must withstand not one unsuccessful trade, but the entire series, and its maximum depth becomes the main risk parameter.
Anti-martingale increases volume only after confirmed profit, spends capital more slowly, but depends entirely on whether the profitable series has time to develop.
The result distribution of the two logics is mirrored. Martingale produces many short gains and rare deep drawdowns: one prolonged trend against the position outweighs dozens of successful cycles.
Anti-martingale produces frequent small losses and rare large profits, and the outcome is decided by the amplitude of the captured movement.
In a trend, anti-martingale increases the position in the direction of movement and trails the stop behind price — the trend becomes the source of the main result.
Martingale in a trend against the position averages into an increasingly losing side, and without a hard limit on the number of steps, the series ends with the loss of working capital.
In a flat market, the picture is reversed: price reversion to the mean closes martingale series in profit, while anti-martingale collects false breakouts and small stops. Therefore, we tie the grid step and multiplier to current volatility and set a limit on series depth.
Technical doubts: what clients ask before launch
Before launch, clients check not so much the math of averaging as the algorithm's behavior in abnormal situations: a sharp move against the position, a connection loss, moving the strategy to another venue. Below are answers to the doubts that most often arise among those who have already traded manually.
What does the algorithm do during a sharp price move against the position?
Volume grows according to the preset grid, but only up to the limit of steps and maximum exposure. At the boundary, the algorithm fixes the loss by the stop rule rather than continuing to average. Such a scenario is run on history in advance.
How is risk limited besides position size?
Three independent limiters: a limit on the averaging series, a drawdown limit per trading session, and an auto-stop when volatility leaves the corridor. Each triggers on its own, without operator involvement.
What happens if the connection to the exchange drops?
The algorithm does not invent quotes: orders remain on the venue side, and when the connection is restored, the state is reconciled with the actual state. The protective scenario runs on local time, so a pause in the channel does not leave the position unattended.
Can the algorithm be moved to another exchange or instrument?
Execution logic is tied to venue rules: order types, price step, limits, commissions. The adaptation layer changes, after which the strategy is run on the new instrument's history.
How is the algorithm validated before launching on real capital?
Three steps: a run on history with rare sharp movements, the exchange test loop, and limited volume. Moving further happens after the calculated and actual results match.
Let's discuss the task: where to start and what to prepare
It is more productive to discuss algorithm development when the inputs are on the table, not just the idea "we need a catch-up".
They determine both the architecture and the scope of work: the outwardly similar martingale and anti-martingale diverge already at the stage of calculating position size after a series.
The minimum set to prepare for the discussion:
- Entry and exit logic — how the first entry is calculated, the averaging step, the multiplier, the maximum number of legs, and the rule for exiting the series.
- Trade statistics — an export for the period: entry and exit time, result, maximum drawdown per series.
- Exchanges and instruments — where we trade, spot or derivatives market, working pairs, position size limits.
- Current risk limits — maximum drawdown per day and per series, position limit, conditions for automatic stop.
- Reporting requirements — what needs to be visible: trade journal, daily summary, notifications about failures and deviations from plan.
- Accesses and validation loop — trading account permissions, exchange test loop, who makes decisions during a failure.
Some inputs can be reconstructed from the account history, so their absence does not block the conversation.
Based on the discussion, we come back with an estimate for the trading automation project and a work plan for the algorithm: stages, a historical data run, and acceptance checkpoints.







