Skip to content

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.

Architecture

Layers ​

LayerFileResponsibility
Browsersrc/app/*/page.tsxReact 19 UI, pure presentation
API routessrc/app/api/*/route.tsAuth + input validation + delegate to lib
Business coresrc/lib/*.tsEngine, AI, error normalization, broadcast
DataPrisma + MongoDBUser / Strategy / Order / Position
Externalccxt · LLM · RedisOKX/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 in src/lib/. Components only send requests and render responses.

Core modules at a glance ​

The most important files in src/lib/:

FileRole
engine.tsStrategy execution engine. Per-tick RuleTree evaluation, BUY/SELL/HOLD signal generation, SL/TP, cooldown, idempotency lock enforcement
trade-service.tsUnified order layer. Amount normalization, balance pre-check, auto-derives positionSide / reduceOnly from intent
exchange-errors.tsccxt error normalizer — translates raw error into ExchangeError with code/hint. Every API boundary must go through it
circuit-breaker.tsPer-user failure isolation (3 failures / 60s breaker). One user's bad key never affects others
profit-broadcaster.tsIn-process pub/sub, close path broadcasts → SSE pushes
session.tsJWT session. Two paths: getServerSession (fast) + requireFreshSession (slow, with tier cache)
encryption.tsUser API Key encryption/decryption
logger.tsStructured logging, JSON in production / text in dev, with requestId correlation
config.tsCentralized 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 / StrategyVisualizer

See 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 lock

See 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:

  1. userId always read from session — never from query/body
  2. ENCRYPTION_KEY and JWT_SECRET must be independent — never reuse
  3. Engine invariants: in-process Set + DB lock + module-load watchdog
  4. Indicator memoization keyed by fingerprint
  5. Side-aware PnL — every close path must distinguish LONG/SHORT
  6. Cross-component UI events use the qt:* namespace; Sidebar is the canonical listener for qt:open-settings

TodoAI · Turn trading ideas into automated strategies