Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .github/workflows/starter.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ on:
paths:
- 'examples/odds_workspace.py'
- 'examples/odds-migration/**'
- 'examples/websocket_stream.py'
- 'examples/websocket-replay/**'
- 'examples/support-report/**'
- 'examples/test_odds_workspace.py'
- 'parlay_api/**'
Expand All @@ -15,6 +17,8 @@ on:
paths:
- 'examples/odds_workspace.py'
- 'examples/odds-migration/**'
- 'examples/websocket_stream.py'
- 'examples/websocket-replay/**'
- 'examples/support-report/**'
- 'parlay_api/**'
- 'pyproject.toml'
Expand All @@ -32,11 +36,13 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
- run: python -m pip install . pytest
- run: python -m pip install ".[ws]" pytest
- name: Exercise the installed CLI outside the checkout
working-directory: ${{ runner.temp }}
run: |
python "$GITHUB_WORKSPACE/tests/test_installed_package.py"
python -m pytest -q --import-mode=importlib "$GITHUB_WORKSPACE/tests/test_odds_coverage.py" "$GITHUB_WORKSPACE/tests/test_first_response.py" "$GITHUB_WORKSPACE/tests/test_migration_example.py"
- name: Exercise the offline support report
run: python -B -m unittest discover -s examples/support-report -p test_support_repro.py
- name: Replay fictional frames and exercise a loopback WebSocket
run: python -B tests/test_websocket_examples.py
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,10 @@ runs without keys or API requests.
After a successful SDK request, `client.last_quota` contains the returned usage
headers. Header fields may be `None` when the service does not provide them.

Optional WebSocket examples require `python -m pip install 'parlay-api[ws]'`.
Practice a disconnect, duplicate update and reconnect using the [offline WebSocket replay](examples/websocket-replay).
It runs with Python alone and includes a fictional price trace.

The optional live WebSocket example requires `python -m pip install 'parlay-api[ws]'`.
WebSocket access is Business tier and up; see the current docs before connecting.

### Request delayed Pinnacle game lines
Expand Down
31 changes: 31 additions & 0 deletions examples/websocket-replay/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# What happens to a price when a WebSocket reconnects?

Follow one fictional NBA moneyline through two connections. You can run the exercise with Python 3.9 or later. It reads the included JSON trace and makes zero network requests.

```sh
python3 examples/websocket-replay/replay.py
```

From the downloadable example bundle, run `python3 websocket-replay/replay.py` instead.

| Trace step | What to look for |
| --- | --- |
| 2–4 | The partial initial state contains home −115 and away +105. A duplicate repeats the same price and row clock. The next update changes both. |
| 5 | A heartbeat leaves the row clock and prices untouched. |
| 6–8 | Disconnecting clears the displayed observation. A delayed callback from connection 1 cannot populate connection 2. |
| 9–10 | Connection 2 starts with an empty recent-row snapshot. Its first matching update supplies a price observed on this connection. |
| 11–12 | Cancel clears the observation. A later callback from that connection is ignored. |

The outer `action` and `connection` fields belong to the local exercise. Inside `frame` are examples of odds-stream messages. The client matches the event, bookmaker, market, period and teams before using a two-sided price. A row's `last_update` is an epoch-millisecond clock. Print it separately from the time your client received the frame.

An empty partial snapshot only describes the rows returned. A reconnect can miss intermediate changes. A later receipt can carry an older observation. For other markets, use the fields that identify that selection, including the player, side, period and line when applicable. The reducer covers the illustrated moneyline shapes.

## Trying one live connection

The sibling `websocket_stream.py` example opens one connection, sends the credential in the handshake header and stops after the chosen frame count. Install `parlay-api[ws]` and set `PARLAY_API_KEY` privately before using it. Use an eligible Business-or-higher account with an available streaming allowance. Each invocation makes a new connection attempt.

```sh
python3 examples/websocket_stream.py basketball_nba --frames 3
```

For a free browser exercise, try the [streaming guide and fictional event](https://parlay-api.com/live-odds-api?utm_source=github&utm_medium=developer_example&utm_campaign=sports_data_preview&utm_content=ws_replay).
96 changes: 96 additions & 0 deletions examples/websocket-replay/replay.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""Replay a fictional two-connection trace for one moneyline, entirely offline."""
import json
from pathlib import Path


SPORT = "basketball_nba"
SELECTION = {
"event_id": "fictional-north-south",
"bookmaker": "example_book",
"kind": "game",
"market_key": "h2h",
"period_key": None,
"home_team": "North Owls",
"away_team": "South Foxes",
}


class SelectedMoneyline:
"""A local observation on one connection. The connection number is client state."""

def __init__(self):
self.latest_connection = 0
self.active_connection = None
self.quote = None
self.row_clock = 0

def observe(self, entry):
connection = entry["connection"]
action = entry["action"]
if action == "open" and connection > self.latest_connection:
self.latest_connection = self.active_connection = connection
self.quote = None
self.row_clock = 0
return "Waiting for a matching observation"
if connection != self.active_connection or action == "open":
return "Ignored callback from inactive connection"
if action in ("disconnect", "cancel"):
self.active_connection = None
self.quote = None
return "Connection closed"
if action != "frame":
raise ValueError("Unrecognized local action")
frame = entry["frame"]
if frame.get("type") == "heartbeat":
return "Heartbeat"
if frame.get("type") not in ("initial_state", "odds_update"):
return "Ignored other frame"
if frame.get("sport_key") != SPORT or not isinstance(frame.get("data"), list):
return "Ignored out-of-scope or malformed frame"
changes = []
for row in frame["data"]:
if not isinstance(row, dict) or row.get("sport_key", SPORT) != SPORT:
continue
if any(row.get(field) != value for field, value in SELECTION.items()):
continue
updated = row.get("last_update")
if type(updated) is not int or updated <= 0:
continue
if updated < self.row_clock:
changes.append("Ignored an older observation")
continue
if row.get("available") is False or row.get("action") == "remove":
self.row_clock = updated
self.quote = None
changes.append("Selection unavailable")
continue
home, away = row.get("home_ml"), row.get("away_ml")
if any(type(price) is not int or abs(price) < 100 for price in (home, away)):
continue
new_quote = (home, away, updated)
if new_quote == self.quote:
changes.append("Ignored duplicate")
elif updated == self.row_clock:
self.quote = None
changes.append("No unambiguous price at this timestamp")
else:
self.row_clock = updated
self.quote = new_quote
changes.append("Observed price")
return ", ".join(changes) or "No matching price observed in this frame"


def main():
session = json.loads(Path(__file__).with_name("session.json").read_text())
selection = SelectedMoneyline()
for index, entry in enumerate(session, 1):
result = selection.observe(entry)
shown = "no observation on this connection"
if selection.quote is not None:
home, away, updated = selection.quote
shown = f"home {home:+d}, away {away:+d}, row clock {updated} ms"
print(f"{index:2d}. {result} | {shown}")


if __name__ == "__main__":
main()
177 changes: 177 additions & 0 deletions examples/websocket-replay/session.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
[
{
"action": "open",
"connection": 1
},
{
"action": "frame",
"connection": 1,
"frame": {
"type": "initial_state",
"sport_key": "basketball_nba",
"snapshot_scope": "recent_rows",
"snapshot_complete": false,
"data": [
{
"sport_key": "basketball_nba",
"event_id": "fictional-north-south",
"home_team": "North Owls",
"away_team": "South Foxes",
"bookmaker": "example_book",
"kind": "game",
"market_key": "h2h",
"period_key": null,
"home_ml": -115,
"away_ml": 105,
"last_update": 1806600000000
}
]
}
},
{
"action": "frame",
"connection": 1,
"frame": {
"type": "odds_update",
"sport_key": "basketball_nba",
"data": [
{
"sport_key": "basketball_nba",
"event_id": "fictional-north-south",
"home_team": "North Owls",
"away_team": "South Foxes",
"bookmaker": "example_book",
"kind": "game",
"market_key": "h2h",
"period_key": null,
"home_ml": -115,
"away_ml": 105,
"last_update": 1806600000000
}
]
}
},
{
"action": "frame",
"connection": 1,
"frame": {
"type": "odds_update",
"sport_key": "basketball_nba",
"data": [
{
"sport_key": "basketball_nba",
"event_id": "fictional-north-south",
"home_team": "North Owls",
"away_team": "South Foxes",
"bookmaker": "example_book",
"kind": "game",
"market_key": "h2h",
"period_key": null,
"home_ml": -120,
"away_ml": 110,
"last_update": 1806600006000
}
]
}
},
{
"action": "frame",
"connection": 1,
"frame": {
"type": "heartbeat",
"timestamp": 1806600010
}
},
{
"action": "disconnect",
"connection": 1
},
{
"action": "open",
"connection": 2
},
{
"action": "frame",
"connection": 1,
"frame": {
"type": "odds_update",
"sport_key": "basketball_nba",
"data": [
{
"sport_key": "basketball_nba",
"event_id": "fictional-north-south",
"home_team": "North Owls",
"away_team": "South Foxes",
"bookmaker": "example_book",
"kind": "game",
"market_key": "h2h",
"period_key": null,
"home_ml": -115,
"away_ml": 105,
"last_update": 1806600000000
}
]
}
},
{
"action": "frame",
"connection": 2,
"frame": {
"type": "initial_state",
"sport_key": "basketball_nba",
"snapshot_scope": "recent_rows",
"snapshot_complete": false,
"data": []
}
},
{
"action": "frame",
"connection": 2,
"frame": {
"type": "odds_update",
"sport_key": "basketball_nba",
"data": [
{
"sport_key": "basketball_nba",
"event_id": "fictional-north-south",
"home_team": "North Owls",
"away_team": "South Foxes",
"bookmaker": "example_book",
"kind": "game",
"market_key": "h2h",
"period_key": null,
"home_ml": -115,
"away_ml": 105,
"last_update": 1806600012000
}
]
}
},
{
"action": "cancel",
"connection": 2
},
{
"action": "frame",
"connection": 2,
"frame": {
"type": "odds_update",
"sport_key": "basketball_nba",
"data": [
{
"sport_key": "basketball_nba",
"event_id": "fictional-north-south",
"home_team": "North Owls",
"away_team": "South Foxes",
"bookmaker": "example_book",
"kind": "game",
"market_key": "h2h",
"period_key": null,
"home_ml": -115,
"away_ml": 105,
"last_update": 1806600000000
}
]
}
}
]
Loading
Loading