Skip to main content

Overview

The Depth component displays market depth information through two tabs: an order book view and a recent trades view. It maintains real-time data via WebSocket subscriptions and manages order book state through React context.

Props

market
string
required
The market identifier for the trading pair (e.g., “SOL_USDC”)

Component State

activeTab
string
default:"orderbook"
Controls which tab is displayed:
  • "orderbook": Shows the OrderBook component
  • "recentTrades": Shows the RecentTrades component

WebSocket Integration

Depth Updates

Subscribes to depth.{market} stream for order book updates:
The component processes incremental depth updates:
  1. Update existing orders: Matches by price level and updates quantity
  2. Remove zero quantities: Filters out orders with quantity = 0
  3. Add new orders: Inserts new price levels not in current book
  4. Sort and trim: Maintains top 30 bids (descending) and asks (ascending)
WsManager.getInstance().registerCallback(
  "depth",
  (data: any) => {
    // Updates bids and asks state
    setBids((originalBids) => {
      // Update logic...
    });
    setAsks((originalAsks) => {
      // Update logic...
    });
  },
  `DEPTH-${market}`
);

Trade Updates

Subscribes to trade.{market} stream for recent trades:
Processes incoming trade data:
WsManager.getInstance().registerCallback(
  "trade",
  (data: any) => {
    const newTrade: Trade = {
      id: data.t,
      isBuyerMaker: data.m,
      price: data.p,
      quantity: data.q,
      quoteQuantity: data.q,
      timestamp: data.T,
    };
    
    setPrice(data.p);  // Update current price
    
    setTrades((oldTrades) => {
      const newTrades = [...oldTrades];
      newTrades.unshift(newTrade);  // Add to front
      newTrades.pop();              // Remove last
      return newTrades;
    });
  },
  `TRADE-${market}`
);

Context Dependencies

The component uses TradesContext to manage shared state:
setTrades
function
Updates the trades array with new trade data
setBids
function
Updates the bids array (buy orders)
setAsks
function
Updates the asks array (sell orders)
setPrice
function
Updates the current market price
setTotalBidSize
function
Sets total quantity of all bids
setTotalAskSize
function
Sets total quantity of all asks
orderBookRef
React.RefObject
Reference to order book container for scroll control

Initial Data Loading

REST API Initialization

The component fetches initial data on mount:
getTrades(market).then((trades) => {
  trades = trades.filter((trade) => parseFloat(trade.quantity) !== 0);
  trades = trades.slice(0, 50);  // Keep last 50 trades
  setTrades(trades);
  setPrice(trades?.[0]?.price);  // Set current price
});

Cleanup & Unsubscription

The component properly cleans up WebSocket subscriptions:
return () => {
  WsManager.getInstance().deRegisterCallback("depth", `DEPTH-${market}`);
  WsManager.getInstance().sendMessage({
    method: "UNSUBSCRIBE",
    params: [`depth.${market}`],
  });
  
  WsManager.getInstance().deRegisterCallback("trade", `TRADE-${market}`);
  WsManager.getInstance().sendMessage({
    method: "UNSUBSCRIBE",
    params: [`trade.${market}`],
  });
};

Child Components

OrderBook

Displays bid/ask ladder with:
  • Price levels
  • Quantities at each level
  • Cumulative depth visualization
  • Re-center button
See: apps/web/src/components/depth/OrderBook.tsx

RecentTrades

Shows trade history with:
  • Trade price (color-coded by side)
  • Trade size
  • Timestamp
See: apps/web/src/components/depth/RecentTrades.tsx

Usage Example

import { Depth } from '@/components/Depth';
import { TradesProvider } from '@/state/TradesProvider';

function MarketPage() {
  return (
    <TradesProvider>
      <Depth market="SOL_USDC" />
    </TradesProvider>
  );
}
The component must be wrapped in a TradesProvider to access the required context.

Order Book Data Format

Bids and asks are arrays of tuples:
type OrderBookLevel = [string, string]; // [price, quantity]

// Example:
const bids: OrderBookLevel[] = [
  ["100.50", "5.234"],  // $100.50 for 5.234 SOL
  ["100.45", "2.156"],
  // ...
];

Trade Data Format

interface Trade {
  id: string;              // Trade ID
  isBuyerMaker: boolean;   // true = sell, false = buy
  price: string;           // Trade price
  quantity: string;        // Trade quantity
  quoteQuantity: string;   // Quote asset quantity
  timestamp: number;       // Unix timestamp
}

Source Code Reference

See implementation in: apps/web/src/components/Depth.tsx:1-258

Build docs developers (and LLMs) love