# AegisTrade AI — Data-Flow Architecture

## 1. End-to-End Data Pipeline

```mermaid
sequenceDiagram
    autonumber
    participant Exchange as Bybit V5 (Demo/Live) / WebSocket
    participant MDE as Market Data Engine
    participant FE as Feature & Regime Engine
    participant AI as AI & Expectancy Engine
    participant Risk as Independent Risk Engine
    participant OMS as Order Management (OMS)
    participant DB as Persistence & Audit Trail
    participant UI as Dashboard & Notification

    Note over Exchange,MDE: Real-time Market Ticks & Candle Sync
    Exchange->>MDE: Raw Kline / Ticker / Orderbook (WS/REST)
    MDE->>MDE: Timestamp validation, spread check, gap detection
    MDE->>DB: Persist market candles & snapshots

    Note over MDE,FE: Feature Generation (Causal Only)
    MDE->>FE: Clean OHLCV series + Orderbook metrics
    FE->>FE: Compute EMAs, RSI, ATR, Regime Classification
    FE->>AI: Vector X(t) with regime metadata

    Note over AI,Risk: Predictive Inference & EV Estimation
    AI->>AI: Model probability P(win), expected return, expected risk
    AI->>AI: Deduct fees, spread, slippage, uncertainty buffer
    alt EV > Hurdle and P(win) >= Threshold
        AI->>Risk: Signal Candidate (Symbol, Side, Entry, Stop, TP)
    else Unfavorable or Uncertain
        AI->>DB: Log NO-TRADE reason
        AI-->>UI: Broadcast Market State / NO-TRADE
    end

    Note over Risk,OMS: Independent Gatekeeping & Sizing
    Risk->>Risk: Verify Kill Switch inactive
    Risk->>Risk: Verify Daily Loss & Drawdown limits
    Risk->>Risk: Verify Max Positions count (<2)
    Risk->>Risk: Calculate Exact Decimal Sizing (0.25% risk)
    Risk->>Risk: Verify Exchange Min Notional & Lot Step
    alt Risk Passed
        Risk->>OMS: Approved Order Intent (UUID, Qty, Price, Stop)
        Risk->>DB: Record Risk Approval Event
    else Risk Rejected
        Risk->>DB: Record Risk Rejection (Reason: e.g. Min Notional breach)
        Risk-->>UI: Emit Risk Warning Event
    end

    Note over OMS,Exchange: Execution & State Machine
    alt Mode == BACKTEST
        OMS->>OMS: Simulate Fill against next historical bar
    else Mode == PAPER
        OMS->>OMS: Match simulated fill against real bid/ask
    else Mode == BYBIT_DEMO / LIVE
        OMS->>Exchange: Submit POST /v5/order/create
        Exchange-->>OMS: Order Ack (orderId, status)
        Exchange-->>OMS: WebSocket Execution Report (filledQty, avgPrice)
    end
    OMS->>DB: Update Order Lifecycle & Position State
    OMS-->>UI: Real-time State Update via WebSocket
```

---

## 2. Market Data Timing & Synchronization
1. **Candle Ingestion**: Every timeframe candle closes at UTC seconds `:00`. The Market Data Engine buffers incoming ticks and finalizes closed candles upon exchange timestamp confirmation.
2. **Feature Computation**: Features for decision timestamp $t$ are calculated exclusively on finalized candles $k \le t$. Unclosed/forming candles are never used in indicator lookbacks.
3. **Heartbeat & Liveness**: A continuous 5-second timer checks the delta between `exchange_server_time` and `local_system_time`. If latency $> 5000\text{ms}$ or no ticks arrive for $> 30\text{s}$, the system switches to `STALE_DATA_HALT`.

---

## 3. Order Lifecycle State Machine

```mermaid
stateDiagram-v2
    [*] --> INTENT_CREATED: Signal approved by Risk
    INTENT_CREATED --> SUBMITTED: Sent to Router / Exchange
    SUBMITTED --> REJECTED: Exchange reject or filter failure
    SUBMITTED --> ACCEPTED: Exchange order ID acknowledged
    ACCEPTED --> PARTIALLY_FILLED: Partial execution
    PARTIALLY_FILLED --> FILLED: Completed
    ACCEPTED --> FILLED: Completed
    ACCEPTED --> CANCELLED: Expired / Kill Switch / Manual
    PARTIALLY_FILLED --> CANCELLED: Remaining qty cancelled
    SUBMITTED --> UNKNOWN: Network timeout / ambiguous ACK
    UNKNOWN --> RECONCILING: Auto-reconciliation query
    RECONCILING --> ACCEPTED: Order found active
    RECONCILING --> FILLED: Order executed
    RECONCILING --> REJECTED: Order not found on exchange
    FILLED --> [*]
    CANCELLED --> [*]
    REJECTED --> [*]
```
