-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathazuro_integration.py
More file actions
505 lines (444 loc) · 19.8 KB
/
Copy pathazuro_integration.py
File metadata and controls
505 lines (444 loc) · 19.8 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
"""
Azuro data-feed integration: fetch live football games and resolve Under outcomes.
AZURIO (migration): Orchestration stays in Python; this module still contains **feed GraphQL**
for live game listing — that path is **deprecated** in favor of Toolkit v6 REST (see
MIGRATION-AZURO.md). Prefer importing `azuro_feed_client.list_live_football_game_candidates()`
from new code so the Graph→REST swap happens in one place.
Live bettable state: **never** final-trust Graph `Condition.state`; use
`azuro_websocket_live` when AZURO_USE_WEBSOCKET_LIVE=1.
Uses the LiveDataFeed subgraph (OnchainFeed: azuro-data-feed-polygon) until REST migration.
"""
from __future__ import annotations
import logging
import os
from dataclasses import dataclass
from typing import Any
import time
import requests
import json
import subprocess
logger = logging.getLogger(__name__)
_script_dir = os.path.dirname(os.path.abspath(__file__))
_env_path = os.path.join(_script_dir, ".env")
if os.path.isfile(_env_path):
from dotenv import load_dotenv
load_dotenv(_env_path)
# AZURIO: Data-feed Graph (live listing) — intent = "candidate games for live scan"
# AZURIO: REPLACE with Toolkit v6 REST feed utilities when wired (PolygonUSDT).
# Data-feed (live games/odds) uses thegraph-1; prematch meta uses azuro-api-polygon.
# Polygon-only wiring.
AZURO_SUBGRAPH_URL = (os.getenv("AZURO_SUBGRAPH_URL") or "https://thegraph-1.onchainfeed.org/subgraphs/name/azuro-protocol/azuro-data-feed-polygon").strip()
# AZURIO: Prematch/API Graph — intent = "condition + outcome titles when feed titles null"
# AZURIO: MIX — prefer toolkit dictionary / REST; keep Graph as fallback until REST covers meta.
AZURO_PREMATCH_SUBGRAPH_URL = (os.getenv("AZURO_PREMATCH_SUBGRAPH_URL") or "https://thegraph.azuro.org/subgraphs/name/azuro-protocol/azuro-api-polygon").strip()
AZURO_TOOLKIT_CHAIN_ID = 137
AZURO_TOOLKIT_NODE_SCRIPT = os.getenv("AZURO_TOOLKIT_NODE_SCRIPT") or os.path.join(_script_dir, "resolve_markets_by_game_ids.js")
def _truthy(v: Any) -> bool:
return str(v).strip().lower() in {"1", "true", "yes", "y", "on"}
@dataclass
class UnderOutcome:
"""One Under market outcome for an event."""
market_id: str # conditionId
outcome_id: int
odds: float
def _graphql(query: str, variables: dict | None = None) -> dict | None:
# AZURIO: transport for **data-feed** subgraph only; migrate callers to REST via azuro_feed_client.
if not AZURO_SUBGRAPH_URL:
return None
try:
r = requests.post(
AZURO_SUBGRAPH_URL,
json={"query": query, "variables": variables or {}},
timeout=25,
)
r.raise_for_status()
data = r.json()
if "errors" in data:
logger.warning("Subgraph errors: %s", data["errors"])
return None
return data.get("data")
except Exception as e:
logger.warning("Subgraph request failed: %s", e)
return None
def _graphql_prematch(query: str, variables: dict | None = None) -> dict | None:
"""Query the prematch/API subgraph (for condition/outcome titles)."""
# AZURIO: KEEP Graph for this niche meta join until Toolkit REST exposes equivalent.
if not AZURO_PREMATCH_SUBGRAPH_URL:
return None
try:
r = requests.post(
AZURO_PREMATCH_SUBGRAPH_URL,
json={"query": query, "variables": variables or {}},
timeout=25,
)
r.raise_for_status()
data = r.json()
if "errors" in data:
logger.warning("Prematch subgraph errors: %s", data["errors"])
return None
return data.get("data")
except Exception as e:
logger.warning("Prematch subgraph request failed: %s", e)
return None
_CONDITION_META_CACHE: dict[str, dict[str, Any]] = {}
_TOOLKIT_MARKETS_CACHE: dict[str, list[dict]] = {}
def _toolkit_resolve_markets_for_game(game_id: str) -> list[dict] | None:
"""
Resolve live markets using Azuro's JS toolkit (selectionName -> conditionId/outcomeId).
Returns toolkit markets array or None if toolkit fails.
"""
if not AZURO_TOOLKIT_NODE_SCRIPT or not os.path.isfile(AZURO_TOOLKIT_NODE_SCRIPT):
return None
if game_id in _TOOLKIT_MARKETS_CACHE:
return _TOOLKIT_MARKETS_CACHE[game_id]
try:
cmd = ["node", AZURO_TOOLKIT_NODE_SCRIPT, json.dumps([str(game_id)])]
# Ensure toolkit uses the active chain's chainId.
env = {**os.environ, "AZURO_TOOLKIT_CHAIN_ID": str(AZURO_TOOLKIT_CHAIN_ID)}
res = subprocess.run(cmd, capture_output=True, text=True, timeout=35, env=env)
if res.returncode != 0:
logger.debug("Toolkit resolve failed: %s", (res.stderr or "").strip()[:300])
return None
markets = json.loads(res.stdout or "[]")
if not isinstance(markets, list):
return None
_TOOLKIT_MARKETS_CACHE[game_id] = markets
return markets
except Exception as e:
logger.debug("Toolkit resolve exception: %s", e)
return None
def _format_goal_line(line_val: float) -> str:
# Toolkit selectionName uses strings like "Under (3.5)".
s = str(line_val)
if "." in s:
s = s.rstrip("0").rstrip(".")
return s
def _get_condition_meta(condition_id: str) -> dict[str, Any] | None:
"""
Cross-reference prematch/API subgraph to get titles for a condition and its outcomes.
Returns dict with keys: title, outcomes[{outcomeId, title}], or None.
"""
if not condition_id:
return None
if condition_id in _CONDITION_META_CACHE:
return _CONDITION_META_CACHE[condition_id]
# AZURIO: intent = "fetch condition + outcome titles by conditionId (prematch API subgraph)"
# AZURIO: MIX — prefer toolkit-enriched fields; Graph cross-ref only when titles missing.
# conditionId is a BigInt; query by conditionId rather than ID to avoid core+id concatenation issues.
query = """
query ConditionById($cid: BigInt!) {
conditions(where: { conditionId: $cid }, first: 1) {
conditionId
title
outcomes {
outcomeId
title
}
}
}
"""
try:
cid_int = int(condition_id)
except (TypeError, ValueError):
logger.debug("Invalid condition_id for prematch lookup: %r", condition_id)
return None
data = _graphql_prematch(query, {"cid": str(cid_int)})
if not data:
return None
conds = data.get("conditions") or []
if not conds:
return None
c = conds[0]
meta = {
"title": c.get("title") or "",
"outcomes": [
{"outcomeId": o.get("outcomeId"), "title": o.get("title") or ""}
for o in (c.get("outcomes") or [])
],
}
_CONDITION_META_CACHE[condition_id] = meta
return meta
def fetch_live_football_games() -> list[dict]:
"""
Fetch live football games from the data-feed subgraph.
Returns list of { gameId, homeTeam, awayTeam, league, startTimestamp, conditions }.
"""
# AZURIO: intent = "list games (live) with conditions/outcomes for Polygon football scan"
# AZURIO: REPLACE with Toolkit v6 REST feed — Graph is candidate-only; stale state is expected.
# Data-feed schema (thegraph-1): Game.state = Live, startsAt; Condition.state/title; Outcome.currentOdds/title
query = """
query LiveFootballGames($where: Game_filter) {
games(
first: 50
where: $where
orderBy: startsAt
orderDirection: asc
) {
id
gameId
title
state
startsAt
sport { slug name }
league { name slug country }
participants {
name
image
}
conditions {
id
conditionId
state
outcomes {
outcomeId
currentOdds
}
}
}
}
"""
variables = {
"where": {
"state": "Live",
},
}
data = _graphql(query, variables)
if not data or "games" not in data:
return []
out = []
for g in data["games"]:
sport = (g.get("sport") or {}).get("slug") or (g.get("sport") or {}).get("name") or ""
sport_lower = sport.lower()
if sport_lower not in ("football", "soccer"):
continue
# Exclude esports (virtual teams)
participants = g.get("participants") or []
if any("esport" in (p.get("name") or "").lower() for p in participants):
continue
if "esport" in (g.get("title") or "").lower():
continue
home = participants[0].get("name", "Home") if len(participants) > 0 else "Home"
away = participants[1].get("name", "Away") if len(participants) > 1 else "Away"
league_obj = g.get("league") or {}
league = league_obj.get("name") or league_obj.get("slug") or ""
# Normalize conditions: include title, map outcome.currentOdds -> odds, condition.state -> status
conditions = []
for c in g.get("conditions") or []:
state = (c.get("state") or "").strip()
if state not in ("Created", "Active", "Stopped"):
continue
conditions.append({
"id": c.get("id"),
"conditionId": c.get("conditionId"),
"title": c.get("title") or "",
"status": c.get("state"),
"isPrematchEnabled": c.get("isPrematchEnabled"),
"isLiveEnabled": c.get("isLiveEnabled"),
"outcomes": [
{
"outcomeId": o.get("outcomeId"),
"odds": o.get("currentOdds"),
"title": o.get("title") or "",
}
for o in (c.get("outcomes") or [])
],
})
out.append({
"gameId": g.get("gameId") or g.get("id"),
"id": g.get("id"),
"homeTeam": home,
"awayTeam": away,
"league": league,
"startTimestamp": g.get("startsAt"),
"conditions": conditions,
"status": g.get("state"),
})
return out
def get_under_outcome_for_event_and_entry(ev: dict, entry: dict) -> UnderOutcome | None:
"""
Find an Under market outcome for this event that matches the entry's target_line and market_half.
entry: { target_line (e.g. "Under 2.5"), market_half (1 = first half, None = full game), ... }
Heuristics:
- Prefer conditions whose title looks like a totals/Under market and, for first-half, mentions first half.
- Within such a condition, prefer outcomes whose title contains 'under' and a number close to the desired line.
- Fall back to the first positive-odds outcome if titles are missing.
Returns UnderOutcome(market_id, outcome_id, odds) or None.
"""
game_id = str(ev.get("gameId") or ev.get("id") or "")
conditions = ev.get("conditions") or []
target_line = (entry.get("target_line") or "").strip().lower()
market_half = entry.get("market_half") # 1 = first half, None = full game
use_ws_live = bool(os.getenv("AZURO_USE_WEBSOCKET_LIVE", "0")) and os.getenv("AZURO_USE_WEBSOCKET_LIVE", "0").strip().lower() in ("1", "true", "yes", "y", "on")
# Time guard: for subgraph-based mode we prevent stale events.
# When websocket verification is enabled, we rely on the socket for "Active"
# so we relax this to avoid rejecting bettable conditions due to stale startsAt.
if not use_ws_live:
start_ts = ev.get("startTimestamp") or ev.get("startsAt")
if start_ts is not None:
try:
start_ts_i = int(start_ts)
now_i = int(time.time())
if abs(start_ts_i - now_i) > (3 * 3600):
return None
except (TypeError, ValueError):
pass
# If the adapter provides a status flag, enforce "Live" at this stage.
# (We still also check condition state later via the toolkit.)
status = (ev.get("status") or "").strip()
if status and status != "Live":
return None
# Parse "under 2.5", "under 1.5", etc.
line_val = None
if "under" in target_line:
for part in target_line.replace(",", " ").split():
try:
line_val = float(part)
break
except ValueError:
continue
if line_val is None:
line_val = 2.5
# === Prefer toolkit resolution for football totals ===
# Toolkit reliably labels selectionName (e.g. "Under (3.5)") even when Polygon titles are null.
if game_id:
markets = _toolkit_resolve_markets_for_game(game_id)
if markets:
goal_line = _format_goal_line(line_val)
want_sel = f"Under ({goal_line})"
want_sel_alt = f"Under({goal_line})"
if market_half == 1:
want_market_sub = "1st Half"
else:
# Full-time totals usually come under "Total Goals" without the "Half" marker.
want_market_sub = "Total Goals"
# Only bet on conditionIds that look live-bettable.
# In websocket mode we do not trust subgraph condition.state freshness;
# websocket verifies the decisive "Active" state before we return.
allowed_live_condition_ids = set()
ev_status = (ev.get("status") or "").strip()
for c in conditions:
cid = c.get("conditionId") or c.get("id")
if cid is None:
continue
feed_state = (c.get("status") or "").strip()
is_live_enabled = bool(c.get("isLiveEnabled"))
is_prematch_enabled = bool(c.get("isPrematchEnabled"))
if ev_status == "Live":
if is_live_enabled and not is_prematch_enabled and (use_ws_live or feed_state == "Active"):
allowed_live_condition_ids.add(str(cid))
else:
# If we don't have a clear lane, keep permissive but still require live-enabled.
if feed_state in ("Active", "Stopped", "Created") and is_live_enabled:
allowed_live_condition_ids.add(str(cid))
for m in markets:
mname = (m.get("name") or "")
if market_half == 1:
if "1st Half" not in mname:
continue
else:
if "Total Goals" not in mname or "Half" in mname:
continue
for cond in m.get("conditions") or []:
cond_id = cond.get("conditionId") or cond.get("condition_id")
if allowed_live_condition_ids and str(cond_id) not in allowed_live_condition_ids:
continue
for o in cond.get("outcomes") or []:
sel = (o.get("selectionName") or "").strip()
if sel != want_sel and sel != want_sel_alt:
continue
oid = o.get("outcomeId")
odds_val = o.get("odds")
try:
odds_float = float(odds_val)
except (TypeError, ValueError):
odds_float = 0.0
if not cond_id or oid is None or odds_float <= 0:
continue
try:
outcome_int = int(oid)
except (TypeError, ValueError):
continue
# Websocket verification: treat socket as source of truth.
if use_ws_live:
try:
import azuro_relayer
from azuro_websocket_live import get_condition_state_via_websocket
ws_state = get_condition_state_via_websocket(
environment=azuro_relayer.AZURO_ENVIRONMENT,
condition_id=str(cond_id),
timeout_s=float(os.getenv("AZURO_WS_VERIFY_TIMEOUT_S", "6.0")),
)
if ws_state != "Active":
continue
except Exception:
continue
return UnderOutcome(market_id=str(cond_id), outcome_id=outcome_int, odds=odds_float)
best: UnderOutcome | None = None
best_score: float = -1.0
for cond in conditions:
if (cond.get("status") or "") not in ("Created", "Active", "Stopped"):
continue
cid = cond.get("conditionId") or cond.get("id")
if not cid:
continue
outcomes = cond.get("outcomes") or []
cond_title = (cond.get("title") or "").lower()
# If titles are missing from data-feed, cross-reference prematch subgraph once for this condition.
if (not cond_title) or all(not (o.get("title") or "").strip() for o in outcomes):
meta = _get_condition_meta(str(cid))
if meta:
if not cond_title:
cond_title = (meta.get("title") or "").lower()
cond["title"] = meta.get("title") or ""
# Attach outcome titles where possible
meta_outs = {str(o.get("outcomeId")): (o.get("title") or "") for o in meta.get("outcomes") or []}
for o in outcomes:
oid_key = str(o.get("outcomeId"))
if not (o.get("title") or "") and oid_key in meta_outs:
o["title"] = meta_outs[oid_key]
# Filter by half when requested
if market_half == 1:
# Require some first-half marker in condition title
if not any(ph in cond_title for ph in ("1st half", "first half", "1h", "1-h", "1st-half")):
continue
elif market_half is None:
# Prefer to avoid explicit first-half conditions when betting full game
if any(ph in cond_title for ph in ("1st half", "first half", "1h", "1-h", "1st-half")):
continue
for out in outcomes:
oid = out.get("outcomeId")
if oid is None:
continue
odds_val = out.get("odds")
try:
odds_float = float(odds_val) if odds_val is not None else 0.0
except (TypeError, ValueError):
odds_float = 0.0
if odds_float <= 0:
continue
out_title = (out.get("title") or "").lower()
score = 0.0
# Reward titles that clearly look like Under with matching line
if "under" in out_title or "u " in out_title:
score += 10.0
# Look for the numeric line in either condition or outcome title
if str(line_val).rstrip("0").rstrip(".") in out_title or str(line_val).rstrip("0").rstrip(".") in cond_title:
score += 20.0
# If we have no useful titles, still allow as a weak candidate
if score == 0.0:
score = 1.0
if score > best_score:
best_score = score
best = UnderOutcome(market_id=str(cid), outcome_id=int(oid), odds=odds_float)
return best
class AzuroAdapter:
"""Adapter for Azuro data-feed and outcomes."""
def is_configured(self) -> bool:
return bool(AZURO_SUBGRAPH_URL)
def fetch_live_football_games(self) -> list[dict]:
# AZURIO: single seam for live listing — swap REST implementation inside azuro_feed_client.
from azuro_feed_client import list_live_football_game_candidates
return list_live_football_game_candidates()
def get_under_outcome_for_event_and_entry(self, ev: dict, entry: dict) -> UnderOutcome | None:
return get_under_outcome_for_event_and_entry(ev, entry)
default_adapter = AzuroAdapter()