Perps-Terminal / backend /README.md
Naufal Arhab
fix(audit): refine bybit split-tp breakeven, 1000x chart scaling, and frontend surfacing
075133b
|
Raw History Blame Contribute Delete
5.15 kB

A newer version of the Gradio SDK is available: 6.32.0

Upgrade

Crypto Perps Signal Backend

A FastAPI backend that collects real-time perpetual futures data from Binance, Bybit, OKX, Bitget, and Hyperliquid DEX, computes multi-factor confluence signals, executes authenticated Bybit V5 bracket orders statelessly, provides causal historical backtesting, and streams updates to the frontend via WebSocket.


Features

  • 5-venue async triangulation: Binance, Bybit, OKX, Bitget, and Hyperliquid DEX (funding rates, OI, L/S ratios, OHLCV including 1m, trades, consolidated orderbook)
  • Quantitative Signal Engine: OI-weighted funding/OI/basis/L-S (contrarian), time-aligned Spot vs Futures CVD, midpoint CVD velocity, deduplicated DEX-vs-CEX spread, ±3-clamped Order Flow cluster, swing_liquidity_proxy liquidity magnet targets, and strict NEUTRAL circuit-breaker vetoes
  • Causal Historical Replay Backtester: engine/backtester.py + scripts/run_backtest.py (no-lookahead slicing, SL-first tie-breaking, taker fees, slippage, 8h funding deductions, Sharpe/Sortino/PF/DD/Expectancy)
  • Fail-Closed Auth & Stateless Bybit V5 Execution: PERPS_API_TOKEN Bearer auth (security.py) on /api/execution/*, /api/pairs*, /api/journal*, plus CRON_SECRET on /api/cron/refresh; request-scoped Bybit credentials with stateful post-fill Limit TP2 reconciliation (STATELESS_MANUAL_TP2 on Vercel)
  • PostgreSQL + In-Memory Fallback: Neon PostgreSQL (DATABASE_URL) with automatic InMemoryDatabaseStore fallback when DATABASE_URL is unset

Quick Start

1. Prerequisites

python 3.11+
pip install -r requirements.txt

2. Environment Variables

cp .env.example .env
# Set PERPS_API_TOKEN (required for protected mutations/execution) and optional DATABASE_URL

3. Run Server & Tests

cd backend
uvicorn main:app --reload --host 0.0.0.0 --port 8000

# Run full pytest suite from repo root:
python -m pytest -q

# Run causal backtester CLI:
python backend/scripts/run_backtest.py --symbol BTCUSDT --days 14

Interactive docs: http://localhost:8000/docs


API Reference

Auth & Health

Method Path Description
GET /health Service status, DB mode, active collector count
GET /api/auth/status Reports whether PERPS_API_TOKEN is configured (no secret leaked)
POST /api/auth/verify Verifies caller's Bearer token

Pairs (Bearer Auth Required)

Method Path Description
GET /api/pairs List all tracked pairs
POST /api/pairs/validate Check {"symbol":"BTCUSDT"} across active exchanges
POST /api/pairs Add pair
DELETE /api/pairs/{symbol} Remove pair
PATCH /api/pairs/{symbol}/toggle Activate / deactivate pair

Signals, Market & Journal

Method Path Description
GET /api/signals Latest signal for every active pair
GET /api/signals/{symbol} Signal history (last 50)
GET /api/signals/{symbol}/latest Single latest signal
POST /api/signals/{symbol}/refresh Compute fresh signal snapshot on demand
GET /api/market/{symbol} Latest market snapshot per exchange
POST/GET/PATCH/DELETE /api/journal* Trade journal CRUD (Bearer Auth Required)
GET/POST/DELETE /api/execution/bybit/* Stateless Bybit V5 settings test, balance & bracket order execution (Bearer Auth Required)

WebSocket

WS ws://localhost:8000/ws/signals

Pushes JSON signal updates every UPDATE_INTERVAL seconds on stateful deployments.


Signal Breakdown

Factor Score Range Notes
funding_rate -2 → +2 Contrarian OI-weighted funding rate
oi_divergence -1 → +1 Price+OI momentum alignment
cvd / spot_futures_cvd / whale_order_flow Clamped [-3, +3] Clustered Order Flow cap prevents multi-counting
hyperliquid -1 → +1 DEX-vs-CEX spread when CEX consensus exists
cross_exchange 0 Non-directional dislocation warning (dislocation_risk)
ls_ratio -1 → +1 Contrarian retail/top-trader positioning (>= 62% → -1, <= 38% → +1)
basis -1 → +1 Mark vs Index spread
market_structure -2 → +2 MTF HH/HL vs LH/LL structure
orderbook_skew -1 → +1 Consolidated bid/ask liquidity skew
fake_detector Veto Gate Forces NEUTRAL & trade_levels = None on manipulation

Confluence thresholds: score ≥ 3 → LONG, ≤ -3 → SHORT, else NEUTRAL (subject to Crowded Funding and FakeDetector circuit-breaker vetoes)


Architecture

main.py  →  lifespan starts background loop (when not on Vercel)
              ├─ DataCollector.collect(symbol)  [Binance, Bybit, OKX, Bitget, Hyperliquid]
              ├─ SignalEngine.compute(data)     [MTF, FakeDetector, Confluence (±4), Predictive proxy]
              ├─ db.py                          [Neon PostgreSQL or InMemoryDatabaseStore]
              └─ WS broadcast / Bybit V5 stateless execution