# Welcome

Describe trading strategies in natural language. Generate executable Python. Backtest, analyze, and deploy with LLM-powered feedback.

```
pip install vibetrading
```

***

## What is VibeTrading?

VibeTrading is an open-source trading framework where users describe strategies in natural language and AI agents generate, backtest, and analyze executable code.

### How It Works

**1. Describe** — Tell the agent what you want in plain English.

**2. Generate** — AI produces framework-compatible strategy code with proper risk management.

**3. Backtest** — Run against historical data from any CCXT-supported exchange.

**4. Analyze** — An LLM evaluates backtest results: scores performance (1-10), finds weaknesses, suggests fixes.

**5. Iterate** — Refine based on analysis and repeat.

```
Describe ──▶ Generate ──▶ Backtest ──▶ Analyze ──▶ Iterate
(prompt)      (LLM)        (engine)     (LLM)       (refine)
                ▲                                      │
                └──────────── feedback ────────────────┘
```

***

## Quick Example

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

# 1. Generate strategy from natural language
code = vibetrading.strategy.generate(
    "ETH mean reversion with Bollinger Bands, short when price hits upper band, "
    "long when price hits lower band, 5x leverage",
    model="gpt-4o",
)

# 2. Backtest
data = vibetrading.tools.download_data(["ETH"], exchange="binance", interval="1h")
results = vibetrading.backtest.run(code, interval="1h", data=data)

if results:
    metrics = results["metrics"]
    print(f"Return: {metrics['total_return']:.2%}")
    print(f"Sharpe: {metrics['sharpe_ratio']:.2f}")
    print(f"Max Drawdown: {metrics['max_drawdown']:.2%}")

# 3. Analyze with LLM
report = vibetrading.strategy.analyze(results, strategy_code=code)
print(f"Score: {report.score}/10")
print(report.suggestions)
```

***

## 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
```

***

## Links

* [GitHub](https://github.com/VibeTradingLabs/vibetrading)
* [PyPI](https://pypi.org/project/vibetrading/)
* [Community](/resources/community)


# Installation

## Install

```bash
pip install vibetrading
```

All core dependencies are included: `pandas`, `numpy`, `pydantic`, `ccxt`, `litellm`, `ta`, and `python-dotenv`.

## Setup

Set at least one LLM API key for strategy generation and analysis:

```bash
export OPENAI_API_KEY=sk-...
# or
export ANTHROPIC_API_KEY=sk-ant-...
# or
export GEMINI_API_KEY=...
# or
export DEEPSEEK_API_KEY=...
```

Optional — if you need an HTTPS proxy:

```bash
export HTTPS_PROXY=http://127.0.0.1:7890
```

Or put them in a `.env` file in your project root — the package loads it automatically via `python-dotenv`.

## With Exchange Adapters (optional)

Exchange adapters are available as optional extras for live trading integration:

```bash
pip install "vibetrading[hyperliquid]"   # Hyperliquid L1
pip install "vibetrading[extended]"      # X10 Extended (StarkNet)
pip install "vibetrading[paradex]"       # Paradex (StarkNet)
pip install "vibetrading[lighter]"       # Lighter (zkSync Era)
pip install "vibetrading[aster]"         # Aster Protocol

pip install "vibetrading[all]"           # Everything
```

## Requirements

* Python >= 3.10
* pandas >= 2.0
* numpy >= 1.24
* pydantic >= 2.0
* python-dotenv >= 1.0
* ccxt >= 4.0
* litellm >= 1.80
* ta >= 0.11


# Quick Start

## Setup

Install and set your LLM API key:

```bash
pip install vibetrading
export OPENAI_API_KEY=sk-...   # or ANTHROPIC_API_KEY, GEMINI_API_KEY, etc.
```

## Generate a Strategy

```python
import vibetrading.strategy

code = vibetrading.strategy.generate(
    "BTC momentum strategy: RSI(14) oversold entry, SMA crossover confirmation, "
    "3x leverage, 10% position size, 8% take-profit, 4% stop-loss",
    model="gpt-4o",
)

print(code)
```

## Backtest

```python
import vibetrading.backtest
import vibetrading.tools

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

results = vibetrading.backtest.run(code, interval="1h", data=data)

if results:
    metrics = results["metrics"]
    print(f"Return: {metrics['total_return']:.2%}")
    print(f"Sharpe: {metrics['sharpe_ratio']:.2f}")
    print(f"Max Drawdown: {metrics['max_drawdown']:.2%}")
    print(f"Win Rate: {metrics['win_rate']:.2%}")
```

## Analyze Results

Use an LLM to evaluate backtest performance:

```python
report = vibetrading.strategy.analyze(results, strategy_code=code, model="gpt-4o")

print(f"Score: {report.score}/10")
print(report.summary)

for s in report.suggestions:
    print(f"  → {s}")
```

See [Backtest Analysis](/library/backtest-analysis) for full details.

## Use the Prompt Template with Any LLM

Don't want to use the built-in generator? Use the prompt template directly with any LLM client:

### OpenAI

```python
import openai
import vibetrading.strategy

messages = vibetrading.strategy.build_generation_prompt(
    "BTC grid strategy with 0.25% spacing, 72 levels per side, 5x leverage",
    assets=["BTC"],
    market_type="perp",
    max_leverage=5,
)

response = openai.chat.completions.create(model="gpt-4o", messages=messages)
strategy_code = response.choices[0].message.content
```

### Anthropic

```python
import anthropic
import vibetrading.strategy

messages = vibetrading.strategy.build_generation_prompt("SOL scalping with VWAP and RSI")

client = anthropic.Anthropic()
response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=4096,
    system=messages[0]["content"],
    messages=[{"role": "user", "content": messages[1]["content"]}],
)
strategy_code = response.content[0].text
```

## Validate Generated Code

Check generated strategy code for common errors before running:

```python
import vibetrading.strategy

result = vibetrading.strategy.validate(strategy_code)

if result.is_valid:
    print("Strategy passed validation")
else:
    print(result)
    feedback = result.format_for_llm()
```


# 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             |


# 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) — 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.


# Backtest Analysis

Use an LLM to evaluate backtest results — get a performance score (1-10), strengths, weaknesses, risk assessment, and actionable improvement suggestions.

## Quick Usage

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

results = vibetrading.backtest.run(strategy_code, interval="1h", data=data)

report = vibetrading.strategy.analyze(
    results,
    strategy_code=strategy_code,
    model="gpt-4o",
)

print(f"Score: {report.score}/10")
print(report.summary)
```

## `BacktestAnalysisResult`

The analysis returns a `BacktestAnalysisResult` with the following fields:

| Field              | Type       | Description                            |
| ------------------ | ---------- | -------------------------------------- |
| score              | int        | Overall score (1-10)                   |
| summary            | str        | 2-3 sentence assessment                |
| strengths          | list\[str] | What the strategy does well            |
| weaknesses         | list\[str] | Problems to address                    |
| risk\_assessment   | str        | Risk evaluation                        |
| suggestions        | list\[str] | Actionable improvement recommendations |
| detailed\_analysis | str        | Multi-paragraph deep analysis          |
| raw\_metrics       | dict       | The metrics dict that was analyzed     |

### Scoring Guidelines

| Score | Meaning     | Characteristics                                      |
| ----- | ----------- | ---------------------------------------------------- |
| 9-10  | Exceptional | Sharpe > 2.0, drawdown < 10%, strong win rate        |
| 7-8   | Good        | Positive risk-adjusted returns, manageable drawdowns |
| 5-6   | Mediocre    | Marginal returns or concerning risk metrics          |
| 3-4   | Poor        | Negative returns or extreme drawdowns                |
| 1-2   | Failing     | Liquidation, massive losses, or non-functional       |

## Reading the Report

```python
report = vibetrading.strategy.analyze(results, strategy_code=code)

# Score & summary
print(f"Score: {report.score}/10")
print(report.summary)

# Strengths
for s in report.strengths:
    print(f"  + {s}")

# Weaknesses
for w in report.weaknesses:
    print(f"  - {w}")

# Risk assessment
print(report.risk_assessment)

# Actionable suggestions
for i, s in enumerate(report.suggestions, 1):
    print(f"  {i}. {s}")

# Full analysis text
print(report.detailed_analysis)
```

## Feeding Analysis Back to the Generator

The analysis result includes `format_for_llm()` — a method that converts the report into structured feedback suitable for a follow-up generation call:

```python
import vibetrading.strategy

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

# Analyze
report = vibetrading.strategy.analyze(results, strategy_code=code)

# Feed back into generator for improvement
feedback = report.format_for_llm()
improved_code = vibetrading.strategy.generate(
    "BTC momentum with RSI",
    model="gpt-4o",
    feedback=feedback,
)
```

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

## Detail Levels

Control how much data is sent to the LLM:

```python
# Metrics only (fast, cheap)
report = vibetrading.strategy.analyze(results, detail_level="brief")

# Metrics + trade summary (default)
report = vibetrading.strategy.analyze(results, detail_level="standard")

# Metrics + trades + equity curve (most thorough)
report = vibetrading.strategy.analyze(results, detail_level="detailed")
```

## Using `BacktestAnalyzer` Directly

For repeated analysis or custom configuration:

```python
from vibetrading.strategy import BacktestAnalyzer

analyzer = BacktestAnalyzer(
    model="gpt-4o",
    temperature=0.3,
)

report1 = analyzer.analyze(results1, strategy_code=code1)
report2 = analyzer.analyze(results2, strategy_code=code2)
```


# 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
```


# Configuration

## LLM API Keys

Strategy generation and backtest analysis require an LLM. Set at least **one** of the following:

| Variable            | Provider              |
| ------------------- | --------------------- |
| OPENAI\_API\_KEY    | OpenAI (GPT-4o, etc.) |
| ANTHROPIC\_API\_KEY | Anthropic (Claude)    |
| GEMINI\_API\_KEY    | Google (Gemini)       |
| DEEPSEEK\_API\_KEY  | DeepSeek              |
| XAI\_API\_KEY       | xAI (Grok)            |

Any OpenAI-compatible endpoint is supported via [litellm](https://github.com/BerriAI/litellm).

## Network Proxy

If your network requires a proxy to reach LLM APIs:

| Variable     | Description     | Example                 |
| ------------ | --------------- | ----------------------- |
| HTTPS\_PROXY | HTTPS proxy URL | `http://127.0.0.1:7890` |

## Data & Exchange

| Variable                       | Description                         | Default   |
| ------------------------------ | ----------------------------------- | --------- |
| VIBETRADING\_DEFAULT\_EXCHANGE | Default exchange for data downloads | `binance` |

## Using a `.env` File

Create a `.env` file in your project root. The package loads it automatically at import time:

```bash
# .env
OPENAI_API_KEY=sk-...
HTTPS_PROXY=http://127.0.0.1:7890
```

See [`.env.dev_example`](https://github.com/VibeTradingLabs/vibetrading/blob/main/.env.dev_example) for a full template.


# Show Case

VibeTrading App is an AI-driven trading platform where autonomous agents can research, reason, backtest, and execute — safely and at scale.

{% embed url="<https://youtu.be/krdHHYms8XM>" %}

## Features

* **Natural Language → Production Agents**: Describe strategies in plain English; we handle the rest
* **Comprehensive Backtesting**: Validate against historical data before risking capital
* **Live Trading Integration**: Deploy agents with real-time market execution across CEX and DEX
* **Built-in Risk Management**: Automated controls, position sizing, and portfolio protection
* **Autonomous Strategy Iteration**: Agents continuously monitor live performance and adapt strategies based on market conditions
* **Transparent Operations**: Every decision is explainable, trackable, and auditable


# Top-5 Grids


# ETH Grid


# Bullish AAVE


# VibeAgent

Vibe is a **multi-agent trading system** that autonomously trades using **multiple signal channels**, while keeping execution and risk controls in your hands.

At a high level:

* **Signal Agents** continuously collect and interpret market signals from different channels
  * Today: **News** + **Whale activity**
  * Future: easily extendable to more channels (e.g., macro, funding, volatility, social, technicals)
* A **Portfolio Agent** acts as the “control layer”
  * fuses signals across channels
  * produces a clear per-asset intent (e.g., buy/sell/hold/watch)
  * keeps decisions consistent across the portfolio
* Your **Quant Program** is the execution and risk layer
  * defines **TP / SL**, sizing, exposure limits, and other risk rules
  * executes trades based on the Portfolio Agent’s intent, within your constraints

***

## End-to-End Flow

{% @mermaid/diagram content="flowchart TD
%% Top: Signal layer
subgraph SA\["Signal Agents"]
direction LR
N\["News Agent"]
W\["Whale Agent"]
F\["Future Agents<br/>(Extensible)"]
end

%% Middle: Decision layer
P\["Portfolio Agent<br/>(Signal Fusion & Control)"]

%% Bottom: Execution layer
subgraph EL
direction LR
Q\["Quant Program<br/>(TP/SL, Risk Rules)"]
X\["Exchange Execution"]
end

N --> P
W --> P
F --> P

P --> Q --> X" %}


# Supported Exchanges

| Exchanges   | Perp | Spot |
| ----------- | ---- | ---- |
| Hyperliquid | ✓    | ✓    |
| Lighter     | ✓    | -    |
| Aster       | ✓    | ✗    |
| Extended    | ✓    | -    |
| Paradex     | ✓    | -    |


# Hyperliquid API Key Setup Guide

Go to <https://app.hyperliquid.xyz/API> , make sure you have login the account you want to trade.

1.Type in the name of wallet annd click **generate**,then click **Authorize API Wallet**

<figure><img src="/files/HBomRn1RBJltPH5VRrEi" alt=""><figcaption></figcaption></figure>

2.Set the valid day of API and copy the **private key**, then click **Authorize**. The wallet extension will pop up to ask for sign.

<figure><img src="/files/XZNNkaWPdytqs66vYBDN" alt=""><figcaption></figcaption></figure>

3.After sign, there is a record of API wallet.

<figure><img src="/files/HTfMCt2MIontn1cte40v" alt=""><figcaption></figcaption></figure>

4.Go to <https://vibetrading.dev/settings/api_management> to submit the keys.

* Account Address: You hyperliquid login wallet
* API Key: The Private Key you copied in step 2.


# Lighter API Key Setup Guide

1.Go to https\://app.lighter.xyz/apikeys to generate Api Key

<figure><img src="/files/LopS7trhl5HPJdjBjDuh" alt=""><figcaption></figcaption></figure>

2.Generate API Key

<figure><img src="/files/O9dHaFKXuCysYTUkmFlj" alt=""><figcaption></figcaption></figure>

3.Copy API Key Index and Private Key, go to <https://vibetrading.dev/settings/api_management> setting:

Account Address: you loginned wallet.

API Key Index: API Key in Step 3

API Key: The Private Key in Step 3


# Aster API Key Setup Guide

Please goto&#x20;

1.Go to <https://www.asterdex.com/en/api-wallet>  to create a ProA AI

<figure><img src="/files/TCx3H379r5MG2oSqi4Rw" alt=""><figcaption></figcaption></figure>

2.Click 'Authorize new API wallet', after filling some of sort, click 'Authorize', wallet extension would pop up for sign

<figure><img src="/files/gK1xItyTN3ij1s66nz9m" alt=""><figcaption></figcaption></figure>

2.Go to <https://vibetrading.dev/settings/api_management> , fill the form accordingly.

3.Fill the API key with following definition.

Account Address: Your loginin wallet address.

API Key: API Key in&#x20;


# Community

Join our community of traders and developers to share strategies and get support.

## Connect With Us

* Twitter: [@vibetrading\_dev](https://x.com/vibetrading_dev)
* Discord: [@vibetrading\_dev](https://discord.com/invite/3sQCQEQmRq)

We look forward to seeing you in our community!


# Changelog

## 2026/03/24

* **Removed** `vibetrading.evolution` module (`StrategyEvolver`, `evolve()`, `EvolutionStep`, `EvolutionResult`) — the project now focuses on generate → backtest → analyze workflows. Users can iterate manually using `vibetrading.strategy.generate()` and `vibetrading.strategy.analyze()`.

## 2026/02/26

* Added LLM-powered backtest analysis (`vibetrading.strategy.analyze()`): scores performance (1-10), identifies strengths/weaknesses, and suggests actionable improvements.
* ~~Added strategy evolution (`vibetrading.evolve()`): iteratively improves strategies through generate → backtest → analyze → regenerate feedback loops.~~ *(removed in v0.4.0)*
* ~~New modules: `vibetrading.evolution` (StrategyEvolver, evolve), `vibetrading.strategy.BacktestAnalyzer`.~~ *(removed in v0.4.0)*
* Added `vibetrading.strategy.generate()` convenience function for one-call generation.
* Updated documentation: new pages for Backtest Analysis, updated Quick Start, API Reference, and Configuration.

## 2025/11/01

* Added Live Agent Edit feature.
* Improved live agent reports.

## 2025/10/23

* Added Live Agent Report feature.

## 2025/10/17

* Improved grid strategies.

## 2025/10/15

* Added Live Agent Chat feature.

## 2025/10/08

* Supported lighter and extended agent, fixed bugs in backtest.

## 2025/09/27

* Released agent showcase page and clone feature.

## 2025/09/23

* Improved Grid Strategies: better managed liquidations; VibeAgent inferred grid center from external data source.
* Backtest: fixed limit order one-side position issue.

## 2025/09/21

* Improved Grid Strategies: added intelligent limit order and position management.
* Backtest now supported simulating limit order and price matching.
* Improved backtest data ingestion and stability.

## 2025/09/15

* Live trade supported limit order and added set\_leverage/reduce\_position function.
* Added coin overview and market data analytics tool for IDE.

## 2025/09/12

* Improved VibeAgent’s strategy code generation.

## 2025/09/10

* Fixed streaming issue in backtesting.
* Added version selection feature in IDE.
* Upgraded VibeAgent architecture to support planning and complex external data.
* Supported external data source (defillama, search).

## 2025/09/05

* Added total transaction fees in backtest.
* Sped up page loading.
* Improved UI.

## 2025/08/31

* Added Paper trading feature, now available for risk-free practice.

## 2025/08/30

* Upgraded VibeAgent with improved intention tracking.


