Skip to content

Erebuzzz/alpha-sim

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Realistic Paper Trading MCP Server

Production-grade MCP server for realistic paper trading simulation. Accurately models real-world market conditions including slippage, latency, fees, and partial fills to help validate trading strategies before live deployment.

Features

🎯 Core Engines

  • Market Data Engine: Multi-provider support (Polygon, Finnhub, Alpaca, Tiingo)

    • Real-time quotes and orderbook data
    • WebSocket streaming for live updates
    • Historical OHLCV candles
    • Automatic failover and caching
  • Execution Engine: Realistic order simulation

    • Volume & volatility-based slippage model
    • Network latency simulation (20ms base + jitter + stress conditions)
    • Maker/taker fee structure
    • 7 order types: market, limit, stop, stop-limit, trailing-stop, IOC, FOK
    • Partial fills based on orderbook liquidity
  • Portfolio Engine: Complete risk management

    • Real-time position tracking with FIFO cost basis
    • Realized & unrealized P&L calculation
    • Margin requirements (initial/maintenance)
    • Pre-trade risk checks (position size, allocation, daily loss, exposure)
    • Configurable leverage up to 2x

🔧 MCP Tools

  • getMarketData - Real-time quotes with bid/ask/last
  • getOrderbook - Level-2 market depth
  • getHistoricalCandles - OHLCV historical data
  • submitOrder - Place orders with automatic risk validation
  • modifyOrder - Modify price or quantity
  • cancelOrder - Cancel pending orders
  • simulateExecution - Dry-run to preview slippage and fees
  • getPortfolio - View positions, cash, P&L
  • getRiskLimits - Check risk limits and usage

📊 MCP Resources

  • portfolio://current - Real-time portfolio state
  • risk://limits - Risk configuration and current usage

Quick Start

1. Installation

cd d:/alpha-sim
npm install

2. Configure API Credentials

Copy .env.example to .env and add your API keys:

cp .env.example .env

Edit .env and add at least one market data provider:

# Polygon (Recommended)
POLYGON_API_KEY=your_key_here

# OR Alpaca
ALPACA_API_KEY=your_key_here
ALPACA_API_SECRET=your_secret_here

Get API keys:

  • Polygon.io - Most comprehensive, free tier available
  • Alpaca - Free paper trading API
  • Finnhub - Free tier for quotes
  • Tiingo - Alternative data source

3. Run the Server

# Development mode with auto-reload
npm run dev

# Production build
npm run build
npm start

The server will start on http://localhost:3001.

4. Connect MCP Client

Add to your Claude Desktop config:

{
  "mcpServers": {
    "paper-trading": {
      "url": "http://localhost:3001"
    }
  }
}

Configuration

All configuration is managed via environment variables in .env:

Portfolio Settings

INITIAL_CASH=100000           # Starting capital
MAX_LEVERAGE=2                # Maximum leverage multiplier

Risk Limits

MAX_POSITION_SIZE=100000      # Max notional per symbol
MAX_SYMBOL_ALLOCATION=0.20    # Max 20% per symbol
MAX_DAILY_LOSS=5000           # Daily loss limit
MAX_TOTAL_EXPOSURE=200000     # Total portfolio exposure

Execution Simulation

BASE_LATENCY_MS=20            # Base execution latency
JITTER_MIN_MS=5               # Random jitter range
JITTER_MAX_MS=50
STRESS_LATENCY_MIN_MS=100     # High volatility latency
STRESS_LATENCY_MAX_MS=500

Fees

MAKER_FEE=0.0001              # 0.01% maker fee
TAKER_FEE=0.0003              # 0.03% taker fee

Usage Examples

Get Real-Time Quote

Use the getMarketData tool for AAPL

Response:

{
  "symbol": "AAPL",
  "timestamp": 1707648000000,
  "bid": 184.50,
  "ask": 184.52,
  "last": 184.51,
  "bidSize": 100,
  "askSize": 150
}

Submit a Market Order

Buy 100 shares of TSLA at market price

This will:

  1. Check risk limits automatically
  2. Calculate realistic slippage based on order size and volatility
  3. Apply maker/taker fees
  4. Update portfolio positions
  5. Return order status and fills

Simulate Order Before Placing

Simulate buying 500 shares of AAPL

Response shows expected fill price, slippage, and fees without actually placing the order.

Check Portfolio

Show me my current portfolio

Returns:

  • Cash balance
  • Buying power
  • All open positions
  • Realized & unrealized P&L
  • Daily P&L

Realism Models

Slippage Calculation

Slippage is calculated using:

slippage = (baseSlippage + volumeImpact + volatilityImpact) * orderTypeMultiplier

Where:

  • Base slippage: 1 basis point default
  • Volume impact: (orderSize / avgVolume) * 0.5
  • Volatility impact: ATR * 0.3
  • Order type multiplier: 1.5x for market orders, 1.0x for limit

Latency Simulation

Three components:

  • Base latency: 20ms (typical network round trip)
  • Random jitter: 5-50ms uniform distribution
  • Stress latency: 100-500ms when volatility > 3% (simulates exchange congestion)

Fee Structure

  • Maker fees: 0.01% (providing liquidity with limit orders)
  • Taker fees: 0.03% (taking liquidity with market orders)
  • Fees are calculated on notional value (quantity × price)

Project Structure

d:/alpha-sim/
├── src/
│   ├── market-data/          # Market data providers
│   │   ├── types.ts
│   │   ├── aggregator.ts
│   │   └── providers/
│   │       ├── polygon.ts
│   │       └── alpaca.ts
│   ├── execution/            # Order execution engine
│   │   ├── types.ts
│   │   ├── slippage-model.ts
│   │   ├── latency-simulator.ts
│   │   ├── fee-calculator.ts
│   │   ├── fill-logic.ts
│   │   └── order-manager.ts
│   ├── portfolio/            # Portfolio management
│   │   ├── types.ts
│   │   ├── position-tracker.ts
│   │   ├── margin-calculator.ts
│   │   ├── risk-manager.ts
│   │   └── portfolio-service.ts
│   ├── services/             # MCP services
│   │   ├── market-data-service.ts
│   │   ├── trading-service.ts
│   │   └── portfolio-service-mcp.ts
│   ├── config.ts
│   └── index.ts              # Main entry point
├── data/                     # Runtime data
│   ├── portfolio.json
│   ├── risk_limits.json
│   ├── fee_model.json
│   └── latency_profile.json
└── package.json

Development

Run Tests

npm test

Lint Code

npm run lint

Build for Production

npm run build

Deployment

Using LeanMCP Platform

leanmcp deploy

Using Docker

FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist ./dist
COPY data ./data
CMD ["node", "dist/index.js"]

Troubleshooting

No market data providers configured

Make sure you've set at least one API key in .env:

POLYGON_API_KEY=your_key_here

Order rejected by risk checks

Check your risk limits in .env or data/risk_limits.json. You may need to:

  • Increase MAX_POSITION_SIZE
  • Increase MAX_DAILY_LOSS
  • Reduce position sizes

WebSocket connection issues

Some providers may have WebSocket rate limits. The server will automatically fall back to REST API polling.

Limitations

  • Orderbook modeling: Most providers don't offer full Level-2 data, so orderbook is simplified
  • After-hours trading: Not currently simulated
  • Corporate actions: Splits, dividends not handled
  • Short selling: Supported but without borrow fees

Contributing

Contributions welcome! Please open an issue or PR.

License

MIT

Support

For issues or questions:


⚠️ Important: This is a paper trading simulator. Always test strategies thoroughly before deploying to live markets. Past performance does not guarantee future results.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors