# Running Optimizations

## Executing Parameter Optimization

Now that you understand optimization fundamentals, this guide walks you through the practical steps of running an optimization in MT4 Strategy Tester.

{% hint style="success" %}
**Goal**: Systematically test multiple parameter combinations to find optimal EA settings for your symbol and timeframe.
{% endhint %}

***

## Quick Start: Running Your First Optimization

### 5-Step Process

1. **Open Strategy Tester** → Press `Ctrl+R`
2. **Enable Optimization** → Check "Optimization" checkbox
3. **Configure Parameters** → Set ranges (Start, Step, Stop) in Inputs tab
4. **Select Criteria** → Choose optimization metric (Profit Factor recommended)
5. **Click Start** → Begin optimization run

***

## Step-by-Step Optimization Setup

### Step 1: Basic Configuration

Open Strategy Tester and configure standard settings:

**Settings Tab**:

```
Expert Advisor: BananaEA-v3.13.21-meanReversion.ex4 ✅
Symbol: GER40.r ✅
Period: H1 ✅
Model: Open Prices Only (for speed) ✅
Spread: 20 points ✅
From: 2023.01.01 ✅
To: 2024.12.31 ✅ (In-sample data only!)
```

{% hint style="info" %}
**In-Sample Data**: Use only 60-70% of your data for optimization. Reserve remaining 30-40% for out-of-sample validation.
{% endhint %}

***

### Step 2: Enable Optimization

**Settings Tab**:

* ✅ Check "Optimization" checkbox
* ❌ Uncheck "Visual mode" (disabled automatically)

**What Changes**:

* Inputs tab shows parameter range controls
* Optimization tab becomes active
* MT4 will test multiple parameter combinations

***

### Step 3: Configure Parameter Ranges

**Inputs Tab Interface**:

When optimization is enabled, each parameter shows:

* **Value**: Current/default value
* **Start**: Beginning of range
* **Step**: Increment size
* **Stop**: End of range
* **Checkbox**: Enable optimization for this parameter (Y/N)

**Example Configuration**:

```
Parameter Name      Value   Start   Step   Stop   Optimize
─────────────────────────────────────────────────────────
RiskPercent         2.0     1.0     0.5    3.0    [✓]
BuyBuffer           5.0     3.0     1.0    10.0   [✓]
SellBuffer          5.0     3.0     1.0    10.0   [✓]
MaxOpenTrades       1       1       1      3      [ ]
BreakEvenMethod     2       2       1      2      [ ]
```

**Optimization Enabled** (✓):

* RiskPercent: Tests 1.0, 1.5, 2.0, 2.5, 3.0 (5 values)
* BuyBuffer: Tests 3, 4, 5, 6, 7, 8, 9, 10 (8 values)
* SellBuffer: Tests 3, 4, 5, 6, 7, 8, 9, 10 (8 values)

**Total Iterations**: 5 × 8 × 8 = **320 passes**

{% hint style="warning" %}
**Iteration Explosion**: Each optimized parameter multiplies total passes. Optimize only 2-3 parameters to keep runtime manageable.
{% endhint %}

***

## Setting Parameter Ranges

### Rule of Thumb: Choose Meaningful Ranges

**Too Narrow** (wastes opportunity):

```
RiskPercent: Start=1.9, Step=0.1, Stop=2.1
→ Only tests 1.9, 2.0, 2.1 (3 values)
→ Not really exploring, just confirming default
```

**Too Wide** (wastes time, risks over-fitting):

```
RiskPercent: Start=0.1, Step=0.1, Stop=10.0
→ Tests 100 values from 0.1% to 10%
→ Most are unrealistic (0.1% = tiny risk, 10% = huge risk)
→ Massive computation for nonsense values
```

**Just Right** (explores meaningful range):

```
RiskPercent: Start=1.0, Step=0.5, Stop=3.0
→ Tests 1.0, 1.5, 2.0, 2.5, 3.0 (5 values)
→ Covers realistic risk range: conservative to moderate
→ Reasonable iterations, actionable insights
```

***

### BananaEA Recommended Ranges

#### Risk Management Parameters

**RiskPercent** (Risk per trade):

```
Start: 1.0    (Conservative - 1% risk)
Step:  0.5    (Meaningful increments)
Stop:  3.0    (Moderate - 3% risk)
Values: 1.0, 1.5, 2.0, 2.5, 3.0 → 5 iterations
```

**MaxOpenTrades** (Position limit):

```
Start: 1      (Single position)
Step:  1      (Integer increments)
Stop:  3      (Up to 3 simultaneous trades)
Values: 1, 2, 3 → 3 iterations
```

***

#### Entry/Exit Parameters

**BuyBuffer** (Pips above signal):

```
Start: 3.0    (Tight entry)
Step:  1.0    (1 pip increments)
Stop:  10.0   (Wider entry buffer)
Values: 3, 4, 5, 6, 7, 8, 9, 10 → 8 iterations
```

**SellBuffer** (Pips below signal):

```
Start: 3.0    (Tight entry)
Step:  1.0    (1 pip increments)
Stop:  10.0   (Wider entry buffer)
Values: 3, 4, 5, 6, 7, 8, 9, 10 → 8 iterations
```

**CandleRangeSL** (Stop loss candle count):

```
Start: 5      (Tight stop)
Step:  5      (Larger increments for speed)
Stop:  20     (Wider stop)
Values: 5, 10, 15, 20 → 4 iterations
```

**CandleRangeTP** (Take profit candle count):

```
Start: 10     (Conservative target)
Step:  5      (Larger increments)
Stop:  30     (Aggressive target)
Values: 10, 15, 20, 25, 30 → 5 iterations
```

***

#### Trade Management Parameters

**BreakEvenMethod** (Break-even strategy):

```
Start: 0      (Disabled)
Step:  1      (Test each method)
Stop:  3      (ATR-based method)
Values: 0, 1, 2, 3 → 4 iterations
```

**TrailingMethod** (Trailing stop type):

```
Start: 0      (Fixed pips)
Step:  1      (Test each method)
Stop:  2      (ATR-based)
Values: 0, 1, 2 → 3 iterations
```

***

### Calculating Total Iterations

**Formula**: Multiply the number of values for each optimized parameter.

**Example 1 - Conservative** (2 parameters):

```
RiskPercent: 5 values (1.0 to 3.0, step 0.5)
MaxOpenTrades: 3 values (1 to 3, step 1)
Total: 5 × 3 = 15 passes ✅ FAST
```

**Example 2 - Standard** (3 parameters):

```
RiskPercent: 5 values
BuyBuffer: 8 values
SellBuffer: 8 values
Total: 5 × 8 × 8 = 320 passes ✅ MODERATE
```

**Example 3 - Aggressive** (5 parameters - NOT recommended):

```
RiskPercent: 5 values
BuyBuffer: 8 values
SellBuffer: 8 values
CandleRangeSL: 4 values
CandleRangeTP: 5 values
Total: 5 × 8 × 8 × 4 × 5 = 6,400 passes ⚠️ SLOW (hours)
```

{% hint style="danger" %}
**Over-Optimization Alert**: 1,000+ passes increases curve-fitting risk. Keep iterations under 500 for robust results.
{% endhint %}

***

## Step 4: Select Optimization Criteria

**Optimization Tab** (becomes active when optimization enabled)

**Available Criteria**:

**Balance Max** (Default)

* Optimizes for maximum net profit
* Risk: May accept huge drawdowns

**Profit Factor** (Recommended)

* Optimizes for best profit/loss ratio
* Balanced risk/reward approach
* Formula: Gross Profit ÷ Gross Loss

**Expected Payoff**

* Optimizes for average profit per trade
* Good for consistent performance

**Balance Drawdown Max**

* Optimizes for maximum balance with lowest drawdown
* Conservative, capital preservation focused

**Custom**

* Use custom optimization criterion (requires coding)

{% hint style="success" %}
**BananaEA Recommendation**: Use **Profit Factor** for most optimizations. It balances profitability with risk management better than raw profit.
{% endhint %}

***

## Step 5: Advanced Optimization Settings

### Genetic Algorithm vs. Slow Complete Algorithm

**Optimization Tab Options**:

**Slow Complete Algorithm** (Brute Force):

* Tests EVERY parameter combination
* Guaranteed to find global optimum
* Use for: 2-3 parameters, <1,000 iterations

**Genetic Algorithm** (Evolutionary):

* Tests random combinations, evolves best performers
* Much faster but may miss global optimum
* Use for: 4+ parameters, >1,000 iterations

**BananaEA Recommendation**:

* **2-3 parameters**: Slow Complete Algorithm (thorough)
* **4+ parameters**: Genetic Algorithm (speed)

***

### Other Settings

**Use Local Agents** (if available):

* Distributes optimization across multiple CPU cores
* Significantly faster for large optimizations
* Check this if your computer has 4+ cores

**Forward Test Validation**:

* MT4 can automatically validate on forward period
* Useful but not replacement for manual out-of-sample testing

***

## Step 6: Start Optimization

**Click \[Start] Button**

**What Happens**:

```
1. MT4 calculates total parameter combinations
   ↓
2. Creates optimization passes (1 to N)
   ↓
3. Runs backtest for each combination
   ↓
4. Records performance metrics
   ↓
5. Ranks results by selected criterion
   ↓
6. Displays best combinations in Optimization Results
```

***

## Monitoring Optimization Progress

### Progress Indicators

**Status Bar** (Bottom of Strategy Tester):

```
Optimization: Pass 145/320 (45%)  [████████████░░░]
```

**Information Displayed**:

* **Current Pass**: Which iteration (e.g., 145/320)
* **Percentage**: Completion progress (45%)
* **Estimated Time**: Time remaining (if available)

**Journal Tab**: Shows progress messages:

```
Optimization pass 1 started
Pass 1 finished: Profit=1234.56, Factor=1.85
Pass 2 started...
```

***

### Typical Optimization Durations

**Quick Optimization** (50-100 passes, 2 years, Open Prices):

* **Time**: 10-30 minutes
* **Use**: Quick parameter screening

**Standard Optimization** (200-500 passes, 2 years, Open Prices):

* **Time**: 1-2 hours
* **Use**: Regular optimization runs

**Large Optimization** (1,000-2,000 passes, 3 years, Open Prices):

* **Time**: 3-8 hours
* **Use**: Comprehensive parameter search

**Massive Optimization** (5,000+ passes, 5 years, Every Tick):

* **Time**: 24-72+ hours
* **Use**: Professional validation (use cloud optimization)

{% hint style="info" %}
**Speed Tip**: Use "Open Prices Only" for optimization. It's 10-50x faster than "Every Tick" while still providing meaningful results for parameter comparison.
{% endhint %}

***

## Optimization Results

### Results Table

After completion, **Optimization Results** tab shows ranked parameter combinations:

```
Pass  Result   Profit  Trades  PF    DD    RiskPct  BuyBuf  SellBuf
────────────────────────────────────────────────────────────────────
145   €18,432  18432   234    2.34  12%   2.0      7.0     6.0     ★
67    €17,890  17890   198    2.41  10%   1.5      8.0     7.0
203   €17,234  17234   267    2.18  15%   2.5      6.0     5.0
89    €16,789  16789   213    2.29  11%   2.0      9.0     8.0
...
```

**Columns**:

* **Pass**: Optimization iteration number
* **Result**: Value of optimization criterion (Profit Factor, Net Profit, etc.)
* **Profit**: Total net profit
* **Trades**: Number of trades executed
* **PF**: Profit Factor (Gross Profit / Gross Loss)
* **DD**: Maximum Drawdown percentage
* **Parameter Values**: Shows values used for each optimized parameter

**★ = Best Result** based on selected criterion

***

### Analyzing Top Results

**NEVER just pick #1!**

**Professional Approach**:

1. **Review Top 10-20 Results** (not just best)
2. **Look for Consistency**:
   * Do top results cluster around similar parameter values?
   * Or are they wildly different?
3. **Check for Red Flags**:
   * Outliers (one amazing result, rest mediocre)
   * Extreme parameters (BuyBuffer=23.7 pips)
   * Too-good-to-be-true metrics (100% win rate)
4. **Prefer Robust Results**:
   * Top 5 results have similar parameters
   * Smooth performance across parameter ranges
   * Reasonable metrics (not extreme)

**Example - Robust Optimization**:

```
Top 5 Results:
Pass 145: RiskPct=2.0, BuyBuf=7, SellBuf=6 → Profit=€18,432, PF=2.34
Pass 203: RiskPct=2.0, BuyBuf=6, SellBuf=6 → Profit=€17,890, PF=2.41
Pass 178: RiskPct=1.5, BuyBuf=7, SellBuf=7 → Profit=€17,234, PF=2.18
Pass  89: RiskPct=2.0, BuyBuf=8, SellBuf=7 → Profit=€16,789, PF=2.29
Pass 134: RiskPct=2.5, BuyBuf=7, SellBuf=6 → Profit=€16,456, PF=2.15

Analysis:
✅ RiskPct clusters around 2.0% (1.5-2.5 range)
✅ BuyBuf clusters around 7 pips (6-8 range)
✅ SellBuf clusters around 6-7 pips
✅ Profit Factor consistently 2.15-2.41 (robust)
✅ No extreme outliers

Decision: Use RiskPct=2.0, BuyBuf=7, SellBuf=6 (best performer with cluster consensus)
```

**Example - Suspicious Optimization**:

```
Top 5 Results:
Pass 423: RiskPct=2.7, BuyBuf=13.2, SellBuf=3.1 → Profit=€25,678, PF=3.87
Pass  67: RiskPct=0.9, BuyBuf=4.5,  SellBuf=19.7 → Profit=€14,234, PF=2.01
Pass 891: RiskPct=5.3, BuyBuf=7.2,  SellBuf=8.1  → Profit=€13,890, PF=1.95
Pass 234: RiskPct=1.2, BuyBuf=22.3, SellBuf=6.4  → Profit=€13,456, PF=1.89
Pass 567: RiskPct=3.1, BuyBuf=9.8,  SellBuf=14.2 → Profit=€12,987, PF=1.83

Analysis:
🚩 Parameters wildly different (no clustering)
🚩 Best result is outlier (€25K vs. €14K)
🚩 Best result has extreme PF (3.87 vs. ~2.0 for others)
🚩 Parameters not intuitive (BuyBuf=13.2, SellBuf=3.1?)

Warning: Likely over-fitted! Pass 423 optimized to historical noise, not robust patterns.
```

***

## Saving Optimization Results

### Export Results Table

**Right-click in Optimization Results tab**:

* **Save as Report**: Exports to HTML file
* Choose filename and location
* Includes full results table with all parameters

**Recommended Filename**:

```
BananaEA_Optimization_DAX-H1_2023-2024_RiskBuyBuffSellBuff_20251020.html
```

**Why Save**:

* Compare optimizations over time
* Track what you've tried
* Reference for future re-optimization
* Documentation for strategy development

***

### Creating Preset Files

Once you've identified optimal parameters:

**Create .set File**:

1. Strategy Tester → Inputs tab
2. Manually enter optimal parameter values
3. Right-click in inputs area
4. Select "Save"
5. Name file: `BananaEA-DAX-H1-Optimized-Oct2025.set`
6. Save in: `MQL4/Presets/` folder

**Benefits**:

* Quick loading of optimal settings
* Easy comparison between parameter sets
* Sharing optimized configurations
* Deployment to live trading

***

## Out-of-Sample Validation (Critical!)

**MANDATORY**: Never use optimized parameters without out-of-sample validation!

### Validation Process

**Step 1: Run Standard Backtest on Out-of-Sample Data**

```
Strategy Tester Setup:
─────────────────────────────────────
Expert Advisor: BananaEA (same version)
Symbol: GER40.r (same symbol)
Period: H1 (same timeframe)
Model: Every Tick (higher accuracy for validation)
Spread: 20 points (same as optimization)
From: 2025.01.01 ← OUT-OF-SAMPLE START
To:   2025.10.20 ← Current date
Optimization: UNCHECKED (just backtest)

Parameters: Load optimized values from previous step
```

**Step 2: Compare In-Sample vs. Out-of-Sample Performance**

**Good Result** (Robust optimization):

```
In-Sample (2023-2024):
- Net Profit: €18,432
- Profit Factor: 2.34
- Max DD: 12%
- Win Rate: 58%

Out-of-Sample (2025):
- Net Profit: €7,234 (similar pace)
- Profit Factor: 2.18 (close to in-sample)
- Max DD: 14% (acceptable increase)
- Win Rate: 56% (consistent)

Verdict: ✅ ROBUST - Parameters work on unseen data!
```

**Bad Result** (Over-fitted):

```
In-Sample (2023-2024):
- Net Profit: €25,678
- Profit Factor: 3.87
- Max DD: 5%
- Win Rate: 78%

Out-of-Sample (2025):
- Net Profit: -€1,234 (LOSS!)
- Profit Factor: 0.87 (losing strategy)
- Max DD: 28% (much worse)
- Win Rate: 42% (dropped dramatically)

Verdict: ❌ OVER-FITTED - Parameters memorized noise, not patterns!
```

{% hint style="danger" %}
**Critical Rule**: If out-of-sample performance degrades significantly (>30% drop in Profit Factor or turns negative), parameters are over-fitted. DO NOT USE. Re-optimize with fewer parameters or wider ranges.
{% endhint %}

***

## Troubleshooting Optimization Issues

### Issue 1: Optimization Taking Too Long

**Problem**: Optimization running for 10+ hours

**Solutions**:

* ✅ Reduce parameter ranges (fewer values)
* ✅ Use larger step sizes (skip intermediate values)
* ✅ Reduce test period (2 years instead of 5)
* ✅ Enable "Use Local Agents" (multi-core processing)
* ✅ Switch to Genetic Algorithm (if 1,000+ passes)

***

### Issue 2: All Results Nearly Identical

**Problem**: Top 100 passes have almost same performance

**Cause**: Parameters have little impact or ranges too narrow

**Solutions**:

* Widen parameter ranges
* Optimize different parameters (more impactful ones)
* Check if EA is actually using the parameters
* Verify sufficient trades executed (not just 5-10 trades)

***

### Issue 3: Best Result is Outlier

**Problem**: Pass #1 is amazing, Pass #2-100 are mediocre

**Cause**: Curve fitting to specific historical anomaly

**Solutions**:

* **Ignore the outlier** (it's over-fitted)
* Use parameters from **Pass #5-10** (more robust)
* Look for **clustering** in top results
* **Re-optimize** with fewer parameters or coarser steps

***

### Issue 4: Optimization Crashes

**Problem**: MT4 crashes mid-optimization

**Solutions**:

* Update MT4 to latest version
* Close other programs (free RAM)
* Reduce test period or iteration count
* Check EA code for memory leaks
* Try different computer if persistent

***

## Next Steps

Now that you can run optimizations:

1. **Analyze Results Deeply** → [Analyzing Results](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/analyzing-results)
2. **Learn Advanced Techniques** → [Advanced Optimization](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/advanced-optimization)
3. **Validate Properly** → [Validation & Forward Testing](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/validation-forward-testing)
4. **Follow Best Practices** → [Best Practices & Tips](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/best-practices)

{% hint style="success" %}
**Professional Tip**: Document every optimization. Keep a spreadsheet with date, parameters optimized, ranges used, in-sample results, out-of-sample results, and final decision. This becomes your optimization history and learning log!
{% endhint %}

***

## Related Resources

* [Optimization Fundamentals](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/optimization-fundamentals) - Theory and concepts
* [Analyzing Results](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/analyzing-results) - Understanding your data
* [Best Practices & Tips](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/best-practices) - Professional workflow
* [Advanced Optimization](https://itradeaims.gitbook.io/banana-ea/backtesting-and-optimization/backtesting-optimization/advanced-optimization) - Walk-forward, Monte Carlo
