# Performance Optimization

## Strategy Optimization

### Parameter Tuning

**Key parameters to optimize:**

Focus on entry parameters including indicator periods, thresholds, and confirmation requirements. Optimize exit parameters such as take profit percentages, stop loss distance, and trailing stops. Fine-tune position sizing by testing fixed versus dynamic approaches, risk percentages, and leverage settings.

**Systematic approach:**

Start by identifying one parameter to test at a time, define a test range with appropriate increments, backtest each variation using the same time period, analyze results focusing on return, risk-adjusted metrics, and consistency, then validate findings with walk-forward testing.

### Walk-Forward Analysis

**Avoid overfitting:**

```
Training Period 1: Months 1-6 → Test: Months 7-8
Training Period 2: Months 3-8 → Test: Months 9-10
Continue pattern...

Requirement: Profit in ALL testing periods
```

**Red flags:**

Watch for perfect training performance with poor testing results indicating overfitting, inconsistent test results suggesting an unstable strategy, or degrading performance over time requiring market adaptation.

### Avoiding Overfitting

| Overfitted Strategy        | Robust Strategy                  |
| -------------------------- | -------------------------------- |
| 95%+ win rate in backtest  | Positive across multiple periods |
| >7 parameters              | 3-5 parameters                   |
| Perfect in one period only | Consistent performance           |
| Fails immediately live     | Works as expected                |

**Prevention:**

Keep strategies simple, limit the number of parameters, test out-of-sample data, and require consistent performance across different market conditions.

## Execution Optimization

### Order Type Selection

| Order Type     | Best When                | Cost                             | Best For                          |
| -------------- | ------------------------ | -------------------------------- | --------------------------------- |
| **Market**     | Need immediate execution | Higher slippage                  | Emergency exits, volatile markets |
| **Limit**      | Can wait for price       | Lower slippage, might not fill   | Normal entries, take profits      |
| **Stop-Limit** | Triggered stops          | Control slippage, might not fill | Stop losses in liquid markets     |

### Slippage & Fee Reduction

**Minimize costs:**

Use limit orders to benefit from maker fees and reduce trading costs. Avoid low liquidity periods when spreads are wider and execution is more expensive. Split large orders across time to minimize market impact and improve fill prices. Trade on exchanges with deep liquidity for better execution and tighter spreads.

**Fee impact example:**

```
High-frequency (100 trades/month): 20% monthly cost
Low-frequency (10 trades/month): 2% monthly cost
Fee impact is MASSIVE - reduce frequency where possible
```

## Bot Configuration

### Refresh Rate

| Frequency | Responsiveness  | API Usage                 | Best For          |
| --------- | --------------- | ------------------------- | ----------------- |
| 1 second  | Most responsive | Highest (rate limit risk) | Scalping only     |
| 15-30 sec | Good balance    | Moderate                  | Most strategies ✓ |
| 1-5 min   | Delayed         | Minimal                   | Swing trading     |

**Match frequency to strategy timeframe**

### Risk Limit Tuning

| Limit Type        | Too Tight               | Too Loose                    | Optimal                   |
| ----------------- | ----------------------- | ---------------------------- | ------------------------- |
| **Daily Loss**    | $100 (normal variance)  | $5,000 (catastrophic)        | $500-1,000 (2-4% capital) |
| **Position Size** | 5% max (inefficient)    | 50% max (concentration risk) | 15-25% max                |
| **Max Drawdown**  | 15% (pauses frequently) | 40% (large losses)           | 20-25% (breathing room)   |

### Concurrent Positions

**Analysis for $50K account:**

```
Position size: $10,000
Max positions: 5

Benefits include diversified exposure across assets, avoiding over-concentration risk, manageable monitoring requirements, and efficient capital utilization.
```

## Market Timing

### Trading Hours

**Analyze performance by time:**

```
Example 6-month analysis:
8:00-12:00 UTC: +8% (best)
12:00-16:00 UTC: +4%
0:00-4:00 UTC: -2% (worst)

Optimization: Trade only during profitable hours
```

### Market Condition Filters

**Volatility filter:**

```
IF volatility > 2x average: Reduce position 50%
ELSE IF volatility < 0.5x average: Skip (too quiet)
ELSE: Normal trading
```

**Trend filter:**

```
IF 200-MA trending up: Long trades only
ELSE IF trending down: Short trades only
ELSE: Mean reversion strategy
```

## Performance Monitoring

**Track these metrics:**

| Metric         | Target   | Warning            |
| -------------- | -------- | ------------------ |
| Win Rate       | >45%     | <35%               |
| Profit Factor  | >1.3     | <1.0               |
| Sharpe Ratio   | >1.0     | <0.5               |
| Max Drawdown   | <20%     | >30%               |
| Monthly Return | Positive | Negative 2+ months |

**Weekly review checklist:**

Compare actual performance to backtest expectations, check slippage against projections, verify fee calculations, review losing trades for patterns, and monitor market regime changes.

## Common Optimization Mistakes

**Over-optimization:**

Perfect backtest results with poor live performance indicate overfitting. Fix by using simpler strategies and walk-forward validation to ensure robustness.

**Ignoring costs:**

Backtests that don't include realistic fees and slippage lead to inflated expectations. Fix by modeling realistic execution costs in all backtests.

**Too frequent trading:**

Excessive trading costs can eat into profits through "death by a thousand fees." Fix by reducing trade frequency and using higher timeframes to minimize costs.

**No market filtering:**

Trading in all market conditions without filtering can lead to poor performance. Fix by adding volatility and trend filters to avoid unfavorable market conditions.

***

**Continuous improvement:** Review performance weekly, optimize quarterly, stay adaptive to changing markets.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://quantsedge.gitbook.io/quantsedge-docs/advanced-topics/performance-optimization.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
