Stream Pinnacle odds over WebSocket in Python and Node
This guide builds a client that keeps a live copy of Pinnacle's prices in memory: it connects, subscribes, loads the snapshot, applies every delta, answers heartbeats and reconnects on its own. The other guides (steam alerts, value betting, the Telegram bot) all build on it.
You need a PinnFeed key on the Builder plan (the WebSocket plan, €99/month, 3 days free). Free and Hobby keys can follow along with the REST examples in the docs.
Step 1 — Get a key and set it#
Create a key in the dashboard and export it, so it never ends up in your code:
export PINNFEED_KEY="pf_live_..."
Step 2 — Understand the frames#
After you connect and send subscribe, the server sends:
subscribed, then a snapshot in parts (part,parts,final) with every event and market that matches your filters;- delta frames, each with a list of
changes:upsertcarries the full new object,removecarries only its id; - a ping every 20 seconds. Reply with
{"type":"pong"}or the server closes the socket after 60 seconds of silence.
Markets are keyed by id (eventId:key), so a dictionary is all the state you need. Each outcome carries decimal, american, fair (no-vig price) and fairProb. The WebSocket reference lists every field.
Step 3 — The Python client#
Install the one dependency with pip install websockets (Python 3.9+). Save this as pinnfeed_stream.py; the steam and Telegram guides import it.
# pinnfeed_stream.py: keep a live copy of the Pinnacle book from the PinnFeed WebSocket.
# pip install websockets (Python 3.9+)
import asyncio, json, os, random
import websockets
WS_URL = os.environ.get("PINNFEED_WS", "wss://pinnfeed.io/v1/stream")
KEY = os.environ["PINNFEED_KEY"]
SIDES = {"home", "away", "draw", "over", "under"}
class Book:
"""Events and markets by id, updated from snapshot + delta frames."""
def __init__(self):
self.events, self.markets = {}, {}
def apply(self, msg, on_market=None):
if msg["type"] == "snapshot":
for e in msg["events"]:
self.events[e["id"]] = e
for m in msg["markets"]:
self.markets[m["id"]] = m
elif msg["type"] == "delta":
for c in msg["changes"]:
if c["kind"] == "event" and c["op"] == "upsert":
self.events[c["event"]["id"]] = c["event"]
elif c["kind"] == "event" and c["op"] == "remove":
self.events.pop(c["id"], None)
for mid in [k for k, m in self.markets.items() if m["eventId"] == c["id"]]:
del self.markets[mid]
elif c["kind"] == "market" and c["op"] == "upsert":
old = self.markets.get(c["market"]["id"])
self.markets[c["market"]["id"]] = c["market"]
if on_market:
on_market(old, c["market"], self.events.get(c["market"]["eventId"]))
elif c["kind"] == "market" and c["op"] == "remove":
self.markets.pop(c["id"], None)
async def stream(subscription, on_market=None, on_ready=None):
"""Connect, subscribe, keep the book current; reconnect with backoff forever."""
delay = 1
while True:
book = Book()
try:
async with websockets.connect(WS_URL, additional_headers={"x-api-key": KEY}, max_size=None) as ws:
await ws.send(json.dumps({"type": "subscribe", **subscription}))
async for raw in ws:
msg = json.loads(raw)
if msg["type"] == "ping":
await ws.send('{"type":"pong"}')
elif msg["type"] == "error":
print("server error:", msg["code"], msg["message"])
elif msg["type"] in ("snapshot", "delta"):
book.apply(msg, on_market if msg["type"] == "delta" else None)
if msg["type"] == "snapshot" and msg.get("final") and on_ready:
on_ready(book)
delay = 1
except (OSError, websockets.ConnectionClosed) as e:
print(f"disconnected ({e}); reconnecting in {delay}s")
await asyncio.sleep(delay + random.random())
delay = min(delay * 2, 30)
if __name__ == "__main__":
def ready(book):
print(f"book ready: {len(book.events)} events, {len(book.markets)} markets")
def moved(old, new, event):
if old and event:
for o_old, o_new in zip(old["outcomes"], new["outcomes"]):
if o_new["name"] in SIDES and o_old["decimal"] != o_new["decimal"]:
print(f'{event["home"]} v {event["away"]} {new["type"]} {o_new["name"]}: '
f'{o_old["decimal"]} -> {o_new["decimal"]} (fair {o_new["fair"]})')
asyncio.run(stream({"sports": ["soccer"], "markets": ["moneyline"], "main": True, "specials": False}, moved, ready))
Run it with python pinnfeed_stream.py. You should see book ready: N events, M markets, then one line per price move.
Step 4 — The Node client#
Same logic in Node 18+ with npm install ws. Save as stream.mjs and run node stream.mjs.
// stream.mjs: live Pinnacle book from the PinnFeed WebSocket (Node 18+).
// npm install ws
import WebSocket from 'ws';
const WS_URL = process.env.PINNFEED_WS || 'wss://pinnfeed.io/v1/stream';
const KEY = process.env.PINNFEED_KEY;
const SIDES = new Set(['home', 'away', 'draw', 'over', 'under']);
const events = new Map();
const markets = new Map();
function connect(delay = 1000) {
const ws = new WebSocket(WS_URL, { headers: { 'x-api-key': KEY }, perMessageDeflate: true });
ws.on('open', () => {
delay = 1000;
ws.send(JSON.stringify({ type: 'subscribe', sports: ['soccer', 'tennis'], markets: ['moneyline'], main: true, specials: false }));
});
ws.on('message', (raw) => {
const msg = JSON.parse(raw);
if (msg.type === 'ping') return ws.send('{"type":"pong"}');
if (msg.type === 'error') return console.error('server error:', msg.code, msg.message);
if (msg.type === 'snapshot') {
if (msg.part === 1) { events.clear(); markets.clear(); }
msg.events.forEach((e) => events.set(e.id, e));
msg.markets.forEach((m) => markets.set(m.id, m));
if (msg.final) console.log(`book ready: ${events.size} events, ${markets.size} markets`);
}
if (msg.type === 'delta') {
for (const c of msg.changes) {
if (c.kind === 'event') c.op === 'upsert' ? events.set(c.event.id, c.event) : events.delete(c.id);
if (c.kind === 'market' && c.op === 'remove') markets.delete(c.id);
if (c.kind === 'market' && c.op === 'upsert') {
const old = markets.get(c.market.id);
markets.set(c.market.id, c.market);
const ev = events.get(c.market.eventId);
if (!old || !ev) continue;
c.market.outcomes.forEach((o, i) => {
const prev = old.outcomes[i];
if (prev && SIDES.has(o.name) && prev.decimal !== o.decimal) console.log(`${ev.home} v ${ev.away} ${o.name}: ${prev.decimal} -> ${o.decimal} (fair ${o.fair})`);
});
}
}
}
});
ws.on('close', (code) => {
const wait = Math.min(delay * 2, 30000);
console.log(`closed (${code}); reconnecting in ${wait / 1000}s`);
setTimeout(() => connect(wait), wait + Math.random() * 1000);
});
ws.on('error', (e) => console.error('ws error:', e.message));
}
connect();
Step 5 — Narrow the subscription#
Filters run on the server, so you only receive and parse what you asked for:
{ "type": "subscribe", "sports": ["tennis"], "live": true, "markets": ["moneyline", "total"], "main": true }
sports: slugs or ids;leaguesandevents: lists of ids.live:truefor in-play only,falsefor prematch only, omit for both.main: truekeeps only the main moneyline, spread and total of each event.- Sending
subscribeagain replaces the subscription and sends a fresh snapshot.
Production checklist#
- Reconnect with backoff and jitter (both clients do: 1 s, 2 s, 4 s, up to 30 s) and rebuild from the new snapshot.
- Enable compression: Python
websocketsnegotiatespermessage-deflateby default; in Node passperMessageDeflate: true. Snapshots shrink 5–10×. - Read fast. If more than 16 MB queues up for a slow client, the server closes it with code
4008. Do heavy work off the socket loop. - Use
seqfor logging, not gap detection: filters skip batches you did not subscribe to.
Questions people ask#
Which plan do I need for the WebSocket?#
Builder (€99/month) or higher. Free and Hobby keys get 403 plan_lacks_ws on the WebSocket and can use REST instead.
How many connections can I open?#
Builder allows 3 WebSocket connections per account and Pro allows 10.
Why do some outcomes have participant ids instead of home or away?#
Specials and some futures list participants instead of home and away. Subscribe with "specials": false and filter on home, away, draw, over and under if you only want game lines, as the examples do.