> For the complete documentation index, see [llms.txt](https://docs.hypertracker.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hypertracker.io/websocket-streams/connecting-with-a-plain-websocket.md). Agents can also search and read this documentation through its [MCP server](https://docs.hypertracker.io/~gitbook/mcp).

# Connecting with a Plain WebSocket

## Connecting with a plain WebSocket

Plain WebSocket requires no SDK. You handle pings, reconnection, replay, and parsing.

### Protocol rules

1. Send `connect` first.
2. Commands carry `id`; replies return it.
3. Events arrive as `{"push":{"channel":"rooms:fills","pub":{"data":{},"offset":42}}}`.
4. Reply `{}` to every `{}` ping.
5. Split frames on `\n` before parsing.
6. Send the key only at connect time.

### JavaScript

```js
const URL = 'wss://jp-ws.hypertracker.io/connection/websocket';
const ws = new WebSocket(URL, { headers: { Authorization: `Bearer ${API_KEY}` } });
ws.onopen = () => ws.send(JSON.stringify({ id: 1, connect: {} }));
ws.onmessage = ({ data }) => {
  for (const line of String(data).split('\n')) {
    if (!line) continue;
    const msg = JSON.parse(line);
    if (Object.keys(msg).length === 0) { ws.send('{}'); continue; }
    if (msg.id === 1) {
      if (msg.error) throw new Error(JSON.stringify(msg.error));
      ws.send(JSON.stringify({ id: 2, subscribe: { channel: 'rooms:fills' } }));
    } else if (msg.push?.pub) console.log(msg.push.channel, msg.push.pub.offset, msg.push.pub.data);
  }
};
```

Browsers cannot set headers. Use `connect: { data: { token: API_KEY } }`.

### Python

```python
import asyncio, json, os, websockets

async def main():
  async with websockets.connect('wss://jp-ws.hypertracker.io/connection/websocket',
      additional_headers={'Authorization': f'Bearer {os.environ["API_KEY"]}'}) as ws:
    await ws.send(json.dumps({'id': 1, 'connect': {}}))
    async for frame in ws:
      for line in frame.split('\n'):
        if not line: continue
        msg = json.loads(line)
        if msg == {}: await ws.send('{}')
        elif msg.get('id') == 1: await ws.send(json.dumps({'id': 2, 'subscribe': {'channel': 'rooms:fills'}}))
        elif msg.get('push', {}).get('pub'): print(msg['push']['pub']['data'])
asyncio.run(main())
```

### Filters and replay

```jsonc
{ "id": 2, "subscribe": {
  "channel": "rooms:fills",
  "tf": { "op": "", "key": "coin", "cmp": "eq", "val": "HYPE" },
  "recover": true, "epoch": "<epoch>", "offset": 12345
}}
```

For `orders:feed`, use `data: { "filter": { … } }`, not `tf`.

### Production checklist

Answer pings, reconnect automatically, split frames, deduplicate by `id`, and process events promptly. A slow client closes with `3008 slow`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.hypertracker.io/websocket-streams/connecting-with-a-plain-websocket.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
