Skip to main content
Glama

get_orderbook

Fetch real-time order book depth (bids and asks) for trading pairs on supported exchanges like MEXC, Gate.io, Bitget, and Kraken to analyze market liquidity and trading opportunities.

Instructions

Fetch order book depth (bids and asks) for a trading pair on a supported exchange

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
exchangeYesExchange to query. Supported: mexc, gateio, bitget, kraken
symbolYesTrading pair symbol (e.g., BTC/USDT, INDY/USDT)
limitNoNumber of results to return (default: 10, max: 100)

Implementation Reference

  • The main handler function for get_orderbook tool. Validates exchange and symbol, gets the exchange connector, fetches order book data, processes bids/asks with limit, calculates spread, and returns formatted JSON response.
    async ({ exchange, symbol, limit }) => {
      const validExchange = validateExchange(exchange);
      const validSymbol = validateSymbol(symbol);
    
      const connector = await getConnectorSafe(exchange);
      const orderbook = await connector.getOrderBook(validSymbol);
    
      const bids = orderbook.bids.slice(0, limit);
      const asks = orderbook.asks.slice(0, limit);
    
      const spread =
        orderbook.asks.length > 0 && orderbook.bids.length > 0
          ? orderbook.asks[0].price - orderbook.bids[0].price
          : null;
      const spreadPercent =
        spread !== null && orderbook.asks[0].price > 0
          ? (spread / orderbook.asks[0].price) * 100
          : null;
    
      return {
        content: [
          {
            type: 'text' as const,
            text: JSON.stringify(
              {
                symbol: orderbook.symbol,
                bids,
                asks,
                spread,
                spreadPercent,
                bidLevels: bids.length,
                askLevels: asks.length,
                timestamp: orderbook.timestamp,
                exchange: validExchange,
              },
              null,
              2
            ),
          },
        ],
      };
    }
  • Tool registration in MCP server. Registers get_orderbook with name, description, and parameter schema (exchange, symbol, limit).
    server.tool(
      'get_orderbook',
      'Fetch order book depth (bids and asks) for a trading pair on a supported exchange',
      {
        exchange: ExchangeParam,
        symbol: SymbolParam,
        limit: LimitParam(10, 100),
      },
      async ({ exchange, symbol, limit }) => {
        const validExchange = validateExchange(exchange);
        const validSymbol = validateSymbol(symbol);
    
        const connector = await getConnectorSafe(exchange);
        const orderbook = await connector.getOrderBook(validSymbol);
    
        const bids = orderbook.bids.slice(0, limit);
        const asks = orderbook.asks.slice(0, limit);
    
        const spread =
          orderbook.asks.length > 0 && orderbook.bids.length > 0
            ? orderbook.asks[0].price - orderbook.bids[0].price
            : null;
        const spreadPercent =
          spread !== null && orderbook.asks[0].price > 0
            ? (spread / orderbook.asks[0].price) * 100
            : null;
    
        return {
          content: [
            {
              type: 'text' as const,
              text: JSON.stringify(
                {
                  symbol: orderbook.symbol,
                  bids,
                  asks,
                  spread,
                  spreadPercent,
                  bidLevels: bids.length,
                  askLevels: asks.length,
                  timestamp: orderbook.timestamp,
                  exchange: validExchange,
                },
                null,
                2
              ),
            },
          ],
        };
      }
    );
  • Zod schema definitions for get_orderbook parameters. ExchangeParam validates supported exchanges, SymbolParam for trading pairs, and LimitParam creates configurable number schemas with min/max/default.
    export const ExchangeParam = z
      .string()
      .describe('Exchange to query. Supported: mexc, gateio, bitget, kraken');
    
    export const SymbolParam = z.string().describe('Trading pair symbol (e.g., BTC/USDT, INDY/USDT)');
    
    export const OptionalSymbolParam = z
      .string()
      .optional()
      .describe('Optional trading pair to filter by (e.g., BTC/USDT). Returns all if omitted.');
    
    export function LimitParam(defaultValue: number, max: number) {
      return z
        .number()
        .min(1)
        .max(max)
        .default(defaultValue)
        .describe(`Number of results to return (default: ${defaultValue}, max: ${max})`);
    }
  • Symbol validation helper used by get_orderbook handler. Converts to uppercase and validates format (supports both BTC/USDT and BTCUSDT styles).
    export function validateSymbol(symbol: string): string {
      if (!symbol) {
        throw new Error('Symbol is required');
      }
      const upper = symbol.toUpperCase();
      if (!/^[A-Z]+\/[A-Z]+$/.test(upper) && !/^[A-Z]+[A-Z]+$/.test(upper)) {
        throw new Error(`Invalid symbol format: ${symbol}. Expected: BTC/USDT or BTCUSDT`);
      }
      return upper;
    }
  • Exchange validation helper used by get_orderbook handler. Validates against supported exchanges (mexc, gateio, bitget, kraken) and returns lowercase validated exchange name.
    export function validateExchange(exchange: string): SupportedExchange {
      const lower = exchange.toLowerCase();
      if (!(SUPPORTED_EXCHANGES as readonly string[]).includes(lower)) {
        throw new Error(
          `Unsupported exchange: ${exchange}. Supported: ${SUPPORTED_EXCHANGES.join(', ')}`
        );
      }
      return lower as SupportedExchange;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden but offers minimal behavioral insight. It mentions 'supported exchange' but doesn't specify rate limits, authentication requirements, error handling, or response format. For a financial data tool with zero annotation coverage, this leaves significant gaps in understanding how the tool behaves.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with zero wasted words. It's front-loaded with the core purpose and appropriately sized for what it communicates. Every word earns its place in conveying the essential function.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a financial data tool with 3 parameters, no annotations, and no output schema, the description is insufficiently complete. It doesn't explain what 'bids and asks' data looks like, how results are structured, whether there are exchange-specific behaviors, or what authentication might be required. The context demands more comprehensive guidance.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all three parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema - it doesn't explain what 'order book depth' means in practice or provide context about the limit parameter's effect on data granularity.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('fetch'), resource ('order book depth'), and scope ('for a trading pair on a supported exchange'), distinguishing it from siblings like get_ticker (price only) or get_trades (historical trades). It precisely communicates what the tool does without ambiguity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention when to choose get_orderbook over get_ticker for price data, or how it differs from list_orders for order information. There's no context about prerequisites or typical use cases.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/QBT-Labs/openmm-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server