Martingale Strategy Simulator [BackQuant]Martingale Strategy Simulator  
 Purpose 
This indicator lets you study how a martingale-style position sizing rule interacts with a simple long or short trading signal. It computes an equity curve from bar-to-bar returns, adapts position size after losing streaks, caps exposure at a user limit, and summarizes risk with portfolio metrics. An optional Monte Carlo module projects possible future equity paths from your realized daily returns.
 What a martingale is 
A martingale sizing rule increases stake after losses and resets after a win. In its classical form from gambling, you double the bet after each loss so that a single win recovers all prior losses plus one unit of profit. In markets there is no fixed “even-money” payout and returns are multiplicative, so an exact recovery guarantee does not exist. The core idea is unchanged:
  
  Lose one leg → increase next position size
  Lose again → increase again
  Win → reset to the base size
  
  The expectation of your strategy still depends on the signal’s edge. Sizing does not create positive expectancy on its own. A martingale raises variance and tail risk by concentrating more capital as a losing streak develops. 
 What it plots 
  
  Equity  – simulated portfolio equity including compounding
  Buy & Hold  – equity from holding the chart symbol for context
  Optional helpers – last trade outcome, current streak length, current allocation fraction
  Optional diagnostics – daily portfolio return, rolling drawdown, metrics table
  Optional Monte Carlo probability cone – p5, p16, p50, p84, p95 aggregate bands
  
 Model assumptions 
 
 Bar-close execution with no slippage or commissions
 Shorting allowed and frictionless
 No margin interest, borrow fees, or position limits
 No intrabar moves or gaps within a bar (returns are close-to-close)
 Sizing applies to equity fraction only and is capped by your setting
 
All results are hypothetical and for education only.
 How the simulator applies it 
 1) Directional signal 
 You pick a simple directional rule that produces +1 for long or −1 for short each bar. Options include 100 HMA slope, RSI above or below 50, EMA or SMA crosses, CCI and other oscillators, ATR move, BB basis, and more. The stance is evaluated bar by bar. When the stance flips, the current trade ends and the next one starts.
 2) Sizing after losses and wins 
 Position size is a fraction of equity:
  
  Initial allocation  – the starting fraction, for example 0.15 means 15 percent of equity
  Increase after loss  – multiply the  next  allocation by your factor after a losing leg, for example 2.00 to double
  Reset after win  – return to the initial allocation
  Max allocation cap  – hard ceiling to prevent runaway growth
  
 At a high level the size after  k  consecutive losses is
  alloc(k) = min( cap , base × factor^k ) .
 In practice the simulator changes size only when a leg ends and its PnL is known.
 3) Equity update 
 Let  r_t = close_t / close_{t-1} − 1  be the symbol’s bar return,  d_{t−1} ∈ {+1, −1}  the prior bar stance, and  a_{t−1}  the prior bar allocation fraction. The simulator compounds:
  eq_t = eq_{t−1} × (1 + a_{t−1} × d_{t−1} × r_t) .
  This is bar-based and avoids intrabar lookahead. Costs, slippage, and borrowing costs are not modeled. 
 Why traders experiment with martingale sizing 
  
  Mean-reversion contexts  – if the signal often snaps back after a string of losses, adding size near the tail of a move can pull the average entry closer to the turn
  Behavioral or microstructure edges  – some rules have modest edge but frequent small whipsaws; size escalation may shorten time-to-recovery when the edge manifests
  Exploration and stress testing  – studying the relationship between streaks, caps, and drawdowns is instructive even if you do not deploy martingale sizing live
  
 Why martingale is dangerous 
 Martingale concentrates capital when the strategy is performing worst. The main risks are structural, not cosmetic:
  
  Loss streaks are inevitable  – even with a 55 percent win rate you should expect multi-loss runs. The probability of at least one k-loss streak in N trades rises quickly with N.
  Size explodes geometrically  – with factor 2.0 and base 10 percent, the sequence is 10, 20, 40, 80, 100 (capped) after five losses. Without a strict cap, required size becomes infeasible.
  No fixed payout  – in gambling, one win at even odds resets PnL. In markets, there is no guaranteed bounce nor fixed profit multiple. Trends can extend and gaps can skip levels.
  Correlation of losses  – losses cluster in trends and in volatility bursts. A martingale tends to be largest just when volatility is highest.
  Margin and liquidity constraints  – leverage limits, margin calls, position limits, and widening spreads can force liquidation before a mean reversion occurs.
  Fat tails and regime shifts  – assumptions of independent, Gaussian returns can understate tail risk. Structural breaks can keep the signal wrong for much longer than expected.
  
 The simulator exposes these dynamics in the equity curve, Max Drawdown, VaR and CVaR, and via Monte Carlo sketches of forward uncertainty.
 Interpreting losing streaks with numbers 
 A rough intuition: if your per-trade win probability is  p  and loss probability is  q=1−p , the chance of a specific run of k consecutive losses is  q^k . Over many trades, the chance that at least one k-loss run occurs grows with the number of opportunities. As a sanity check:
  
  If  p=0.55 , then  q=0.45 . A 6-loss run has probability  q^6 ≈ 0.008  on any six-trade window. Across hundreds of trades, a 6 to 8-loss run is not rare.
  If your size factor is 1.5 and your base is 10 percent, after 8 losses the requested size is  10% × 1.5^8 ≈ 25.6% . With factor 2.0 it would try to be  10% × 2^8 = 256%  but your cap will stop it. The equity curve will still wear the compounded drawdown from the sequence that led to the cap.
  
 This is why the cap setting is central. It does not remove tail risk, but it prevents the sizing rule from demanding impossible positions
Note: The p and q math is illustrative. In live data the win rate and distribution can drift over time, so real streaks can be longer or shorter than the simple q^k intuition suggests..
 Using the simulator productively 
 Parameter studies 
 Start with conservative settings. Increase one element at a time and watch how the equity, Max Drawdown, and CVaR respond.
  
  Initial allocation  – lower base reduces volatility and drawdowns across the board
  Increase factor  – set modestly above 1.0 if you want the effect at all; doubling is aggressive
  Max cap  – the most important brake; many users keep it between 20 and 50 percent
  
 Signal selection 
Keep sizing fixed and rotate signals to see how streak patterns differ. Trend-following signals tend to produce long wrong-way streaks in choppy ranges. Mean-reversion signals do the opposite. Martingale sizing interacts very differently with each.
 Diagnostics to watch 
 Use the built-in metrics to quantify risk:
  
  Max Drawdown  – worst peak-to-trough equity loss
  Sharpe and Sortino  – volatility and downside-adjusted return
  VaR 95 percent and CVaR  – tail risk measures from the realized distribution
  Alpha and Beta  – relationship to your chosen benchmark
  
If you would like to check out the original performance metrics script with multiple assets with a better explanation on all metrics please see 
 Monte Carlo exploration 
 
 When enabled, the forecast draws many synthetic paths from your realized daily returns:
  
  Choose a horizon and a number of runs
  Review the bands: p5 to p95 for a wide risk envelope; p16 to p84 for a narrower range; p50 as the median path
  Use the table to read the expected return over the horizon and the tail outcomes
  Remember it is a sketch based on your recent distribution, not a predictor
  
 Concrete examples 
 Example A: Modest martingale 
 Base 10 percent, factor 1.25, cap 40 percent, RSI>50 signal. You will see small escalations on 2 to 4 loss runs and frequent resets. The equity curve usually remains smooth unless the signal enters a prolonged wrong-way regime. Max DD may rise moderately versus fixed sizing.
 Example B: Aggressive martingale 
 Base 15 percent, factor 2.0, cap 60 percent, EMA cross signal. The curve can look stellar during favorable regimes, then a single extended streak pushes allocation to the cap, and a few more losses drive deep drawdown. CVaR and Max DD jump sharply. This is a textbook case of high tail risk.
 Strengths 
  
  Bar-by-bar, transparent computation of equity from stance and size
  Explicit handling of wins, losses, streaks, and caps
  Portable signal inputs so you can A–B test ideas quickly
  Risk diagnostics and forward uncertainty visualization in one place
  
Example, Rolling Max Drawdown 
 Limitations and important notes 
  
  Martingale sizing can escalate drawdowns rapidly. The cap limits position size but not the possibility of extended adverse runs.
  No commissions, slippage, margin interest, borrow costs, or liquidity limits are modeled.
  Signals are evaluated on closes. Real execution and fills will differ.
  Monte Carlo assumes independent draws from your recent return distribution. Markets often have serial correlation, fat tails, and regime changes.
  All results are hypothetical. Use this as an educational tool, not a production risk engine.
  
 Practical tips 
  
  Prefer gentle factors such as 1.1 to 1.3. Doubling is usually excessive outside of toy examples.
  Keep a strict cap. Many users cap between 20 and 40 percent of equity per leg.
  Stress test with different start dates and subperiods. Long flat or trending regimes are where martingale weaknesses appear.
  Compare to an anti-martingale (increase after wins, cut after losses) to understand the other side of the trade-off.
  If you deploy sizing live, add external guardrails such as a daily loss cut, volatility filters, and a global max drawdown stop.
  
 Settings recap 
  
  Backtest start date and initial capital
  Initial allocation, increase-after-loss factor, max allocation cap
  Signal source selector
  Trading days per year and risk-free rate
  Benchmark symbol for Alpha and Beta
  UI toggles for equity, buy and hold, labels, metrics, PnL, and drawdown
  Monte Carlo controls for enable, runs, horizon, and result table
  
 Final thoughts 
 A martingale is not a free lunch. It is a way to tilt capital allocation toward losing streaks. If the signal has a real edge and mean reversion is common, careful and capped escalation can reduce time-to-recovery. If the signal lacks edge or regimes shift, the same rule can magnify losses at the worst possible moment. This simulator makes those trade-offs visible so you can calibrate parameters, understand tail risk, and decide whether the approach belongs anywhere in your research workflow.
