> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kairos.trade/llms.txt
> Use this file to discover all available pages before exploring further.

# Live sports scores stream

> Push updates of live game scores for every sport over the market data WebSocket

The sports scores stream pushes every change to a live game's score and state,
so you do not have to poll [`GET /sports/live-events`](https://docs.kairos.trade/rest/sports#live-events).
It carries game data only: competitors, scores, period, clock and lifecycle. To
join a game to its markets and prices, match its `slug` against the REST
endpoint.

One message shape covers every sport. Head-to-head games (basketball, soccer,
tennis, table tennis, esports, chess, fights) and fields of many competitors
(golf, motorsport) use the same fields, so a new sport or score format arrives
without a schema change.

## Conventions

These rules hold for every message on the stream:

* **Lifecycle.** `phase` is the game's only lifecycle field. It is normalized
  the same way for every sport and source.
* **Order.** Scores and per-competitor lists follow `competitors` order, home
  first, whatever order the source writes them in.
* **Times.** Times are int64 Unix milliseconds, named `*_at_ms`. A value of `0`
  means the time is not known.
* **Vocabularies.** `phase`, event `kind`, `subtype`, `side` and `role` take
  snake\_case values from a documented list, and lists may grow. Read a
  `phase` you do not know as `unknown`, and a `kind` you do not know as
  `other`.
* **Attributes.** Every game `attributes` key is listed on this page, and
  every event `attributes` key on the
  [play-by-play page](https://docs.kairos.trade/websocket/sports-play-by-play.md#event-attributes). Ignore
  a key you do not know. Keys are added, never renamed.
* **Versions.** Fields and vocabulary values are added without notice. A
  breaking change is announced first. `schema_version` and `content_hash` are
  for Kairos's own services; ignore them.

## Connecting

The stream runs on the market data WebSocket at `wss://stream.kairos.trade`,
with the same binary `[1-byte tag][protobuf]` framing. See
[Market data stream](https://docs.kairos.trade/websocket/market-data-websocket.md#connecting) for the
connection, keepalive and error rules.

**An API key is required.** Connect with the `X-Client-Id`, `X-Api-Key` and
`X-Api-Secret` headers. Anonymous `kairos.marketdata.public.v1` connections are
refused with an in-band error (tag `0x17`), and the socket stays open for other
topics.

## Subscribing

Send a `SubscribeRequest` (tag `0x10`) with `provider: "sports"`,
`topics: ["sports"]`, and the scope you want as `contract_id`:

| `contract_id` | You receive |
| - | - |
| `all` | Every live game |
| `family:<sportFamily>` | One sport, e.g. `family:basketball`, `family:tennis` |
| `league:<league>` | One league, e.g. `league:nba`, `league:epl`, `league:atp`, `league:tennis-opticodds` |
| `game:<gameId>` | One game, e.g. `game:20023921` |

`sportFamily`, `league` and `gameId` take the same values as `sportFamily`,
`sport` and `gameId` on [`GET /sports/live-events`](https://docs.kairos.trade/rest/sports#live-events).
The topic list is `["sports"]`; add `sports.events` for
[play-by-play](https://docs.kairos.trade/websocket/sports-play-by-play.md). A `game:` scope for a game the
stream does not hold yet is accepted, and stays empty until the game appears.

A connection can hold up to 51 scopes of any kind, `all` included.
Subscribing again to a scope you hold sets its topics to exactly what you name,
and sends a new snapshot.

Unsubscribe with an `UnsubscribeRequest` (tag `0x11`) carrying the same
`provider` and `contract_id`. Its `topics` (field 4) drops only the topics you
name, e.g. `["sports.events"]`; leave it empty to drop the whole scope. Older
copies of `websocket_control.proto` lack field 4, so download the file again if
yours does. The server answers with an `UnsubscribedResponse`
(tag `0x15`), also for a scope you did not hold.

After the `SubscribedResponse` (tag `0x14`), the server sends a
`SportsSnapshot` (tag `0x24`) with every game in the scope, then a
`SportsGameUpdate` (tag `0x23`) each time one of them changes.

Scopes can overlap, e.g. `all` and `family:basketball`. Each update is then
delivered once per scope that covers the game. Keep one state per game for the
whole connection, and drop the copies with the `(lease_epoch, seq)` check in
[Ordering and recovery](#ordering-and-recovery).

## Messages

| Tag | Message | When |
| - | - | - |
| `0x24` | `SportsSnapshot` | After each accepted subscribe, in one or more chunks |
| `0x23` | `SportsGameUpdate` | Each change to a game in any of your scopes, once per scope |

### SportsSnapshot

| Field | Type | Description |
| - | - | - |
| `scope` | string | The subscription it answers, e.g. `all`, `league:nba` |
| `games` | `SportsGameUpdate[]` | Every game in the scope |
| `chunk_index` | uint32 | A snapshot over about 256 KB arrives in several chunks, numbered from 0. Apply each one |
| `last_chunk` | bool | Treat the scope as loaded after this chunk |
| `complete` | bool | False while the server may be missing games: after a gateway restart, after a new publisher takes over, and after 30 seconds without publisher frames. It turns true again at the publisher's next full pass, about every 10 seconds. Games it learns meanwhile arrive as ordinary updates |
| `events` | `SportsEventUpdate[]` | Only for a `sports.events` subscription; see [play-by-play](https://docs.kairos.trade/websocket/sports-play-by-play.md) |
| `schema_version` | uint32 | Internal; ignore it |

### SportsGameUpdate

| Field | Type | Description |
| - | - | - |
| `game_id` | string | The game |
| `kind` | enum | `CHANGED` or `REFRESH`: replace what you hold. `REMOVED`: drop the game and its events |
| `game` | `SportsGame` | The whole game state; unset when `kind` is `REMOVED` |
| `lease_epoch`, `seq` | uint64 | Ordering; see [Ordering and recovery](#ordering-and-recovery) |
| `sport_family`, `league` | string | Set on every kind, including `REMOVED` |
| `published_at_ms` | int64 | When the update was published, in Unix milliseconds |
| `schema_version`, `content_hash` | uint32, string | Internal; ignore them |

Every update carries the game's whole state, never a partial change. `REFRESH`
is the game re-sent unchanged by the publisher's periodic pass. Most snapshot
rows carry it, and it also arrives as a live update after a gateway restart.
Handle it exactly like `CHANGED`.

### SportsGame

| Field | Type | Description |
| - | - | - |
| `game_id` | string | Matches `gameId` on `/sports/live-events` for a game listed there; a game only TxODDS or ESPN describes is not. Opaque: do not parse it |
| `league` | string | League or tour code, e.g. `nba`, `epl`, `atp`, `tennis-opticodds`, `val` |
| `sport_family` | string | e.g. `basketball`, `soccer`, `tennis`, `cricket`, `esports` |
| `competition` | string | The competition's name when a source gives one, e.g. `NFL`; usually empty. Group by `league`, which is always set |
| `competitors` | `SportsCompetitor[]` | Two for a head-to-head game, home first; every entrant for a field |
| `phase` | string | The game's lifecycle; see [Phases](#phases) |
| `status` | string | The source's own status text, e.g. `InProgress`, `running`, `F/OT`. A label only |
| `score` | string | The whole score on one line, in `competitors` order: `98-94`, `6-2, 7-6(8-6), 2-2:30-15`, `11-9, 8-11, 11-7`, `000-000\|2-0\|Bo3`, `0-1\|Submission` |
| `parts` | `SportsScorePart[]` | The score broken into sets, games, innings, maps and so on, when the source provides them |
| `period` | string | The source's period text, e.g. `Q4`, `H2`, `HT`, `S3`, `2/3` |
| `clock` | string | The game clock, e.g. `05:12`; empty when the sport has none |
| `slug` | string | Event slug: REST's `matchingSlug`, or its `slug` when that is empty. It is the key of `matchingMarkets` on `/sports/live-events`, so use it to find the game's markets |
| `stale` | bool | No score update for 120 seconds, so the score may be behind. Also true for a game with no score feed |
| `source` | string | Where the game's state comes from: `polymarket` for a live score feed; `predictfun` or `schedule` for a listed game without one; `txodds` or `espn` for a game no Polymarket score feed covers yet, whose `game_id` is then `txodds:<fixture>` or `espn:<league>:<event>` (attribute `polymarket_game_id` names the listed Polymarket game, when there is one). See [play-by-play](https://docs.kairos.trade/websocket/sports-play-by-play.md#which-games-have-play-by-play) |
| `attributes` | map | Other providers' ids for the game, and facts only some sports have. See [Game attributes](#game-attributes) |
| `updated_at_ms` | int64 | When the score state was observed, in Unix ms; `0` for a game with no score feed |
| `scheduled_at_ms` | int64 | Scheduled start, in Unix ms; `0` when the source does not give one. The same time as `primaryMarket.gameStartTime` on `/sports/live-events` |
| `finished_at_ms` | int64 | When the game finished, in Unix ms; `0` until then or when the source does not say |

Use `phase` for the game's state. `status` and `period` vary by league, so
show them as labels and do not parse them.

### Phases

| `phase` | Meaning |
| - | - |
| `scheduled` | Not started |
| `live` | In play |
| `break` | In play, paused between periods: half-time, an intermission, the end of a quarter, inning or round |
| `overtime` | In overtime or extra time |
| `shootout` | In a penalty or hockey shootout |
| `final` | Finished |
| `suspended` | Stopped mid-game, to resume later |
| `delayed` | Start or play held up |
| `postponed` | Moved to a later date before it started |
| `cancelled` | Will not be played |
| `unknown` | Listed, but Kairos cannot tell where it is: no score feed (`source` `predictfun` or `schedule`), or a source status not yet mapped |

A game is in play when `phase` is `live`, `break`, `overtime` or `shootout`.
`timing.status` on [`GET /sports/live-events`](https://docs.kairos.trade/rest/sports#timing-and-late-game-strategies)
has the same value.

### Game attributes

`attributes` maps names to strings. Keys are snake\_case, and a provider's id
for the game is `<provider>_<thing>_id`. An attribute is present only when it
has a value. New attributes may be added, so **ignore any attribute you do not
know**. For a game on `/sports/live-events`, `events[].attributes` is the
same map less the linking ids `txodds_fixture_id` and `espn_event_id`, which
only the stream adds. The other TxODDS and ESPN keys are only on games that
source alone describes, and REST does not list those games. The stream also
fills competitor `abbreviation` from Polymarket's team registry or a linked
TxODDS or ESPN game, and `competition` from a linked game; REST has neither
field.

| Attribute | Meaning |
| - | - |
| `sportradar_game_id` | Sportradar's id for the game, when Polymarket's feed sends it (today mostly college football) |
| `polymarket_metadata_game_id` | Polymarket's metadata id for the fixture, e.g. `id2703831375414204` for cricket |
| `oddspapi_fixture_id` | OddsPapi's id for the fixture, on cricket games |
| `txodds_fixture_id` | TxODDS's fixture id: TxODDS play-by-play describes this game. See [play-by-play](https://docs.kairos.trade/websocket/sports-play-by-play.md#which-games-have-play-by-play) |
| `txodds_competition_id` | TxODDS's competition id, on a game only TxODDS describes |
| `espn_event_id` | ESPN's event id: ESPN play-by-play describes this game |
| `polymarket_game_id` | On a `txodds` or `espn` game: the Polymarket game it describes, when Polymarket lists the game but isn't scoring it yet (often the first minutes after kickoff). Its `slug` is then Polymarket's, so you can join it to the market |
| `status_detail` | ESPN's status line, e.g. `End of 3rd Quarter`, on a game only ESPN describes |
| `possession` | The side in possession, `home` or `away`, on a game only TxODDS describes |
| `threat` | How dangerous that possession is, e.g. `danger`, on a game only TxODDS describes |
| `var_review` | The VAR review under way, as TxODDS writes it, on a game only TxODDS describes |

### SportsCompetitor

| Field | Type | Description |
| - | - | - |
| `name` | string | Team, player, pair or driver |
| `abbreviation` | string | Short name, e.g. `LAL`, from Polymarket's team list, TxODDS or ESPN; often empty (most esports, tennis and soccer teams have none) |
| `side` | string | `home` or `away` in a head-to-head game; empty in a field |
| `score` | string | This competitor's score as written: `98`, `3` (sets), `245/6`, `-5` (to par). Empty when there is no score feed |
| `score_value` | double, optional | The score as a number, when it is one |
| `position` | int32, optional | Place in a field of many competitors, 1 = leading |
| `has_turn` | bool | Serving, batting, in possession or to move. Both false when the source does not say |
| `attributes` | map | Reserved for competitor facts; empty today |

The unit of `score` depends on the sport, as on the REST endpoint: points or
goals in team sports, sets won in tennis, maps won in an esports series. See
[Reading scores by sport](https://docs.kairos.trade/rest/sports.md#reading-scores-by-sport).

### SportsScorePart

| Field | Type | Description |
| - | - | - |
| `kind` | string | `set`, `game`, `inning`, `quarter`, `map`, … or `segment` when the source does not say |
| `label` | string | Its name within the game: `1`, `2`, `OT`, `current` |
| `scores` | string\[] | One score per competitor, in `competitors` order |
| `detail` | string | Anything else reported for the segment, e.g. a tiebreak `8-6` |
| `in_progress` | bool | The segment being played |
| `parts` | `SportsScorePart[]` | Nested segments, e.g. the game in play inside a set |

## Ordering and recovery

For each game, keep the `(lease_epoch, seq)` of the last update you applied,
and ignore an update whose pair is not greater. This also drops the copies that
overlapping scopes deliver. A larger `lease_epoch` means a new publisher took
over; accept it and every later update. Because each update is the whole game
state, a missed update costs nothing once the next one arrives.

A game leaves your state only on `REMOVED`, which is sent when:

* it ended more than five minutes ago;
* it has been off every source for 30 seconds (a source that fails for a few
  seconds removes nothing);
* for a game only TxODDS or ESPN describes: 15 minutes after its final, when
  its source stops sending it, or at once when it links to a Polymarket game,
  which then carries its events;
* on a `family:` or `league:` subscription, the game moved to another family or
  league. It is still live; an `all` or `game:` subscription keeps it. If you
  also hold such a scope, the `CHANGED` that follows the `REMOVED` puts the game
  back.

After a disconnect, reconnect, subscribe again, and replace your state with the
new snapshot. A connection can end without a close frame (code 1006), for
example when a network path between you and the gateway resets it; treat that
like any other disconnect.

## Errors

Subscribe errors arrive as `ErrorResponse` (tag `0x17`) with `action`
`subscribe_error:sports:<scope>`:

| Message | Meaning |
| - | - |
| `Live sports scores need an API key or a signed-in session` | The connection is anonymous |
| `Subscribe to topics ["sports"], ["sports.events"] or both, with provider "sports"` | Other topics were mixed into the request |
| `Sports subscription limit reached: 51 scopes per connection` | The connection already holds 51 scopes |
| `Sports snapshot rate limit reached; retry this scope in a few seconds` | The connection asked for more snapshot data than its budget; retry after a pause |
| `Live sports scores are switched off` | The stream is temporarily disabled; poll `/sports/live-events` meanwhile |

An invalid scope returns an error that names the problem, e.g. `sports scope
must be all, family:<family>, league:<league> or game:<gameId>`. On an
unsubscribe, the same error comes with `action`
`unsubscribe_error:sports:<scope>`.

**Snapshot budget.** Each connection may take 16 MiB of snapshots at once, then
1 MiB per second. The size counted is the snapshot before compression. A
refused subscribe changes nothing: you hold the scope as before, or not at all.
A single snapshot larger than 16 MiB is still sent when the budget is full.

### Errors while subscribed

The server can drop your sports scopes while you hold them. Each dropped scope
gets an `ErrorResponse` with `action` `sports_disabled:<scope>`, and no
`UnsubscribedResponse`:

| Message | Meaning |
| - | - |
| `Live sports scores were switched off; subscribe again later` | The stream was disabled |
| `Live sports scores stopped updating; subscribe again later` | The gateway had no frame from the publisher for 30 seconds |

The scope is gone, with all its topics; no more updates come for it. Poll
[`GET /sports/live-events`](https://docs.kairos.trade/rest/sports#live-events) meanwhile, then subscribe
again. Until the stream is back, a new subscribe is refused with
`Live sports scores are switched off`, or its snapshot comes with `complete`
false. For play-by-play, see
[its errors](https://docs.kairos.trade/websocket/sports-play-by-play.md#errors).

## Example

```python theme={null}
import os
import websocket

from kairos.v1 import sports_pb2, websocket_control_pb2

TAG_SUBSCRIBE, TAG_ERROR = 0x10, 0x17
TAG_UPDATE, TAG_SNAPSHOT = 0x23, 0x24

ws = websocket.create_connection(
    "wss://stream.kairos.trade",
    header=[
        f"X-Client-Id: {os.environ['KAIROS_CLIENT_ID']}",
        f"X-Api-Key: {os.environ['KAIROS_API_KEY']}",
        f"X-Api-Secret: {os.environ['KAIROS_API_SECRET']}",
    ],
)

request = websocket_control_pb2.SubscribeRequest(contract_id="family:basketball", provider="sports", topics=["sports"])
ws.send_binary(bytes([TAG_SUBSCRIBE]) + request.SerializeToString())

games, last = {}, {}


def apply(update):
    order = (update.lease_epoch, update.seq)
    if update.game_id in last and order <= last[update.game_id]:
        return
    last[update.game_id] = order
    if update.kind == sports_pb2.SPORTS_UPDATE_KIND_REMOVED:
        games.pop(update.game_id, None)
    else:
        # CHANGED and REFRESH both carry the whole game.
        games[update.game_id] = update.game


while True:
    frame = ws.recv()
    if not isinstance(frame, bytes) or not frame:
        continue
    tag, payload = frame[0], frame[1:]
    if tag == TAG_SNAPSHOT:
        snapshot = sports_pb2.SportsSnapshot.FromString(payload)
        for update in snapshot.games:
            apply(update)
    elif tag == TAG_UPDATE:
        update = sports_pb2.SportsGameUpdate.FromString(payload)
        apply(update)
        game = games.get(update.game_id)
        if game:
            line = " vs ".join(f"{c.name} {c.score}" for c in game.competitors)
            print(game.league, line, game.period, game.clock, game.phase)
    elif tag == TAG_ERROR:
        error = websocket_control_pb2.ErrorResponse.FromString(payload)
        print("server error", error.action, error.message)
```

Compile `sports.proto` and `websocket_control.proto` as described in
[Protobuf reference](https://docs.kairos.trade/websocket/protobuf-reference.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.