# MarketPulse — Trading-Signal → Alert → Order Blueprint

> **What this is.** A complete, build-ready specification that turns a chart
> pattern into (1) a **multi-channel alert** (web, mobile, email, WhatsApp,
> Telegram) and (2) an **order** placed into a **paper** or **live** trading
> account — with a human approve/reject step in the loop by default.
>
> **Who it is for.** These documents are written as *instructions for Claude
> (or any engineer)* to implement, module by module. Every pattern has a
> precise formula, a detection algorithm, entry/stop/target rules, and a
> copy-paste "Claude task" prompt. Every subsystem has an interface contract
> and acceptance criteria.

> [!WARNING]
> **This is engineering documentation, not financial advice.** Automated
> trading can lose money quickly. Nothing here is a recommendation to trade
> any instrument. Ship **paper-trading first**, keep a human approval step,
> and read [`docs/06-risk-and-safety.md`](docs/06-risk-and-safety.md) before
> connecting any live brokerage key. You are responsible for regulatory
> compliance in your jurisdiction (SEBI, SEC/FINRA, MiFID II, etc.).

---

## The one-sentence architecture

```
Market data  →  Indicator/Pattern engine  →  Signal  →  Strategy & risk gate
      →  Alert fan-out (web · mobile · email · WhatsApp · Telegram)
      →  Human approve / auto-execute  →  Order router  →  Paper or Live broker
      →  Fill  →  Position & P&L ledger  →  Notify + audit log
```

Each arrow is a module with a typed contract. Build them in the order given in
[`docs/07-claude-build-prompts.md`](docs/07-claude-build-prompts.md).

---

## Document map

| # | Document | What it covers |
|---|----------|----------------|
| 00 | [`docs/01-architecture.md`](docs/01-architecture.md) | System layers, data flow, the canonical `Signal` / `Alert` / `Order` schemas, tech stack, and the `Detector` interface every pattern implements. |
| 01 | [`docs/02-patterns-price-structure.md`](docs/02-patterns-price-structure.md) | **Price-structure patterns**: harmonic (Gartley, Butterfly, Bat, Crab, Shark, Cypher, ABCD, 3-Drives), classical chart patterns (H&S, double/triple tops, triangles, wedges, flags, cup & handle), and candlestick patterns. |
| 02 | [`docs/03-indicators.md`](docs/03-indicators.md) | **Indicator signals**: moving-average crossovers (Golden/Death Cross, EMA pullback), momentum oscillators (RSI, MACD, Stochastic, CCI, Williams %R, MFI), volatility/breakout (Bollinger, Keltner, Donchian, TTM squeeze, Supertrend), volume & trend (OBV, VWAP, ADX/DMI, Ichimoku, Parabolic SAR). |
| 03 | [`docs/04-signal-delivery.md`](docs/04-signal-delivery.md) | Alert fan-out across web push, mobile push (FCM/APNs), email, **WhatsApp** (Meta / Twilio), **Telegram** bot — plus interactive **approve/reject → order** buttons and two-way command handling. |
| 04 | [`docs/05-order-execution.md`](docs/05-order-execution.md) | The order router, the **paper-trading simulator**, and **live broker adapters** (Alpaca, Interactive Brokers, Binance, Zerodha Kite, Angel One). Idempotency, OCO/bracket orders, reconciliation. |
| 05 | [`docs/06-risk-and-safety.md`](docs/06-risk-and-safety.md) | Position sizing, per-trade/daily risk caps, the **kill switch**, paper→live promotion gates, secrets handling, audit trail, disclaimers & compliance. |
| 06 | [`docs/07-claude-build-prompts.md`](docs/07-claude-build-prompts.md) | The phased delivery plan: milestone-by-milestone Claude prompts with acceptance criteria, from "compute an SMA" to "route a live bracket order." |

A one-page visual overview lives at [`index.html`](index.html) (open it in a
browser or via GitHub Pages).

---

## Runnable code (not just spec)

Parts of the blueprint are implemented, tested, and runnable — **198 tests pass**
(`npm run test:marketpulse`):

| Package | What runs | Where |
|---------|-----------|-------|
| [`engine/`](engine/README.md) | Indicators + 28 detectors + backtester + paper OMS. Pure, zero-dep, browser **and** Node. | [`engine/`](engine/) · **46 tests** |
| [`lab.html`](lab.html) | In-browser demo: generate candles → detect → **backtest (equity curve)** → approve → paper-fill. | open in a browser |
| [`server/`](server/README.md) | The backend + **live scanner**: data feed → detect on each closed bar → alert (email / **Telegram** / **WhatsApp** / **mobile push**) **or auto-route** → idempotent order router + risk gate → **paper, Alpaca, Binance, Zerodha Kite, Angel One or IBKR** → **streaming fills** → **multi-account portfolio ledger**. Zero-dep `node:http`. | [`server/`](server/) · **152 tests** |

```bash
npm run test:marketpulse          # engine + server (198 tests)
node marketpulse/server/server.js # boot the alert→order backend (paper by default)
node marketpulse/demo/showcase.js # narrated end-to-end walkthrough of the real pipeline
```

A visual **[demo showcase](demo/showcase.html)** (nine animated scenes) renders to
a video / PDF; [`demo/showcase.js`](demo/showcase.js) is the runnable walkthrough
behind it and [`demo/SCRIPT.md`](demo/SCRIPT.md) is the narration.

The blueprint's execution + delivery path ships end-to-end: **six broker
adapters** (paper, Alpaca, Binance, Zerodha Kite, Angel One, Interactive Brokers
— one conformance suite) with native brackets on Alpaca/IBKR and a **spot OCO**
on Binance; **five alert channels** (email magic-link, Telegram, WhatsApp, FCM,
APNs); **three durable stores** (memory, file, Postgres) behind one Store
interface; the **live-venue auth flows** (Kite login/checksum, Angel One TOTP +
refresh, IBKR gateway session); **streaming fill feeds** (venue user-data socket
→ OMS status + ledger); and a **multi-account portfolio ledger** (per-account
cash/positions/P&L, cross-venue aggregation, reconciliation). See
[`docs/07`](docs/07-claude-build-prompts.md).

---

## The pattern library at a glance

MarketPulse ships **detectors** grouped into seven families. Each detector emits
the same [`Signal`](docs/01-architecture.md#signal-schema) object, so the
alert and execution layers never need to know *which* pattern fired.

| Family | Examples | Doc |
|--------|----------|-----|
| **Harmonic** (Fibonacci reversal) | Gartley · Butterfly · Bat · Crab · Deep Crab · Shark · Cypher · ABCD · 3-Drives · 5-0 | [02](docs/02-patterns-price-structure.md#1-harmonic-patterns) |
| **Classical chart** | Head & Shoulders (± inverse) · Double/Triple Top & Bottom · Triangles · Wedges · Flags & Pennants · Cup & Handle · Rectangles | [02](docs/02-patterns-price-structure.md#2-classical-chart-patterns) |
| **Candlestick** | Engulfing · Hammer · Shooting Star · Doji · Morning/Evening Star · Harami · 3 Soldiers/Crows · Tweezers · Piercing/Dark Cloud | [02](docs/02-patterns-price-structure.md#3-candlestick-patterns) |
| **Moving averages** | Golden Cross · Death Cross · Price/MA cross · EMA pullback · MA ribbon · VWAP cross · Supertrend | [03](docs/03-indicators.md#1-moving-average-signals) |
| **Momentum oscillators** | RSI · MACD · Stochastic · Stoch-RSI · CCI · Williams %R · ROC · Awesome Osc · MFI · divergences | [03](docs/03-indicators.md#2-momentum-oscillators) |
| **Volatility / breakout / volume / trend** | Bollinger bounce & squeeze · Keltner · Donchian (turtle) · TTM squeeze · Volume spike · OBV · ADX/DMI · Ichimoku · Parabolic SAR | [03](docs/03-indicators.md#3-volatility--breakout-signals) |

Full count and precise trigger rules are in the two catalog docs.

---

## How to use these instructions with Claude

1. **Start with the contract.** Read `docs/01-architecture.md` so every module
   speaks the same `Signal` / `Order` shape.
2. **Pick a milestone** from `docs/07-claude-build-prompts.md` (they are
   ordered so nothing depends on code that doesn't exist yet).
3. **Paste the "Claude task" block** for that milestone. Each one names the
   files to create, the interface to satisfy, and the acceptance test.
4. **Verify against the acceptance criteria** before moving on. Indicators and
   detectors are pure functions — unit-test them against a fixed candle series.
5. **Stay on paper.** The `EXECUTION_MODE` flag defaults to `paper`. Promoting
   to `live` is a deliberate, gated step (see doc 05 §Promotion gates).

---

## Non-negotiable safety defaults (baked into every doc)

- **Paper by default** — `live` requires an explicit env flag *and* a signed
  acknowledgement per account.
- **Human-in-the-loop by default** — an alert asks for approval; full
  auto-execute is opt-in per strategy and always bounded by risk caps.
- **Idempotent orders** — every order carries a `client_order_id` so a retried
  webhook or duplicate alert can never double-fill.
- **Global kill switch** — one flag flattens nothing but *blocks all new
  orders* across every channel and strategy.
- **Everything is logged** — signal → alert → decision → order → fill is an
  append-only audit trail.

---

*Part of [kalilurrahman.github.io](../index.html). Built as a reference
blueprint; not affiliated with any broker or exchange.*
