Back to search
dr-manhattan
SkillWorks with Claude CodeGitHub
Trade prediction markets (Polymarket, Kalshi, Opinion, Limitless, Predict.fun) using a unified CCXT-style API. Use when the user wants to browse, search, or trade prediction markets, check balances and positions, manage orders, run market-making strategies, or compare prices across exchanges.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Checked today
Badge for your README
Markdown
[](/listings/guzus--dr-manhattan)HTML
<a href="/listings/guzus--dr-manhattan"><img src="/api/listings/guzus--dr-manhattan/badge.svg" alt="findsafeskills safety rating" /></a>Install
i
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
uv venv uv pip install -e .
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 195 lines
- ---
- name: dr-manhattan
- description: Trade prediction markets (Polymarket, Kalshi, Opinion, Limitless, Predict.fun) using a unified CCXT-style API. Use when the user wants to browse, search, or trade prediction markets, check balances and positions, manage orders, run market-making strategies, or compare prices across exchanges.
- license: Apache-2.0
- compatibility: Requires Python >= 3.11 and uv. Requires network access for exchange APIs. Optionally requires exchange credentials (private keys, API keys) for trading.
- metadata:
- author: guzus
- version: "1.0"
- ---
- # Dr. Manhattan - Prediction Market Trading
- Dr. Manhattan is a unified API for prediction markets, similar to how CCXT works for cryptocurrency exchanges. It supports Polymarket, Kalshi, Opinion, Limitless, and Predict.fun through a single interface.
- ## Setup
- Install dependencies with uv:
- ```bash
- uv venv && uv pip install -e .
- ```
- For MCP server (Claude integration):
- ```bash
- uv sync --extra mcp
- ```
- ## Supported Exchanges
- | Exchange | Chain/Type | Auth |
- |------------- |--------------- |------------------------------------------ |
- | Polymarket | Polygon | Private key + funder address |
- | Kalshi | Regulated CEX | API key + RSA private key |
- | Opinion | BNB Chain | API key + private key + multi-sig address |
- | Limitless | Base | Private key |
- | Predict.fun | BNB Chain | API key + private key (EOA or smart wallet) |
- ## Usage as a Python Library
- ### Read-Only (No Credentials)
- ```python
- import dr_manhattan
- polymarket = dr_manhattan.Polymarket({'timeout': 30})
- markets = polymarket.fetch_markets()
- for market in markets:
- print(f"{market.question}: {market.prices}")
- ```
- ### With Authentication
- ```python
- import dr_manhattan
- polymarket = dr_manhattan.Polymarket({
- 'private_key': '0x...',
- 'funder': '0x...',
- })
- 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'}
- )
- ```
- ### Exchange Factory
- ```python
- from dr_manhattan import create_exchange, list_exchanges
- print(list_exchanges()) # ['polymarket', 'opinion', 'limitless', 'predictfun', 'kalshi']
- exchange = create_exchange('polymarket', {'timeout': 30})
- ```
- ## Usage via MCP Server
- Dr. Manhattan exposes all trading capabilities as MCP tools. Configure in Claude Code (`~/.claude/settings.json` or `.mcp.json`):
- ```json
- {
- "mcpServers": {
- "dr-manhattan": {
- "command": "/path/to/dr-manhattan/.venv/bin/python",
- "args": ["-m", "dr_manhattan.mcp.server"],
- "cwd": "/path/to/dr-manhattan"
- }
- }
- }
- ```
- ### MCP Tools Reference
- **Exchange Tools:**
- - `list_exchanges` - List all available prediction market exchanges.
- - `get_exchange_info(exchange)` - Get metadata and capabilities for an exchange.
- - `validate_credentials(exchange)` - Check if credentials are valid without trading.
- **Market Discovery:**
- - `search_markets(exchange, query)` - Search markets by keyword. This is the fastest way to find markets about a topic.
- - `fetch_markets(exchange, limit?, offset?)` - Fetch all markets with pagination.
- - `fetch_market(exchange, market_id)` - Fetch a specific market by ID.
- - `fetch_markets_by_slug(exchange, slug)` - Fetch markets by slug or URL (Polymarket, Limitless).
- - `find_tradeable_market(exchange, binary?, limit?, min_liquidity?)` - Find a suitable market for trading.
- - `find_crypto_hourly_market(exchange, token_symbol?)` - Find crypto hourly price markets (Polymarket).
- - `fetch_token_ids(exchange, market_id)` - Get token IDs for a market.
- - `parse_market_identifier(identifier)` - Extract slug from a Polymarket URL.
- - `get_tag_by_slug(slug)` - Get Polymarket tag information.
- **Orderbook:**
- - `get_orderbook(exchange, token_id)` - Get full orderbook (bids and asks).
- - `get_best_bid_ask(exchange, token_id)` - Get best bid and ask prices.
- **Trading:**
- - `create_order(exchange, market_id, outcome, side, price, size)` - Place a buy or sell order. Price is 0-1 (probability). Side is "buy" or "sell".
- - `cancel_order(exchange, order_id, market_id?)` - Cancel a specific order.
- - `cancel_all_orders(exchange, market_id?)` - Cancel all open orders.
- - `fetch_order(exchange, order_id, market_id?)` - Get order details and fill status.
- - `fetch_open_orders(exchange, market_id?)` - List all open orders.
- **Account:**
- - `fetch_balance(exchange)` - Get account balance (USDC).
- - `fetch_positions(exchange, market_id?)` - Get current positions with PnL.
- - `fetch_positions_for_market(exchange, market_id)` - Get positions for a specific market.
- - `calculate_nav(exchange, market_id?)` - Calculate net asset value (cash + positions).
- **Strategy Management:**
- - `create_strategy_session(strategy_type, exchange, market_id, ...)` - Start a market-making strategy in the background.
- - `get_strategy_status(session_id)` - Get real-time strategy status (NAV, positions, delta).
- - `get_strategy_metrics(session_id)` - Get performance metrics (uptime, fills).
- - `pause_strategy(session_id)` - Pause a running strategy.
- - `resume_strategy(session_id)` - Resume a paused strategy.
- - `stop_strategy(session_id, cleanup?)` - Stop a strategy and optionally cancel orders.
- - `list_strategy_sessions` - List all active strategy sessions.
- ## Common Workflows
- ### Find and Analyze a Market
- 1. Use `search_markets` with a keyword to find relevant markets.
- 2. Pick a market from the results and note its `id` and `metadata.clobTokenIds`.
- 3. Use `get_orderbook` with a token ID to see current bids and asks.
- 4. Use `get_best_bid_ask` for a quick spread check.
- ### Place a Trade
- 1. Find the market using `search_markets` or `fetch_markets_by_slug`.
- 2. Check `fetch_balance` to confirm available funds.
- 3. Get the orderbook with `get_orderbook` to see current prices.
- 4. Use `create_order` with the market ID, outcome ("Yes" or "No"), side ("buy" or "sell"), price (0-1), and size.
- 5. Monitor with `fetch_order` or `fetch_open_orders`.
- ### Run a Market-Making Strategy
- 1. Find a market with `search_markets` or `find_tradeable_market`.
- 2. Start with `create_strategy_session(strategy_type="market_making", exchange, market_id)`.
- 3. Monitor with `get_strategy_status` and `get_strategy_metrics`.
- 4. Control with `pause_strategy`, `resume_strategy`, or `stop_strategy`.
- ### Check Portfolio
- 1. `fetch_balance` to see cash.
- 2. `fetch_positions` to see all open positions with unrealized PnL.
- 3. `calculate_nav` for total portfolio value (cash + positions).
- ## Key Concepts
- - **Prices are probabilities** ranging from 0 to 1 (exclusive). A price of 0.65 means the market implies a 65% chance.
- - **Outcomes** are typically "Yes" and "No" for binary markets. Their prices sum to approximately 1.
- - **Token IDs** are exchange-specific identifiers for each outcome of a market. Needed for orderbook queries.
- - **Slugs** are human-readable URL identifiers (e.g., "trump-2024") used by Polymarket and Limitless.
- - **Order types** supported: GTC (Good-Til-Cancel), FOK (Fill-Or-Kill), IOC (Immediate-Or-Cancel).
- ## Running Examples
- ```bash
- uv run python examples/list_all_markets.py polymarket
- uv run python examples/spread_strategy.py --exchange polymarket --slug fed-decision
- uv run python examples/spike_strategy.py -e opinion -m 813 --spike-threshold 0.02
- ```
- ## Data Models
- **Market** fields: `id`, `question`, `outcomes`, `prices`, `volume`, `liquidity`, `close_time`, `tick_size`, `description`, `metadata` (contains `slug`, `clobTokenIds`).
- **Order** fields: `id`, `market_id`, `outcome`, `side` (BUY/SELL), `price`, `size`, `filled`, `status` (PENDING/OPEN/FILLED/CANCELLED), `time_in_force`.
- **Position** fields: `market_id`, `outcome`, `size`, `average_price`, `current_price`. Properties: `cost_basis`, `current_value`, `unrealized_pnl`.
- **Orderbook** fields: `bids` (price, size descending), `asks` (price, size ascending). Properties: `best_bid`, `best_ask`, `mid_price`, `spread`.
README.md · README · 389 lines
- # dr-manhattan
- CCXT-style unified API for prediction markets. Simple, scalable, and easy to extend.
- [](https://deepwiki.com/guzus/dr-manhattan)
- <p align="center">
- <img src="assets/polymarket.png" alt="Polymarket" width="50"/>
- <img src="assets/kalshi.jpeg" alt="Kalshi" width="50"/>
- <img src="assets/opinion.jpg" alt="Opinion" width="50"/>
- <img src="assets/limitless.jpg" alt="Limitless" width="50"/>
- <img src="assets/predict_fun.jpg" alt="Predict.fun" width="50"/>
- </p>
- ## Architecture
- `dr-manhattan` provides a unified interface to interact with multiple prediction market platforms, similar to how CCXT works for cryptocurrency exchanges.
- ### Core Components
- ```
- 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/ # Polymarket (mixin-based package) → [detailed docs](dr_manhattan/exchanges/polymarket/README.md)
- │ │ ├── __init__.py # Unified Polymarket class
- │ │ ├── polymarket_core.py # Constants, init, request helpers
- │ │ ├── polymarket_clob.py # CLOB API (orders, positions)
- │ │ ├── polymarket_gamma.py # Gamma API (markets, events, search)
- │ │ ├── polymarket_data.py # Data API (trades, analytics)
- │ │ ├── polymarket_ctf.py # CTF (split/merge/redeem)
- │ │ ├── polymarket_ws.py # Market/User WebSocket
- │ │ ├── polymarket_ws_ext.py # Sports/RTDS WebSocket
- │ │ ├── polymarket_builder.py # Builder API
- │ │ └── polymarket_operator.py # Operator API
- │ ├── 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
- 1. **Unified Interface**: All exchanges implement the same `Exchange` base class
- 2. **Scalability**: Adding new exchanges is straightforward - just implement the abstract methods
- 3. **Simplicity**: Clean abstractions with minimal dependencies
- 4. **Type Safety**: Full type hints throughout
- ### Key Features
- - Fetch markets and market data
- - Create and cancel orders
- - Query positions and balances
- - WebSocket support for real-time data
- - Strategy base class for building trading strategies
- - Order tracking and event logging
- - Standardized error handling
- - Exchange-agnostic code
- - **MCP server for Claude Desktop integration**
- ## Installation
- ```bash
- uv venv
- uv pip install -e .
- ```
- ## Usage
- ### Basic Usage (Public API)
- ```python
- import dr_manhattan
- # Initialize exchange without authentication
- polymarket = dr_manhattan.Polymarket({'timeout': 30})
- opinion = dr_manhattan.Opinion({'timeout': 30})
- limitless = dr_manhattan.Limitless({'timeout': 30})
- predictfun = dr_manhattan.PredictFun({'timeout': 30})
- kalshi = dr_manhattan.Kalshi({'timeout': 30})
- # Fetch markets
- markets = polymarket.fetch_markets()
- for market in markets:
- print(f"{market.question}: {market.prices}")
- ```
- ### Advanced Usage (With Authentication)
- ```python
- import dr_manhattan
- # Polymarket
- polymarket = dr_manhattan.Polymarket({
- 'private_key': 'your_private_key',
- 'funder': 'your_funder_address',
- })
- # Opinion (BNB Chain)
- opinion = dr_manhattan.Opinion({
- 'api_key': 'your_api_key',
- 'private_key': 'your_private_key',
- 'multi_sig_addr': 'your_multi_sig_addr'
- })
- # Limitless
- limitless = dr_manhattan.Limitless({
- 'private_key': 'your_private_key',
- 'timeout': 30
- })
- # Predict.fun (BNB Chain)
- 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'
- })
- # Create 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'}
- )
- # Fetch balance
- balance = polymarket.fetch_balance()
- print(f"USDC: {balance['USDC']}")
- ```
- ### Using the Strategy Base Class
- ```python
- from dr_manhattan import Strategy
- class MyStrategy(Strategy):
- def on_tick(self):
- self.log_status()
- self.place_bbo_orders()
- strategy = MyStrategy(exchange, market_id="123")
- strategy.run()
- ```
- ### Exchange Factory
- ```python
- from dr_manhattan import create_exchange, list_exchanges
- # List available exchanges
- print(list_exchanges()) # ['polymarket', 'opinion', 'limitless', 'predictfun', 'kalshi']
- # Create exchange by name using environment credentials
- exchange = create_exchange('polymarket')
- # Read-only instance without requiring credentials
- public_exchange = create_exchange('polymarket', validate=False)
- ```
- Use `predictfun` with `create_exchange()` and CLI examples. The low-level `PredictFun.id` property is `predict.fun`, matching the venue name, but the factory key is `predictfun`.
- ### MCP Server
- Trade prediction markets directly from Claude using the Model Context Protocol (MCP).
- ```bash
- # Install with MCP dependencies
- uv sync --extra mcp
- # Configure credentials
- cp .env.example .env
- # Edit .env with your POLYMARKET_PRIVATE_KEY and POLYMARKET_FUNDER
- ```
- #### Claude Code
- Add to `~/.claude/settings.json` or project `.mcp.json`:
- ```json
- {
- "mcpServers": {
- "dr-manhattan": {
- "command": "/path/to/dr-manhattan/.venv/bin/python",
- "args": ["-m", "dr_manhattan.mcp.server"],
- "cwd": "/path/to/dr-manhattan"
- }
- }
- }
- ```
- Restart Claude Code and verify with `/mcp`.
- #### Claude Desktop
- Add to Claude Desktop config (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):
- ```json
- {
- "mcpServers": {
- "dr-manhattan": {
- "command": "/path/to/dr-manhattan/.venv/bin/python",
- "args": ["-m", "dr_manhattan.mcp.server"],
- "cwd": "/path/to/dr-manhattan"
- }
- }
- }
- ```
- #### Remote Server (No Installation Required)
- Connect to the hosted MCP server via SSE. No private keys needed - uses Polymarket Builder profile:
- ```json
- {
- "mcpServers": {
- "dr-manhattan": {
- "type": "sse",
- "url": "https://dr-manhattan-mcp-production.up.railway.app/sse",
- "headers": {
- "X-Polymarket-Api-Key": "your_api_key",
- "X-Polymarket-Api-Secret": "your_api_secret",
- "X-Polymarket-Passphrase": "your_passphrase"
- }
- }
- }
- }
- ```
- **Note:** Remote server supports Polymarket trading only. Other exchanges are read-only for security. See [wiki/mcp/remote-server.md](wiki/mcp/remote-server.md) for details.
- After restarting, you can:
- - "Show my Polymarket balance"
- - "Find active prediction markets"
- - "Buy 10 USDC of Yes on market X at 0.55"
- See [examples/mcp_usage_example.md](examples/mcp_usage_example.md) for the complete setup guide.
- ## Adding New Exchanges
- To add a new exchange, create a class that inherits from `Exchange`:
- ```python
- from dr_manhattan.base import Exchange
- class NewExchange(Exchange):
- @property
- def id(self) -> str:
- return "newexchange"
- @property
- def name(self) -> str:
- return "New Exchange"
- def fetch_markets(self, params=None):
- # Implement API call
- pass
- # Implement other abstract methods...
- ```
- Register in `dr_manhattan/__init__.py`:
- ```python
- from .exchanges.newexchange import NewExchange
- exchanges = {
- "polymarket": Polymarket,
- "opinion": Opinion,
- "limitless": Limitless,
- "predictfun": PredictFun,
- "kalshi": Kalshi,
- "newexchange": NewExchange,
- }
- ```
- ## Data Models
- ### Market
- - Question and outcomes
- - Prices and volume
- - Close time and status
- ### Order
- - Market and outcome
- - Side (buy/sell), price, size
- - Status tracking
- ### Position
- - Current holdings
- - PnL calculation
- - Average entry price
- ### OrderBook
- - Bids and asks
- - Best bid/ask prices
- ## Error Handling
- All errors inherit from `DrManhattanError`:
- - `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
- ## Examples
- Check out the [examples/](examples/) directory for working examples:
- - **mcp_usage_example.md** - Complete MCP server setup and usage guide for Claude Desktop
- - **list_all_markets.py** - List markets from any exchange
- - **spread_strategy.py** - Exchange-agnostic BBO market making strategy
- Run examples:
- ```bash
- # List markets
- uv run python examples/list_all_markets.py polymarket
- uv run python examples/list_all_markets.py opinion
- uv run python examples/list_all_markets.py limitless
- uv run python examples/list_all_markets.py predictfun
- uv run python examples/list_all_markets.py kalshi
- # Run spread strategy
- uv run python examples/spread_strategy.py --exchange polymarket --slug fed-decision
- uv run python examples/spread_strategy.py --exchange opinion --market-id 813
- ```
- See [examples/README.md](examples/README.md) for detailed documentation.
- ## Contributing with Claude
- <p align="center">
- <img src="assets/claude.png" alt="Claude" width="100"/>
- </p>
- We use Claude Code to implement new features from trading strategy ideas:
- 1. Spot a good strategy on Twitter/X
- 2. Create a GitHub issue describing the strategy
- 3. Add a label: `feature`, `bug`, or `chore`
- 4. Mention `@claude` in the issue
- 5. Claude creates a PR with the implementation
- Branch naming follows the label:
- - `feature` -> `feat/issue-{number}`
- - `bug` -> `fix/issue-{number}`
- - `chore` -> `chore/issue-{number}`
- See [.github/workflows/claude.yml](.github/workflows/claude.yml) for details.
- ## Dependencies
- - Python >= 3.11
- - requests >= 2.31.0
- - websockets >= 15.0.1
- - python-socketio >= 5.11.0
- - eth-account >= 0.11.0
- - py-clob-client >= 0.28.0
- - opinion-clob-sdk >= 0.4.3
- - pandas >= 2.0.0
- Development:
- - pytest
- - black
- - ruff
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.