omnibook 1.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.
- omnibook/__init__.py +34 -0
- omnibook/_base.py +61 -0
- omnibook/async_client.py +272 -0
- omnibook/auth.py +90 -0
- omnibook/client.py +285 -0
- omnibook/errors.py +117 -0
- omnibook/models.py +41 -0
- omnibook/py.typed +0 -0
- omnibook/ws.py +261 -0
- omnibook-1.1.0.dist-info/METADATA +132 -0
- omnibook-1.1.0.dist-info/RECORD +13 -0
- omnibook-1.1.0.dist-info/WHEEL +4 -0
- omnibook-1.1.0.dist-info/licenses/LICENSE +21 -0
omnibook/__init__.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Official Python SDK for the Omnibook prediction market exchange."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .async_client import AsyncClient
|
|
6
|
+
from .auth import DEFAULT_BASE_URL, DEFAULT_WS_URL
|
|
7
|
+
from .client import Client
|
|
8
|
+
from .errors import (
|
|
9
|
+
OmnibookAPIError,
|
|
10
|
+
OmnibookAuthError,
|
|
11
|
+
OmnibookError,
|
|
12
|
+
OmnibookRateLimitError,
|
|
13
|
+
OmnibookTimeoutError,
|
|
14
|
+
OmnibookWSError,
|
|
15
|
+
)
|
|
16
|
+
from .ws import AsyncWebSocketClient, WebSocketClient
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"AsyncClient",
|
|
20
|
+
"AsyncWebSocketClient",
|
|
21
|
+
"Client",
|
|
22
|
+
"DEFAULT_BASE_URL",
|
|
23
|
+
"DEFAULT_WS_URL",
|
|
24
|
+
"OmnibookAPIError",
|
|
25
|
+
"OmnibookAuthError",
|
|
26
|
+
"OmnibookError",
|
|
27
|
+
"OmnibookRateLimitError",
|
|
28
|
+
"OmnibookTimeoutError",
|
|
29
|
+
"OmnibookWSError",
|
|
30
|
+
"WebSocketClient",
|
|
31
|
+
"__version__",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
__version__ = "1.1.0"
|
omnibook/_base.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Shared REST helpers used by sync and async clients."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any
|
|
7
|
+
from urllib.parse import urlparse
|
|
8
|
+
|
|
9
|
+
from .auth import DEFAULT_BASE_URL, DEFAULT_WS_URL, decode_secret, signed_headers
|
|
10
|
+
from .errors import raise_for_response
|
|
11
|
+
from .models import JsonDict, compact_json_bytes, path_with_query
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class BaseClient:
|
|
15
|
+
"""Credential + URL configuration shared by Client and AsyncClient."""
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
api_key: str | int,
|
|
20
|
+
api_secret: str | bytes,
|
|
21
|
+
*,
|
|
22
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
23
|
+
ws_url: str = DEFAULT_WS_URL,
|
|
24
|
+
timeout: float = 30.0,
|
|
25
|
+
) -> None:
|
|
26
|
+
self.api_key = str(api_key)
|
|
27
|
+
self._secret = decode_secret(api_secret)
|
|
28
|
+
self.base_url = base_url.rstrip("/")
|
|
29
|
+
self.ws_url = ws_url
|
|
30
|
+
self.timeout = timeout
|
|
31
|
+
parsed = urlparse(self.base_url)
|
|
32
|
+
if not parsed.scheme or not parsed.netloc:
|
|
33
|
+
raise ValueError(f"invalid base_url: {base_url!r}")
|
|
34
|
+
|
|
35
|
+
def _prepare(
|
|
36
|
+
self,
|
|
37
|
+
method: str,
|
|
38
|
+
path: str,
|
|
39
|
+
*,
|
|
40
|
+
params: dict[str, Any] | None = None,
|
|
41
|
+
json_body: JsonDict | list[Any] | None = None,
|
|
42
|
+
) -> tuple[str, bytes, dict[str, str]]:
|
|
43
|
+
target = path_with_query(path, params)
|
|
44
|
+
body = b""
|
|
45
|
+
if json_body is not None:
|
|
46
|
+
body = compact_json_bytes(json_body)
|
|
47
|
+
headers = signed_headers(self.api_key, self._secret, method, target, body)
|
|
48
|
+
return target, body, headers
|
|
49
|
+
|
|
50
|
+
@staticmethod
|
|
51
|
+
def _parse_response(status_code: int, text: str, header_map: dict[str, str]) -> Any:
|
|
52
|
+
data: Any
|
|
53
|
+
if not text:
|
|
54
|
+
data = None
|
|
55
|
+
else:
|
|
56
|
+
try:
|
|
57
|
+
data = json.loads(text)
|
|
58
|
+
except json.JSONDecodeError:
|
|
59
|
+
data = text
|
|
60
|
+
raise_for_response(status_code, data, header_map)
|
|
61
|
+
return data
|
omnibook/async_client.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""Asynchronous Omnibook REST client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from ._base import BaseClient
|
|
10
|
+
from .auth import DEFAULT_BASE_URL, DEFAULT_WS_URL
|
|
11
|
+
from .models import JsonDict
|
|
12
|
+
from .ws import AsyncWebSocketClient
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AsyncClient(BaseClient):
|
|
16
|
+
"""HMAC-authenticated async client for the Omnibook venue API."""
|
|
17
|
+
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
api_key: str | int,
|
|
21
|
+
api_secret: str | bytes,
|
|
22
|
+
*,
|
|
23
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
24
|
+
ws_url: str = DEFAULT_WS_URL,
|
|
25
|
+
timeout: float = 30.0,
|
|
26
|
+
http_client: httpx.AsyncClient | None = None,
|
|
27
|
+
) -> None:
|
|
28
|
+
super().__init__(
|
|
29
|
+
api_key,
|
|
30
|
+
api_secret,
|
|
31
|
+
base_url=base_url,
|
|
32
|
+
ws_url=ws_url,
|
|
33
|
+
timeout=timeout,
|
|
34
|
+
)
|
|
35
|
+
self._owns_http = http_client is None
|
|
36
|
+
self._http = http_client or httpx.AsyncClient(timeout=timeout)
|
|
37
|
+
|
|
38
|
+
async def aclose(self) -> None:
|
|
39
|
+
if self._owns_http:
|
|
40
|
+
await self._http.aclose()
|
|
41
|
+
|
|
42
|
+
async def __aenter__(self) -> AsyncClient:
|
|
43
|
+
return self
|
|
44
|
+
|
|
45
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
46
|
+
await self.aclose()
|
|
47
|
+
|
|
48
|
+
async def request(
|
|
49
|
+
self,
|
|
50
|
+
method: str,
|
|
51
|
+
path: str,
|
|
52
|
+
*,
|
|
53
|
+
params: dict[str, Any] | None = None,
|
|
54
|
+
json: JsonDict | list[Any] | None = None,
|
|
55
|
+
) -> Any:
|
|
56
|
+
target, body, headers = self._prepare(method, path, params=params, json_body=json)
|
|
57
|
+
url = f"{self.base_url}{target}"
|
|
58
|
+
resp = await self._http.request(
|
|
59
|
+
method.upper(),
|
|
60
|
+
url,
|
|
61
|
+
content=body if body else None,
|
|
62
|
+
headers=headers,
|
|
63
|
+
)
|
|
64
|
+
header_map = {k.lower(): v for k, v in resp.headers.items()}
|
|
65
|
+
if "retry-after" in header_map:
|
|
66
|
+
header_map["Retry-After"] = header_map["retry-after"]
|
|
67
|
+
return self._parse_response(resp.status_code, resp.text, header_map)
|
|
68
|
+
|
|
69
|
+
async def get(self, path: str, *, params: dict[str, Any] | None = None) -> Any:
|
|
70
|
+
return await self.request("GET", path, params=params)
|
|
71
|
+
|
|
72
|
+
async def post(self, path: str, *, json: JsonDict | None = None) -> Any:
|
|
73
|
+
return await self.request("POST", path, json=json)
|
|
74
|
+
|
|
75
|
+
async def delete(self, path: str, *, params: dict[str, Any] | None = None) -> Any:
|
|
76
|
+
return await self.request("DELETE", path, params=params)
|
|
77
|
+
|
|
78
|
+
async def get_exchange_status(self) -> JsonDict:
|
|
79
|
+
return await self.get("/v1/exchange/status")
|
|
80
|
+
|
|
81
|
+
async def get_exchange_schedule(self) -> JsonDict:
|
|
82
|
+
return await self.get("/v1/exchange/schedule")
|
|
83
|
+
|
|
84
|
+
async def get_markets(
|
|
85
|
+
self,
|
|
86
|
+
*,
|
|
87
|
+
status: str | None = None,
|
|
88
|
+
cursor: str | None = None,
|
|
89
|
+
limit: int | None = None,
|
|
90
|
+
) -> JsonDict:
|
|
91
|
+
return await self.get(
|
|
92
|
+
"/v1/markets",
|
|
93
|
+
params={"status": status, "cursor": cursor, "limit": limit},
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
async def get_market(self, market_id: int) -> JsonDict:
|
|
97
|
+
return await self.get(f"/v1/markets/{market_id}")
|
|
98
|
+
|
|
99
|
+
async def get_orderbook(self, market_id: int, *, depth: int | None = None) -> JsonDict:
|
|
100
|
+
return await self.get(
|
|
101
|
+
f"/v1/markets/{market_id}/orderbook",
|
|
102
|
+
params={"depth": depth},
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
async def get_trades(
|
|
106
|
+
self,
|
|
107
|
+
market_id: int,
|
|
108
|
+
*,
|
|
109
|
+
cursor: str | None = None,
|
|
110
|
+
limit: int | None = None,
|
|
111
|
+
) -> JsonDict:
|
|
112
|
+
return await self.get(
|
|
113
|
+
f"/v1/markets/{market_id}/trades",
|
|
114
|
+
params={"cursor": cursor, "limit": limit},
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
async def get_rounds(
|
|
118
|
+
self,
|
|
119
|
+
*,
|
|
120
|
+
limit: int | None = None,
|
|
121
|
+
cursor: str | None = None,
|
|
122
|
+
category: str | None = None,
|
|
123
|
+
) -> JsonDict:
|
|
124
|
+
return await self.get(
|
|
125
|
+
"/v1/rounds",
|
|
126
|
+
params={"limit": limit, "cursor": cursor, "category": category},
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
async def get_round(self, round_id: int | str) -> JsonDict:
|
|
130
|
+
return await self.get(f"/v1/rounds/{round_id}")
|
|
131
|
+
|
|
132
|
+
async def get_oracle_price(self) -> JsonDict:
|
|
133
|
+
return await self.get("/v1/oracle/price")
|
|
134
|
+
|
|
135
|
+
async def get_balance(self) -> JsonDict:
|
|
136
|
+
return await self.get("/v1/portfolio/balance")
|
|
137
|
+
|
|
138
|
+
async def get_positions(
|
|
139
|
+
self,
|
|
140
|
+
*,
|
|
141
|
+
market_id: int | None = None,
|
|
142
|
+
cursor: str | None = None,
|
|
143
|
+
limit: int | None = None,
|
|
144
|
+
) -> JsonDict:
|
|
145
|
+
return await self.get(
|
|
146
|
+
"/v1/portfolio/positions",
|
|
147
|
+
params={"market_id": market_id, "cursor": cursor, "limit": limit},
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
async def get_fills(
|
|
151
|
+
self,
|
|
152
|
+
*,
|
|
153
|
+
market_id: int | None = None,
|
|
154
|
+
order_id: str | None = None,
|
|
155
|
+
cursor: str | None = None,
|
|
156
|
+
limit: int | None = None,
|
|
157
|
+
) -> JsonDict:
|
|
158
|
+
return await self.get(
|
|
159
|
+
"/v1/portfolio/fills",
|
|
160
|
+
params={
|
|
161
|
+
"market_id": market_id,
|
|
162
|
+
"order_id": order_id,
|
|
163
|
+
"cursor": cursor,
|
|
164
|
+
"limit": limit,
|
|
165
|
+
},
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
async def get_orders(
|
|
169
|
+
self,
|
|
170
|
+
*,
|
|
171
|
+
market_id: int | None = None,
|
|
172
|
+
status: str | None = None,
|
|
173
|
+
client_order_id: str | None = None,
|
|
174
|
+
cursor: str | None = None,
|
|
175
|
+
limit: int | None = None,
|
|
176
|
+
) -> JsonDict:
|
|
177
|
+
return await self.get(
|
|
178
|
+
"/v1/portfolio/orders",
|
|
179
|
+
params={
|
|
180
|
+
"market_id": market_id,
|
|
181
|
+
"status": status,
|
|
182
|
+
"client_order_id": client_order_id,
|
|
183
|
+
"cursor": cursor,
|
|
184
|
+
"limit": limit,
|
|
185
|
+
},
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
async def get_order(self, order_id: str) -> JsonDict:
|
|
189
|
+
return await self.get(f"/v1/portfolio/orders/{order_id}")
|
|
190
|
+
|
|
191
|
+
async def place_order(
|
|
192
|
+
self,
|
|
193
|
+
*,
|
|
194
|
+
client_order_id: str | int,
|
|
195
|
+
market_id: int,
|
|
196
|
+
side: str,
|
|
197
|
+
outcome: str,
|
|
198
|
+
type: str,
|
|
199
|
+
qty: int,
|
|
200
|
+
tick: int | None = None,
|
|
201
|
+
tif: str | None = None,
|
|
202
|
+
worst_tick: int | None = None,
|
|
203
|
+
expiry_ts: str | None = None,
|
|
204
|
+
max_cost: str | None = None,
|
|
205
|
+
group_id: int | None = None,
|
|
206
|
+
post_only: bool = False,
|
|
207
|
+
reduce_only: bool = False,
|
|
208
|
+
cancel_on_pause: bool = False,
|
|
209
|
+
stp_maker: bool = False,
|
|
210
|
+
) -> JsonDict:
|
|
211
|
+
body: JsonDict = {
|
|
212
|
+
"client_order_id": str(client_order_id),
|
|
213
|
+
"market_id": market_id,
|
|
214
|
+
"side": side,
|
|
215
|
+
"outcome": outcome,
|
|
216
|
+
"type": type,
|
|
217
|
+
"qty": qty,
|
|
218
|
+
}
|
|
219
|
+
if tick is not None:
|
|
220
|
+
body["tick"] = tick
|
|
221
|
+
if tif is not None:
|
|
222
|
+
body["tif"] = tif
|
|
223
|
+
if worst_tick is not None:
|
|
224
|
+
body["worst_tick"] = worst_tick
|
|
225
|
+
if expiry_ts is not None:
|
|
226
|
+
body["expiry_ts"] = expiry_ts
|
|
227
|
+
if max_cost is not None:
|
|
228
|
+
body["max_cost"] = max_cost
|
|
229
|
+
if group_id is not None:
|
|
230
|
+
body["group_id"] = group_id
|
|
231
|
+
if post_only:
|
|
232
|
+
body["post_only"] = True
|
|
233
|
+
if reduce_only:
|
|
234
|
+
body["reduce_only"] = True
|
|
235
|
+
if cancel_on_pause:
|
|
236
|
+
body["cancel_on_pause"] = True
|
|
237
|
+
if stp_maker:
|
|
238
|
+
body["stp_maker"] = True
|
|
239
|
+
return await self.post("/v1/portfolio/orders", json=body)
|
|
240
|
+
|
|
241
|
+
async def place_orders_batch(self, orders: list[JsonDict]) -> Any:
|
|
242
|
+
return await self.post("/v1/portfolio/orders/batch", json={"orders": orders})
|
|
243
|
+
|
|
244
|
+
async def cancel_order(self, order_id: str) -> JsonDict:
|
|
245
|
+
return await self.delete(f"/v1/portfolio/orders/{order_id}")
|
|
246
|
+
|
|
247
|
+
async def mass_cancel(
|
|
248
|
+
self,
|
|
249
|
+
*,
|
|
250
|
+
market_id: int | None = None,
|
|
251
|
+
group_id: int | None = None,
|
|
252
|
+
) -> JsonDict:
|
|
253
|
+
return await self.delete(
|
|
254
|
+
"/v1/portfolio/orders",
|
|
255
|
+
params={"market_id": market_id, "group_id": group_id},
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
async def decrease_order(self, order_id: str, *, new_qty: int) -> JsonDict:
|
|
259
|
+
return await self.post(
|
|
260
|
+
f"/v1/portfolio/orders/{order_id}/decrease",
|
|
261
|
+
json={"new_qty": new_qty},
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
async def get_deposit_address(self) -> JsonDict:
|
|
265
|
+
return await self.get("/v1/deposit-address")
|
|
266
|
+
|
|
267
|
+
def websocket(self) -> AsyncWebSocketClient:
|
|
268
|
+
return AsyncWebSocketClient(
|
|
269
|
+
api_key=self.api_key,
|
|
270
|
+
secret=self._secret,
|
|
271
|
+
ws_url=self.ws_url,
|
|
272
|
+
)
|
omnibook/auth.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""HMAC signing helpers for the Omnibook venue gateway (gateway.md §4.2)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
import hmac
|
|
8
|
+
import re
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
DEFAULT_BASE_URL = "https://api.omnibook.xyz"
|
|
13
|
+
DEFAULT_WS_URL = "wss://api.omnibook.xyz/v1/ws"
|
|
14
|
+
WS_PATH = "/v1/ws"
|
|
15
|
+
|
|
16
|
+
_HEX64 = re.compile(r"^[0-9a-fA-F]{64}$")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def canonical(ts_ms: int, method: str, target: str, body: bytes) -> bytes:
|
|
20
|
+
"""Build ``ts\\nMETHOD\\npath?query\\n`` + body bytes."""
|
|
21
|
+
return f"{ts_ms}\n{method.upper()}\n{target}\n".encode("ascii") + body
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def access_signature(
|
|
25
|
+
secret: bytes, ts_ms: int, method: str, target: str, body: bytes
|
|
26
|
+
) -> str:
|
|
27
|
+
"""Return ``base64(HMAC-SHA256(secret, canonical))``."""
|
|
28
|
+
mac = hmac.new(
|
|
29
|
+
secret, canonical(ts_ms, method, target, body), hashlib.sha256
|
|
30
|
+
).digest()
|
|
31
|
+
return base64.b64encode(mac).decode("ascii")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def decode_secret(secret: str | bytes) -> bytes:
|
|
35
|
+
"""Decode a Settings secret to the raw 32-byte HMAC key.
|
|
36
|
+
|
|
37
|
+
Accepts:
|
|
38
|
+
- raw ``bytes`` of length 32
|
|
39
|
+
- 64-char hex string (current Settings format)
|
|
40
|
+
- standard base64 of 32 bytes (legacy keys)
|
|
41
|
+
"""
|
|
42
|
+
if isinstance(secret, bytes):
|
|
43
|
+
if len(secret) == 32:
|
|
44
|
+
return secret
|
|
45
|
+
text = secret.decode("ascii")
|
|
46
|
+
else:
|
|
47
|
+
text = secret.strip()
|
|
48
|
+
|
|
49
|
+
if _HEX64.match(text):
|
|
50
|
+
return bytes.fromhex(text)
|
|
51
|
+
|
|
52
|
+
try:
|
|
53
|
+
raw = base64.b64decode(text, validate=False)
|
|
54
|
+
except Exception as exc: # noqa: BLE001 — surface as ValueError below
|
|
55
|
+
raise ValueError("API secret must be 64-char hex or base64 of 32 bytes") from exc
|
|
56
|
+
if len(raw) != 32:
|
|
57
|
+
raise ValueError(f"API secret must decode to 32 bytes, got {len(raw)}")
|
|
58
|
+
return raw
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def decode_secret_b64(secret_b64: str | bytes) -> bytes:
|
|
62
|
+
"""Alias for :func:`decode_secret` (kept for older callers)."""
|
|
63
|
+
return decode_secret(secret_b64)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def signed_headers(
|
|
67
|
+
key_id: str | int,
|
|
68
|
+
secret: bytes,
|
|
69
|
+
method: str,
|
|
70
|
+
target: str,
|
|
71
|
+
body: bytes = b"",
|
|
72
|
+
*,
|
|
73
|
+
ts_ms: int | None = None,
|
|
74
|
+
) -> dict[str, str]:
|
|
75
|
+
"""Build the three ``DX-ACCESS-*`` headers (plus JSON content type)."""
|
|
76
|
+
if ts_ms is None:
|
|
77
|
+
ts_ms = int(time.time() * 1000)
|
|
78
|
+
sig = access_signature(secret, ts_ms, method, target, body)
|
|
79
|
+
return {
|
|
80
|
+
"DX-ACCESS-KEY": str(key_id),
|
|
81
|
+
"DX-ACCESS-TIMESTAMP": str(ts_ms),
|
|
82
|
+
"DX-ACCESS-SIGNATURE": sig,
|
|
83
|
+
"Content-Type": "application/json",
|
|
84
|
+
"Accept": "application/json",
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def ws_handshake_headers(key_id: str | int, secret: bytes) -> dict[str, str]:
|
|
89
|
+
"""Headers for the WebSocket upgrade (signs ``GET /v1/ws`` with empty body)."""
|
|
90
|
+
return signed_headers(key_id, secret, "GET", WS_PATH, b"")
|
omnibook/client.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Synchronous Omnibook REST + WebSocket client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from ._base import BaseClient
|
|
10
|
+
from .auth import DEFAULT_BASE_URL, DEFAULT_WS_URL
|
|
11
|
+
from .models import JsonDict
|
|
12
|
+
from .ws import WebSocketClient
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Client(BaseClient):
|
|
16
|
+
"""HMAC-authenticated sync client for the Omnibook venue API."""
|
|
17
|
+
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
api_key: str | int,
|
|
21
|
+
api_secret: str | bytes,
|
|
22
|
+
*,
|
|
23
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
24
|
+
ws_url: str = DEFAULT_WS_URL,
|
|
25
|
+
timeout: float = 30.0,
|
|
26
|
+
http_client: httpx.Client | None = None,
|
|
27
|
+
) -> None:
|
|
28
|
+
super().__init__(
|
|
29
|
+
api_key,
|
|
30
|
+
api_secret,
|
|
31
|
+
base_url=base_url,
|
|
32
|
+
ws_url=ws_url,
|
|
33
|
+
timeout=timeout,
|
|
34
|
+
)
|
|
35
|
+
self._owns_http = http_client is None
|
|
36
|
+
self._http = http_client or httpx.Client(timeout=timeout)
|
|
37
|
+
|
|
38
|
+
def close(self) -> None:
|
|
39
|
+
if self._owns_http:
|
|
40
|
+
self._http.close()
|
|
41
|
+
|
|
42
|
+
def __enter__(self) -> Client:
|
|
43
|
+
return self
|
|
44
|
+
|
|
45
|
+
def __exit__(self, *exc: object) -> None:
|
|
46
|
+
self.close()
|
|
47
|
+
|
|
48
|
+
def request(
|
|
49
|
+
self,
|
|
50
|
+
method: str,
|
|
51
|
+
path: str,
|
|
52
|
+
*,
|
|
53
|
+
params: dict[str, Any] | None = None,
|
|
54
|
+
json: JsonDict | list[Any] | None = None,
|
|
55
|
+
) -> Any:
|
|
56
|
+
target, body, headers = self._prepare(method, path, params=params, json_body=json)
|
|
57
|
+
url = f"{self.base_url}{target}"
|
|
58
|
+
resp = self._http.request(
|
|
59
|
+
method.upper(),
|
|
60
|
+
url,
|
|
61
|
+
content=body if body else None,
|
|
62
|
+
headers=headers,
|
|
63
|
+
)
|
|
64
|
+
header_map = {k.lower(): v for k, v in resp.headers.items()}
|
|
65
|
+
# Preserve Retry-After casing lookup via lower map
|
|
66
|
+
if "retry-after" in header_map:
|
|
67
|
+
header_map["Retry-After"] = header_map["retry-after"]
|
|
68
|
+
return self._parse_response(resp.status_code, resp.text, header_map)
|
|
69
|
+
|
|
70
|
+
def get(self, path: str, *, params: dict[str, Any] | None = None) -> Any:
|
|
71
|
+
return self.request("GET", path, params=params)
|
|
72
|
+
|
|
73
|
+
def post(self, path: str, *, json: JsonDict | None = None) -> Any:
|
|
74
|
+
return self.request("POST", path, json=json)
|
|
75
|
+
|
|
76
|
+
def delete(self, path: str, *, params: dict[str, Any] | None = None) -> Any:
|
|
77
|
+
return self.request("DELETE", path, params=params)
|
|
78
|
+
|
|
79
|
+
# --- Exchange ---
|
|
80
|
+
|
|
81
|
+
def get_exchange_status(self) -> JsonDict:
|
|
82
|
+
return self.get("/v1/exchange/status")
|
|
83
|
+
|
|
84
|
+
def get_exchange_schedule(self) -> JsonDict:
|
|
85
|
+
return self.get("/v1/exchange/schedule")
|
|
86
|
+
|
|
87
|
+
# --- Markets ---
|
|
88
|
+
|
|
89
|
+
def get_markets(
|
|
90
|
+
self,
|
|
91
|
+
*,
|
|
92
|
+
status: str | None = None,
|
|
93
|
+
cursor: str | None = None,
|
|
94
|
+
limit: int | None = None,
|
|
95
|
+
) -> JsonDict:
|
|
96
|
+
return self.get(
|
|
97
|
+
"/v1/markets",
|
|
98
|
+
params={"status": status, "cursor": cursor, "limit": limit},
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
def get_market(self, market_id: int) -> JsonDict:
|
|
102
|
+
return self.get(f"/v1/markets/{market_id}")
|
|
103
|
+
|
|
104
|
+
def get_orderbook(self, market_id: int, *, depth: int | None = None) -> JsonDict:
|
|
105
|
+
return self.get(
|
|
106
|
+
f"/v1/markets/{market_id}/orderbook",
|
|
107
|
+
params={"depth": depth},
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
def get_trades(
|
|
111
|
+
self,
|
|
112
|
+
market_id: int,
|
|
113
|
+
*,
|
|
114
|
+
cursor: str | None = None,
|
|
115
|
+
limit: int | None = None,
|
|
116
|
+
) -> JsonDict:
|
|
117
|
+
return self.get(
|
|
118
|
+
f"/v1/markets/{market_id}/trades",
|
|
119
|
+
params={"cursor": cursor, "limit": limit},
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
# --- Rounds / oracle ---
|
|
123
|
+
|
|
124
|
+
def get_rounds(
|
|
125
|
+
self,
|
|
126
|
+
*,
|
|
127
|
+
limit: int | None = None,
|
|
128
|
+
cursor: str | None = None,
|
|
129
|
+
category: str | None = None,
|
|
130
|
+
) -> JsonDict:
|
|
131
|
+
return self.get(
|
|
132
|
+
"/v1/rounds",
|
|
133
|
+
params={"limit": limit, "cursor": cursor, "category": category},
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
def get_round(self, round_id: int | str) -> JsonDict:
|
|
137
|
+
return self.get(f"/v1/rounds/{round_id}")
|
|
138
|
+
|
|
139
|
+
def get_oracle_price(self) -> JsonDict:
|
|
140
|
+
return self.get("/v1/oracle/price")
|
|
141
|
+
|
|
142
|
+
# --- Portfolio ---
|
|
143
|
+
|
|
144
|
+
def get_balance(self) -> JsonDict:
|
|
145
|
+
return self.get("/v1/portfolio/balance")
|
|
146
|
+
|
|
147
|
+
def get_positions(
|
|
148
|
+
self,
|
|
149
|
+
*,
|
|
150
|
+
market_id: int | None = None,
|
|
151
|
+
cursor: str | None = None,
|
|
152
|
+
limit: int | None = None,
|
|
153
|
+
) -> JsonDict:
|
|
154
|
+
return self.get(
|
|
155
|
+
"/v1/portfolio/positions",
|
|
156
|
+
params={"market_id": market_id, "cursor": cursor, "limit": limit},
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
def get_fills(
|
|
160
|
+
self,
|
|
161
|
+
*,
|
|
162
|
+
market_id: int | None = None,
|
|
163
|
+
order_id: str | None = None,
|
|
164
|
+
cursor: str | None = None,
|
|
165
|
+
limit: int | None = None,
|
|
166
|
+
) -> JsonDict:
|
|
167
|
+
return self.get(
|
|
168
|
+
"/v1/portfolio/fills",
|
|
169
|
+
params={
|
|
170
|
+
"market_id": market_id,
|
|
171
|
+
"order_id": order_id,
|
|
172
|
+
"cursor": cursor,
|
|
173
|
+
"limit": limit,
|
|
174
|
+
},
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
def get_orders(
|
|
178
|
+
self,
|
|
179
|
+
*,
|
|
180
|
+
market_id: int | None = None,
|
|
181
|
+
status: str | None = None,
|
|
182
|
+
client_order_id: str | None = None,
|
|
183
|
+
cursor: str | None = None,
|
|
184
|
+
limit: int | None = None,
|
|
185
|
+
) -> JsonDict:
|
|
186
|
+
return self.get(
|
|
187
|
+
"/v1/portfolio/orders",
|
|
188
|
+
params={
|
|
189
|
+
"market_id": market_id,
|
|
190
|
+
"status": status,
|
|
191
|
+
"client_order_id": client_order_id,
|
|
192
|
+
"cursor": cursor,
|
|
193
|
+
"limit": limit,
|
|
194
|
+
},
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
def get_order(self, order_id: str) -> JsonDict:
|
|
198
|
+
return self.get(f"/v1/portfolio/orders/{order_id}")
|
|
199
|
+
|
|
200
|
+
def place_order(
|
|
201
|
+
self,
|
|
202
|
+
*,
|
|
203
|
+
client_order_id: str | int,
|
|
204
|
+
market_id: int,
|
|
205
|
+
side: str,
|
|
206
|
+
outcome: str,
|
|
207
|
+
type: str,
|
|
208
|
+
qty: int,
|
|
209
|
+
tick: int | None = None,
|
|
210
|
+
tif: str | None = None,
|
|
211
|
+
worst_tick: int | None = None,
|
|
212
|
+
expiry_ts: str | None = None,
|
|
213
|
+
max_cost: str | None = None,
|
|
214
|
+
group_id: int | None = None,
|
|
215
|
+
post_only: bool = False,
|
|
216
|
+
reduce_only: bool = False,
|
|
217
|
+
cancel_on_pause: bool = False,
|
|
218
|
+
stp_maker: bool = False,
|
|
219
|
+
) -> JsonDict:
|
|
220
|
+
body: JsonDict = {
|
|
221
|
+
"client_order_id": str(client_order_id),
|
|
222
|
+
"market_id": market_id,
|
|
223
|
+
"side": side,
|
|
224
|
+
"outcome": outcome,
|
|
225
|
+
"type": type,
|
|
226
|
+
"qty": qty,
|
|
227
|
+
}
|
|
228
|
+
if tick is not None:
|
|
229
|
+
body["tick"] = tick
|
|
230
|
+
if tif is not None:
|
|
231
|
+
body["tif"] = tif
|
|
232
|
+
if worst_tick is not None:
|
|
233
|
+
body["worst_tick"] = worst_tick
|
|
234
|
+
if expiry_ts is not None:
|
|
235
|
+
body["expiry_ts"] = expiry_ts
|
|
236
|
+
if max_cost is not None:
|
|
237
|
+
body["max_cost"] = max_cost
|
|
238
|
+
if group_id is not None:
|
|
239
|
+
body["group_id"] = group_id
|
|
240
|
+
if post_only:
|
|
241
|
+
body["post_only"] = True
|
|
242
|
+
if reduce_only:
|
|
243
|
+
body["reduce_only"] = True
|
|
244
|
+
if cancel_on_pause:
|
|
245
|
+
body["cancel_on_pause"] = True
|
|
246
|
+
if stp_maker:
|
|
247
|
+
body["stp_maker"] = True
|
|
248
|
+
return self.post("/v1/portfolio/orders", json=body)
|
|
249
|
+
|
|
250
|
+
def place_orders_batch(self, orders: list[JsonDict]) -> Any:
|
|
251
|
+
return self.post("/v1/portfolio/orders/batch", json={"orders": orders})
|
|
252
|
+
|
|
253
|
+
def cancel_order(self, order_id: str) -> JsonDict:
|
|
254
|
+
return self.delete(f"/v1/portfolio/orders/{order_id}")
|
|
255
|
+
|
|
256
|
+
def mass_cancel(
|
|
257
|
+
self,
|
|
258
|
+
*,
|
|
259
|
+
market_id: int | None = None,
|
|
260
|
+
group_id: int | None = None,
|
|
261
|
+
) -> JsonDict:
|
|
262
|
+
return self.delete(
|
|
263
|
+
"/v1/portfolio/orders",
|
|
264
|
+
params={"market_id": market_id, "group_id": group_id},
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
def decrease_order(self, order_id: str, *, new_qty: int) -> JsonDict:
|
|
268
|
+
return self.post(
|
|
269
|
+
f"/v1/portfolio/orders/{order_id}/decrease",
|
|
270
|
+
json={"new_qty": new_qty},
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
# --- Funding (read) ---
|
|
274
|
+
|
|
275
|
+
def get_deposit_address(self) -> JsonDict:
|
|
276
|
+
return self.get("/v1/deposit-address")
|
|
277
|
+
|
|
278
|
+
# --- WebSocket ---
|
|
279
|
+
|
|
280
|
+
def websocket(self) -> WebSocketClient:
|
|
281
|
+
return WebSocketClient(
|
|
282
|
+
api_key=self.api_key,
|
|
283
|
+
secret=self._secret,
|
|
284
|
+
ws_url=self.ws_url,
|
|
285
|
+
)
|
omnibook/errors.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Typed errors for Omnibook API responses."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class OmnibookError(Exception):
|
|
9
|
+
"""Base error for the Omnibook SDK."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class OmnibookAPIError(OmnibookError):
|
|
13
|
+
"""HTTP error with the venue's stable error envelope."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
status_code: int,
|
|
18
|
+
*,
|
|
19
|
+
code: str | None = None,
|
|
20
|
+
message: str | None = None,
|
|
21
|
+
origin: str | None = None,
|
|
22
|
+
num: int | None = None,
|
|
23
|
+
details: Any = None,
|
|
24
|
+
body: Any = None,
|
|
25
|
+
retry_after: str | None = None,
|
|
26
|
+
) -> None:
|
|
27
|
+
self.status_code = status_code
|
|
28
|
+
self.code = code
|
|
29
|
+
self.message = message
|
|
30
|
+
self.origin = origin
|
|
31
|
+
self.num = num
|
|
32
|
+
self.details = details
|
|
33
|
+
self.body = body
|
|
34
|
+
self.retry_after = retry_after
|
|
35
|
+
parts = [f"HTTP {status_code}"]
|
|
36
|
+
if code:
|
|
37
|
+
parts.append(code)
|
|
38
|
+
if message:
|
|
39
|
+
parts.append(message)
|
|
40
|
+
super().__init__(": ".join(parts))
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def is_auth_error(self) -> bool:
|
|
44
|
+
return self.status_code == 401 or self.code == "unauthorized"
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def is_rate_limited(self) -> bool:
|
|
48
|
+
return self.status_code == 429 or self.code == "rate_limited"
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def is_sequencing_timeout(self) -> bool:
|
|
52
|
+
return self.status_code == 504 or self.code == "sequencing_timeout"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class OmnibookAuthError(OmnibookAPIError):
|
|
56
|
+
"""401 / unauthorized — bad signature, unknown key, or clock skew."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class OmnibookRateLimitError(OmnibookAPIError):
|
|
60
|
+
"""429 — back off using ``retry_after`` / ``details.retry_after_ms``."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class OmnibookTimeoutError(OmnibookAPIError):
|
|
64
|
+
"""504 sequencing timeout — retry with the same ``client_order_id``."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class OmnibookWSError(OmnibookError):
|
|
68
|
+
"""WebSocket command or protocol error."""
|
|
69
|
+
|
|
70
|
+
def __init__(self, wscode: int | None = None, text: str | None = None) -> None:
|
|
71
|
+
self.wscode = wscode
|
|
72
|
+
self.text = text
|
|
73
|
+
msg = text or "websocket error"
|
|
74
|
+
if wscode is not None:
|
|
75
|
+
msg = f"wscode={wscode}: {msg}"
|
|
76
|
+
super().__init__(msg)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def raise_for_response(status_code: int, data: Any, headers: dict[str, str] | None = None) -> None:
|
|
80
|
+
"""Raise a typed error from a non-2xx response body."""
|
|
81
|
+
if 200 <= status_code < 300:
|
|
82
|
+
return
|
|
83
|
+
|
|
84
|
+
headers = headers or {}
|
|
85
|
+
retry_after = headers.get("retry-after") or headers.get("Retry-After")
|
|
86
|
+
err = {}
|
|
87
|
+
if isinstance(data, dict):
|
|
88
|
+
maybe = data.get("error")
|
|
89
|
+
if isinstance(maybe, dict):
|
|
90
|
+
err = maybe
|
|
91
|
+
elif "code" in data:
|
|
92
|
+
err = data
|
|
93
|
+
|
|
94
|
+
code = err.get("code")
|
|
95
|
+
message = err.get("message")
|
|
96
|
+
origin = err.get("origin")
|
|
97
|
+
num = err.get("num")
|
|
98
|
+
details = err.get("details")
|
|
99
|
+
|
|
100
|
+
kwargs = dict(
|
|
101
|
+
status_code=status_code,
|
|
102
|
+
code=code,
|
|
103
|
+
message=message,
|
|
104
|
+
origin=origin,
|
|
105
|
+
num=num,
|
|
106
|
+
details=details,
|
|
107
|
+
body=data,
|
|
108
|
+
retry_after=retry_after,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
if status_code == 401 or code == "unauthorized":
|
|
112
|
+
raise OmnibookAuthError(**kwargs)
|
|
113
|
+
if status_code == 429 or code == "rate_limited":
|
|
114
|
+
raise OmnibookRateLimitError(**kwargs)
|
|
115
|
+
if status_code == 504 or code == "sequencing_timeout":
|
|
116
|
+
raise OmnibookTimeoutError(**kwargs)
|
|
117
|
+
raise OmnibookAPIError(**kwargs)
|
omnibook/models.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Lightweight response helpers. Venue responses are plain dicts; ignore unknown fields."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Mapping, MutableMapping
|
|
6
|
+
from urllib.parse import urlencode
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
JsonDict = dict[str, Any]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def encode_query(params: Mapping[str, Any] | None) -> str:
|
|
13
|
+
"""Build a query string, omitting None values. Stable key order for signing."""
|
|
14
|
+
if not params:
|
|
15
|
+
return ""
|
|
16
|
+
items: list[tuple[str, str]] = []
|
|
17
|
+
for key in sorted(params.keys()):
|
|
18
|
+
value = params[key]
|
|
19
|
+
if value is None:
|
|
20
|
+
continue
|
|
21
|
+
if isinstance(value, bool):
|
|
22
|
+
items.append((key, "true" if value else "false"))
|
|
23
|
+
elif isinstance(value, (list, tuple)):
|
|
24
|
+
items.append((key, ",".join(str(v) for v in value)))
|
|
25
|
+
else:
|
|
26
|
+
items.append((key, str(value)))
|
|
27
|
+
if not items:
|
|
28
|
+
return ""
|
|
29
|
+
return urlencode(items)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def path_with_query(path: str, params: Mapping[str, Any] | None = None) -> str:
|
|
33
|
+
qs = encode_query(params)
|
|
34
|
+
return f"{path}?{qs}" if qs else path
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def compact_json_bytes(payload: MutableMapping[str, Any] | Mapping[str, Any] | list[Any]) -> bytes:
|
|
38
|
+
"""Serialize JSON with separators that match what we sign and send."""
|
|
39
|
+
import json
|
|
40
|
+
|
|
41
|
+
return json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
omnibook/py.typed
ADDED
|
File without changes
|
omnibook/ws.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""WebSocket clients for Omnibook market data and private user channel."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import itertools
|
|
7
|
+
from typing import Any, AsyncIterator, Iterator
|
|
8
|
+
|
|
9
|
+
from websockets.sync.client import connect as sync_connect
|
|
10
|
+
from websockets.asyncio.client import connect as async_connect
|
|
11
|
+
|
|
12
|
+
from .auth import ws_handshake_headers
|
|
13
|
+
from .errors import OmnibookWSError
|
|
14
|
+
from .models import JsonDict
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
PUBLIC_CHANNELS = frozenset(
|
|
18
|
+
{"orderbook_delta", "trades", "ticker", "rounds", "oracle"}
|
|
19
|
+
)
|
|
20
|
+
PRIVATE_CHANNELS = frozenset({"user"})
|
|
21
|
+
CHANNELS_NEEDING_MARKETS = frozenset({"orderbook_delta", "trades", "ticker"})
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _WSCommandMixin:
|
|
25
|
+
_next_id: Any
|
|
26
|
+
_ws: Any
|
|
27
|
+
|
|
28
|
+
def _build_cmd(
|
|
29
|
+
self,
|
|
30
|
+
cmd: str,
|
|
31
|
+
*,
|
|
32
|
+
channels: list[str] | None = None,
|
|
33
|
+
market_ids: list[int] | None = None,
|
|
34
|
+
sids: list[int] | None = None,
|
|
35
|
+
) -> JsonDict:
|
|
36
|
+
msg_id = next(self._next_id)
|
|
37
|
+
payload: JsonDict = {"id": msg_id, "cmd": cmd}
|
|
38
|
+
params: JsonDict = {}
|
|
39
|
+
if channels is not None:
|
|
40
|
+
params["channels"] = list(channels)
|
|
41
|
+
if market_ids is not None:
|
|
42
|
+
params["market_ids"] = list(market_ids)
|
|
43
|
+
if sids is not None:
|
|
44
|
+
params["sids"] = list(sids)
|
|
45
|
+
if params:
|
|
46
|
+
payload["params"] = params
|
|
47
|
+
return payload
|
|
48
|
+
|
|
49
|
+
@staticmethod
|
|
50
|
+
def _check_reply(data: JsonDict) -> JsonDict:
|
|
51
|
+
if data.get("type") == "error":
|
|
52
|
+
msg = data.get("msg") or {}
|
|
53
|
+
raise OmnibookWSError(msg.get("wscode"), msg.get("text"))
|
|
54
|
+
return data
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class WebSocketClient(_WSCommandMixin):
|
|
58
|
+
"""Synchronous WebSocket client (websockets sync API)."""
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
*,
|
|
63
|
+
api_key: str,
|
|
64
|
+
secret: bytes,
|
|
65
|
+
ws_url: str,
|
|
66
|
+
) -> None:
|
|
67
|
+
self._api_key = api_key
|
|
68
|
+
self._secret = secret
|
|
69
|
+
self._ws_url = ws_url
|
|
70
|
+
self._ws = None
|
|
71
|
+
self._next_id = itertools.count(1)
|
|
72
|
+
self._last_seq: dict[int, int] = {}
|
|
73
|
+
|
|
74
|
+
def connect(self) -> WebSocketClient:
|
|
75
|
+
headers = ws_handshake_headers(self._api_key, self._secret)
|
|
76
|
+
self._ws = sync_connect(self._ws_url, additional_headers=headers)
|
|
77
|
+
return self
|
|
78
|
+
|
|
79
|
+
def close(self) -> None:
|
|
80
|
+
if self._ws is not None:
|
|
81
|
+
self._ws.close()
|
|
82
|
+
self._ws = None
|
|
83
|
+
|
|
84
|
+
def __enter__(self) -> WebSocketClient:
|
|
85
|
+
return self.connect()
|
|
86
|
+
|
|
87
|
+
def __exit__(self, *exc: object) -> None:
|
|
88
|
+
self.close()
|
|
89
|
+
|
|
90
|
+
def _send(self, payload: JsonDict) -> None:
|
|
91
|
+
if self._ws is None:
|
|
92
|
+
raise RuntimeError("WebSocket is not connected")
|
|
93
|
+
self._ws.send(json.dumps(payload, separators=(",", ":")))
|
|
94
|
+
|
|
95
|
+
def _recv_raw(self) -> JsonDict:
|
|
96
|
+
if self._ws is None:
|
|
97
|
+
raise RuntimeError("WebSocket is not connected")
|
|
98
|
+
raw = self._ws.recv()
|
|
99
|
+
if isinstance(raw, bytes):
|
|
100
|
+
raw = raw.decode("utf-8")
|
|
101
|
+
return json.loads(raw)
|
|
102
|
+
|
|
103
|
+
def subscribe(
|
|
104
|
+
self,
|
|
105
|
+
*,
|
|
106
|
+
channels: list[str],
|
|
107
|
+
market_ids: list[int] | None = None,
|
|
108
|
+
) -> list[JsonDict]:
|
|
109
|
+
needs_markets = any(c in CHANNELS_NEEDING_MARKETS for c in channels)
|
|
110
|
+
if needs_markets and not market_ids:
|
|
111
|
+
raise ValueError("market_ids required for orderbook_delta, trades, and ticker")
|
|
112
|
+
self._send(
|
|
113
|
+
self._build_cmd("subscribe", channels=channels, market_ids=market_ids)
|
|
114
|
+
)
|
|
115
|
+
replies: list[JsonDict] = []
|
|
116
|
+
for _ in channels:
|
|
117
|
+
replies.append(self._check_reply(self._recv_raw()))
|
|
118
|
+
return replies
|
|
119
|
+
|
|
120
|
+
def unsubscribe(
|
|
121
|
+
self,
|
|
122
|
+
*,
|
|
123
|
+
channels: list[str] | None = None,
|
|
124
|
+
market_ids: list[int] | None = None,
|
|
125
|
+
sids: list[int] | None = None,
|
|
126
|
+
) -> list[JsonDict]:
|
|
127
|
+
self._send(
|
|
128
|
+
self._build_cmd(
|
|
129
|
+
"unsubscribe",
|
|
130
|
+
channels=channels,
|
|
131
|
+
market_ids=market_ids,
|
|
132
|
+
sids=sids,
|
|
133
|
+
)
|
|
134
|
+
)
|
|
135
|
+
# Venue may reply per channel; collect until timeout isn't available —
|
|
136
|
+
# read one reply and return; callers can drain with recv().
|
|
137
|
+
reply = self._check_reply(self._recv_raw())
|
|
138
|
+
return [reply]
|
|
139
|
+
|
|
140
|
+
def list_subscriptions(self) -> JsonDict:
|
|
141
|
+
self._send(self._build_cmd("list_subscriptions"))
|
|
142
|
+
return self._check_reply(self._recv_raw())
|
|
143
|
+
|
|
144
|
+
def recv(self, *, check_gaps: bool = True) -> JsonDict:
|
|
145
|
+
data = self._recv_raw()
|
|
146
|
+
if check_gaps and "sid" in data and "seq" in data:
|
|
147
|
+
sid = int(data["sid"])
|
|
148
|
+
seq = int(data["seq"])
|
|
149
|
+
prev = self._last_seq.get(sid)
|
|
150
|
+
if prev is not None and seq != prev + 1:
|
|
151
|
+
# Public channels: gap ⇒ caller should resubscribe.
|
|
152
|
+
data["_gap"] = True
|
|
153
|
+
data["_expected_seq"] = prev + 1
|
|
154
|
+
self._last_seq[sid] = seq
|
|
155
|
+
return data
|
|
156
|
+
|
|
157
|
+
def __iter__(self) -> Iterator[JsonDict]:
|
|
158
|
+
while True:
|
|
159
|
+
yield self.recv()
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class AsyncWebSocketClient(_WSCommandMixin):
|
|
163
|
+
"""Asynchronous WebSocket client."""
|
|
164
|
+
|
|
165
|
+
def __init__(
|
|
166
|
+
self,
|
|
167
|
+
*,
|
|
168
|
+
api_key: str,
|
|
169
|
+
secret: bytes,
|
|
170
|
+
ws_url: str,
|
|
171
|
+
) -> None:
|
|
172
|
+
self._api_key = api_key
|
|
173
|
+
self._secret = secret
|
|
174
|
+
self._ws_url = ws_url
|
|
175
|
+
self._ws = None
|
|
176
|
+
self._next_id = itertools.count(1)
|
|
177
|
+
self._last_seq: dict[int, int] = {}
|
|
178
|
+
|
|
179
|
+
async def connect(self) -> AsyncWebSocketClient:
|
|
180
|
+
headers = ws_handshake_headers(self._api_key, self._secret)
|
|
181
|
+
self._ws = await async_connect(self._ws_url, additional_headers=headers)
|
|
182
|
+
return self
|
|
183
|
+
|
|
184
|
+
async def close(self) -> None:
|
|
185
|
+
if self._ws is not None:
|
|
186
|
+
await self._ws.close()
|
|
187
|
+
self._ws = None
|
|
188
|
+
|
|
189
|
+
async def __aenter__(self) -> AsyncWebSocketClient:
|
|
190
|
+
return await self.connect()
|
|
191
|
+
|
|
192
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
193
|
+
await self.close()
|
|
194
|
+
|
|
195
|
+
async def _send(self, payload: JsonDict) -> None:
|
|
196
|
+
if self._ws is None:
|
|
197
|
+
raise RuntimeError("WebSocket is not connected")
|
|
198
|
+
await self._ws.send(json.dumps(payload, separators=(",", ":")))
|
|
199
|
+
|
|
200
|
+
async def _recv_raw(self) -> JsonDict:
|
|
201
|
+
if self._ws is None:
|
|
202
|
+
raise RuntimeError("WebSocket is not connected")
|
|
203
|
+
raw = await self._ws.recv()
|
|
204
|
+
if isinstance(raw, bytes):
|
|
205
|
+
raw = raw.decode("utf-8")
|
|
206
|
+
return json.loads(raw)
|
|
207
|
+
|
|
208
|
+
async def subscribe(
|
|
209
|
+
self,
|
|
210
|
+
*,
|
|
211
|
+
channels: list[str],
|
|
212
|
+
market_ids: list[int] | None = None,
|
|
213
|
+
) -> list[JsonDict]:
|
|
214
|
+
needs_markets = any(c in CHANNELS_NEEDING_MARKETS for c in channels)
|
|
215
|
+
if needs_markets and not market_ids:
|
|
216
|
+
raise ValueError("market_ids required for orderbook_delta, trades, and ticker")
|
|
217
|
+
await self._send(
|
|
218
|
+
self._build_cmd("subscribe", channels=channels, market_ids=market_ids)
|
|
219
|
+
)
|
|
220
|
+
replies: list[JsonDict] = []
|
|
221
|
+
for _ in channels:
|
|
222
|
+
replies.append(self._check_reply(await self._recv_raw()))
|
|
223
|
+
return replies
|
|
224
|
+
|
|
225
|
+
async def unsubscribe(
|
|
226
|
+
self,
|
|
227
|
+
*,
|
|
228
|
+
channels: list[str] | None = None,
|
|
229
|
+
market_ids: list[int] | None = None,
|
|
230
|
+
sids: list[int] | None = None,
|
|
231
|
+
) -> list[JsonDict]:
|
|
232
|
+
await self._send(
|
|
233
|
+
self._build_cmd(
|
|
234
|
+
"unsubscribe",
|
|
235
|
+
channels=channels,
|
|
236
|
+
market_ids=market_ids,
|
|
237
|
+
sids=sids,
|
|
238
|
+
)
|
|
239
|
+
)
|
|
240
|
+
reply = self._check_reply(await self._recv_raw())
|
|
241
|
+
return [reply]
|
|
242
|
+
|
|
243
|
+
async def list_subscriptions(self) -> JsonDict:
|
|
244
|
+
await self._send(self._build_cmd("list_subscriptions"))
|
|
245
|
+
return self._check_reply(await self._recv_raw())
|
|
246
|
+
|
|
247
|
+
async def recv(self, *, check_gaps: bool = True) -> JsonDict:
|
|
248
|
+
data = await self._recv_raw()
|
|
249
|
+
if check_gaps and "sid" in data and "seq" in data:
|
|
250
|
+
sid = int(data["sid"])
|
|
251
|
+
seq = int(data["seq"])
|
|
252
|
+
prev = self._last_seq.get(sid)
|
|
253
|
+
if prev is not None and seq != prev + 1:
|
|
254
|
+
data["_gap"] = True
|
|
255
|
+
data["_expected_seq"] = prev + 1
|
|
256
|
+
self._last_seq[sid] = seq
|
|
257
|
+
return data
|
|
258
|
+
|
|
259
|
+
async def __aiter__(self) -> AsyncIterator[JsonDict]:
|
|
260
|
+
while True:
|
|
261
|
+
yield await self.recv()
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: omnibook
|
|
3
|
+
Version: 1.1.0
|
|
4
|
+
Summary: Official Python SDK for the Omnibook prediction market exchange
|
|
5
|
+
Project-URL: Homepage, https://omnibook.xyz
|
|
6
|
+
Project-URL: Documentation, https://docs.omnibook.xyz/sdk/python
|
|
7
|
+
Project-URL: Repository, https://github.com/OmniBook-HQ/python-sdk-v1
|
|
8
|
+
Project-URL: Issues, https://github.com/OmniBook-HQ/python-sdk-v1/issues
|
|
9
|
+
Author-email: Raeth AI <devs@omnibook.xyz>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: exchange,omnibook,prediction-markets,sdk,trading
|
|
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.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Requires-Dist: httpx>=0.27
|
|
25
|
+
Requires-Dist: websockets>=12.0
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
29
|
+
Requires-Dist: respx>=0.21; extra == 'dev'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# Omnibook Python SDK
|
|
33
|
+
|
|
34
|
+
Official Python client for the [Omnibook](https://omnibook.xyz) prediction market
|
|
35
|
+
exchange. Sign up, create an API key, install this package, and trade.
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install omnibook
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from omnibook import Client
|
|
43
|
+
|
|
44
|
+
client = Client(api_key="<alphanumeric-api-key>", api_secret="<64-char-hex-secret>")
|
|
45
|
+
|
|
46
|
+
status = client.get_exchange_status()
|
|
47
|
+
rounds = client.get_rounds(limit=5)
|
|
48
|
+
order = client.place_order(
|
|
49
|
+
client_order_id="42",
|
|
50
|
+
market_id=66,
|
|
51
|
+
side="buy",
|
|
52
|
+
outcome="yes",
|
|
53
|
+
type="limit",
|
|
54
|
+
tick=47,
|
|
55
|
+
qty=10,
|
|
56
|
+
tif="gtc",
|
|
57
|
+
post_only=True,
|
|
58
|
+
)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Prerequisites
|
|
62
|
+
|
|
63
|
+
1. Sign in at [omnibook.xyz](https://omnibook.xyz).
|
|
64
|
+
2. Deposit USDC (bot keys cannot withdraw).
|
|
65
|
+
3. Create a key under **Settings → API keys**. Copy the **API key** and **secret**
|
|
66
|
+
(the secret is shown once).
|
|
67
|
+
|
|
68
|
+
Docs: [docs.omnibook.xyz/sdk/python](https://docs.omnibook.xyz/sdk/python)
|
|
69
|
+
|
|
70
|
+
## Environments
|
|
71
|
+
|
|
72
|
+
| Env | REST | WebSocket |
|
|
73
|
+
| --- | --- | --- |
|
|
74
|
+
| Production (default) | `https://api.omnibook.xyz` | `wss://api.omnibook.xyz/v1/ws` |
|
|
75
|
+
| Local | `http://127.0.0.1:9104` | `ws://127.0.0.1:9105/v1/ws` |
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
client = Client(
|
|
79
|
+
api_key="...",
|
|
80
|
+
api_secret="...",
|
|
81
|
+
base_url="http://127.0.0.1:9104",
|
|
82
|
+
ws_url="ws://127.0.0.1:9105/v1/ws",
|
|
83
|
+
)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Sync and async
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from omnibook import Client, AsyncClient
|
|
90
|
+
|
|
91
|
+
# Sync
|
|
92
|
+
with Client(api_key=..., api_secret=...) as client:
|
|
93
|
+
print(client.get_balance())
|
|
94
|
+
|
|
95
|
+
# Async
|
|
96
|
+
async with AsyncClient(api_key=..., api_secret=...) as client:
|
|
97
|
+
print(await client.get_balance())
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## WebSocket
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from omnibook import Client
|
|
104
|
+
|
|
105
|
+
with Client(api_key=..., api_secret=...) as client:
|
|
106
|
+
with client.websocket() as ws:
|
|
107
|
+
ws.subscribe(channels=["rounds", "oracle", "user"])
|
|
108
|
+
ws.subscribe(channels=["orderbook_delta", "trades"], market_ids=[66])
|
|
109
|
+
for msg in ws:
|
|
110
|
+
print(msg)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Auth note
|
|
114
|
+
|
|
115
|
+
Every request is HMAC-SHA256 signed. Settings hands you a **64-character hex**
|
|
116
|
+
secret (32 raw bytes). Pass that string (or a legacy base64 secret) to
|
|
117
|
+
`api_secret` — the SDK hex-/base64-decodes it to the raw HMAC key for you.
|
|
118
|
+
|
|
119
|
+
## Tests
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
pip install -e ".[dev]"
|
|
123
|
+
pytest # unit tests (mocked)
|
|
124
|
+
OMNIBOOK_RUN_INTEGRATION=1 \
|
|
125
|
+
OMNIBOOK_API_KEY=... \
|
|
126
|
+
OMNIBOOK_API_SECRET=... \
|
|
127
|
+
pytest -m integration # live venue
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## License
|
|
131
|
+
|
|
132
|
+
MIT
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
omnibook/__init__.py,sha256=j8B6RgrzAl8zQQ3UDeb8BVqVHnEXvE6yM8BJ66N26DE,779
|
|
2
|
+
omnibook/_base.py,sha256=549FtU6yClVFvwH6B6PaDq-sRljkumUKyx0EvJToFzE,1911
|
|
3
|
+
omnibook/async_client.py,sha256=xftGhT6Llq1n0cRLUgWDoLNez6RO0Dhr6yqoZGqjWpw,8344
|
|
4
|
+
omnibook/auth.py,sha256=kI-Vm0-RDHP7UB3iPWyag710ZNfjvj0ktXxJEbIXipQ,2704
|
|
5
|
+
omnibook/client.py,sha256=emXWEpf88yTmmm2M8ozakor03Kb5CBX21EXwAr2UrUk,8213
|
|
6
|
+
omnibook/errors.py,sha256=_mYwybbmjp5RRpP9NE_UUgcd1d6u8EYhMPlCFdDUeIo,3369
|
|
7
|
+
omnibook/models.py,sha256=umMuaqCz_1mEIbCOCEtVWsz1W-BP6BUpW2ToQSLihWU,1343
|
|
8
|
+
omnibook/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
omnibook/ws.py,sha256=nDg_jspG0gICLZ02E7GDdiHJEQUbsos7JlrEaaTgXjs,8312
|
|
10
|
+
omnibook-1.1.0.dist-info/METADATA,sha256=R3V91W5Y_gv7lfvjuu3QESLsAL3POYJUiSsFEJ7Rh7M,3651
|
|
11
|
+
omnibook-1.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
12
|
+
omnibook-1.1.0.dist-info/licenses/LICENSE,sha256=wUrFh94pDqMF284judvdUW-EKxLNLHEA_V-Ejqtw59Q,1065
|
|
13
|
+
omnibook-1.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Raeth AI
|
|
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.
|