Find a race
Filter the schedule by racing code, country and start time.
Quick start with the Racing API.
Build with horse, greyhound and harness racecards, win and place prices from 11 bookmakers, and Betfair back and lay odds. One event_id connects the race, live prices, results and history.
Filter the schedule by racing code, country and start time.
Read bookmaker runners, win/place prices and Betfair liquidity.
Replace bookmaker snapshots as updates arrive and resume after reconnecting.
curl -sS -G 'https://api.odds-api.net/v1/racing/events' \
-H "X-API-Key: $ODDS_API_KEY" \
--data-urlencode 'race_type=horse-racing' \
--data-urlencode 'race_country=AU' \
--data-urlencode 'limit=25'
X-API-Key: $ODDS_API_KEY
Race codeshorse-racing, greyhound-racing, harness-racing
CountriesAustralia (AU), New Zealand (NZ), Ireland (IE), United Kingdom (GB)
Endpoints
Discover races, load one race’s bookmaker snapshots, then subscribe to its updates. Results and historical prices have separate endpoints.
| Need | Endpoint | What it returns |
|---|---|---|
| Find races | GET /v1/racing/events | A filtered, paginated race schedule with canonical event IDs. |
| Race record | GET /v1/racing/events/{event_id} | Race identity, start time, distance and field metadata under data. |
| Bookmaker prices | GET /v1/racing/events/{event_id}/odds | One snapshot containing bookmaker items, compact runners and a resume token. |
| Price updates | GET /v1/racing/events/{event_id}/odds/stream | SSE bookmaker updates for one race; /odds/ws is the WebSocket alternative. |
| Schedule updates | GET /v1/racing/events/stream | Race upserts and removals; /racing/events/ws is the WebSocket alternative. |
| Race result | GET /v1/racing/events/{event_id}/results | A pending or available result, with placings and source-specific result fields. |
| Batch results | POST /v1/racing/results | Results for 1–100 event_ids in one JSON request. |
| Find past races | GET /v1/racing/history/events | Races with recorded price history, filtered by scheduled UTC date. |
| Price history | GET /v1/racing/events/{event_id}/odds/history | Timestamped bookmaker and runner series, with optional final prices. |
Coverage
Use the same race discovery and odds endpoints for all three racing codes. Pass comma-separated values to select several codes or countries.
| Racing code | race_type | Overview |
|---|---|---|
| Thoroughbred horse racing | horse-racing | Horse racing API |
| Greyhound racing | greyhound-racing | Greyhound racing API |
| Harness racing | harness-racing | Harness racing API |
Set race_country=AU,NZ,IE,GB for Australia, New Zealand, Ireland and the United Kingdom. Add race_state to narrow regional meetings.
Sportsbet, Ladbrokes, PlayUp, PointsBet, Dabble, BetRight, Betr, Unibet, Sky Bet, William Hill, Paddy Power, plus Betfair Exchange.
Use canonical source keys from GET /v1/bookmakers. Pass bookmakers=sportsbet,ladbrokes,betfair to narrow an odds snapshot or its stream. Racing includes the available racing sources independently of your API key’s selected sports bookmakers.
Omit status when discovering the full schedule. Early races can have prices while the event status is open; status=fetching selects a narrower collection stage.
Race discovery
Request GET /v1/racing/events with start_from and start_to in Unix seconds. Follow next_cursor with the same filters until it is null. The default lower bound is 15 minutes before the current time; limit accepts 1–1,000 races.
{
"count": 1,
"items": [
{
"active_runners": 7,
"event_id": "race-1001",
"race_country": "AU",
"race_number": "3",
"race_start_time": 1794708300,
"race_type": "horse-racing",
"race_venue": "Doomben",
"runner_count_complete": true,
"runner_count_source": "betfair",
"scratched_runners": 1,
"status": "open",
"total_runners": 8
}
],
"next_cursor": null
}
Keep the returned event_id. URL-encode it as RACE_EVENT_ID for the cURL requests, then load the race record:
curl -sS -G "https://api.odds-api.net/v1/racing/events/$RACE_EVENT_ID" \
-H "X-API-Key: $ODDS_API_KEY" \
--data-urlencode 'include_raw_payload=false' \
--data-urlencode 'include_source=true'
The record is under data. Use its venue, distance, start time, race number and field counts for the race header. Read each bookmaker item’s racecard.runners for the declared field, including unpriced and scratched runners.
items[].runners contains compact priced runners. Build the full racecard from racecard, and inspect field_complete and connections_complete separately. A missing price does not remove a runner from the declared field.
Show active_runners, total_runners and scratched_runners with runner_count_source, runner_count_updated_at_ts and runner_count_complete when assessing field state.
Bookmaker prices
Load one race with GET /v1/racing/events/{event_id}/odds. The response contains bookmaker items and a resume token. This race snapshot is returned in one response.
curl -sS -G "https://api.odds-api.net/v1/racing/events/$RACE_EVENT_ID/odds" \
-H "X-API-Key: $ODDS_API_KEY" \
--data-urlencode 'bookmakers=sportsbet,ladbrokes,betfair' \
--data-urlencode 'include_raw_payload=false' \
--data-urlencode 'include_source=true' \
--data-urlencode 'include_unavailable=true'
{
"as_of_ts_ms": 1794708000000,
"event_id": "race-1001",
"items": [
{
"bookmaker_name": "sportsbet",
"race_id": "race-1001",
"runners": [
{
"is_scratched": false,
"place_odds": 1.9,
"runner_name": "Example Runner",
"runner_number": "4",
"runner_status": "ACTIVE",
"selection_id": "104992755",
"win_odds": 5.4
}
],
"status": "ok",
"updated_at_ts": 1794708000
}
],
"resume": "1794708000000-0"
}
Read decimal prices from runners[].win_odds and runners[].place_odds. Keep the bookmaker key, runner identity, quote timestamp and market attached to every price. Use include_links=true to include bookmaker links.
Read place_terms.places and place_terms.fraction for each-way terms. Keep Top 2, Top 3 and other place markets separate. TAB NZ’s explicitly requested tabnz feed uses fixed Top 3 place terms, which can differ from Ladbrokes on 5–7 runner fields.
items[].markets carries markets such as BETTING_WITHOUT, PLACE_ONLY, TO_BE_PLACED, FORECAST, TRICAST and MATCH_BET. Preserve market_type, places, excluded_runners and each selection’s ordered runner_numbers. Use markets_updated_at_ts for their freshness.
Exchange prices
Read Betfair’s best back and lay quotes directly from runner.exchange.win or runner.exchange.place, with the available size on each side.
{
"bookmaker_name": "betfair",
"exchange_markets": {
"win": {
"in_play": false,
"number_of_winners": 1,
"status": "OPEN"
}
},
"runners": [
{
"exchange": {
"place": {
"back": 1.8,
"back_size": 60.0,
"lay": 1.85,
"lay_size": 41.2
},
"win": {
"back": 5.0,
"back_size": 120.5,
"lay": 5.1,
"lay_size": 80.1
}
},
"runner_name": "Example Runner",
"runner_number": "4",
"selection_id": "104992755",
"win_odds": 5.1
}
],
"size_currency": "AUD"
}
For Betfair, win_odds is the best WIN lay price. Use the explicit exchange.win.back and exchange.win.lay fields to distinguish the two sides.
Use the same race, runner and WIN or PLACE market. The runnable comparison requires one unique matching selection_id and compares bookmaker WIN prices with exchange.win.lay.
Require a positive lay_size and keep size_currency. total_matched and runner traded_volume describe cumulative trading; use back/lay sizes for current depth.
Check exchange_markets.win.status, in_play, the runner state and quote age before comparing. For PLACE, also align the number of winners with the bookmaker’s place terms.
gap_pct = (bookmaker_win_odds / betfair_win_lay - 1) * 100
gap_pct is the price difference before exchange commission. The Python and Node.js examples expire stale comparisons and reject scratched, suspended or ambiguous selections.
Streaming
Save the snapshot’s resume token as RACING_RESUME. Connect to the same race’s SSE endpoint with since and catchup=true, keeping the same bookmaker and response-shape filters.
curl -NsS -G "https://api.odds-api.net/v1/racing/events/$RACE_EVENT_ID/odds/stream" \
-H "X-API-Key: $ODDS_API_KEY" \
--data-urlencode "since=$RACING_RESUME" \
--data-urlencode 'catchup=true' \
--data-urlencode 'bookmakers=sportsbet,ladbrokes,betfair' \
--data-urlencode 'include_raw_payload=false' \
--data-urlencode 'include_source=true' \
--data-urlencode 'include_unavailable=true'
An SSE delta carries the race ID, next resume token and bookmaker changes:
event: delta
data: {"changes": [{"bookmaker_name": "sportsbet", "op": "upsert", "snapshot": {"bookmaker_name": "sportsbet", "race_id": "race-1001", "runners": [{"is_scratched": false, "place_odds": 1.9, "runner_name": "Example Runner", "runner_number": "4", "runner_status": "ACTIVE", "selection_id": "104992755", "win_odds": 5.4}], "status": "ok", "updated_at_ts": 1794708001}}], "event_id": "race-1001", "resume": "1794708001000-0"}
| Message | Client action |
|---|---|
delta / upsert | Replace that bookmaker’s complete race snapshot. Save the new resume token after applying the changes. |
delta / remove | Remove that bookmaker’s snapshot and any comparisons that depend on it. |
heartbeat | Keep the connection alive and expire prices that have become too old for your display. |
resync | Reload the REST snapshot, replace local state and reconnect from its fresh resume token. |
Use wss://api.odds-api.net/v1/racing/events/{event_id}/odds/ws for the equivalent WebSocket feed. It accepts the SSE query parameters and sends JSON envelopes shaped as {"event": "delta", "data": {...}}. Send X-API-Key from your server’s WebSocket client.
GET /v1/racing/events/stream and /racing/events/ws send schedule upserts and removals. Apply your code, country and time-window filters in your consumer. Use heartbeat_sec from 5–120 seconds and max_batch from 1–2,000 to tune streaming delivery.
Results
Request GET /v1/racing/events/{event_id}/results using the same canonical race ID. The wrapper’s status is pending or available.
{
"event_id": "race-1001",
"result": null,
"status": "pending"
}
For an available result, read result.status as provisional, official or abandoned. Preserve the source, observation time, placings, scratchings and supplied dividends. Keep dividends_status separate from result availability.
curl -sS 'https://api.odds-api.net/v1/racing/results' \
-H "X-API-Key: $ODDS_API_KEY" \
-H 'Content-Type: application/json' \
--data '{"event_ids":["race-1001","race-1002"]}'
Batch 1–100 event_ids per request. Each returned item has its own availability status. Use the supplied rule4_deductions, places_paid and settlement_coverage fields when your application needs the recorded bookmaker terms.
Price history
Racing history is in beta and requires the racing-history add-on. Recorded history begins on 8 November 2026 at 19:38 UTC. Use the UTC date of the scheduled start to find past races, including races that have left the current schedule.
curl -sS -G 'https://api.odds-api.net/v1/racing/history/events' \
-H "X-API-Key: $ODDS_API_KEY" \
--data-urlencode 'date=2026-11-12' \
--data-urlencode 'race_type=horse-racing' \
--data-urlencode 'country=GB'
Request the selected race’s price series, with optional bookmaker, market and runner filters:
curl -sS -G "https://api.odds-api.net/v1/racing/events/$RACE_EVENT_ID/odds/history" \
-H "X-API-Key: $ODDS_API_KEY" \
--data-urlencode 'bookmakers=betfair,sportsbet' \
--data-urlencode 'market=win' \
--data-urlencode 'runner_number=4' \
--data-urlencode 'include_final=true' \
--data-urlencode 'limit=5000'
Each series belongs to a bookmaker and runner, with points ordered oldest first. Plot tick_ts against win_odds, place_odds or the explicit exchange back/lay fields. changed identifies which prices moved.
Pass meta.next_cursor as cursor until it is null. Keep all filters unchanged. Use ISO 8601 UTC from_ts and to_ts to bound the chart, and meta.complete_through_ts to show its completion time.
History is written as each UTC hour closes. include_final=true adds the last recorded prices frozen at the jump. Keep price history and race results as separate records.
Response fields
Use compact responses for a consistent runner model. Request include_source=true for bookmaker timestamps and include_raw_payload=false for the compact shape.
| Field | Type | Meaning |
|---|---|---|
event_id | string | Canonical race ID. Keep it unchanged across race detail, odds, results and history requests. |
race_type / race_country | string | Canonical racing code and country: horse-racing, greyhound-racing or harness-racing; AU, NZ, GB or IE. |
race_venue / race_number | string | Meeting venue and race number. Display labels rather than a cross-source identity key. |
race_start_time | integer | Scheduled start in Unix seconds. Convert to the viewer’s local timezone for display. |
race_distance / race_state | string | Race distance and regional state metadata. |
active_runners / total_runners / scratched_runners | integer | Counts for the field, active runners and scratchings. |
runner_count_source / runner_count_updated_at_ts / runner_count_complete | string / integer / boolean | Source, Unix-second timestamp and completeness of the field count. |
racecard | object | Source-declared field inside a bookmaker item, including unpriced and scratched runners. Inspect field_complete and connections_complete independently. |
| Field | Type | Meaning |
|---|---|---|
items[].bookmaker_name | string | Canonical source key. Use it to store and replace one bookmaker’s race snapshot. |
items[].status | string | Bookmaker capture state. Both ok and fetching can contain valid prices; this differs from the event lifecycle status. |
items[].updated_at_ts | integer | Bookmaker capture time in Unix seconds; request include_source=true. |
runners[].runner_number / runner_name | string | Saddlecloth or trap number and runner name, scoped to this race. |
runners[].selection_id | string / integer | Selection identifier supplied by the source. The comparison example requires a unique matching ID. |
runners[].win_odds / place_odds | number / string | Decimal prices. For Betfair, win_odds is the best WIN lay price. |
runners[].runner_status / is_scratched | string / boolean | Runner state and scratching flag. Remove scratched or inactive runners from active comparisons. |
runners[].jockey_name / trainer_name | string | Published racing connections. |
markets[] / place_terms | array / object | Additional fixed-odds markets and each-way places/fraction. Keep differing place terms separate. |
| Field | Type | Meaning |
|---|---|---|
runners[].exchange.win / exchange.place | object | Best back and lay prices with back_size and lay_size for the named market. |
size_currency | string | Currency of the available exchange sizes. Keep it alongside the quoted liquidity. |
exchange_markets.win / exchange_markets.place | object | Exchange market identity, status, in_play state, number_of_winners and BSP reconciliation state. |
total_matched / runners[].traded_volume | number | Cumulative matched volume for the WIN market or runner. Available depth is back_size or lay_size. |
runners[].bsp.win / bsp.place | object | near and far are projected starting prices. actual is the reconciled starting price. |
| Field | Type | Meaning |
|---|---|---|
as_of_ts_ms | integer | Snapshot time in Unix milliseconds. Bookmaker updated_at_ts uses seconds. |
resume / since | string | Opaque stream continuation token. Send snapshot.resume as since when opening the stream. |
changes[].op / bookmaker_name / snapshot | string / object | Apply upsert as a complete bookmaker replacement. Remove the source on remove. |
series[].points[].tick_ts | ISO 8601 string | Recorded history point time. Each point contains the runner’s price state at that change. |
meta.next_cursor / meta.complete_through_ts | string | History pagination token and timestamp through which the returned record is complete. |
result.status | string | provisional, official or abandoned inside an available race result. The response wrapper uses available or pending. |
Production
| State | Action |
|---|---|
| Server-side authentication | Store ODDS_API_KEY on your server. Proxy data to browser clients without exposing the key. |
| Schedule pagination | Use bounded start_from/start_to windows, preserve filters across cursors, and deduplicate by event_id. |
| Identity | URL-encode event IDs in paths. Keep runner numbers scoped to the race and require a unique source match for comparisons. |
| Freshness | Track as_of_ts_ms in milliseconds and updated_at_ts in seconds. Expire quotes using your product’s age threshold. |
| Scratched or suspended | Retain the racecard row, suppress its active price and remove dependent comparisons. |
| 401 / 403 | Check the key and endpoint entitlement. racing_history_access_required identifies the racing-history add-on requirement. |
| 429 / disconnect | Respect rate-limit headers, back off and reconnect using the latest applied resume token or a fresh snapshot. |
| resync | Replace local state with a new snapshot before reconnecting. Resume from that snapshot’s token. |
Read GET /v1/limits for the account’s request and stream allowances. See plans and add-ons and status and support for operational details.
Runnable examples
The Python and Node.js examples load a race snapshot, follow SSE updates and compare Sportsbet and Ladbrokes WIN prices with Betfair’s WIN lay quote. Both enforce a 30-second quote age, positive lay size and a unique matching selection ID.
Set RACE_EVENT_ID to the original ID from race discovery. The examples handle path encoding. They reload the snapshot after an interruption or resync, then resume from the fresh token.
python -m pip install requests
export ODDS_API_KEY='your_api_key'
export RACE_EVENT_ID='your_race_event_id'
python racing-lay-comparison.py
Download Python, Node.js, or cURL. Run Node.js with node racing-lay-comparison.mjs. The cURL script uses jq for a snapshot comparison and then opens the raw SSE stream.
"""Python 3.10+: pip install requests; set ODDS_API_KEY, then run this file."""
import json
import math
import os
import sys
import time
from urllib.parse import quote
import requests
BASE = "https://api.odds-api.net/v1"
BOOKMAKERS = {"sportsbet", "ladbrokes"}
SHAPE = {"include_raw_payload": "false", "include_source": "true",
"include_unavailable": "true"}
UNAVAILABLE = {"closed", "suspended", "removed", "inactive", "unavailable",
"off", "settled", "finished", "cancelled", "abandoned"}
def number(value):
try:
value = float(value)
return value if math.isfinite(value) else 0
except (ValueError, TypeError):
return 0
def active(row):
status = str(row.get("runner_status") or row.get("status") or "").strip().lower()
status = status.replace("-", "_").replace(" ", "_")
return (status not in UNAVAILABLE | {"scratched", "withdrawn", "non_runner"}
and str(row.get("is_scratched", "")).lower() not in {"true", "1", "yes"})
def fresh(book, now_ms, max_age_ms):
stamp = number(book.get("updated_at_ts"))
stamp = stamp * 1000 if stamp < 1e12 else stamp
return stamp > 0 and -5000 <= now_ms - stamp <= max_age_ms and active(book)
def compare(books, now_ms, max_age_ms=30000):
exchange = books.get("betfair", {})
market = exchange.get("exchange_markets", {}).get("win", {})
if not fresh(exchange, now_ms, max_age_ms) or not active(market):
return []
selections = {}
for runner in exchange.get("runners", []):
if runner.get("selection_id") and active(runner):
selections.setdefault(str(runner["selection_id"]), []).append(runner)
rows = []
for bookmaker in sorted(BOOKMAKERS):
book = books.get(bookmaker, {})
if not fresh(book, now_ms, max_age_ms):
continue
for runner in book.get("runners", []):
matches = selections.get(str(runner.get("selection_id") or ""), [])
if not active(runner) or len(matches) != 1:
continue
win = matches[0].get("exchange", {}).get("win", {})
back, lay, size = map(number, (runner.get("win_odds"),
win.get("lay"), win.get("lay_size")))
if back <= 1 or lay <= 1 or size <= 0:
continue
rows.append({"runner": runner.get("runner_name"),
"selection_id": str(runner["selection_id"]),
"bookmaker": bookmaker, "back": back, "lay": lay,
"lay_size": size,
"lay_currency": exchange.get("size_currency"),
# Price difference, before exchange commission.
"gap_pct": round((back / lay - 1) * 100, 2),
"bookmaker_updated_at": book["updated_at_ts"],
"betfair_updated_at": exchange["updated_at_ts"]})
return rows
def apply_changes(books, changes):
for change in changes:
name = change.get("bookmaker_name")
if name not in BOOKMAKERS | {"betfair"}:
continue
if change.get("op") == "remove":
books.pop(name, None)
elif change.get("op") == "upsert" and isinstance(change.get("snapshot"), dict):
# A complete bookmaker replacement also removes vanished runners.
books[name] = change["snapshot"]
else:
raise ValueError("Reload the snapshot after an unknown change.")
def sse(lines):
event, data = "message", []
for line in lines:
if not line:
if data:
yield event, json.loads("\n".join(data))
event, data = "message", []
elif line.startswith("event:"):
event = line[6:].strip()
elif line.startswith("data:"):
data.append(line[5:].lstrip(" "))
def main():
headers = {"X-API-Key": os.environ["ODDS_API_KEY"]}
def checked(response):
if response.status_code in {401, 402, 403, 404}:
raise SystemExit(f"API returned HTTP {response.status_code}.")
response.raise_for_status()
return response
def get(path, params):
with requests.get(BASE + path, headers=headers, params=params, timeout=20) as response:
return checked(response).json()
event_id = os.environ.get("RACE_EVENT_ID")
if not event_id:
events = get("/racing/events", {"race_type": "horse-racing", "race_country": "AU",
"status": "fetching", "start_from": int(time.time()), "limit": 50})
if not events.get("items"):
raise SystemExit("No upcoming race found. Set RACE_EVENT_ID to a current race.")
event_id = events["items"][0]["event_id"]
path = f"/racing/events/{quote(event_id, safe='')}/odds"
while True:
try:
snapshot = get(path, SHAPE)
if snapshot.get("event_id") != event_id:
raise ValueError("Unexpected race in snapshot.")
books = {item["bookmaker_name"]: item for item in snapshot.get("items", [])}
resume = snapshot["resume"]
print(json.dumps({"event_id": event_id, "rows": compare(books, time.time() * 1000)}), flush=True)
with requests.get(BASE + path + "/stream", headers=headers,
params={**SHAPE, "since": resume, "catchup": "true"},
stream=True, timeout=(10, 30)) as response:
checked(response)
response.encoding = "utf-8"
for event, message in sse(response.iter_lines(decode_unicode=True)):
if event == "resync":
break
if event == "delta":
if message.get("event_id") != event_id:
raise ValueError("Unexpected race in stream.")
apply_changes(books, message.get("changes", []))
resume = message.get("resume", resume)
# Heartbeats expire stale comparisons even without a delta.
print(json.dumps({"event_id": event_id, "rows": compare(books, time.time() * 1000)}), flush=True)
except (requests.RequestException, ValueError, KeyError):
print("Refreshing racing snapshot after a stream interruption.", file=sys.stderr)
print(json.dumps({"event_id": event_id, "rows": [], "state": "reconnecting"}), flush=True)
time.sleep(2) # Reconnect from a fresh snapshot and its resume token.
if __name__ == "__main__":
main()
// Node.js 20+: set ODDS_API_KEY, then node racing-lay-comparison.mjs
import { pathToFileURL } from "node:url";
const BASE = "https://api.odds-api.net/v1";
const BOOKMAKERS = new Set(["sportsbet", "ladbrokes"]);
const SHAPE = { include_raw_payload: "false", include_source: "true", include_unavailable: "true" };
const UNAVAILABLE = new Set(["closed", "suspended", "removed", "inactive", "unavailable",
"off", "settled", "finished", "cancelled", "abandoned", "scratched", "withdrawn", "non_runner"]);
const number = value => Number.isFinite(Number(value)) ? Number(value) : 0;
const active = row => !UNAVAILABLE.has(String(row.runner_status ?? row.status ?? "").trim().toLowerCase().replaceAll(/[- ]/g, "_"))
&& !["true", "1", "yes"].includes(String(row.is_scratched ?? "").toLowerCase());
const fresh = (book, now, maxAge) => {
let stamp = number(book.updated_at_ts);
if (stamp < 1e12) stamp *= 1000;
return stamp > 0 && now - stamp >= -5000 && now - stamp <= maxAge && active(book);
};
export function compare(books, now = Date.now(), maxAge = 30000) {
const exchange = books.betfair ?? {};
if (!fresh(exchange, now, maxAge) || !active(exchange.exchange_markets?.win ?? {})) return [];
const selections = new Map();
for (const runner of exchange.runners ?? []) {
if (!runner.selection_id || !active(runner)) continue;
const id = String(runner.selection_id);
selections.set(id, [...(selections.get(id) ?? []), runner]);
}
const rows = [];
for (const bookmaker of [...BOOKMAKERS].sort()) {
const book = books[bookmaker] ?? {};
if (!fresh(book, now, maxAge)) continue;
for (const runner of book.runners ?? []) {
const matches = selections.get(String(runner.selection_id ?? "")) ?? [];
if (!active(runner) || matches.length !== 1) continue;
const win = matches[0].exchange?.win ?? {};
const [back, lay, size] = [runner.win_odds, win.lay, win.lay_size].map(number);
if (back <= 1 || lay <= 1 || size <= 0) continue;
rows.push({ runner: runner.runner_name, selection_id: String(runner.selection_id),
bookmaker, back, lay, lay_size: size, lay_currency: exchange.size_currency ?? null,
gap_pct: Math.round((back / lay - 1) * 10000) / 100, // Before commission.
bookmaker_updated_at: book.updated_at_ts, betfair_updated_at: exchange.updated_at_ts });
}
}
return rows;
}
export function applyChanges(books, changes) {
for (const change of changes) {
const name = change.bookmaker_name;
if (!BOOKMAKERS.has(name) && name !== "betfair") continue;
if (change.op === "remove") delete books[name];
else if (change.op === "upsert" && change.snapshot && typeof change.snapshot === "object") {
books[name] = change.snapshot; // Replace the entire bookmaker snapshot.
} else throw new Error("Reload the snapshot after an unknown change.");
}
}
export async function* sse(body) {
const decoder = new TextDecoder();
let buffer = "";
for await (const chunk of body) {
buffer = (buffer + decoder.decode(chunk, { stream: true })).replaceAll("\r\n", "\n");
let end;
while ((end = buffer.indexOf("\n\n")) !== -1) {
const lines = buffer.slice(0, end).split("\n");
buffer = buffer.slice(end + 2);
const event = lines.find(line => line.startsWith("event:"))?.slice(6).trim() ?? "message";
const data = lines.filter(line => line.startsWith("data:")).map(line => line.slice(5).trimStart()).join("\n");
if (data) yield { event, message: JSON.parse(data) };
}
}
}
async function main() {
if (!process.env.ODDS_API_KEY) throw new Error("Set ODDS_API_KEY before running this file.");
const headers = { "X-API-Key": process.env.ODDS_API_KEY };
const checked = response => {
if ([401, 402, 403, 404].includes(response.status)) {
const error = new Error(`API returned HTTP ${response.status}.`);
error.fatal = true;
throw error;
}
if (!response.ok) throw new Error(`API returned HTTP ${response.status}.`);
return response;
};
const get = async (path, params) => {
const response = await fetch(`${BASE}${path}?${new URLSearchParams(params)}`,
{ headers, signal: AbortSignal.timeout(20000) });
return checked(response).json();
};
let eventId = process.env.RACE_EVENT_ID;
if (!eventId) {
const events = await get("/racing/events", { race_type: "horse-racing", race_country: "AU",
status: "fetching", start_from: Math.floor(Date.now() / 1000), limit: 50 });
eventId = events.items?.[0]?.event_id;
if (!eventId) throw new Error("No upcoming race found. Set RACE_EVENT_ID to a current race.");
}
const path = `/racing/events/${encodeURIComponent(eventId)}/odds`;
while (true) {
try {
const snapshot = await get(path, SHAPE);
if (snapshot.event_id !== eventId) throw new Error("Unexpected race in snapshot.");
const books = Object.fromEntries((snapshot.items ?? []).map(item => [item.bookmaker_name, item]));
let resume = snapshot.resume;
const show = () => console.log(JSON.stringify({ event_id: eventId, rows: compare(books) }));
show();
const query = new URLSearchParams({ ...SHAPE, since: resume, catchup: "true" });
// Bound the connection; reconnects always reload a current snapshot.
const controller = new AbortController();
const deadline = setTimeout(() => controller.abort(), 60000);
try {
const response = checked(await fetch(`${BASE}${path}/stream?${query}`, { headers, signal: controller.signal }));
for await (const { event, message } of sse(response.body)) {
if (event === "resync") break;
if (event === "delta") {
if (message.event_id !== eventId) throw new Error("Unexpected race in stream.");
applyChanges(books, message.changes ?? []);
resume = message.resume ?? resume;
}
show(); // Heartbeats also expire stale comparisons.
}
} finally {
clearTimeout(deadline);
controller.abort();
}
} catch (error) {
if (error.fatal) throw error;
console.error("Refreshing racing snapshot after a stream interruption.");
}
console.log(JSON.stringify({ event_id: eventId, rows: [], state: "reconnecting" }));
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main();
# Requires curl and jq. Keep ODDS_API_KEY in your shell environment.
: "${ODDS_API_KEY:?Set ODDS_API_KEY first}"
BASE="https://api.odds-api.net/v1"
# Discover an upcoming Australian horse race.
curl -fsS -G "$BASE/racing/events" \
-H "X-API-Key: $ODDS_API_KEY" \
--data-urlencode "race_type=horse-racing" \
--data-urlencode "race_country=AU" \
--data-urlencode "status=fetching" \
--data-urlencode "start_from=$(date +%s)" \
--data-urlencode "limit=50" | jq '.items[] | {event_id, race_venue, race_number}'
# Set RACE_EVENT_ID to the race you want to compare.
: "${RACE_EVENT_ID:?Set RACE_EVENT_ID from the race list}"
RACE_PATH=$(printf '%s' "$RACE_EVENT_ID" | jq -sRr @uri)
SNAPSHOT=$(curl -fsS -G "$BASE/racing/events/$RACE_PATH/odds" \
-H "X-API-Key: $ODDS_API_KEY" \
--data-urlencode "include_raw_payload=false" \
--data-urlencode "include_source=true" \
--data-urlencode "include_unavailable=true")
# Compare the same WIN selection with a positive Betfair lay quote.
# gap_pct is the price difference before exchange commission.
printf '%s' "$SNAPSHOT" | jq '
def active:
((.runner_status // .status // "") | ascii_downcase | gsub("[- ]"; "_")) as $status |
(["closed","suspended","scratched","removed","inactive","unavailable","off",
"settled","finished","cancelled","abandoned","withdrawn","non_runner"] |
index($status) | not) and
((.is_scratched | tostring | ascii_downcase) as $flag |
["true","1","yes"] | index($flag) | not);
def fresh:
. as $book | (.updated_at_ts | tonumber? // 0) as $stamp |
(if $stamp < 1e12 then $stamp * 1000 else $stamp end) as $ms |
($book | active) and $ms > 0 and
(now * 1000 - $ms >= -5000) and (now * 1000 - $ms <= 30000);
[.items[] | select(.bookmaker_name == "betfair" and fresh and
(.exchange_markets.win | active))] as $exchanges |
select(($exchanges | length) == 1) | $exchanges[0] as $exchange |
[$exchange.runners[] | select(active)] as $lays |
.items[] | select((.bookmaker_name == "sportsbet" or .bookmaker_name == "ladbrokes") and fresh) as $book |
$book.runners[] | select(active and .selection_id != null) as $runner |
[$lays[] | select((.selection_id | tostring) == ($runner.selection_id | tostring))] as $matches |
select(($matches | length) == 1) | $matches[0].exchange.win as $win |
select($win.lay > 1 and $win.lay_size > 0 and $runner.win_odds > 1) |
{runner: $runner.runner_name, bookmaker: $book.bookmaker_name,
back: $runner.win_odds, lay: $win.lay, lay_size: $win.lay_size,
lay_currency: $exchange.size_currency,
gap_pct: (($runner.win_odds / $win.lay - 1) * 100)}'
# Continue from this snapshot. Node.js/Python maintain and validate live state.
RESUME=$(printf '%s' "$SNAPSHOT" | jq -r '.resume')
curl -fNsS -G "$BASE/racing/events/$RACE_PATH/odds/stream" \
-H "X-API-Key: $ODDS_API_KEY" \
--data-urlencode "since=$RESUME" \
--data-urlencode "catchup=true" \
--data-urlencode "include_raw_payload=false" \
--data-urlencode "include_source=true" \
--data-urlencode "include_unavailable=true"
Copy the prompt or download the agent instructions to build the same racing comparison.
Build a racing odds comparison board with https://api.odds-api.net/v1. Keep ODDS_API_KEY server-side and send it in the X-API-Key header.
Find an upcoming race at /racing/events?race_type=horse-racing&race_country=AU&status=fetching&limit=50, using start_from for the current Unix time. Load /racing/events/{event_id}/odds with include_raw_payload=false, include_source=true and include_unavailable=true.
Keep a state map keyed by bookmaker_name. Connect to /racing/events/{event_id}/odds/stream with the same response flags, since=<snapshot.resume> and catchup=true. Replace the entire bookmaker snapshot on upsert; delete it on remove. Reload the snapshot after resync, a malformed update or a disconnect, then reconnect with its resume token.
Within the same canonical race and WIN market, join Sportsbet or Ladbrokes runners to Betfair runners by selection_id. Read the bookmaker's win_odds and Betfair's runner.exchange.win.lay and lay_size. Require a unique selection match, positive lay liquidity and fresh updated_at_ts values. Exclude scratched runners, suspended books and closed WIN markets; expire stale rows on heartbeats and in the UI.
Show the runner, bookmaker, win price, lay price, available lay size, size_currency and both timestamps. Calculate gap_pct = (win_odds / lay - 1) * 100 and label it as a price difference before commission. Use configurable exchange commission for any net-return calculation. Include empty and reconnecting states, country and race-type filters, and copyable event IDs.
Reference
Read the racing request parameters alongside the public OpenAPI contract. The full API reference includes response schemas and status codes.
/v1/racing/eventsrace_typeComma-separated canonical racing type filters: `horse-racing`, `greyhound-racing`, or `harness-racing`. Legacy aliases such as `horse`, `thoroughbred`, `greyhound`, `dog`, `dogs`, and `harness` are normalized for backward compatibility.
race_stateComma-separated racing state filters.
race_countryComma-separated racing country filters: `AU`, `NZ`, `GB`, or `IE`. Returned combinations depend on the live racing schedule.
statusComma-separated event lifecycle statuses. Omit for early discovery: fetching alone excludes open races that may already have prices. This is not the bookmaker odds snapshot status.
start_fromUnix seconds lower bound for event start time. Use bounded windows in production polling.
start_toUnix seconds upper bound for event start time. Keep windows narrow for hot sync jobs.
cursorPagination cursor from the previous `next_cursor`. Keep filters identical between pages.
limitMaximum items to return. Respect the caps returned by `/limits`.
include_linksWhen true, include bookmaker/deep-link fields such as match links and racing links.
include_sourceWhen true, include per-line/per-bookmaker provenance and capture metadata. Top-level freshness fields are always kept.
/v1/racing/events/streaminclude_linksWhen true, include bookmaker/deep-link fields such as match links and racing links.
include_raw_payloadWhen true, include raw stored payload/data objects where the endpoint exposes them.
include_sourceWhen true, include per-line/per-bookmaker provenance and capture metadata. Top-level freshness fields are always kept.
sinceResume token from a previous snapshot or stream message. Pass it after reconnecting.
catchupWhen true, return available missed stream events after `since` before waiting for new events.
heartbeat_secMaximum seconds between messages: a `heartbeat` is sent whenever this long passes without another message. Valid range is 5-120.
max_batchMaximum stream messages to read per batch. Default is 500; use smaller batches for low-latency clients.
/v1/racing/events/wsinclude_linksWhen true, include bookmaker/deep-link fields such as match links and racing links.
include_raw_payloadWhen true, include raw stored payload/data objects where the endpoint exposes them.
include_sourceWhen true, include per-line/per-bookmaker provenance and capture metadata. Top-level freshness fields are always kept.
sinceResume token from a previous snapshot or stream message. Pass it after reconnecting.
catchupWhen true, return available missed stream events after `since` before waiting for new events.
heartbeat_secMaximum seconds between messages: a `heartbeat` is sent whenever this long passes without another message. Valid range is 5-120.
max_batchMaximum stream messages to read per batch. Default is 500; use smaller batches for low-latency clients.
/v1/racing/events/{event_id}event_idrequiredCanonical event or race identifier from an event list response.
include_linksWhen true, include bookmaker/deep-link fields such as match links and racing links.
include_raw_payloadWhen true, include raw stored payload/data objects where the endpoint exposes them.
include_sourceWhen true, include per-line/per-bookmaker provenance and capture metadata. Top-level freshness fields are always kept.
/v1/racing/events/{event_id}/oddsevent_idrequiredCanonical event or race identifier from an event list response.
bookmakersComma-separated bookmaker allow-list. Use `/bookmakers` to discover supported keys.
include_linksInclude bookmaker_link when available, independently of raw payload. Compact clients omit links by default. false removes links including nested raw links.
include_raw_payloadInclude bookmaker-specific payload. Compact clients default to false and receive runners[].win_odds; Sportsbet raw WIN prices are payload.horse_data[].odds.
include_sourceInclude source metadata such as updated_at_ts (Unix seconds). Compact clients omit it by default.
include_unavailableInclude bookmaker snapshots without compact WIN or PLACE runner prices. This does not restrict odds to status fetching; early status ok may contain valid prices.
/v1/racing/events/{event_id}/odds/streamevent_idrequiredCanonical event or race identifier from an event list response.
include_linksInclude bookmaker_link when available, independently of raw payload. Compact clients omit links by default. false removes links including nested raw links.
include_raw_payloadInclude bookmaker-specific payload. Compact clients default to false and receive runners[].win_odds; Sportsbet raw WIN prices are payload.horse_data[].odds.
include_sourceInclude source metadata such as updated_at_ts (Unix seconds). Compact clients omit it by default.
include_unavailableInclude bookmaker snapshots without compact WIN or PLACE runner prices. This does not restrict odds to status fetching; early status ok may contain valid prices.
bookmakersComma-separated bookmaker allow-list. Use `/bookmakers` to discover supported keys.
sinceResume token from a previous snapshot or stream message. Pass it after reconnecting.
catchupWhen true, return available missed stream events after `since` before waiting for new events.
heartbeat_secMaximum seconds between messages: a `heartbeat` is sent whenever this long passes without another message. Valid range is 5-120.
max_batchMaximum stream messages to read per batch. Default is 500; use smaller batches for low-latency clients.
/v1/racing/events/{event_id}/odds/wsevent_idrequiredCanonical event or race identifier from an event list response.
include_linksInclude bookmaker_link when available, independently of raw payload. Compact clients omit links by default. false removes links including nested raw links.
include_raw_payloadInclude bookmaker-specific payload. Compact clients default to false and receive runners[].win_odds; Sportsbet raw WIN prices are payload.horse_data[].odds.
include_sourceInclude source metadata such as updated_at_ts (Unix seconds). Compact clients omit it by default.
include_unavailableInclude bookmaker snapshots without compact WIN or PLACE runner prices. This does not restrict odds to status fetching; early status ok may contain valid prices.
bookmakersComma-separated bookmaker allow-list. Use `/bookmakers` to discover supported keys.
sinceResume token from a previous snapshot or stream message. Pass it after reconnecting.
catchupWhen true, return available missed stream events after `since` before waiting for new events.
heartbeat_secMaximum seconds between messages: a `heartbeat` is sent whenever this long passes without another message. Valid range is 5-120.
max_batchMaximum stream messages to read per batch. Default is 500; use smaller batches for low-latency clients.
/v1/racing/history/eventsdaterequiredUTC day of the scheduled start (YYYY-MM-DD).
countryrace_typeComma-separated canonical racing type filters: `horse-racing`, `greyhound-racing`, or `harness-racing`. Legacy aliases such as `horse`, `thoroughbred`, `greyhound`, `dog`, `dogs`, and `harness` are normalized for backward compatibility.
venuebookmakerCanonical bookmaker filter. Use `/bookmakers` or `/coverage` to discover supported keys.
limitMaximum items to return. Respect the caps returned by `/limits`.
cursorPagination cursor from the previous `next_cursor`. Keep filters identical between pages.
/v1/racing/events/{event_id}/odds/historyevent_idrequiredCanonical event or race identifier from an event list response.
bookmakersComma-separated bookmaker allow-list. Use `/bookmakers` to discover supported keys.
marketwin, place or all.
runner_numberOnly this runner's cloth number.
from_tsISO8601 UTC start timestamp for a bounded history query.
to_tsISO8601 UTC end timestamp for a bounded history query.
limitMaximum items to return. Respect the caps returned by `/limits`.
cursorPagination cursor from the previous `next_cursor`. Keep filters identical between pages.
include_finalInclude the last prices frozen at the jump.
/v1/racing/events/{event_id}/resultsevent_idrequiredCanonical event or race identifier from an event list response.
/v1/racing/resultsSend JSON with event_ids: an array of 1–100 canonical race IDs.