polymarket-sdk 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. polymarket_sdk-0.2.0/.gitignore +18 -0
  2. polymarket_sdk-0.2.0/CHANGELOG.md +26 -0
  3. polymarket_sdk-0.2.0/CONTRIBUTING.md +39 -0
  4. polymarket_sdk-0.2.0/LICENSE +21 -0
  5. polymarket_sdk-0.2.0/PKG-INFO +388 -0
  6. polymarket_sdk-0.2.0/README.md +361 -0
  7. polymarket_sdk-0.2.0/RISK_POLICY.md +366 -0
  8. polymarket_sdk-0.2.0/examples/fetch_markets.py +29 -0
  9. polymarket_sdk-0.2.0/examples/mean_reversion.py +111 -0
  10. polymarket_sdk-0.2.0/examples/place_order.py +37 -0
  11. polymarket_sdk-0.2.0/policy.yaml +83 -0
  12. polymarket_sdk-0.2.0/pyproject.toml +44 -0
  13. polymarket_sdk-0.2.0/src/polymarket_autopilot/__init__.py +3 -0
  14. polymarket_sdk-0.2.0/src/polymarket_autopilot/audit.py +194 -0
  15. polymarket_sdk-0.2.0/src/polymarket_autopilot/fetcher/__init__.py +61 -0
  16. polymarket_sdk-0.2.0/src/polymarket_autopilot/fetcher/fetcher.py +489 -0
  17. polymarket_sdk-0.2.0/src/polymarket_autopilot/market_snapshot.py +173 -0
  18. polymarket_sdk-0.2.0/src/polymarket_autopilot/metrics.py +159 -0
  19. polymarket_sdk-0.2.0/src/polymarket_autopilot/policy.py +400 -0
  20. polymarket_sdk-0.2.0/src/polymarket_autopilot/py.typed +0 -0
  21. polymarket_sdk-0.2.0/src/polymarket_autopilot/state_machine.py +315 -0
  22. polymarket_sdk-0.2.0/src/polymarket_autopilot/trading/__init__.py +5 -0
  23. polymarket_sdk-0.2.0/src/polymarket_autopilot/trading/trading.py +500 -0
  24. polymarket_sdk-0.2.0/tests/__init__.py +1 -0
  25. polymarket_sdk-0.2.0/tests/test_audit.py +67 -0
  26. polymarket_sdk-0.2.0/tests/test_fetcher.py +27 -0
  27. polymarket_sdk-0.2.0/tests/test_logic.py +154 -0
  28. polymarket_sdk-0.2.0/tests/test_market_snapshot.py +86 -0
  29. polymarket_sdk-0.2.0/tests/test_metrics.py +62 -0
  30. polymarket_sdk-0.2.0/tests/test_policy.py +167 -0
  31. polymarket_sdk-0.2.0/tests/test_state_machine.py +218 -0
  32. polymarket_sdk-0.2.0/tests/test_trading.py +38 -0
  33. polymarket_sdk-0.2.0/uv.lock +1091 -0
@@ -0,0 +1,18 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .eggs/
8
+ *.egg
9
+ .env
10
+ .venv/
11
+ venv/
12
+ .ruff_cache/
13
+ .mypy_cache/
14
+ .pytest_cache/
15
+ htmlcov/
16
+ .coverage
17
+ polymarket_data/
18
+ .github/workflows/
@@ -0,0 +1,26 @@
1
+ # Changelog
2
+
3
+ ## [0.6.0] — 2026-06-05
4
+
5
+ ### Added
6
+ - **Market snapshot validation** (`market_snapshot.py`): Polymarket-specific CLOB
7
+ sanity checks — prices in (0,1), crossed-book detection, spread limits, mid-price
8
+ divergence guard. Raises `MarketDataError` on degenerate/stale snapshots.
9
+ - **Drawdown metrics** (`metrics.py`): venue-agnostic `drawdown_series`,
10
+ `max_drawdown`, `rank_drawdown_leaderboard` for equity-curve analysis.
11
+
12
+ ## [0.1.0] — 2026-05-23
13
+
14
+ ### Added
15
+ - Market data fetcher: 25+ endpoints covering Gamma, CLOB, and Data APIs
16
+ - Event/market browsing with pagination, filtering, and search
17
+ - Price history (OHLCV), orderbook depth, spreads, and midpoints
18
+ - Order execution: limit orders with EIP-712 signing (optional eth-account)
19
+ - Position tracking, order management, and balance queries
20
+ - Strategy framework: mean-reversion, momentum, convergence
21
+ - Zero-dependency core (trading extra is opt-in)
22
+ - 15 tests covering fetcher, trading, models, and error handling
23
+ - GitHub Actions CI (Python 3.10, 3.11, 3.12)
24
+ - MIT License
25
+
26
+ [0.1.0]: https://github.com/counterfactual5/polymarket-autopilot/releases/tag/v0.1.0
@@ -0,0 +1,39 @@
1
+ # Contributing to polymarket-autopilot
2
+
3
+ ## Setup
4
+
5
+ ```bash
6
+ git clone https://github.com/counterfactual5/polymarket-autopilot.git
7
+ cd polymarket-autopilot
8
+ uv pip install -e ".[dev,trading]"
9
+ ```
10
+
11
+ ## Running Tests
12
+
13
+ ```bash
14
+ uv run pytest tests/ -v
15
+ ```
16
+
17
+ 15 tests covering fetcher API, trading, order/position models, error handling, and pagination.
18
+
19
+ ## Code Style
20
+
21
+ - Python 3.10+ compatible
22
+ - 120-char line length
23
+ - Public functions have docstrings
24
+ - Core package has zero dependencies (trading needs only eth-account)
25
+
26
+ ## Project Structure
27
+
28
+ ```
29
+ src/polymarket_autopilot/
30
+ ├── fetcher/ # Market data: Gamma, CLOB, and Data APIs
31
+ │ └── fetcher.py # 25+ endpoints
32
+ └── trading/ # Authenticated trading
33
+ └── trading.py # EIP-712 signing, order execution
34
+ ```
35
+
36
+ ## Pull Requests
37
+
38
+ 1. Fork → feature branch → changes + tests → PR to `master`
39
+ 2. Keep PRs focused — one concern per PR
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 counterfactual5
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,388 @@
1
+ Metadata-Version: 2.4
2
+ Name: polymarket-sdk
3
+ Version: 0.2.0
4
+ Summary: Polymarket trading client and market data fetcher
5
+ Project-URL: Repository, https://github.com/counterfactual5/polymarket-sdk
6
+ Project-URL: Issues, https://github.com/counterfactual5/polymarket-sdk/issues
7
+ Author: counterfactual5
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: clob,polymarket,prediction-market,trading
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Office/Business :: Financial :: Investment
19
+ Requires-Python: >=3.10
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest-cov; extra == 'dev'
22
+ Requires-Dist: pytest>=7.0; extra == 'dev'
23
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
24
+ Provides-Extra: trading
25
+ Requires-Dist: eth-account>=0.10; extra == 'trading'
26
+ Description-Content-Type: text/markdown
27
+
28
+ <div align="center">
29
+
30
+ # 🎯 Polymarket Autopilot
31
+
32
+ ### The Python SDK Polymarket never shipped.
33
+
34
+ **Fetch markets. Place orders. Track positions.** All in pure Python.
35
+
36
+ Zero Dependencies* · Polymarket CLOB API · EIP-191 Signing · 25+ API Endpoints
37
+
38
+ <sub>*Market data: zero deps. Trading: `eth-account` only, for message signing.</sub>
39
+
40
+ [![Test](https://github.com/counterfactual5/polymarket-autopilot/actions/workflows/test.yml/badge.svg)](https://github.com/counterfactual5/polymarket-autopilot/actions)
41
+ [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
42
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
43
+ [![Zero Deps](https://img.shields.io/badge/dependencies-zero-brightgreen.svg)](pyproject.toml)
44
+
45
+ [Installation](#installation) · [Market Data](#-fetch-market-data) · [Trading](#-place--manage-orders) · [API Reference](#api-reference)
46
+
47
+ </div>
48
+
49
+ ---
50
+
51
+ > [!IMPORTANT]
52
+ > **Trading safety.** Order paths run through a shared risk-control policy
53
+ > (amount caps, price range, max position value, chain allow-list) evaluated
54
+ > between the `PREFLIGHT` and `SIGNED` states. Read **[RISK_POLICY.md](RISK_POLICY.md)**
55
+ > and copy `policy.yaml` to `~/.stageforge/policy.yaml` before going live.
56
+
57
+ ## The Problem
58
+
59
+ Polymarket is the world's largest prediction market — but they don't offer a Python SDK. Their [official docs](https://docs.polymarket.com) show raw `curl` commands and JavaScript examples. If you want to build trading bots, analyze markets, or automate strategies in Python, you're on your own.
60
+
61
+ **polymarket-autopilot fills that gap.** One `pip install` gives you 25+ endpoints covering market data, trading, and portfolio management — pure Python, zero dependencies.
62
+
63
+ ```
64
+ Without this library: With this library:
65
+
66
+ 1. Read Polymarket API docs 1. pip install polymarket-autopilot
67
+ 2. Write HTTP client from scratch 2. from polymarket_autopilot.fetcher import search
68
+ 3. Implement message signing 3. results = search("US election")
69
+ 4. Debug authentication headers
70
+ 5. Handle pagination manually ✅ Done.
71
+ ```
72
+
73
+ ---
74
+
75
+ ## Features
76
+
77
+ ### 📊 Market Data (no auth required)
78
+
79
+ - **Events** — browse active, closed, featured events by volume and recency
80
+ - **Markets** — full market details or simplified lightweight listings
81
+ - **Search** — fuzzy search across all events and markets
82
+ - **Price History** — OHLCV candles at any interval (1m, 1h, 1d)
83
+ - **Orderbook** — full bid/ask depth for any outcome token
84
+ - **Spreads & Midpoints** — real-time pricing data
85
+ - **Open Interest** — market-wide position statistics
86
+ - **Leaderboard** — top traders by PnL
87
+ - **Tags & Series** — browse by category (politics, crypto, sports, etc.)
88
+ - **Trades** — recent fills filtered by market, maker, or taker
89
+
90
+ ### ⚡ Trading (auth required)
91
+
92
+ - **Place Orders** — limit orders on any outcome with personal-sign (EIP-191)
93
+ - **Cancel Orders** — cancel single or all orders
94
+ - **View Positions** — current holdings across all markets
95
+ - **View Open Orders** — pending orders with optional market filter
96
+ - **Balance Check** — USDC balance query
97
+
98
+ ### 🔧 Engineering
99
+
100
+ - **Zero dependencies** — pure Python stdlib (urllib, json, hashlib)
101
+ - **Pagination handled** — automatic offset-based pagination for large result sets
102
+ - **Retry logic** — built-in retry with exponential backoff
103
+ - **Gzip support** — automatic decompression for faster responses
104
+ - **Type-annotated** — full type hints for IDE autocomplete
105
+
106
+ ---
107
+
108
+ ## Installation
109
+
110
+ ```bash
111
+ # Market data only (zero deps)
112
+ pip install polymarket-autopilot
113
+
114
+ # Add trading support (eth-account for signing)
115
+ pip install "polymarket-autopilot[trading]"
116
+ ```
117
+
118
+ That's it. No Node.js. No curl. No web3.py. Pure Python.
119
+
120
+ ---
121
+
122
+ ## Quick Start
123
+
124
+ ### 📊 Fetch Market Data
125
+
126
+ ```python
127
+ from polymarket_autopilot.fetcher import (
128
+ fetch_events, search, fetch_price_history,
129
+ fetch_orderbook, fetch_spread, resolve_market_token_id,
130
+ )
131
+ ```
132
+
133
+ **Browse trending events:**
134
+
135
+ ```python
136
+ events = fetch_events(limit=5)
137
+ for ev in events:
138
+ print(f" {ev['title']}")
139
+ print(f" Volume: ${ev.get('volume', 0):,.0f}")
140
+ print(f" Markets: {len(ev.get('markets', []))}")
141
+ ```
142
+
143
+ ```
144
+ Will Bitcoin reach $150K by end of 2026?
145
+ Volume: $12,450,000
146
+ Markets: 2
147
+ US Presidential Election 2028
148
+ Volume: $8,320,000
149
+ Markets: 5
150
+ Will ETH flip BTC in market cap?
151
+ Volume: $3,100,000
152
+ Markets: 1
153
+ ```
154
+
155
+ **Search for a market:**
156
+
157
+ ```python
158
+ results = search("bitcoin 100k")
159
+ for market in results.get("markets", [])[:3]:
160
+ print(f" {market['question']}")
161
+ print(f" YES: {market.get('outcomePrices', ['?'])[0]}")
162
+ ```
163
+
164
+ ```
165
+ Will Bitcoin reach $100,000 by December 2026?
166
+ YES: 0.452
167
+ Will Bitcoin be above $100K on June 1?
168
+ YES: 0.381
169
+ Bitcoin $100K end of year?
170
+ YES: 0.417
171
+ ```
172
+
173
+ **Get price history:**
174
+
175
+ ```python
176
+ history = fetch_price_history("will-bitcoin-hit-100k", interval="1d")
177
+ for candle in history[-5:]:
178
+ print(f" {candle['timestamp']} O:{candle['open']} H:{candle['high']} L:{candle['low']} C:{candle['close']}")
179
+ ```
180
+
181
+ **Check the orderbook:**
182
+
183
+ ```python
184
+ token_id = resolve_market_token_id("will-bitcoin-hit-100k", outcome_index=0) # YES
185
+ book = fetch_orderbook(token_id)
186
+ spread = fetch_spread(token_id)
187
+ print(f" Bid: {book['bids'][0]['price']} Ask: {book['asks'][0]['price']}")
188
+ print(f" Spread: {spread['spread']}")
189
+ ```
190
+
191
+ ### ⚡ Place & Manage Orders
192
+
193
+ ```python
194
+ import os
195
+ from polymarket_autopilot.trading import PolymarketTrader, Order
196
+
197
+ # Configure via environment variables
198
+ # export POLYMARKET_API_KEY="..."
199
+ # export POLYMARKET_ADDRESS="0x..."
200
+ # export POLYMARKET_PRIVATE_KEY="..." # via env var, never on disk
201
+
202
+ trader = PolymarketTrader.from_env()
203
+ ```
204
+
205
+ **Buy YES on a market:**
206
+
207
+ ```python
208
+ token_id = resolve_market_token_id("will-bitcoin-hit-100k", outcome_index=0)
209
+
210
+ order = Order(
211
+ token_id=token_id,
212
+ side="buy", # "buy" or "sell"
213
+ price=0.45, # price in USDC (0-1 range for binary options)
214
+ size=10, # quantity in USDC
215
+ )
216
+
217
+ result = trader.place_order(order)
218
+ print(f" Order ID: {result['orderID']}")
219
+ print(f" Status: {result['status']}")
220
+ ```
221
+
222
+ ```
223
+ Order ID: 12345678
224
+ Status: LIVE
225
+ ```
226
+
227
+ **Check your positions:**
228
+
229
+ ```python
230
+ positions = trader.get_positions()
231
+ for pos in positions:
232
+ print(f" {pos.token_id[:10]}... {pos.side} {pos.size} @ avg {pos.avg_price}")
233
+ ```
234
+
235
+ **Manage open orders:**
236
+
237
+ ```python
238
+ # View open orders
239
+ orders = trader.get_orders()
240
+ for o in orders:
241
+ print(f" {o['id']}: {o['side']} {o['original_size']} @ {o['price']}")
242
+
243
+ # Cancel a specific order
244
+ trader.cancel_order("12345678")
245
+
246
+ # Cancel all orders for a token
247
+ trader.cancel_all_orders(token_id=token_id)
248
+ ```
249
+
250
+ ---
251
+
252
+ ## API Reference
253
+
254
+ ### Market Data (no auth)
255
+
256
+ | Function | Endpoint | Description |
257
+ |---|---|---|
258
+ | `fetch_events()` | Gamma API | Browse events with filters (active, closed, featured) |
259
+ | `fetch_event_by_id()` | Gamma API | Get single event by ID |
260
+ | `fetch_event_by_slug()` | Gamma API | Get single event by URL slug |
261
+ | `fetch_markets()` | Gamma API | Browse markets with full details |
262
+ | `fetch_market_by_id()` | Gamma API | Get single market by ID |
263
+ | `fetch_market_by_slug()` | Gamma API | Get single market by URL slug |
264
+ | `fetch_simplified_markets()` | Gamma API | Lightweight market list (faster) |
265
+ | `search()` | Gamma API | Fuzzy search across events and markets |
266
+ | `fetch_event_tags()` | Gamma API | Tags for an event |
267
+ | `fetch_tags()` | Gamma API | All available tags/categories |
268
+ | `fetch_series()` | Gamma API | Market series/collections |
269
+ | `fetch_price_history()` | CLOB API | OHLCV price candles |
270
+ | `fetch_orderbook()` | CLOB API | Full bid/ask order book |
271
+ | `fetch_midpoint()` | CLOB API | Midpoint price for a token |
272
+ | `fetch_spread()` | CLOB API | Bid-ask spread |
273
+ | `fetch_trades()` | CLOB API | Recent trade fills |
274
+ | `fetch_open_interest()` | Data API | Open interest statistics |
275
+ | `fetch_leaderboard()` | Data API | Top traders by PnL |
276
+ | `resolve_market_token_id()` | — | Convert market slug → CLOB token ID |
277
+ | `fetch_all_snapshot()` | Multiple | Bulk snapshot of events + markets |
278
+
279
+ ### Trading (auth required)
280
+
281
+ | Method | Description |
282
+ |---|---|
283
+ | `PolymarketTrader.from_env()` | Create trader from environment variables |
284
+ | `trader.place_order(order)` | Place a limit order (signed) |
285
+ | `trader.cancel_order(order_id)` | Cancel a specific order |
286
+ | `trader.cancel_all_orders(token_id?)` | Cancel all orders (optionally filtered) |
287
+ | `trader.get_orders(token_id?)` | List open orders |
288
+ | `trader.get_positions()` | List current positions |
289
+ | `trader.get_balance()` | Check USDC balance |
290
+
291
+ ---
292
+
293
+ ## Architecture
294
+
295
+ ```
296
+ polymarket_autopilot/
297
+ ├── fetcher/ Market data (no auth)
298
+ │ └── fetcher.py 25 endpoints — Gamma, CLOB, Data APIs
299
+ │ ├── Gamma API Events, markets, tags, series, search
300
+ │ ├── CLOB API Prices, orderbook, spreads, trades
301
+ │ └── Data API Leaderboard, open interest
302
+
303
+ └── trading/ Authenticated trading
304
+ └── trading.py Order execution + portfolio management
305
+ ├── Order Limit order dataclass
306
+ ├── Position Position dataclass
307
+ └── PolymarketTrader Main trading client
308
+ ├── Message signing (eth-account, optional)
309
+ ├── Place / cancel orders
310
+ └── Position & balance queries
311
+ ```
312
+
313
+ ```
314
+ Data Flow:
315
+
316
+ User Code
317
+
318
+ ├── fetcher.search() ──────────→ Polymarket Gamma API ──→ events, markets, tags
319
+
320
+ ├── fetcher.fetch_orderbook() ──→ Polymarket CLOB API ──→ prices, spreads, trades
321
+
322
+ ├── fetcher.fetch_leaderboard() → Polymarket Data API ──→ leaderboard, open interest
323
+
324
+ └── trader.place_order(order) ──→ Sign ──→ Polymarket CLOB ──→ ✅ Order placed
325
+
326
+ eth-account
327
+ (trading extra)
328
+ ```
329
+
330
+ ## Security
331
+
332
+ | Concern | How we handle it |
333
+ |---|---|
334
+ | Private keys | Environment variable only — never on disk, never logged |
335
+ | Order signing | In-process via eth-account — no external CLI, no IPC |
336
+ | API keys | Passed via env vars, not hardcoded or stored in config files |
337
+ | HTTP requests | urllib with gzip + retry — no third-party HTTP libraries |
338
+
339
+ ```bash
340
+ # Required for trading
341
+ export POLYMARKET_API_KEY="your-api-key"
342
+ export POLYMARKET_ADDRESS="0x..."
343
+ export POLYMARKET_PRIVATE_KEY="0x..." # via env var, never written to a file
344
+ ```
345
+
346
+ ## For AI Agent Developers
347
+
348
+ This library is designed as the execution backend for AI trading agents:
349
+
350
+ ```python
351
+ # 1. Research → search markets, check prices and spreads
352
+ # 2. Analyze → fetch orderbook depth, price history, open interest
353
+ # 3. Decide → your model / strategy logic
354
+ # 4. Execute → place_order() with message signing
355
+ # 5. Monitor → get_positions(), get_orders()
356
+ ```
357
+
358
+ Works with [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [Cursor](https://cursor.sh), [Codex](https://github.com/openai/codex), or any Python-capable agent.
359
+
360
+ ## Development
361
+
362
+ ```bash
363
+ git clone https://github.com/counterfactual5/polymarket-autopilot.git
364
+ cd polymarket-autopilot
365
+
366
+ # Install with dev + trading deps
367
+ uv pip install -e ".[dev,trading]"
368
+
369
+ # Run tests
370
+ uv run pytest tests/ -v
371
+ ```
372
+
373
+ ## Roadmap
374
+
375
+ - [x] Strategy framework (mean-reversion, momentum, convergence)
376
+ - [ ] Market analysis (probability trends, volume anomalies)
377
+ - [ ] Backtesting engine with historical data
378
+ - [ ] Arbitrage scanner (spread + cross-market)
379
+ - [ ] WebSocket support for real-time price feeds
380
+ - [ ] Async support (async/await)
381
+
382
+ ## License
383
+
384
+ [MIT](LICENSE) — use it however you want.
385
+
386
+ ---
387
+
388
+ If this project helped you, please ⭐ star this repo — it helps others find it!