System architecture
TodoAI is a Next.js 16 (App Router) + MongoDB full-stack application, with a deterministic event-driven engine + ccxt adapters at its core.

Layers
| Layer | File | Responsibility |
|---|---|---|
| Browser | src/app/*/page.tsx | React 19 UI, pure presentation |
| API routes | src/app/api/*/route.ts | Auth + input validation + delegate to lib |
| Business core | src/lib/*.ts | Engine, AI, error normalization, broadcast |
| Data | Prisma + MongoDB | User / Strategy / Order / Position |
| External | ccxt · LLM · Redis | OKX/Binance · DeepSeek · tier cache |
⚠️ Strict UI/business separation — all React components in
src/components/do not directly read/write the database, do not call ccxt, do not manipulate Prisma. All business logic lives insrc/lib/. Components only send requests and render responses.
Core modules at a glance
The most important files in src/lib/:
| File | Role |
|---|---|
engine.ts | Strategy execution engine. Per-tick RuleTree evaluation, BUY/SELL/HOLD signal generation, SL/TP, cooldown, idempotency lock enforcement |
trade-service.ts | Unified order layer. Amount normalization, balance pre-check, auto-derives positionSide / reduceOnly from intent |
exchange-errors.ts | ccxt error normalizer — translates raw error into ExchangeError with code/hint. Every API boundary must go through it |
circuit-breaker.ts | Per-user failure isolation (3 failures / 60s breaker). One user's bad key never affects others |
profit-broadcaster.ts | In-process pub/sub, close path broadcasts → SSE pushes |
session.ts | JWT session. Two paths: getServerSession (fast) + requireFreshSession (slow, with tier cache) |
encryption.ts | User API Key encryption/decryption |
logger.ts | Structured logging, JSON in production / text in dev, with requestId correlation |
config.ts | Centralized runtime config (timeouts, slippage, poll cadences). Each constant has a "why" comment |
Data flow
AI strategy generation
Natural language idea
→ ai-reasoning-service.ts (Stage 1, reasoning chain, SSE streamed)
→ ai-service-stream.ts (Stage 2, DSL compilation)
→ strategy-validator.ts (Zod validation)
→ MongoDB (Strategy model)
→ DslEditor / StrategyVisualizerSee AI Pipeline for details.
Engine execution
scripts/cron-tick.ts (systemd timer every 30s)
→ engine.executeStrategy(strategyId)
→ Load strategy + in-process Set + DB lock
→ withTimeout(15s) fetch candles
→ Compute indicators (fingerprint-keyed cache)
→ Evaluate RuleTree (LONG + SHORT)
→ SL/TP + cooldown check
→ TradeService.execute → AdapterFactory → ccxt
→ Write StrategyEventLog (with remediationCode)
→ profit-broadcaster (close path)
→ finally release lockSee Engine Tick for details.
Real-time push
3 independent SSE + in-process pub/sub + cross-component window events. See SSE Streaming.
Auth
JWT is written to an httpOnly cookie; all API userIds are read from the session, never from query/body (PR1–PR3 IDOR defense). See Auth & Session.
Error handling
The moment any ccxt error crosses the API boundary, it must be translated via src/lib/exchange-errors.ts::normalizeExchangeError into {code, status, messageKey, doc, hint?}. See Error Normalization.
Deployment topology
┌──────────────────┐
│ Cloudflare/Caddy│ ← TLS
└────────┬─────────┘
│
┌────────▼─────────┐
│ Next.js server │ ← systemd: quantokx-web
│ (port 3000) │
└────────┬─────────┘
│
┌─────────────────────┼─────────────────────┐
│ │ │
┌────────▼────────┐ ┌─────────▼────────┐ ┌────────▼────────┐
│ quantokx-cron │ │ MongoDB │ │ Upstash Redis │
│ systemd timer │ │ (cluster) │ │ (tier cache) │
│ every 30s │ │ │ │ │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│
┌────────▼─────────┐
│ OKX / Binance │
│ (REST + WS) │
└──────────────────┘Load-bearing invariants
From CLAUDE.md — all new code must respect these:
userIdalways read from session — never from query/bodyENCRYPTION_KEYandJWT_SECRETmust be independent — never reuse- Engine invariants: in-process Set + DB lock + module-load watchdog
- Indicator memoization keyed by fingerprint
- Side-aware PnL — every close path must distinguish LONG/SHORT
- Cross-component UI events use the
qt:*namespace; Sidebar is the canonical listener forqt:open-settings