Overview
The ExchangeSimulator provides realistic trading behavior without risking capital. It simulates order matching, position lifecycle, margin requirements, and automated exit execution.Account State Management
Account Structure
Each account maintains:- Cash balance - Current cash position (can go negative with leverage)
- Available cash - Free capital available for new positions
- Margin balance - Total margin locked in open positions
- Equity - Total account value (cash + unrealized P&L)
- Positions - Open position details with real-time P&L
Retrieving Account State
Balance Calculations
The simulator tracks capital allocation with leverage support:src/server/features/simulator/accountState.ts
Available cash only increases when positions are closed (realized P&L). Unrealized P&L does not affect buying power.
Order Execution
Order Types
The simulator supports two order types:order type
Executes immediately at best available price by walking the order book. May result in partial fills if liquidity is insufficient.
order type
Places order at specified price. If price crosses the spread, acts as taker (immediate execution). Otherwise, fills at limit price as maker.
Placing Orders
Order Matching Logic
The simulator uses realistic matching with order book depth:src/server/features/simulator/orderMatching.ts
Execution Statuses
status
Order fully executed at one or more price levels
status
Order partially executed - insufficient liquidity to fill complete quantity
status
Order failed validation (insufficient cash, no liquidity, invalid parameters)
Fill Details
Each execution returns detailed fill information:Position Management
Position Lifecycle
Positions are created and modified through order execution:- Opening - Buy order creates LONG position, sell order creates SHORT position
- Adding - Same-side order increases position size (average entry price recalculated)
- Reducing - Opposite-side order decreases position size (realizes P&L)
- Flipping - Large opposite-side order closes position and opens reverse position
- Closing - Opposite-side order equal to position size fully closes position
Position Tracking
Retrieving Open Positions
Position State Updates
The simulator applies executions with precise P&L tracking:src/server/features/simulator/accountState.ts
Exit Plans (Stop-Loss / Take-Profit)
Exit Plan Structure
Setting Exit Plans
Exit plans can be set when opening positions or updated later:Automatic Exit Execution
The simulator monitors exit plans during each market refresh cycle:src/server/features/simulator/accountState.ts
- Collects triggers during market refresh
- Queues auto-close operations
- Executes market order to close position
- Updates database - Records exit in
Orderstable withcloseTriggerfield - Logs trade - Creates
CLOSE_POSITIONentry inToolCallstable withautoTriggermetadata - Emits events - Notifies clients of position closure
Margin & Leverage
Margin Calculation
Margin is allocated based on position notional and leverage:Leverage Rules
- Default leverage: 1x (no borrowing)
- Maximum leverage: No hard limit enforced by simulator (exchange limits apply in live mode)
- Margin requirement:
notional / leveragemust not exceed available cash - Liquidation: Not implemented in simulator (positions can go deeply underwater)
Cash Sufficiency Check
Before executing orders, the simulator validates sufficient capital:src/server/features/simulator/accountState.ts
The simulator allows negative cash balance (borrowing) as long as equity remains above total margin requirement.
Event System
The simulator emits events for real-time updates:Event Types
Subscribing to Events
Database Integration
Orders Table as Source of Truth
All positions are persisted to theOrders table:
- OPEN status = Active position
- CLOSED status = Completed trade
- Fields:
symbol,side,quantity,entryPrice,exitPrice,leverage,exitPlan,closeTrigger
Trade History Tracking
Completed trades are logged in theToolCalls table:
Next Steps
Order Execution
Learn to place orders and track fills
Position Management
Detailed guide to position lifecycle and P&L calculation

