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.1
Order Placement
Create market order with IOC (Immediate-Or-Cancel) time-in-force
2
Fill Tracking
Poll
waitForTransaction() and checkOrderStatus() to verify execution3
SL/TP Placement
Place real stop-loss and take-profit orders on the exchange
4
Database Sync
Persist position to
Orders table with fill detailsSimulation
Uses an in-memory order book matching engine.1
Order Matching
Match orders against cached order book snapshots
2
Position Tracking
Maintain position state in
AccountState (in-memory)3
Auto-Close Triggers
Poll positions every refresh interval and trigger SL/TP
4
Database Sync
Persist simulated trades to
Orders table for consistencysrc/server/features/simulator/exchangeSimulator.ts:203
Key Files
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

