Repository navigation
Expand file tree
/
Copy pathodds_api.py
More file actions
230 lines (191 loc) · 9.72 KB
/
Copy pathodds_api.py
File metadata and controls
230 lines (191 loc) · 9.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""Small helper for the Diamond Exch API. Python 3.8+, needs only `requests`.
DIAMONDEXCHAPI_KEY your key (fg_test_... for the sandbox, fg_live_... for live)
DIAMONDEXCHAPI_BASE_URL optional, defaults to the sandbox: https://api-sandbox.diamondexchapi.live
"""
import json
import os
import random
import sys
import time
import requests
BASE = os.environ.get("DIAMONDEXCHAPI_BASE_URL", "https://api-sandbox.diamondexchapi.live").rstrip("/")
DEFAULT_SPORT = os.environ.get("SPORT", "")
def api_key():
key = os.environ.get("DIAMONDEXCHAPI_KEY")
if not key:
sys.exit("Set DIAMONDEXCHAPI_KEY first. Ask for a sandbox key at https://diamondexchapi.live/telegram")
return key
def is_sandbox_key():
return api_key().startswith("fg_test_")
class ApiError(Exception):
def __init__(self, status, code, message, request_id=None):
super().__init__(f"{status} {code}: {message}" + (f" (X-Request-Id {request_id})" if request_id else ""))
self.status, self.code, self.request_id = status, code, request_id
session = requests.Session()
session.headers.update({"Accept": "application/json", "User-Agent": "diamondexchapi-api-examples/1.0"})
# requests sends Accept-Encoding: gzip and decompresses for you.
_last_call = [0.0]
def _pace():
# The sandbox allows 2 requests per second; 0.55 s between calls stays inside it.
wait = _last_call[0] + 0.55 - time.time()
if wait > 0:
time.sleep(wait)
_last_call[0] = time.time()
def get(path, params=None, headers=None):
"""GET a path. Retries 429 rate_limited and 503 starting. Returns the Response."""
params = {k: v for k, v in (params or {}).items() if v not in (None, "")}
h = {"X-API-Key": api_key(), **(headers or {})}
for attempt in range(5):
_pace()
r = session.get(BASE + path, params=params, headers=h, timeout=(10, 30))
if r.status_code < 400:
return r
try:
body = r.json()
except ValueError:
body = {}
code = body.get("code", f"http_{r.status_code}")
if attempt < 4 and (r.status_code, code) in ((429, "rate_limited"), (503, "starting")):
after = float(r.headers.get("Retry-After") or 2)
print(f"... {code}, retrying in {after:g}s", file=sys.stderr)
time.sleep(after)
continue
raise ApiError(r.status_code, code, body.get("message", r.text[:200]), r.headers.get("X-Request-Id"))
def get_json(path, params=None):
return get(path, params).json()
def inplay_event_ids(limit, sport=None):
sport = DEFAULT_SPORT if sport is None else sport
events = get_json("/v1/events", {"state": "inplay", "sport": sport})["events"]
return [e["id"] for e in events[:limit]]
def main(fn):
"""Run fn(); print API errors cleanly instead of a traceback."""
try:
fn()
except ApiError as e:
print(e, file=sys.stderr)
if e.status == 403:
print("Requests are accepted only from IPs on your allowlist, and a key works only in its own environment.", file=sys.stderr)
sys.exit(1)
except KeyboardInterrupt:
pass
# --- Reading prices ---------------------------------------------------------
# decimal match odds, Yes/No, Odd/Even price = decimal odds, size = amount available
# rate bookmaker price = profit per 100 staked; decimal = 1 + rate / 100
# line fancy / session price = the line, size = the rate; back = Yes, lay = No
# range khado price = first winning score, size = the rate; back only
# Always read `format` first: a bookmaker rate of 13 is decimal 1.13, not 13.
def rate_to_decimal(rate):
return 1 + rate / 100
def tradeable(market, runner=None):
"""Take bets only on OPEN, not stale, with the runner OPEN."""
return (market.get("status") == "OPEN" and not market.get("stale")
and (runner is None or runner.get("status", "OPEN") == "OPEN"))
def best(ladder):
return ladder[0] if ladder else None
def _n(x):
return "-" if x is None else f"{x:g}"
def describe_runner(market, runner):
b, l = best(runner.get("back")), best(runner.get("lay"))
fmt = market.get("format")
if fmt == "decimal":
return (f"back {_n(b['price']) + ' x ' + _n(b['size']) if b else '-'} | "
f"lay {_n(l['price']) + ' x ' + _n(l['size']) if l else '-'}")
if fmt == "rate":
return (f"back {_n(b['price']) + ' (decimal ' + format(rate_to_decimal(b['price']), '.3g') + ')' if b else '-'} | "
f"lay {_n(l['price']) + ' (decimal ' + format(rate_to_decimal(l['price']), '.3g') + ')' if l else '-'}")
if fmt == "line":
return (f"No {_n(l['price']) + ' · ' + _n(l['size']) if l else '-'} | "
f"Yes {_n(b['price']) + ' · ' + _n(b['size']) if b else '-'}")
if fmt == "range":
# The docs name a width but not its field; shown when `width` is present.
w = runner.get("width", market.get("width"))
s = f"Yes from {_n(b['price']) + ' · ' + _n(b['size']) if b else '-'}"
if w and b:
s += f" width {w} (wins on {_n(b['price'])} to {_n(b['price'] + w - 1)})"
return s
return f"unknown format {fmt!r}"
def print_market(m):
flag = f"{m['status']}, stale" if m.get("stale") else m["status"]
print(f" [{flag}] {m['name']} ({m['type']}, {m['format']})" + ("" if tradeable(m) else " <- no bets"))
for r in m.get("runners", []):
rs = f" [{r['status']}]" if r.get("status", "OPEN") != "OPEN" else ""
print(f" {(r['name'] + rs):<28} {describe_runner(m, r)}")
# --- The live stream --------------------------------------------------------
def stream(url, on_message, on_status=lambda s: print(f"[stream] {s}", file=sys.stderr)):
"""Read /v1/stream for ever, resuming with Last-Event-ID.
- sends the id of the last message back as Last-Event-ID on each reconnect,
so nothing is missed;
- a `reconnect` message (about every 14 minutes, and before a server
restart) closes the connection and reconnects at once;
- a dropped connection, including a 15-minute (900 s) cut by a proxy, is
resumed after the server's retry: hint plus jitter;
- 45 s without a byte is a dead connection (heartbeats come every 15 s):
the read timeout below catches it;
- an `error` message, or 400/401/403/404, stops: retrying will not help.
"""
last_id, retry_ms, failures = None, 1000, 0
while True:
rotate = connected = False
headers = {"X-API-Key": api_key(), "Accept": "text/event-stream", "Cache-Control": "no-cache"}
if last_id:
headers["Last-Event-ID"] = last_id
on_status(f"connecting, resuming after {last_id}" if last_id else "connecting")
try:
# (connect timeout, read timeout): no byte for 45 s raises and we reconnect.
with session.get(url, headers=headers, stream=True, timeout=(10, 45)) as r:
if r.status_code >= 400:
try:
body = r.json()
except ValueError:
body = {}
msg = f"{r.status_code} {body.get('code', '')} {body.get('message', '')}".strip()
if r.status_code in (400, 401, 403, 404):
raise ApiError(r.status_code, body.get("code"), body.get("message"), r.headers.get("X-Request-Id"))
after = float(r.headers.get("Retry-After") or min(30, 5 * 2 ** failures))
on_status(f"{msg}; retrying in {after:g} s")
failures += 1
time.sleep(after)
continue
failures, connected = 0, True
on_status("connected")
event, data, msg_id = "message", [], None
for raw in r.iter_lines(chunk_size=None):
line = raw.decode("utf-8")
if line == "": # end of one message
if msg_id is not None:
last_id = msg_id
if data:
text = "\n".join(data)
try:
payload = json.loads(text)
except ValueError:
payload = text
if event == "reconnect":
on_status("server asked us to reconnect")
rotate = True
break
if event == "error":
raise ApiError("stream", payload.get("code"), payload.get("message"))
on_message(event, payload, last_id)
event, data, msg_id = "message", [], None
continue
if line.startswith(":"):
continue # comment, e.g. ": heartbeat"
field, _, value = line.partition(":")
value = value[1:] if value.startswith(" ") else value
if field == "event":
event = value
elif field == "data":
data.append(value)
elif field == "id":
msg_id = value
elif field == "retry" and value.isdigit():
retry_ms = int(value)
if not rotate:
on_status("connection closed by server")
except requests.RequestException as e:
on_status(f"connection lost: {type(e).__name__}")
if not connected:
failures += 1
if not rotate:
time.sleep(min(30, retry_ms / 1000 * 2 ** min(failures, 5)) + random.random())