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
| Name | Required | Description | Default |
|---|---|---|---|
| category | No | Category of the instrument (spot, linear, inverse) | |
| limit | No | Limit for the number of bids and asks (1, 25, 50, 100, 200) | |
| symbol | Yes | Trading pair symbol (e.g., 'BTCUSDT') |
Implementation Reference
- src/tools/GetOrderbook.ts:84-128 (handler)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) } }
- src/tools/GetOrderbook.ts:13-28 (schema)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() })
- src/tools/GetOrderbook.ts:44-68 (schema)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"], }, }
- src/tools/GetOrderbook.ts:70-82 (helper)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) }
- src/utils/toolLoader.ts:23-81 (registration)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 [] } }