> For the complete documentation index, see [llms.txt](https://rock-odds.gitbook.io/rock-odds-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://rock-odds.gitbook.io/rock-odds-docs/endpoints/streaming.md).

# Real-time stream

The RockOdds stream sends an initial odds snapshot followed by incremental updates over [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) (SSE).

Use it when your application needs to maintain a current local odds board without repeatedly polling REST endpoints.

```http
GET /stream
```

## Connect

The stream is a long-lived HTTP response. It uses standard SSE frames:

```
event: snapshot
data: {"count":1,"games":[...]}

```

### curl

```bash
curl --no-buffer \
  --url "https://rockodds.live/api/v2/stream?sport=NBA&game_status=all" \
  --header "X-API-Key: YOUR_API_KEY"
```

`--no-buffer` prints each event as it arrives.

### Query parameters

| Parameter     | Type    | Required                | Default    | Description                                                         |
| ------------- | ------- | ----------------------- | ---------- | ------------------------------------------------------------------- |
| `api_key`     | string  | Only without the header | —          | API key for clients that cannot send `X-API-Key`.                   |
| `game_status` | string  | No                      | `pregame`  | `pregame`, `live`, or `all` for both pregame and live odds.         |
| `live`        | boolean | No                      | —          | Legacy alias: `false` selects pregame and `true` selects live odds. |
| `sport`       | string  | No                      | All sports | Filter by `NFL`, `NBA`, `NCAA`, `NHL`, `MLB`, or `SOCCER`.          |

The stream does not currently accept `market` or `period` filters. Filter those values in your client.

{% hint style="info" %}
Use `game_status=all` to receive pregame and live odds over one connection. Existing `live=true` and `live=false` integrations remain supported. Do not send `game_status` and `live` together.
{% endhint %}

## State model

Keep games in a map keyed by `game_id`. Inside each game, keep markets keyed by `market_id`:

```
games[game_id].markets[market_id]
```

Apply events in the order received on a connection. Treat all IDs as opaque strings.

| Event         | Client action                                                           |
| ------------- | ----------------------------------------------------------------------- |
| `snapshot`    | Replace all local state for this connection.                            |
| `update`      | Merge the market metadata and replace that market's `lines`.            |
| `locked`      | Mark every line in the identified market as locked.                     |
| `game_add`    | Add or replace the supplied game.                                       |
| `market_add`  | Replace the supplied game; it includes the complete current market set. |
| `game_remove` | Delete the game.                                                        |
| `live_update` | Update the game's `live` value.                                         |
| `heartbeat`   | No state change. Use it to monitor the connection.                      |
| `shutdown`    | Reconnect with backoff.                                                 |

Ignore unknown event types so your integration remains forward-compatible.

## Browser example

The browser `EventSource` API cannot set an `X-API-Key` header, so it requires query-parameter authentication.

{% hint style="warning" %}
Do not put a secret API key in a public website. Proxy the stream through your backend. Use the direct browser example only in a trusted environment where exposing the key is acceptable.
{% endhint %}

```javascript
const url = new URL("https://rockodds.live/api/v2/stream");
url.searchParams.set("api_key", "YOUR_API_KEY");
url.searchParams.set("sport", "NBA");
url.searchParams.set("game_status", "all");

const stream = new EventSource(url);
const games = new Map();

stream.addEventListener("snapshot", (event) => {
  const snapshot = JSON.parse(event.data);
  games.clear();

  for (const game of snapshot.games) {
    games.set(game.game_id, game);
  }
});

stream.addEventListener("update", (event) => {
  const update = JSON.parse(event.data);
  const game = games.get(update.game_id);

  if (!game) return;

  const existing = game.markets[update.market_id] ?? {};
  game.markets[update.market_id] = {
    ...existing,
    market_type: update.market_type,
    period: update.period,
    limit: update.limit ?? null,
    lines: update.lines,
  };
});

stream.addEventListener("locked", (event) => {
  const update = JSON.parse(event.data);
  const market = games.get(update.game_id)?.markets?.[update.market_id];

  if (!market) return;

  market.lines = market.lines.map((line) => ({
    ...line,
    locked: true,
  }));
});

for (const eventType of ["game_add", "market_add"]) {
  stream.addEventListener(eventType, (event) => {
    const game = JSON.parse(event.data);
    games.set(game.game_id, game);
  });
}

stream.addEventListener("game_remove", (event) => {
  const update = JSON.parse(event.data);
  games.delete(update.game_id);
});

stream.addEventListener("live_update", (event) => {
  const update = JSON.parse(event.data);
  const game = games.get(update.game_id);

  if (game) {
    game.live = update.live;
  }
});

stream.addEventListener("heartbeat", () => {
  // Connection is active. No state change is needed.
});

stream.addEventListener("shutdown", () => {
  stream.close();
  // Create a new EventSource after a backoff delay.
});

stream.onerror = () => {
  // EventSource normally reconnects automatically.
  // Update connection status in your application here.
};
```

## Python example

This example uses `httpx` and reconnects with exponential backoff.

```python
import json
import os
import time

import httpx


STREAM_URL = "https://rockodds.live/api/v2/stream"
games: dict[str, dict] = {}


def apply_event(event_type: str, data: dict) -> None:
    if event_type == "snapshot":
        games.clear()
        games.update((game["game_id"], game) for game in data["games"])
        return

    if event_type == "update":
        game = games.get(data["game_id"])
        if not game:
            return

        existing = game["markets"].get(data["market_id"], {})
        game["markets"][data["market_id"]] = {
            **existing,
            "market_type": data["market_type"],
            "period": data["period"],
            "limit": data.get("limit"),
            "lines": data["lines"],
        }
        return

    if event_type == "locked":
        game = games.get(data["game_id"])
        market = game and game["markets"].get(data["market_id"])
        if market:
            for line in market["lines"]:
                line["locked"] = True
        return

    if event_type in {"game_add", "market_add"}:
        games[data["game_id"]] = data
        return

    if event_type == "game_remove":
        games.pop(data["game_id"], None)
        return

    if event_type == "live_update":
        game = games.get(data["game_id"])
        if game:
            game["live"] = data["live"]


def consume() -> None:
    backoff_seconds = 1

    while True:
        try:
            timeout = httpx.Timeout(65.0, connect=10.0)
            with httpx.stream(
                "GET",
                STREAM_URL,
                headers={"X-API-Key": os.environ["ODDS_API_KEY"]},
                params={"sport": "NBA", "game_status": "all"},
                timeout=timeout,
            ) as response:
                response.raise_for_status()
                backoff_seconds = 1
                event_type = None

                for line in response.iter_lines():
                    if line.startswith("event:"):
                        event_type = line.removeprefix("event:").strip()
                    elif line.startswith("data:") and event_type:
                        data = json.loads(line.removeprefix("data:").strip())

                        if event_type == "shutdown":
                            break

                        if event_type != "heartbeat":
                            apply_event(event_type, data)

                        event_type = None

        except (httpx.HTTPError, json.JSONDecodeError) as exc:
            print(f"Stream disconnected: {exc}")

        time.sleep(backoff_seconds)
        backoff_seconds = min(backoff_seconds * 2, 30)


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

Install the client with `pip install httpx`.

## Event payloads

### `snapshot`

Sent immediately after connection. It contains the complete state matching the connection's `sport` and game-status filters.

```json
{
  "count": 1,
  "games": [
    {
      "game_id": "a1b2c3d4-e5f6-47a8-9012-3456789abcde",
      "sport": "NBA",
      "home_team": "Los Angeles Lakers",
      "away_team": "Boston Celtics",
      "start_time": "2026-08-28T19:30:00-04:00",
      "live": false,
      "markets": {}
    }
  ]
}
```

Always replace state when a new connection receives its snapshot. The stream does not replay missed events.

### `update`

Sent when one market's odds change:

```json
{
  "type": "update",
  "game_id": "a1b2c3d4-e5f6-47a8-9012-3456789abcde",
  "market_id": "game:spread",
  "market_type": "spread",
  "period": "game",
  "live": false,
  "sport": "NBA",
  "limit": 500,
  "lines": []
}
```

Replace `lines` for this market. Preserve existing `side` and `label` fields when merging the update.

### `locked`

Sent when all lines in one market become unavailable:

```json
{
  "type": "locked",
  "game_id": "a1b2c3d4-e5f6-47a8-9012-3456789abcde",
  "market_id": "game:spread",
  "market_type": "spread",
  "period": "game",
  "live": false,
  "sport": "NBA"
}
```

Mark every locally stored line in the market as `locked: true`.

### `game_add` and `market_add`

Both contain a complete game object in the same shape used by the snapshot. Add or replace the game in local state.

### `game_remove`

```json
{
  "type": "game_remove",
  "game_id": "a1b2c3d4-e5f6-47a8-9012-3456789abcde",
  "sport": "NBA"
}
```

Delete the game and all its markets.

### `live_update`

```json
{
  "type": "live_update",
  "game_id": "a1b2c3d4-e5f6-47a8-9012-3456789abcde",
  "sport": "NBA",
  "live": true
}
```

Update the stored `live` value. A game that transitions to live will no longer receive odds updates on a pregame-only stream. A `game_status=all` stream continues receiving that game's live odds updates on the same connection.

### `heartbeat`

Sent approximately every 30 seconds:

```json
{
  "ts": "2026-08-28T23:30:00.000000+00:00"
}
```

No state change is required. Reconnect if no event, including a heartbeat, arrives for more than 60 seconds.

### `shutdown`

```json
{
  "reason": "server shutting down"
}
```

Reconnect with backoff. A shutdown frame is not guaranteed for every network interruption, so also handle ordinary connection closure.

## Reconnection and recovery

There are no replay IDs or missed-event recovery requests. Recovery is snapshot-based:

1. Detect the closed or stale connection.
2. Reconnect with exponential backoff.
3. Wait for the new `snapshot`.
4. Replace the old state with that snapshot.
5. Resume applying incremental events.

Each client has a bounded event buffer. A client that stops consuming events can be disconnected; use the same reconnect flow to recover.

## Connection limits

API keys normally allow three concurrent stream connections, although account-specific limits may differ. Connection attempts are limited to 30 per minute. See [errors and limits](/rock-odds-docs/errors-and-limits.md) for retry behavior.

## Integration checklist

* Store games by `game_id` and markets by `market_id`.
* Treat all IDs as opaque.
* Replace all state on `snapshot`.
* Merge `update` metadata and replace its `lines`.
* Preserve `side` and `label` when applying an update.
* Handle game additions, removals, live transitions, and locked markets.
* Monitor heartbeats and reconnect stale connections.
* Replace state from the next snapshot after every reconnect.
* Ignore unknown fields and event types.
