> 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/strategy-generation.md).

# Strategy Generation

## The `@vibe` Decorator

Every strategy must have exactly ONE function decorated with `@vibe`. This registers the function as a callback that the engine executes at each tick.

```python
from vibetrading import vibe

@vibe(interval="1m")
def on_tick():
    pass
```

For live trading, always use `interval="1m"`. Implement frame-skipping for longer intervals:

```python
last_execution_time = None

@vibe(interval="1m")
def strategy():
    global last_execution_time
    current_time = get_current_time()

    manage_risk()

    if last_execution_time and (current_time - last_execution_time).total_seconds() < 300:
        return
    last_execution_time = current_time
    # ... main logic ...
```

## Write Strategies Manually

You can write strategies by hand. A strategy is a Python function decorated with `@vibe`:

```python
import math
import ta
from vibetrading import (
    vibe,
    get_current_time,
    get_perp_price,
    get_futures_ohlcv,
    get_perp_summary,
    get_perp_position,
    long,
    reduce_position,
    set_leverage,
)

ASSET = "BTC"
LEVERAGE = 3
TP_PCT = 0.08
SL_PCT = 0.04
RISK_PER_TRADE_PCT = 0.10
RSI_OVERSOLD = 30
SMA_FAST = 10
SMA_SLOW = 20


@vibe(interval="1m")
def my_strategy():
    current_price = get_perp_price(ASSET)
    if math.isnan(current_price):
        return

    perp_summary = get_perp_summary()
    available_margin = perp_summary.get("available_margin", 0.0)
    position = get_perp_position(ASSET)

    if position:
        size = position.get("size", 0.0)
        entry_price = position.get("entry_price", 0.0)
        pnl_pct = (current_price - entry_price) / entry_price if entry_price > 0 else 0

        if pnl_pct >= TP_PCT:
            reduce_position(ASSET, abs(size) * 0.5)
            return
        elif pnl_pct <= -SL_PCT:
            reduce_position(ASSET, abs(size))
            return
        return

    ohlcv = get_futures_ohlcv(ASSET, "1m", SMA_SLOW + 10)
    if len(ohlcv) < SMA_SLOW:
        return

    rsi = ta.momentum.rsi(ohlcv["close"], window=14).iloc[-1]
    sma_fast = ohlcv["close"].rolling(SMA_FAST).mean().iloc[-1]
    sma_slow = ohlcv["close"].rolling(SMA_SLOW).mean().iloc[-1]

    if rsi < RSI_OVERSOLD and sma_fast > sma_slow:
        set_leverage(ASSET, LEVERAGE)
        qty = (available_margin * RISK_PER_TRADE_PCT * LEVERAGE) / current_price
        long(ASSET, qty, price=current_price)
```

> **Note:** Strategy code uses `from vibetrading import vibe, get_price, ...` — these symbols are injected at runtime by the backtest engine or live runner. They don't need to be real functions in the package.

## AI-Powered Generation

### Convenience Function

The simplest way to generate a strategy:

```python
import vibetrading.strategy

code = vibetrading.strategy.generate(
    "BTC scalping strategy with VWAP",
    model="gpt-4o",
)
```

### StrategyGenerator Class

For repeated generation or custom configuration:

```python
import vibetrading.strategy

generator = vibetrading.strategy.StrategyGenerator(model="gpt-4o")
code = generator.generate(
    "BTC scalping strategy with VWAP",
    validate=True,
    max_retries=3,
)
```

### Closed-Loop: Validate → Fix

The validator produces structured feedback that can be fed back to the LLM:

```python
import vibetrading.strategy

messages = vibetrading.strategy.build_generation_prompt("BTC scalping strategy with VWAP")

code = call_your_llm(messages)
result = vibetrading.strategy.validate(code)

if not result.is_valid:
    messages.append({"role": "assistant", "content": code})
    messages.append({"role": "user", "content": result.format_for_llm()})
    code = call_your_llm(messages)
```

### Closed-Loop: Backtest → Analyze → Regenerate

For iterative improvement based on backtest performance:

```python
import vibetrading.strategy
import vibetrading.backtest

code = vibetrading.strategy.generate("BTC momentum with RSI", model="gpt-4o")
results = vibetrading.backtest.run(code, interval="1h", data=data)

report = vibetrading.strategy.analyze(results, strategy_code=code)
# report.format_for_llm() produces structured feedback for the next generation

improved = vibetrading.strategy.generate(
    "BTC momentum with RSI",
    model="gpt-4o",
    feedback=report.format_for_llm(),
)
```

Or use `vibetrading.strategy.generate()` and `vibetrading.strategy.analyze()` in a loop to iterate manually.

### Agent Integration Components

| Component                   | Import                                           | Purpose                                            |
| --------------------------- | ------------------------------------------------ | -------------------------------------------------- |
| generate()                  | vibetrading.strategy.generate                    | Generate strategy from natural language            |
| validate()                  | vibetrading.strategy.validate                    | Validate generated code                            |
| analyze()                   | vibetrading.strategy.analyze                     | LLM-powered backtest analysis                      |
| StrategyGenerator           | vibetrading.strategy.StrategyGenerator           | Full generation + validation pipeline              |
| BacktestAnalyzer            | vibetrading.strategy.BacktestAnalyzer            | LLM-powered backtest analysis (class)              |
| BacktestAnalysisResult      | vibetrading.strategy.BacktestAnalysisResult      | Structured analysis result                         |
| STRATEGY\_SYSTEM\_PROMPT    | vibetrading.strategy.STRATEGY\_SYSTEM\_PROMPT    | Complete system prompt for LLM strategy generation |
| VIBETRADING\_API\_REFERENCE | vibetrading.strategy.VIBETRADING\_API\_REFERENCE | API documentation string                           |
| STRATEGY\_CONSTRAINTS       | vibetrading.strategy.STRATEGY\_CONSTRAINTS       | Code generation rules                              |
| build\_generation\_prompt() | vibetrading.strategy.build\_generation\_prompt   | Build message list for chat completion             |


---

# 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/strategy-generation.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.
