Intelligence, Advanced Charting & Trading Platform

1 # ADR-0004 — ChartNova multi-market REST + WebSocket + Lightweight Charts
2
3 **Date:** 2026-10-12
4 **Status:** Accepted as architecture/scaffold; implementation and release gates still open.
5
6 ## 1. Intent and compatibility
7
8 Keep the existing modular-monolith market domain, Neon PostgreSQL schema, ECB daily-rate archive, Cloudflare Worker/KV fallback, domestic prices, watchlists and widgets. Do not rebuild the working service. The user's original Windows working tree contains modifications, including an untracked `db/migrations/0005_navasan_private_daily_ohlc.sql`; they were not edited or executed.
9
10 This branch is based on `feature/chartnova-neon-direct-history`; it is separate from the production `main` line and currently has **no production deployment**.
11
12 ## 2. Chosen boundaries
13
14 ```text
15 User React frontend (client only)
16 ├── Lightweight Charts v5 Canvas
17 │ ├── source_ohlc → CandlestickSeries
18 │ └── daily_reference_point_not_ohlc / reference_point → LineSeries
19 ├── HTTPS GET /api/v2/history?... → server REST contract / license gate
20 └── WSS /stream?symbol=... → Cloudflare Worker gateway → per-symbol Durable Object (hibernation)
21 ↑ privately authenticated publisher
22 Source adapters / ingestion scheduler
23 ├── CoinGecko market_chart (price points, not OHLC)
24 ├── Binance spot klines (exchange-specific source OHLC; access gating)
25 ├── yfinance (offline research-only bridge; never public production)
26 ├── Polygon.io (future provider WebSocket subscription, plan-dependent)
27 ├── Navasan (existing adapter; unit and redisplay authorization audit)
28 └── Bonbast (future adapter blocked pending API/license evidence)
29 ↓ normalizers, raw immutable evidence, license contract, quality gates
30 Neon PostgreSQL (canonical raw observations, ticks, OHLC, provenance)
31 ↓
32 KV (cache only)
33 ```
34
35 **Provider adapters never decide final canonical symbol or market unit by guessing.** Mappings are explicit. Quote side (bid/ask/sell/reference/trade), instrument/venue, data time, receive time, quality status and rights are mandatory. Provider prices shall be stored as exact decimals in PostgreSQL, not rounded by rendering code.
36
37 **REST** is for bounded, indexed historical queries (ISO dates, 1h/1d, max 400-day window, <=5000 records/page, cursor). Never query upstream on each UI request. Neon reader restricted to history view; database URL only in secure server runtime. `serveHistoryV2` is an unmounted repository-port scaffold; when lookup is absent, it returns HTTP 503.
38
39 **WebSocket** is for low-latency incremental licensed events, not historical backfill. Proposed Cloudflare Durable Objects Hibernation gateway supports subscription validation, per-channel monotonic sequence, reconnection and gap detection. History replay on reconnect comes from REST. Publisher is authenticated by a private 32+ character token and rejected if rights are not `approved_public`. No provider publishers are active yet.
40
41 **Canvas**: `apps/market-terminal/src/main.jsx` is the runnable standalone React/Vite client using Lightweight Charts version 5 with `chart.addSeries(CandlestickSeries|LineSeries)`; `packages/chart-ui/src/LightweightMarketChart.tsx` remains a reusable component prototype. It does not turn ECB, CoinGecko, or other sampled points into fake OHLC. All public pages must include TradingView NOTICE and link.
42
43 ## 3. Canonical API design
44
45 - Request: `GET /api/v2/history?symbol=BTC_USD&dataKind=source_ohlc&timeframe=1h&from=2025-10-12&to=2026-10-12&limit=1000&cursor=...`
46 - Response: `ok`, `symbol`, `source`, `attribution`, `unit`, `dataKind`, `timeframe`, `series[]`, `page.hasMore`, `page.nextCursor`, `delayed`.
47 - In `source_ohlc`, each returned observation is a real provider bar (`open/high/low/close`; source volume only when supplied), not a resampled single price.
48 - In `reference_point`, each observation contains only `time/price/quality`. Reference daily ECB remains distinct in the existing `/api/history` endpoint.
49 - Query fails closed if provider rights are not independently approved; raw payloads, keys and user credentials are never returned.
50
51 ## 4. Commercial and operational security gates
52
53 No historical OHLC or predictions can be marked complete without:
54 1. Written terms/license confirming retrieval, storage, commercial redistribution, display, attribution, and derived analytics, separately for each provider and asset class.
55 2. A verified provider response from a reachable licensed endpoint, with a deterministic rate limiter and circuit breaker.
56 3. The existing `chartnova_history_ro` role securely activated (not `neondb_owner`); role remains NOLOGIN until credential handoff is approved. Never place DATABASE_URL, API keys or tokens in Git.
57 4. Provider-unit mapping, quote side, timezone/session calendar, duplicate and gap QC, source mutation policy, provenance and correct OHLC semantics.
58 5. Integration tests for actual REST→DB and WebSocket→client sequences, stale data, backpressure, reconnection and recovery; zero fabricated data.
59 6. A runnable React host application, documented deployment target, protected Cloudflare DO binding and safe rollback.
60 7. Successful CI and explicit deployment approval. Existing PR #23 had RED GitHub Actions checks, so local tests do not imply deployability.
61
62 ## 5. Initial implementation files
63
64 ```text
65 packages/market-feed/src/contracts.mjs
66 packages/market-feed/src/adapters.mjs
67 packages/market-feed/src/realtime-protocol.mjs
68 packages/market-feed/src/history-api.mjs
69 packages/market-feed/test/*.test.mjs
70 packages/chart-ui/package.json
71 packages/chart-ui/tsconfig.json
72 packages/chart-ui/src/LightweightMarketChart.tsx
73 deploy/chartnova/market-stream-worker.mjs
74 docs/architecture/ADR-0004-multimarket-rest-ws-charts.md
75 docs/data/multimarket-provider-matrix.md
76 ```
77
78 **Important:** a standalone Vite/React app exists at `apps/market-terminal` and has passed a local production build, but it has **not** been mounted into or deployed over the existing production ChartNova app. No Durable Object was created, no live WebSocket opened and no backfill of unlicensed data was executed.
79
80 ## 6. Resolution of competing scaffolds (implementation detail)
81 Two isolated WebSocket gateway sketches were prototyped while the architecture was being developed. To avoid sending a browser a protocol that its gateway cannot understand, **only** `deploy/chartnova/market-stream-worker.mjs` with `deploy/chartnova/wrangler.realtime.example.toml` is the selected deployment candidate. It uses `/stream?symbol=<CANONICAL_SYMBOL>`, per-symbol `SymbolStreamRoom`, server-side `STREAM_INGEST_TOKEN`, `STREAM_SYMBOL_ALLOWLIST`, and version-1 client `stream.subscribe` messages.
82
83 `deploy/chartnova/realtime-gateway.mjs` and `packages/market-feed/src/realtime-protocol.mjs` remain non-deployed alternative prototypes; do not point the React frontend at the `/ws/market` interface without deliberately migrating and re-testing the protocol. Neither approach has an active provider publisher or a live production route.
84
85 For historical data, the current standalone chart loads the **existing** ECB-only `/api/history` REST endpoint and renders those points as a line. `serveHistoryV2` is a provider-neutral and unmounted port for future licensed OHLC. It returns 503 without a configured repository; real candle display remains disabled until a licensed and independently validated data source, persistence and production REST integration exist.