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

# useOrderbook

> Real-time orderbook data via WebSocket

```tsx theme={null}
import { useOrderbook } from "@0xmonaco/react";

const { 
  orderbook,
  subscribed,
  error,
  clearError
} = useOrderbook(tradingPairId, tradingMode, magnitude, quotationMode, depth?);
```

## Parameters

<ParamField path="tradingPairId" type="string" required>
  Trading pair UUID. Get this from `sdk.market.getTradingPairBySymbol('BTC/USDC')`.
</ParamField>

<ParamField path="tradingMode" type="'SPOT' | 'MARGIN'" required>
  Trading mode for the orderbook subscription. Use `'SPOT'` for spot markets and `'MARGIN'` for perp markets.
</ParamField>

<ParamField path="magnitude" type="number" required>
  Price level grouping magnitude. Valid values: `0.0001`, `0.001`, `0.01`, `0.1`, `1`, `10`, `100`, `1000`, `10000`
</ParamField>

<ParamField path="quotationMode" type="'BASE' | 'QUOTE'" required>
  Quantity denomination. `BASE` shows quantities in base token, `QUOTE` multiplies by price.
</ParamField>

<ParamField path="depth" type="number" default="10">
  Number of price levels to fetch (max: 100)
</ParamField>

## Return Values

<ResponseField name="orderbook" type="OrderbookEvent | null">
  Current orderbook snapshot with bids, asks, best prices, and volumes

  **Properties:**

  * `tradingPairId`: Trading pair ID (UUID)
  * `tradingMode`: "SPOT" | "MARGIN"
  * `bids`: Array of `{ price, quantity, orderCount }`
  * `asks`: Array of `{ price, quantity, orderCount }`
  * `bestBid` (optional): Best bid price
  * `bestAsk` (optional): Best ask price
  * `bidVolume` (optional): Total bid volume
  * `askVolume` (optional): Total ask volume
  * `priceChange`: Price change info (optional) - `{ side, oldPrice?, newPrice?, levelRemoved, levelAdded }`
  * `baseDecimals`: Base token decimals
  * `quoteDecimals`: Quote token decimals
  * `timestamp`: Snapshot timestamp
  * `sequence`: Sequence number for ordering
</ResponseField>

<ResponseField name="subscribed" type="boolean">
  Whether currently subscribed to real-time updates
</ResponseField>

<ResponseField name="error" type="Error | null">
  Connection or subscription error if any
</ResponseField>

<ResponseField name="clearError" type="() => void">
  Clear the current error
</ResponseField>

## Example

```tsx theme={null}
import { useOrderbook, useMarket } from "@0xmonaco/react";
import { useEffect, useState } from "react";

function OrderbookDisplay() {
  const { getTradingPairBySymbol } = useMarket();
  const [tradingPairId, setTradingPairId] = useState<string | null>(null);
  
  useEffect(() => {
    getTradingPairBySymbol('BTC/USDC').then(pair => {
      setTradingPairId(pair.id);
    });
  }, []);
  
  const { orderbook, subscribed, error } = useOrderbook(
    tradingPairId ?? '',
    'SPOT',
    1,        // Group by $1 price levels
    'BASE',   // Show quantities in base token
    20        // 20 levels each side
  );
  
  if (!tradingPairId) return <div>Loading pair...</div>;
  if (error) return <div>Error: {error.message}</div>;
  if (!orderbook) return <div>Loading orderbook...</div>;
  
  return (
    <div>
      <h2>Orderbook {subscribed ? '(live)' : '(connecting...)'}</h2>
      <p>Spread: ${(Number(orderbook.bestAsk) - Number(orderbook.bestBid)).toFixed(2)}</p>
      
      <div style={{ display: 'flex', gap: '2rem' }}>
        <div>
          <h3>Bids</h3>
          {orderbook.bids.slice(0, 10).map((level, i) => (
            <div key={i} style={{ color: 'green' }}>
              {level.quantity} @ ${level.price}
            </div>
          ))}
        </div>
        
        <div>
          <h3>Asks</h3>
          {orderbook.asks.slice(0, 10).map((level, i) => (
            <div key={i} style={{ color: 'red' }}>
              {level.quantity} @ ${level.price}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
```

## How It Works

1. **Initial Load**: Fetches orderbook snapshot via REST API
2. **Real-time Updates**: Subscribes to WebSocket for live updates
3. **Auto-cleanup**: Unsubscribes when component unmounts or params change

The hook combines REST and WebSocket for the best experience - instant data on load, real-time updates after.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.