# In-play odds in Python: follow a match into play

> Follow one football match from before kick-off into play in Python with the standard library: one event id, the in_play flag, and each bookmaker's price.

Published 23 November 2026

**In play odds from an API, in Python, take one parameter: ask OddsRelay's raw board or event route with `inPlay=include` and read the `in_play` flag on each event. The event keeps its `id` at kick-off, so one loop can follow a match from before the start into play.** The script below does that for one football match, with nothing beyond the standard library.

## How do you get in-play odds from an odds API in Python?

You add one parameter to the request: `inPlay=include`. Since 2 November 2026, OddsRelay has served [in-play odds](https://oddsrelay.io/glossary/in-play-odds) on raw, on the event route and on the standard and dutching boards. On `GET /v2/odds/raw` and `GET /v2/odds/event/{id}`, `inPlay` takes three values. `exclude`, the default, leaves out every event in play. `include` serves pre-match and in-play events together, and `only` serves the events in play alone. Asking for in-play costs what the same call without it costs.

The prices are the venues' own, as raw always serves them. There are no scores and no match clock, the 2Up, each-way, extra place and Best odds guaranteed boards stay pre-match, and horse racing is never in play. The [in-play guide](https://oddsrelay.io/docs/guides/in-play) sets out what each value returns on each route.

## Two files in one folder

It runs on Python 3.9 or later, with nothing to install. Save both files below side by side, get a key through the [quickstart](https://oddsrelay.io/docs/guides/quickstart), and set `ODDSRELAY_KEY` in your shell. With no `--event`, the script takes the first football event on the raw board.

Run it · example:

```sh
export ODDSRELAY_KEY="your API key"
python3 main.py
python3 main.py --event or_evt_0123456789ab --every 60 --polls 30 --max-tokens 50
```

Here is `api.py`, the helper every one of our Python tutorials shares. It reads the key from the environment, asks for gzip, waits out a `429` for as long as `Retry-After` says, and stops on any other error with the API's own `error.code`, message and `request_id`. `afford()` reads a `quote=true` reply, the price of a call, which costs nothing, and carries on only when the price is zero, within `--max-tokens`, or confirmed at the terminal.

api.py · example:

```python
"""The small HTTP helper every example here shares. Each folder keeps an identical copy, so any
folder runs on its own with nothing but the Python standard library."""
from __future__ import annotations

import gzip
import json
import os
import sys
import time
from http.client import HTTPMessage
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen

API = "https://api.oddsrelay.io"


def get(path: str, params: dict, headers: dict | None = None) -> tuple[int, HTTPMessage, Any]:
    """GET one route with gzip: (status, headers, decoded JSON or None). Waits out 429s, exits on errors."""
    key = os.environ.get("ODDSRELAY_KEY", "").strip()  # a stray newline would put the key in a ValueError
    if not key:
        sys.exit("set ODDSRELAY_KEY to your API key")
    query = urlencode({k: v for k, v in params.items() if v is not None})
    for attempt in range(3):
        req = Request(f"{API}{path}" + (f"?{query}" if query else ""), headers={
            "Authorization": f"Bearer {key}", "Accept-Encoding": "gzip", **(headers or {})})
        try:
            with urlopen(req, timeout=30) as res:
                status, hdrs, body = res.status, res.headers, res.read()
        except HTTPError as err:  # urllib raises for 304 and for every 4xx and 5xx
            status, hdrs, body = err.code, err.headers, err.read()
        except URLError as err:
            sys.exit(f"could not reach {API}: {err.reason}")
        if body and hdrs.get("Content-Encoding") == "gzip":
            body = gzip.decompress(body)
        if status == 429:  # rate-limited: wait as long as the reply says, unless that was the last try
            if attempt < 2:
                time.sleep(int(hdrs.get("Retry-After", "1")))
            continue
        if status >= 400:
            error = json.loads(body).get("error", {}) if body[:1] == b"{" else {}
            sys.exit(f"HTTP {status} {error.get('code', '')}: {error.get('message', '')} "
                     f"(request id {error.get('request_id', '-')})")
        return status, hdrs, json.loads(body) if body else None
    sys.exit("still rate-limited after 3 tries")


def afford(quote: dict, max_tokens: int | None) -> bool:
    """True when a quoted price is fine: free, within --max-tokens, or confirmed at the prompt."""
    left = "unknown" if quote["remaining"] is None else quote["remaining"]
    print(f"quote: {quote['cost']} tokens ({left} left)", file=sys.stderr)
    if quote["cost"] == 0 or (max_tokens is not None and quote["cost"] <= max_tokens):
        return True
    if max_tokens is None and sys.stdin.isatty():
        print("fetch it? [y/N] ", end="", file=sys.stderr, flush=True)  # stderr: stdout may be redirected
        return input().strip().lower() == "y"
    return False
```

## How do you tell when an event has gone in play?

You read `in_play`, not `commence_time`. Under `inPlay=include` or `only`, every event carries `in_play`, and it is `true` when the event's venues show it in play. A kick-off time can move, and a match can start late, so the clock is a guess where the flag is the venues' own word. Here is `main.py`:

main.py · example:

```python
"""Follow one football event from before kick-off into play: each read prints the time, whether
the event is in play, and every venue's back price on the match result (h2h) market.

Run: ODDSRELAY_KEY=<your key> python3 main.py
"""
from __future__ import annotations

import argparse
import sys
import time
from datetime import datetime, timezone

from api import afford, get

MARKET = "h2h"


def first_event(region: str, max_tokens: int | None) -> str:
    """The id of the first football event on the raw board, in play or not."""
    params = {"region": region, "sports": "soccer", "markets": MARKET, "inPlay": "include", "limit": 1}
    if not afford(get("/v2/odds/raw", {**params, "quote": "true"})[2], max_tokens):
        sys.exit("not fetched: pass --max-tokens, or --event with an id you already have")
    events = get("/v2/odds/raw", params)[2]["data"]
    if not events:
        sys.exit("no football event on the board right now")
    return events[0]["id"]


def prices(event: dict) -> str:
    """'venue: outcome price, outcome price' for every venue quoting the market."""
    parts = []
    for venue in event["bookmakers"]:
        for market in venue["markets"]:
            if market["key"] == MARKET:
                quotes = [f"{o['name']} {o.get('price') or o.get('back_price')}" for o in market["outcomes"]]
                parts.append(f"{venue['key']}: " + ", ".join(quotes))
    return " | ".join(parts) or "no venue quotes this market now"


def main() -> None:
    ap = argparse.ArgumentParser(description="Follow one football event into play.")
    ap.add_argument("--event", help="an event id; left out, the first football event on the raw board")
    ap.add_argument("--region", default="uk", help="one region code")
    ap.add_argument("--every", type=int, default=60, help="seconds between reads")
    ap.add_argument("--polls", type=int, default=30, help="how many reads before it stops")
    ap.add_argument("--max-tokens", type=int, help="spend up to this many tokens a call without asking")
    args = ap.parse_args()
    event_id = args.event or first_event(args.region, args.max_tokens)
    path, params = f"/v2/odds/event/{event_id}", {"region": args.region, "inPlay": "include"}
    if not afford(get(path, {**params, "quote": "true"})[2], args.max_tokens):
        sys.exit("not fetched: pass --max-tokens to set a ceiling for each read")
    was_in_play = None
    for n in range(args.polls):
        event = get(path, params)[2]
        now = datetime.now(timezone.utc).strftime("%H:%M:%S")
        in_play = event.get("in_play", False)
        if in_play and was_in_play is False:
            print(f"{now}  gone in play: {event['home_team']} v {event['away_team']}, still {event['id']}")
        was_in_play = in_play
        print(f"{now}  in_play={in_play}  {prices(event)}")
        if n < args.polls - 1:
            time.sleep(args.every)


if __name__ == "__main__":
    main()
```

`first_event()` asks `GET /v2/odds/raw` for one football event, `sports=soccer` with `markets=h2h`, under `inPlay=include` so a match already under way can be the one it finds. The board is ordered by kick-off, so `limit=1` gives the earliest. It quotes the call first and stops before spending if the price is above your ceiling.

The loop then reads that one event from `GET /v2/odds/event/{id}`, which answers with the event itself rather than a list. Each venue in `bookmakers` carries its `markets`, and each outcome on a market carries the venue's own `name` and a price: `price` for a bookmaker, `back_price` for a venue that also quotes a lay side. `prices()` joins those into one line per read.

The first time `in_play` turns from `false` to `true`, the script prints one extra line, with the same `id` it started with. If the event was already in play on the first read, there is no turn to report, and every line says `in_play=True`.

Here is a real run, on 23 Nov 2026 at 04:54 UTC, with `--every 5 --polls 2 --max-tokens 50` and no `--event`. The first football event on the board was a women's match in Japan already in play, so both lines say `in_play=True` and there is no turn to report. Here is what it printed to stdout once its quotes were accepted:

Output · example:

```text
04:54:31  in_play=True  7bet: Draw 4.33, Nojima Stella (W) 1.2, Omiya Ardija Ventus (W) 15.0 | betfair_exchange: Draw 5.0, Noj Stel Kanagawa (W) 1.3, Omiya Ardija (W) 21.0 | betfair_sportsbook: Draw 5.0, Noj Stel Kanagawa (W) 1.22, Omiya Ardija (W) 16.0 | betfred: Draw 4.33, Nojima Stella Kanagawa Sagamihara Women 1.29, Omiya Ardija Ventus Women 15.0 | betnero: Draw 4.33, Nojima Stella (W) 1.2, Omiya Ardija Ventus (W) 15.0 | bwin: Draw 4.2, Nojima Stella Kanagawa Sagamihara (Women) 1.24, Omiya Ardija Ventus (Women) 12.5 | coral: Draw 4.2, Nojima Stella Kanagawa Sagamihara (Women) 1.25, Omiya Ardija Ventus (Women) 12.0 | hopa: Draw 4.33, Nojima Stella (W) 1.2, Omiya Ardija Ventus (W) 15.0 | karamba: Draw 4.33, Nojima Stella (W) 1.2, Omiya Ardija Ventus (W) 15.0 | ladbrokes: Draw 4.2, Nojima Stella Kanagawa Sagamihara (Women) 1.25, Omiya Ardija Ventus (Women) 11.0 | lottoland: Draw 4.67, Nojima Stella (W) 1.23, Omiya Ardija Ventus (W) 17.0 | mcbookie: Draw 4.5, Nojima Stella (W) 1.22, Omiya Ardija Ventus (W) 17.0 | mr_vegas: Draw 4.67, Nojima Stella (W) 1.23, Omiya Ardija Ventus (W) 17.0 | pub_casino: Draw 4.33, Nojima Stella (W) 1.2, Omiya Ardija Ventus (W) 15.0 | sky_bet: Draw 5.0, Noj Stel Kanagawa (W) 1.22, Omiya Ardija (W) 15.0 | smarkets: Draw 4.4, Nojima Stella Kanagawa Sagamihara Women 1.28, Omiya Ardija Ventus Women 18.48 | sportingbet: Draw 4.2, Nojima Stella Kanagawa Sagamihara (Women) 1.24, Omiya Ardija Ventus (Women) 12.5
04:54:36  in_play=True  7bet: Draw 4.33, Nojima Stella (W) 1.2, Omiya Ardija Ventus (W) 15.0 | betfair_exchange: Draw 5.0, Noj Stel Kanagawa (W) 1.3, Omiya Ardija (W) 20.0 | betfair_sportsbook: Draw 5.0, Noj Stel Kanagawa (W) 1.22, Omiya Ardija (W) 16.0 | betfred: Draw 4.33, Nojima Stella Kanagawa Sagamihara Women 1.29, Omiya Ardija Ventus Women 15.0 | betnero: Draw 4.33, Nojima Stella (W) 1.2, Omiya Ardija Ventus (W) 15.0 | bwin: Draw 4.2, Nojima Stella Kanagawa Sagamihara (Women) 1.24, Omiya Ardija Ventus (Women) 12.5 | hopa: Draw 4.33, Nojima Stella (W) 1.2, Omiya Ardija Ventus (W) 15.0 | karamba: Draw 4.33, Nojima Stella (W) 1.2, Omiya Ardija Ventus (W) 15.0 | ladbrokes: Draw 4.2, Nojima Stella Kanagawa Sagamihara (Women) 1.25, Omiya Ardija Ventus (Women) 11.0 | lottoland: Draw 4.67, Nojima Stella (W) 1.23, Omiya Ardija Ventus (W) 17.0 | mcbookie: Draw 4.5, Nojima Stella (W) 1.22, Omiya Ardija Ventus (W) 17.0 | mr_vegas: Draw 4.67, Nojima Stella (W) 1.23, Omiya Ardija Ventus (W) 17.0 | pub_casino: Draw 4.33, Nojima Stella (W) 1.2, Omiya Ardija Ventus (W) 15.0 | sky_bet: Draw 5.0, Noj Stel Kanagawa (W) 1.22, Omiya Ardija (W) 15.0 | smarkets: Draw 4.4, Nojima Stella Kanagawa Sagamihara Women 1.28, Omiya Ardija Ventus Women 18.48 | sportingbet: Draw 4.2, Nojima Stella Kanagawa Sagamihara (Women) 1.24, Omiya Ardija Ventus (Women) 12.5
```

## Does the event id change at kick-off?

No. An event keeps its `id` when it goes in play, and under `include` it keeps its place in the board's order and is served once. That is why the loop never has to find the match again: the id it read before the start is the id it reads in play. An id that was merged into another event still answers, as that event, whose own id is in the reply.

The parameter matters on the event route. Asked with no `inPlay`, or with `exclude`, an event in play is a `404 unknown_event`, and the message says to ask with `inPlay=include`. The same `404` comes back once the event has left the board, and `get()` stops the script there with the API's own message.

## What each read costs

The script quotes the event call once, before the loop, and every read after it costs about that again, since the price is the whole event's. `--polls` caps how many reads it makes, so the quote times `--polls` is roughly your ceiling for a run. How often to read is your product's call: `--every` sets the gap, and the [polling post](https://oddsrelay.io/blog/polling-an-odds-feed-efficiently) covers how to keep a loop cheap.

## Where to take it next

- **Follow many matches in one call.** `GET /v2/odds/raw` with `inPlay=include` and `eventIds` (up to 50 ids) returns each of those events with its `in_play` flag, in one reply.
- **Read only what is in play.** `inPlay=only` serves the events in play alone, on raw and on the standard and dutching boards, each marked `in_play`.
- **Pick a different market.** Change `MARKET` to another key raw serves, such as `over_under`. Keyless `/v2/coverage` lists raw's market keys.
- **Start from the basics.** [Odds API in Python](https://oddsrelay.io/blog/odds-api-in-python) uses the same `api.py` for an oddsmatcher over a matched board, and [live vs pre-match odds data](https://oddsrelay.io/blog/live-vs-pre-match-odds-data) sets out what in-play asks of a feed.

## Run it on a match tonight

Pick a football match that kicks off soon, pass its id as `--event`, and leave the script running across the start. The [API reference](https://oddsrelay.io/docs/reference) lists every parameter the two routes take.

Test it free on your own key. A page or tool that other people use runs on [Enterprise](https://oddsrelay.io/enterprise).

18+ · OddsRelay supplies odds data only and takes no bets. Please gamble responsibly.

Source: https://oddsrelay.io/blog/in-play-odds-in-python
