Skip to main content

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:
  1. Opening - Buy order creates LONG position, sell order creates SHORT position
  2. Adding - Same-side order increases position size (average entry price recalculated)
  3. Reducing - Opposite-side order decreases position size (realizes P&L)
  4. Flipping - Large opposite-side order closes position and opens reverse position
  5. 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
When a trigger is detected, the simulator:
  1. Collects triggers during market refresh
  2. Queues auto-close operations
  3. Executes market order to close position
  4. Updates database - Records exit in Orders table with closeTrigger field
  5. Logs trade - Creates CLOSE_POSITION entry in ToolCalls table with autoTrigger metadata
  6. Emits events - Notifies clients of position closure
Exit plans execute at market price when triggered. Actual fill price may differ slightly from trigger price due to spread and order book depth.

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 / leverage must 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 the Orders table:
  • OPEN status = Active position
  • CLOSED status = Completed trade
  • Fields: symbol, side, quantity, entryPrice, exitPrice, leverage, exitPlan, closeTrigger
The simulator rehydrates state from this table on startup (see Position Rehydration).

Trade History Tracking

Completed trades are logged in the ToolCalls table:

Next Steps

Order Execution

Learn to place orders and track fills

Position Management

Detailed guide to position lifecycle and P&L calculation