# Architecture

## Overview

```
┌──────────────────────────┐        ┌─────────────────────────────────┐
│  Frontend (Next.js/TS)   │  HTTP  │  Backend (FastAPI, Python)      │
│  Dashboard · Scanner ·   │◄──────►│  REST API  /api/*               │
│  Signals · Paper Trades  │        │        │                        │
│  Risk · Reports ·        │        │        ▼                        │
│  Settings                │        │  Agent Orchestrator             │
└──────────────────────────┘        │   ├─ Market Scanner Agent       │
        mock-data fallback          │   ├─ Volatility Agent           │
        when API offline            │   ├─ Technical Analysis Agent   │
                                    │   ├─ Options Analysis Agent     │
                                    │   ├─ News & Sentiment Agent     │
                                    │   ├─ AI Probability Agent       │
                                    │   └─ Risk Manager Agent (gate)  │
                                    │        │                        │
                                    │        ▼                        │
                                    │  Services                       │
                                    │   ├─ Market Data (mock/Alpaca/  │
                                    │   │   Tradier interface)        │
                                    │   ├─ Paper Trading              │
                                    │   └─ Reporting                  │
                                    │        │                        │
                                    │        ▼                        │
                                    │  SQLAlchemy → SQLite / MySQL    │
                                    └─────────────────────────────────┘
                                             ▲
                             cron: scanner/run_scan.py (backend/scanner)
```

## Agent pipeline

Each agent implements `Agent.run(context) -> AgentResult` (see
`backend/app/agents/base.py`) and is independently testable/replaceable.

1. **Market Scanner** — ranks the universe by activity (|change| + relative volume), picks top candidates.
2. **Volatility** — ATR% sweet-spot scoring (2–6% ideal) + relative-volume bonus.
3. **Technical** — RSI, MACD, EMA9/21 cross, SMA50 structure, Bollinger %B, 5-day momentum → bull/bear points → direction + conviction.
4. **Options** — scans the chain on the signal side; scores delta fit (~0.55), liquidity (OI/volume), spread tightness, IV; selects best contract.
5. **Sentiment** — mock in MVP (price-action proxy); Phase 2 swaps in an LLM reading real headlines. Interface unchanged.
6. **AI Probability** — weighted ensemble (technical 40%, options 25%, volatility 20%, sentiment 15%) with agreement bonus / disagreement penalty → confidence, then a deliberately conservative probability mapping (capped at 90%).
7. **Risk Manager** — entry = price, stop = 1.5×ATR, targets at 2R/3R, position sized to the 1%-risk rule (capped at 20% notional), then gates on min confidence / probability / R:R / daily-risk budget. Failures → `status=rejected` with explicit reasons.

## Data flow

`POST /api/scanner/run` (or the cron runner) executes the pipeline and writes a
`ScanRun` + `Signal` rows. The frontend reads signals, opens `PaperTrade`s from
approved signals only, and `POST /api/paper-trades/mark` marks-to-market and
auto-closes on stop/target. `POST /api/reports/generate` aggregates the day.

## Mock-first design (Rule 6)

- Backend: `MockMarketDataProvider` generates deterministic OHLCV + options chains (seeded per symbol/day). Swap via `DATA_PROVIDER` env + `get_provider()`.
- Frontend: `src/lib/api.ts` tries the live API with a 3.5s timeout and falls back to `src/lib/mock.ts`; pages show a Live/Demo badge.

## Safety invariants

- No order-execution code paths exist anywhere in this codebase.
- Only `status="approved"` signals can open paper trades (HTTP 400 otherwise).
- All thresholds live in env config (`backend/app/config.py`), not scattered in code.
