About This Tool
This is a backtesting engine for analyzing Martingale betting strategies on Bitcoin 5-minute OHLCV data. It simulates different entry strategies and measures their profitability, win rates, and risk metrics.
How the Strategy Works
1️⃣ Detect Streaks
Watch for N consecutive candles in the same direction (red or green). When a streak is detected, it signals an entry point.
2️⃣ Place Bet
After N red candles → Bet UP (expect reversal)
After N green candles → Bet DOWN (expect reversal)
3️⃣ Martingale Logic
Win? Pocket profit, reset bet.
Loss? Double bet next time.
Repeat until win or hit max consecutive loss limit.
Example Scenario
Setup: Streak=3, Start Bet=$2, Max Loss=11, Payout=2x
Signal: 3 red candles in a row detected ✓
Action: Bet UP for next candles
Result: Net profit: $8 - $2 - $4 = $2
How to Use
-
Prepare CSV Data
Get historical 5-min candle data from Binance in CSV format
Format:open_time, open, high, low, close, volume -
Place CSV in backtesting/data/ folder
Default file:backtesting/data/file.csv -
Run Backtest
python backtesting/tes.py --streak 3 --start_bet 2 --max_loss 11 -
Analyze Results
Check win rate, P&L, ruin probability, and loss distribution
Configuration Parameters
| Parameter | Default | Description |
|---|---|---|
--file |
data/file.csv |
Path to CSV file with OHLCV data |
--streak |
3 |
Number of consecutive candles to detect before entry |
--start_bet |
2.0 |
Initial bet size in USDC |
--max_loss |
11 |
Max consecutive losses before stopping cycle (risk control) |
--payout |
2.0 |
Multiplier for winning bet (2x = earn 1x bet as profit) |
--fee |
0.0 |
Trading fee as decimal (0.01 = 1% per trade) |
Interpreting Results
Win Rate
Percentage of trades that are profitable
✅ > 50% = Good
❌ < 50% = Likely lose money
Net P&L
Total profit or loss in USDC
✅ Positive = Strategy works!
❌ Negative = Strategy loses money
Ruin Events
Times when hitting max consecutive loss limit
✅ Low (< 5%) = Safe
❌ High (> 20%) = Risky
Capital Needed
Minimum capital to survive max_loss streak
Example: $2,046 needed to survive 11x consecutive losses
📈 Live Backtest Results - Strategy A (3-Streak, $1 Start Bet)
Data: 846,445 BTC 5-min candles (2017-2025) | Updated: Feb 22, 2026
Fee 0% (Ideal)
Fee 2% (Realistic Polymarket)
Fee Impact
Win Rate by Fee
Net P&L Comparison
Loss Distribution (Fee 2%)
Ruin Probability vs Max Loss
| Metric | Fee 0% | Fee 2% | Impact |
|---|---|---|---|
| Win Rate | 55.9% | 55.9% | No change |
| Net P&L | $76,621.00 | $67,074.26 | -12.5% |
| P&L per Cycle | $0.8193 | $0.7172 | -12.5% |
| Total Cycles | 93,517 | 93,517 | No change |
| Total Trades | 167,270 | 167,270 | No change |
| Max Consecutive Loss | 8 | 8 | No change |
| Ruin Events (8x) | 66 | 66 | No change |
| Capital Required | $255 | $255 | No change |
💡 Key Insights
- ✅ Edge: 55.9% win rate beats 50% baseline by 11.8%
- ✅ Fees Matter: Strategy stays highly profitable even with 2% fees
- ✅ Safe Risk: Only 0.07% chance of hitting 8x consecutive losses
- ⚠️ Real World: Polymarket spreads may be 2-3%, add 0.5-1% for slippage
- 💰 Capital: Minimum $255-300 recommended for safe operation
- 📊 ROI: ~$467/day average on $1 starting bet (1,556% annual if consistent)
Analysis Types
Baseline
Simple "Bet UP every candle" with no streak filter. Used as comparison baseline.
Strategy A
Bet UP after N red candles. Tests if red streaks reverse to green.
Strategy B
Bet DOWN after N green candles. Tests if green streaks reverse to red.
Sweep Analysis
Test win rate for different streak lengths (1-7) to find optimal entry point.
Ruin Analysis
Analyze ruin probability for different max_loss values. Shows probability of hitting limits.
⚠️ Important Caveats
- Backtesting ≠ Live Trading - Historical performance doesn't guarantee future results
- Fees Matter - Real exchanges charge 0.1%-0.5% per trade. Update
--feeaccordingly - Slippage Not Included - Assumes instant execution at exact price
- Market Assumptions - Assumes random walk, actual crypto has trends and correlations
- Payout Assumption - Assumes 2x payout. Verify with your actual contract terms
- Risk Management - Even profitable strategies can lose entire account during drawdowns
Usage Examples
Basic run with defaults:
python backtesting/tes.py
Custom parameters:
python backtesting/tes.py \
--file backtesting/data/file.csv \
--streak 5 \
--start_bet 5 \
--max_loss 8 \
--payout 2.0 \
--fee 0.01
Using as Python Module
The backtest engine can be imported and used in other Python projects:
from backtesting.utils import BacktestEngine, BacktestConfig, load_data, add_direction
# Load and prepare data
df = load_data('data/file.csv')
df = add_direction(df)
# Create engine
engine = BacktestEngine(df)
# Configure
config = BacktestConfig(
streak_len=3,
start_bet=2.0,
max_loss=11,
)
# Run
result = engine.run(config)
print(f"Win rate: {result.win_rate:.1f}%")
print(f"P&L: ${result.balance_change:.2f}")
Project Structure
backtesting/
├── README.md # Full documentation
├── tes.py # CLI tool (main entrypoint)
├── utils/
│ ├── __init__.py
│ └── backtest_engine.py # Core reusable module
├── data/
│ └── file.csv # Historical OHLCV data
└── output/ # Output results (if needed)
Tech Stack
- Python 3.9+ - Core language
- Pandas - Data manipulation and analysis
- NumPy - Numerical computations
Next Steps
- Read the full 📖 README.md for detailed documentation
- Prepare your CSV data (Binance 5-min OHLCV format)
- Run the backtest with different parameters
- Analyze results and compare strategies
- Use insights to improve your trading approach