> 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/api-reference.md).

# API Reference

## Package Modules

```
import vibetrading                # vibe decorator
import vibetrading.strategy       # generate, validate, analyze strategies
import vibetrading.backtest       # backtest engine (BacktestEngine, run())
import vibetrading.tools          # data download & CSV loading
```

## Strategy API (`vibetrading.strategy`)

| Function / Class             | Purpose                                           |
| ---------------------------- | ------------------------------------------------- |
| generate(prompt, model, ...) | Generate strategy code from natural language      |
| validate(code)               | Static analysis — catches errors before execution |
| analyze(results, ...)        | LLM evaluates backtest results (score + feedback) |
| StrategyGenerator            | Full generation + validation pipeline (class)     |
| BacktestAnalyzer             | LLM-powered backtest analysis (class)             |
| BacktestAnalysisResult       | Structured analysis result dataclass              |
| StrategyValidationResult     | Validation result dataclass                       |
| build\_generation\_prompt()  | Build message list for chat completion            |
| STRATEGY\_SYSTEM\_PROMPT     | Complete system prompt for LLM generation         |
| VIBETRADING\_API\_REFERENCE  | API documentation string for prompts              |
| STRATEGY\_CONSTRAINTS        | Code generation rules for prompts                 |

## Backtest API (`vibetrading.backtest`)

| Function / Class               | Purpose                                       |
| ------------------------------ | --------------------------------------------- |
| run(code, data, interval, ...) | Quick backtest — returns results dict         |
| BacktestEngine                 | Full engine with custom configuration (class) |

## Tools API (`vibetrading.tools`)

| Function                    | Purpose                      |
| --------------------------- | ---------------------------- |
| download\_data(assets, ...) | Download OHLCV data via CCXT |
| load\_csv(path)             | Load local CSV data          |

## The Sandbox Interface

All trading operations inside strategy code go through a unified interface. Whether backtesting or live trading, the API is identical:

| Category     | Functions                                                                              |
| ------------ | -------------------------------------------------------------------------------------- |
| **Account**  | get\_spot\_summary(), get\_perp\_summary(), get\_perp\_position(asset)                 |
| **Trading**  | buy(asset, qty, price), sell(asset, qty, price)                                        |
| **Futures**  | long(asset, qty, price), short(asset, qty, price), reduce\_position(asset, qty)        |
| **Leverage** | set\_leverage(asset, leverage)                                                         |
| **Price**    | get\_perp\_price(asset), get\_spot\_price(asset)                                       |
| **OHLCV**    | get\_spot\_ohlcv(asset, interval, limit), get\_futures\_ohlcv(asset, interval, limit)  |
| **Funding**  | get\_funding\_rate(asset), get\_funding\_rate\_history(asset, limit)                   |
| **OI**       | get\_open\_interest(asset), get\_open\_interest\_history(asset, limit)                 |
| **Orders**   | get\_perp\_open\_orders(), get\_spot\_open\_orders(), cancel\_perp\_orders(asset, ids) |
| **Time**     | get\_current\_time()                                                                   |

> These functions are injected at runtime by the backtest engine or live runner. In strategy code, import them with `from vibetrading import vibe, get_perp_price, long, ...`.

## Architecture

```
User Prompt (natural language)
         │
         ▼
┌─────────────────────────┐
│   LLM Agent             │  ← any model (GPT, Claude, Gemini, ...)
│   + prompt template     │  ← vibetrading.strategy.STRATEGY_SYSTEM_PROMPT
└────────┬────────────────┘
         │ generates
         ▼
Strategy Code (@vibe decorated)
         │
         ▼
┌─────────────────────────┐
│   Backtest Engine       │  ← vibetrading.backtest.run()
│   (historical data)     │  ← vibetrading.tools.download_data()
└────────┬────────────────┘
         │ results
         ▼
┌─────────────────────────┐
│   LLM Analyzer          │  ← vibetrading.strategy.analyze()
│   (score + feedback)    │
└────────┬────────────────┘
         │ feedback
         ▼
    (iterate manually)
```

## Project Structure

```
vibetrading/
├── __init__.py          # Package root (vibe decorator, version)
├── strategy.py          # → vibetrading.strategy (generate, validate, analyze, prompts)
├── backtest.py          # → vibetrading.backtest (BacktestEngine, run())
├── tools.py             # → vibetrading.tools (download_data, load_csv)
├── _config.py           # Configuration & exchange registry
├── _agent/              # Strategy generation & analysis internals
│   ├── generator.py     #   StrategyGenerator, generate()
│   ├── validator.py     #   validate(), StrategyValidationResult
│   ├── analyzer.py      #   BacktestAnalyzer, analyze(), BacktestAnalysisResult
│   └── prompt.py        #   System prompts & prompt templates
├── _core/               # Core engine internals
├── _metrics/            # Performance metrics calculator
├── _tools/              # Data acquisition internals
└── _utils/              # Utilities
```


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.vibetrading.dev/library/api-reference.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
