# Product Requirements Document (PRD v2.0 — GCP-Flagship Edition)
## Stock Market Elephant: Google Cloud Agentic Stock Trading & Cross-Repricing Convergence Platform

**Repository:** `sme-stock-agents` (dedicated private agent repository)  
**Public Live Surface:** `https://stockmarketelephant.com/agents/` (sanitized telemetry & animated agent floor)  
**Cloud Platform:** **100% Google Cloud Platform (GCP)** (`us-central1`, scale-to-zero, keyless GitHub OIDC)  
**Monthly Cloud Budget Ceiling:** **Hard-capped at `$35.00/month`** (projected Phase 1–3 burn: **`$4.20–$8.90/month`**)  
**Execution Lock:** Strictly **SHADOW / PAPER ONLY** until Gate 4 explicit human sign-off  
**Version:** 2.0 (Post Red-Team Review Remediation) · 2026-11-20  

---

## 1. Vision & Why GCP Is the Flagship Backbone

We are building a disciplined, transparent, multi-agent equity trading system focused on **5–20 routinely traded liquid stocks** (anchored on high-impact catalysts like `ANT` Day-2 IPO unwinds and cross-asset repricing waves across AI Silicon, Foundation AI, Hyperscalers, and Defensive Rotation).

Instead of stitching together fragile local cron jobs, brittle browser state, and unguarded LLM prompts, **every single layer of the system runs natively on Google Cloud Platform**:

1. **Precision Morning Timing (`Cloud Scheduler` + `Pub/Sub`):** Eliminates GitHub Actions cron drift (`±1s` SLA from `08:00–10:30 ET`) so `ANT` morning flush alerts fire on the exact minute they happen.
2. **Serverless Scale-to-Zero Compute (`Cloud Run` + `Cloud Run Jobs`):** The deterministic convergence engine, FastAPI control plane, and walk-forward backtest sandbox scale to zero outside trading windows—costing pennies per day while supporting sub-second warm execution during the `08:30–10:15 ET` rush.
3. **Calibrated AI Reasoning (`Vertex AI / Gemini Enterprise` + `Google ADK` + `Model Armor`):** `gemini-decision-1` and `gemini-4-argon` score catalysts and adversarial Bull/Bear theses *only* on the top `≤ 3` candidates that pass deterministic NumPy/Pandas displacement & cluster-sync filters—protecting both latency (`<2s`) and token budget (`<$4/mo`).
4. **ACID State & Immutable Audit (`Cloud Firestore` + `BigQuery`):** `Firestore` guarantees atomic kill-switch locks, daily drawdown accounting, and cluster slot caps across container restarts; `BigQuery` (`sme_stock_agents` dataset) stores every bar, agent proposal, policy verdict, shadow fill, and TradeZella reconciliation row for point-in-time walk-forward auditing.
5. **Zero-Secret Security (`Secret Manager` + `Workload Identity Federation` + `Cloud Monitoring`):** Keyless GitHub OIDC deploys, zero plaintext credentials, automated billing-cap alarms (`$15` warn / `$35` hard budget), and instant kill-switch paging via Cloud Monitoring + Pub/Sub.

---

## 2. End-to-End GCP Service Mapping (All 8 Illustrated Agents + 5 Plumbing Steps)

Every agent visualized on `stockmarketelephant.com/agents/` maps 1-to-1 onto a concrete Google Cloud service boundary:

| Layer | Illustrated Agent | Primary GCP Services | Responsibility & Contract |
|---|---|---|---|
| **L0 · Orchestration** | **Elephant Conductor** | **Cloud Run** + **Google ADK** + **Cloud Scheduler** + **Pub/Sub** + **Secret Manager** | Triggers morning DAG (`08:00–10:30 ET`), manages shared Context Store in Firestore, exposes typed MCP tool registry, writes every run span to **Cloud Trace / Logging**. |
| **L1 · Cognitive** | **Radar Owl** (*Research & Idea*) | **Vertex AI / Gemini Enterprise** (`gemini-4-argon`) + **Model Armor** | Parses structured morning catalysts (`ANT` IPO flow, short reports, macro prints) and runs adversarial Bull/Bear debate on top `≤ 3` filtered tickers. Read-only; zero execution privileges. |
| **L1 · Cognitive** | **Repricing Octopus** (*Convergence*) | **Cloud Run (Python/NumPy)** + **BigQuery** | Computes empirical 20d OLS beta, rolling peer correlation `ρ_ij` (with Bayesian IPO shrinkage for Day 1–20 listings like `ANT`), dynamic anchor election, cluster sync %, and anchor lag %. |
| **L1 · Cognitive** | **Forge Fox** (*Strategy & Backtest*) | **Cloud Run Jobs** + **BigQuery** (Point-in-Time) | Runs containerized deterministic walk-forward simulation, slippage sensitivity, CPCV/DSR overfitting checks, and increments the Graveyard trial counter before any rule can be promoted. |
| **L1 · Cognitive** | **Scale Tortoise** (*Risk & Optimizer*) | **Cloud Run** + **BigQuery** | Computes `1R = |entry - stop|` share sizing (`$500` max risk/trade), enforces portfolio cluster correlation caps (max **1 active slot per cluster**), and optimizes Sharpe/drawdown rails. |
| **L2 · Plumbing (1)+(2)** | **Signal Hound** (*Ingestion & Policy Gate*) | **Cloud Run (Deterministic Python)** + **Firestore** | Enforces non-overridable checks: `staleness <= 120s`, `volume_verified` gate, IPO/Volatility collar (`ipo_days <= 5` → `WATCH_COLLAR`), cluster duplicate cap (`CAPPED_CLUSTER_DUP`), daily loss cap (`$1,000`), and venue compliance. |
| **L2 · Plumbing (3)+(4)** | **Relay Falcon** (*Order Router & State Store*) | **Cloud Run** + **Firestore (Native ACID)** + **Cloud Tasks** | Manages transactional state (`positions`, `orders`, `daily_pnl`, `restart_state`), retry/rate-limit queues, and shadow/paper broker routing. **Locked in `SHADOW_PAPER` mode until Gate 4.** |
| **L2 · Plumbing (5)** | **Sentinel Rhino** (*Kill Switch & Alerting*) | **Cloud Monitoring** + **Pub/Sub (`sme-alerts`)** + **Firestore** + **Cloud Storage** | Watches drawdown, API latency, feed staleness, and custom `ANT` price/gap alarms. Trips atomic `system/kill_switch` in Firestore, freezes Relay Falcon, and publishes sanitized JSON to GCS/CDN for `stockmarketelephant.com/agents/`. |

---

## 3. Data Architecture & BigQuery Warehouse (`sme_stock_agents`)

All analytical state lives in BigQuery (partitioned by `session_date`, clustered by `ticker`) for zero-lookahead walk-forward research and TradeZella MCP reconciliation:

1. **`sme_stock_agents.premarket_bars`** — 1m/5m extended-hours & RTH bars with `volume_verified` flag, `source` (`yfinance` vs `alpaca_sip` / `polygon`), and `ingested_at_utc` (strictly point-in-time!).
2. **`sme_stock_agents.convergence_snapshots`** — Every morning scan output per ticker: `anchor_ticker`, `beta_20d`, `corr_20d`, `gap_pct`, `rs_pct`, `rs_z`, `cluster_sync_pct`, `repricing_lag_pct`, `convergence_score`, `state`.
3. **`sme_stock_agents.agent_proposals`** — Typed JSON proposals emitted by `Radar Owl`, `Repricing Octopus`, `Forge Fox`, and `Scale Tortoise` (including Gemini model version, token count, latency ms, and prompt hash).
4. **`sme_stock_agents.policy_verdicts`** — Every `Signal Hound` decision (`PASS_SHADOW`, `WATCH_COLLAR`, `CAPPED_CLUSTER_DUP`, `HOLD_TRIGGER`, `REJECT_STALE`, `REJECT_NOISE`, `HALTED_KILL_SWITCH`) with deterministic rule codes.
5. **`sme_stock_agents.shadow_orders_fills`** — Simulated/paper order lifecycle, intended price vs fill price, realized slippage (`ticks/bps`), `1R` outcome, and TradeZella MCP reconciliation residuals.
6. **`sme_stock_agents.graveyard_trials`** — Pre-registered equity strategy hypotheses, walk-forward OOS Sharpe/expectancy, DSR verdict, and honest failure log.

---

## 4. Transactional State Machine (`Cloud Firestore`)

To fix **RR-04** from the Red Team Review, runtime state NEVER lives solely in browser storage or container memory:
- `system/kill_switch` → `{ tripped: bool, reason: string, tripped_at: timestamp, tripped_by: string, daily_loss_usd: float, daily_loss_cap_usd: 1000.0 }`
- `config/focus_basket` → `{ tickers: [5..20], pinned_anchor: "ANT", alert_rules: { ant_gap_pct: -5.0, ant_price_floor: 87.0 } }`
- `sessions/{YYYY-MM-DD}/slots` → `{ active_clusters: { "AI Silicon": "ARM", "Rotation & Defense": "UNH" }, total_risk_usd: 1000.0 }`
- `orders/{order_id}` → Transactional order state (`CREATED → SHADOW_ROUTED → FILLED_SIM → CLOSED_TIMESTOP`).

---

## 5. GCP Cost Model & Billing Guardrails (`$35/mo` Hard Cap)

Designed explicitly to coexist inside the existing SME trading GCP `$35/month` budget alongside the MNQ futures agent (`~$2.03/mo`):

| GCP Service | Configuration | Estimated Monthly Burn |
|---|---|---|
| **Cloud Run** (`sme-stock-agents`) | `us-central1`, 512MiB / 1 vCPU, `min-instances=0`, `max-instances=2`, ~120 invocations/day | **`$0.00–$1.20`** (mostly Free Tier) |
| **Cloud Run Jobs** (`forge-fox-backtest`) | On-demand walk-forward runs (~4 runs/mo, 2 vCPU, 3 min each) | **`$0.15`** |
| **Cloud Scheduler + Pub/Sub** | 4–6 weekday jobs + `<100k` messages/month | **`$0.10–$0.30`** |
| **BigQuery** (`sme_stock_agents`) | `<1 GB` storage, `<50 GB` queries/mo (Free Tier = 10 GB / 1 TB) | **`$0.00`** |
| **Cloud Firestore** | `<50k` reads/writes/day (Free Tier covers daily ops) | **`$0.00–$0.50`** |
| **Vertex AI / Gemini Enterprise** | Deterministic-first funnel: max `3` tickers × `4` morning windows × `22` days = `~264` calls/mo | **`$2.50–$4.50`** |
| **Cloud Storage + Secret Manager + Logging** | Public JSON bucket + 3 secrets + 30-day log retention | **`$0.40–$0.80`** |
| **TOTAL PROJECTED STOCK-AGENT BURN** | **Combined with MNQ agent (`~$2.03/mo`) = `~$5.20–$9.30/mo`** | **Well inside `$35.00/mo` hard cap** |

---

## 6. Security, Zero-Leak & Compliance Contract

1. **Zero Public Cloud Leakage:** The public website (`stockmarketelephant.com/agents/`) NEVER receives raw GCP project IDs, project numbers, service-account emails, billing IDs, or raw `.a.run.app` URLs. Instead, `Sentinel Rhino` exports a sanitized static JSON payload (`morning_snapshot.json`) via Cloud Storage / GitHub dispatch verified by `.github/workflows/site-guard.yml`.
2. **Keyless CI/CD:** GitHub Actions authenticates to GCP strictly via **Workload Identity Federation (OIDC)**—zero long-lived JSON key files.
3. **Model Armor & Schema Confinement:** Raw news/filings never enter the execution path. `Radar Owl` outputs strictly validated Pydantic JSON schemas.
4. **Hard Execution & Venue Guard:** `Relay Falcon` is locked to `SHADOW_PAPER` until Gate 4. Cloud automation strictly forbids non-compliant prop endpoints.

---

## 7. Phased GCP Rollout & Promotion Gates (Gate 0 → Gate 4)

| Phase | GCP Milestones | Quantitative & Operational Exit Gate | Status |
|---|---|---|---|
| **Phase 0 · Repo, Red Review & Live UI** | Ship `sme-stock-agents` repo with Red-Review-hardened `convergence.py` + `plumbing.py` + Cloud Run FastAPI `server.py` + unit tests + GCP IaC blueprints; update `stockmarketelephant.com/agents/` with Red Review & GCP-Flagship PRD v2.0 | All `pytest` invariants pass (staleness, IPO collar, cluster cap, unverified volume cap, kill-switch freeze); `site-guard.yml` PASS; zero accidental cloud spend | **SHIPPED (2026-11-20)** |
| **Phase 1 · GCP Live Ingestion & Alerting** | Provision Cloud Run (`sme-stock-agents`), Cloud Scheduler (`08:00–10:15 ET` ±1s), Pub/Sub, Firestore, BigQuery dataset, and verified extended-hours volume adapter (Alpaca SIP / Polygon via Secret Manager) | **Gate 1:** 10 consecutive weekdays with `<= 2s` schedule drift, `volume_verified=true` on 100% of Core-18 tickers, and verified live `ANT`/anchor alerts | Ready for Deploy Approval |
| **Phase 2 · Forge Fox Walk-Forward Audit** | Execute pre-registered Cross-Repricing Convergence backtest on **Cloud Run Jobs** using point-in-time BigQuery bars (including splits/delisted hygiene & realistic slippage) | **Gate 2:** OOS Expectancy `> +0.15R`, Deflated Sharpe PASS, zero lookahead audit, Graveyard log updated | Planned |
| **Phase 3 · Paper Broker & TradeZella MCP** | Connect **Relay Falcon** to Paper Equity API (`09:30–10:15 ET`) with Firestore ACID ledger + 16:20 ET **TradeZella MCP** fill-drift reconciliation | **Gate 3:** 20 consecutive RTH sessions, zero unhandled exceptions, zero kill-switch misses, realized fill drift within tolerance | Planned |
| **Phase 4 · Bounded Live Autonomy** | Micro-size live risk (`$100–$250` `1R`) with mandatory human morning arming click in Firestore + Cloud Monitoring kill-switch breaker | **Gate 4:** Explicit human sign-off after Phase 3 audit | Locked |
