> For the complete documentation index, see [llms.txt](https://docs.vibetrading.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.vibetrading.dev/library/backtesting.md).

# Backtesting

## Run a Backtest

```python
from datetime import datetime, timezone

import vibetrading.backtest
import vibetrading.tools

start = datetime(2025, 1, 1, tzinfo=timezone.utc)
end = datetime(2025, 7, 1, tzinfo=timezone.utc)

data = vibetrading.tools.download_data(
    ["BTC"],
    exchange="binance",
    start_time=start,
    end_time=end,
    interval="1h",
)

engine = vibetrading.backtest.BacktestEngine(
    start_time=start,
    end_time=end,
    interval="1h",
    exchange="binance",
    initial_balances={"USDC": 10000},
    data=data,
)

results = engine.run(strategy_code)

print(results["metrics"])
```

## Quick Backtest with `run()`

For a simpler interface, use the `run()` shortcut:

```python
results = vibetrading.backtest.run(
    code,
    start_time=start,
    end_time=end,
    interval="1h",
    data=data,
)
```

## Backtest Results

`engine.run()` returns a dictionary containing:

```python
results["metrics"]          # Performance metrics dict
results["trades"]           # List of all executed trades
results["final_balances"]   # Final asset balances
results["results"]          # Time-series DataFrame of portfolio values
results["simulation_info"]  # Metadata (steps, time range, liquidation status)
```

## Metrics

| Metric                          | Description                            |
| ------------------------------- | -------------------------------------- |
| total\_return                   | Total portfolio return (decimal)       |
| max\_drawdown                   | Maximum peak-to-trough drawdown        |
| sharpe\_ratio                   | Annualized Sharpe ratio                |
| win\_rate                       | Percentage of profitable closed trades |
| number\_of\_trades              | Total number of trades executed        |
| funding\_revenue                | Net funding payments received/paid     |
| total\_tx\_fees                 | Total transaction fees paid            |
| average\_trade\_duration\_hours | Mean holding period                    |

## Supported Intervals

`1s`, `1m`, `5m`, `15m`, `30m`, `1h`, `6h`, `1d`

## Supported Exchanges

Data is fetched from exchanges via CCXT. Download data first, then pass it to the backtest engine:

```python
import vibetrading.tools

data = vibetrading.tools.download_data(["BTC", "ETH"], exchange="binance", ...)
data = vibetrading.tools.download_data(["BTC"], exchange="bybit", ...)
data = vibetrading.tools.download_data(["BTC"], exchange="okx", ...)
```

## Next Steps

After backtesting, you can:

* [**Analyze results**](/library/backtest-analysis.md) — Use an LLM to score performance and get actionable improvement suggestions.
* **Iterate manually** — Use `vibetrading.strategy.generate()` and `vibetrading.strategy.analyze()` in a loop to refine based on feedback.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://docs.vibetrading.dev/library/backtesting.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.
