Day 23: Paper Trading Engine

~5 min read

What I Built

  • PaperTradingEngine Class: Async order submission with market-like fills including 5bps slippage simulation
  • Position Tracking: Real-time position management with average price calculations and P&L tracking
  • PriceStreamManager: Real-time price update streams with callback system for dashboard integration
  • Order Execution Tests: Comprehensive test suite covering order fills, balance validation, and position tracking
  • Async Architecture: Non-blocking order processing with random latency simulation (0.5-2 seconds)

Code Highlight

class PaperTradingEngine:
    """Simulate order execution with market-like fills."""

    def __init__(self, initial_balance: float = 100000.0):
        self.balance = initial_balance
        self.positions: Dict[str, Dict] = {}  # {symbol: {quantity, avg_price}}
        self.orders: Dict[str, Order] = {}
        self.trades_executed = 0
        self.trade_log: List[Dict[str, Any]] = []
        self.slippage_bps = 5  # 0.05% slippage

    async def submit_order(self, symbol: str, action: str, price: float, quantity: int) -> str:
        """Submit order for execution."""
        order_id = f"{symbol}_{datetime.now(timezone.utc).timestamp()}"
        order = Order(
            symbol=symbol,
            action=action,
            entry_price=price,
            quantity=quantity,
            timestamp=datetime.now(timezone.utc)
        )
        self.orders[order_id] = order

        # Simulate async order processing (random fill time 0-5 seconds)
        asyncio.create_task(self._process_order(order_id))
        return order_id

Architecture Decision

Async Order Processing: Used asyncio.create_task() for non-blocking order execution rather than a thread pool. This ensures the event loop remains responsive for real-time price updates while simulating realistic market latency (0.5-2 seconds). The trade-off is complexity in test synchronization, but it provides accurate simulation of async broker APIs.

Slippage Simulation: Implemented 5bps (0.05%) slippage per side to simulate market impact. This creates realistic fill prices that differ from entry prices, preparing the system for live trading where perfect fills are rare. The model applies slippage consistently (long orders fill higher, short orders fill lower) to maintain directional bias.

Testing Results

All 4 unit tests pass, covering critical paper trading scenarios:

  • Order Submission: Validates async order creation and status tracking
  • Fill Simulation: Confirms slippage application and balance updates
  • Balance Validation: Ensures insufficient funds cancel orders appropriately
  • Position Tracking: Verifies correct position accumulation and average price calculations

Tests run in ~9 seconds with 100% pass rate, using pytest-asyncio for proper async handling.

Next Steps

Day 24: Trading Profile Integration - Connect the 3-profile system (Momentum Crossover, Volatility Expansion, Catalyst Hunter) to the paper trading engine for automated multi-profile trade execution across multiple symbols.


Follow @therealkamba on X for regular updates. View all posts →