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

# Market Channel

> Receiving updates about specific markets

## Overview

The `market` channel allows you to receive real-time updates about one or more specific markets. You can choose to receive orderbook updates, trades, or both.

## Authentication

The `market` channel **does not require authentication**. You can subscribe without providing an API key.

## Subscribe

To subscribe to the market channel:

```json theme={null}
{
  "type": "subscribe",
  "channel": "market",
  "markets": ["market-id-1", "market-id-2"],
  "filter": "orderbook"
}
```

### Requirements

* **`markets`** (required): Array of market IDs
* **`filter`** (optional): Desired update type
  * `""` or `"all"`: All updates (default)
  * `"orderbook"`: Only orderbook updates
  * `"trades"`: Only trade updates

### Examples

#### Receive All Updates

```json theme={null}
{
  "type": "subscribe",
  "channel": "market",
  "markets": ["market-id-1"]
}
```

#### Receive Only Orderbook

```json theme={null}
{
  "type": "subscribe",
  "channel": "market",
  "markets": ["market-id-1", "market-id-2"],
  "filter": "orderbook"
}
```

#### Receive Only Trades

```json theme={null}
{
  "type": "subscribe",
  "channel": "market",
  "markets": ["market-id-1"],
  "filter": "trades"
}
```

## Received Messages

### Orderbook Update

Received when there are changes to a market's orderbook (when `filter` is `"orderbook"` or `"all"`).

**Structure:**

```json theme={null}
{
  "msg_type": "update-orderbook",
  "event_id": "string",
  "market_id": "string",
  "orderbook": {
    "yes_orderbook": {
      "outcome": "YES",
      "bids": [
        {
          "price_ticks": 40,
          "quantity": 100,
          "order_count": 2
        }
      ],
      "asks": [
        {
          "price_ticks": 41,
          "quantity": 150,
          "order_count": 3
        }
      ],
      "spread": 1,
      "last_transaction": 40
    },
    "no_orderbook": {
      "outcome": "NO",
      "bids": [],
      "asks": [],
      "spread": null,
      "last_transaction": null
    },
    "market_price_yes": 40,
    "market_price_no": 60,
    "chance": 40,
    "volume": 10000,
    "liquidity": 5000,
    "spread_yes": 1,
    "spread_no": 2
  }
}
```

### New Trade

Received when a new trade is executed on a market (when `filter` is `"trades"` or `"all"`).

**Structure:**

```json theme={null}
{
  "msg_type": "new-trades",
  "event_id": "string",
  "market_id": "string",
  "last_trades": {
    "canceled": false,
    "order_id": "string",
    "user_id": "string",
    "total_amount": 1000,
    "qty_contracts": 10,
    "avg_price": 40,
    "side": "BUY",
    "contract_type": "YES",
    "makers": [
      {
        "user_id": "string",
        "order_id": "string",
        "qty_contracts": 5,
        "price": 40,
        "total_amount": 500,
        "side": "SELL",
        "contract_type": "YES"
      }
    ]
  }
}
```

### Complete Update

Received when there are general updates to the market (when `filter` is `"all"` or not specified).

**Structure:**

```json theme={null}
{
  "msg_type": "update",
  "event_id": "string",
  "market_id": "string",
  "orderbook": {
    // Same structure as orderbook above
  },
  "last_trades": [
    {
    // Same structure as trade above
  }
  ]
}
```

## Usage Example

<CodeGroup>
  ```javascript JavaScript theme={null}
  const ws = new WebSocket('wss://data-ws-dev.voxfi.com.br');

  ws.onopen = () => {
    // Subscribe to a market with orderbook filter
    ws.send(JSON.stringify({
      type: 'subscribe',
      channel: 'market',
      markets: ['market-id-1'],
      filter: 'orderbook'
    }));
  };

  ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    
    if (data.msg_type === 'update-orderbook') {
      console.log('Orderbook updated for market:', data.market_id);
      console.log('YES price:', data.orderbook.market_price_yes);
      console.log('NO price:', data.orderbook.market_price_no);
    } else if (data.msg_type === 'new-trades') {
      console.log('New trade on market:', data.market_id);
      console.log('Trades:', data.last_trades);
    }
  };
  ```

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

  async def subscribe_market():
      uri = "wss://data-ws-dev.voxfi.com.br"
      
      async with websockets.connect(uri) as websocket:
          # Subscribe to a market
          subscribe_msg = {
              "type": "subscribe",
              "channel": "market",
              "markets": ["market-id-1"],
              "filter": "orderbook"
          }
          await websocket.send(json.dumps(subscribe_msg))
          
          # Receive messages
          async for message in websocket:
              data = json.loads(message)
              
              if data.get("msg_type") == "update-orderbook":
                  print(f"Orderbook updated for market: {data['market_id']}")
                  print(f"YES price: {data['orderbook']['market_price_yes']}")
                  print(f"NO price: {data['orderbook']['market_price_no']}")
              elif data.get("msg_type") == "new-trades":
                  print(f"New trade on market: {data['market_id']}")
                  print(f"Trade: {data['last_trades']}")

  asyncio.run(subscribe_market())
  ```
</CodeGroup>

## Unsubscribe

To unsubscribe from specific markets:

```json theme={null}
{
  "type": "unsubscribe",
  "channel": "market",
  "markets": ["market-id-1", "market-id-2"]
}
```

## Orderbook Fields

See the [complete orderbook documentation](/en/api/orderbook) for details about the returned fields.

### Main Fields

* **`market_price_yes`**: Current market price for YES in ticks (0-100);
* **`market_price_no`**: Current market price for NO in ticks (0-100);
* **`chance`**: YES probability in percentage (0-100);
* **`volume`**: Total contracts created (historical trades);
* **`liquidity`**: Total contracts available in the orderbook;
* **`spread_yes`**: Spread for YES in ticks;
* **`spread_no`**: Spread for NO in ticks.

## Use Cases

* **Price Monitoring**: Use with `orderbook` filter to receive real-time price updates;
* **Liquidity Analysis**: Monitor orderbook depth to assess liquidity;
* **Trade Tracking**: Use with `trades` filter to monitor trading activity;
* **Price Alerts**: Set up alerts when prices reach certain levels;
* **Market Making**: Use orderbook updates to adjust your limit orders.

## Best Practices

* **Use Filters**: If you only need orderbook or trades, use the appropriate filter to reduce traffic;
* **Multiple Markets**: You can subscribe to multiple markets on the same connection;
* **State Management**: Keep local orderbook state and update as messages arrive;
* **Market Identification**: Always check the `market_id` in messages to ensure you're processing the correct market.
