347 lines
6.7 KiB
Markdown
347 lines
6.7 KiB
Markdown
# AI Trading Bot - Build Spec
|
|
|
|
Full-stack grid trading bot with Binance + AI optimization. Extensible for future strategies.
|
|
|
|
---
|
|
|
|
## STACK
|
|
|
|
**Backend:** FastAPI, PostgreSQL + TimescaleDB, Redis, Celery, ccxt, anthropic
|
|
**Frontend:** Vue 3, Vite, TailwindCSS, Lightweight Charts, Pinia
|
|
**Deploy:** Docker compose
|
|
|
|
---
|
|
|
|
## REQUIREMENTS
|
|
|
|
### 1. Binance Integration
|
|
```python
|
|
# Connect to Binance (testnet + mainnet toggle)
|
|
# Real-time price via WebSocket
|
|
# Place/cancel limit orders
|
|
# Get balance, positions, order status, trade history
|
|
# Rate limiting, auto-reconnect, health checks
|
|
```
|
|
|
|
### 2. Grid Trading Strategy
|
|
```python
|
|
# Calculate support/resistance
|
|
# Generate N buy orders (lower bound → mid)
|
|
# Generate N sell orders (mid → upper bound)
|
|
# Monitor fills, rebalance grid
|
|
# Track P&L per trade
|
|
|
|
# User config:
|
|
- pair (BTC/USDT)
|
|
- capital ($10k)
|
|
- lower_bound ($95k)
|
|
- upper_bound ($105k)
|
|
- grid_levels (20)
|
|
- stop_loss_pct (2%)
|
|
```
|
|
|
|
### 3. AI Optimization
|
|
```python
|
|
# Call Claude API with market data:
|
|
- current price, 24h range
|
|
- volatility, volume
|
|
- support/resistance levels
|
|
|
|
# AI returns JSON:
|
|
{
|
|
"grid_lower": 95000,
|
|
"grid_upper": 105000,
|
|
"num_levels": 20,
|
|
"confidence": 78,
|
|
"reasoning": "...",
|
|
"risk_level": "medium"
|
|
}
|
|
|
|
# User can accept/reject AI suggestions
|
|
```
|
|
|
|
### 4. Trading Modes
|
|
- **Paper Mode:** Simulate orders, fake money, real prices
|
|
- **Live Mode:** Real execution, confirmation required
|
|
|
|
### 5. Dashboard (Vue 3)
|
|
```
|
|
[Header]
|
|
- P&L today / all-time
|
|
- Balance
|
|
- PAPER/LIVE indicator
|
|
- Emergency STOP button
|
|
|
|
[Bot Status Card]
|
|
- Strategy: Grid Trading
|
|
- Pair: BTC/USDT
|
|
- Status: Running/Stopped
|
|
- Grid: $95k - $105k
|
|
- Open orders: 15/20
|
|
- Realized P&L: +$234
|
|
- Unrealized P&L: +$45
|
|
- [Start] [Stop] [Configure]
|
|
|
|
[Price Chart]
|
|
- TradingView chart
|
|
- Grid levels overlay
|
|
- Buy/sell markers
|
|
|
|
[Trade History Table]
|
|
- Last 20 trades
|
|
- Time | Side | Price | Amount | P&L
|
|
|
|
[Stats]
|
|
- Win rate, total trades, avg profit, max drawdown
|
|
```
|
|
|
|
### 6. Config Page
|
|
```
|
|
Form fields:
|
|
- Trading pair (dropdown)
|
|
- Capital ($)
|
|
- Grid lower/upper (AI suggests button)
|
|
- Grid levels (slider 10-50)
|
|
- Stop loss %
|
|
- Max daily loss ($)
|
|
- API keys (encrypted)
|
|
- Paper/Live toggle
|
|
|
|
[Save] [AI Optimize] [Test Config]
|
|
```
|
|
|
|
---
|
|
|
|
## DATABASE SCHEMA
|
|
|
|
```sql
|
|
-- users
|
|
CREATE TABLE users (
|
|
id SERIAL PRIMARY KEY,
|
|
email VARCHAR(255) UNIQUE,
|
|
api_key_encrypted TEXT,
|
|
api_secret_encrypted TEXT,
|
|
created_at TIMESTAMP DEFAULT NOW()
|
|
);
|
|
|
|
-- bots
|
|
CREATE TABLE bots (
|
|
id SERIAL PRIMARY KEY,
|
|
user_id INTEGER REFERENCES users(id),
|
|
strategy VARCHAR(50), -- 'grid'
|
|
pair VARCHAR(20), -- 'BTC/USDT'
|
|
status VARCHAR(20), -- 'running', 'stopped'
|
|
config JSONB,
|
|
created_at TIMESTAMP DEFAULT NOW()
|
|
);
|
|
|
|
-- orders
|
|
CREATE TABLE orders (
|
|
id SERIAL PRIMARY KEY,
|
|
bot_id INTEGER REFERENCES bots(id),
|
|
exchange_order_id VARCHAR(100),
|
|
side VARCHAR(10), -- 'buy', 'sell'
|
|
price DECIMAL(20, 8),
|
|
amount DECIMAL(20, 8),
|
|
status VARCHAR(20), -- 'open', 'filled', 'cancelled'
|
|
created_at TIMESTAMP DEFAULT NOW()
|
|
);
|
|
|
|
-- trades (filled pairs)
|
|
CREATE TABLE trades (
|
|
id SERIAL PRIMARY KEY,
|
|
bot_id INTEGER REFERENCES bots(id),
|
|
buy_order_id INTEGER REFERENCES orders(id),
|
|
sell_order_id INTEGER REFERENCES orders(id),
|
|
profit DECIMAL(20, 8),
|
|
created_at TIMESTAMP DEFAULT NOW()
|
|
);
|
|
|
|
-- prices (TimescaleDB hypertable)
|
|
CREATE TABLE prices (
|
|
time TIMESTAMPTZ NOT NULL,
|
|
symbol VARCHAR(20),
|
|
open DECIMAL(20, 8),
|
|
high DECIMAL(20, 8),
|
|
low DECIMAL(20, 8),
|
|
close DECIMAL(20, 8),
|
|
volume DECIMAL(20, 8)
|
|
);
|
|
SELECT create_hypertable('prices', 'time');
|
|
```
|
|
|
|
---
|
|
|
|
## API ENDPOINTS
|
|
|
|
```python
|
|
# Auth
|
|
POST /api/auth/register
|
|
POST /api/auth/login
|
|
|
|
# Bots
|
|
GET /api/bots
|
|
POST /api/bots
|
|
GET /api/bots/{id}
|
|
PUT /api/bots/{id}
|
|
POST /api/bots/{id}/start
|
|
POST /api/bots/{id}/stop
|
|
|
|
# Trading
|
|
GET /api/orders
|
|
GET /api/trades
|
|
GET /api/balance
|
|
|
|
# AI
|
|
POST /api/ai/optimize # body: {pair, capital, volatility, ...}
|
|
|
|
# Market
|
|
GET /api/market/price/{symbol}
|
|
GET /api/market/indicators/{symbol}
|
|
|
|
# WebSocket
|
|
WS /ws/bot/{id} # real-time updates
|
|
WS /ws/market/{symbol} # price feed
|
|
```
|
|
|
|
---
|
|
|
|
## STRATEGY PLUGIN INTERFACE
|
|
|
|
```python
|
|
# For future extensibility
|
|
from abc import ABC, abstractmethod
|
|
|
|
class TradingStrategy(ABC):
|
|
@abstractmethod
|
|
def initialize(self, config: dict):
|
|
"""Setup strategy"""
|
|
pass
|
|
|
|
@abstractmethod
|
|
def generate_signals(self, market_data: dict) -> List[Signal]:
|
|
"""Return buy/sell signals"""
|
|
pass
|
|
|
|
@abstractmethod
|
|
def optimize_with_ai(self, ai_client) -> dict:
|
|
"""Get AI suggestions"""
|
|
pass
|
|
|
|
# Grid strategy implements this
|
|
# Future strategies (mean reversion, momentum) implement this
|
|
# Registry: STRATEGIES = {'grid': GridStrategy, ...}
|
|
```
|
|
|
|
---
|
|
|
|
## SECURITY
|
|
|
|
- Encrypt API keys (AES-256)
|
|
- Hash passwords (bcrypt)
|
|
- JWT auth tokens
|
|
- Rate limit all endpoints
|
|
- Confirmation prompt for live mode
|
|
- Daily loss limits enforced
|
|
- Emergency stop kills all orders
|
|
|
|
---
|
|
|
|
## DOCKER SETUP
|
|
|
|
```yaml
|
|
services:
|
|
backend:
|
|
build: ./backend
|
|
environment:
|
|
- DATABASE_URL=postgresql://...
|
|
- REDIS_URL=redis://...
|
|
- BINANCE_TESTNET=true
|
|
depends_on:
|
|
- postgres
|
|
- redis
|
|
|
|
frontend:
|
|
build: ./frontend
|
|
ports:
|
|
- "80:80"
|
|
|
|
postgres:
|
|
image: timescale/timescaledb:latest-pg15
|
|
volumes:
|
|
- pgdata:/var/lib/postgresql/data
|
|
|
|
redis:
|
|
image: redis:alpine
|
|
|
|
celery:
|
|
build: ./backend
|
|
command: celery -A app.celery worker
|
|
```
|
|
|
|
---
|
|
|
|
## SUCCESS CRITERIA
|
|
|
|
Bot works when:
|
|
- [x] Connects to Binance testnet
|
|
- [x] Places grid orders via UI
|
|
- [x] Dashboard shows live P&L
|
|
- [x] AI suggests parameters
|
|
- [x] Paper trading tracks correctly
|
|
- [x] Start/stop works
|
|
- [x] Runs stable 24h+
|
|
- [x] WebSocket updates real-time
|
|
|
|
---
|
|
|
|
## PROJECT STRUCTURE
|
|
|
|
```
|
|
/backend
|
|
/app
|
|
/api # FastAPI routes
|
|
/strategies # grid.py, base.py
|
|
/services # binance.py, ai.py
|
|
/models # db models
|
|
main.py
|
|
requirements.txt
|
|
|
|
/frontend
|
|
/src
|
|
/components # BotCard.vue, PriceChart.vue, etc.
|
|
/views # Dashboard.vue, Config.vue
|
|
/stores # botStore.js
|
|
vite.config.js
|
|
|
|
docker-compose.yml
|
|
.env.example
|
|
README.md
|
|
```
|
|
|
|
---
|
|
|
|
## CRITICAL RULES
|
|
|
|
- Start with paper trading ONLY
|
|
- Use Binance testnet for dev
|
|
- No leverage/margin (spot only)
|
|
- Validate all inputs
|
|
- Log everything
|
|
- Test grid math extensively
|
|
- AI suggestions are optional (user confirms)
|
|
|
|
---
|
|
|
|
## DELIVERABLES
|
|
|
|
1. Working grid bot (paper mode)
|
|
2. Vue dashboard with real-time updates
|
|
3. Docker compose setup
|
|
4. README with setup steps
|
|
5. .env.example with all variables
|
|
|
|
---
|
|
|
|
**BUILD THIS.** No phases, no fluff. Grid strategy working end-to-end, extensible for future strategies.
|