# Introduction to Backtesting

## What is Backtesting?

**Backtesting** is the process of testing a trading strategy on historical market data to evaluate how it would have performed in the past. Think of it as a "time machine" for your trading strategy - you can see how your EA would have traded during specific market conditions without risking real money.

{% hint style="info" %}
**Definition**: Backtesting simulates trades based on historical price data, applying your EA's rules to past market movements to generate performance statistics.
{% endhint %}

***

## Why Backtest?

### 1. **Risk-Free Strategy Validation**

Test your strategy without losing real money. Discover flaws and weaknesses before live trading.

### 2. **Parameter Optimization**

Find the best settings for your EA by testing different parameter combinations systematically.

### 3. **Performance Estimation**

Get realistic expectations for profit potential, drawdown, win rate, and other key metrics.

### 4. **Strategy Comparison**

Compare different approaches (aggressive vs. conservative, different timeframes, etc.) objectively.

### 5. **Confidence Building**

Gain confidence in your strategy by seeing it perform well across different market conditions and time periods.

***

## How Backtesting Works

### The Process

```
1. Historical Data → MT4 loads price history for your symbol/timeframe
                  ↓
2. EA Execution   → Your EA analyzes each bar as if trading live
                  ↓
3. Trade Simulation → MT4 simulates order placement and management
                  ↓
4. Results Generation → Statistics, graphs, and reports are created
```

### What Gets Simulated

✅ **Signal Detection** - Your EA's entry logic\
✅ **Order Placement** - Buy/sell orders at calculated prices\
✅ **Stop Loss & Take Profit** - SL/TP hit simulation\
✅ **Break-Even & Trailing Stop** - Dynamic SL management\
✅ **Partial Closes** - Position management\
✅ **Risk Management** - Lot sizing, drawdown control\
✅ **Time Filters** - Trading hours and session windows

### What Cannot Be Simulated Perfectly

⚠️ **Slippage** - Price differences between order and execution\
⚠️ **Spread Variations** - Fixed spread used, real spreads fluctuate\
⚠️ **Broker Rejections** - Assumes all orders execute\
⚠️ **Server Delays** - No latency simulation\
⚠️ **News Events** - Historical data doesn't capture sentiment

***

## Backtest Modeling Modes

MT4 offers different quality levels for backtesting:

### Control Points (Fastest, Least Accurate)

* Uses only OHLC (Open, High, Low, Close) of each bar
* **Accuracy**: \~25%
* **Use Case**: Quick preliminary tests only

### Open Prices Only (Fast, Limited)

* Uses only the opening price of each bar
* **Accuracy**: \~10%
* **Use Case**: Optimization runs (speed > precision)

### Every Tick (Slowest, Most Accurate)

* Simulates every tick within each bar
* **Accuracy**: \~90%
* **Use Case**: Final validation and detailed analysis
* **Requirement**: Tick data must be downloaded

### Every Tick Based on Real Ticks (Most Accurate)

* Uses actual historical tick data
* **Accuracy**: \~99%
* **Use Case**: Professional-grade validation
* **Requirement**: Real tick data from broker

{% hint style="warning" %}
**BananaEA Recommendation**: Use "Every Tick" mode for accurate results. "Open Prices Only" mode is acceptable for optimization but NOT for final validation.
{% endhint %}

***

## Understanding Backtest Limitations

### 1. **Past Performance ≠ Future Results**

The most important rule: **Historical performance does NOT guarantee future profits.**

Market conditions change:

* Volatility increases/decreases
* Trends emerge and disappear
* Correlations shift
* Liquidity varies

A strategy that worked beautifully in 2020 might struggle in 2025.

### 2. **Look-Ahead Bias**

Your EA must not "peek into the future":

* Using `Close[0]` before bar closes = cheating
* Indicator calculations must use completed bars only
* BananaEA correctly uses `shift = 1` for signal detection

### 3. **Data Quality Issues**

Poor historical data = unreliable results:

* Missing bars create false signals
* Incorrect prices distort performance
* Gaps in data cause test failures

**Solution**: Use data from your actual broker or high-quality data providers.

### 4. **Over-Fitting (Curve Fitting)**

Finding parameters that work perfectly on historical data but fail in live trading:

* Too many parameters optimized = over-fit
* Testing on same data repeatedly = bias
* Complex strategies = fragile

**Solution**: Keep strategies simple, use out-of-sample testing, validate with forward testing.

### 5. **Market Regime Changes**

Markets shift between different states:

* **Trending Markets**: Directional strategies excel
* **Ranging Markets**: Mean reversion strategies shine
* **High Volatility**: Wider stops needed
* **Low Volatility**: Tighter profit targets work

A backtest covering only one regime type gives incomplete picture.

***

## Realistic Expectations

### What Good Backtests Look Like

✅ **Consistent Performance** across different time periods\
✅ **Reasonable Drawdown** (typically 10-30% max)\
✅ **Profit Factor** > 1.5 (ideally 1.8+)\
✅ **Win Rate** 45-65% (not too high, not too low)\
✅ **Smooth Equity Curve** (not vertical lines)\
✅ **Works Across Multiple Symbols** (if applicable)

### Red Flags

❌ **100% Win Rate** - Impossible, indicates look-ahead bias\
❌ **Vertical Equity Curve** - Over-optimized or lucky period\
❌ **Zero Losing Months** - Unrealistic, too good to be true\
❌ **Max Drawdown < 2%** - Either tiny risk or data issues\
❌ **Wildly Different Results** on similar time periods

***

## Common Backtesting Mistakes

### Mistake 1: Testing on Insufficient Data

**Problem**: Testing on 1 month of data\
**Solution**: Use at least 1-2 years, preferably 3-5 years

### Mistake 2: Ignoring Drawdown

**Problem**: Focusing only on profit\
**Solution**: Always check max drawdown and recovery time

### Mistake 3: Over-Optimizing Parameters

**Problem**: Testing 20+ parameters with tiny steps\
**Solution**: Optimize 2-3 key parameters with reasonable ranges

### Mistake 4: Not Validating Results

**Problem**: Going live immediately after backtest\
**Solution**: Always forward test on demo first

### Mistake 5: Using Wrong Spread

**Problem**: Backtesting with 1 pip spread when broker charges 3 pips\
**Solution**: Use realistic spread settings matching your broker

### Mistake 6: Ignoring Commission/Swap

**Problem**: Backtest shows profit, live trading shows loss\
**Solution**: Always include trading costs in backtests

### Mistake 7: Testing on Cherry-Picked Periods

**Problem**: Only testing trending markets\
**Solution**: Test across different market conditions

***

## Backtest Quality Checklist

Before trusting your backtest results, verify:

* [ ] **Data Quality**: Historical data is complete and accurate
* [ ] **Test Duration**: At least 1-2 years of data tested
* [ ] **Modeling Quality**: "Every Tick" mode used for final validation
* [ ] **Realistic Spread**: Matches your broker's actual spread
* [ ] **Commission Included**: Trading costs accounted for
* [ ] **Swap Considered**: Overnight fees included (if holding overnight)
* [ ] **Initial Deposit Realistic**: Matches your actual trading capital
* [ ] **Maximum Drawdown Acceptable**: You can tolerate the worst-case losses
* [ ] **Market Conditions Varied**: Test includes trends, ranges, high/low volatility
* [ ] **Results Make Sense**: No red flags or "too good to be true" metrics

***

## Next Steps

Now that you understand backtesting fundamentals, you're ready to:

1. **Learn MT4 Strategy Tester** → [MT4 Strategy Tester Guide](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/strategy-tester-guide)
2. **Set Up Your First Backtest** → [Backtesting Setup](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/backtesting-setup)
3. **Run Your First Test** → [Running Backtests](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/running-backtests)

{% hint style="success" %}
**Remember**: Backtesting is a tool for strategy development, not a guarantee of future performance. Always validate with forward testing before risking real capital!
{% endhint %}

***

## Related Resources

* [Optimization Fundamentals](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/optimization-fundamentals) - Learn how to optimize parameters
* [Validation & Forward Testing](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/validation-forward-testing) - Validate your results
* [Best Practices & Tips](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/best-practices) - Professional workflow
* [Performance Results](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/broken-reference) - Real BananaEA trading results
