polysimulator 0.2.2__tar.gz → 0.4.1__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 (52) hide show
  1. polysimulator-0.4.1/PKG-INFO +1137 -0
  2. polysimulator-0.4.1/README.md +1102 -0
  3. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_clob_client/client.py +34 -88
  4. polysimulator-0.4.1/polysim_polymarket/__init__.py +235 -0
  5. polysimulator-0.4.1/polysim_polymarket/clients/__init__.py +0 -0
  6. polysimulator-0.4.1/polysim_polymarket/clients/_account.py +213 -0
  7. polysimulator-0.4.1/polysim_polymarket/clients/_common.py +573 -0
  8. polysimulator-0.4.1/polysim_polymarket/clients/_onchain.py +293 -0
  9. polysimulator-0.4.1/polysim_polymarket/clients/_trade.py +520 -0
  10. polysimulator-0.4.1/polysim_polymarket/clients/async_public.py +450 -0
  11. polysimulator-0.4.1/polysim_polymarket/clients/async_secure.py +1153 -0
  12. polysimulator-0.4.1/polysim_polymarket/clients/public.py +443 -0
  13. polysimulator-0.4.1/polysim_polymarket/clients/secure.py +1200 -0
  14. polysimulator-0.4.1/polysim_polymarket/environments.py +62 -0
  15. polysimulator-0.4.1/polysim_polymarket/errors.py +59 -0
  16. polysimulator-0.4.1/polysim_polymarket/models.py +784 -0
  17. polysimulator-0.4.1/polysim_polymarket/pagination.py +228 -0
  18. polysimulator-0.4.1/polysim_polymarket/rfq.py +312 -0
  19. polysimulator-0.4.1/polysim_polymarket/streams/__init__.py +112 -0
  20. polysimulator-0.4.1/polysim_polymarket/streams/_adapt.py +432 -0
  21. polysimulator-0.4.1/polysim_polymarket/streams/_crypto_events.py +54 -0
  22. polysimulator-0.4.1/polysim_polymarket/streams/_handle.py +152 -0
  23. polysimulator-0.4.1/polysim_polymarket/streams/_market_events.py +221 -0
  24. polysimulator-0.4.1/polysim_polymarket/streams/_runner.py +80 -0
  25. polysimulator-0.4.1/polysim_polymarket/streams/_specs.py +144 -0
  26. polysimulator-0.4.1/polysim_polymarket/streams/_stream_open.py +212 -0
  27. polysimulator-0.4.1/polysim_polymarket/streams/_user_events.py +136 -0
  28. polysimulator-0.4.1/polysim_polymarket/streams/_validators.py +149 -0
  29. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_sdk/__init__.py +2 -0
  30. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_sdk/_http.py +10 -0
  31. polysimulator-0.4.1/polysim_sdk/_shared.py +135 -0
  32. polysimulator-0.4.1/polysim_sdk/retry.py +89 -0
  33. {polysimulator-0.2.2 → polysimulator-0.4.1}/pyproject.toml +12 -3
  34. polysimulator-0.2.2/PKG-INFO +0 -508
  35. polysimulator-0.2.2/README.md +0 -475
  36. {polysimulator-0.2.2 → polysimulator-0.4.1}/.gitignore +0 -0
  37. {polysimulator-0.2.2 → polysimulator-0.4.1}/LICENSE +0 -0
  38. {polysimulator-0.2.2 → polysimulator-0.4.1}/NOTICE +0 -0
  39. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_clob_client/__init__.py +0 -0
  40. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_clob_client/clob_types.py +0 -0
  41. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_clob_client/constants.py +0 -0
  42. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_clob_client/exceptions.py +0 -0
  43. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_clob_client/order_builder/__init__.py +0 -0
  44. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_clob_client/order_builder/constants.py +0 -0
  45. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_sdk/aio.py +0 -0
  46. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_sdk/client.py +0 -0
  47. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_sdk/constants.py +0 -0
  48. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_sdk/exceptions.py +0 -0
  49. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_sdk/pagination.py +0 -0
  50. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_sdk/sse.py +0 -0
  51. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_sdk/updown.py +0 -0
  52. {polysimulator-0.2.2 → polysimulator-0.4.1}/polysim_sdk/ws.py +0 -0
@@ -0,0 +1,1137 @@
1
+ Metadata-Version: 2.4
2
+ Name: polysimulator
3
+ Version: 0.4.1
4
+ Summary: Python SDK for the PolySimulator paper-trading API, with py-clob-client v1 drop-in parity (not py-clob-client-v2) and a polysim_polymarket paper-mode mirror of Polymarket's unified py-sdk (polymarket-client 0.1.0b8).
5
+ Project-URL: Homepage, https://polysimulator.com
6
+ Project-URL: Documentation, https://docs.polysimulator.com
7
+ Project-URL: API Reference, https://api.polysimulator.com/docs
8
+ Project-URL: Repository, https://github.com/Bavariance/polysimulator-sdk
9
+ Author: Bavariance
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Keywords: api-sdk,paper-trading,polymarket,polysimulator,trading
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Office/Business :: Financial
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: httpx<1,>=0.27
23
+ Requires-Dist: pydantic<3,>=2
24
+ Requires-Dist: websockets<17,>=12
25
+ Provides-Extra: dev
26
+ Requires-Dist: build>=1.0; extra == 'dev'
27
+ Requires-Dist: mypy>=1.10; extra == 'dev'
28
+ Requires-Dist: polymarket-client==0.1.0b8; extra == 'dev'
29
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
30
+ Requires-Dist: pytest>=8; extra == 'dev'
31
+ Requires-Dist: respx>=0.21; extra == 'dev'
32
+ Requires-Dist: ruff>=0.6; extra == 'dev'
33
+ Requires-Dist: twine>=5.0; extra == 'dev'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # PolySimulator Python SDK
37
+
38
+ [![PyPI](https://img.shields.io/pypi/v/polysimulator.svg)](https://pypi.org/project/polysimulator/)
39
+ [![Python versions](https://img.shields.io/pypi/pyversions/polysimulator.svg)](https://pypi.org/project/polysimulator/)
40
+ [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
41
+ [![py-clob-client compat](https://img.shields.io/badge/py--clob--client-v1%20drop--in-blue.svg)](https://github.com/Polymarket/py-clob-client)
42
+ [![py-sdk mirror](https://img.shields.io/badge/polymarket--client-0.1.0b8%20mirror-blueviolet.svg)](https://pypi.org/project/polymarket-client/)
43
+
44
+ > **Mirrors Polymarket's unified py-sdk** — `polysim_polymarket` is a paper-mode mirror of [`polymarket-client`](https://pypi.org/project/polymarket-client/) **`0.1.0b8`**: sync + async PublicClient/SecureClient, trading, and core streams. Swap the import prefix + host + auth and your py-sdk bot runs on paper. [Compat matrix ↓](#compat-matrix)
45
+
46
+ The official Python client for the [PolySimulator](https://polysimulator.com)
47
+ paper-trading API. **One package, three import surfaces:**
48
+
49
+ | Import surface | Use it when |
50
+ |---|---|
51
+ | `polysim_sdk` | You're starting fresh. A clean, modern client — sync **and** async, WebSocket streaming, pagination iterators, typed exceptions. |
52
+ | `polysim_clob_client` | You already have a bot written against Polymarket's [`py-clob-client`](https://github.com/Polymarket/py-clob-client). This is a **drop-in mirror** — port by changing the import path, the host, and the auth call. |
53
+ | `polysim_polymarket` | You target Polymarket's newer unified **[py-sdk](https://pypi.org/project/polymarket-client/)** (`pip install polymarket-client`, import `polymarket`). A **paper-mode mirror** of its unified surface — sync **and** async `PublicClient` / `SecureClient` (reads, account/auth, trading) plus core realtime streams. Port by swapping the import prefix + host + auth. See [Polymarket py-sdk (v2) mirror](#polymarket-py-sdk-v2-mirror) — read the [sim→real seam contract](#the-simreal-seam-contract-what-paper-mode-does-and-doesnt-do) and [compat matrix](#compat-matrix) before you rely on a surface area. |
54
+
55
+ PolySimulator is paper trading, so there is **no on-chain anything**: no private
56
+ key, no `chain_id`, no `funder`, no `signature_type`, no EIP-712 signing, no USDC
57
+ allowance/approval transactions, no web3/Polygon RPC. The SDK depends only on
58
+ `httpx` and `websockets`. Authentication is a single `ps_live_*` API key sent as
59
+ the `X-API-Key` header.
60
+
61
+ ---
62
+
63
+ ## Install
64
+
65
+ Targets Python 3.10+.
66
+
67
+ ```bash
68
+ pip install polysimulator
69
+ ```
70
+
71
+ > The install name is **`polysimulator`**; the import name stays **`polysim_sdk`**
72
+ > (like `pip install pillow` → `import PIL`). The older `polysim-sdk` name is now a
73
+ > thin alias that installs `polysimulator` for you, so existing installs keep working.
74
+
75
+ From a checkout of this directory (for development):
76
+
77
+ ```bash
78
+ python -m venv .venv && source .venv/bin/activate
79
+ pip install -e ".[dev]" # editable install + pytest/ruff/mypy/build/twine
80
+ ```
81
+
82
+ Provide your key via the `POLYSIM_API_KEY` environment variable (recommended) or
83
+ pass it to the constructor. To target staging instead of production:
84
+
85
+ ```bash
86
+ export POLYSIM_API_KEY="ps_live_…"
87
+ export POLYSIM_BASE_URL="https://staging-api.polysimulator.com"
88
+ ```
89
+
90
+ ---
91
+
92
+ ## Quickstart — native `polysim_sdk`
93
+
94
+ ```python
95
+ from polysim_sdk import PolySimClient
96
+
97
+ with PolySimClient() as client: # POLYSIM_API_KEY from env
98
+ me = client.me()
99
+ print(me["balance"]) # your trading balance (a JSON string)
100
+
101
+ market = client.list_markets(limit=1, hot_only=True)[0]
102
+ cid = market["condition_id"]
103
+
104
+ book = client.get_book(cid) # by condition id (+ outcome=/depth=)
105
+ asks = book.get("asks") or [] # levels: [{"price","size"}, ...]
106
+ best_ask = min((float(a["price"]) for a in asks), default=None)
107
+ print("best ask:", best_ask) # lowest ask = best price to buy at
108
+
109
+ # …or by outcome-token id, the Polymarket-native way:
110
+ # token_book = client.get_book_by_token("<outcome-token-id>")
111
+
112
+ fill = client.place_order(
113
+ market_id=cid,
114
+ side="BUY",
115
+ outcome="YES",
116
+ quantity=10,
117
+ order_type="market",
118
+ price="0.99", # worst-acceptable fill (YES < $1 → "any fill")
119
+ )
120
+ print(f"filled {fill['status']} @ {fill.get('price')}")
121
+ ```
122
+
123
+ Async is the same API with `await`:
124
+
125
+ ```python
126
+ import asyncio
127
+ from polysim_sdk import AsyncPolySimClient
128
+
129
+ async def main():
130
+ async with AsyncPolySimClient() as client:
131
+ me = await client.me()
132
+ print(me["balance"])
133
+
134
+ asyncio.run(main())
135
+ ```
136
+
137
+ ---
138
+
139
+ ## Finding BTC Up/Down markets
140
+
141
+ Short-horizon **crypto Up/Down** markets — "is BTC/ETH/SOL/… up or down over
142
+ this window" resolving on a 5-minute … daily horizon — are the platform's
143
+ most-traded product. They have a dedicated endpoint and do **not** show up
144
+ through `list_markets(q="btc")` (free-text search is the `q` filter). Use
145
+ `list_updown` / `get_updown`:
146
+
147
+ ```python
148
+ with PolySimClient() as client:
149
+ # Currently-tradeable BTC 5-minute windows, filtered server-side:
150
+ live = client.list_updown(asset="BTC", interval="5M", live=True)
151
+ window = live[0]
152
+ print(window["slug"]) # btc-updown-5m-1781400900
153
+ print(window["time_range"]) # "9:35PM-9:40PM ET"
154
+ print(window["group_item_threshold"]) # resolution strike (None until the window opens)
155
+
156
+ # Outcome tokens live in the nested markets[] array (JSON-string fields):
157
+ nested = window["markets"][0]
158
+ print(nested["outcomes"]) # '["Up", "Down"]'
159
+ print(nested["outcome_prices"]) # '["0.595", "0.405"]'
160
+ cid = window["condition_id"]
161
+ ```
162
+
163
+ `interval` is one of `5M` / `15M` / `1H` / `4H` / `daily` (**uppercase**).
164
+ `live=True` keeps only `active and not closed and not resolved` windows.
165
+
166
+ The **live underlying spot price** plus the available assets/intervals come from
167
+ the full payload via `get_updown`:
168
+
169
+ ```python
170
+ payload = client.get_updown(asset="BTC")
171
+ btc = (payload.get("crypto_prices") or {}).get("BTC") or {}
172
+ print(btc.get("price")) # 64588.0 — live BTC/USD (coingecko)
173
+ print(payload["available_intervals"]) # ['5M', '15M', '1H', '4H', 'daily']
174
+ print(payload["interval_counts"]) # {'5M': 169, '15M': 402, ...}
175
+ ```
176
+
177
+ > The spot price can be momentarily absent right at a window boundary (the
178
+ > payload is cached and the feed can lag a second or two), so read it
179
+ > defensively with `.get(...)` rather than chained `[...]` indexing.
180
+
181
+ ### Pricing an Up/Down market
182
+
183
+ The raw order book (`get_book`) on an Up/Down market is a **synthetic
184
+ placeholder** — its `asks[0]` sits near ~0.99 and is not a real resting quote.
185
+ For price, use the market's own fields instead:
186
+
187
+ - `window["live_price"]` → `{"buy": 0.595, "sell": 0.405, ...}` (current marketable prices)
188
+ - `nested["outcome_prices"]` → the latest Up/Down implied probabilities
189
+ - the realised `price` returned by `place_order` — the SDK fills against the real
190
+ internal book and reports the true fill price, `fee`, and `book_walk_levels`
191
+
192
+ A market order with a worst-price cap still fills correctly regardless; just
193
+ don't read `get_book(...)["asks"][0]` as a tradeable quote on these markets.
194
+
195
+ > **Drop-in `polysim_clob_client` users:** `get_midpoint`, `get_price`,
196
+ > `get_spread` and `calculate_market_price` read the outcome token's **synthetic
197
+ > ~0.99 ladder** on Up/Down markets — they are *not* the underlying asset price.
198
+ > For the asset, use the native reads below.
199
+
200
+ ### Up/Down for HFT: strike, spot, and a push feed
201
+
202
+ The two numbers an Up/Down strategy actually trades on — the **strike**
203
+ ("price to beat") and the **live underlying spot** — have dedicated reads on the
204
+ native client, plus a push stream and a few pure helpers:
205
+
206
+ ```python
207
+ from polysim_sdk import PolySimClient
208
+ from polysim_sdk import updown
209
+
210
+ with PolySimClient() as client:
211
+ live = client.list_updown(asset="BTC", interval="5M", live=True)
212
+ window = updown.next_to_expire(live) or live[0] # the contract closing soonest
213
+ cid = window["condition_id"]
214
+
215
+ strike = client.get_price_to_beat(cid)["price"] # GET /prices/ptb/{cid}; 404 = not set yet
216
+ spot = client.get_spot("BTC")["price"] # GET /prices/live/BTC — live underlying
217
+ # all spots in one call: client.get_spots()["prices"]
218
+
219
+ print(updown.ptb_distance(spot, strike)) # signed price units; >0 ⇒ "Up" in the money
220
+ print(updown.ptb_distance_bps(spot, strike)) # same, in bps of the strike
221
+ print(updown.seconds_to_expiry(window)) # time left on the window
222
+ ```
223
+
224
+ `get_price_to_beat` raises `ApiError` with `status_code == 404` while a window's
225
+ strike is still pending — that is "not set yet", not "market absent". It accepts
226
+ a `condition_id` **or** an outcome-token id. Its `source` field tells you the
227
+ provenance: `polymarket_open_price` / `polymarket_scrape` / `gamma_event_metadata`
228
+ (Polymarket's own reported strike) and `chainlink_onchain` / `chainlink_timeline`
229
+ (the resolution oracle) are the settlement strike; `gamma_api` / `cryptocompare`
230
+ are best-effort fallbacks — treat them as indicative.
231
+
232
+ The `polysim_sdk.updown` helpers are pure functions over the row dicts (no
233
+ network, tolerant of missing fields): `seconds_to_expiry`, `is_window_open`,
234
+ `price_to_beat` (reads the strike off a row you already have), `ptb_distance` /
235
+ `ptb_distance_bps`, `open_windows`, `next_to_expire`, plus the `ASSETS` /
236
+ `INTERVALS` vocab tuples. For a **streaming** tap on the underlying, see
237
+ [SSE: live underlying spot](#sse-live-underlying-spot) below.
238
+
239
+ ### New-market warm-up: retry order placement on a 404
240
+
241
+ A **brand-new** market — especially the 5m Up/Down windows that roll every few
242
+ minutes — has a short window after creation before it enters the
243
+ order-validation catalog. An order placed in that window transiently fails with
244
+ a `404` (`code="MARKET_NOT_FOUND"`). The window is short — on the order of ~30s,
245
+ the Up/Down roll cadence — but it is a cadence, **not** a guarantee.
246
+
247
+ The SDK does **not** auto-retry 404s (by design — a 404 is normally permanent),
248
+ so a bot trading freshly-rolled markets should catch and retry that one signal
249
+ with backoff. The native client ships a small opt-in helper that retries **only**
250
+ the warm-up 404 and re-raises everything else (and the 404 itself once the budget
251
+ is spent):
252
+
253
+ ```python
254
+ from polysim_sdk import PolySimClient, retry_on_market_warmup
255
+
256
+ with PolySimClient() as client:
257
+ fill = retry_on_market_warmup(
258
+ lambda: client.place_order(
259
+ market_id=cid, side="BUY", outcome="Up", amount="10", price="0.99",
260
+ ),
261
+ attempts=6, base_delay=2.0, # ~2,4,8,16,30s capped backoff between tries
262
+ )
263
+ ```
264
+
265
+ It wraps any zero-argument callable, so the same helper works with a
266
+ `polysim_clob_client` drop-in call (e.g.
267
+ `retry_on_market_warmup(lambda: clob.create_and_post_order(args))`); the drop-in
268
+ surfaces the same condition as a `PolyApiException` with `status_code == 404`.
269
+ See [Errors](#errors) for the standalone retry-on-404 pattern if you'd rather
270
+ roll your own.
271
+
272
+ ---
273
+
274
+ ## Polymarket compatibility
275
+
276
+ `polysim_clob_client` is a drop-in mirror of Polymarket's
277
+ [`py-clob-client`](https://github.com/Polymarket/py-clob-client) **v1** — the
278
+ `0.x` line, surface-parity with v1 `0.34.x`. Method names, argument shapes, and
279
+ return shapes match v1, so a v1 bot ports by changing three things (import path,
280
+ host, auth) and deleting the on-chain prelude — see
281
+ [Migrating from `py-clob-client`](#migrating-from-py-clob-client) below.
282
+
283
+ Polymarket's newer [`py-clob-client-v2`](https://github.com/Polymarket/py-clob-client-v2)
284
+ is a **separate PyPI package** (`pip install py-clob-client-v2`, import
285
+ `py_clob_client_v2`; current `1.0.1`) and a hard breaking release — it renames the
286
+ package, changes the constructor and the order-signing payload, and moves to pUSD
287
+ collateral. A bot written against v2 will **not** run against this mirror
288
+ unchanged (the `py_clob_client_v2` import and the v2 `create_or_derive_api_key()`
289
+ bootstrap don't exist here). If you're on v2, either pin `py-clob-client<2` for
290
+ the drop-in path, or use the native
291
+ [`polysim_sdk`](#quickstart--native-polysim_sdk) client, which is
292
+ paper-mode-native and not tied to any `py-clob-client` generation.
293
+
294
+ | Polymarket client | Compatibility |
295
+ |---|---|
296
+ | `py-clob-client` v1 (`< 2.0`; latest `0.34.6`) | ✅ Drop-in via `polysim_clob_client` |
297
+ | `py-clob-client-v2` (`1.0.x`) | ❌ Not supported — use `polysim_sdk`, or pin `py-clob-client<2` |
298
+ | unified **py-sdk** (`polymarket-client`, import `polymarket`; `0.1.0b8`) | 🔶 **Paper-mode mirror** via `polysim_polymarket` — sync + async `PublicClient` / `SecureClient` (reads, account/auth, trading) + core streams; on-chain are paper no-ops and Gamma/Data reads are deferred. See [below](#polymarket-py-sdk-v2-mirror) and the [compat matrix](#compat-matrix) |
299
+
300
+ The v2-only concepts — EIP-712 v2 signing, pUSD collateral, protocol-side fees,
301
+ builder codes — have no analog in paper trading, so there is nothing to port:
302
+ you drop them entirely.
303
+
304
+ ---
305
+
306
+ ## Polymarket py-sdk (v2) mirror
307
+
308
+ Polymarket also ships a newer **unified Python SDK**, published to PyPI as
309
+ [`polymarket-client`](https://pypi.org/project/polymarket-client/) and imported
310
+ as `polymarket`. It folds the CLOB, gamma (markets/events), data, RFQ, and
311
+ realtime-stream surfaces into one client and returns **typed pydantic models**
312
+ (`OrderBook`, `Market`, `LastTradePrice`, …) instead of raw dicts.
313
+ `polysim_polymarket` is our **paper-mode mirror** of that SDK — the package we
314
+ call the **v2 mirror** in this repo (the `polysim_clob_client` mirror above is
315
+ v1).
316
+
317
+ It mirrors the unified client family in paper mode: **sync and async**
318
+ `PublicClient` and `SecureClient`, the authenticated **trading** write surface,
319
+ the **account/auth/order** reads, the **on-chain** methods (as paper no-ops), the
320
+ **rewards/builder/RFQ** stubs, and the **core realtime streams** (`market` /
321
+ `user` / `crypto_prices`). What it does *not* mirror are the **Gamma/Data reads**
322
+ (events, series, tags, comments, sports, portfolio/positions, leaderboards) and
323
+ the **rewards-engine** reads — those are documented-deferred. The exact
324
+ support level for every surface area is in the [compat matrix](#compat-matrix)
325
+ below; the precise places paper diverges from real are in the
326
+ [sim→real seam contract](#the-simreal-seam-contract-what-paper-mode-does-and-doesnt-do).
327
+ Read both before you rely on a surface area — this is a **paper-trading** mirror,
328
+ not a drop-in for *everything* py-sdk does.
329
+
330
+ The port is the same mechanical swap as v1 — change the import **prefix**, the
331
+ **host**, and the **auth**:
332
+
333
+ ```diff
334
+ - from polymarket import SecureClient
335
+ + from polysim_polymarket import SecureClient
336
+
337
+ - client = SecureClient(private_key="0x…") # real Polymarket wallet + EIP-712 signing
338
+ + client = SecureClient(host="https://api.polysimulator.com", api_key="ps_live_…")
339
+
340
+ # unchanged from here on — same method names, same keyword-only call shapes,
341
+ # same model field names/types. A read:
342
+ book = client.get_order_book(token_id="711811…")
343
+ # py-sdk OrderBook ordering: bids ascending (best = bids[-1]), asks
344
+ # descending (best = asks[-1]).
345
+ print(book.bids[-1].price, book.asks[-1].price, book.token_id)
346
+
347
+ # …and a trade — flat keyword args, py-sdk's SignedOrder / OrderResponse:
348
+ signed = client.create_market_order(token_id="711811…", side="BUY", amount=10)
349
+ resp = client.post_order(signed) # paper-accepted, not on-chain-settled
350
+ print(resp.order_id, resp.status)
351
+ ```
352
+
353
+ (The `PublicClient` swap is identical — drop the auth entirely:
354
+ `PublicClient(host="https://api.polysimulator.com", api_key="ps_live_…")` against
355
+ `polymarket`'s `PublicClient()`.)
356
+
357
+ The model field names and types (`OrderBook`, `OrderBookLevel`,
358
+ `LastTradePrice`, `PriceHistoryPoint`, `Market` — with its nested `.state`
359
+ `MarketState` — `Page`, `Paginator`, the trading types `OrderSide` / `OrderType`
360
+ / `SignedOrder` / `OrderResponse` / `CancelOrdersResponse`, and the RFQ types) all
361
+ track py-sdk so the swap stays mechanical, and every public name a bot imports is
362
+ re-exported off the package root, exactly as on real Polymarket — including the
363
+ named errors the surface raises (`UserInputError`,
364
+ `InsufficientLiquidityError`, `UnexpectedResponseError`), so
365
+ `from polymarket import UserInputError` survives the prefix swap unchanged. (Like
366
+ py-sdk, `MarketState` itself is *not* promoted to the package root — it's reached
367
+ via `market.state` or `polysim_polymarket.models.MarketState`, never `from
368
+ polysim_polymarket import MarketState`.) The **one** deliberate divergence is the
369
+ error-tree *base* name: those three named errors subclass the
370
+ py-clob-client-lineage `PolyException` / `PolyApiException` base (shared by
371
+ identity with the v1 mirror) rather than py-sdk's `PolymarketError`, so a bot
372
+ that catches the broad base by name needs `except PolyException` here vs `except
373
+ PolymarketError` on real Polymarket; an `except UserInputError` block is
374
+ identical on both:
375
+
376
+ ```python
377
+ from polysim_polymarket import PublicClient, OrderBook, Environment, PolyException, Paginator
378
+ ```
379
+
380
+ ### The sim→real seam contract: what paper mode does and doesn't do
381
+
382
+ This is a **paper-trading** mirror. The call shapes and model fields match py-sdk
383
+ so the port is mechanical, but paper mode is not Polymarket — it has no chain, no
384
+ wallet, and its own market universe. Every place paper deliberately diverges from
385
+ real Polymarket is enumerated here, up front, so a bot author knows exactly what
386
+ they're getting before they rely on a surface area:
387
+
388
+ - **Signing is inert (accepted, never settled on-chain).** The authenticated
389
+ trading write surface IS implemented — `create_limit_order` /
390
+ `create_market_order` / `place_limit_order` / `place_market_order` /
391
+ `post_order` / `post_orders` / `cancel_order` / `cancel_orders` / `cancel_all` /
392
+ `cancel_market_orders`, with py-sdk's flat keyword args and `SignedOrder` /
393
+ `OrderResponse` / `CancelOrdersResponse` return models. But paper trading needs
394
+ no signer, so signing is **accepted-and-inert**: the order is produced with an
395
+ **empty signature** and the *unsigned* paper body is submitted. There is **no
396
+ EIP-712 signing, no on-chain settlement, and no Polygon transaction** — the fill
397
+ happens entirely in PolySimulator's paper matching engine.
398
+ - **Collateral / balances are PAPER.** Your balance is PolySimulator's paper
399
+ balance (the `balance` from `me()` on the native client), not an on-chain USDC
400
+ balance. `get_balance_allowance` reports the paper account's collateral; there
401
+ is no real USDC, no allowance/approval transaction, no funder wallet.
402
+ - **A settled trade carries the per-fill fee RATE, not a fee amount.**
403
+ PolySimulator's matching engine charges and records a real (paper) fee on each
404
+ fill. What it surfaces over the typed read surface is the fee *rate*: a settled
405
+ trade read via `list_account_trades` returns a `ClobTrade` model carrying the
406
+ per-fill fee rate as `fee_rate_bps` (basis points — the category taker rate
407
+ applied to the fill, `0` for fee-free fills), exactly matching py-sdk's
408
+ `ClobTrade`. **What IS surfaced:** the per-fill `fee_rate_bps`. **What is NOT
409
+ surfaced:** a realized per-fill fee *amount* — there is no `fee` / `fee_usdc`
410
+ field on `ClobTrade` (the only model carrying those is `BuilderTrade`, whose
411
+ reads are stubbed — see below), so the sim's debited fee amount is not exposed
412
+ as a typed field on the implemented read surface. **What is NOT mirrored at
413
+ all:** Polymarket **builder** fees (the builder-attribution program — see the
414
+ builder stub row), and any protocol-side / pUSD v2 fee economics; the
415
+ `builder_code=` kwarg on the order builders is accepted for parity but stays
416
+ **inert** (no builder fee taken, no builder-revenue ledger). On maker/taker: the
417
+ sim classifies a marketable-at-placement GTC (one that crosses the book on
418
+ submit) as a **taker** and charges the taker fee, matching Polymarket; only a
419
+ genuinely-resting GTC that is filled later — when the market moves into it — is
420
+ booked as a $0-fee maker. This is a fidelity *match*, not a gap.
421
+ - **The market universe is PolySimulator's, NOT Polymarket's live universe.**
422
+ Reads resolve against the markets PolySimulator carries, which is a curated
423
+ subset of Polymarket plus the platform's own crypto **Up/Down** products. A
424
+ `token_id` / `condition_id` / slug that exists on Polymarket but not in
425
+ PolySimulator's universe will not resolve here. Do not assume `list_markets` /
426
+ `get_market` returns the same set, count, or ordering as real Polymarket.
427
+ - **On-chain methods are instant PAPER no-ops.** `approve_erc20` /
428
+ `approve_erc1155_for_all` / `transfer_erc20` / `split_position` /
429
+ `merge_positions` / `redeem_positions` / `setup_trading_approvals` /
430
+ `setup_gasless_wallet` carry py-sdk's exact signatures, but paper mode accepts
431
+ the call (replicating py-sdk's pre-chain input guards so a bot hits the SAME
432
+ `UserInputError`) and **settles nothing**: no chain write, no ledger mutation,
433
+ no balance change. Each returns a paper transaction handle whose `.wait()`
434
+ returns **instantly** with a valid-format placeholder hash
435
+ (`0x` + 64 hex, `transaction_id=None`). Unlike real py-sdk,
436
+ `redeem_positions` / `merge_positions` do **not** balance-check the position on
437
+ paper. (Address checks are a 40-hex FORMAT check, not an EIP-55 checksum, and
438
+ the returned address is not checksum-normalized — moot on paper, where it's
439
+ never used on a chain.)
440
+ - **Rewards / builder / RFQ are honest stubs.** The rewards/scoring reads return
441
+ honest **empties** (`get_order_scoring` → `False`, the `list_*` rewards reads →
442
+ empty paginators, `get_reward_percentages` → `{}`, …) — the paper rewards engine
443
+ is a separate roadmap item, so a reward-accounting loop runs and truthfully finds
444
+ nothing. The builder-attribution reads (`get_builder_volumes` /
445
+ `list_builder_trades` / `get_builder_fee_rates` / `list_builder_leaderboard`)
446
+ mirror py-sdk's signatures but **raise `NotImplementedError`** — there is no
447
+ builder economy on paper. RFQ has no synchronous `SecureClient` method on py-sdk
448
+ (so the mirror invents none), the RFQ **types** re-export for type-hint parity,
449
+ and any RFQ *action* (incl. the async `open_rfq_session`) **raises
450
+ `NotImplementedError`** — RFQ quoting is not simulated.
451
+ - **Streams are core-topics-only, with documented seams.** `subscribe()` is
452
+ **async-only** (sync clients have no `subscribe`, matching py-sdk) and covers
453
+ py-sdk's **CORE** topics: `market` (`MarketSpec`), `crypto_prices`
454
+ (`CryptoPricesSpec`), and the authenticated `user` feed (`UserSpec`, secure
455
+ client only). The **sports / comments / equity** topics are **deferred** (their
456
+ specs/events aren't shipped). The documented stream seams: the market feed is
457
+ **top-of-book, not L2** (it emits `price_change` / `last_trade_price`, never a
458
+ `book` event — call `get_order_book` for the ladder); `MarketSpec.token_ids` are
459
+ the SDK's **`condition_id:LABEL`** tokens (not raw Polymarket numeric token ids);
460
+ stream id fields are plain `str` (not py-sdk's hex-validated newtypes); and the
461
+ lifecycle market events (`NewMarketEvent`, `MarketResolvedEvent`, …) are defined
462
+ for `match`-parity but never emitted on paper. Full detail in
463
+ [Realtime streams](#realtime-streams-v2-mirror).
464
+ - **Read-model fidelity gaps.** A handful of implemented reads are present but
465
+ *narrower* than py-sdk's (e.g. `Market` is a focused identity+state subset, not
466
+ the full gamma model; `list_markets` accepts py-sdk's full gamma keyword set but
467
+ only forwards the few PolySimulator honours; `get_last_trade_price` reports a
468
+ constant `side="BUY"` from a book snapshot with no trade side; `Decimal`
469
+ string-form may carry extra trailing zeros; `0` is the no-quote sentinel). None
470
+ break the call shape — see [Fidelity gaps](#fidelity-gaps-within-the-implemented-surface).
471
+
472
+ Because the real py-sdk is a **superset**, swapping back to real Polymarket only
473
+ ever *adds* capability over this seam — it never breaks a bot that stuck to the
474
+ mirrored surface and respected the seams above.
475
+
476
+ ### Compat matrix
477
+
478
+ > Pinned to **`polymarket-client==0.1.0b8`** — parity is re-locked against this exact pin by the full-surface parity gate; when the pin bumps, this matrix + the badge bump with it.
479
+
480
+ Support level for every py-sdk surface area, cross-checked against what's
481
+ actually implemented in `polysim_polymarket`:
482
+
483
+ | Surface area | Support | Notes |
484
+ |---|---|---|
485
+ | **Public reads** (CLOB market data) | ✅ **Full parity** | `get_order_book(s)` / `get_midpoint(s)` / `get_price(s)` / `get_spread(s)` / `get_last_trade_price(s)` / `get_price_history` / `estimate_market_price` / `get_market` / `list_markets` — sync + async, identical call shapes & model fields (subset/sentinel gaps documented; see [Fidelity gaps](#fidelity-gaps-within-the-implemented-surface) for the `Market` subset + the ignored `list_markets` filters). |
486
+ | **Secure reads** (CLOB market data) | ✅ **Full parity** | The secure client shares the public reads, identical signatures. |
487
+ | **Account / auth** | 🟡 **Paper seam** | `fetch_api_keys` / `delete_api_key` / `get_balance_allowance` / `is_gasless_ready` / `get_closed_only_mode` / `get_notifications` / `get_order` / `list_open_orders` / `list_account_trades` implemented over paper auth (single `ps_live_*` key). Note: `is_gasless_ready` / `get_closed_only_mode` / `get_notifications` are **constant honest stubs** (return `True` / `False` / `()` with **no network call**), distinct from `get_balance_allowance` / `get_order` / `list_open_orders` / `list_account_trades`, which are genuinely backed by the paper API. py-sdk's wallet-auth `end_authentication` and the `drop_notifications` write are **deferred**. |
488
+ | **Trading** (orders) | 🟡 **Paper seam** | Full write surface (`create_*` / `place_*` / `post_order(s)` / `cancel_*`) with py-sdk's flat kwargs + `SignedOrder` / `OrderResponse` / `CancelOrdersResponse`. **Signing inert, settled in paper engine, not on-chain.** |
489
+ | **On-chain** (ERC-20/1155, split/merge/redeem, approvals) | 🟡 **Paper seam (no-op)** | All methods implemented with exact signatures; each is an **instant no-op** returning a placeholder tx handle — no chain write, no balance/ledger mutation, no balance-check. |
490
+ | **Rewards / scoring** | ⚪ **Stub (honest empties)** | `get_order(s)_scoring` / `list_*` rewards / `get_total_earnings_*` / `get_reward_percentages` implemented but return honest empties — no paper rewards engine yet. |
491
+ | **Builder attribution** | ⚪ **Stub (NotImplementedError)** | `get_builder_volumes` / `list_builder_trades` / `get_builder_fee_rates` / `list_builder_leaderboard` mirror signatures, raise `NotImplementedError` — no builder economy on paper. |
492
+ | **RFQ** | ⚪ **Stub (types + NotImplementedError)** | RFQ **types** re-export for type-hint parity; py-sdk has no sync `SecureClient` RFQ method (mirror invents none); the async `open_rfq_session` and any RFQ action raise `NotImplementedError`. |
493
+ | **Market stream** | 🟡 **Paper seam** | `subscribe(MarketSpec)` → `price_change` / `last_trade_price` over `/v1/ws/prices`. **TOB, not L2** (no `book` event); `condition_id:LABEL` token keying; lifecycle events defined-but-never-emitted. |
494
+ | **User stream** | 🟡 **Paper seam** | `subscribe(UserSpec)` (secure only) → order/trade fills over the authenticated executions channel; `UserSpec.markets` is a client-side filter; lean frames with honest derivations. |
495
+ | **Crypto stream** | 🟡 **Paper seam** | `subscribe(CryptoPricesSpec)` → Binance / Chainlink ticks, routed by exact source label, over the spot SSE feed. |
496
+ | **Sports / comments / equity streams** | 🔴 **Deferred** | `SportsSpec` / `CommentsSpec` / `EquityPricesSpec` (+ the `RtdsSpec` base alias) and their events are **not shipped**; pass a single CORE spec per `subscribe()`. |
497
+ | **Gamma / Data reads** (events, series, tags, comments, sports, portfolio, positions, leaderboards, combo, search, accounting export) | 🔴 **Deferred** | Not implemented on `PublicClient` / `SecureClient` (calling one raises `AttributeError`). Real py-sdk is a superset, so the swap to real Polymarket only *adds* them. |
498
+
499
+ Legend — **✅ Full parity**: same behaviour & shape as py-sdk (documented
500
+ narrowness aside). **🟡 Paper seam**: implemented with paper-mode semantics
501
+ (see the seam contract). **⚪ Stub**: importable & callable, returns an honest
502
+ empty or raises `NotImplementedError` — no fabricated data. **🔴 Deferred**: not
503
+ implemented yet; absent from the surface.
504
+
505
+ ### Implemented surface — method reference
506
+
507
+ The **CLOB market-data READ** core (the foundation, shared by every client and
508
+ backed by the same proven read path as the v1 mirror):
509
+
510
+ | Method | Returns |
511
+ |---|---|
512
+ | `get_order_book(*, token_id)` / `get_order_books(*, token_ids)` | `OrderBook` / `tuple[OrderBook, …]` |
513
+ | `get_midpoint(*, token_id)` / `get_midpoints(*, token_ids)` | `Decimal` / `dict[str, Decimal]` |
514
+ | `get_price(*, token_id, side)` / `get_prices(*, requests)` | `Decimal` / `dict[str, dict[side, Decimal]]` |
515
+ | `get_spread(*, token_id)` / `get_spreads(*, token_ids)` | `Decimal` / `dict[str, Decimal]` |
516
+ | `get_last_trade_price(*, token_id)` / `get_last_trade_prices(*, token_ids)` | `LastTradePrice` / `tuple[LastTradePriceForToken, …]` |
517
+ | `get_price_history(*, token_id, …)` | `tuple[PriceHistoryPoint, …]` (a bare tuple, like py-sdk) |
518
+ | `estimate_market_price(*, token_id, side, …)` | `Decimal` (marginal/limit price — the worst book level touched to fill, like py-sdk; `FOK` underfill raises `InsufficientLiquidityError`, `FAK` falls back to the deepest level) |
519
+ | `get_market(*, id=…/slug=…)` | `Market` (with a nested `.state`) |
520
+ | `list_markets(*, …)` | `Paginator[Market]` — drive with `.first_page()` / `.iter_items()` |
521
+
522
+ The **authenticated `SecureClient`** adds, on top of those reads (see the
523
+ [compat matrix](#compat-matrix) for support level and the
524
+ [seam contract](#the-simreal-seam-contract-what-paper-mode-does-and-doesnt-do)
525
+ for paper semantics):
526
+
527
+ | Group | Methods |
528
+ |---|---|
529
+ | Account / auth | `fetch_api_keys` / `delete_api_key` / `get_balance_allowance` / `is_gasless_ready` / `get_closed_only_mode` / `get_notifications` / `get_order` / `list_open_orders` / `list_account_trades` |
530
+ | Trading | `create_limit_order` / `create_market_order` / `place_limit_order` / `place_market_order` / `post_order` / `post_orders` / `cancel_order` / `cancel_orders` / `cancel_all` / `cancel_market_orders` |
531
+ | On-chain (paper no-ops) | `approve_erc20` / `approve_erc1155_for_all` / `transfer_erc20` / `split_position` / `merge_positions` / `redeem_positions` / `setup_trading_approvals` / `setup_gasless_wallet` |
532
+ | Rewards / scoring (honest stubs) | `get_order_scoring` / `get_orders_scoring` / `list_current_rewards` / `list_market_rewards` / `list_user_earnings_for_day` / `get_total_earnings_for_user_for_day` / `list_user_earnings_and_markets_config` / `get_reward_percentages` |
533
+ | Builder (NotImplementedError) | `get_builder_volumes` / `list_builder_trades` / `get_builder_fee_rates` / `list_builder_leaderboard` |
534
+
535
+ Develop and paper-test a bot here against PolySimulator (no wallet, no key, no
536
+ gas), then run the **same code** on real Polymarket by swapping the prefix back to
537
+ `polymarket`, pointing at the real host, and supplying real credentials.
538
+
539
+ **Async twins.** Both clients have async counterparts — `AsyncPublicClient` (the
540
+ async twin of `PublicClient`) and `AsyncSecureClient` (the async twin of
541
+ `SecureClient`) — exposing the identical surface with every per-request method an
542
+ `async def` coroutine (the `list_*` reads stay synchronous, returning an
543
+ `AsyncPaginator` you then `await`). Construct with `AsyncSecureClient(api_key=…)`
544
+ or `await AsyncSecureClient.create(private_key=…)`, drive with `await`, and use
545
+ `async with AsyncSecureClient(…) as client:` for lifecycle — exactly as py-sdk's
546
+ async client does. The async twins share the same transport-free logic as the sync
547
+ clients (no second copy), so their behaviour is identical by construction.
548
+
549
+ ### Seam details — implementation reference
550
+
551
+ The [seam contract](#the-simreal-seam-contract-what-paper-mode-does-and-doesnt-do)
552
+ above is the high-level "what diverges"; this section is the precise
553
+ implementation reference for each seam — the exact input guards, return values,
554
+ and edge behaviours. (A genuinely *deferred* method — the Gamma/Data reads — is
555
+ absent and raises `AttributeError`, which is honest: the surface simply isn't
556
+ there yet, rather than a stub that pretends and fails later. The stubs below
557
+ instead exist, are callable, and return honest empties / raise
558
+ `NotImplementedError`.)
559
+
560
+ - **EIP-712 signing & on-chain machinery** — the real-Polymarket signer /
561
+ builder-auth path. Paper trading needs no signer, so signing is
562
+ **accepted-and-inert**: the authenticated `SecureClient`'s **trading write
563
+ surface IS implemented** (`create_limit_order` / `create_market_order` /
564
+ `place_limit_order` / `place_market_order` / `post_order` / `post_orders` /
565
+ `cancel_order` / `cancel_orders` / `cancel_all` / `cancel_market_orders`, with
566
+ py-sdk's flat keyword args and `SignedOrder` / `OrderResponse` /
567
+ `CancelOrdersResponse` return models) — it just produces an inert-signed order
568
+ (empty signature) and submits the unsigned paper body.
569
+ - **On-chain methods are PAPER no-ops.** `approve_erc20` /
570
+ `approve_erc1155_for_all` / `transfer_erc20` / `split_position` /
571
+ `merge_positions` / `redeem_positions` / `setup_trading_approvals` /
572
+ `setup_gasless_wallet` are **implemented** with py-sdk's exact signatures, but
573
+ paper mode accepts the call (validating inputs) and **does NOT settle on-chain
574
+ or mutate any paper state** (no ledger write, no balance change): each returns a
575
+ paper transaction handle whose `.wait()` returns **instantly** with a
576
+ valid-format placeholder `TransactionOutcome` (`0x` + 64 hex hash,
577
+ `transaction_id=None`). In particular — unlike real py-sdk, which consults
578
+ on-chain ERC-1155 balances — `redeem_positions` / `merge_positions` do NOT
579
+ balance-check the position on paper, so they always succeed (the paper position
580
+ ledger isn't wired into the on-chain methods in this gate). py-sdk's pre-chain
581
+ input guards are replicated so a bot hits the SAME `UserInputError` in paper as
582
+ in prod (exactly-one of
583
+ `condition_id`/`legs`; exactly-one of `condition_id`/`market_id`/`position_id`;
584
+ positive amount on a combo split). **Address checks are a 40-hex FORMAT check,
585
+ NOT an EIP-55 checksum.** The accepted shape matches py-sdk's
586
+ `to_checksum_address` acceptance set — a 40-hex address with an **optional**
587
+ `0x`/`0X` prefix, case-insensitive — so the guard accepts every input py-sdk
588
+ accepts and rejects the same malformed ones (wrong length, non-hex). Paper
589
+ trading never touches a chain, so to keep the dependency surface thin the mirror
590
+ does not pull in `eth-utils`/`web3`/`eth_account`; that means — unlike py-sdk's
591
+ `to_checksum_address`, which normalizes any accepted address to its
592
+ EIP-55-checksummed form for on-chain use — the mirror does NOT compute the
593
+ checksum normalization and returns the address unchanged (moot on paper, where
594
+ the address is never used on a chain).
595
+ - **Rewards / scoring reads are honest empty stubs.** `get_order_scoring` →
596
+ `False`, `get_orders_scoring` → all-`False` dict, the `list_*` rewards reads →
597
+ empty paginators, `get_total_earnings_for_user_for_day` → `()`,
598
+ `get_reward_percentages` → `{}`. The paper **rewards engine** is a separate
599
+ backend roadmap item, so these return honest empties with no fabricated data —
600
+ a bot's reward-accounting loop runs and truthfully finds nothing (rewards
601
+ aren't earned on paper).
602
+ - **Builder attribution raises `NotImplementedError`.** `get_builder_volumes` /
603
+ `list_builder_trades` / `get_builder_fee_rates` / `list_builder_leaderboard`
604
+ mirror py-sdk's signatures but raise `NotImplementedError("Builder attribution
605
+ is not simulated in PolySimulator paper mode.")` — there is no builder fee, no
606
+ builder revenue ledger, no builder leaderboard on paper. The `builder_code=`
607
+ kwarg on the order builders stays inert (no builder fee).
608
+ - **Collateral / balances / positions** — the account balance/order reads ARE
609
+ implemented (`get_balance_allowance` / `get_order` / `list_open_orders` /
610
+ `list_account_trades`); the wider portfolio/positions reads are deferred (see
611
+ the Gamma/Data row of the [compat matrix](#compat-matrix)).
612
+ - **Realtime streams (CORE topics ARE implemented).** The async clients'
613
+ `subscribe()` covers py-sdk's **CORE** stream topics — `market`
614
+ (`MarketSpec` → book / price_change / last_trade), `crypto_prices`
615
+ (`CryptoPricesSpec` → Binance / Chainlink ticks), and the authenticated `user`
616
+ feed (`UserSpec` → order / trade fills, secure client only) — backed by our
617
+ `polysim_sdk` WS + SSE transport. See the **Realtime streams (v2 mirror)**
618
+ section below for the topic→transport map, the deferred topics, and the seams.
619
+ Streaming is **async-only** (the sync `PublicClient` / `SecureClient` have no
620
+ `subscribe`, mirroring py-sdk). The **sports / comments / equity** topics are
621
+ DEFERRED (their specs/events aren't shipped).
622
+ - **RFQ** — the RFQ session flow is not simulated. The **RFQ types**
623
+ (`RfqQuoteRequestEvent`, `RfqSession`, the enums, the rejection errors, …) DO
624
+ re-export from the package root so a maker bot's type hints survive the prefix
625
+ swap; py-sdk has no synchronous `SecureClient` RFQ method, so the mirror
626
+ invents none, and any RFQ *action* raises `NotImplementedError("RFQ quoting is
627
+ not simulated in PolySimulator paper mode.")`.
628
+ - **`Paginator` dataframe exports** — `.to_pandas` / `.to_polars` / `.to_arrow`
629
+ (they need pandas/polars/pyarrow) are not shipped; the paginator's
630
+ `.first_page()` / `.iter_items()` / iteration surface is here.
631
+
632
+ Because the real py-sdk is a **superset**, the swap to real Polymarket only ever
633
+ *adds* these — it never breaks a bot that stuck to the implemented surface.
634
+
635
+ ### Fidelity gaps within the implemented surface
636
+
637
+ A handful of implemented methods are present but **narrower** than py-sdk's. None
638
+ break the prefix swap (the field names and call shapes match), but a bot that
639
+ relies on the listed behaviour will see *more* on real Polymarket than the
640
+ mirror provides:
641
+
642
+ - **`Market` is a focused subset.** The mirror's `Market` carries only the
643
+ identity fields (`id`, `condition_id`, `question`, `slug`) plus a focused
644
+ nested `.state` (`active` / `closed` / `neg_risk`). py-sdk's `Market` is a
645
+ deeply-nested gamma model — the **`outcomes`, per-outcome `prices`, and the
646
+ `metrics` / `volume` / `liquidity` blocks are not present here**, and
647
+ `market.state` omits py-sdk's wider fields (`archived`, `accepting_orders`,
648
+ `enable_order_book`, `start_date` / `end_date` / `closed_time`). The mirror
649
+ also **does not hex-validate `condition_id`** and **does not reject
650
+ non-binary markets** the way py-sdk's `Market` model does — a payload py-sdk
651
+ would raise `UnexpectedResponseError` on may bind here. Read only the focused
652
+ identity+state subset for a clean swap; the rest lands when `Market` widens.
653
+ - **`list_markets` accepts py-sdk's full gamma keyword set but only forwards a
654
+ few.** Only the filters PolySimulator's `GET /v1/markets` honours (`closed`,
655
+ `order`→`sort`, `ascending`) reach the server; **every other gamma keyword
656
+ (`liquidity_num_min/max`, `volume_num_min/max`, `tag_id`, `clob_token_ids`,
657
+ `question_ids`, `start_date_*` / `end_date_*`, …) is accepted for signature
658
+ parity and silently ignored**. The call won't error, but the result set is
659
+ *not* filtered by an ignored knob. (On real Polymarket every one of these
660
+ filters applies server-side.)
661
+ - **`get_last_trade_price` always reports side `BUY`.** PolySim's book snapshot
662
+ carries `last_trade_price` but **no trade side**, so the mirror fills py-sdk's
663
+ required `side` field with a constant `"BUY"`. Don't branch on the last-trade
664
+ side against the mirror — it isn't real provenance; on Polymarket it reflects
665
+ the actual maker/taker side.
666
+ - **`Decimal` string-form (trailing zeros) may differ.** The mirror computes
667
+ prices from PolySim's `/v1/book` and quantises to the 4-decimal grid, so a
668
+ midpoint/price/spread can render as `Decimal("0.5000")` where py-sdk's
669
+ server-computed value renders `Decimal("0.5")`. The **numeric value is equal**
670
+ (`==` and arithmetic match — the behavioural-parity suite asserts this), but
671
+ `str(value)` and `value.as_tuple()` can differ in trailing zeros. Compare by
672
+ numeric value, never by string form, for a clean swap.
673
+ - **`0` is the no-quote sentinel.** When a token's book has no two-sided quote,
674
+ `get_midpoint` / `get_price` / `get_spread` return `Decimal("0")` (py-sdk's
675
+ "no value available" sentinel) rather than `None` or an error. A genuine `0`
676
+ and a missing quote are indistinguishable — treat a `0` result as "no quote",
677
+ not as a real price of zero.
678
+
679
+ ### Realtime streams (v2 mirror)
680
+
681
+ The async clients mirror py-sdk's `subscribe()` for the **CORE** stream topics,
682
+ backed by our `polysim_sdk` WS + SSE transport. A consumer iterates a
683
+ `SubscriptionHandle` and closes it (or uses it as an async context manager):
684
+
685
+ ```python
686
+ from polysim_polymarket import AsyncSecureClient
687
+ from polysim_polymarket.streams import MarketSpec, CryptoPricesSpec, UserSpec
688
+
689
+ async with await AsyncSecureClient.create(api_key="ps_live_…") as client:
690
+ async with await client.subscribe(MarketSpec(token_ids=["…"])) as h:
691
+ async for ev in h: # MarketPriceChangeEvent / MarketLastTradePriceEvent
692
+ print(ev.payload.market, ev.type)
693
+ ```
694
+
695
+ The stream surface lives in `polysim_polymarket.streams` (the specs, the event
696
+ types, `SubscriptionHandle`) — **exactly as py-sdk keeps it in
697
+ `polymarket.streams`. Neither package promotes any stream name to its package
698
+ root**, so nothing stream-related is re-exported from `polysim_polymarket` (the
699
+ re-export subset is empty by design).
700
+
701
+ **CORE topics → transport.** Each topic maps to one `polysim_sdk` stream:
702
+
703
+ | Spec | Topic | Events emitted | Transport |
704
+ |---|---|---|---|
705
+ | `MarketSpec` | `market` | `MarketPriceChangeEvent`, `MarketLastTradePriceEvent` | `ws.aprices_stream` (`/v1/ws/prices`) |
706
+ | `CryptoPricesSpec` | `prices.crypto.{binance,chainlink}` | `CryptoPricesBinanceEvent` / `CryptoPricesChainlinkEvent` | `sse.aspot_stream` (`/prices/stream`) |
707
+ | `UserSpec` *(secure only)* | `user` | `UserTradeEvent`, `UserOrderEvent` | `ws.aexecutions_stream` (`/v1/ws/executions`) |
708
+
709
+ `subscribe()` is **async-only** (the sync clients have no `subscribe`, mirroring
710
+ py-sdk). The handle is a bounded queue with **drop-oldest backpressure**: under a
711
+ slow consumer it drops the oldest events and counts the losses in
712
+ `handle.dropped`. Pass `queue_size=` (a mirror-only keyword) to size it.
713
+
714
+ **Seams — documented, not fabricated.** Because PolySimulator's push surface is
715
+ leaner than Polymarket's, the mirror is explicit where a py-sdk field has no
716
+ real provenance:
717
+
718
+ - **Auth handshake (user stream).** The `user` feed mints a short-lived WS JWT
719
+ from the secure client's API key (`ws_token()`) and connects to the
720
+ authenticated `/v1/ws/executions` channel — so it's scoped to that one account.
721
+ There is no per-subscription credential; `UserSpec.markets`, when set, is
722
+ applied as a **client-side filter** in the adapter (the channel delivers all of
723
+ the account's fills).
724
+ - **`MarketSpec.token_ids` are the SDK's `condition_id:LABEL` tokens** (the
725
+ same form `get_*` and trading use) — **not** raw Polymarket numeric token ids.
726
+ The prices WS subscribes by `condition_id`, so the opener strips each token's
727
+ `:LABEL` suffix (a **generic last-colon split**, so non-binary `UP`/`DOWN`
728
+ labels strip correctly — not the binary-only `_split_token`), de-duplicates,
729
+ and subscribes those condition ids. Each delivered frame carries per-outcome
730
+ entries with a `label` (`Yes`/`No`/`Up`/`Down`) and the Polymarket
731
+ **CLOB-numeric** `token_id`; that raw digit is a *different namespace* from the
732
+ SDK token, so the adapter does **not** filter on it (it would match nothing).
733
+ Instead the adapter **derives** each outcome's SDK token
734
+ `f"{condition_id}:{LABEL}"` from the frame's `market_id` + outcome `label` and
735
+ both filters on and emits that — so a `MarketSpec` built from the SDK's own
736
+ `condition_id:LABEL` tokens (e.g. `["0xCID:YES", "0xCID:NO"]`) subscribes
737
+ `["0xCID"]` AND receives correctly-filtered events for those outcomes, end to
738
+ end. The emitted event's `token_id` is the `condition_id:LABEL` form a bot
739
+ uses for reads/trading, never the backend CLOB digit. (A raw pm numeric token
740
+ id is not a valid `MarketSpec.token_id` here.)
741
+ - **No `book` event from the market stream.** `/v1/ws/prices` is a top-of-book
742
+ cache, not an L2 ladder feed — so the market stream emits `price_change` and
743
+ `last_trade_price` but never a full `book` event. (Call `get_order_book` for
744
+ the ladder.)
745
+ - **Stream id fields are plain `str`.** Token / condition / order id fields on
746
+ the stream-event models (`token_id`, `market`, `id`, `taker_order_id`, …) are
747
+ plain `str`, consistent with the mirror-wide id-typing decision — they are
748
+ **not** py-sdk's hex-validated `TokenId` / `CtfConditionId` newtypes, so no
749
+ hex-shape validation is applied to ids arriving on the wire.
750
+ - **Custom-feature / lifecycle market events are defined for parity but never
751
+ emitted.** `MarketBestBidAskEvent`, `NewMarketEvent`, `MarketResolvedEvent`,
752
+ and `MarketTickSizeChangeEvent` are part of the `MarketEvent` union (so a ported
753
+ bot's imports and `match`-on-`type` resolve) but the paper stream produces none
754
+ of them — `MarketSpec(custom_feature_enabled=True)` is accepted for signature
755
+ parity and is otherwise inert.
756
+ - **Lean user frames, honest derivation.** The backend fill frame carries
757
+ `market_id` + `outcome` but **no CLOB token/asset id**, so the event's
758
+ `token_id` is *derived* — `f"{market_id}:{OUTCOME}"`, the SDK's canonical token
759
+ convention (the inverse of `_split_token`, the same form `get_*`/trading use),
760
+ not faked from the order id. `id`/`taker_order_id` keep the fill's real
761
+ `order_id` (those are order ids). Remaining py-sdk fields the frame lacks get
762
+ honest defaults: the order's `original_size` == `size_matched` == the filled
763
+ `quantity` with `order_event_type="UPDATE"`, `status="MATCHED"`. A fill missing
764
+ its `outcome` yields no event (no honest token could be built).
765
+ - **`last_trade_price` side + size are read from the frame top level.** The
766
+ prices producer stamps the most-recent trade's `last_trade_side` /
767
+ `last_trade_size` at the **frame top level** (not on the per-outcome entry,
768
+ which carries only the trade *price*). The adapter reads them there and emits
769
+ the real side — a SELL trade yields `side="SELL"`, never a fabricated `BUY`. If
770
+ a frame ever lacks the top-level side, the `last_trade_price` event is dropped
771
+ rather than mislabeled.
772
+ - **Crypto topic routing is by exact source label.** The Binance feed's wire
773
+ `source` is `polymarket_rtds` (with `relay_binance` as a fallback-relay label);
774
+ Chainlink's is `chainlink_rtds`. The adapter routes by exact membership in
775
+ those label sets — `prices.crypto.binance` receives the live Binance ticks and
776
+ Binance ticks never leak into a `prices.crypto.chainlink` subscription.
777
+
778
+ **DEFERRED topics.** py-sdk's `polymarket.streams` also ships `sports`
779
+ (`SportsSpec` / `SportsEvent`), `comments` (`CommentsSpec` / `CommentsEvent` /
780
+ reactions), and `prices.equity.pyth` (`EquityPricesSpec` / `EquityPricesEvent`),
781
+ plus the `RtdsSpec` / `StreamEvent` aliases and the merged multi-spec
782
+ `subscribe(Sequence[...])`. **None of those are shipped here** — pass a single
783
+ CORE spec per `subscribe()` call. Because real py-sdk is a superset, the swap to
784
+ real Polymarket only *adds* them.
785
+
786
+ ---
787
+
788
+ ## Migrating from `py-clob-client`
789
+
790
+ > The import below is the **v1** path (`py_clob_client`). `py-clob-client-v2`
791
+ > (`py_clob_client_v2`) is a different package and is out of scope — see
792
+ > [Polymarket compatibility](#polymarket-compatibility) above.
793
+
794
+ If you have a Polymarket bot, you change **three things** and delete the on-chain
795
+ prelude. Everything else — method names, argument shapes, return shapes — stays.
796
+
797
+ ```diff
798
+ - from py_clob_client.client import ClobClient
799
+ - from py_clob_client.clob_types import OrderArgs, OrderType
800
+ + from polysim_clob_client.client import ClobClient
801
+ + from polysim_clob_client.clob_types import OrderArgs, OrderType
802
+
803
+ - client = ClobClient(
804
+ - host="https://clob.polymarket.com",
805
+ - key=PRIVATE_KEY, # your wallet's private key
806
+ - chain_id=POLYGON,
807
+ - signature_type=1,
808
+ - funder=PROXY_WALLET_ADDRESS,
809
+ - )
810
+ - client.set_api_creds(client.create_or_derive_api_creds())
811
+ - # ...plus USDC allowance/approval txns, web3 setup, etc.
812
+ + client = ClobClient(
813
+ + host="https://api.polysimulator.com",
814
+ + key="ps_live_…", # your PolySimulator API key
815
+ + )
816
+
817
+ # unchanged from here on:
818
+ order = client.create_order(OrderArgs(token_id=tid, price=0.55, size=10, side="BUY"))
819
+ resp = client.post_order(order)
820
+ ```
821
+
822
+ ### What maps how
823
+
824
+ Every method maps by one of three strategies:
825
+
826
+ - **mirror** — identical behaviour, delegated to the HTTP core.
827
+ - **adapt** — translated onto the PolySim REST surface (e.g. `get_midpoint`,
828
+ `get_price`, `get_spread` are computed from `GET /v1/markets/{id}/book`).
829
+ - **stub-noop** — on-chain machinery with no analog (allowances, signing,
830
+ scoring, builder auth). These return a benign canned value and **make no
831
+ network call**; each says so in its docstring so nothing breaks silently.
832
+
833
+ ### `token_id` ↔ `(market_id, outcome)`
834
+
835
+ `py-clob-client` addresses a single outcome token by `token_id`; PolySimulator
836
+ addresses a **market plus an outcome**. The seam: a bare `token_id` is treated as
837
+ the market id with outcome `YES`. Append `":NO"` or `":YES"` to target the other
838
+ side explicitly. **Up/Down markets** carry `Up`/`Down` outcomes, so the same
839
+ colon form also accepts `":UP"` / `":DOWN"` (case-insensitive); the backend
840
+ matches the order outcome case-insensitively, so either case is accepted.
841
+
842
+ ```python
843
+ client.create_order(OrderArgs(token_id="0xMARKET", ...)) # → market 0xMARKET, YES
844
+ client.create_order(OrderArgs(token_id="0xMARKET:NO", ...)) # → market 0xMARKET, NO
845
+ client.create_order(OrderArgs(token_id="0xUPDOWN:UP", ...)) # → Up/Down market, UP
846
+ ```
847
+
848
+ **Reads are true-token-parity; writes use the market+outcome model.** This is an
849
+ intentional asymmetry:
850
+
851
+ - **Book/quote reads** — `get_order_book`, `get_midpoint`, `get_price`,
852
+ `get_spread`, `get_tick_size`, `get_neg_risk`, `get_last_trade_price`,
853
+ `calculate_market_price` — send a **bare** `token_id` to the token-native
854
+ endpoint `GET /v1/book?token_id=...`. This matches Polymarket's CLOB book
855
+ reads exactly: pass the real outcome-token id you already use with
856
+ `py-clob-client` and the quote comes back for *that* token, no `:YES`/`:NO`
857
+ needed. The `condition_id:OUTCOME` colon form still works and routes to the
858
+ condition-id book endpoint (threading the outcome through), but it is a
859
+ PolySimulator convenience extension, not the parity path.
860
+ - **Order writes** — `create_order` / `create_market_order` / `post_order` —
861
+ resolve the `token_id` through the market+outcome seam above and submit to the
862
+ rich `POST /v1/orders` endpoint (with slippage/impact/position telemetry in the
863
+ response). A *bare* token id on the write path is read as a `market_id` with
864
+ the `YES` outcome; if that id isn't a valid market, the server rejects the
865
+ order loudly — it never silently places a different one.
866
+
867
+ If you only ever pass real outcome-token ids (the `py-clob-client` norm), reads
868
+ "just work" with full parity. The `:YES`/`:NO` suffix (and `:UP`/`:DOWN` for
869
+ Up/Down markets) exists for callers who prefer to address PolySimulator markets
870
+ by condition id directly.
871
+
872
+ ### Orders are never signed
873
+
874
+ `create_order` / `create_market_order` return a plain `dict` with **no
875
+ `signature` field** — there is nothing to sign. `post_order` serialises it
876
+ straight to `POST /v1/orders`. The recommended one-call path is
877
+ `create_and_post_order(...)`.
878
+
879
+ ### Auth assertions
880
+
881
+ The three `py-clob-client` auth levels collapse into one. `assert_level_1_auth()`
882
+ and `assert_builder_auth()` are no-ops; `assert_level_2_auth()` raises
883
+ `PolyApiException` only if no API key is configured.
884
+
885
+ ---
886
+
887
+ ## Pagination
888
+
889
+ The native client exposes Python iterators that page transparently:
890
+
891
+ ```python
892
+ from polysim_sdk import PolySimClient
893
+ from polysim_sdk.pagination import iter_markets, iter_orders
894
+
895
+ with PolySimClient() as client:
896
+ for market in iter_markets(client, hot_only=True):
897
+ ...
898
+ for order in iter_orders(client, status="OPEN"):
899
+ ...
900
+ ```
901
+
902
+ The drop-in surface preserves `py-clob-client`'s base64 cursor protocol, so the
903
+ classic loop terminates correctly:
904
+
905
+ ```python
906
+ from polysim_clob_client.constants import END_CURSOR
907
+
908
+ cursor = ""
909
+ while cursor != END_CURSOR:
910
+ page = client.get_markets(cursor)
911
+ handle(page["data"])
912
+ cursor = page["next_cursor"]
913
+ ```
914
+
915
+ ---
916
+
917
+ ## WebSocket streaming
918
+
919
+ ```python
920
+ from polysim_sdk import PolySimClient
921
+ from polysim_sdk.ws import prices_stream, executions_stream
922
+
923
+ with PolySimClient() as client:
924
+ for event in prices_stream(client, ["0xMARKET_A", "0xMARKET_B"]):
925
+ print(event) # blocks; reconnects with a fresh token + backoff
926
+ ```
927
+
928
+ Async generators (`aprices_stream`, `aexecutions_stream`) are available for
929
+ `async for`. The SDK mints a short-lived WS JWT per connection automatically.
930
+
931
+ ### SSE: live underlying spot
932
+
933
+ The WS channel above carries **market** prices. The live **underlying spot**
934
+ (BTC/ETH/SOL/… ticks — the number an Up/Down bet resolves against) comes from the
935
+ public, unauthenticated `/prices/stream` Server-Sent-Events firehose instead:
936
+
937
+ ```python
938
+ from polysim_sdk import PolySimClient
939
+ from polysim_sdk.sse import spot_stream
940
+
941
+ with PolySimClient() as client:
942
+ for event in spot_stream(client, ["BTC", "ETH"], crypto_source="chainlink"):
943
+ if event["event"] == "crypto_price":
944
+ tick = event["data"]
945
+ print(tick["symbol"], tick["price"], tick["source"])
946
+ ```
947
+
948
+ Each event is `{"event": <type>, "data": <payload>}`. The spot-bearing types are
949
+ `crypto_price` and `crypto_price_batch`; `keepalive` arrives every ~5 s. Pass
950
+ `crypto_source="chainlink"` (authoritative for 5m/15m settlement) or `"binance"`
951
+ (denser ~10 Hz ticks); omit for both. With `condition_ids=[...]` the same stream
952
+ also delivers `snapshot` / `market_price` / `orderbook` events. The async twin
953
+ `aspot_stream` is available for `async for`. Both reconnect with exponential
954
+ backoff and a per-connection cache-buster (so a CDN can't coalesce subscribers).
955
+
956
+ ---
957
+
958
+ ## Errors
959
+
960
+ Catch `PolySimError` to handle every SDK-raised error; `PolyApiException` (the
961
+ drop-in alias) is the same class.
962
+
963
+ ```python
964
+ from polysim_sdk.exceptions import (
965
+ EdgeBlockedError,
966
+ PolySimError,
967
+ RateLimitError,
968
+ ValidationError,
969
+ )
970
+
971
+ try:
972
+ fill = client.place_order(...)
973
+ except RateLimitError as exc:
974
+ print(f"backing off for {exc.retry_after}s")
975
+ except ValidationError as exc:
976
+ print(f"bad request: {exc.code} → {exc}")
977
+ except EdgeBlockedError as exc:
978
+ print(f"blocked at the CDN edge — check your User-Agent: {exc}")
979
+ except PolySimError as exc:
980
+ print(f"other API error ({exc.status_code}): {exc}")
981
+ ```
982
+
983
+ The client paces itself (a 50 ms floor between requests) and backs off on
984
+ `429`/`425`/`5xx` using `Retry-After`. Opt out with `floor_interval=0.0` and
985
+ `max_retries=0` to handle pacing yourself.
986
+
987
+ ### New-market warm-up `404` (retry-on-404)
988
+
989
+ The SDK auto-retries `429`/`5xx` but **never** a `404` — a 404 is normally
990
+ permanent. The one benign exception is a **freshly-created market** (most often
991
+ a 5m Up/Down window): for a short window after creation — on the order of ~30s,
992
+ the Up/Down roll cadence, though not a guarantee — it is not yet in the
993
+ order-validation catalog and order placement transiently fails with
994
+ `ApiError(status_code=404, code="MARKET_NOT_FOUND")`. Retry **only** that signal,
995
+ with backoff; re-raise any other error (including a 404 with a different `code`,
996
+ which is a real "not found").
997
+
998
+ Use the shipped helper (recommended) …
999
+
1000
+ ```python
1001
+ from polysim_sdk import PolySimClient, retry_on_market_warmup
1002
+
1003
+ with PolySimClient() as client:
1004
+ fill = retry_on_market_warmup(
1005
+ lambda: client.place_order(
1006
+ market_id=cid, side="BUY", outcome="Up", amount="10", price="0.99",
1007
+ ),
1008
+ attempts=6, base_delay=2.0,
1009
+ )
1010
+ ```
1011
+
1012
+ … or roll your own on the native `ApiError`:
1013
+
1014
+ ```python
1015
+ import time
1016
+ from polysim_sdk import ApiError
1017
+
1018
+ for i in range(6):
1019
+ try:
1020
+ fill = client.place_order(market_id=cid, side="BUY", outcome="Up",
1021
+ amount="10", price="0.99")
1022
+ break
1023
+ except ApiError as exc:
1024
+ if exc.status_code == 404 and exc.code == "MARKET_NOT_FOUND" and i < 5:
1025
+ time.sleep(min(2.0 * 2**i, 30.0)) # capped backoff, then retry
1026
+ continue
1027
+ raise # any other error — and the final 404 — propagates
1028
+ ```
1029
+
1030
+ With the **`polysim_clob_client` drop-in**, the same condition surfaces as a
1031
+ `PolyApiException` with `status_code == 404`; catch it and retry the same way (or
1032
+ pass your drop-in call to `retry_on_market_warmup(lambda: clob.create_and_post_order(...))`,
1033
+ which works with any callable):
1034
+
1035
+ ```python
1036
+ from polysim_clob_client.exceptions import PolyApiException
1037
+
1038
+ try:
1039
+ resp = clob.create_and_post_order(order_args)
1040
+ except PolyApiException as exc:
1041
+ if exc.status_code == 404 and getattr(exc, "code", None) == "MARKET_NOT_FOUND":
1042
+ ... # warm-up — retry with backoff
1043
+ else:
1044
+ raise # any other error — including a 404 with a different code — propagates
1045
+ ```
1046
+
1047
+ ### Troubleshooting: `error code: 1010` / blocked User-Agent
1048
+
1049
+ If a raw HTTP call returns **HTTP 403** with the body `error code: 1010`, the
1050
+ request was blocked at the CDN edge — **not** by the API. The edge rejects
1051
+ Python's stdlib `urllib` default User-Agent (`Python-urllib/x.y`). `requests`,
1052
+ `httpx`, `aiohttp`, and **this SDK** all send User-Agents that pass, so you only
1053
+ hit this with raw `urllib` or a custom client that forwards the stdlib UA.
1054
+
1055
+ This SDK sends a branded `User-Agent: polysim-sdk/<version>` and turns any edge
1056
+ block into a clear `EdgeBlockedError` (an `ApiError`, `code="EDGE_BLOCKED"`). If
1057
+ you must call the API without the SDK, set your own header:
1058
+
1059
+ ```python
1060
+ # raw urllib — set a User-Agent so the edge lets you through
1061
+ import urllib.request, json
1062
+ req = urllib.request.Request(
1063
+ "https://api.polysimulator.com/v1/markets?limit=1",
1064
+ headers={"User-Agent": "my-app/1.0", "X-API-Key": "ps_live_..."},
1065
+ )
1066
+ data = json.load(urllib.request.urlopen(req))
1067
+ ```
1068
+
1069
+ ---
1070
+
1071
+ ## Rate limits
1072
+
1073
+ Authoritative values are returned live by `GET /v1/keys/tiers` (`client.tiers()`).
1074
+ At the time of writing:
1075
+
1076
+ | Tier | rps | rpm | WS conns | Batch | API balance |
1077
+ |---|---|---|---|---|---|
1078
+ | Free | 2 | 120 | 1 | 1 | none — read only |
1079
+ | Pro | 10 | 600 | 3 | 5 | $10K |
1080
+ | Pro+ | 30 | 1800 | 10 | 10 | $25K |
1081
+ | Enterprise | 100 | 6000 | 50 | 25 | custom |
1082
+
1083
+ `free` allows 2 requests/second up to 120/minute and is read-only (no API
1084
+ balance). Use `pro` or above for any continuously-running bot. The table is
1085
+ illustrative — always trust `client.tiers()` for the live values.
1086
+
1087
+ ---
1088
+
1089
+ ## Beta caveats
1090
+
1091
+ During the closed-cohort phase, a few sim behaviours differ from Polymarket.
1092
+ These are known limitations, not bugs:
1093
+
1094
+ 1. **Shared API balance across keys.** Every key a user owns draws on the same
1095
+ balance pool today (the `balance` field returned by `me()`). Treat it as
1096
+ user-scoped, not key-scoped.
1097
+ 2. **Maker/taker classification.** A marketable-at-placement GTC (one that
1098
+ crosses the book on submit) is classified as a **taker** and charged the taker
1099
+ fee, matching Polymarket; only a genuinely-resting GTC that is filled later —
1100
+ when the market moves into it — is booked as a $0-fee maker. The realized
1101
+ per-fill fee *rate* is surfaced as `ClobTrade.fee_rate_bps` (the realized fee
1102
+ *amount* is not a typed field).
1103
+ 3. **Orderbook freshness.** The book cache TTL is 300 s. For markets Polymarket
1104
+ updates less often than that, a fill may revert to displayed midpoint; a ±15%
1105
+ sanity guard bounds the drift. High-volume markets always fill at real ask/bid.
1106
+
1107
+ ---
1108
+
1109
+ ## What's included
1110
+
1111
+ | Path | Purpose |
1112
+ |---|---|
1113
+ | `polysim_sdk/` | Native client: `PolySimClient` (sync) + `AsyncPolySimClient` (async), `ws`, `sse` (underlying-spot stream), `updown` (Up/Down row helpers), `pagination`, `exceptions`, `constants`. |
1114
+ | `polysim_clob_client/` | `py-clob-client` drop-in: `ClobClient` + matching `clob_types`, `constants`, `order_builder`, `exceptions`. |
1115
+ | `polysim_polymarket/` | Unified **py-sdk** (`polymarket`) paper-mode mirror: sync + async `PublicClient` / `SecureClient` (CLOB reads, account/auth, trading), on-chain paper no-ops, rewards/builder/RFQ stubs, and core realtime streams — returning typed pydantic models. See [Polymarket py-sdk (v2) mirror](#polymarket-py-sdk-v2-mirror). |
1116
+ | `scripts/01_balance_and_market.py` | Smallest end-to-end native demo. |
1117
+ | `scripts/02_clob_dropin_demo.py` | The `py-clob-client` drop-in surface end-to-end. |
1118
+ | `scripts/03_async_concurrent.py` | Concurrent reads via the async client. |
1119
+ | `scripts/04_btc_updown.py` | Discover the live BTC Up/Down window: spot, strike, prices, tokens. |
1120
+ | `tests/` | respx-mocked unit tests for both surfaces (no creds, no network). |
1121
+
1122
+ Run the test suite with `pytest`. Lint/type with `ruff check . && mypy polysim_sdk polysim_clob_client polysim_polymarket`.
1123
+
1124
+ ---
1125
+
1126
+ ## License
1127
+
1128
+ [Apache License 2.0](./LICENSE). You may use, modify, and redistribute this
1129
+ SDK — including in commercial and closed-source projects — provided you keep
1130
+ the license and attribution notices (see [`NOTICE`](./NOTICE)). Apache-2.0 also
1131
+ grants an explicit patent license, which is why many companies prefer it over
1132
+ MIT for dependencies.
1133
+
1134
+ The `polysim_clob_client` package mirrors the *public surface* of
1135
+ [`py-clob-client`](https://github.com/Polymarket/py-clob-client) (MIT) for
1136
+ drop-in compatibility; no upstream source is bundled. This project is not
1137
+ affiliated with or endorsed by Polymarket.