Skip to main content
Glama
kalshi-trading-mcp

kalshi-trading-mcp

README.md
# kalshi-trading-mcp

A full-featured [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server for [Kalshi](https://kalshi.com) prediction markets. Includes 20+ tools for account management, market analysis, order execution, multi-source weather forecasting, ensemble model analysis, real-time METAR observations, and position drift monitoring.

## Why This Server?

Most existing Kalshi MCP servers are thin API wrappers (5-10 tools). This one is different:

- **Multi-source weather forecasting** — NWS, HRRR, GFS, ECMWF, Open-Meteo, and more
- **Probability analysis** — Bucket math, edge calculation, maker fee impact
- **Safety controls** — Price caps, daily limits, cash reserve, NO-only strategy
- **Position management** — Drift analysis, METAR trend tracking, early exit signals
- **Cross-city intelligence** — Correlated forecast errors, AFD change detection

## Quick Start

### Install

```bash
pip install kalshi-trading-mcp
```

Or install from source:

```bash
git clone https://github.com/alexandermazza/kalshi-trading-mcp.git
cd kalshi-trading-mcp
pip install -e .
```

### Configure

1. Get your API credentials from [Kalshi Settings](https://kalshi.com/settings/api)

2. Create a `.env` file (or set environment variables):

```bash
KALSHI_API_KEY_ID=your-key-id
KALSHI_PRIVATE_KEY_PATH=/path/to/your/private_key.pem
KALSHI_ENV=demo  # or 'prod' for real trading
```

### Use with Claude Code

Add to your `.mcp.json` (or `~/.claude/mcp.json` for global):

```json
{
  "mcpServers": {
    "kalshi": {
      "type": "stdio",
      "command": "kalshi-mcp",
      "env": {
        "KALSHI_API_KEY_ID": "your-key-id",
        "KALSHI_PRIVATE_KEY_PATH": "/path/to/private_key.pem",
        "KALSHI_ENV": "prod"
      }
    }
  }
}
```

Then ask Claude things like:
- "What's my Kalshi balance?"
- "Scan for weather trading opportunities"
- "Analyze the NYC high temp market for tomorrow"
- "Show me the ensemble forecast for Chicago"

### Use with Claude Desktop

Add to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "kalshi": {
      "command": "kalshi-mcp",
      "env": {
        "KALSHI_API_KEY_ID": "your-key-id",
        "KALSHI_PRIVATE_KEY_PATH": "/path/to/private_key.pem",
        "KALSHI_ENV": "prod"
      }
    }
  }
}
```

## Tools Reference

### Account & Positions

| Tool | Description |
|------|-------------|
| `kalshi_balance` | Get cash balance, portfolio value, environment |
| `kalshi_positions` | List open positions with exposure |

### Markets

| Tool | Description |
|------|-------------|
| `kalshi_markets` | List markets with optional filtering by series/status |
| `kalshi_market` | Get single market details including orderbook |
| `kalshi_cities` | List supported weather cities with coordinates |

### Weather Forecasting

| Tool | Description |
|------|-------------|
| `kalshi_forecast` | Get weather forecast for a city/date |
| `kalshi_ensemble_forecast` | Multi-model data (HRRR, GFS, ECMWF) with spread analysis |
| `kalshi_analyze_opportunity` | Compare forecast vs market price — edge, probability, recommendation |
| `kalshi_scan_opportunities` | Scan all cities for trading opportunities |

### Weather Signals

| Tool | Description |
|------|-------------|
| `kalshi_forecast_timing` | Check NWS/GFS update freshness for timing optimization |
| `kalshi_metar_current` | Get current airport observations (temperature, wind, visibility) |
| `kalshi_metar_trend` | Track temperature trajectory for same-day positions |
| `kalshi_cross_city_signal` | Check correlated city forecast errors |
| `kalshi_afd_change_detection` | Detect Area Forecast Discussion guidance shifts |

### Orders (Two-Step Confirmation)

| Tool | Description |
|------|-------------|
| `kalshi_prepare_order` | Prepare order for review (returns confirmation_id) |
| `kalshi_confirm_order` | Execute or cancel a prepared order |
| `kalshi_cancel_order` | Cancel a resting order |
| `kalshi_resting_orders` | List unfilled orders with age/stale detection |
| `kalshi_reevaluate_resting_orders` | Re-analyze resting orders for edge degradation |

### Position Recovery

| Tool | Description |
|------|-------------|
| `kalshi_position_drift_analysis` | Analyze forecast drift for early exit decisions |

## Configuration

All settings are configurable via environment variables:

### Required

| Variable | Description |
|----------|-------------|
| `KALSHI_API_KEY_ID` | Your Kalshi API key ID |
| `KALSHI_PRIVATE_KEY_PATH` | Path to your RSA private key (.pem) |
| `KALSHI_ENV` | `demo` or `prod` (default: `demo`) |

### Safety Limits

| Variable | Default | Description |
|----------|---------|-------------|
| `MCP_MAX_ORDER_SIZE` | `20.0` | Max cost per order ($) |
| `MCP_DAILY_LIMIT` | `500.0` | Max daily trading volume ($) |
| `MCP_MAX_CONTRACTS` | `15` | Max contracts per order |
| `CASH_RESERVE` | `20.0` | Minimum cash to keep in account ($) |
| `MAX_NO_PRICE` | `65` | Max NO price in cents (payoff protection) |
| `NO_ONLY_STRATEGY` | `true` | Only allow NO-side weather trades |
| `DISABLED_CITIES` | *(empty)* | Comma-separated city codes to skip (e.g., `AUS,MIA`) |

### Weather Analysis

| Variable | Default | Description |
|----------|---------|-------------|
| `WEATHER_MIN_EDGE` | `0.10` | Minimum edge to recommend a trade |
| `WEATHER_MAX_EDGE` | `0.18` | Max edge (higher = edge paradox warning) |
| `DAMPENING_THRESHOLD` | `0.18` | Dampen edges above this |
| `DAMPENING_FACTOR` | `0.50` | How much to dampen (0.5 = halve excess) |
| `CITY_STD_DEV_NYC` | `5.2` | Override NYC forecast std dev |
| `CITY_STD_DEV_CHI` | `6.6` | Override CHI forecast std dev |
| `CITY_STD_DEV_DEN` | `8.5` | Override DEN forecast std dev |

### Optional API Keys (Improves Forecast Accuracy)

| Variable | Description |
|----------|-------------|
| `OPENWEATHER_API_KEY` | [OpenWeather](https://openweathermap.org/api) |
| `WEATHERAPI_KEY` | [WeatherAPI](https://www.weatherapi.com/) |
| `TOMORROWIO_API_KEY` | [Tomorrow.io](https://www.tomorrow.io/) |
| `VISUAL_CROSSING_API_KEY` | [Visual Crossing](https://www.visualcrossing.com/) |

The server works without these keys (NWS is free and always available), but adding more sources improves forecast accuracy through ensemble averaging.

## Architecture

```
kalshi_trading_mcp/
├── server.py              # FastMCP instance + lazy-loaded singletons
├── config.py              # Env-based configuration
├── safety.py              # Trade safety controls + audit logging
├── client/                # Kalshi REST API client
│   ├── client.py          # API wrapper with dataclass models
│   └── auth.py            # RSA signature authentication
├── tools/                 # MCP tool definitions (20+ tools)
│   ├── account.py         # Balance, positions
│   ├── markets.py         # Market listing, details
│   ├── orders.py          # Order flow + edge re-evaluation
│   ├── weather.py         # Forecasts, analysis, scanning
│   ├── weather_signals.py # METAR, timing, cross-city, AFD
│   └── position_recovery.py  # Drift analysis
├── forecasting/           # Weather data integration
│   ├── multisource.py     # Multi-source forecast aggregation
│   ├── nbm.py             # National Blend of Models
│   ├── metar.py           # Airport observations
│   └── cities.py          # City configs + correlations
├── analysis/              # Pure computation
│   ├── probability.py     # CDF, edge, fee math
│   ├── ticker_parser.py   # Kalshi ticker parsing
│   └── timing.py          # Optimal trading windows
└── logging/
    └── trade_log.py       # JSONL audit trail
```

## Supported Cities

| Code | City | High Series | Low Series |
|------|------|-------------|------------|
| NYC | New York | KXHIGHNY | KXLOWTNY |
| CHI | Chicago | KXHIGHCH | KXLOWTCH |
| MIA | Miami | KXHIGHMI | KXLOWTMI |
| AUS | Austin | KXHIGHAT | KXLOWTAT |
| HOU | Houston | KXHIGHHO | KXLOWTHO |
| LAX | Los Angeles | KXHIGHLA | KXLOWTLA |
| DEN | Denver | KXHIGHDE | KXLOWTDE |
| PHL | Philadelphia | KXHIGHPH | KXLOWTPH |

## Dependencies

Only 4 core dependencies:

- `fastmcp>=2.0.0` — MCP protocol framework
- `requests>=2.31.0` — HTTP client for APIs
- `cryptography>=41.0.0` — RSA signature auth
- `python-dotenv>=1.0.0` — .env file support

## License

MIT — see [LICENSE](LICENSE) for details.