# System Overview — TradingBite Platform

**Version:** 0.7.0  
**Status:** Phase F3 — multi-asset historical data foundation

### Phase F3 as-built

- **Instruments:** `lib/market/instruments.ts` — FX, METAL, CRYPTO, INDEX ([ADR-005](../decisions/ADR-005-MULTI-ASSET-DATA-ARCHITECTURE.md))
- **Historical adapters:** OANDA + Binance public klines → `fetchHistoricalFromSource`
- **Warehouse:** SQLite schema v2 migration; batched import; query cap 5000 + `afterMs`
- **Providers doc:** [PROVIDER-SOURCES-F3.md](../data/PROVIDER-SOURCES-F3.md)

### Phase F2 as-built

- **Indicator:** `tradingbite.sr-finder-2.1` — Pine 2.1 chart-TF simulation ([SR-FINDER-2.1.md](../indicators/SR-FINDER-2.1.md))
- **Chart:** optional **S/R Finder** overlay (green support / red resistance lines)

### Phase F1 as-built

- **Engine:** `lib/indicators/*` — registry, parameters, `runIndicator()` ([ADR-004](../decisions/ADR-004-INDICATOR-ENGINE.md))
- **Reference indicator:** `reference.sma` (overlay line; not a Pine port)
- **Chart:** optional SMA toggle + period on `TradingChart.tsx`; disabled = Phase D/E behavior

### Phase E as-built

- **DB:** `lib/warehouse/*`, SQLite at `data/tradingbite-warehouse.sqlite` ([ADR-003](../decisions/ADR-003-WAREHOUSE-STORAGE.md))
- **Import:** `lib/brokers/oanda/historical.ts`, `npm run warehouse:import:*`
- **Query:** `getWarehouseCandles` → `GET /api/warehouse/candles`
- **Chart:** Data selector **Warehouse** vs **OANDA Live** (warehouse: EUR/USD M15)

### Phase D as-built

- **UI:** `components/TradingChart.tsx` — symbol/timeframe toolbar, manual refresh, fit content
- **Validation:** `lib/market/symbols.ts`, `timeframes.ts`, `validation.ts`, `limits.ts`
- **API:** `GET /api/candles` with optional `count` (max 500)
- **Cache:** `lib/cache/memory-cache.ts` — 30s TTL + dedupe ([ADR-002](../decisions/ADR-002-phase-d-memory-cache.md))
- **Stale guard:** `lib/market/chart-guard.ts` + client request sequence

### Phase C as-built (retained)

- **App root:** repository root (`app/`, `components/`, `lib/`) — not split into `apps/web` yet.
- **API:** `GET /api/candles` with Phase C validation (`EUR_USD`, `H1` only).
- **OANDA:** `lib/brokers/oanda/adapter.ts` → practice URL only; `count=100`; mid prices; tick `volumeType`.
- **Chart:** Lightweight Charts v5 in `components/EurUsdChart.tsx` (client-only; no token in bundle).
- **Not implemented:** cache layer, DB, auth, FXCM, indicators, backtest.

## Goals

- Professional web terminal for FX charts and (later) backtesting
- **Normalized** market data independent of broker UI
- **Adapter pattern** for OANDA (initial), FXCM (later), optional crypto exchanges
- **$0 recurring** infrastructure where possible; self-hosted / local warehouse for long history
- TradingBite indicators ported **Pine → TypeScript** with validation tests (no Pine in browser by default)

## Logical architecture

```text
┌─────────────────────────────────────────────────────────────────┐
│  Client (Browser)                                                │
│  TradingBite Web — chart, panels, backtest UI (phased)           │
│  Chart engine: Lightweight Charts (OSS, MIT — verify at Phase D) │
└────────────────────────────┬────────────────────────────────────┘
                             │ HTTPS (JSON)
                             │ No broker secrets in browser
┌────────────────────────────▼────────────────────────────────────┐
│  Application server (Phase C+: Next.js Route Handlers or API)    │
│  ┌─────────────┐ ┌──────────────┐ ┌─────────────────────────┐   │
│  │ Symbols     │ │ Candles API  │ │ Health / config         │   │
│  └─────────────┘ └──────────────┘ └─────────────────────────┘   │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │ Provider layer (interfaces)                              │   │
│  │  OandaAdapter │ FxcmAdapter (future) │ ExchangeAdapter   │   │
│  └─────────────────────────────────────────────────────────┘   │
└────────────┬───────────────────────────────┬────────────────────┘
             │                               │
             ▼                               ▼
┌────────────────────────┐      ┌───────────────────────────────┐
│  Cache (optional)      │      │  Historical warehouse         │
│  In-memory → file/DB   │      │  Phase E: SQLite / PostgreSQL │
│  Rate-limit protection │      │  Incremental ingest + dedupe  │
└────────────────────────┘      └───────────────────────────────┘
             │
             ▼
┌────────────────────────┐
│  External (permitted)  │
│  OANDA v20 REST/Stream │
│  FXCM REST (later)     │
└────────────────────────┘
```

## Component responsibilities

### Frontend

- Rendering, interaction (zoom, pan, crosshair, TF switch)
- Calls **only** first-party APIs for market data
- Indicator rendering driven by TS indicator engine (Phase F)
- Dark trading-terminal UX; TradingBite branding (not TradingView assets)

### Chart engine

- Decoupled from broker: consumes `NormalizedCandle[]`
- Supports overlays and separate panes (Phase F/G)
- Real-time updates via server push or polling (Phase D), merged bar rules documented

### Backend

- Holds broker credentials (`OANDA_API_TOKEN`, etc.)
- Adapters fetch raw candles → normalize → return DTOs
- Future: auth, watchlists, alert jobs, backtest jobs (phased)

### Data adapters

```text
BrokerProvider
  listInstruments()
  getCandles(symbol, timeframe, from, to) → NormalizedCandle[]
  (optional) streamPrices()
```

Implementations: `OandaAdapter` (Phase C), `FxcmAdapter` (Phase J).

### Historical data warehouse (Phase E)

- Downloader uses adapters; stores canonical OHLCV
- Backtest engine reads warehouse, not live API per run (Phase H)
- Metadata per dataset: source, symbol, TF, range, timezone, import date, validation status

### Indicator engine (Phase F)

- Pure functions / pipelines over bar arrays
- Outputs: line series, histograms, markers
- Golden tests vs reference CSV from Pine exports

### Backtesting engine (Phase H)

- Closed-bar event loop; spread/slippage models
- Metrics: equity, DD, trade list, profit factor, etc.
- Clear disclaimer: simulation ≠ live performance

### Authentication (Phase K)

- Not in Phase C. Future: session auth, encrypted broker token storage per user if multi-tenant

### Storage

- Phase C: none required (pass-through API)
- Phase E: SQLite acceptable locally; PostgreSQL for multi-user later
- `data/` gitignored — no committed market datasets

### Caching

- Start: in-process TTL cache for candle requests (Phase C optional)
- Add Redis only if demonstrated need (project rules: avoid premature infra)

### Testing

- Unit: normalization, indicator math, backtest no-lookahead
- Integration: adapter mocks + recorded fixtures (no live API in CI if no secrets)
- E2E: Playwright after Chart MVP (Phase D+)

### Deployment (Phase K)

- Static/SSR front + API on single VPS or free-tier host **only if** terms remain $0
- Secret audit before any public URL

## Security boundaries

| Secret / asset | Location |
|----------------|----------|
| OANDA API token | Server env only |
| DB credentials | Server env only |
| Normalized candles | API responses to authenticated or local dev user |
| Historical files | Server disk, not public bucket without access control |

## Module boundaries (future monorepo)

```text
apps/web          — Next.js UI + route handlers
packages/core     — Normalized types, timeframe utils
packages/broker-oanda
packages/broker-fxcm   (later)
packages/indicators
packages/backtest      (Phase H)
```

Phase C may start as a single `apps/web` package; extract packages when duplication appears (no premature split).

## Related documents

- [ADR-001](../decisions/ADR-001-stack-and-oanda-first.md)
- [Normalized OHLCV](../data/NORMALIZED-OHLCV.md)
- [Phase C scope](../phases/PHASE-C-SCOPE.md)
