# AegisTrade AI — System Architecture Document

## 1. Executive Summary & Philosophy

**AegisTrade AI** is a production-grade, capital-preserving algorithmic trading and quantitative research platform designed for cryptocurrency markets, connecting directly to the **Bybit V5 API**.

Unlike naive trading bots that emphasize high leverage, aggressive compounding, or martingale recovery schemes, AegisTrade AI is architected from first principles with **Capital Preservation as the Prime Directive**. Its core tenets are:
1. **Decoupled Risk Gatekeeper**: Risk management operates as an independent, authoritative subsystem that can veto any AI signal.
2. **Causal Statistical Rigor**: Zero look-ahead bias, calibrated out-of-sample probability estimates, and cost-adjusted Expected Value (EV) hurdles.
3. **Defense-in-Depth Execution**: Multi-mode architecture (Backtest, Paper, Bybit Demo, Live) with a persistent Emergency Kill Switch and fail-safe order reconciliation.
4. **Small-Account Protection**: Built-in sizing logic that respects exchange lot constraints, fee structures, and strict equity risk fractions (default 0.25%).

---

## 2. High-Level System Architecture

```mermaid
graph TD
    subgraph Market Data Engine
        MDE_REST[Bybit V5 REST Client] --> Cache[Market Data Store]
        MDE_WS[Bybit V5 Public WS] --> Cache
        MDE_HIST[Historical Loader] --> Cache
    end

    subgraph Feature & Regime Engine
        Cache --> Indicators[Causal Indicator Calculator]
        Indicators --> Regimes[Market Regime Classifier]
        Regimes --> FeatureVec[Feature Vector t]
    end

    subgraph AI & Expectancy Engine
        FeatureVec --> ML_Predictor[Calibrated Probabilistic Model]
        ML_Predictor --> EV_Calc[Cost-Adjusted EV Engine]
        EV_Calc --> SignalGen[Signal Generator: LONG / SHORT / NO-TRADE]
    end

    subgraph Independent Risk Engine
        SignalGen --> PreTradeCheck{Risk Gatekeeper Checks}
        KillSwitch[Persistent Kill Switch] --> PreTradeCheck
        AccountState[Portfolio & Balance Tracker] --> PreTradeCheck
        RiskParams[Risk Policy: 0.25% risk, 1x lev, drawdowns] --> PreTradeCheck
        PreTradeCheck -->|Veto / Fail| AuditLog[Audit Trail: NO-TRADE / REJECT]
        PreTradeCheck -->|Approved| OrderSizer[Decimal Order Sizing & Guardrails]
    end

    subgraph Order Management & Execution
        OrderSizer --> OMS[Order Management State Machine]
        OMS --> ExecutionRouter{Execution Mode Router}
        ExecutionRouter -->|MODE: BACKTEST| BacktestLedger[Backtesting Ledger]
        ExecutionRouter -->|MODE: PAPER| PaperEngine[Simulated Matching Engine]
        ExecutionRouter -->|MODE: BYBIT_DEMO| BybitDemoAPI[Bybit Demo REST/WS API]
        ExecutionRouter -->|MODE: LIVE (Locked)| BybitLiveAPI[Bybit Mainnet API]
    end

    subgraph Monitoring & Dashboard
        OMS --> AuditLog
        AuditLog --> DB[(SQLite / PostgreSQL Database)]
        DB --> FastAPIServer[FastAPI Backend & WebSockets]
        FastAPIServer --> ReactUI[React + Vite + Tailwind Dashboard]
        FastAPIServer --> Alerts[Alert Engine: Telegram / Webhooks / UI]
    end
```

---

## 3. Subsystem Breakdown

### 3.1 Market Data Engine (`backend/app/market_data`)
- **Bybit V5 API Connector**: Handles REST polling (`/v5/market/kline`, `/v5/market/tickers`, `/v5/market/orderbook`) and WebSockets (`kline`, `orderbook.50`, `publicTrade`).
- **Data Normalization**: Converts raw exchange payloads into standardized, immutable domain models (`Candle`, `Ticker`, `OrderBook`, `FundingRate`, `OpenInterest`).
- **Integrity & Freshness**: Detects missing candles, duplicate sequences, and stale timestamps. Suspends trading if data latency exceeds 30 seconds.

### 3.2 Feature & Regime Engine (`backend/app/features`)
- **Causal Feature Pipeline**: Computes Trend (EMA, ADX), Momentum (RSI, MACD), Volatility (ATR, Bollinger Bands), Volume (Relative Volume, Order Book Imbalance), and Derivatives signals (Funding rate delta, Open Interest trends).
- **Market Regime Classifier**: Segregates market dynamics into `TRENDING_BULL`, `TRENDING_BEAR`, `RANGING_LOW_VOL`, `RANGING_HIGH_VOL`, and `LIQUIDITY_STRESS`.
- **Causality Enforcement**: Features at index $i$ depend strictly on $t \le i$; future leakage tests run automatically in CI.

### 3.3 AI & Expected Value Engine (`backend/app/strategy` & `backend/app/models`)
- **Machine Learning Models**:
  - Baseline Logistic Regression with L2 regularization.
  - Gradient Boosted Trees (LightGBM / HistGradientBoosting).
  - Out-of-sample probability calibration (Isotonic regression & Platt scaling).
- **Cost-Adjusted Expected Value (EV)**:
  $$\mathbb{E}[\text{EV}] = P_{\text{win}} \cdot R_{\text{target}} - (1 - P_{\text{win}}) \cdot R_{\text{stop}} - \text{Spread} - 2 \cdot \text{TakerFee} - \text{Slippage} - \text{UncertaintyMargin}$$
- **Decision Space**:
  - If $\mathbb{E}[\text{EV}] > \text{EV}_{\text{min\_hurdle}}$ and $P_{\text{win}} > 0.55$: Emit `LONG` or `SHORT`.
  - Otherwise: Emit `NO-TRADE`.

### 3.4 Independent Risk Engine (`backend/app/risk`)
- **Immutable Authority**: Has absolute veto power over signals.
- **Risk Budgeting**:
  $$\text{Risk Budget} = \text{Account Equity} \times 0.0025$$
  $$\text{Units} = \frac{\text{Risk Budget}}{\text{Entry Price} - \text{Stop Price} + \text{Slippage} + \text{Fees}}$$
- **Guardrails**:
  - Max simultaneous open positions = 2.
  - Daily loss circuit breaker = 1.0% of day start equity.
  - Max peak-to-trough drawdown = 5.0%.
  - Default leverage = 1.0x (strictly spots / linear isolated 1x).
  - Exchange lot size check: If minimum notional > risk budget, reject trade.
  - Stale data / high spread filter.

### 3.5 Execution & OMS (`backend/app/execution`)
- **Deterministic State Machine**: `REQUESTED` $\to$ `SUBMITTED` $\to$ `ACCEPTED` $\to$ `PARTIALLY_FILLED` $\to$ `FILLED` / `CANCELLED` / `REJECTED`.
- **Modes**:
  - `BACKTEST`: Auditable event-driven historical backtester.
  - `PAPER`: Internal matching engine matching against real-time live tickers.
  - `BYBIT_DEMO`: Dedicated demo endpoint (`api-demo.bybit.com`) using demo API credentials.
  - `LIVE`: Disabled by default; gated by multi-stage human approval.

### 3.6 Frontend Financial Terminal (`frontend/`)
- Responsive dark-themed trading terminal built with **React**, **Vite**, **TypeScript**, and **Tailwind CSS**.
- Real-time updates via WebSockets and REST.
- Interactive charting with Lightweight Charts and Recharts.
- Dedicated command panels for the Emergency Kill Switch, Risk Controls, Model Diagnostics, Backtesting Workbench, and Audit Logs.
