> ## 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 play-by-play

> Push every play of a live game, in one event shape for every sport, over the market data WebSocket

The play-by-play stream pushes each thing that happens in a live game: a goal,
a card, a substitution, a basket, a timeout, a period ending. Every sport uses
the same `SportsGameEvent` shape. A normalized `kind` tells you what happened,
and the source's own type and text tell you how it described it, so a new sport
arrives without a schema change.

It extends the [sports scores stream](https://docs.kairos.trade/websocket/sports-scores.md): the same
connection, API key, scopes and ordering. You can take scores, events, or both.

## Subscribing

Send a `SubscribeRequest` (tag `0x10`) with `provider: "sports"`, the scope as
`contract_id`, and `sports.events` in `topics`:

| `topics` | You receive |
| - | - |
| `["sports", "sports.events"]` | Games and their events |
| `["sports.events"]` | Events only; no game state |
| `["sports"]` | Games only, as on the [scores stream](https://docs.kairos.trade/websocket/sports-scores.md) |

The scopes are the same as for scores: `all`, `family:<sportFamily>`,
`league:<league>` and `game:<gameId>`, and they count toward the same 51-scope
limit. Subscribing again to a scope you hold replaces what it streams with what
you name, and sends a new snapshot. To drop only the events, send an
`UnsubscribeRequest` (tag `0x11`) with the scope, `provider: "sports"` and
`topics: ["sports.events"]` (field 4; see
[Subscribing](https://docs.kairos.trade/websocket/sports-scores.md#subscribing) if your
`websocket_control.proto` lacks it).

After the `SubscribedResponse` (tag `0x14`), the `SportsSnapshot` (tag `0x24`)
carries each covered game's 50 most recent events in `events`, oldest first per
game. A `SportsEventUpdate` (tag `0x25`) follows for every new, corrected,
overturned or deleted event, once per scope that covers the game. A connection that did not
ask for `sports.events` never receives a `0x25` frame.

## Which games have play-by-play

| Source | Sports today | Events |
| - | - | - |
| `txodds` | Soccer (Premier League, World Cup), NFL | Goals, cards, corners, shots, free kicks, offsides, substitutions, VAR reviews, injuries, stoppages; touchdowns, field goals, conversions, penalties, turnovers, sacks, punts, timeouts, reviews; kick-off, half time and full time |
| `espn` | NBA | Every play: baskets and misses with shot distance and court position, free throws, rebounds, turnovers, fouls, violations, substitutions, timeouts, reviews, period and game end |
| every other game with a live score | Basketball, soccer, tennis, baseball, esports, table tennis, fights, motorsport and the rest | Events derived from the scoreboard: start, each period change, every score change with the score after it, suspensions and delays, final |

One match is one game. A TxODDS or ESPN game links to a Polymarket game by
teams, league and date. Exactly one Polymarket game must qualify:

* the same league and sport family;
* both teams the same, by name or code, read through Polymarket's team
  registry;
* dates at most a day apart, or, when either game has no date, both games
  started.

If two games from one source qualify for the same Polymarket game, neither
links. A linked game's events arrive on the Polymarket game's `game_id`, in its
competitor order, and that game carries the source's id: `txodds_fixture_id` or
`espn_event_id`. Those ids are how you tell that a game has rich play-by-play.
Its scoreboard-derived events are withdrawn then, since the source reports the
same plays.

A TxODDS or ESPN game that links to no Polymarket game arrives as a game of its
own (`txodds:<fixture>`, `espn:<league>:<event>`) with `source` `txodds` or
`espn`. A TxODDS competition Kairos does not map to a league gets the league
`txodds-<competitionId>`. One that is only on the schedule, with no events yet,
is not sent. A game that was linked once does not come back as a game of its own.
Listed games without a score feed (`source` `predictfun` or `schedule`) have no
events.

## Messages

| Tag | Message | When |
| - | - | - |
| `0x24` | `SportsSnapshot` | After each accepted subscribe, in one or more chunks; `events` holds recent events for a `sports.events` subscription |
| `0x25` | `SportsEventUpdate` | Each new, corrected, overturned or deleted event in any of your scopes, once per scope |

### SportsEventUpdate

| Field | Type | Description |
| - | - | - |
| `game_id` | string | The game the event belongs to |
| `event` | `SportsGameEvent` | The event's whole current state |
| `lease_epoch`, `seq` | uint64 | Shared with `SportsGameUpdate`; see [Ordering](#ordering-and-corrections) |
| `sport_family`, `league` | string | Routing keys, as on `SportsGameUpdate` |
| `published_at_ms` | int64 | When it was published, in Unix milliseconds |
| `schema_version`, `content_hash` | uint32, string | Internal; ignore them |

### SportsGameEvent

| Field | Type | Description |
| - | - | - |
| `event_id` | string | Stable for the life of the game and unique across the stream: `<source>:<source_event_id>` |
| `game_id` | string | The game |
| `source` | string | `txodds` or `espn` for a play-by-play feed; `scoreboard` for an event derived from score and phase changes |
| `source_event_id` | string | The source's own id for the event |
| `revision` | uint64 | Grows each time the event is corrected, overturned or deleted |
| `deleted` | bool | Drop the event: it was a feed error, e.g. a source's duplicate of a play it still lists, or it left this game (see [Which games have play-by-play](#which-games-have-play-by-play)). A play overturned on review is never deleted; see [Overturned plays](#overturned-plays-and-reviews) |
| `kind` | string | What happened, normalized across sports; see [Kinds](#kinds) |
| `subtype` | string | The normalized refinement of `kind`, e.g. `yellow` for a `card`; empty when there is none. See [Subtypes](#subtypes) |
| `source_type` | string | The source's own type, e.g. `penalty_flag`, `touchdown`, `Pullup Jump Shot`; for an event Kairos derives (a period start), the derived name |
| `description` | string | The source's own text, e.g. `Tyler Kolek makes 29-foot running jump shot (Jalen Brunson assists)`; empty when it has none |
| `period` | string | The period the event happened in, as the source writes it: `H2`, `Q4`, `3` |
| `clock` | string | The game clock at the event: `67'` (soccer minute), `08:00` (time left in an NFL quarter), `23.3` |
| `occurred_at_ms` | int64 | Wall time it happened, in Unix milliseconds; 0 when unknown |
| `sort_key` | int64 | Order within the game: sort ascending, ties by `event_id`. A late event carries the key of when it happened |
| `sequence` | uint64 | The source's own sequence number within the game (TxODDS's message seq, ESPN's play sequence); 0 when it has none |
| `competitor_index` | int32, optional | The side, as an index into `SportsGame.competitors`; unset for an event of the whole game |
| `participants` | `SportsParticipant[]` | The people involved |
| `scores` | string\[] | The score right after the event, one per competitor, as `SportsCompetitor.score` writes it; empty when unknown |
| `scoring` | bool | The event changed the score; `false` once the play is overturned |
| `attributes` | map | Detail only some events have; see [Event attributes](#event-attributes) |
| `measures` | `SportsEventMeasure[]` | Measured detail, e.g. `shot_distance` (ft) or `coordinate` with parts `x` and `y` |
| `received_at_ms` | int64 | When Kairos first saw this revision |

### SportsParticipant

| Field | Type | Description |
| - | - | - |
| `name` | string | As the source writes it; empty when the source gives only an id |
| `id` | string | The source's id for the person |
| `role` | string | What they did: `scorer`, `assist`, `shooter`, `blocker`, `player_in`, `player_out`, `fouler`, `fouled`, `rebounder`, `stealer`, `gained_possession`, `carded`, `injured`, `penalized`, `intercepted_by`; `player` when the source does not say |
| `competitor_index` | int32, optional | Their side, when known |

### Event attributes

Every key an event's `attributes` can hold. An attribute is present only when
it has a value. New keys may be added; ignore any you do not know.

| Attribute | Source | Meaning |
| - | - | - |
| `points` | every source | Points the event added to its side, e.g. `3`; kept on an overturned play |
| `overturned` | every source | `true` on a play that happened and was then reversed: a goal disallowed, a touchdown taken off on review, a play the source withdrew or edited to say it was reversed |
| `ref_event_id` | every source | On a `review`: the `event_id` of the play it concerns |
| `outcome` | every source | On a `review`: `overturned` or `upheld`. On a missed field goal (`txodds`): `missed` |
| `subject` | every source | What a review was about: `goal`, `red_card`, `score`, or the subtype or kind of the play, e.g. `touchdown` |
| `threat` | `txodds` | How dangerous a possession is, e.g. `danger` |
| `detail` | `txodds` | TxODDS's own detail for the event, as written |
| `espn_type_id` | `espn` | ESPN's id for the play type |
| `period_name` | `espn` | ESPN's name for the period, e.g. `1st Quarter` |
| `short_description` | `espn` | ESPN's short text for the play |
| `score` | `scoreboard` | The game's whole score line after the event, as `SportsGame.score` |
| `score_detail` | `scoreboard` | The score's segments after the event, e.g. `set 1: 6-4; set 2: 3-2` |
| `phase` | `scoreboard` | On a `stoppage`: the phase the game entered, `suspended` or `delayed` |

### SportsEventMeasure

| Field | Type | Description |
| - | - | - |
| `name` | string | e.g. `shot_distance`, `coordinate`, `x`, `y` |
| `value` | string | As the source writes it |
| `number` | double, optional | The value as a number |
| `unit` | string | e.g. `ft`; empty when there is none |
| `parts` | `SportsEventMeasure[]` | Nested values, e.g. the `x` and `y` of a coordinate |

## Kinds

`kind` is one of:

| Kind | Examples |
| - | - |
| `game_start`, `game_end` | Kick-off, full time, end of game |
| `period_start`, `period_end` | A new quarter, half time, end of a set or innings |
| `score` | A goal, a basket, a touchdown, a run, a set or game won |
| `shot` | A shot on or off target, a missed basket or field goal, a free throw attempt |
| `foul`, `penalty`, `card`, `violation` | A personal foul, a penalty kick or flag, a yellow card, traveling |
| `substitution`, `timeout`, `injury`, `review`, `stoppage` | A player change, a timeout, a VAR check, a coach's challenge or its outcome, a score correction, a delay |
| `set_piece`, `offside` | A corner, free kick or goal kick; an offside |
| `possession`, `turnover`, `rebound` | A jump ball or a drive starting, a turnover, a rebound |
| `play` | A routine play no other kind names, e.g. a punt or a sack |
| `point` | A point inside a game that does not change the score line, e.g. 15-0 in a tennis game |
| `rally`, `pitch`, `at_bat`, `lap`, `pit_stop`, `knockdown`, `round_end` | Reserved for sources that report them |
| `other` | Anything a source reports that no kind covers |

New kinds may be added. Treat a kind you do not know as `other`, and show
`source_type` and `description` as the source wrote them.

### Subtypes

`subtype` refines a kind. It is empty when the source gives nothing finer, and
the lists may grow; treat a subtype you do not know as empty.

| Kind | Subtypes |
| - | - |
| `card` | `yellow`, `red` |
| `set_piece` | `corner`, `free_kick`, `goal_kick` |
| `score` | `touchdown`, `field_goal`, `extra_point`, `two_point_conversion`, `safety` |
| `shot` | `field_goal`, `free_throw` |
| `turnover` | `interception` |
| `play` | `fumble`, `sack`, `punt`, `kickoff` |
| `possession` | `drive_start`, `jump_ball` |
| `review` | `var`, `challenge` |
| `penalty` | `spot_kick` (soccer), `flag` (American football), `ejection` |

### American football (TxODDS)

Each play carries TxODDS's own time (`occurred_at_ms`), message `sequence`, raw
action (`source_type`) and the quarter clock. A flag and its enforcement are one
`penalty`, whose `detail` attribute reads e.g. `offensive, 5 yds, accept` and
whose side is the penalized team. A scoring play arrives on the play itself;
TxODDS confirms it a little later. A play it never confirms, or whose points it
takes back, is overturned.

## Overturned plays and reviews

The feed is a record of the game. A play that happened stays on it when it is
reversed: a goal disallowed by VAR, a touchdown taken off on review, a basket
ESPN removes after a challenge, or a score the scoreboard corrects down. Kairos
sends the play again at a higher `revision` with the attribute `overturned`
set to `true` and `scoring` set to `false`. Its `kind`, `subtype` and `points`
stay as they were called, so you can show "Goal (disallowed)". The game's own
score already excludes it.

A review and its outcome are events of their own, of kind `review`. Each
carries `ref_event_id`, the `event_id` of the play it concerns:

| Event | `subtype` | `attributes` |
| - | - | - |
| A VAR check opens (`txodds`) | `var` | `subject` (`goal`, `red_card`), `ref_event_id` |
| A challenge or replay review (`txodds`, NFL) | `challenge` | `ref_event_id` once the play it reversed is known |
| A goal disallowed (`txodds`, `source_type` usually `var_end`) | empty | `outcome` `overturned`, `subject` `goal`, `ref_event_id` |
| A VAR goal check that stands (`txodds`, `source_type` `var_end`) | `var` | `outcome` `upheld`, `subject` `goal`, `ref_event_id` |
| A coach's challenge result (`espn`) | `challenge` | `outcome` `overturned` or `upheld`; `ref_event_id` when ESPN drops the play it reversed |
| A score corrected down (`scoreboard`, `source_type` `score_correction`) | empty | `outcome` `overturned`, `subject` `score`, `score`; `ref_event_id` when the feed sent an event for the score it replaced |
| An outcome the source did not send (`source_type` `overturned`, `event_id` `<play event_id>:overturned`) | the review's, or empty | `outcome` `overturned`, `subject`, `ref_event_id` |

Sorted by `sort_key`, a review follows the play it concerns and its outcome
follows the review. An event Kairos adds sorts after the newest event of the
game when the play was reversed. TxODDS reports how a VAR check ended only for a
goal; other checks get no outcome. `ref_event_id` may name an event older than
the snapshot. A play overturned and then listed again by its source stands
again: it arrives without `overturned`, at a higher `revision`, and an outcome
Kairos added for it (`source_type` `overturned` or `score_correction`) is deleted.

Of a source's own changes, only a feed error is `deleted: true`: an event that
duplicates a play its source still lists, one Kairos could not name (`other`)
that carried no text, or an outcome Kairos added for a play that stands again.
Events also leave a game deleted when it links to a play-by-play source, or when
a source's link moves to another game.

## Ordering and corrections

Event frames share `(lease_epoch, seq)` with game updates, so a game's update
always arrives before its first event. For each `event_id`, keep the
`revision` you hold and ignore a frame whose `revision` is not greater. A
correction, such as a player added to a goal or an edited play, arrives as the
same `event_id` with a larger `revision` and the whole new state; so does an
overturned play. A deleted event arrives with `deleted: true`; drop it. The same check drops the copies
that overlapping scopes deliver, and the repeats sent after a gateway restart.

When a game's `SportsGameUpdate` is `REMOVED`, drop its events too. After a
disconnect, reconnect, subscribe again, and rebuild from the snapshot. The
snapshot holds each game's 50 most recent events; it is not the game's full
history.

## Errors

Subscribe errors arrive as `ErrorResponse` (tag `0x17`) with `action`
`subscribe_error:sports:<scope>`, as on the [scores stream](https://docs.kairos.trade/websocket/sports-scores.md#errors). Play-by-play adds:

| Message | Meaning |
| - | - |
| `Live sports play-by-play is switched off` | Events are temporarily disabled; scores still work |

If events are switched off while you hold them, each scope with `sports.events`
gets an `ErrorResponse` with `action` `sports_events_disabled:<scope>` and
`message` `Live sports play-by-play was switched off; scores continue`. The
scope loses `sports.events`, and no `UnsubscribedResponse` is sent. Its scores
keep flowing; a scope that held only `sports.events` is gone. To get events
back, subscribe to the scope again with the topics you want once play-by-play
is back on. Until then that subscribe is refused with
`Live sports play-by-play is switched off`.

When scores are switched off or stop updating, the whole scope is dropped,
events included; see
[Errors while subscribed](https://docs.kairos.trade/websocket/sports-scores.md#errors-while-subscribed).

## 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, TAG_EVENT = 0x23, 0x24, 0x25

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:soccer", provider="sports", topics=["sports", "sports.events"]
)
ws.send_binary(bytes([TAG_SUBSCRIBE]) + request.SerializeToString())

games, timelines = {}, {}


def apply_event(update):
    timeline = timelines.setdefault(update.game_id, {})
    held = timeline.get(update.event.event_id)
    if held is not None and update.event.revision <= held.revision:
        return
    if update.event.deleted:
        timeline.pop(update.event.event_id, None)
        return
    timeline[update.event.event_id] = update.event
    game = games.get(update.game_id)
    if game is not None:
        score = "-".join(update.event.scores)
        note = " (overturned)" if update.event.attributes.get("overturned") == "true" else ""
        print(game.league, update.event.clock, update.event.kind, update.event.subtype, score + note)


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:
            games[update.game_id] = update.game
        for update in snapshot.events:
            apply_event(update)
    elif tag == TAG_UPDATE:
        update = sports_pb2.SportsGameUpdate.FromString(payload)
        if update.kind == sports_pb2.SPORTS_UPDATE_KIND_REMOVED:
            games.pop(update.game_id, None)
            timelines.pop(update.game_id, None)
        else:
            games[update.game_id] = update.game
    elif tag == TAG_EVENT:
        apply_event(sports_pb2.SportsEventUpdate.FromString(payload))
    elif tag == TAG_ERROR:
        error = websocket_control_pb2.ErrorResponse.FromString(payload)
        print("server error", error.action, error.message)
```

The example applies game updates without checking `(lease_epoch, seq)`; see
[Ordering and recovery](https://docs.kairos.trade/websocket/sports-scores.md#ordering-and-recovery) for
that check. Sort a game's timeline by `sort_key`, then `event_id`, to show it in
order.


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