Architecture
The trading system is built on a single source of truth pattern where theOrders table in PostgreSQL serves as the canonical state for all positions and trades.
Orders Table
- OPEN status = active positions
- CLOSED status = completed trades
- Stores entry/exit prices, P&L, and exit plans
Dual Mode
- Live Trading via Lighter exchange API
- Simulation with order book matching engine
- Toggle via
IS_SIMULATION_ENABLEDenvironment variable
Core Components
Trade Executor
Orchestrates the complete trading workflow for each AI model.src/server/features/trading/tradeExecutor.ts:82
Key Responsibilities:
- Fetch portfolio, positions, and market data
- Build AI prompts with current state
- Execute agent with tool calls (create/close/hold positions)
- Track telemetry and update database
- Emit SSE events for real-time UI updates
- Query current portfolio and open positions
- Calculate performance metrics (Sharpe, win rate, drawdown)
- Fetch shared market intelligence (cached across models)
- Build variant-specific prompts
- Execute AI agent with retry logic (2 retries, exponential backoff)
- Process tool calls and capture results
- Persist invocation and emit events
Scheduler
Runs trading workflows on a 5-minute interval for all active models.src/server/features/trading/tradeExecutor.ts:376
Execution Strategy:
- Models run in parallel (non-blocking)
- Per-model timeout ensures no model blocks others
- Stale detection clears models stuck >10 minutes
- Market intelligence cache invalidated after batch completion
Database Schema
TheOrders table is the single source of truth for all trading state.
src/db/schema.ts:125
Key Fields:
status:OPEN(active position) orCLOSED(completed trade)exitPlan: JSONB containing stop-loss, take-profit, invalidation conditionsslOrderIndex/tpOrderIndex: References to live SL/TP orders on exchangecloseTrigger: Tracks whether position was closed manually or via SL/TP
- Derived values not stored:
entryNotionalandexitNotionalcalculated on-the-fly - Unrealized P&L computed live: Uses current market prices
- Confidence stored in exitPlan: Represents AI’s confidence in the exit strategy
Data Flow
Execution Modes
Live Trading
Directly interacts with the Lighter exchange via SignerClient.Simulation
Uses an in-memory order book matching engine.
Bootstrap Process:
The simulator restores OPEN positions from the database on startup, ensuring auto-close triggers work across server restarts.
src/server/features/simulator/exchangeSimulator.ts:203
Key Files
| File | Purpose |
|---|---|
tradeExecutor.ts | Main workflow orchestration and scheduler |
order.ts | Order creation and fill tracking |
fillTracker.ts | Transaction polling and fill verification |
slTpOrderManager.ts | SL/TP order placement on exchange |
createPosition.ts | Position opening logic (live + sim) |
closePosition.ts | Position closure logic (live + sim) |
exchangeSimulator.ts | Simulation engine and order matching |
orderMatching.ts | Order book matching algorithm |
accountState.ts | In-memory position and P&L tracking |
Environment Variables
Next Steps
Order Execution
Learn how orders are placed and filled
Position Management
Understand position tracking and exit plans
Risk Controls
Explore risk management mechanisms
AI Strategies
Explore the AI trading strategy variants

