astra-quant-agent README

README проекта с github.com/0xethanq/astra-quant-agent. Одним файлом markdown: README.md.

AstraQuant

Self-Hosted OKX Perpetuals AI Quant Decision & Execution System

License Python Vue 3 OKX V5 Version

English · 简体中文 · Live Terminal (astraquant.top) · Sister Skills Hub (tradeskill.si)


AstraQuant Live Dashboard


Overview

AstraQuant is a self-hosted algorithmic trading and operations system built natively for OKX USDT-Margined Perpetuals (OKX V5 API). It pairs deterministic Python microstructure analysis and hard risk interlocks with configurable LLM reasoning — backed by an interactive Web workstation and a conversational Control Plane.


Visual Tour (v9.2.0)

Live Trading Workstation
Live Workstation
AI Assistant & Atomic Diff Proposals
AI Assistant Console
Strategy Config & Smart Order Routing
Strategy Config
AI Decisions Timeline
AI Decisions
Chain-of-Thought Audit Drawer
CoT Audit Drawer
Closed-Loop Strategy Review
Strategy Review
Trade Ledger & Lifecycle
Trade Ledger
Market Intelligence & Long/Short Ratio
Market News

Core Architecture

OKX V5 (Candles · Orderbook · Funding · OI · Positions)
   │
   ▼
7-Tier Quantitative Factor Matrix (backend/scripts/market_radar.py)
   │  Multi-timeframe trend (4H/1H/15M), VWAP value area, CVD divergence, orderbook imbalance
   ▼
AI Decision Engine (backend/scripts/ai_brain_trader.py)
   │  Single primary LLM or optional Multi-Model Council (Macro / Tech / Risk / CIO)
   ▼
32-Param Fail-Closed Risk Engine (backend/scripts/risk_constants.py)
   │  1R risk budget · leverage caps · min R:R · daily loss circuit breaker · cooldown · DEMO gate
   ▼
Execution & Cloud Protection (backend/scripts/trader/)
   │  Smart hybrid (Post-Only maker -> IOC fallback) · Limit · Market
   │  Two-leg Scale-Out (TP1 partial close + SL to breakeven + TP2 runner) · Cloud OCO Algo orders
   ▼
Closed-Loop Operations (/admin/agent · /lab)
      Trade attrition review, structured experience rules, conversational Agent diagnostics & rollback

Key Capabilities in v9.2.0

  1. Conversational AI Assistant (/admin/agent): Inspects live positions, 48-cycle order funnel drop-offs, risk conflicts, and runtime logs via read-only tools. Every configuration change is staged as a visual Key-Value Diff Proposal card with an automatic Pre-Apply Policy Snapshot and 1-Click Rollback.
  2. Unified 5-Tab Strategy Config (/admin/strategy):
    • Risk & Orders: 3 preset risk suites (conservative, balanced, aggressive), limit / market / smart hybrid order routing, Scale-Out (TP1/TP2 + breakeven SL) toggle, and 32 validated physics risk gates.
    • Model Council: Enable or bypass multi-seat deliberation (Macro, Tech, Risk, CIO) with per-seat model binding, reasoning effort, and fallback to single primary model.
    • Prompts: Modular system/user prompt pipeline editor with locked safety cores and versioned profiles.
    • Memory & Review: Automated post-trade attribution (self_improvement_engine.py) and toggleable experience rules injected back into future prompts.
    • Windows & Jobs: UTC+8 trading-session gates and on-demand manual maintenance jobs.
  3. Hard DEMO / LIVE Isolation: Separate encrypted keystores and .env execution gates ensure simulated paper accounts (DEMO) can never accidentally submit real mainnet orders.

Quick Start

git clone https://github.com/0xethanq/astra-quant-agent.git
cd astra-quant-agent

# Copy default template (defaults to OKX DEMO paper mode)
cp backend/env.example backend/.env
chmod 600 backend/.env

# Optional: run interactive initialization wizard
python3 backend/scripts/setup_wizard.py

# Start backend + watchdog + gateway
ASTRA_BUILD_REVISION="$(git rev-parse HEAD)" docker compose up -d --build

Open http://127.0.0.1:8080:

The admin version page compares the running image's commit with GitHub main. To deploy a newer commit, rebuild the backend and gateway images from a clean host checkout using the same build command.

2. Local Standalone Development

See STANDALONE.md for running Python + Vite without Docker and RECOVERY_GUIDE.md for daemon & database recovery procedures.


Sister Project: TradeSkill (OKX 20% Fee Rebate & AI IDE Skills)

Looking to query markets or place trades directly inside Claude Code, Cursor, Codex, or Windsurf, or reduce OKX perpetual fees?


Repository Layout

astra-quant-agent/
├── backend/
│   ├── astra_backend/       # FastAPI control plane, Agent console, LLM hub, risk & backup APIs
│   ├── astra_gateway/       # Encrypted secrets vault, notification channels & backup supervisor
│   ├── scripts/             # Core quant loop, 7-tier market radar, execution & evolution engine
│   ├── docs/images/         # Documentation screenshots served at /images/* and /docs/images/*
│   └── tests/               # Offline pytest/unittest audit, trading, UI, LLM & ops suites
├── frontend/
│   ├── src/views/dashboard/ # Public terminal views (/, /factors, /news, /lab, /history)
│   ├── src/views/admin/     # Admin workbench (/admin/agent, /admin/strategy, /admin/llm, ...)
│   ├── src/views/docs/      # Interactive in-app user manual (/docs)
│   └── tests/               # Frontend design parity, i18n copy & dead-UI Node test gates
├── Dockerfile               # Multi-stage Node 26 + Python 3.14 production build
└── docker-compose.yml       # Single-host deployment orchestration

Code map

Entry-point guides inside each subsystem:

Notice: OPENCODE.md does not exist in this repository and was never contained here. Start from the subsystem READMEs below.

File Purpose
backend/astra_backend/README.md Backend layering & subsystem placement rules (L0-L3, routers vs domain services)
backend/scripts/README.md Runtime scripts & daemons entrypoints (ai_brain_trader, market_radar, trader/)
frontend/src/components/admin/README.md Frontend components & state conventions, composables, and design gates
RECOVERY_GUIDE.md Emergency stop, process restart, and ledger recovery commands

Automated doc & test baseline gates:


Brand & codename

The public product name is AstraQuant and the internal codebase prefix is astra (astra_backend, astra_gateway, ASTRA_*). Intentional historical markers retained solely for backward compatibility with existing exchange orders and encrypted backups:


License & Disclaimer

Licensed under GNU AGPL-3.0 + Commons Clause v1.0 + Anti-Scam Special Addendum — personal/internal quant usage and transparent auditing are free; unauthorized commercial resale, SaaS hosting, or fraudulent signal schemes are prohibited.

Risk Disclosure: Algorithmic cryptocurrency futures trading carries significant financial risk. Start in OKX DEMO simulated mode, validate risk parameters and stop-loss protection before committing real capital, and never expose admin tokens or API keys publicly.

astra-quant-agent (0xethanq/astra-quant-agent)

Ищем в базе…

Что это?R20 Quantum Trading System — автономный криптотрейдинговый агент, который использует комитет из нескольких LLM (Claude, GPT-4o, DeepSeek, Gemini и др.) для анализа рынка и предложения сделок, а отдельный детерминированный слой на Python обеспечивает жёсткие правила риска и исполняет ордера на OKX.
ИИ на самом деле сам размещает сделки или только предлагает их?У комитета LLM есть только «право предложения» — каждый ордер перед размещением всё равно должен пройти физический перехватчик Fail-Closed на Python, проверяющий геометрическую валидность, R:R >= 2.0, вето тренда 4H и лимиты позиций в одну сторону.
Как это запустить?Вместо провайдера по умолчанию вы сами настраиваете LLM_BASE_URL/OPENAI_BASE_URL и LLM_API_KEY на любого желаемого провайдера моделей, а затем сначала запускаете систему против OKX в симулированном режиме.
Нужны ли свой API-ключ LLM и аккаунт OKX?Да — в системе нет встроенного шлюза-ретранслятора по умолчанию, поэтому нужно явно настроить свой LLM-эндпоинт/ключ (совместимый с OpenAI, прямой провайдер или self-hosted ретранслятор) и собственный аккаунт OKX для исполнения.
Безопасно ли сразу переключаться на реальную торговлю?Нет — по умолчанию используется демо/симулированный режим OKX, и на live нужно переключать явно, да и потом 17 предохранителей риска на слое исполнения (порог уверенности, фильтр ADX, нижняя граница R:R, автомат отключения при дневном убытке и т.д.) могут перевести сделки в состояние WAIT.
Что на самом деле делает функция самоэволюции?Каждые 6 часов система разбирает реальные закрытые сделки и дистиллирует уроки по win-rate и profit-factor в файл AI_TRADING_MEMORY.md, который затем влияет на каждое будущее решение; есть защита от шума выбросов и период полураспада 7–14 дней, чтобы устаревшие уроки выводились из оборота.
Что такое многомодельный инвестиционный комитет (Council Pro)?Вы можете свободно добавлять и убирать места советников (momentum, risk, quant, macro, sentiment или свои эксперты), привязывать каждое место к своему провайдеру LLM и температуре и давать им спорить несколько раундов, прежде чем модель CIO выпустит финальный структурированный ордер.
Можно откатиться, если изменение стратегии пошло не так?Каждая полная конфигурация (промпты, плагины-перехватчики, места комитета и параметры риска) снимается по SHA-256 и архивируется как именованный снапшот, так что можно атомарно откатиться к любой прошлой версии примерно за 0,5 секунды.
На какой бирже и какими инструментами он торгует?Он торгует бессрочными фьючерсами/контрактами OKX через настраиваемый пул инструментов (data/instrument_pool.json), так что вы не ограничены фиксированным набором монет.
Какие есть похожие проекты?QuantDinger, bytex, daily_stock_analysis, nofx, Vibe-Trading, Qbot, deepseek-harness-quant, beebots
Автор
0xethanq
Размер
50.8 MB
Звёзды
422
Возраст
3 мес
Коммиты · 90 дней