# Backtesting Guide

This guide explains how to use the backtesting feature to evaluate trading strategies on historical data.

## Running a Backtest

1. Navigate to the **Backtesting** page
2. Configure your backtest in the form:
   - **Strategy**: Select a strategy from the dropdown (required)
   - **Symbol**: Trading pair to test (e.g., BTC/USD)
   - **Exchange**: Data source exchange (e.g., coinbase)
   - **Timeframe**: Data timeframe (1m, 5m, 15m, 1h, 4h, 1d) - 1h recommended for most strategies
   - **Start Date**: Beginning of test period (required)
   - **End Date**: End of test period (required)
   - **Initial Capital**: Starting capital in USD (default: $100)
   - **Slippage (%)**: Expected slippage percentage (default: 0.1%)
   - **Fee Rate (%)**: Trading fee percentage (default: 0.1%)
3. Click **Run Backtest**
4. A progress overlay will appear showing the backtest is running
5. An operations panel will show the running backtest with status
6. Wait for completion (you'll receive a success notification)
7. Review results in the **Backtest Results** section below

## Understanding Results

The backtest results include:

- **Total Return**: Overall percentage return
- **Sharpe Ratio**: Risk-adjusted return metric (higher is better)
- **Sortino Ratio**: Downside risk-adjusted return (higher is better)
- **Max Drawdown**: Largest peak-to-trough decline
- **Win Rate**: Percentage of profitable trades
- **Total Trades**: Number of trades executed
- **Final Value**: Portfolio value at end of backtest

## Exporting Results

After a backtest completes, you can export the results:

1. In the backtest results section, find the export buttons
2. **Export CSV**: 
   - Click **Export CSV** button
   - Downloads a CSV file with all trades from the backtest
   - File includes: timestamp, side, price, quantity, value
3. **Export PDF**:
   - Click **Export PDF** button
   - Generates a comprehensive PDF report
   - Includes charts, metrics, and trade analysis

Both exports are automatically named with the current date for easy organization.

## Parameter Optimization

Parameter optimization allows you to automatically find the best strategy parameters. This feature requires backend API support and will be available once the optimization endpoints are implemented.

The UI includes an information card explaining this feature. When available, you'll be able to:
- Select parameters to optimize
- Set parameter ranges
- Choose optimization method (Grid Search, Genetic Algorithm, Bayesian Optimization)
- View optimization progress
- Compare optimization results

## Interpreting Metrics

- **Sharpe Ratio > 1**: Good risk-adjusted returns
- **Max Drawdown < 20%**: Acceptable risk level
- **Win Rate > 50%**: More winning than losing trades

# Backtesting Guide

Learn how to test your trading strategies on historical data.

## What is Backtesting?

Backtesting is the process of testing a trading strategy on historical data to evaluate its performance before risking real money.

## Running a Backtest

1. Navigate to Backtest view
2. Select a strategy
3. Configure backtest parameters:
   - **Start Date**: Beginning of test period
   - **End Date**: End of test period
   - **Initial Capital**: Starting capital
   - **Symbol**: Trading pair to test
   - **Timeframe**: Data timeframe
4. Click "Run Backtest"
5. Wait for completion
6. Review results

## Backtest Parameters

### Time Period

- **Start Date**: When to begin the backtest
- **End Date**: When to end the backtest
- **Duration**: Length of test period
- Longer periods provide more reliable results

### Capital Settings

- **Initial Capital**: Starting amount (e.g., $10,000)
- **Currency**: Base currency (USD, EUR, etc.)

### Market Settings

- **Symbol**: Trading pair (BTC/USD, ETH/USD, etc.)
- **Timeframe**: Data granularity (1m, 5m, 1h, 1d)
- **Exchange**: Historical data source

## Understanding Results

### Performance Metrics

- **Total Return**: Overall profit/loss percentage
- **Final Capital**: Ending portfolio value
- **Sharpe Ratio**: Risk-adjusted return measure
- **Sortino Ratio**: Downside risk-adjusted return
- **Max Drawdown**: Largest peak-to-trough decline
- **Win Rate**: Percentage of profitable trades

### Trade Analysis

- **Total Trades**: Number of trades executed
- **Winning Trades**: Number of profitable trades
- **Losing Trades**: Number of unprofitable trades
- **Average Win**: Average profit per winning trade
- **Average Loss**: Average loss per losing trade
- **Profit Factor**: Ratio of gross profit to gross loss

### Charts

- **Equity Curve**: Portfolio value over time
- **Drawdown Chart**: Drawdown periods
- **Trade Distribution**: Win/loss distribution
- **Monthly Returns**: Performance by month

## Realistic Backtesting

Crypto Trader includes realistic backtesting features:

### Slippage

Slippage simulates the difference between expected and actual execution prices.

- **Default**: 0.1% for market orders
- **Configurable**: Adjust based on market conditions
- **Market Impact**: Larger orders have more slippage

### Fees

Trading fees are automatically included:

- **Maker Fees**: For limit orders (typically 0.1%)
- **Taker Fees**: For market orders (typically 0.2%)
- **Exchange-Specific**: Fees vary by exchange

### Order Execution

- **Market Orders**: Execute at current price + slippage
- **Limit Orders**: Execute only if price reaches limit
- **Partial Fills**: Large orders may fill partially

## Parameter Optimization

Optimize strategy parameters for better performance:

1. Select strategy
2. Choose parameters to optimize
3. Set parameter ranges
4. Select optimization method:
   - **Grid Search**: Test all combinations
   - **Genetic Algorithm**: Evolutionary optimization
   - **Bayesian Optimization**: Efficient parameter search
5. Run optimization
6. Review results and select best parameters

## Best Practices

1. **Use Sufficient Data**: Test on at least 6-12 months of data
2. **Avoid Overfitting**: Don't optimize too aggressively
3. **Test Multiple Periods**: Verify performance across different market conditions
4. **Consider Fees**: Always include realistic fees
5. **Check Slippage**: Account for execution costs
6. **Validate Results**: Compare with paper trading

## Limitations

Backtesting has limitations:

- **Past Performance**: Doesn't guarantee future results
- **Market Conditions**: Markets change over time
- **Data Quality**: Results depend on data accuracy
- **Execution**: Real trading may differ from simulation

## Exporting Results

Export backtest results for analysis:

1. Click "Export Results"
2. Choose format:
   - **CSV**: For spreadsheet analysis
   - **PDF**: For reports
3. Save file

## Troubleshooting

**No results?**
- Check date range has data
- Verify symbol is correct
- Check strategy parameters

**Unrealistic results?**
- Verify fees are enabled
- Check slippage settings
- Review data quality

