Documentation

dr-manhattan is a CCXT-style unified API for prediction markets. It provides a simple, scalable, and extensible interface to interact with multiple prediction market platforms.

Unified Interface

One API for all prediction markets. Write once, deploy anywhere.

Real-time Data

WebSocket support for live orderbook and trade updates.

Type Safe

Full type hints throughout for better IDE support.

Installation

Install dr-manhattan using uv (recommended):

terminal
# Create virtual environment and install
uv venv
uv pip install -e .

# Or install directly from GitHub
uv pip install -e git+https://github.com/guzus/dr-manhattan

Note: dr-manhattan requires Python 3.11 or higher.

Quick Start

Here's a simple example to get you started:

example.py
import dr_manhattan

# Initialize any exchange
polymarket = dr_manhattan.Polymarket({'timeout': 30})
opinion = dr_manhattan.Opinion({'timeout': 30})
limitless = dr_manhattan.Limitless({'timeout': 30})
predictfun = dr_manhattan.PredictFun({'timeout': 30})

# Fetch markets
markets = polymarket.fetch_markets()

for market in markets:
    print(f"{market.question}: {market.prices}")

API Reference

All exchanges implement the same base interface, making it easy to switch between platforms or build cross-exchange applications.

Exchange Factory

Use the exchange factory to dynamically create exchange instances:

factory.py
from dr_manhattan import create_exchange, list_exchanges

# List available exchanges
print(list_exchanges())
# ['polymarket', 'kalshi', 'limitless', 'opinion', 'predictfun']

# Create exchange by name
exchange = create_exchange('polymarket', {'timeout': 30})

Markets

Fetch and query prediction markets:

Method Description
fetch_markets() Fetch all available markets
fetch_market(market_id) Fetch a specific market by ID
fetch_orderbook(market_id) Get the orderbook for a market

Market Model

models/market.py
class Market:
    id: str              # Unique market identifier
    question: str        # Market question
    outcomes: list       # Available outcomes (e.g., ["Yes", "No"])
    prices: dict         # Current prices for each outcome
    volume: float        # Total trading volume
    close_time: datetime # When the market closes
    status: str          # Market status (open, closed, resolved)

Orders

Create and manage orders:

trading.py
import dr_manhattan

# Initialize with authentication
polymarket = dr_manhattan.Polymarket({
    'private_key': 'your_private_key',
    'funder': 'your_funder_address',
})

# Create a buy order
order = polymarket.create_order(
    market_id="market_123",
    outcome="Yes",
    side=dr_manhattan.OrderSide.BUY,
    price=0.65,
    size=100,
    params={'token_id': 'token_id'}
)

# Cancel an order
polymarket.cancel_order(order.id)

Positions

Track your positions and balances:

positions.py
# Fetch balance
balance = polymarket.fetch_balance()
print(f"USDC: {balance['USDC']}")

# Fetch positions
positions = polymarket.fetch_positions()
for pos in positions:
    print(f"{pos.market_id}: {pos.size} @ {pos.avg_price}")

WebSockets

Subscribe to real-time market data:

websocket.py
import asyncio
from dr_manhattan import PolymarketWS

async def main():
    ws = PolymarketWS()

    async def on_orderbook(data):
        print(f"Orderbook update: {data}")

    await ws.subscribe_orderbook("market_id", on_orderbook)
    await ws.run()

asyncio.run(main())

Supported Exchanges

dr-manhattan supports the following prediction market exchanges:

Polymarket

Polymarket is the leading prediction market on Polygon. It uses USDC for trading and requires a wallet for authentication.

polymarket_example.py
import dr_manhattan

polymarket = dr_manhattan.Polymarket({
    'private_key': 'your_private_key',
    'funder': 'your_funder_address',
})

# Fetch active markets
markets = polymarket.fetch_markets()

Kalshi

Kalshi is a US-regulated prediction market exchange. It uses RSA-PSS authentication.

kalshi_example.py
import dr_manhattan

kalshi = dr_manhattan.Kalshi({
    'api_key': 'your_api_key',
    'private_key_path': '/path/to/private_key.pem',
})

Opinion

Opinion is a prediction market on BNB Chain.

opinion_example.py
import dr_manhattan

opinion = dr_manhattan.Opinion({
    'api_key': 'your_api_key',
    'private_key': 'your_private_key',
    'multi_sig_addr': 'your_multi_sig_addr'
})

Limitless

Limitless is a prediction market platform with WebSocket support.

limitless_example.py
import dr_manhattan

limitless = dr_manhattan.Limitless({
    'private_key': 'your_private_key',
    'timeout': 30
})

Predict.fun

Predict.fun is a prediction market on BNB Chain with smart wallet support.

predictfun_example.py
import dr_manhattan

predictfun = dr_manhattan.PredictFun({
    'api_key': 'your_api_key',
    'private_key': 'your_private_key',
    'use_smart_wallet': True,
    'smart_wallet_owner_private_key': 'your_owner_private_key',
    'smart_wallet_address': 'your_smart_wallet_address'
})

Strategy Framework

dr-manhattan provides a base class for building trading strategies with order tracking, position management, and event logging.

my_strategy.py
from dr_manhattan import Strategy

class MyStrategy(Strategy):
    def on_tick(self):
        self.log_status()
        self.place_bbo_orders()

# Run the strategy
strategy = MyStrategy(exchange, market_id="123")
strategy.run()

Spread Strategy

The spread strategy implements BBO (Best Bid/Offer) market making. It places orders at the best bid and ask prices with a configurable spread.

terminal
uv run python examples/spread_strategy.py --exchange polymarket --slug fed-decision
uv run python examples/spread_strategy.py --exchange opinion --market-id 813

Spike Strategy

The spike strategy implements mean reversion trading. It detects price spikes and places counter-trend orders.

Architecture

dr-manhattan follows a clean, modular architecture:

structure
dr_manhattan/
├── base/               # Core abstractions
│   ├── exchange.py     # Abstract base class for exchanges
│   ├── exchange_client.py  # High-level trading client
│   ├── exchange_factory.py # Exchange instantiation
│   ├── strategy.py     # Strategy base class
│   ├── order_tracker.py    # Order event tracking
│   ├── websocket.py    # WebSocket base class
│   └── errors.py       # Exception hierarchy
├── exchanges/          # Exchange implementations
│   ├── polymarket.py
│   ├── polymarket_ws.py
│   ├── kalshi.py
│   ├── opinion.py
│   ├── limitless.py
│   ├── limitless_ws.py
│   ├── predictfun.py
│   └── predictfun_ws.py
├── models/             # Data models
│   ├── market.py
│   ├── order.py
│   ├── orderbook.py
│   └── position.py
├── strategies/         # Strategy implementations
└── utils/              # Utilities

Design Principles

  • Unified Interface: All exchanges implement the same Exchange base class
  • Scalability: Adding new exchanges is straightforward - just implement the abstract methods
  • Simplicity: Clean abstractions with minimal dependencies
  • Type Safety: Full type hints throughout the codebase

Error Handling

All errors inherit from DrManhattanError:

Error Description
ExchangeError Exchange-specific errors
NetworkError Connectivity issues
RateLimitError Rate limit exceeded
AuthenticationError Auth failures
InsufficientFunds Not enough balance
InvalidOrder Invalid order parameters
MarketNotFound Market doesn't exist

MCP Server

Trade prediction markets directly from Claude using the Model Context Protocol (MCP).

terminal
# Install with MCP dependencies
uv sync --extra mcp

# Configure credentials
cp .env.example .env
# Edit .env with your POLYMARKET_PRIVATE_KEY and POLYMARKET_FUNDER

Add to your Claude Code settings (~/.claude/settings.json or project .mcp.json):

settings.json
{
  "mcpServers": {
    "dr-manhattan": {
      "command": "/path/to/dr-manhattan/.venv/bin/python",
      "args": ["-m", "dr_manhattan.mcp.server"],
      "cwd": "/path/to/dr-manhattan"
    }
  }
}

After restarting, you can:

  • "Show my Polymarket balance"
  • "Find active prediction markets"
  • "Buy 10 USDC of Yes on market X at 0.55"