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

# Market data

> Real-time activity feeds, price updates, and order book snapshots

## Overview

The `/ws/v1/markets` endpoint streams real-time market data. No authentication is required.

```
wss://socket.bayse.markets/ws/v1/markets
```

Four subscription types are available:

| Subscription  | Channel       | Server event type         | Description                                            |
| ------------- | ------------- | ------------------------- | ------------------------------------------------------ |
| Activity feed | `activity`    | `buy_order`, `sell_order` | Buy and sell order activity for an event.              |
| Price updates | `prices`      | `price_update`            | Market price changes for an event.                     |
| Orderbook     | `orderbook`   | `orderbook_update`        | Order book snapshots for a market.                     |
| User trades   | `user_trades` | `buy_order`, `sell_order` | Trade activity for a specific user across all markets. |

## Activity feed

Subscribe to trade activity for a prediction event. Optionally filter by a specific market.

### Subscribe

```json theme={null}
{
  "type": "subscribe",
  "channel": "activity",
  "eventId": "EVENT_ID"
}
```

To filter activity to a specific market within the event:

```json theme={null}
{
  "type": "subscribe",
  "channel": "activity",
  "eventId": "EVENT_ID",
  "marketId": "MARKET_ID"
}
```

Room names: `activity:<eventId>` or `activity:<eventId>:<marketId>`

### Events received

**`buy_order`** — A buy order was filled.

```json theme={null}
{
  "type": "buy_order",
  "data": {
    "user": {
      "id": "usr_8b5c3c3a",
      "tag": "prediction_pro",
      "imageUrl": "https://cdn.bayse.markets/users/8b5c3c3a.png"
    },
    "order": {
      "id": "ord_7f5e2a1c",
      "amount": 100.00,
      "quantity": 150.0,
      "price": 0.65,
      "status": "FILLED",
      "type": "BUY",
      "outcome": "YES",
      "outcomeLabel": "Yes",
      "currency": "USD",
      "createdAt": "2026-02-17T10:30:00Z",
      "updatedAt": "2026-02-17T10:30:01Z"
    },
    "event": {
      "id": "evt_123",
      "slug": "us-fed-rate-cut-2026",
      "title": "Will the Fed cut rates in 2026?",
      "type": "SINGLE_MARKET",
      "createdAt": "2026-01-10T09:00:00Z",
      "imageUrl": "https://cdn.bayse.markets/events/fed.png"
    },
    "market": {
      "id": "mkt_456",
      "title": "Yes or No",
      "imageUrl": null
    }
  },
  "timestamp": 1700000000000
}
```

**`sell_order`** — A sell order was filled.

```json theme={null}
{
  "type": "sell_order",
  "data": {
    "user": { "id": "usr_9a1d2f4b", "tag": null, "imageUrl": null },
    "order": {
      "id": "ord_aa12bb34",
      "amount": 50.00,
      "quantity": 80.0,
      "price": 0.70,
      "status": "FILLED",
      "type": "SELL",
      "outcome": "YES",
      "outcomeLabel": "Yes",
      "currency": "USD",
      "createdAt": "2026-02-17T10:35:00Z",
      "updatedAt": "2026-02-17T10:35:01Z"
    },
    "event": { "id": "evt_123", "slug": "us-fed-rate-cut-2026", "title": "Will the Fed cut rates in 2026?", "type": "SINGLE_MARKET", "createdAt": "2026-01-10T09:00:00Z", "imageUrl": "https://cdn.bayse.markets/events/fed.png" },
    "market": { "id": "mkt_456", "title": "Yes or No", "imageUrl": null }
  },
  "timestamp": 1700000000000
}
```

<Note>
  `quantity` is floored. `createdAt` and `updatedAt` are ISO 8601 strings.
</Note>

### Unsubscribe

```json theme={null}
{ "type": "unsubscribe", "room": "activity:EVENT_ID" }
```

For a market-specific subscription:

```json theme={null}
{ "type": "unsubscribe", "room": "activity:EVENT_ID:MARKET_ID" }
```

## Price updates

Subscribe to price changes for all markets in a prediction event.

### Subscribe

```json theme={null}
{
  "type": "subscribe",
  "channel": "prices",
  "eventId": "EVENT_ID"
}
```

Room name: `prices:<eventId>`

### Events received

**`price_update`** — A market price changed.

The `data` field contains the full event snapshot. Example (trimmed):

```json theme={null}
{
  "type": "price_update",
  "data": {
    "id": "evt_123",
    "slug": "us-fed-rate-cut-2026",
    "title": "Will the Fed cut rates in 2026?",
    "status": "open",
    "type": "SINGLE_MARKET",
    "markets": [
      {
        "id": "mkt_456",
        "question": "Yes or No?",
        "outcomes": ["Yes", "No"],
        "engine": "CLOB",
        "prices": { "YES": 0.65, "NO": 0.35 }
      }
    ]
  },
  "timestamp": 1700000000000
}
```

### Unsubscribe

```json theme={null}
{ "type": "unsubscribe", "room": "prices:EVENT_ID" }
```

## Orderbook updates

Subscribe to order book snapshots for specific markets. Snapshots reflect the current state of bids and asks.

### Subscribe

```json theme={null}
{
  "type": "subscribe",
  "channel": "orderbook",
  "marketIds": ["MARKET_ID"]
}
```

To receive orderbook data in a specific currency:

```json theme={null}
{
  "type": "subscribe",
  "channel": "orderbook",
  "marketIds": ["MARKET_ID"],
  "currency": "NGN"
}
```

<Note>
  `marketIds` supports up to 10 markets per subscription. The `currency` field accepts `USD` or `NGN`.
</Note>

Room names: `orderbook:<marketId>` or `orderbook:<marketId>:<currency>`

### Events received

**`orderbook_update`** — The order book snapshot was updated.

```json theme={null}
{
  "type": "orderbook_update",
  "data": {
    "orderbook": {
      "marketId": "mkt_456",
      "outcomeId": "out_789",
      "timestamp": "2026-02-17T10:40:00Z",
      "bids": [
        { "price": 0.60, "quantity": 500, "total": 300.0 },
        { "price": 0.55, "quantity": 300, "total": 165.0 }
      ],
      "asks": [
        { "price": 0.65, "quantity": 200, "total": 130.0 },
        { "price": 0.70, "quantity": 400, "total": 280.0 }
      ],
      "lastTradedPrice": 0.65,
      "lastTradedSide": "BUY"
    }
  },
  "timestamp": 1700000000000
}
```

### Unsubscribe

For USD (default):

```json theme={null}
{ "type": "unsubscribe", "room": "orderbook:MARKET_ID" }
```

For NGN:

```json theme={null}
{ "type": "unsubscribe", "room": "orderbook:MARKET_ID:NGN" }
```

## User trades

Subscribe to a specific user's trade activity across all markets. Receives `buy_order` and `sell_order` events whenever the user's orders are filled, regardless of the market engine (CLOB or AMM).

To get a user's ID from their tag, use the [Lookup user](/api-reference/user/lookup) endpoint.

### Subscribe

```json theme={null}
{
  "type": "subscribe",
  "channel": "user_trades",
  "userId": "USER_ID"
}
```

Room name: `user_trades:<userId>`

### Events received

**`buy_order`** / **`sell_order`** — The user's order was filled.

```json theme={null}
{
  "type": "buy_order",
  "data": {
    "payload": {
      "user": {
        "id": "68eea9d8-a0fe-4534-ae88-b71e2f4f5c8f",
        "tag": "mulumba",
        "imageUrl": "https://cdn.bayse.markets/profile-images/mulumba.png"
      },
      "order": {
        "id": "7f5e2a1c-3b4d-4e6f-8a9b-1c2d3e4f5a6b",
        "amount": 100.00,
        "quantity": 150,
        "price": 0.65,
        "status": "FILLED",
        "type": "BUY",
        "outcome": "YES",
        "outcomeLabel": "Yes",
        "currency": "USD",
        "engine": "CLOB",
        "orderType": "MARKET",
        "createdAt": "2026-02-17T10:30:00Z",
        "updatedAt": "2026-02-17T10:30:01Z"
      },
      "event": {
        "id": "a1b2c3d4-5e6f-7a8b-9c0d-1e2f3a4b5c6d",
        "slug": "arsenal-trophyless-2026",
        "title": "Will Arsenal Go Trophyless This Season?",
        "type": "SINGLE_MARKET",
        "createdAt": "2026-01-10T09:00:00Z",
        "imageUrl": "https://cdn.bayse.markets/events/arsenal.png"
      },
      "market": {
        "id": "b2c3d4e5-6f7a-8b9c-0d1e-2f3a4b5c6d7e",
        "title": "Yes or No",
        "imageUrl": null
      }
    }
  },
  "timestamp": 1700000000000
}
```

### Unsubscribe

```json theme={null}
{ "type": "unsubscribe", "channel": "user_trades", "userId": "USER_ID" }
```

## Full example

<CodeGroup>
  ```javascript JavaScript theme={null}
  const ws = new WebSocket("wss://socket.bayse.markets/ws/v1/markets");

  ws.addEventListener("open", () => {
    // Subscribe to multiple channels
    ws.send(JSON.stringify({
      type: "subscribe",
      channel: "activity",
      eventId: "EVENT_ID"
    }));

    ws.send(JSON.stringify({
      type: "subscribe",
      channel: "prices",
      eventId: "EVENT_ID"
    }));

    ws.send(JSON.stringify({
      type: "subscribe",
      channel: "orderbook",
      marketIds: ["MARKET_ID"],
      currency: "USD"
    }));
  });

  ws.addEventListener("message", (event) => {
    for (const line of event.data.split("\n")) {
      if (!line.trim()) continue;
      const msg = JSON.parse(line);

      switch (msg.type) {
        case "buy_order":
        case "sell_order":
          console.log("Trade:", msg.data);
          break;
        case "price_update":
          console.log("Price:", msg.data);
          break;
        case "orderbook_update":
          console.log("Orderbook:", msg.data);
          break;
      }
    }
  });
  ```

  ```python Python theme={null}
  import asyncio
  import json
  import websockets

  async def stream_market_data(event_id, market_id):
      async with websockets.connect("wss://socket.bayse.markets/ws/v1/markets") as ws:
          # Subscribe to multiple channels
          await ws.send(json.dumps({
              "type": "subscribe",
              "channel": "activity",
              "eventId": event_id,
          }))
          await ws.send(json.dumps({
              "type": "subscribe",
              "channel": "prices",
              "eventId": event_id,
          }))
          await ws.send(json.dumps({
              "type": "subscribe",
              "channel": "orderbook",
              "marketIds": [market_id],
              "currency": "USD",
          }))

          async for message in ws:
              for line in message.split("\n"):
                  if not line.strip():
                      continue
                  msg = json.loads(line)

                  if msg["type"] in ("buy_order", "sell_order"):
                      print("Trade:", msg["data"])
                  elif msg["type"] == "price_update":
                      print("Price:", msg["data"])
                  elif msg["type"] == "orderbook_update":
                      print("Orderbook:", msg["data"])

  asyncio.run(stream_market_data("EVENT_ID", "MARKET_ID"))
  ```

  ```go Go theme={null}
  package main

  import (
  	"encoding/json"
  	"fmt"
  	"log"
  	"strings"

  	"github.com/gorilla/websocket"
  )

  func main() {
  	conn, _, err := websocket.DefaultDialer.Dial(
  		"wss://socket.bayse.markets/ws/v1/markets", nil,
  	)
  	if err != nil {
  		log.Fatal(err)
  	}
  	defer conn.Close()

  	eventID := "EVENT_ID"
  	marketID := "MARKET_ID"

  	conn.WriteJSON(map[string]any{
  		"type":    "subscribe",
  		"channel": "activity",
  		"eventId": eventID,
  	})
  	conn.WriteJSON(map[string]any{
  		"type":    "subscribe",
  		"channel": "prices",
  		"eventId": eventID,
  	})
  	conn.WriteJSON(map[string]any{
  		"type":      "subscribe",
  		"channel":   "orderbook",
  		"marketIds": []string{marketID},
  		"currency":  "USD",
  	})

  	for {
  		_, data, err := conn.ReadMessage()
  		if err != nil {
  			log.Fatal(err)
  		}
  		for _, line := range strings.Split(string(data), "\n") {
  			if strings.TrimSpace(line) == "" {
  				continue
  			}
  			var msg map[string]any
  			json.Unmarshal([]byte(line), &msg)
  			fmt.Printf("%s: %v\n", msg["type"], msg["data"])
  		}
  	}
  }
  ```
</CodeGroup>
