WebSockets

Examples

Minimal clients that connect, subscribe to one market, print each trade, and reconnect on 4001. For a client that handles all of this for you, use the SDK streaming client.

Node.js (ws)

JavaScript
import WebSocket from 'ws';

function connect() {
  const ws = new WebSocket('wss://ripple.heisenberg.so/ws', {
    headers: { Authorization: 'Bearer ' + process.env.HEISENBERG_TOKEN },
  });

  ws.on('open', () => {
    ws.send(JSON.stringify({
      action: 'subscribe',
      subscriptions: [
        { type: 'polymarket.trade', filters: { slug: 'btc-updown-5m-1779889800' } },
      ],
    }));
  });

  ws.on('message', (raw) => {
    const msg = JSON.parse(raw.toString());
    if (msg.action === 'subscribed') {
      console.log('subscribed:', msg.subscriptions.map((s) => s.id));
    } else if (msg.action === 'error' || msg.action === 'rate_limit') {
      console.warn(msg.action + ':', msg.message);
    } else if (msg.type === 'polymarket.trade') {
      const t = msg.data;
      console.log(t.side, t.size, '@', t.price, '·', t.slug);
    }
  });

  // The ws library answers server pings automatically.
  ws.on('close', (code) => {
    if (code === 4001) setTimeout(connect, 1000); // upstream interrupted — reconnect + re-subscribe
  });
}

connect();

Python (websockets)

Python
import asyncio, json, os
import websockets

async def main():
    url = "wss://ripple.heisenberg.so/ws"
    headers = {"Authorization": f"Bearer {os.environ['HEISENBERG_TOKEN']}"}
    async with websockets.connect(url, additional_headers=headers) as ws:
        await ws.send(json.dumps({
            "action": "subscribe",
            "subscriptions": [
                {"type": "polymarket.trade", "filters": {"slug": "btc-updown-5m-1779889800"}},
            ],
        }))
        async for raw in ws:
            msg = json.loads(raw)
            if "action" in msg:               # subscribed / error / rate_limit
                print(msg)
            elif msg.get("type") == "polymarket.trade":
                t = msg["data"]
                print(t["side"], t["size"], "@", t["price"], "·", t["slug"])

asyncio.run(main())

Need more streams?

More event types are on the way. To request early access or a dedicated event type, reach us at contact@heisenberg.so.