polyorderbooks 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,20 @@
1
+ """Official Python client for the PolyOrderbooks API."""
2
+
3
+ from polyorderbooks.client import PolyOrderbooksClient
4
+ from polyorderbooks.exceptions import (
5
+ APIError,
6
+ AuthenticationError,
7
+ NotFoundError,
8
+ PolyOrderbooksError,
9
+ RateLimitError,
10
+ )
11
+
12
+ __all__ = [
13
+ "APIError",
14
+ "AuthenticationError",
15
+ "NotFoundError",
16
+ "PolyOrderbooksClient",
17
+ "PolyOrderbooksError",
18
+ "RateLimitError",
19
+ ]
20
+ __version__ = "0.1.0"
@@ -0,0 +1,86 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from typing import Any
5
+
6
+ import httpx
7
+
8
+ from polyorderbooks.exceptions import (
9
+ APIError,
10
+ AuthenticationError,
11
+ NotFoundError,
12
+ RateLimitError,
13
+ )
14
+
15
+ DEFAULT_BASE_URL = "https://api.polyorderbooks.com"
16
+ DEFAULT_TIMEOUT = 60.0
17
+ ENV_API_KEY = "POLYORDERBOOKS_API_KEY"
18
+
19
+
20
+ def resolve_api_key(explicit: str | None) -> str:
21
+ api_key = explicit or os.environ.get(ENV_API_KEY)
22
+ if not api_key:
23
+ raise ValueError(
24
+ "API key required. Pass api_key=... or set POLYORDERBOOKS_API_KEY."
25
+ )
26
+ return api_key
27
+
28
+
29
+ def build_headers(api_key: str) -> dict[str, str]:
30
+ return {
31
+ "Accept": "application/json",
32
+ "X-API-Key": api_key,
33
+ "User-Agent": "polyorderbooks-python/0.1.0",
34
+ }
35
+
36
+
37
+ def parse_error_message(response: httpx.Response) -> str:
38
+ try:
39
+ payload = response.json()
40
+ except ValueError:
41
+ return response.text or response.reason_phrase
42
+
43
+ if isinstance(payload, dict):
44
+ detail = payload.get("detail")
45
+ if isinstance(detail, str) and detail:
46
+ return detail
47
+ message = payload.get("message")
48
+ if isinstance(message, str) and message:
49
+ return message
50
+ return response.reason_phrase
51
+
52
+
53
+ def raise_for_status(response: httpx.Response) -> None:
54
+ if response.is_success:
55
+ return
56
+
57
+ message = parse_error_message(response)
58
+ kwargs = {"body": None}
59
+ try:
60
+ kwargs["body"] = response.json()
61
+ except ValueError:
62
+ kwargs["body"] = response.text
63
+
64
+ status = response.status_code
65
+ if status == 401:
66
+ raise AuthenticationError(status, message, **kwargs)
67
+ if status == 404:
68
+ raise NotFoundError(status, message, **kwargs)
69
+ if status == 429:
70
+ raise RateLimitError(status, message, **kwargs)
71
+ raise APIError(status, message, **kwargs)
72
+
73
+
74
+ def request_json(
75
+ client: httpx.Client,
76
+ method: str,
77
+ path: str,
78
+ *,
79
+ params: dict[str, Any] | None = None,
80
+ ) -> dict[str, Any]:
81
+ response = client.request(method, path, params=params)
82
+ raise_for_status(response)
83
+ payload = response.json()
84
+ if not isinstance(payload, dict):
85
+ raise APIError(response.status_code, "Expected JSON object response.")
86
+ return payload
@@ -0,0 +1,309 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterator
4
+ from typing import Any, Literal
5
+
6
+ import httpx
7
+
8
+ from polyorderbooks._http import (
9
+ DEFAULT_BASE_URL,
10
+ DEFAULT_TIMEOUT,
11
+ build_headers,
12
+ request_json,
13
+ resolve_api_key,
14
+ )
15
+
16
+ Resolution = Literal["1s", "60s", "1m", "5m", "10m", "15m", "1h", "6h", "1d"]
17
+ SortField = Literal["updated_at", "created_at", "start_date", "end_date", "title"]
18
+ SortOrder = Literal["asc", "desc"]
19
+ TagsMatch = Literal["any", "all"]
20
+
21
+
22
+ class PolyOrderbooksClient:
23
+ """Sync client for the PolyOrderbooks read API."""
24
+
25
+ def __init__(
26
+ self,
27
+ api_key: str | None = None,
28
+ *,
29
+ base_url: str = DEFAULT_BASE_URL,
30
+ timeout: float = DEFAULT_TIMEOUT,
31
+ ) -> None:
32
+ self._api_key = resolve_api_key(api_key)
33
+ self._base_url = base_url.rstrip("/")
34
+ self._client = httpx.Client(
35
+ base_url=self._base_url,
36
+ headers=build_headers(self._api_key),
37
+ timeout=timeout,
38
+ )
39
+
40
+ def close(self) -> None:
41
+ self._client.close()
42
+
43
+ def __enter__(self) -> PolyOrderbooksClient:
44
+ return self
45
+
46
+ def __exit__(self, *args: object) -> None:
47
+ self.close()
48
+
49
+ # --- Utility ---
50
+
51
+ def get_usage(self) -> dict[str, Any]:
52
+ """Return plan, limits, and quota usage for the authenticated API key."""
53
+ return request_json(self._client, "GET", "/v1/usage")
54
+
55
+ # --- Discovery ---
56
+
57
+ def list_series(
58
+ self,
59
+ *,
60
+ search: str | None = None,
61
+ tags: list[str] | str | None = None,
62
+ tags_match: TagsMatch = "any",
63
+ start_date_min: str | None = None,
64
+ start_date_max: str | None = None,
65
+ end_date_min: str | None = None,
66
+ end_date_max: str | None = None,
67
+ sort: SortField = "updated_at",
68
+ order: SortOrder = "desc",
69
+ limit: int | None = None,
70
+ cursor: str | None = None,
71
+ ) -> dict[str, Any]:
72
+ params = self._discovery_params(
73
+ search=search,
74
+ tags=tags,
75
+ tags_match=tags_match,
76
+ start_date_min=start_date_min,
77
+ start_date_max=start_date_max,
78
+ end_date_min=end_date_min,
79
+ end_date_max=end_date_max,
80
+ sort=sort,
81
+ order=order,
82
+ limit=limit,
83
+ cursor=cursor,
84
+ )
85
+ return request_json(self._client, "GET", "/v1/series", params=params)
86
+
87
+ def list_events(
88
+ self,
89
+ *,
90
+ search: str | None = None,
91
+ series_id: str | None = None,
92
+ series_slug: str | None = None,
93
+ sort: SortField = "updated_at",
94
+ order: SortOrder = "desc",
95
+ limit: int | None = None,
96
+ cursor: str | None = None,
97
+ ) -> dict[str, Any]:
98
+ params = self._discovery_params(
99
+ search=search,
100
+ series_id=series_id,
101
+ series_slug=series_slug,
102
+ sort=sort,
103
+ order=order,
104
+ limit=limit,
105
+ cursor=cursor,
106
+ )
107
+ return request_json(self._client, "GET", "/v1/events", params=params)
108
+
109
+ def list_markets(
110
+ self,
111
+ *,
112
+ search: str | None = None,
113
+ event_id: str | None = None,
114
+ event_slug: str | None = None,
115
+ include_closed: bool = False,
116
+ sort: SortField = "updated_at",
117
+ order: SortOrder = "desc",
118
+ limit: int | None = None,
119
+ cursor: str | None = None,
120
+ ) -> dict[str, Any]:
121
+ params = self._discovery_params(
122
+ search=search,
123
+ event_id=event_id,
124
+ event_slug=event_slug,
125
+ include_closed=include_closed,
126
+ sort=sort,
127
+ order=order,
128
+ limit=limit,
129
+ cursor=cursor,
130
+ )
131
+ return request_json(self._client, "GET", "/v1/markets", params=params)
132
+
133
+ def get_market(self, id_or_slug: str) -> dict[str, Any]:
134
+ return request_json(
135
+ self._client, "GET", f"/v1/markets/{id_or_slug}"
136
+ )
137
+
138
+ def list_tags(self) -> dict[str, Any]:
139
+ return request_json(self._client, "GET", "/v1/tags")
140
+
141
+ # --- History ---
142
+
143
+ def get_market_metrics(
144
+ self,
145
+ id_or_slug: str,
146
+ *,
147
+ start_ts: str,
148
+ end_ts: str,
149
+ resolution: Resolution,
150
+ limit: int | None = None,
151
+ cursor: str | None = None,
152
+ ) -> dict[str, Any]:
153
+ return self._history_request(
154
+ f"/v1/markets/{id_or_slug}/metrics",
155
+ start_ts=start_ts,
156
+ end_ts=end_ts,
157
+ resolution=resolution,
158
+ limit=limit,
159
+ cursor=cursor,
160
+ )
161
+
162
+ def get_market_prices(
163
+ self,
164
+ id_or_slug: str,
165
+ *,
166
+ start_ts: str,
167
+ end_ts: str,
168
+ resolution: Resolution,
169
+ limit: int | None = None,
170
+ cursor: str | None = None,
171
+ ) -> dict[str, Any]:
172
+ return self._history_request(
173
+ f"/v1/markets/{id_or_slug}/prices",
174
+ start_ts=start_ts,
175
+ end_ts=end_ts,
176
+ resolution=resolution,
177
+ limit=limit,
178
+ cursor=cursor,
179
+ )
180
+
181
+ def get_market_books(
182
+ self,
183
+ id_or_slug: str,
184
+ *,
185
+ start_ts: str,
186
+ end_ts: str,
187
+ resolution: Resolution,
188
+ limit: int | None = None,
189
+ cursor: str | None = None,
190
+ ) -> dict[str, Any]:
191
+ return self._history_request(
192
+ f"/v1/markets/{id_or_slug}/books",
193
+ start_ts=start_ts,
194
+ end_ts=end_ts,
195
+ resolution=resolution,
196
+ limit=limit,
197
+ cursor=cursor,
198
+ )
199
+
200
+ def get_token_prices(
201
+ self,
202
+ token_id: str,
203
+ *,
204
+ start_ts: str,
205
+ end_ts: str,
206
+ resolution: Resolution,
207
+ limit: int | None = None,
208
+ cursor: str | None = None,
209
+ ) -> dict[str, Any]:
210
+ return self._history_request(
211
+ f"/v1/tokens/{token_id}/prices",
212
+ start_ts=start_ts,
213
+ end_ts=end_ts,
214
+ resolution=resolution,
215
+ limit=limit,
216
+ cursor=cursor,
217
+ )
218
+
219
+ def get_token_books(
220
+ self,
221
+ token_id: str,
222
+ *,
223
+ start_ts: str,
224
+ end_ts: str,
225
+ resolution: Resolution,
226
+ limit: int | None = None,
227
+ cursor: str | None = None,
228
+ ) -> dict[str, Any]:
229
+ return self._history_request(
230
+ f"/v1/tokens/{token_id}/books",
231
+ start_ts=start_ts,
232
+ end_ts=end_ts,
233
+ resolution=resolution,
234
+ limit=limit,
235
+ cursor=cursor,
236
+ )
237
+
238
+ # --- Pagination helpers ---
239
+
240
+ def iter_markets(
241
+ self,
242
+ **params: Any,
243
+ ) -> Iterator[dict[str, Any]]:
244
+ """Yield each page from ``list_markets`` until ``next_cursor`` is exhausted."""
245
+ yield from self._iter_pages(self.list_markets, params)
246
+
247
+ def iter_market_books(
248
+ self,
249
+ id_or_slug: str,
250
+ **params: Any,
251
+ ) -> Iterator[dict[str, Any]]:
252
+ """Yield each page from ``get_market_books`` until ``next_cursor`` is exhausted."""
253
+ yield from self._iter_pages(
254
+ lambda **kw: self.get_market_books(id_or_slug, **kw),
255
+ params,
256
+ )
257
+
258
+ def _history_request(
259
+ self,
260
+ path: str,
261
+ *,
262
+ start_ts: str,
263
+ end_ts: str,
264
+ resolution: Resolution,
265
+ limit: int | None,
266
+ cursor: str | None,
267
+ ) -> dict[str, Any]:
268
+ params = self._compact(
269
+ start_ts=start_ts,
270
+ end_ts=end_ts,
271
+ resolution=resolution,
272
+ limit=limit,
273
+ cursor=cursor,
274
+ )
275
+ return request_json(self._client, "GET", path, params=params)
276
+
277
+ def _discovery_params(self, **kwargs: Any) -> dict[str, Any]:
278
+ params = dict(kwargs)
279
+ tags = params.pop("tags", None)
280
+ if tags is not None:
281
+ if isinstance(tags, list):
282
+ params["tags"] = ",".join(tags)
283
+ else:
284
+ params["tags"] = tags
285
+ include_closed = params.pop("include_closed", None)
286
+ if include_closed is not None:
287
+ params["include_closed"] = str(include_closed).lower()
288
+ return self._compact(**params)
289
+
290
+ @staticmethod
291
+ def _compact(**kwargs: Any) -> dict[str, Any]:
292
+ return {key: value for key, value in kwargs.items() if value is not None}
293
+
294
+ @staticmethod
295
+ def _iter_pages(
296
+ fetch_page: Any,
297
+ params: dict[str, Any],
298
+ ) -> Iterator[dict[str, Any]]:
299
+ cursor: str | None = None
300
+ while True:
301
+ page_params = dict(params)
302
+ if cursor:
303
+ page_params["cursor"] = cursor
304
+ page = fetch_page(**page_params)
305
+ yield page
306
+ metadata = page.get("metadata") or {}
307
+ cursor = metadata.get("next_cursor")
308
+ if not cursor:
309
+ break
@@ -0,0 +1,29 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+
6
+ class PolyOrderbooksError(Exception):
7
+ """Base error for the PolyOrderbooks SDK."""
8
+
9
+
10
+ class APIError(PolyOrderbooksError):
11
+ """HTTP error returned by the PolyOrderbooks API."""
12
+
13
+ def __init__(self, status_code: int, message: str, *, body: Any | None = None) -> None:
14
+ super().__init__(message)
15
+ self.status_code = status_code
16
+ self.message = message
17
+ self.body = body
18
+
19
+
20
+ class AuthenticationError(APIError):
21
+ """Missing or invalid API key (401)."""
22
+
23
+
24
+ class NotFoundError(APIError):
25
+ """Resource not found (404)."""
26
+
27
+
28
+ class RateLimitError(APIError):
29
+ """Rate limit exceeded (429)."""
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.4
2
+ Name: polyorderbooks
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the PolyOrderbooks historical Polymarket data API.
5
+ Project-URL: Homepage, https://polyorderbooks.com
6
+ Project-URL: Documentation, https://docs.polyorderbooks.com
7
+ Project-URL: Repository, https://github.com/polyorderbooks/python-sdk
8
+ Project-URL: Issues, https://github.com/polyorderbooks/python-sdk/issues
9
+ Author-email: PolyOrderbooks <contact@polyorderbooks.com>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: api,order-book,polymarket,prediction-markets
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.9
24
+ Requires-Dist: httpx<1.0.0,>=0.27.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest-httpx>=0.35.0; extra == 'dev'
27
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # PolyOrderbooks Python SDK
31
+
32
+ Official Python client for the [PolyOrderbooks API](https://docs.polyorderbooks.com) — historical Polymarket order books, prices, and liquidity metrics.
33
+
34
+ [![CI](https://github.com/polyorderbooks/python-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/polyorderbooks/python-sdk/actions/workflows/ci.yml)
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install polyorderbooks
40
+ ```
41
+
42
+ Or install the latest from GitHub:
43
+
44
+ ```bash
45
+ pip install git+https://github.com/polyorderbooks/python-sdk.git
46
+ ```
47
+
48
+ ## Quickstart
49
+
50
+ Get an API key from [polyorderbooks.com/signup](https://polyorderbooks.com/signup), then:
51
+
52
+ ```python
53
+ import os
54
+ from datetime import datetime, timedelta, timezone
55
+
56
+ from polyorderbooks import PolyOrderbooksClient
57
+
58
+ client = PolyOrderbooksClient(api_key=os.environ["POLYORDERBOOKS_API_KEY"])
59
+
60
+ # Or rely on POLYORDERBOOKS_API_KEY in the environment:
61
+ # client = PolyOrderbooksClient()
62
+
63
+ markets = client.list_markets(search="bitcoin", limit=5)
64
+ slug = markets["data"][0]["slug"]
65
+
66
+ end = datetime.now(timezone.utc)
67
+ start = end - timedelta(hours=6)
68
+
69
+ books = client.get_market_books(
70
+ slug,
71
+ start_ts=start.isoformat().replace("+00:00", "Z"),
72
+ end_ts=end.isoformat().replace("+00:00", "Z"),
73
+ resolution="60s",
74
+ limit=100,
75
+ )
76
+
77
+ for outcome, points in books["data"].items():
78
+ for point in points[:2]:
79
+ bids = point.get("b") or []
80
+ asks = point.get("a") or []
81
+ best_bid = bids[0][0] if bids else None
82
+ best_ask = asks[0][0] if asks else None
83
+ print(point["t"], outcome, "bid", best_bid, "ask", best_ask)
84
+
85
+ client.close()
86
+ ```
87
+
88
+ Context manager usage:
89
+
90
+ ```python
91
+ with PolyOrderbooksClient() as client:
92
+ usage = client.get_usage()
93
+ print(usage["plan"], usage["limits"])
94
+ ```
95
+
96
+ ## Pagination
97
+
98
+ Use `metadata.next_cursor` manually, or helpers:
99
+
100
+ ```python
101
+ for page in client.iter_market_books(
102
+ slug,
103
+ start_ts="2026-04-01T00:00:00Z",
104
+ end_ts="2026-04-02T00:00:00Z",
105
+ resolution="60s",
106
+ ):
107
+ process(page["data"])
108
+ ```
109
+
110
+ ## API coverage
111
+
112
+ | Method | Endpoint |
113
+ | --- | --- |
114
+ | `get_usage()` | `GET /v1/usage` |
115
+ | `list_series(...)` | `GET /v1/series` |
116
+ | `list_events(...)` | `GET /v1/events` |
117
+ | `list_markets(...)` | `GET /v1/markets` |
118
+ | `get_market(id_or_slug)` | `GET /v1/markets/{id_or_slug}` |
119
+ | `list_tags()` | `GET /v1/tags` |
120
+ | `get_market_metrics(...)` | `GET /v1/markets/{id_or_slug}/metrics` |
121
+ | `get_market_prices(...)` | `GET /v1/markets/{id_or_slug}/prices` |
122
+ | `get_market_books(...)` | `GET /v1/markets/{id_or_slug}/books` |
123
+ | `get_token_prices(...)` | `GET /v1/tokens/{token_id}/prices` |
124
+ | `get_token_books(...)` | `GET /v1/tokens/{token_id}/books` |
125
+
126
+ ## Authentication
127
+
128
+ Send your API key via the client constructor or `POLYORDERBOOKS_API_KEY`. The SDK sets `X-API-Key` on every request (the API also accepts `Authorization: Bearer pob_…`).
129
+
130
+ ## Errors
131
+
132
+ ```python
133
+ from polyorderbooks import AuthenticationError, NotFoundError, RateLimitError, APIError
134
+ ```
135
+
136
+ - `AuthenticationError` — 401
137
+ - `NotFoundError` — 404
138
+ - `RateLimitError` — 429
139
+ - `APIError` — other HTTP failures
140
+
141
+ ## Development
142
+
143
+ ```bash
144
+ python -m venv .venv
145
+ source .venv/bin/activate
146
+ pip install -e ".[dev]"
147
+ pytest
148
+ ```
149
+
150
+ ## Links
151
+
152
+ - Product: [polyorderbooks.com](https://polyorderbooks.com)
153
+ - Docs: [docs.polyorderbooks.com](https://docs.polyorderbooks.com)
154
+ - OpenAPI: [docs.polyorderbooks.com/openapi.json](https://docs.polyorderbooks.com/openapi.json)
155
+
156
+ ## License
157
+
158
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,8 @@
1
+ polyorderbooks/__init__.py,sha256=JwfIUzqmssLLwgiYSfRQ9b7oWgnFBHc3D5VqoQ_8s9Y,436
2
+ polyorderbooks/_http.py,sha256=0EF0jPjIsNrEmWLd34WAqclcoe3rJBjWH38jEv9Z5rw,2261
3
+ polyorderbooks/client.py,sha256=YSB998crcEinpY3ru1MGl8v7A9b6dRXP0A2dcHHHHLE,8825
4
+ polyorderbooks/exceptions.py,sha256=mgBTac_twpj5PxlKDaHZnkKzFyRM6tnN--rXWHxnq_U,689
5
+ polyorderbooks-0.1.0.dist-info/METADATA,sha256=FJg_WKmQx9mqIQRbch1XfUy1LtfirlkwND_kdhCUNzQ,4682
6
+ polyorderbooks-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
7
+ polyorderbooks-0.1.0.dist-info/licenses/LICENSE,sha256=lCKRPH_aMyu0sknO7QW6G7Hi7uzhW8Mc_ow2Bm4bjas,1071
8
+ polyorderbooks-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PolyOrderbooks
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.