polyorderbooks 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- polyorderbooks-0.1.0/.github/workflows/ci.yml +25 -0
- polyorderbooks-0.1.0/.github/workflows/publish.yml +29 -0
- polyorderbooks-0.1.0/.gitignore +218 -0
- polyorderbooks-0.1.0/LICENSE +21 -0
- polyorderbooks-0.1.0/PKG-INFO +158 -0
- polyorderbooks-0.1.0/README.md +129 -0
- polyorderbooks-0.1.0/pyproject.toml +41 -0
- polyorderbooks-0.1.0/src/polyorderbooks/__init__.py +20 -0
- polyorderbooks-0.1.0/src/polyorderbooks/_http.py +86 -0
- polyorderbooks-0.1.0/src/polyorderbooks/client.py +309 -0
- polyorderbooks-0.1.0/src/polyorderbooks/exceptions.py +29 -0
- polyorderbooks-0.1.0/tests/test_client.py +89 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: [main]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
test:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
strategy:
|
|
13
|
+
matrix:
|
|
14
|
+
python-version: ["3.9", "3.11", "3.12"]
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v4
|
|
17
|
+
- uses: actions/setup-python@v5
|
|
18
|
+
with:
|
|
19
|
+
python-version: ${{ matrix.python-version }}
|
|
20
|
+
- name: Install
|
|
21
|
+
run: |
|
|
22
|
+
python -m pip install --upgrade pip
|
|
23
|
+
pip install -e ".[dev]"
|
|
24
|
+
- name: Run tests
|
|
25
|
+
run: pytest
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags:
|
|
6
|
+
- "v*"
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
id-token: write
|
|
11
|
+
|
|
12
|
+
jobs:
|
|
13
|
+
publish:
|
|
14
|
+
runs-on: ubuntu-latest
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v4
|
|
17
|
+
|
|
18
|
+
- uses: actions/setup-python@v5
|
|
19
|
+
with:
|
|
20
|
+
python-version: "3.12"
|
|
21
|
+
|
|
22
|
+
- name: Install build tooling
|
|
23
|
+
run: python -m pip install --upgrade pip build
|
|
24
|
+
|
|
25
|
+
- name: Build package
|
|
26
|
+
run: python -m build
|
|
27
|
+
|
|
28
|
+
- name: Publish to PyPI
|
|
29
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py.cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
# Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
# uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
# poetry.lock
|
|
109
|
+
# poetry.toml
|
|
110
|
+
|
|
111
|
+
# pdm
|
|
112
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
113
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
114
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
115
|
+
# pdm.lock
|
|
116
|
+
# pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# pixi
|
|
121
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
122
|
+
# pixi.lock
|
|
123
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
124
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
125
|
+
.pixi
|
|
126
|
+
|
|
127
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
128
|
+
__pypackages__/
|
|
129
|
+
|
|
130
|
+
# Celery stuff
|
|
131
|
+
celerybeat-schedule
|
|
132
|
+
celerybeat.pid
|
|
133
|
+
|
|
134
|
+
# Redis
|
|
135
|
+
*.rdb
|
|
136
|
+
*.aof
|
|
137
|
+
*.pid
|
|
138
|
+
|
|
139
|
+
# RabbitMQ
|
|
140
|
+
mnesia/
|
|
141
|
+
rabbitmq/
|
|
142
|
+
rabbitmq-data/
|
|
143
|
+
|
|
144
|
+
# ActiveMQ
|
|
145
|
+
activemq-data/
|
|
146
|
+
|
|
147
|
+
# SageMath parsed files
|
|
148
|
+
*.sage.py
|
|
149
|
+
|
|
150
|
+
# Environments
|
|
151
|
+
.env
|
|
152
|
+
.envrc
|
|
153
|
+
.venv
|
|
154
|
+
env/
|
|
155
|
+
venv/
|
|
156
|
+
ENV/
|
|
157
|
+
env.bak/
|
|
158
|
+
venv.bak/
|
|
159
|
+
|
|
160
|
+
# Spyder project settings
|
|
161
|
+
.spyderproject
|
|
162
|
+
.spyproject
|
|
163
|
+
|
|
164
|
+
# Rope project settings
|
|
165
|
+
.ropeproject
|
|
166
|
+
|
|
167
|
+
# mkdocs documentation
|
|
168
|
+
/site
|
|
169
|
+
|
|
170
|
+
# mypy
|
|
171
|
+
.mypy_cache/
|
|
172
|
+
.dmypy.json
|
|
173
|
+
dmypy.json
|
|
174
|
+
|
|
175
|
+
# Pyre type checker
|
|
176
|
+
.pyre/
|
|
177
|
+
|
|
178
|
+
# pytype static type analyzer
|
|
179
|
+
.pytype/
|
|
180
|
+
|
|
181
|
+
# Cython debug symbols
|
|
182
|
+
cython_debug/
|
|
183
|
+
|
|
184
|
+
# PyCharm
|
|
185
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
186
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
187
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
188
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
189
|
+
# .idea/
|
|
190
|
+
|
|
191
|
+
# Abstra
|
|
192
|
+
# Abstra is an AI-powered process automation framework.
|
|
193
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
194
|
+
# Learn more at https://abstra.io/docs
|
|
195
|
+
.abstra/
|
|
196
|
+
|
|
197
|
+
# Visual Studio Code
|
|
198
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
199
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
200
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
201
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
202
|
+
# .vscode/
|
|
203
|
+
# Temporary file for partial code execution
|
|
204
|
+
tempCodeRunnerFile.py
|
|
205
|
+
|
|
206
|
+
# Ruff stuff:
|
|
207
|
+
.ruff_cache/
|
|
208
|
+
|
|
209
|
+
# PyPI configuration file
|
|
210
|
+
.pypirc
|
|
211
|
+
|
|
212
|
+
# Marimo
|
|
213
|
+
marimo/_static/
|
|
214
|
+
marimo/_lsp/
|
|
215
|
+
__marimo__/
|
|
216
|
+
|
|
217
|
+
# Streamlit
|
|
218
|
+
.streamlit/secrets.toml
|
|
@@ -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.
|
|
@@ -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
|
+
[](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,129 @@
|
|
|
1
|
+
# PolyOrderbooks Python SDK
|
|
2
|
+
|
|
3
|
+
Official Python client for the [PolyOrderbooks API](https://docs.polyorderbooks.com) — historical Polymarket order books, prices, and liquidity metrics.
|
|
4
|
+
|
|
5
|
+
[](https://github.com/polyorderbooks/python-sdk/actions/workflows/ci.yml)
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install polyorderbooks
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or install the latest from GitHub:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install git+https://github.com/polyorderbooks/python-sdk.git
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quickstart
|
|
20
|
+
|
|
21
|
+
Get an API key from [polyorderbooks.com/signup](https://polyorderbooks.com/signup), then:
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
import os
|
|
25
|
+
from datetime import datetime, timedelta, timezone
|
|
26
|
+
|
|
27
|
+
from polyorderbooks import PolyOrderbooksClient
|
|
28
|
+
|
|
29
|
+
client = PolyOrderbooksClient(api_key=os.environ["POLYORDERBOOKS_API_KEY"])
|
|
30
|
+
|
|
31
|
+
# Or rely on POLYORDERBOOKS_API_KEY in the environment:
|
|
32
|
+
# client = PolyOrderbooksClient()
|
|
33
|
+
|
|
34
|
+
markets = client.list_markets(search="bitcoin", limit=5)
|
|
35
|
+
slug = markets["data"][0]["slug"]
|
|
36
|
+
|
|
37
|
+
end = datetime.now(timezone.utc)
|
|
38
|
+
start = end - timedelta(hours=6)
|
|
39
|
+
|
|
40
|
+
books = client.get_market_books(
|
|
41
|
+
slug,
|
|
42
|
+
start_ts=start.isoformat().replace("+00:00", "Z"),
|
|
43
|
+
end_ts=end.isoformat().replace("+00:00", "Z"),
|
|
44
|
+
resolution="60s",
|
|
45
|
+
limit=100,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
for outcome, points in books["data"].items():
|
|
49
|
+
for point in points[:2]:
|
|
50
|
+
bids = point.get("b") or []
|
|
51
|
+
asks = point.get("a") or []
|
|
52
|
+
best_bid = bids[0][0] if bids else None
|
|
53
|
+
best_ask = asks[0][0] if asks else None
|
|
54
|
+
print(point["t"], outcome, "bid", best_bid, "ask", best_ask)
|
|
55
|
+
|
|
56
|
+
client.close()
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Context manager usage:
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
with PolyOrderbooksClient() as client:
|
|
63
|
+
usage = client.get_usage()
|
|
64
|
+
print(usage["plan"], usage["limits"])
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Pagination
|
|
68
|
+
|
|
69
|
+
Use `metadata.next_cursor` manually, or helpers:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
for page in client.iter_market_books(
|
|
73
|
+
slug,
|
|
74
|
+
start_ts="2026-04-01T00:00:00Z",
|
|
75
|
+
end_ts="2026-04-02T00:00:00Z",
|
|
76
|
+
resolution="60s",
|
|
77
|
+
):
|
|
78
|
+
process(page["data"])
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## API coverage
|
|
82
|
+
|
|
83
|
+
| Method | Endpoint |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `get_usage()` | `GET /v1/usage` |
|
|
86
|
+
| `list_series(...)` | `GET /v1/series` |
|
|
87
|
+
| `list_events(...)` | `GET /v1/events` |
|
|
88
|
+
| `list_markets(...)` | `GET /v1/markets` |
|
|
89
|
+
| `get_market(id_or_slug)` | `GET /v1/markets/{id_or_slug}` |
|
|
90
|
+
| `list_tags()` | `GET /v1/tags` |
|
|
91
|
+
| `get_market_metrics(...)` | `GET /v1/markets/{id_or_slug}/metrics` |
|
|
92
|
+
| `get_market_prices(...)` | `GET /v1/markets/{id_or_slug}/prices` |
|
|
93
|
+
| `get_market_books(...)` | `GET /v1/markets/{id_or_slug}/books` |
|
|
94
|
+
| `get_token_prices(...)` | `GET /v1/tokens/{token_id}/prices` |
|
|
95
|
+
| `get_token_books(...)` | `GET /v1/tokens/{token_id}/books` |
|
|
96
|
+
|
|
97
|
+
## Authentication
|
|
98
|
+
|
|
99
|
+
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_…`).
|
|
100
|
+
|
|
101
|
+
## Errors
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
from polyorderbooks import AuthenticationError, NotFoundError, RateLimitError, APIError
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
- `AuthenticationError` — 401
|
|
108
|
+
- `NotFoundError` — 404
|
|
109
|
+
- `RateLimitError` — 429
|
|
110
|
+
- `APIError` — other HTTP failures
|
|
111
|
+
|
|
112
|
+
## Development
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
python -m venv .venv
|
|
116
|
+
source .venv/bin/activate
|
|
117
|
+
pip install -e ".[dev]"
|
|
118
|
+
pytest
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Links
|
|
122
|
+
|
|
123
|
+
- Product: [polyorderbooks.com](https://polyorderbooks.com)
|
|
124
|
+
- Docs: [docs.polyorderbooks.com](https://docs.polyorderbooks.com)
|
|
125
|
+
- OpenAPI: [docs.polyorderbooks.com/openapi.json](https://docs.polyorderbooks.com/openapi.json)
|
|
126
|
+
|
|
127
|
+
## License
|
|
128
|
+
|
|
129
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "polyorderbooks"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Official Python SDK for the PolyOrderbooks historical Polymarket data API."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
authors = [{ name = "PolyOrderbooks", email = "contact@polyorderbooks.com" }]
|
|
13
|
+
keywords = ["polymarket", "order-book", "prediction-markets", "api"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.9",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
dependencies = ["httpx>=0.27.0,<1.0.0"]
|
|
27
|
+
|
|
28
|
+
[project.optional-dependencies]
|
|
29
|
+
dev = ["pytest>=8.0.0", "pytest-httpx>=0.35.0"]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://polyorderbooks.com"
|
|
33
|
+
Documentation = "https://docs.polyorderbooks.com"
|
|
34
|
+
Repository = "https://github.com/polyorderbooks/python-sdk"
|
|
35
|
+
Issues = "https://github.com/polyorderbooks/python-sdk/issues"
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.wheel]
|
|
38
|
+
packages = ["src/polyorderbooks"]
|
|
39
|
+
|
|
40
|
+
[tool.pytest.ini_options]
|
|
41
|
+
testpaths = ["tests"]
|
|
@@ -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,89 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from polyorderbooks import (
|
|
4
|
+
AuthenticationError,
|
|
5
|
+
PolyOrderbooksClient,
|
|
6
|
+
RateLimitError,
|
|
7
|
+
)
|
|
8
|
+
from polyorderbooks._http import resolve_api_key
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_resolve_api_key_from_argument():
|
|
12
|
+
assert resolve_api_key("pob_test") == "pob_test"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_resolve_api_key_missing(monkeypatch):
|
|
16
|
+
monkeypatch.delenv("POLYORDERBOOKS_API_KEY", raising=False)
|
|
17
|
+
with pytest.raises(ValueError, match="API key required"):
|
|
18
|
+
resolve_api_key(None)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_list_markets_builds_query(httpx_mock):
|
|
22
|
+
httpx_mock.add_response(
|
|
23
|
+
json={"data": [{"slug": "btc-100k"}], "metadata": {"next_cursor": None}},
|
|
24
|
+
)
|
|
25
|
+
with PolyOrderbooksClient(api_key="pob_test") as client:
|
|
26
|
+
payload = client.list_markets(search="bitcoin", limit=5)
|
|
27
|
+
|
|
28
|
+
assert payload["data"][0]["slug"] == "btc-100k"
|
|
29
|
+
request = httpx_mock.get_request()
|
|
30
|
+
assert request.url.path == "/v1/markets"
|
|
31
|
+
assert request.headers["X-API-Key"] == "pob_test"
|
|
32
|
+
assert "search=bitcoin" in str(request.url)
|
|
33
|
+
assert "limit=5" in str(request.url)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_get_market_books(httpx_mock):
|
|
37
|
+
httpx_mock.add_response(
|
|
38
|
+
json={"data": {"Yes": []}, "metadata": {"next_cursor": None}},
|
|
39
|
+
)
|
|
40
|
+
with PolyOrderbooksClient(api_key="pob_test") as client:
|
|
41
|
+
payload = client.get_market_books(
|
|
42
|
+
"will-btc-hit-100k",
|
|
43
|
+
start_ts="2026-04-01T00:00:00Z",
|
|
44
|
+
end_ts="2026-04-01T06:00:00Z",
|
|
45
|
+
resolution="60s",
|
|
46
|
+
limit=100,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
assert "Yes" in payload["data"]
|
|
50
|
+
request = httpx_mock.get_request()
|
|
51
|
+
assert request.url.path == "/v1/markets/will-btc-hit-100k/books"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_authentication_error(httpx_mock):
|
|
55
|
+
httpx_mock.add_response(status_code=401, json={"detail": "Invalid API key."})
|
|
56
|
+
with PolyOrderbooksClient(api_key="pob_bad") as client:
|
|
57
|
+
with pytest.raises(AuthenticationError, match="Invalid API key"):
|
|
58
|
+
client.get_usage()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_rate_limit_error(httpx_mock):
|
|
62
|
+
httpx_mock.add_response(
|
|
63
|
+
status_code=429,
|
|
64
|
+
json={"detail": "Rate limit exceeded. Please try again later."},
|
|
65
|
+
)
|
|
66
|
+
with PolyOrderbooksClient(api_key="pob_test") as client:
|
|
67
|
+
with pytest.raises(RateLimitError):
|
|
68
|
+
client.list_tags()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_iter_market_books_pagination(httpx_mock):
|
|
72
|
+
httpx_mock.add_response(
|
|
73
|
+
json={"data": {"Yes": [{"t": "1"}]}, "metadata": {"next_cursor": "abc"}},
|
|
74
|
+
)
|
|
75
|
+
httpx_mock.add_response(
|
|
76
|
+
json={"data": {"Yes": [{"t": "2"}]}, "metadata": {"next_cursor": None}},
|
|
77
|
+
)
|
|
78
|
+
with PolyOrderbooksClient(api_key="pob_test") as client:
|
|
79
|
+
pages = list(
|
|
80
|
+
client.iter_market_books(
|
|
81
|
+
"sample-market",
|
|
82
|
+
start_ts="2026-04-01T00:00:00Z",
|
|
83
|
+
end_ts="2026-04-02T00:00:00Z",
|
|
84
|
+
resolution="60s",
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
assert len(pages) == 2
|
|
89
|
+
assert httpx_mock.get_requests()[1].url.params.get("cursor") == "abc"
|