> ## Documentation Index
> Fetch the complete documentation index at: https://pond.dflow.net/llms.txt
> Use this file to discover all available pages before exploring further.

# Websockets Overview

> Stream real-time price, trade, and orderbook updates via WebSocket

The WebSocket API provides real-time streaming of market data, including price updates, trade executions, and orderbook depth. Connect once and receive continuous updates for the markets you're interested in.

<Info>
  The WebSocket API is ideal for building real-time trading interfaces, price
  tickers, and trade feeds. For historical data or one-time queries, use the
  [REST API endpoints](/resources/metadata-api/introduction).
</Info>

<Info>
  Looking for Trading API WebSocket streams? See the
  [Trading API Websockets overview](/resources/trading-api/websockets/overview).
</Info>

## Connection

The dev WebSocket URL is:

```
wss://dev-prediction-markets-api.dflow.net/api/v1/ws
```

This endpoint does not require an API key. For production, use the `wss:` protocol with your Prediction Markets API host and the `/api/v1/ws` path:

```
wss://<your-prediction-markets-api-host>/api/v1/ws
```

## Channels

The WebSocket API supports three channels:

| Channel     | Description                                   |
| ----------- | --------------------------------------------- |
| `prices`    | Real-time bid/ask price updates for markets   |
| `trades`    | Real-time trade execution updates             |
| `orderbook` | Real-time orderbook depth updates for markets |

<CardGroup cols={3}>
  <Card title="Prices Channel" href="prices" icon="chart-line">
    Subscribe to real-time bid/ask price updates for prediction markets
  </Card>

  <Card title="Trades Channel" href="trades" icon="receipt">
    Subscribe to real-time trade execution updates
  </Card>

  <Card title="Orderbook Channel" href="orderbook" icon="list">
    Subscribe to real-time orderbook depth updates
  </Card>
</CardGroup>

## Subscription Management

After connecting, send JSON messages to subscribe or unsubscribe from channels. Each channel maintains independent subscription state.

### Subscribe to All Markets

Subscribe to receive updates for all markets on a channel:

```json theme={null}
{
  "type": "subscribe",
  "channel": "prices",
  "all": true
}
```

### Subscribe to Specific Tickers

Subscribe to receive updates for specific market tickers:

```json theme={null}
{
  "type": "subscribe",
  "channel": "prices",
  "tickers": ["BTCD-25DEC0313-T92749.99", "SPX-25DEC0313-T5000"]
}
```

### Unsubscribe from All Markets

Unsubscribe from all markets on a channel:

```json theme={null}
{
  "type": "unsubscribe",
  "channel": "prices",
  "all": true
}
```

### Unsubscribe from Specific Tickers

Unsubscribe from specific market tickers:

```json theme={null}
{
  "type": "unsubscribe",
  "channel": "prices",
  "tickers": ["BTCD-25DEC0313-T92749.99"]
}
```

<Warning>
  Unsubscribing from specific tickers has no effect if you are subscribed to
  "all" for that channel. You must first unsubscribe from "all" before managing
  individual ticker subscriptions.
</Warning>

### Subscription Behavior

* Subscribing to `"all": true` clears any specific ticker subscriptions for that channel.
* Subscribing to specific tickers disables "all" mode for that channel.
* Each channel (`prices`, `trades`, and `orderbook`) maintains independent subscription state.
* You can be subscribed to all prices while only subscribing to specific tickers for trades or orderbooks, or any combination.
* In `"all"` mode, you receive all channel updates, including updates from markets created after the subscription is established.

## Quick Start Example

```typescript theme={null}
// Dev endpoint — no API key required, but rate-limited.
// For production, use your production WS URL and add:
//   { headers: { "x-api-key": "YOUR_API_KEY" } }
// as the second argument to new WebSocket().
const WS_URL = "wss://dev-prediction-markets-api.dflow.net/api/v1/ws";

const ws = new WebSocket(WS_URL);

ws.onopen = () => {
  console.log("Connected to WebSocket");

  // Subscribe to all price updates
  ws.send(
    JSON.stringify({
      type: "subscribe",
      channel: "prices",
      all: true,
    })
  );

  // Subscribe to all trade updates
  ws.send(
    JSON.stringify({
      type: "subscribe",
      channel: "trades",
      all: true,
    })
  );

  // Subscribe to all orderbook updates
  ws.send(
    JSON.stringify({
      type: "subscribe",
      channel: "orderbook",
      all: true,
    })
  );
};

ws.onmessage = (event) => {
  const message = JSON.parse(event.data);

  switch (message.channel) {
    case "prices":
      console.log("Price update:", message);
      break;
    case "trades":
      console.log("Trade update:", message);
      break;
    case "orderbook":
      console.log("Orderbook update:", message);
      break;
  }
};

ws.onerror = (error) => {
  console.error("WebSocket error:", error);
};

ws.onclose = () => {
  console.log("WebSocket connection closed");
};
```

## Best Practices

<CardGroup cols={2}>
  <Card title="Connection Management" icon="plug">
    Implement reconnection logic with exponential backoff to handle
    disconnections gracefully.
  </Card>

  <Card title="Subscription Scope" icon="filter">
    Subscribe only to the markets you need. Use specific tickers rather than
    "all" when possible to reduce bandwidth.
  </Card>

  <Card title="Message Handling" icon="message">
    Process messages asynchronously to avoid blocking the WebSocket connection
    during high-volume periods.
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation">
    Always implement `onerror` and `onclose` handlers to detect and respond to
    connection issues.
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Discover Markets" href="/prediction-markets/recipes/find-markets" icon="search">
    Find market tickers to subscribe to using the REST API
  </Card>

  <Card title="Trade Tokens" href="/prediction-markets/recipes/buy-outcome-tokens" icon="arrow-right-arrow-left">
    Execute trades on markets you're monitoring
  </Card>
</CardGroup>
