Skip to content
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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/guzus--dr-manhattan/badge.svg)](/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
  1. ---
  2. name: dr-manhattan
  3. 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.
  4. license: Apache-2.0
  5. compatibility: Requires Python >= 3.11 and uv. Requires network access for exchange APIs. Optionally requires exchange credentials (private keys, API keys) for trading.
  6. metadata:
  7. author: guzus
  8. version: "1.0"
  9. ---
  10. # Dr. Manhattan - Prediction Market Trading
  11. 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.
  12. ## Setup
  13. Install dependencies with uv:
  14. ```bash
  15. uv venv && uv pip install -e .
  16. ```
  17. For MCP server (Claude integration):
  18. ```bash
  19. uv sync --extra mcp
  20. ```
  21. ## Supported Exchanges
  22. | Exchange | Chain/Type | Auth |
  23. |------------- |--------------- |------------------------------------------ |
  24. | Polymarket | Polygon | Private key + funder address |
  25. | Kalshi | Regulated CEX | API key + RSA private key |
  26. | Opinion | BNB Chain | API key + private key + multi-sig address |
  27. | Limitless | Base | Private key |
  28. | Predict.fun | BNB Chain | API key + private key (EOA or smart wallet) |
  29. ## Usage as a Python Library
  30. ### Read-Only (No Credentials)
  31. ```python
  32. import dr_manhattan
  33. polymarket = dr_manhattan.Polymarket({'timeout': 30})
  34. markets = polymarket.fetch_markets()
  35. for market in markets:
  36. print(f"{market.question}: {market.prices}")
  37. ```
  38. ### With Authentication
  39. ```python
  40. import dr_manhattan
  41. polymarket = dr_manhattan.Polymarket({
  42. 'private_key': '0x...',
  43. 'funder': '0x...',
  44. })
  45. order = polymarket.create_order(
  46. market_id="market_123",
  47. outcome="Yes",
  48. side=dr_manhattan.OrderSide.BUY,
  49. price=0.65,
  50. size=100,
  51. params={'token_id': 'token_id'}
  52. )
  53. ```
  54. ### Exchange Factory
  55. ```python
  56. from dr_manhattan import create_exchange, list_exchanges
  57. print(list_exchanges()) # ['polymarket', 'opinion', 'limitless', 'predictfun', 'kalshi']
  58. exchange = create_exchange('polymarket', {'timeout': 30})
  59. ```
  60. ## Usage via MCP Server
  61. Dr. Manhattan exposes all trading capabilities as MCP tools. Configure in Claude Code (`~/.claude/settings.json` or `.mcp.json`):
  62. ```json
  63. {
  64. "mcpServers": {
  65. "dr-manhattan": {
  66. "command": "/path/to/dr-manhattan/.venv/bin/python",
  67. "args": ["-m", "dr_manhattan.mcp.server"],
  68. "cwd": "/path/to/dr-manhattan"
  69. }
  70. }
  71. }
  72. ```
  73. ### MCP Tools Reference
  74. **Exchange Tools:**
  75. - `list_exchanges` - List all available prediction market exchanges.
  76. - `get_exchange_info(exchange)` - Get metadata and capabilities for an exchange.
  77. - `validate_credentials(exchange)` - Check if credentials are valid without trading.
  78. **Market Discovery:**
  79. - `search_markets(exchange, query)` - Search markets by keyword. This is the fastest way to find markets about a topic.
  80. - `fetch_markets(exchange, limit?, offset?)` - Fetch all markets with pagination.
  81. - `fetch_market(exchange, market_id)` - Fetch a specific market by ID.
  82. - `fetch_markets_by_slug(exchange, slug)` - Fetch markets by slug or URL (Polymarket, Limitless).
  83. - `find_tradeable_market(exchange, binary?, limit?, min_liquidity?)` - Find a suitable market for trading.
  84. - `find_crypto_hourly_market(exchange, token_symbol?)` - Find crypto hourly price markets (Polymarket).
  85. - `fetch_token_ids(exchange, market_id)` - Get token IDs for a market.
  86. - `parse_market_identifier(identifier)` - Extract slug from a Polymarket URL.
  87. - `get_tag_by_slug(slug)` - Get Polymarket tag information.
  88. **Orderbook:**
  89. - `get_orderbook(exchange, token_id)` - Get full orderbook (bids and asks).
  90. - `get_best_bid_ask(exchange, token_id)` - Get best bid and ask prices.
  91. **Trading:**
  92. - `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".
  93. - `cancel_order(exchange, order_id, market_id?)` - Cancel a specific order.
  94. - `cancel_all_orders(exchange, market_id?)` - Cancel all open orders.
  95. - `fetch_order(exchange, order_id, market_id?)` - Get order details and fill status.
  96. - `fetch_open_orders(exchange, market_id?)` - List all open orders.
  97. **Account:**
  98. - `fetch_balance(exchange)` - Get account balance (USDC).
  99. - `fetch_positions(exchange, market_id?)` - Get current positions with PnL.
  100. - `fetch_positions_for_market(exchange, market_id)` - Get positions for a specific market.
  101. - `calculate_nav(exchange, market_id?)` - Calculate net asset value (cash + positions).
  102. **Strategy Management:**
  103. - `create_strategy_session(strategy_type, exchange, market_id, ...)` - Start a market-making strategy in the background.
  104. - `get_strategy_status(session_id)` - Get real-time strategy status (NAV, positions, delta).
  105. - `get_strategy_metrics(session_id)` - Get performance metrics (uptime, fills).
  106. - `pause_strategy(session_id)` - Pause a running strategy.
  107. - `resume_strategy(session_id)` - Resume a paused strategy.
  108. - `stop_strategy(session_id, cleanup?)` - Stop a strategy and optionally cancel orders.
  109. - `list_strategy_sessions` - List all active strategy sessions.
  110. ## Common Workflows
  111. ### Find and Analyze a Market
  112. 1. Use `search_markets` with a keyword to find relevant markets.
  113. 2. Pick a market from the results and note its `id` and `metadata.clobTokenIds`.
  114. 3. Use `get_orderbook` with a token ID to see current bids and asks.
  115. 4. Use `get_best_bid_ask` for a quick spread check.
  116. ### Place a Trade
  117. 1. Find the market using `search_markets` or `fetch_markets_by_slug`.
  118. 2. Check `fetch_balance` to confirm available funds.
  119. 3. Get the orderbook with `get_orderbook` to see current prices.
  120. 4. Use `create_order` with the market ID, outcome ("Yes" or "No"), side ("buy" or "sell"), price (0-1), and size.
  121. 5. Monitor with `fetch_order` or `fetch_open_orders`.
  122. ### Run a Market-Making Strategy
  123. 1. Find a market with `search_markets` or `find_tradeable_market`.
  124. 2. Start with `create_strategy_session(strategy_type="market_making", exchange, market_id)`.
  125. 3. Monitor with `get_strategy_status` and `get_strategy_metrics`.
  126. 4. Control with `pause_strategy`, `resume_strategy`, or `stop_strategy`.
  127. ### Check Portfolio
  128. 1. `fetch_balance` to see cash.
  129. 2. `fetch_positions` to see all open positions with unrealized PnL.
  130. 3. `calculate_nav` for total portfolio value (cash + positions).
  131. ## Key Concepts
  132. - **Prices are probabilities** ranging from 0 to 1 (exclusive). A price of 0.65 means the market implies a 65% chance.
  133. - **Outcomes** are typically "Yes" and "No" for binary markets. Their prices sum to approximately 1.
  134. - **Token IDs** are exchange-specific identifiers for each outcome of a market. Needed for orderbook queries.
  135. - **Slugs** are human-readable URL identifiers (e.g., "trump-2024") used by Polymarket and Limitless.
  136. - **Order types** supported: GTC (Good-Til-Cancel), FOK (Fill-Or-Kill), IOC (Immediate-Or-Cancel).
  137. ## Running Examples
  138. ```bash
  139. uv run python examples/list_all_markets.py polymarket
  140. uv run python examples/spread_strategy.py --exchange polymarket --slug fed-decision
  141. uv run python examples/spike_strategy.py -e opinion -m 813 --spike-threshold 0.02
  142. ```
  143. ## Data Models
  144. **Market** fields: `id`, `question`, `outcomes`, `prices`, `volume`, `liquidity`, `close_time`, `tick_size`, `description`, `metadata` (contains `slug`, `clobTokenIds`).
  145. **Order** fields: `id`, `market_id`, `outcome`, `side` (BUY/SELL), `price`, `size`, `filled`, `status` (PENDING/OPEN/FILLED/CANCELLED), `time_in_force`.
  146. **Position** fields: `market_id`, `outcome`, `size`, `average_price`, `current_price`. Properties: `cost_basis`, `current_value`, `unrealized_pnl`.
  147. **Orderbook** fields: `bids` (price, size descending), `asks` (price, size ascending). Properties: `best_bid`, `best_ask`, `mid_price`, `spread`.
README.md · README · 389 lines
  1. # dr-manhattan
  2. CCXT-style unified API for prediction markets. Simple, scalable, and easy to extend.
  3. [![](https://deepwiki.com/badge.svg)](https://deepwiki.com/guzus/dr-manhattan)
  4. <p align="center">
  5. <img src="assets/polymarket.png" alt="Polymarket" width="50"/>
  6. <img src="assets/kalshi.jpeg" alt="Kalshi" width="50"/>
  7. <img src="assets/opinion.jpg" alt="Opinion" width="50"/>
  8. <img src="assets/limitless.jpg" alt="Limitless" width="50"/>
  9. <img src="assets/predict_fun.jpg" alt="Predict.fun" width="50"/>
  10. </p>
  11. ## Architecture
  12. `dr-manhattan` provides a unified interface to interact with multiple prediction market platforms, similar to how CCXT works for cryptocurrency exchanges.
  13. ### Core Components
  14. ```
  15. dr_manhattan/
  16. ├── base/ # Core abstractions
  17. │ ├── exchange.py # Abstract base class for exchanges
  18. │ ├── exchange_client.py # High-level trading client
  19. │ ├── exchange_factory.py # Exchange instantiation
  20. │ ├── strategy.py # Strategy base class
  21. │ ├── order_tracker.py # Order event tracking
  22. │ ├── websocket.py # WebSocket base class
  23. │ └── errors.py # Exception hierarchy
  24. ├── exchanges/ # Exchange implementations
  25. │ ├── polymarket/ # Polymarket (mixin-based package) → [detailed docs](dr_manhattan/exchanges/polymarket/README.md)
  26. │ │ ├── __init__.py # Unified Polymarket class
  27. │ │ ├── polymarket_core.py # Constants, init, request helpers
  28. │ │ ├── polymarket_clob.py # CLOB API (orders, positions)
  29. │ │ ├── polymarket_gamma.py # Gamma API (markets, events, search)
  30. │ │ ├── polymarket_data.py # Data API (trades, analytics)
  31. │ │ ├── polymarket_ctf.py # CTF (split/merge/redeem)
  32. │ │ ├── polymarket_ws.py # Market/User WebSocket
  33. │ │ ├── polymarket_ws_ext.py # Sports/RTDS WebSocket
  34. │ │ ├── polymarket_builder.py # Builder API
  35. │ │ └── polymarket_operator.py # Operator API
  36. │ ├── kalshi.py
  37. │ ├── opinion.py
  38. │ ├── limitless.py
  39. │ ├── limitless_ws.py
  40. │ ├── predictfun.py
  41. │ └── predictfun_ws.py
  42. ├── models/ # Data models
  43. │ ├── market.py
  44. │ ├── order.py
  45. │ ├── orderbook.py
  46. │ └── position.py
  47. ├── strategies/ # Strategy implementations
  48. └── utils/ # Utilities
  49. ```
  50. ### Design Principles
  51. 1. **Unified Interface**: All exchanges implement the same `Exchange` base class
  52. 2. **Scalability**: Adding new exchanges is straightforward - just implement the abstract methods
  53. 3. **Simplicity**: Clean abstractions with minimal dependencies
  54. 4. **Type Safety**: Full type hints throughout
  55. ### Key Features
  56. - Fetch markets and market data
  57. - Create and cancel orders
  58. - Query positions and balances
  59. - WebSocket support for real-time data
  60. - Strategy base class for building trading strategies
  61. - Order tracking and event logging
  62. - Standardized error handling
  63. - Exchange-agnostic code
  64. - **MCP server for Claude Desktop integration**
  65. ## Installation
  66. ```bash
  67. uv venv
  68. uv pip install -e .
  69. ```
  70. ## Usage
  71. ### Basic Usage (Public API)
  72. ```python
  73. import dr_manhattan
  74. # Initialize exchange without authentication
  75. polymarket = dr_manhattan.Polymarket({'timeout': 30})
  76. opinion = dr_manhattan.Opinion({'timeout': 30})
  77. limitless = dr_manhattan.Limitless({'timeout': 30})
  78. predictfun = dr_manhattan.PredictFun({'timeout': 30})
  79. kalshi = dr_manhattan.Kalshi({'timeout': 30})
  80. # Fetch markets
  81. markets = polymarket.fetch_markets()
  82. for market in markets:
  83. print(f"{market.question}: {market.prices}")
  84. ```
  85. ### Advanced Usage (With Authentication)
  86. ```python
  87. import dr_manhattan
  88. # Polymarket
  89. polymarket = dr_manhattan.Polymarket({
  90. 'private_key': 'your_private_key',
  91. 'funder': 'your_funder_address',
  92. })
  93. # Opinion (BNB Chain)
  94. opinion = dr_manhattan.Opinion({
  95. 'api_key': 'your_api_key',
  96. 'private_key': 'your_private_key',
  97. 'multi_sig_addr': 'your_multi_sig_addr'
  98. })
  99. # Limitless
  100. limitless = dr_manhattan.Limitless({
  101. 'private_key': 'your_private_key',
  102. 'timeout': 30
  103. })
  104. # Predict.fun (BNB Chain)
  105. predictfun = dr_manhattan.PredictFun({
  106. 'api_key': 'your_api_key',
  107. 'private_key': 'your_private_key',
  108. 'use_smart_wallet': True,
  109. 'smart_wallet_owner_private_key': 'your_owner_private_key',
  110. 'smart_wallet_address': 'your_smart_wallet_address'
  111. })
  112. # Create order
  113. order = polymarket.create_order(
  114. market_id="market_123",
  115. outcome="Yes",
  116. side=dr_manhattan.OrderSide.BUY,
  117. price=0.65,
  118. size=100,
  119. params={'token_id': 'token_id'}
  120. )
  121. # Fetch balance
  122. balance = polymarket.fetch_balance()
  123. print(f"USDC: {balance['USDC']}")
  124. ```
  125. ### Using the Strategy Base Class
  126. ```python
  127. from dr_manhattan import Strategy
  128. class MyStrategy(Strategy):
  129. def on_tick(self):
  130. self.log_status()
  131. self.place_bbo_orders()
  132. strategy = MyStrategy(exchange, market_id="123")
  133. strategy.run()
  134. ```
  135. ### Exchange Factory
  136. ```python
  137. from dr_manhattan import create_exchange, list_exchanges
  138. # List available exchanges
  139. print(list_exchanges()) # ['polymarket', 'opinion', 'limitless', 'predictfun', 'kalshi']
  140. # Create exchange by name using environment credentials
  141. exchange = create_exchange('polymarket')
  142. # Read-only instance without requiring credentials
  143. public_exchange = create_exchange('polymarket', validate=False)
  144. ```
  145. 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`.
  146. ### MCP Server
  147. Trade prediction markets directly from Claude using the Model Context Protocol (MCP).
  148. ```bash
  149. # Install with MCP dependencies
  150. uv sync --extra mcp
  151. # Configure credentials
  152. cp .env.example .env
  153. # Edit .env with your POLYMARKET_PRIVATE_KEY and POLYMARKET_FUNDER
  154. ```
  155. #### Claude Code
  156. Add to `~/.claude/settings.json` or project `.mcp.json`:
  157. ```json
  158. {
  159. "mcpServers": {
  160. "dr-manhattan": {
  161. "command": "/path/to/dr-manhattan/.venv/bin/python",
  162. "args": ["-m", "dr_manhattan.mcp.server"],
  163. "cwd": "/path/to/dr-manhattan"
  164. }
  165. }
  166. }
  167. ```
  168. Restart Claude Code and verify with `/mcp`.
  169. #### Claude Desktop
  170. Add to Claude Desktop config (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):
  171. ```json
  172. {
  173. "mcpServers": {
  174. "dr-manhattan": {
  175. "command": "/path/to/dr-manhattan/.venv/bin/python",
  176. "args": ["-m", "dr_manhattan.mcp.server"],
  177. "cwd": "/path/to/dr-manhattan"
  178. }
  179. }
  180. }
  181. ```
  182. #### Remote Server (No Installation Required)
  183. Connect to the hosted MCP server via SSE. No private keys needed - uses Polymarket Builder profile:
  184. ```json
  185. {
  186. "mcpServers": {
  187. "dr-manhattan": {
  188. "type": "sse",
  189. "url": "https://dr-manhattan-mcp-production.up.railway.app/sse",
  190. "headers": {
  191. "X-Polymarket-Api-Key": "your_api_key",
  192. "X-Polymarket-Api-Secret": "your_api_secret",
  193. "X-Polymarket-Passphrase": "your_passphrase"
  194. }
  195. }
  196. }
  197. }
  198. ```
  199. **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.
  200. After restarting, you can:
  201. - "Show my Polymarket balance"
  202. - "Find active prediction markets"
  203. - "Buy 10 USDC of Yes on market X at 0.55"
  204. See [examples/mcp_usage_example.md](examples/mcp_usage_example.md) for the complete setup guide.
  205. ## Adding New Exchanges
  206. To add a new exchange, create a class that inherits from `Exchange`:
  207. ```python
  208. from dr_manhattan.base import Exchange
  209. class NewExchange(Exchange):
  210. @property
  211. def id(self) -> str:
  212. return "newexchange"
  213. @property
  214. def name(self) -> str:
  215. return "New Exchange"
  216. def fetch_markets(self, params=None):
  217. # Implement API call
  218. pass
  219. # Implement other abstract methods...
  220. ```
  221. Register in `dr_manhattan/__init__.py`:
  222. ```python
  223. from .exchanges.newexchange import NewExchange
  224. exchanges = {
  225. "polymarket": Polymarket,
  226. "opinion": Opinion,
  227. "limitless": Limitless,
  228. "predictfun": PredictFun,
  229. "kalshi": Kalshi,
  230. "newexchange": NewExchange,
  231. }
  232. ```
  233. ## Data Models
  234. ### Market
  235. - Question and outcomes
  236. - Prices and volume
  237. - Close time and status
  238. ### Order
  239. - Market and outcome
  240. - Side (buy/sell), price, size
  241. - Status tracking
  242. ### Position
  243. - Current holdings
  244. - PnL calculation
  245. - Average entry price
  246. ### OrderBook
  247. - Bids and asks
  248. - Best bid/ask prices
  249. ## Error Handling
  250. All errors inherit from `DrManhattanError`:
  251. - `ExchangeError` - Exchange-specific errors
  252. - `NetworkError` - Connectivity issues
  253. - `RateLimitError` - Rate limit exceeded
  254. - `AuthenticationError` - Auth failures
  255. - `InsufficientFunds` - Not enough balance
  256. - `InvalidOrder` - Invalid order parameters
  257. - `MarketNotFound` - Market doesn't exist
  258. ## Examples
  259. Check out the [examples/](examples/) directory for working examples:
  260. - **mcp_usage_example.md** - Complete MCP server setup and usage guide for Claude Desktop
  261. - **list_all_markets.py** - List markets from any exchange
  262. - **spread_strategy.py** - Exchange-agnostic BBO market making strategy
  263. Run examples:
  264. ```bash
  265. # List markets
  266. uv run python examples/list_all_markets.py polymarket
  267. uv run python examples/list_all_markets.py opinion
  268. uv run python examples/list_all_markets.py limitless
  269. uv run python examples/list_all_markets.py predictfun
  270. uv run python examples/list_all_markets.py kalshi
  271. # Run spread strategy
  272. uv run python examples/spread_strategy.py --exchange polymarket --slug fed-decision
  273. uv run python examples/spread_strategy.py --exchange opinion --market-id 813
  274. ```
  275. See [examples/README.md](examples/README.md) for detailed documentation.
  276. ## Contributing with Claude
  277. <p align="center">
  278. <img src="assets/claude.png" alt="Claude" width="100"/>
  279. </p>
  280. We use Claude Code to implement new features from trading strategy ideas:
  281. 1. Spot a good strategy on Twitter/X
  282. 2. Create a GitHub issue describing the strategy
  283. 3. Add a label: `feature`, `bug`, or `chore`
  284. 4. Mention `@claude` in the issue
  285. 5. Claude creates a PR with the implementation
  286. Branch naming follows the label:
  287. - `feature` -> `feat/issue-{number}`
  288. - `bug` -> `fix/issue-{number}`
  289. - `chore` -> `chore/issue-{number}`
  290. See [.github/workflows/claude.yml](.github/workflows/claude.yml) for details.
  291. ## Dependencies
  292. - Python >= 3.11
  293. - requests >= 2.31.0
  294. - websockets >= 15.0.1
  295. - python-socketio >= 5.11.0
  296. - eth-account >= 0.11.0
  297. - py-clob-client >= 0.28.0
  298. - opinion-clob-sdk >= 0.4.3
  299. - pandas >= 2.0.0
  300. Development:
  301. - pytest
  302. - black
  303. - ruff

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.