astra-quant-agent

0xethanq活跃维护

用多个大模型做行情分析、Python 确定性代码做风控、对接 OKX 执行的自主加密货币量化交易系统,让 LLM 决策有硬性风控兜底。

结合多大模型分析与确定性代码风控的自主量化交易系统 | Autonomous crypto trading system with multi-LLM analysis, deterministic Python risk control & OKX execution.

v8.6.1发布于 2026-10-03 14:23 UTC412star116fork同步于 2026-11-07 07:29 UTC

怎么上手

由 README 提炼,执行前请确认
git clone https://github.com/0xethanq/astra-quant-agent.git && cd astra-quant-agent
./setup.sh
./deploy/docker-start.sh
硬件要求按 README 说明

README 未说明显存或 GPU 要求;部署仅要求 Docker 与 Docker Compose,或裸机 Python 3.11+、Node.js 18+、Git,未提及 GPU 厂商或型号

支持 Apple Silicon有 Docker 镜像
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

多 LLM 分析市场、Python 代码硬性风控、OKX 原生执行的自主加密货币量化交易系统

用多个大模型做行情分析、Python 确定性代码做风控、对接 OKX 执行的自主加密货币量化交易系统,让 LLM 决策有硬性风控兜底。

核心能力

  • 多席位 LLM 委员会分别做宏观、趋势、微观结构分析
  • Python 确定性风控对杠杆、仓位、止损拥有一票否决权
  • 每笔成交后立即挂交易所原生 OCO 条件单含分批止盈与止损
  • 持续计算 CVD、OBI、资金费率、IV Skew、VWAP 等微观因子
  • 共享前缀提示缓存降低 LLM 调用延迟与 token 成本

容易踩的坑

默认以 paper trading(demo)模式启动,需提供并校验交易所凭证后才解锁实盘;执行引擎只支持 OKX 原生 API,Binance 和 Gate.io 仅为返佣链接不支持 API 交易;云服务器需放行 8080 入站与 443 出站,OKX API Key 切勿开启提现权限

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v8.6.1
  1. v8.6.1Release v8.6.1: fix ledger reset_time penetration, auto-purge legacy trades & baseline cycle management最新正式版2026-10-03 · 2026-10-03 14:23 UTC

    AstraQuant v8.6.1 Release Notes

    • Ledger Security & Baseline Guard: Eliminate reset_time epoch penetration (1970 fallback) in sync_full_ledger.py and /api/v1/public/ledger; inherit evolution_start_time baseline to prevent historical manual trades from polluting quant ledger.
    • Automated Legacy Trade Purge: Add on-the-fly purge before ledger persistence to strip pre-baseline foreign closed trades, instantly cleaning contaminated user ledgers upon next sync.
    • Baseline Cycle Management: Export update_reset_time in account_baseline.py and expose PUT /api/v1/admin/account-baseline/reset-time with atomic lock and Beijing datetime validation.
    • Ledger UI & Perceptibility: Resolve empty-array clearance bug in LedgerView.vue, add explicit cycle vs all-time badges ([本期] / [全量]) to eliminate user scope ambiguity.
    • Verification & Test Coverage: Add comprehensive unit tests for update_reset_time and router endpoints; full test suites passing across Tier 0 (1,549), Tier 1 (3,912), and Tier 2 (3,755).
  2. v8.6.0AstraQuant v8.6.0: Regime-Adaptive Dual-Mode Engine (Trend vs Chop), Agile Breakeven & Anti-Chop Guardrails2026-10-03 · 2026-10-03 09:50 UTC
    查看更新说明

    🚀 AstraQuant v8.6.0: Regime-Adaptive Dual-Mode Engine, Anti-Chop Protocol & Agile Capital Management

    AstraQuant v8.6.0 Official Feature Release is live! This major release addresses a critical real-world trading dilemma: protecting capital during choppy, range-bound markets while maximizing trend capture. It introduces the Regime-Adaptive Dual-Mode Architecture, an uncompromising Anti-Chop Protocol, agile breakeven ratcheting, and tightened capital rotation.


    ⚡ 1. Regime-Adaptive Dual-Mode Engine (Trend vs. Chop)

    • Autonomous Market Regime Classifier: Dynamic instrument-level classification combining 4H macro channel, 1H swing structure, and 1H ADX:
      • STRONG_TREND: 4H macro and 1H swing aligned + 1H ADX ≥ 20.0 (aggressive pullback buying, trend breakouts, distant multi-tier TP2 trailing).
      • CHOP_RANGE: 4H range, 1H chop, or 1H ADX < 20.0 (strict defensive posture, zero momentum chasing, boundary mean-reversion only).
    • Prompt Architecture Regime Injection: Real-time regime diagnosis banners injected directly into each asset's triple-barrier structure (- 🏛️ 三重滤网宏观结构: ... | 标的体制=CHOP_RANGE (区间震荡·严禁追单)), providing LLM CIO agents with explicit, unambiguous market context.

    🛡️ 2. Quantitative Anti-Chop Protocol & Signal Engine Hardening

    • Suppression of False Breakouts: Programmatically disables Setup 3 (🚀 Momentum Breakout) and Setup 4 (🌪️ Breakdown Acceleration) when ADX indicates range-bound conditions, eliminating the fatal trap of buying range tops and shorting range bottoms.
    • Extreme Boundary Mean Reversion: Restricts chop entries exclusively to Setup 5 (💎 Extreme Mean Reversion) and Setup 6 (🛡️ Sweep Reversal) at 24H VWAP Value Area extremes (VAL / VAH) with confirmed exhaustion wicks.
    • Mid-Range Noise Gating: Zeroes out deceptive temporary EMA alignment scores in chop; enforces strict HOLD when an asset lacks extreme reversal setups, preventing random sub-factor sum bleed.
    • Elevated Confidence Threshold: Increases minimum entry confidence to ≥ 82% in chop regimes.

    🎯 3. Agile Breakeven Ratchet & Tightened Capital Rotation

    • Chop-Adaptive Breakeven Trigger:
      • In normal/trend markets: preserves the standard 1.5x ATR trigger for wave breathing.
      • In chop regimes: ratchets breakeven stop loss forward at 0.9x ATR peak profit (~0.6R–0.7R), locking in cost + 0.2% fee cushion before oscillating swings reverse.
    • Compact Volatility Time-Stop: Shortens time-stop from 4.0 hours to 2.5 hours (0.625x) for range-bound positions, immediately freeing up collateral and avoiding dead capital lockup.
    • Near-End Structural Take-Profit: Prohibits unreachable distant targets (>2.0x ATR) in chop; mandates pinning TP to range centers (VWAP / POC) or opposite bounds.

    🎨 4. Workstation & Landing Page Upgrades

    • Landing Page Modernization: Refreshed visual aesthetics, high-conversion typography, and interactive trading preview card.
    • Exchange Referral Channels: Integrated official fee rebate channels for OKX, Binance, and Gate.
    • Standardized Community Templates: Added GitHub Issue & Pull Request templates (.github/).

    🧪 5. Multi-Tier Quality Gate Verification

    • Tier 0 (Core Quant Gates): 1,545 Python tests + 459 frontend tests passing 100%.
    • Tier 1 (Multi-Model & UI Gates): 3,909 Python tests passing + Vue production bundle compiled + vue-tsc type-check clean.
    • Tier 2 (Full System & Audit Gates): 2,531 architecture and invariant audit tests passing 100%.

    📦 Upgrade Guide

    git pull origin main
    # For Docker deployments:
    ./deploy/docker-start.sh
    # For Bare Metal deployments:
    sh deploy/install.sh && ./start.sh
    
  3. v8.5.1AstraQuant v8.5.1: Clean Text Notification Engine, Prompt Guide Overhaul & Risk Alignment2026-10-02 · 2026-10-02 16:05 UTC
    查看更新说明

    🚀 AstraQuant v8.5.1: Clean Text Notification Engine, Prompt Engineering Guide Overhaul & Risk Guardrail Alignment

    AstraQuant v8.5.1 Maintenance & Quality Release is officially released! This release focuses on de-slopping the notification engine, overhauling the quantitative prompt authoring guide, hardening risk parameters, and ensuring seamless custom AI model configuration.


    📢 1. Notification Engine Upgrade & Quantitative Text De-Slop

    • Emoji & Noise Removal: Stripped noisy and emotional emojis (🟢, 🔴, 🚀, 🎉, 🏷️) across trading notifications, replacing them with institutional bracketed labels ([实盘开仓], [限价成交], [风控止损], [阶梯止盈 TP1 达成]).
    • Enriched Quantitative Metadata: Open alerts now explicitly report the active AI decision model (AI主脑:{active_model}) and order execution mode (委托单型:市价单/限价单), alongside 1H ATR volatility references.
    • Physical Message Sanitizer: Hardened gateway worker with an automated HTML/SVG/IMG sanitizer (sanitize_message_content), stripping rogue rich-text and SVG payloads to guarantee clean display across notification channels.

    📖 2. Complete Rewrite of the Prompt Engineering Guide (docs/PROMPT_GUIDE.md)

    • Full Alignment with v8.5+ Architecture: Purged historical deprecated calculus concepts (v/a/j/I/E/A/VaR) and fake-zero macro regime fallbacks.
    • 7-Tier Microstructure Factor Reference: Standardized prompt integration for T0 Derivatives, T0.5 Orderflow CVD, T1 Orderbook OBI, T1.5 Options Skew, T2 Term Basis, T3 VWAP/POC, and T4 Normalized MACD.
    • 5 Golden Rules for High-Winrate Swings:
      1. Structural Breathing: Refrain from premature breakeven trailing; grant 1.8x–2.2x ATR breathing room.
      2. Let Runners Run: Eliminate panic market exits during healthy intraday retracements.
      3. Directional Beta Discipline: Enforce higher entry confidence thresholds (≥85%) when holding ≥2 correlated positions.
      4. Post-Stop Composure: Programmatic cooldown enforcement against revenge trading.
      5. Maker Limit Geometry: Strict geometric enforcement with positive mathematical expectancy (R:R ≥ 1.6).
    • Prompt Studio Variable Dictionary: Synchronized in-app metadata in scripts/prompt_library.py to match the 7-tier factor matrix.

    🛡️ 3. Execution Risk Guardrail & LLM Configuration Hardening

    • Position Cap Invariant Alignment: Corrected cross-field validation between concurrent position cap and same-direction limits, ensuring long-running backend processes reload risk snapshots without drift (stale: false).
    • Custom LLM Provider Dual-Sync: Streamlined quick onboarding modal to pure custom provider inputs (Base URL, Model Name, API Key) with atomic dual-synchronization to data/llm_models.json.

    🧪 4. Full Quality Gate Verification

    • Tier 0 (Core Quant Gates): 1,538 Python tests + 459 frontend tests passing 100%.
    • Tier 1 (Multi-Model & UI Gates): 3,904 Python tests passing + Vue production bundle compiled + vue-tsc type-check clean.
    • Tier 2 (Audit & Invariants): 3,751 tests passing 100%.

    📦 Upgrade Guide

    git pull origin main
    # For Docker deployments:
    ./deploy/docker-start.sh
    # For Bare Metal deployments:
    sh deploy/install.sh && ./start.sh
    
  4. v8.5.0AstraQuant v8.5.0: Autonomous Quant OS, Prompt Caching Architecture & Ethereal Workstation2026-09-30 · 2026-09-30 03:13 UTC
    查看更新说明

    🚀 AstraQuant v8.5.0: Autonomous Quant OS, Prompt Caching Architecture & Ethereal Workstation

    AstraQuant v8.5.0 Official Release is here! This milestone release marks the full maturation of our autonomous quant trading operating system, delivering enterprise-grade Prompt Caching & Session Affinity, high-end Ethereal Glassmorphic UI, GNU AGPL-3.0 + Commons Clause v1.0 + Anti-Scam Rider licensing, a 2-minute Zero-Config Setup Wizard, and a comprehensive overhaul of our documentation center.


    ⚡ 1. Upstream Prompt Caching & Session Affinity Architecture (2026-10)

    Multi-agent quant desks usually suffer from massive LLM token overheads and latency. v8.5.0 introduces an institutional-grade prompt caching architecture:

    • Shared Market & Rules Prefix (>90% cached): Static trading doctrine, risk mandates, and the 7-tier quant factor matrix are consolidated into the prefix, enabling multi-agent council seats (Trend, Momentum, Quant, Macro) to hit the same KV cache block.
    • Monotonic Volatility Hierarchy: Strict structuring by mutation frequency:
      • Zone 0 (Immutable): Core doctrine, role identities, and read-only JSON Schema.
      • Zone 1 (Slow-moving): 6-hour self-evolution memory lessons.
      • Zone 2 (Medium-moving): 10-minute news intelligence and sentiment scores.
      • Zone 3 (Cycle-moving): 15-minute 7-tier quant factor matrix.
      • Zone 4 (Fast-moving): Second-level orderbook ticks and millisecond timestamps.
    • Claude Ephemeral Breakpoints: Native injection of cache_control: {"type": "ephemeral"} at Zone boundaries; 64/128-token chunk alignment for OpenAI and DeepSeek models.
    • Float Anti-Jitter: Mathematical rounding stabilization prevents minute decimal fluctuations from busting upstream cache keys.
    • L1 In-Memory + SQLite Persistent Cache: Eliminates redundant remote roundtrips during council debate and failover sequences.

    🎨 2. Ethereal Glassmorphism & High-End Minimalist UI

    • Ethereal Glass Surfaces: Translucent frosted glass layering (rgba(13, 15, 21, 0.76) + backdrop-filter: blur(20px) saturate(180%)) with subtle ambient spatial depth.
    • Dual-Bezel Hairline Inset Highlights: Ultra-fine chamfered borders (inset 0 1px 0 rgba(255, 255, 255, 0.09)) replacing heavy borders with crisp optical edges.
    • Tactile Micro-Interactions: Custom buttons with active depression kinematics, polished focus rings, and zero cyberpunk visual pollution.
    • Sanitized Framework Comments: Completely cleaned all legacy external platform attribution comments across CSS and Vue components for pristine production delivery.

    ⚖️ 3. GNU AGPL-3.0 + Commons Clause v1.0 + Anti-Scam Rider

    To protect open-source quant contributors and community users from commercial resale, predatory closed-sourcing, and financial scams:

    • Strong Copyleft for Network Services (AGPL-3.0): Anyone modifying and hosting the system over a network must make full source code available to users.
    • No Commercial Resale or Paid Signals (Commons Clause v1.0): Prohibits selling, renting, or charging subscription fees for the software or derived signal channels. Private self-hosted trading and academic research remain 100% free.
    • Anti-Scam Rider: Strictly bans fraudulent financial schemes, token issuance, and unauthorized paid copy-trading groups.

    🚀 4. Production Deployment & Onboarding Overhaul

    • 2-Minute Interactive Setup Wizard (./setup.sh): Fast CLI onboarding for exchange mode (Demo/Live), API keys, AI model provider, risk baseline, and secure password generation; supports --non-interactive for automated server deployments.
    • Docker Compose Clean-up: Completely eliminated stale ./plugins mounts following the 2026-10 strategy interceptor retirement, preventing root-owned host folder pollution.
    • Adaptive Execution: install.sh now upgrades pip automatically before installing dependencies; systemd services properly inherit virtualenv binar
  5. v8.4.0AstraQuant v8.4.0: Obsidian-Emerald Workstation, Dynamic Sizing & Production Engine2026-09-30 · 2026-09-30 03:13 UTC
    查看更新说明

    🚀 AstraQuant v8.4.0: Obsidian-Emerald Workstation, Dynamic Sizing & Production Engine

    AstraQuant v8.4.0 is a milestone release delivering an all-new Obsidian-Emerald visual brand identity, dynamic equity-proportional sizing, high-frequency prompt & risk suites, a live-only Strategy Plaza sharing endpoint, unified 3-source error center, and best-in-class bilingual documentation with updated high-resolution telemetry screenshots.


    🌟 What's New in v8.4.0

    1. 🖥️ Obsidian-Emerald Trading Workstation & Brand Upgrade

    • Visual Identity: Upgraded to the new institutional Obsidian-Emerald design system (#00E599 emerald accent on deep obsidian slate) with the Concept C Astral Spark brand logo.
    • KLineChart v10 Native Candlestick Engine: High-fidelity candlestick chart rendering live BBO maker limit entry, multi-target TP1/TP2 brackets, trailing stop lines, and depth metrics with zero horizontal line truncation or mobile indicator clipping.
    • Brand-New Landing Page: Introduced a modern, responsive showcase page at / with real-time connectivity telemetry, features breakdown, and instant access to the trading desk.

    2. ⚡ Dynamic Margin Sizing & Capital Allocation

    • Pure Dynamic Equity Sizing: Completely eliminated historical fixed USD floors. All 1R risk budgets, single-trade margin bounds, cumulative account limits, and daily drawdown halts are now purely proportional to account equity ($1R = \text{min}(\text{cap}, \text{equity} \times 2.0%)$).
    • Proportional Scaling: Seamless scaling from a 20 USDT demo trial to 10,000+ USDT institutional capital pools without configuration hacks.
    • Order Execution Mode: Prioritized order mode selection in /admin/security, supporting both BBO Maker limit execution and instant Market orders.

    3. 👥 Multi-Model Investment Committee & Fail-Closed Risk Pipeline

    • Heterogeneous LLM Routing: Each committee seat independently binds to its own provider, model, and reasoning temperature (Claude 3.7 / DeepSeek-R1 / GPT-4o / Gemini).
    • Thinking Budget Control: Global long-CoT reasoning budget support (10s to 1800s) with millisecond-grade failover across backup model chains on HTTP 429 / provider outages.
    • 4 Factory Interceptor Gates: Non-bypassable physical Python risk pipeline (4H macro trend veto, entry confidence gate, 1H ADX chop filter, and 2.0R risk/reward floor). Fail-closed by design: any error or timeout unconditionally halts order entry.

    4. 🌐 Three-Venue Equal Parity & Strategy Plaza

    • OKX, Binance & Gate Parity: Equal status across all 3 venues with unified asset telemetry, native hedge-mode handling, and atomic conditional orders.
    • Strategy Plaza Live Sharing: Introduced /api/v1/public/plaza/profile telemetry and one-click clone endpoint with a strict live-trading preflight guard (rejects demo mode) and physical zero-secret sanitization.
    • Admin Control: Granular privacy switches to conceal exact equity, trades history, or active positions while sharing strategy fingerprints.

    5. 🧬 Closed-Loop Self-Evolution & 3-Source Error Center

    • 6-Hour Heuristic Evolution: Mines closed-trade ledgers for win rate, profit factor, and attribution slices, distilling operational wisdom into long-term prompt memory with a 7–14 day sharpness half-life.
    • Consolidated Error Center: Unified system logs under /admin/decisions with a dedicated 3-source Error Center aggregating trader daemon, FastAPI backend, and gateway scheduler errors.
    • Full Lifecycle Untruncated Ledger: Delivered untruncated trade lifecycle history with pagination support and all-time statistics.

    6. 📖 Best-in-Class Documentation & Updated Visuals

    • Comprehensive Bilingual Documentation: Completely rewritten README.md (English) and README.zh-CN.md (Chinese) covering core architecture, mathematical calculus dynamics, risk mechanics, and developer code maps.
    • 15 Fresh Screenshots: Replaced legacy grap

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    简体中文 · English

    AstraQuant

    Autonomous Crypto Trading System with Multi-LLM Analysis & Deterministic Risk Control

    Release License Python Vue 3

    AstraQuant combines large language models (macro, technical, and microstructure analysis) with deterministic Python risk management and OKX-native conditional order execution.

    Preview · Quick Start · Referral · Architecture · Market Factors · Risk Control · Deploy · Code Map


    Preview

    Quant Trading WorkstationLive WorkstationChain-of-Thought (CoT) Decision DrawerChain of Thought
    Execution Risk Control CenterRisk ControlMulti-Model Committee BoardCouncil Board
    Prompt Engineering StudioPrompt StudioClosed-Loop Self-Evolution HubSelf Evolution
    LLM Gateway & Thinking ConfigLLM HubSystem Governance & Admin OverviewAdmin Overview
    Security & Credential PlazaSecurity PlazaFactor Telemetry TableFactor Matrix

    Quick Start

    git clone https://github.com/0xethanq/astra-quant-agent.git && cd astra-quant-agent
    ./setup.sh                  # Interactive onboarding wizard (recommended)
    # Container launch: ./deploy/docker-start.sh | Bare-metal: ./deploy/install.sh && ./start.sh
    
    Service SurfaceLocal Access URLRole & Purpose
    Trading Workstationhttp://localhost:8080/tradingReal-time position HUD & factor telemetry
    Admin Control Planehttp://localhost:8080/admin/loginRisk settings, prompt studio, API keys
    API Documentationhttp://localhost:8080/docsOpenAPI schema & endpoint specifications

    Fail-Closed Default: AstraQuant boots in paper trading mode (demo) by default. Live execution is physically blocked until exchange credentials are provided and validated via read-only balance snapshots.


    Exchange Referral & Fee Rebates

    Trading API Compatibility Notice: AstraQuant's autonomous execution engine only supports OKX native API. Binance and Gate.io are community partner links provided solely for registration discounts and fee rebates; our automated trading system does not support direct API execution on other exchanges.

    ExchangeRole & CompatibilityReferral LinkCodeSpecial Note
    OKXNative Trading Supported (Official Engine Target)Register on OKX48039151Supports new accounts & dormant accounts (inactive > 180 days)
    BinancePartner Promotion Only (No API Trading)Register on BinanceCPA_00N8UVQ2OGExclusive fee rebate link; not supported by trading engine
    Gate.ioPartner Promotion Only (No API Trading)Register on GateMCHDBKYFExclusive fee rebate link; not supported by trading engine

    Core Principles

    1. Hypothesis vs. Enforcement: LLMs analyze market structure and propose order intents; deterministic Python code holds absolute veto authority over leverage, position sizing, and stop-loss placements.
    2. Multi-Perspective Synthesis: Specialized analytical seats (Macro, Trend, Microstructure, Contrarian) independently assess each cycle to mitigate single-model bias.
    3. Exchange-Native Protection: Every filled order is immediately hedged on the exchange side with native conditional OCO brackets (TP1 partial scale-out + TP2 runner + stop-loss).

    System Architecture

    AstraQuant executes on a 15-minute trading cycle across four decoupled boundaries:

    1. Market Ingestion & Factors    ──> CVD, Orderbook Imbalance (OBI), Funding Rate, Options IV Skew, VWAP
    2. Multi-Model Council (LLMs)   ──> Macro, Trend, and Microstructure seats analyze & synthesize order intent
    3. Python Physical Risk Gates   ──> Sizing clamps, R:R floor verification, same-direction cap, circuit breaker
    4. OKX Execution & Cloud OCO    ──> Passive BBO Maker limits, scale-out TP legs, and 100% cloud stop-loss
    

    Market Microstructure Factors

    Rather than relying purely on lagging indicators, AstraQuant continuously calculates derivative market metrics:

    DimensionKey MetricsRole in Strategy
    Order Flow & Taker DeltaCumulative Volume Delta (CVD) Divergence, Whale Taker FlowIdentifies aggressive buying or selling absorbing passive liquidity
    Orderbook MicrostructureOrder Book Imbalance (OBI), Top-20 L2 Depth AsymmetryMeasures instantaneous book liquidity and bid/ask resistance
    Settlement & Open InterestFunding Rate Velocity, Open Interest (OI) AccelerationGauges leverage crowding and liquidation vulnerability
    Volatility SurfaceImplied Volatility (IV) Skew, Max Pain Strike DistanceEvaluates market tail-risk expectations and institutional hedging
    Structural BenchmarksVolume-Weighted Average Price (VWAP ±1σ / ±2σ), VPVR POCLocates institutional fair-value zones and mean-reversion boundaries
    Trend & MomentumMACD Histogram Velocity & Acceleration, ADX VectorDistinguishes trend continuation from exhaustion chop

    Multi-Model Analysis & Prompt Caching

    • Specialized Seats: Configurable models (DeepSeek-V3/R1, Claude 3.5 Sonnet, GPT-4o, Qwen) evaluate distinct domains (Macro, Microstructure, Momentum, Contrarian Risk).
    • Consensus Arbitration: Configurable modes include Paranoid Veto (unconditional downgrade to WAIT on severe anomaly), Weighted Majority, or Alpha Momentum.
    • Prompt Caching Architecture:
      • Over 90% of the prompt context consists of static doctrine, risk rules, and multi-symbol factor matrices.
      • Council seats broadcast over this shared prefix with session affinity, achieving sub-second Time-To-First-Token (TTFT) and significantly reducing LLM API token costs.

    Capital Management & Risk Control

    Risk rules are enforced strictly by Python code (scripts/risk_constants.py). Baseline parameters:

    ParameterBaseline ValueDescription
    Max Concurrent Positions6 positionsUpper limit of active open positions across all instruments
    Max Same-Direction Positions4 positionsPrevents directional over-exposure during market-wide correlated moves
    Max Single-Asset MarginEquity × 30%Prevents concentration risk in a single coin
    Intraday Drawdown Breakermin(150 USDT, Equity × 5%)Halts new entries for 24h if daily drawdown threshold is breached
    Dynamic Leverage Clamp2.0x – 5.0xClamped to instrument ATR and liquidity limits
    Minimum Reward:Risk (R:R)R:R ≥ 2.0Prohibits low-expectancy trades; requires favorable risk-reward
    Time Invalidation Stop4.0 hoursCloses stagnant positions that fail to expand within the expected window
    Cloud Stop-Loss Coverage100%Every position is covered by exchange-side cloud conditional orders

    Deploy

    💡 Cloud Server Security Group & Port Notice: When deploying on a cloud VPS (AWS, GCP, DigitalOcean, Alibaba Cloud, etc.), verify inbound firewall rules in your cloud console:

    • 8080 (TCP Inbound): AstraQuant Trading Workstation & Admin Plane;
    • 22 (TCP Inbound): SSH remote access and server operations;
    • 443 (TCP Outbound): OKX V5 REST API & LLM gateway connectivity.

    ⚠️ API Security Redline: OKX API Key requires only Read and Trade permissions. Never enable Withdrawal permissions. IP binding to your static server IP is strongly advised.

    ModeHost PrerequisitesHighlights & TargetRecommendation
    Docker Compose (Recommended)Docker & Docker ComposeZero host dependency, auto multi-stage build, supervised watchdog⭐⭐⭐⭐⭐
    Bare Metal Linux / macOSPython 3.11+ (python3-venv), Node.js 18+, GitLocal source development and memory-constrained environments⭐⭐⭐

    Docker (Recommended)

    git clone https://github.com/0xethanq/astra-quant-agent.git && cd astra-quant-agent
    ./setup.sh                  # Interactive CLI onboarding wizard
    ./deploy/docker-start.sh    # Builds and launches backend & gateway daemons
    docker compose ps           # Check container health
    

    Bare Metal Linux / macOS

    git clone https://github.com/0xethanq/astra-quant-agent.git && cd astra-quant-agent
    sh deploy/install.sh        # Installs Python environment & dependencies
    ./setup.sh                  # Prepares .env configuration
    cd frontend && npm install && npm run build && cd ..
    ./start.sh                  # Starts control plane on http://0.0.0.0:8080
    

    Automated Testing

    # Tier 0: Core Quant & Execution Gates (~20s)
    .venv/bin/pytest tests/trading tests/venues tests/risk tests/backtest -n auto -q
    
    # Tier 1: Multi-Model & Frontend Integration Gates (~60s)
    .venv/bin/pytest tests/llm tests/ui tests/core -n auto -q
    cd frontend && npm run build && npx vue-tsc --noEmit && node --test tests/*.test.mjs && cd ..
    
    # Tier 2: Architectural Audit & Invariant Gates (~90s)
    .venv/bin/pytest tests/audit tests/extraction tests/ops -n auto -q
    

    Code map

    This repository has never contained an OPENCODE.md. Authoritative architectural entry points:

    DomainSpecification DocumentKey Scope
    Architecture Overviewdocs/STRUCTURE_OVERVIEW.mdLayered architecture and subsystem directory layout
    Backend Layeringastra_backend/README.mdBackend layering (L0 Facade / L1 Wiring / L2 Routes / L3 Domain / L4 Subpackages)
    Runtime Scripts & Daemonsscripts/README.mdRuntime scripts & daemons (38 root-level scripts, daemons, and scheduling mechanics)
    Prompt Engineeringdocs/PROMPT_GUIDE.mdJSON-only prompt library, 8 semantic slots, council doctrines
    Failure Semanticsdocs/FAILURE_SEMANTICS.mdReal-world failure post-mortems and defensive invariants
    Beijing Time Contractdocs/BEIJING_TIME_CONTRACT.mdUnified UTC+8 financial accounting and settlement foundation
    Frontend Architecturefrontend/src/components/admin/README.mdFrontend components & state (Vue 3, composables, stores)
    Standalone DeploymentSTANDALONE.mdEnvironment configuration and host-native execution
    Disaster RecoveryRECOVERY_GUIDE.mdEmergency liquidation and state recovery playbooks
    Observabilitydeploy/observability/README.mdPrometheus metrics scraping and Grafana dashboards

    Continuous Governance Gates:

    GateScope & Protection
    tests/audit/test_directory_docs_current.pyEnsures all modules are registered in __init__.py and documented
    tests/core/test_readme_baseline_numbers.pyKeeps test count baselines aligned with actual test suites
    tests/audit/test_doc_paths_are_committed.pyEnsures all source paths referenced in documentation exist and are tracked

    Brand & Namespace Governance

    • Public Brand: AstraQuant — https://www.astraquant.tech
    • Internal Namespace: astra (packages astra_backend, astra_gateway; configuration prefix ASTRA_*)

    Intentional Legacy Markers — Do Not Rename

    Three historical markers are intentionally preserved to protect live production state and open positions (tests/audit/test_brand_strings_are_consistent.py):

    1. Exchange leg tags t-r20sl* / t-r20tp*: Open orders placed prior to namespace upgrade remain live on exchange matching engines. Preserved so cloud ratchets maintain tracking; new orders use astrasl / astratp.
    2. Encrypted backup magic R20GCM2 + NUL: Historic backups must remain decryptable. New archives use ASTRAGCM.
    3. cpa.r20.cn in test fixtures: The maintainer's internal DNS gateway for upstream LLM routing, not a repository namespace.

    Community

    AstraQuant officially links to and endorses the LINUX DO (linux.do) open-source community.


    Disclaimer

    1. This project is an open-source algorithmic trading framework and quantitative research system, created strictly for academic research, education, and simulation purposes.
    2. Cryptocurrency derivatives trading entails significant capital risk and extreme volatility. Historical backtests do not guarantee future performance.
    3. Users must maintain comprehensive risk management practices and validate strategies thoroughly in paper trading (demo) before committing live capital.
    4. The authors and contributors assume zero liability for financial losses incurred through the deployment of this software.

    License

    AstraQuant is distributed under the GNU Affero General Public License v3.0 (AGPL-3.0) with the Commons Clause Condition v1.0 and Anti-Scam Addendum.

    • Free for Research & Proprietary Trading: Full source code available for academic study, individual backtesting, and self-hosted personal trading.
    • Network-Use Copyleft (AGPLv3): Any modified version made accessible over a network must release corresponding source code.
    • No Commercial Resale or Paid Signals (Commons Clause): Selling the software, packaging as closed-source commercial offerings, or operating paid copy-trading subscription services derived from this software is prohibited without written permission.
    • Anti-Scam Rider: Strictly prohibits use for fraudulent schemes, token issuance, or unauthorized commercial endorsement.