# Watchtower — Market Watcher Service (M4)

Deterministic price watcher. Evaluates declarative YAML alert rules against live
market data and notifies **only when something actionable happens** — no LLM in
the hot path, no per-cycle spam, restart-safe.

This is **M4** per `specs/watchtower.md §8`: everything in M1/M2/M3 **plus** the
**web dashboard** (watchlist, watch detail with candlesticks + rule levels,
history feed, system health), **live SSE updates**, self-help **management**
(pause / mute / re-arm / edit levels / new-watch wizard / test-fire / delete),
token auth, and nginx + TLS deploy drafts for `watch.invesper.ai`.

M3 baseline (still here): the **LLM compose path** (best-effort Vesper agent
wake for in-voice follow-ups), **expiry pings** (one-shot "still relevant?" when
a watch passes its `expires`), and a **ccxt/Binance crypto provider**.

M2 baseline (still here): market-hours calendars, a Tencent real-time China/HK
provider, indicator conditions (sma/rsi/volume/avg_volume), cooldown batching,
currency-aware alerts, systemd hardening.

M1 baseline (still here): engine + yahoo/gold_api providers, asyncio polling,
template alerts, ARMED→FIRED→LATCHED state machine, `list/status/test` CLI.

## Layout

```
watchtower/
├── watches/*.yaml         # one declarative watch per file
├── state/state.sqlite     # rule states, fire history, session marks, cooldowns
├── logs/watchtower.jsonl  # one compact line per evaluation cycle
├── logs/outbox.jsonl      # delivered alerts (file backend)
├── config.yaml            # runtime config (delivery, ops, poll, alerts)
├── bin/watchtower         # CLI wrapper
├── deploy/watchtower.service   # system-unit draft (hardened; not installed)
└── src/
    ├── main.py            # asyncio scheduler loop (market-hours aware)
    ├── cli.py             # list | status | test
    ├── engine.py          # safe AST condition evaluator (no eval())
    ├── calendars.py       # exchange_calendars wrapper (M2)
    ├── lifecycle.py       # ARMED/FIRED/LATCHED transitions
    ├── store.py           # sqlite persistence (+ session marks, cooldowns)
    ├── notify.py          # template render (currency-aware) + delivery + batching
    ├── runner.py          # shared fetch+evaluate (loop & CLI), market helpers
    ├── watch.py           # YAML model + validation (compose/expires, M3)
    ├── wake.py            # M3: best-effort agent wake (LLM compose path)
    ├── seed_state.py      # seed latched rules from the legacy cron
    └── providers/         # yahoo, gold_api, tencent, binance_ccxt (M3), base, registry
```

## Setup

```bash
cd watchtower
python3 -m venv .venv
.venv/bin/pip install -r requirements.txt   # now includes exchange_calendars
```

Seed the state DB so rules the old cron already fired start LATCHED (idempotent):

```bash
.venv/bin/python -m src.seed_state
```

## Running

```bash
# Live loop, each watch on its YAML interval, market-hours aware:
.venv/bin/python -m src.main

# Testing: override interval + stop after N cycles (also forces evaluation
# regardless of whether the venue is open):
.venv/bin/python -m src.main --interval 8 --cycles 2 --log-level INFO
```

Installed as a **user** systemd service (`~/.config/systemd/user/watchtower.service`,
lingering enabled). The `deploy/watchtower.service` draft is the stricter
system-unit variant for a future migration.

```bash
systemctl --user restart watchtower
systemctl --user status  watchtower
```

## Market-hours semantics (M2)

Each watch resolves a calendar **venue** from its primary source:

| Source | Venue | Hours |
|---|---|---|
| `.SZ` suffix (Shenzhen) | `XSHG`¹ | 09:30–11:30 / 13:00–15:00 CST |
| `.SS` suffix (Shanghai) | `XSHG` | 09:30–11:30 / 13:00–15:00 CST |
| `.HK` suffix (Hong Kong) | `XHKG` | 09:30–12:00 / 13:00–16:00 HKT (lunch break) |
| plain US ticker (LULU) | `XNYS` | 09:30–16:00 ET |
| `gold_api`, `=F` futures, crypto | `24h` | always open |

¹ `exchange_calendars` ships no `XSHE`; Shenzhen shares Shanghai's sessions, so
`XSHG` is used. Override per source with an explicit `calendar:` field.

Behaviour:

- **Market OPEN** — poll at the configured `interval`; evaluate live `price`
  rules; the stale-data guard still applies (skip if data older than 2×interval).
- **Market CLOSED** (including the lunch break) — drop to a **slow poll**
  (`poll.closed_interval`, default 30 min, per-watch `schedule.closed_interval`
  override). `price` rules are **not** evaluated (jsonl `skipped:"market_closed"`),
  and data is **not** marked stale merely because the venue is closed.
- **`daily_close(...)` / indicator rules** — evaluated **once per completed
  session**, shortly after the session close, against the last *completed*
  daily bar. A per-`(watch, rule)` session mark is persisted in sqlite so
  restarts never double-evaluate or skip. 24h venues (gold) use the UTC date
  as the session key, so close-based rules evaluate once per UTC day.

The scheduler splits each watch's rules into **price rules** (live, market-aware)
and **daily_close rules** (session-gated). A rule counts as a daily_close rule
when it uses completed daily bars (`daily_close`/`sma`/`rsi`/`avg_volume`) and
does **not** also gate on the live `price`.

## Providers

- **tencent** (`qt.gtimg.cn`): **real-time** last price for HK + China A-shares,
  which Yahoo delays. Batch GBK response; fields `[3]`=last, `[30]`=timestamp,
  `[33]/[34]`=day high/low, currency near the tail. Intraday only (no daily
  bars) — pair with a `yahoo` daily source for `daily_close`/indicators. Wired
  with automatic **Yahoo fallback** on failure via the source `fallback:` field.
- **yahoo** (`query{1,2}.finance.yahoo.com`): stocks/futures/FX. Last price +
  daily bars (history window auto-sized to the largest indicator lookback, capped
  at ~250 bars). Carries the venue `currency`.
- **gold_api** (`api.gold-api.com`): spot metals (XAU). Spot price only.
- **binance_ccxt** (`ccxt` → Binance, **M3**): spot crypto (e.g. `BTC/USDT`,
  `ETH/USDT`). Last price + 24h stats from `fetch_ticker`, daily OHLCV from
  `fetch_ohlcv('1d')` (feeds `daily_close`/`sma`/`rsi`/`volume`). **Public
  endpoints only — no API keys anywhere** (the exchange is built with no
  credentials). Retry/backoff on `ccxt.NetworkError` mirrors the other
  providers; non-network `ccxt` errors fail fast (no hammering). Crypto maps to
  the `24h` venue (always open). See `watches/examples/btc-example.yaml` for a
  documented crypto watch with an `rsi(14)` trigger and `compose: llm`.

## Adding a watch

```yaml
id: my-watch
symbol: 300750.SZ
sources:
  intraday:                       # real-time price
    provider: tencent
    symbol: "300750.SZ"
    calendar: XSHG                # optional explicit venue
    currency: CNY                 # optional; used in alert rendering
    fallback: yahoo               # optional; try this provider if tencent fails
  daily:                          # daily bars for close/indicator rules
    provider: yahoo
    symbol: "300750.SZ"
    currency: CNY
primary: intraday
schedule:
  interval: 5m
  closed_interval: 30m            # optional slow poll while closed
  quiet_hours: "01:00-07:00 Asia/Singapore"   # optional
cooldown: 30m                     # optional per-watch alert batching window
context: |
  Why you're watching this — the thesis.
rules:
  - id: reclaim_50d
    when: "daily_close(daily) >= 360"   # evaluated once per session close
    priority: high
    once: true
    message: "Daily close reclaimed the 50-day."
  - id: low_defence
    when: "price <= 285"                # live price rule (market hours)
    priority: high
    once: true
    rearm: "price > 305"
    message: "Testing the 52-week-low defence zone."
notify:
  channel: telegram
  to: "131270671"
  compose: template          # template (default) | llm — see below
expires: 2026-12-31          # inclusive last valid day; past it -> expiry ping
```

Example files under `watches/examples/` are **not** loaded (the loader globs
`watches/*.yaml` and does not recurse). Copy one up a level to arm it.

Validate: `./bin/watchtower test my-watch` (dry-run, sends/mutates nothing).

### Condition language

| Expression | Meaning |
|---|---|
| `price <= X` / `price >= X` | primary source last price vs level |
| `daily_close(source)` | last **completed** daily close (source optional → primary) |
| `sma(n[, source])` | simple moving average of `n` daily closes |
| `rsi(n[, source])` | Wilder RSI over `n` daily periods |
| `volume([source])` | current session volume |
| `avg_volume(n[, source])` | average volume over `n` daily bars |
| `A and B`, `A or B`, `not A` | boolean combinators |
| `90 <= price <= 110` | chained comparisons |
| `volume() > 3 * avg_volume(20)` | arithmetic between numeric/indicator operands |

Indicator functions default to the **primary** source when no source name is
given. Conditions are parsed to an AST and evaluated against a strict whitelist
— there is **no** `eval()` on rule strings, and the top-level expression must be
boolean (a bare `price + 1` is rejected). Missing data (e.g. `sma(50)` with too
few bars) evaluates as "not met" rather than firing.

## Alerts, currency & cooldown batching

- Rendered prices include currency, e.g. `Price: ¥291.11 (CNY)` /
  `HK$431 (HKD)` / `$96.87 (USD)`. Currency comes from the provider metadata or
  the per-source `currency:` field.
- **Cooldown batching** (spec §4): a per-watch minimum gap between alert
  messages (`alerts.cooldown_seconds`, default 30 min; per-watch `cooldown:`
  override). All rules that fire in the **same evaluation cycle** are batched
  into **one** message listing every trigger. Within the cooldown window a
  further message is suppressed — unless a **high-priority** rule is present and
  `alerts.high_priority_bypass` is on, which forces an immediate send. Fire
  history still records each rule separately.

## Config (`config.yaml`)

```yaml
notify:
  backend: file          # append alerts to logs/outbox.jsonl (default, safe)
  # backend: command     # run a shell command; message on stdin + last argv
  # command: ["/path/to/send-telegram", "--to", "131270671"]
ops:
  provider_down_alert_minutes: 30   # one ops alert past this downtime, no spam
poll:
  stale_multiplier: 2    # skip eval if primary data older than 2x interval
  max_retries: 3
  backoff_base: 2.0
  closed_interval: 1800  # slow poll (s) while the primary venue is closed
alerts:
  cooldown_seconds: 1800     # per-watch min gap between alert messages
  high_priority_bypass: true # high-priority rules bypass the cooldown
```

**No API tokens live in this repo.** Real Telegram delivery is wired at review
time by pointing the `command` backend at a sender script.

## LLM compose path (M3)

`compose: llm` (per `notify.compose`, or per-rule `compose:`; default
`template`) layers **best-effort in-voice commentary on top of guaranteed
delivery**. The rule is strict and deliberate:

1. **The deterministic template alert is ALWAYS sent first** via the normal
   notify backend. **Money alerts never wait on an LLM.**
2. **Only after that message is actually delivered** does Watchtower wake the
   Vesper agent — asking it to send a **second** message with richer analysis
   *when warranted* (and to stay silent otherwise). It never sends orders.
3. **If the wake fails, it is logged and dropped — never retried.** A slow or
   absent gateway cannot delay or block the poll loop, and cannot suppress the
   template that already went out.

### Wake mechanism

The wake uses OpenClaw's supported primitive for handing an agent a task from an
external process:

```
openclaw system event --mode now --session-key agent:vesper:main --text <payload>
```

(chosen after reading the local OpenClaw docs `cli/system.md` +
`automation/hooks.md`; `system event` is the same call the docs use in the
`gateway:pre-restart` hook example). `--session-key` targets the **Vesper**
agent specifically — this gateway hosts multiple agents — and per the docs
collapses to an immediate targeted wake. Watchtower does **not** wait for a
final response (fire-and-forget), so the agent can never stall the loop.

### Wake payload

The agent receives watch id, rule id, condition, fired price + currency, recent
price context (last 5 daily closes + today's high/low range), the watch's
`context` block, and the rule's template message as fallback copy:

```json
{
  "watch_id": "btc-example",
  "rule_id": "oversold_rsi",
  "condition": "rsi(14) < 30",
  "fired_price": 58120.5,
  "currency": "USDT",
  "recent_daily_closes": [61800, 60500, 59900, 58800, 58120],
  "today_range": {"high": 59500, "low": 57800},
  "context": "Example BTC momentum watch. Buy oversold flushes...",
  "fallback_message": "BTC daily RSI(14) < 30 — oversold. Consider a starter add."
}
```

### Wake config & secrets

```yaml
wake:
  enabled: true                         # false -> template still sent, no follow-up
  session_key: "agent:vesper:main"      # which agent session to wake
  mode: now                             # now | next-heartbeat
  token_path: "~/.secrets/watchtower-gateway"  # OUTSIDE the repo; optional
  require_token: false                  # if true + token missing -> feature disables itself
  timeout: 20
```

**No gateway token is stored in the repo.** `token_path` points at a secrets
file outside it; the local gateway RPC needs none, so it stays unset. If
`require_token` is set and the file is absent, the feature **disables itself with
one log warning** (no crash, no spam) — the template path is unaffected.

## Expiry pings (M3)

A watch with `expires` in the past is **disabled** (no further evaluation) and
sends exactly **one** final `⏰ watch expired — still relevant?` ping. The ping
is gated by a persisted `expiry_pings` row, so it **never repeats**, even across
restarts. `expires` is an *inclusive* last-valid date: a watch expires the day
*after* its `expires` date. `watchtower list`/`status` show `⏰ EXPIRED`.

## CLI

```bash
./bin/watchtower list              # all watches + per-rule states + venue + compose + ⏰EXPIRED
./bin/watchtower status <id>       # detail: live prices, currency, market_open, compose, history
./bin/watchtower test <id>         # dry-run vs LIVE data — sends/mutates nothing
./bin/watchtower history [--days N] # fire history across all watches (default limit 100)
```

`list`/`status` mark `compose: llm` rules with a 🧠 badge and expired watches
with `⏰ EXPIRED`.

## Dashboard (M4)

A server-rendered web UI (FastAPI + Jinja2 + htmx + `lightweight-charts` from
CDN — no SPA build step), dark and mobile-first, on its **own** user service
separate from the engine. It reads the same sqlite (read-only connections, WAL
mode) and the `watches/*.yaml` directory; **every mutation goes through the same
validated path as the CLI** (`src/manage.py`), so the UI is a client, never a
second brain.

### Run

```bash
# Local (foreground):
./bin/watchtower-web            # uvicorn on 127.0.0.1:8787 ONLY (never 0.0.0.0)

# As a user service (installed at ~/.config/systemd/user/watchtower-web.service):
systemctl --user enable --now watchtower-web
systemctl --user status watchtower-web
journalctl --user -u watchtower-web -f
```

The engine (`watchtower.service`) and the web (`watchtower-web.service`) are
**independently restartable** — restarting one never touches the other.

### Auth

The app assumes nginx sits in front with its own auth, but **also** enforces a
signed token session so it's safe even if nginx auth is misconfigured:

- A bearer token lives at `~/.secrets/watchtower-web-token` (0600), generated on
  first start if absent. **Never** stored in the repo.
- Login page: paste the token once → an HttpOnly cookie is set. Requests are
  authorized by a **constant-time** compare of the cookie (or an
  `Authorization: Bearer` header) against the on-disk token.

```bash
cat ~/.secrets/watchtower-web-token       # hand this to whoever logs in
# rotate: rm the file && systemctl --user restart watchtower-web
```

### Views (spec §5.1)

- **Watchlist** (`/`) — one card per watch: symbol, last price + currency, 1d %,
  inline SVG sparkline (last ~50 persisted samples), per-rule state chips
  (🟢 ARMED / 🔴 FIRED / ⚪ LATCHED / ⏸ PAUSED / ⏰ EXPIRED), a
  **distance-to-trigger** bar + % per armed price rule, staleness indicator
  (red when data is older than 2× interval while the venue is open; market-closed
  shown distinctly). The **closest trigger across all watches floats to top**.
- **Watch detail** (`/w/<id>`, deep-linkable) — candlestick chart with rule
  levels as horizontal lines colored by state + fire markers; **1h / 4h / 1D**
  timeframe toggle (bars fetched server-side via Yahoo, cached with a TTL; 4h is
  resampled from 1h; degrades to daily if intraday is unavailable); rule table
  (condition, state, fired at price/time, re-arm, cooldown remaining, compose
  badge); fire history; the YAML `context` rendered as the thesis note.
- **History** (`/history`) — chronological alerts across watches with prices +
  delivery status.
- **System** (`/system`, JSON at `/health`) — provider status (last success,
  error counts, down-since), last poll cycle + age, state-db size, engine uptime,
  web version.

### Management (spec §5.2, shared path)

Pause/resume, mute-until (keeps evaluating + logging, suppresses delivery),
re-arm a latched rule, edit rule levels (inline → validate → rewrite YAML →
archive previous version → audit old→new → engine hot-reload), new-watch wizard
(level / breakout / rsi templates), test-fire (dry-run, sends nothing), delete
(archives YAML to `watches/archive/`, never hard-deletes). The same actions are
available on the CLI:

```bash
./bin/watchtower pause  gold-reentry        # --resume to undo
./bin/watchtower mute   gold-reentry --hours 4   # 0 to unmute
./bin/watchtower rearm  gold-reentry zone_entry
./bin/watchtower edit   lulu-base base_breakout --when 'daily_close(primary) >= 106'
./bin/watchtower new    tsla-dip --symbol TSLA --template level --level 200
./bin/watchtower delete old-watch
```

The **engine picks up YAML changes without a restart**: a `WatchRegistry`
re-reads changed files by mtime each cycle (a bad edit is logged and the prior
good version is kept); a supervisor launches loops for newly added watches. It's
also restart-safe, because all state lives in sqlite.

### Live updates (spec §5.3)

An SSE endpoint (`/events`) tails the engine's cycle jsonl and pushes a `cycle`
event (watch id, price, states, ts) per poll cycle. The watchlist refreshes its
cards via htmx on each event; the client reconnects with exponential backoff.
The pages are **fully server-rendered without JS** — SSE is enhancement only.

### Deploy (drafts in `deploy/`, parent applies with sudo)

- `deploy/watchtower-web.service` — the user unit (bind 127.0.0.1:8787).
- `deploy/nginx-watch.invesper.ai.conf` — TLS + basic auth + `proxy_pass`, with
  `proxy_buffering off` on `/events` for SSE and a 502/503 static fallback.
- `deploy/offline.html` — the graceful-degradation page served when the app is
  down (spec §5.3).
- `deploy/DEPLOY.md` — exact certbot + htpasswd + nginx commands.

## Lifecycle & safety

- **ARMED → FIRED → LATCHED**: `once: true` latches after one fire; `rearm`
  restores ARMED when its condition is true again.
- **Restart-idempotent**: state, session marks and cooldown clocks live in
  sqlite. A LATCHED rule never re-fires after a restart; a `daily_close` rule
  never double-evaluates a session it already saw.
- **Stale-data guard**: skipped when primary data is older than `2 × interval`
  — but a closed venue alone does **not** count as stale.
- **Provider resilience**: retry with backoff; per-source Yahoo fallback; one
  ops alert if a provider stays down past the threshold.
- **Quiet hours**: during the window, only `priority: high` rules alert
  immediately; others queue and flush when the window ends.

## Tests

```bash
.venv/bin/python -m pytest -q
```

Covers the engine evaluator (comparisons, `daily_close`, indicators, arithmetic,
unsafe-input rejection), the market calendars (open/lunch/closed, session keys,
via a fixed clock), the Tencent parser (recorded GBK fixture, HK + A-share
timestamp shapes), indicator math (SMA, Wilder RSI against a hand-computed
series, volume/avg_volume), cooldown batching + high-priority bypass +
restart persistence, once-per-session daily_close gating, lifecycle transitions
incl. restart idempotency, and YAML loading/validation incl. the shipped watches.

**M3 tests** add: the **compose fallback ordering** (template always sent; wake
fires only for sent `compose: llm` rules; a suppressed send fires no wake; a
wake failure is swallowed with no retry; disabled/missing-token self-disable),
the **expiry one-shot ping** (boundary date, sent once, never repeats across a
simulated restart), the **Binance provider** (ticker + OHLCV parsing, currency
from the pair, retry/backoff on `NetworkError`, no-retry on `ExchangeError`,
range→limit mapping, registry wiring), and the **history CLI** (cross-watch
ordering, `--days` filter).

**M4 tests** add: **distance-to-trigger** math (down/up thresholds, num-on-left
flip, `daily_close` parsing, clamp-at-zero, non-parsable indicator/boolean
conditions, monotonic progress), **management mutations via the shared path**
(pause/resume/mute + audit, re-arm only-when-latched, edit → YAML rewrite +
archive + old→new audit, invalid-expression rejected with no write, delete
archives, template wizard produces valid YAML, duplicate/bad-template rejected),
the **web app** (auth redirect + 401, bad/good token login + cookie, watchlist
renders all watches, detail + 404, pause/re-arm/edit/delete/test-fire/wizard over
HTTP, health endpoint shape, SSE `hello`+relay handshake), and the **engine
hot-reload** (`WatchRegistry` add/change/remove + keep-prior-good-on-bad-edit,
pause/mute flag roundtrip, price-sample trim/order, provider-health + engine-meta
persistence).

All web/SSE tests run against tmp fixtures with an isolated token and stubbed
quotes — no real sends, no network, no live-state mutation.
```
