Race discovery
Filter races by type, country, state, status and start time before requesting a full racecard.
GET /v1/racing/events
Stream win and place odds from 11 bookmakers, plus Betfair lay odds, across Australia, New Zealand, Ireland and the UK.
{
"as_of_ts_ms": 1794692261932,
"events": [{
"event_id": "dunstall park_11_greyhound-racing_1794692280",
"race_type": "greyhound-racing",
"race_venue": "dunstall park",
"race_number": "11",
"race_country": "GB",
"selections": [
{
"selection_number": "3", "selection_name": "Darbys Harlie",
"best_bookmaker": "sportsbet", "best_odds": 4.20,
"betfair_odds": 4.40
},
{
"selection_number": "5", "selection_name": "Wingates Woody",
"best_bookmaker": "pointsbet", "best_odds": 4.00,
"betfair_odds": 5.10
}
]
}],
"resume": "1794692261932"
}
Use one event ID to connect the racecard, runner market, bookmaker snapshots and live price updates.
Filter races by type, country, state, status and start time before requesting a full racecard.
GET /v1/racing/events
Read the venue, race number, start time, distance, active runners and canonical event ID.
GET /v1/racing/events/{event_id}
Compare bookmaker, runner number, runner name, win_odds and place_odds in one timestamped snapshot.
GET /v1/racing/events/{event_id}/odds
Apply racing price changes over SSE or WebSockets and reconnect from the latest resume token.
GET /v1/racing/events/{event_id}/odds/stream
Stream bookmaker win odds and compare each runner with Betfair’s lay price.
X-API-KeyBookmaker + Betfair/v1/racing/events/{event_id}/odds/stream
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.
// 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();
"""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()
# 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"
Request thoroughbred horse, greyhound and harness racing across Australia, New Zealand, Ireland and the UK.
Fixed-odds bookmaker prices and Betfair exchange data across horse, greyhound and harness racing.
Filter the race list, load the runner market and keep bookmaker prices current with SSE or WebSockets.
Choose horse, greyhound or harness, then narrow the list by AU, NZ, IE or GB and keep the returned event ID.
GET /v1/racing/events?race_type=horse-racing&race_country=AU&status=fetching&limit=25
Use the event ID to load bookmaker snapshots, runner-level win and place prices, timestamps and the resume token.
GET /v1/racing/events/{event_id}/odds
Continue from the snapshot resume token, apply price changes, and reload the snapshot after a resync event.
SSE or WebSocket
Use typed SDKs, Postman and OpenAPI. Connect coding agents through MCP or add live prices with SSE and WebSockets.
Start with typed clients, racing request models and API-key authentication.
Generate a client from the public racing event, odds and stream schemas.
Run working racing requests with your own API key and event ID.
Connect supported coding agents to racing events, odds and streams.
Start with a snapshot, then receive supported runner price changes.
Use a persistent connection for richer live racing products.
Race types, country filters, returned fields and live odds updates.
Race records include the venue, race number, start time, country, state, distance, active runners and status. Odds snapshots add bookmaker names, runner numbers and names, win and place prices, timestamps and a resume token.
Use the canonical values race_type=horse-racing, race_type=greyhound-racing and race_type=harness-racing. Legacy shorthand remains normalized for backward compatibility.
The racing catalog covers Australia, New Zealand, Ireland and the United Kingdom. Filter them with the country codes AU, NZ, IE and GB.
The racing catalog includes 11 fixed-odds bookmakers: Sportsbet, Ladbrokes, PlayUp, PointsBet, Dabble, BetRight, Betr, Unibet, Sky Bet, William Hill and Paddy Power, plus Betfair exchange. Horse, greyhound and harness coverage is listed on each racing page.
GET /v1/racing/events accepts race_type, race_country, race_state, status, start_from, start_to, cursor and limit. This lets you request the race window your application needs.
Yes. Load an odds snapshot first, then connect to the matching SSE or WebSocket endpoint. Reconnect with the latest resume token and reload the snapshot after a resync event.
Choose a plan by request volume, streaming hours, rate limits and support.
Enterprise grade
Custom projects, scoped with your team.
Choose a paid plan and start building with real odds data.