Skip to main content
Glama

get_orderbook

Retrieve real-time orderbook data for a specific trading pair on Bybit, including market depth for bids and asks, to analyze liquidity and trading opportunities.

Instructions

Get orderbook (market depth) data for a trading pair

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
categoryNoCategory of the instrument (spot, linear, inverse)
limitNoLimit for the number of bids and asks (1, 25, 50, 100, 200)
symbolYesTrading pair symbol (e.g., 'BTCUSDT')

Implementation Reference

  • Main handler logic for the get_orderbook tool: input validation, API call execution with retry, response formatting, and error handling.
    async toolCall(request: z.infer<typeof CallToolRequestSchema>) { try { this.logInfo("Starting get_orderbook tool call") // Parse and validate input const validationResult = inputSchema.safeParse(request.params.arguments) if (!validationResult.success) { throw new Error(`Invalid input: ${JSON.stringify(validationResult.error.errors)}`) } const { symbol, category = CONSTANTS.DEFAULT_CATEGORY as "spot" | "linear" | "inverse", limit = "25" } = validationResult.data this.logInfo(`Validated arguments - symbol: ${symbol}, category: ${category}, limit: ${limit}`) // Execute API request with rate limiting and retry logic const response = await this.executeRequest(async () => { const data = await this.getOrderbookData(symbol, category, limit) return data }) // Format response const result = { symbol, category, limit: parseInt(limit, 10), asks: response.a, bids: response.b, timestamp: response.ts, updateId: response.u, meta: { requestId: crypto.randomUUID() } } this.logInfo(`Successfully retrieved orderbook data for ${symbol}`) return this.formatResponse(result) } catch (error) { this.logInfo(`Error in get_orderbook: ${error instanceof Error ? error.message : String(error)}`) return this.handleError(error) } }
  • Zod schema used for validating and parsing tool input parameters (symbol, category, limit).
    const inputSchema = z.object({ symbol: z.string() .min(1, "Symbol is required") .regex(/^[A-Z0-9]+$/, "Symbol must contain only uppercase letters and numbers"), category: z.enum(["spot", "linear", "inverse"]).optional(), limit: z.union([ z.enum(["1", "25", "50", "100", "200"]), z.number().transform(n => { const validLimits = [1, 25, 50, 100, 200] const closest = validLimits.reduce((prev, curr) => Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev ) return String(closest) }) ]).optional() })
  • MCP-compatible tool definition including name, description, and JSON input schema.
    toolDefinition: Tool = { name: this.name, description: "Get orderbook (market depth) data for a trading pair", inputSchema: { type: "object", properties: { symbol: { type: "string", description: "Trading pair symbol (e.g., 'BTCUSDT')", pattern: "^[A-Z0-9]+$" }, category: { type: "string", description: "Category of the instrument (spot, linear, inverse)", enum: ["spot", "linear", "inverse"], }, limit: { type: "string", description: "Limit for the number of bids and asks (1, 25, 50, 100, 200)", enum: ["1", "25", "50", "100", "200"], }, }, required: ["symbol"], }, }
  • Helper method that constructs parameters and calls the Bybit API client to retrieve orderbook data.
    private async getOrderbookData( symbol: string, category: "spot" | "linear" | "inverse", limit: string ): Promise<APIResponseV3WithTime<OrderbookData>> { const params: GetOrderbookParamsV5 = { category, symbol, limit: parseInt(limit, 10), } this.logInfo(`Fetching orderbook with params: ${JSON.stringify(params)}`) return await this.client.getOrderbook(params) }
  • Dynamic registration loader that discovers, imports, instantiates, and validates all tool classes from the src/tools directory, including GetOrderbook.
    export async function loadTools(): Promise<BaseToolImplementation[]> { try { const toolsPath = await findToolsPath() const files = await fs.readdir(toolsPath) const tools: BaseToolImplementation[] = [] for (const file of files) { if (!isToolFile(file)) { continue } try { const modulePath = `file://${join(toolsPath, file)}` const { default: ToolClass } = await import(modulePath) if (!ToolClass || typeof ToolClass !== 'function') { console.warn(JSON.stringify({ type: "warning", message: `Invalid tool class in ${file}` })) continue } const tool = new ToolClass() if ( tool instanceof BaseToolImplementation && tool.name && tool.toolDefinition && typeof tool.toolCall === "function" ) { tools.push(tool) console.info(JSON.stringify({ type: "info", message: `Loaded tool: ${tool.name}` })) } else { console.warn(JSON.stringify({ type: "warning", message: `Invalid tool implementation in ${file}` })) } } catch (error) { console.error(JSON.stringify({ type: "error", message: `Error loading tool from ${file}: ${error instanceof Error ? error.message : String(error)}` })) } } return tools } catch (error) { console.error(JSON.stringify({ type: "error", message: `Failed to load tools: ${error instanceof Error ? error.message : String(error)}` })) return [] } }

Other Tools

Related 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/sammcj/bybit-mcp'

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