# 07 · Phased Build Plan — Claude Prompts & Acceptance

The whole system, sequenced so **nothing depends on code that doesn't exist
yet**. Each milestone is a self-contained "Claude task" you can paste, plus the
acceptance test that says it's done. Ship them **in order** — each is usable on
its own, and paper-trading works end-to-end by Milestone 7, long before any live
key is touched.

> Convention: paste the milestone block to Claude. It references the types and
> interfaces from [`01-architecture.md`](01-architecture.md); keep that doc open.
> Language is your choice (Python or TypeScript) — keep the wire format JSON.

---

## Milestone map

| # | Milestone | Depends on | Outcome |
|---|-----------|-----------|---------|
| 0 | Repo skeleton + types + event bus | — | contracts compile; bus works |
| 1 | Market-data ingest → `Candle[]` | 0 | live + historical candles on the bus |
| 2 | Indicator library + `IndicatorBook` | 0 | all formulas, unit-tested |
| 3 | Detectors: indicators (MA/osc/vol/trend) | 2 | most `Signal`s firing |
| 4 | Detectors: price-structure (harmonic/chart/candle) | 2 | remaining `Signal`s |
| 5 | Backtester (reuses detectors) | 1–4 | strategies measurable |
| 6 | Strategy + risk gate + sizing + kill switch | 3–4 | `Signal → Intent` |
| 7 | Order router + **paper simulator** + ledger | 6 | **paper trading works E2E** |
| 8 | Alert render + web/mobile/email | 6 | alerts + approvals (web) |
| 9 | Telegram + WhatsApp bots (approve→order) | 7–8 | chat-driven trading |
| 10 | Live broker adapter (Alpaca paper→live) | 7 | live-shaped execution |
| 11 | Promotion gates, audit, observability, hardening | all | production-ready |

---

## Milestone 0 — Skeleton, types, bus

> **Claude task.** Scaffold the repo per doc 01 §7 (`ingest/ engine/ strategy/
> risk/ alerts/ oms/ ledger/ config/`). Define the shared types from doc 01 §2
> (`Candle, Signal, Intent, Order, Fill, Alert`) and the `Detector`, `Broker`,
> `AlertChannel`, `IndicatorBook` interfaces. Set up an internal event bus
> (Redis Streams / NATS) with typed publish/subscribe, a Postgres schema for
> orders/fills/positions/alerts/audit **with a UNIQUE index on
> `orders.client_order_id`**, and a `config/` module exposing `EXECUTION_MODE`
> (default `paper`), symbol/timeframe lists, and strategy params.
> **Acceptance:** types compile; a message published on the bus is received by a
> subscriber; migrations create the tables and the unique index; `EXECUTION_MODE`
> reads `paper` by default.

## Milestone 1 — Market-data ingest

> **Claude task.** Implement `ingest/` adapters that produce normalised
> `Candle[]` (doc 01 §2.1) onto the bus: one **historical** loader (REST
> backfill) and one **real-time** stream (WebSocket), for at least one provider
> (e.g. Alpaca/Polygon/Finnhub for equities or Binance/CCXT for crypto). Emit
> only **closed** bars downstream (mark forming bars `closed:false`). Handle
> reconnects, gap-fill on reconnect, and timezone→UTC-ms normalisation.
> **Acceptance:** backfilling N days yields a contiguous gap-free series; the
> live stream appends closed bars in order; a forced disconnect auto-recovers and
> back-fills the gap.

## Milestone 2 — Indicator library

> **Claude task.** Implement every formula in [`03-indicators.md`](03-indicators.md)
> §0 as pure, incremental functions in `engine/indicators/`, plus
> `engine/indicators/swings.ts` (doc 02 §0). Assemble them into `IndicatorBook`
> (doc 01 §5) with memoisation keyed on `(symbol, tf, lastBarTs)`. **Acceptance:**
> values match TA-Lib/pandas-ta within 1e-6 on a fixed 500-bar fixture; EMA/RSI/
> ATR update O(1) per new bar; `swings` returns a strictly alternating H/L list.

## Milestone 3 — Indicator detectors

> **Claude task.** Implement the detectors in `03-indicators.md` §6:
> `engine/detectors/ma.ts, osc.ts, vol.ts, trend.ts` (golden/death cross,
> price_cross, ema_pullback, ribbon, vwap_cross, supertrend, rsi(+divergence),
> macd(+divergence), stochastic, stoch_rsi, cci, williams_r, roc, ao, mfi,
> bb_bounce, bb_squeeze, ttm_squeeze, keltner, donchian, atr_breakout,
> volume_spike, obv, cmf, adx, ichimoku, psar, aroon). All threshold-crossers
> reuse `crossUp/crossDown`; each emits the shared `Signal` with `evidence` and
> normalised `strength`. **Acceptance:** the engine loop (doc 01 §3) run over a
> scripted series fires each detector on the correct bar with the correct `side`;
> nothing fires on a forming bar (no repaint).

## Milestone 4 — Price-structure detectors

> **Claude task.** Implement `engine/detectors/harmonic.ts` (generic
> `makeHarmonic(spec)` + gartley/butterfly/bat/crab/deep_crab/cypher/shark/abcd/
> three_drives), `engine/detectors/chart.ts` (head_shoulders±inverse, double/
> triple top&bottom, triangles, wedges, flags/pennants, cup_handle, rectangle),
> and `engine/detectors/candles.ts` (the single/two/three-bar set) — all per
> [`02-patterns-price-structure.md`](02-patterns-price-structure.md), gated by
> PRZ/break/trend confirmation. **Acceptance:** synthetic series with known
> XABCD ratios fire the right harmonic with populated `evidence.ratios`; chart
> patterns fire only on the confirmed break with height-projection targets;
> candlesticks respect trend context.

## Milestone 5 — Backtester

> **Claude task.** Build a backtester that feeds **historical** candles through
> the **exact same** detectors and strategy code bar-by-bar (no look-ahead),
> simulating fills with slippage+fees, and reports win rate, expectancy, max
> drawdown, Sharpe, and per-detector stats. **Acceptance:** a known strategy on a
> fixed dataset reproduces identical results on repeat runs; swapping the feed to
> live requires zero detector changes (proves backtest==live code path).

## Milestone 6 — Strategy, risk gate, sizing, kill switch

> **Claude task.** Implement `strategy/` (rule engine consuming `Signal`s with
> confluence/filters per doc 03 §5 & doc 06 §2), `risk/sizing.ts`,
> `risk/gate.ts`, and `risk/killswitch.ts` per [`06-risk-and-safety.md`](06-risk-and-safety.md).
> Output is an `Intent` (or a logged rejection). **Acceptance:** a rule requiring
> two detectors only emits an Intent when both agree within the window; sizing
> yields constant currency-risk across stop distances; every §3 limit rejects
> with a reason; the kill switch blocks new Intents.

## Milestone 7 — Router + paper simulator + ledger  ⭐ (paper trading live)

> **Claude task.** Implement `oms/router.ts` (idempotent `route()` deriving
> `clientOrderId`, re-running the risk gate, building brackets), `oms/paper.ts`
> (the `Broker` simulator filling against the live feed with slippage+fees, doc
> 05 §3), and `ledger/` (positions, P&L, blotter, audit). **Acceptance:** an
> `ApprovedIntent` becomes exactly one order even if replayed; a market buy
> paper-fills and updates equity; a bracket TP fill cancels its SL; `/positions`
> and the blotter reflect reality. **At this milestone the full pipeline works
> end-to-end in paper mode.**

## Milestone 8 — Alert rendering + web/mobile/email

> **Claude task.** Implement `alerts/render.ts` (Intent+Signal → Alert with
> annotated chart), `alerts/web.ts` (WebSocket + Web Push + `POST
> /alerts/:id/respond`), `alerts/mobile.ts` (FCM/APNs actions), `alerts/email.ts`
> (signed magic-link buttons), and the idempotent `resolveAlert` choke point
> (doc 04 §4). **Acceptance:** a paper Intent raises an alert in the web inbox;
> approving it routes the order; expired/forged tokens are refused; the message
> updates to show the resolution.

## Milestone 9 — Telegram + WhatsApp (chat-driven approve→order)

> **Claude task.** Implement `alerts/telegram.ts` (inline-keyboard alerts +
> `callback_query` webhook + slash commands `/positions /pause /resume /kill
> /mode`) and `alerts/whatsapp.ts` (Meta Cloud API template buttons **or**
> Twilio, with signed webhook), both resolving through `resolveAlert`. **Acceptance:**
> tapping Approve in Telegram places a paper order and edits the message;
> simultaneous approvals across channels yield one order (first wins); unsigned
> webhooks are rejected; `/kill` freezes new orders.

## Milestone 10 — Live broker adapter (Alpaca first)

> **Claude task.** Implement `brokers/alpaca.ts` to the `Broker` interface
> against Alpaca's **paper** endpoint first: `client_order_id`, native bracket
> orders, WS updates → `OrderUpdate`, symbol/tick rounding, startup
> reconciliation; keys from the vault. Then gate real-money `live` behind the
> `EXECUTION_MODE=live` flag + signed ack (doc 06 §5). **Acceptance:** a bracket
> order places on Alpaca paper and fills stream into the ledger; `getPositions`
> reconciles; a `live` order without the ack is refused. Add
> `binance.ts/kite.ts/ibkr.ts/angelone.ts` later to the same conformance suite.

## Milestone 11 — Promotion gates, audit, observability, hardening

> **Claude task.** Add the paper→live promotion gates (doc 06 §5), the `LIVE`
> banner, full append-only audit (signal→alert→decision→order→fill), metrics/
> alerts (latencies, reject rate, slippage vs model, feed staleness, reconciliation
> drift, P&L vs limits), rate limiting, and secret hygiene checks. **Acceptance:**
> a strategy can't be promoted to live-auto without meeting the criteria; the
> audit reconstructs any fill's full path; a secret-scanner finds nothing;
> circuit breakers trip the kill switch on simulated feed-staleness/loss-limit.

---

## Definition of done (whole system)

- [ ] Paper pipeline runs end-to-end: data → signal → alert → approve → paper
      fill → ledger, across all five channels.
- [ ] Every detector and indicator has unit tests against fixtures; backtest and
      live share the exact detector code.
- [ ] Orders are idempotent; the kill switch and daily-loss circuit breaker work.
- [ ] Going live requires the env flag **and** a signed per-account ack; a `LIVE`
      banner is unmissable.
- [ ] No secrets in the repo; all webhooks signature-verified; full audit trail.
- [ ] Risk disclaimer shown in-app and in alerts; broker/market-data terms
      respected.

---

## Suggested build order in one line

`M0 types/bus → M1 data → M2 indicators → M3+M4 detectors → M5 backtest →
M6 strategy/risk → M7 paper OMS → M8 web/mobile/email alerts →
M9 Telegram/WhatsApp → M10 Alpaca live-shaped → M11 harden & gate live.`

Start at [`../README.md`](../README.md) · contract at
[`01-architecture.md`](01-architecture.md).
