Skip to main content
Glama

get_order_blocks

Identify institutional order accumulation zones using volume analysis on Bybit trading pairs. Detect bullish and bearish order blocks via volume peaks and monitor mitigation status for actionable insights.

Instructions

Detect institutional order accumulation zones based on volume analysis. Identifies bullish and bearish order blocks using volume peaks and tracks their mitigation status.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
bearishBlocksNoNumber of bearish blocks to track (default: 3)
bullishBlocksNoNumber of bullish blocks to track (default: 3)
categoryYesCategory of the instrument
intervalYesKline interval
limitNoHistorical data points to analyse (default: 200)
mitigationMethodNoMitigation detection method (default: wick)
symbolYesTrading pair symbol (e.g., 'BTCUSDT')
volumePivotLengthNoVolume pivot detection period (default: 5)

Implementation Reference

  • The GetOrderBlocks class extends BaseToolImplementation and provides the core handler logic for the 'get_order_blocks' tool. It defines the tool name, schema, description, and implements the toolCall method which fetches historical kline data from Bybit, performs volume-based order block detection, calculates active levels and stats, and returns structured order block analysis.
    class GetOrderBlocks extends BaseToolImplementation { name = "get_order_blocks" toolDefinition: Tool = { name: this.name, description: "Detect institutional order accumulation zones based on volume analysis. Identifies bullish and bearish order blocks using volume peaks and tracks their mitigation status.", 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", enum: ["spot", "linear", "inverse"] }, interval: { type: "string", description: "Kline interval", enum: ["1", "3", "5", "15", "30", "60", "120", "240", "360", "720", "D", "W", "M"] }, volumePivotLength: { type: "number", description: "Volume pivot detection period (default: 5)", minimum: 1, maximum: 20 }, bullishBlocks: { type: "number", description: "Number of bullish blocks to track (default: 3)", minimum: 1, maximum: 10 }, bearishBlocks: { type: "number", description: "Number of bearish blocks to track (default: 3)", minimum: 1, maximum: 10 }, mitigationMethod: { type: "string", description: "Mitigation detection method (default: wick)", enum: ["wick", "close"] }, limit: { type: "number", description: "Historical data points to analyse (default: 200)", minimum: 100, maximum: 1000 } }, required: ["symbol", "category", "interval"] } } async toolCall(request: z.infer<typeof CallToolRequestSchema>): Promise<CallToolResult> { const startTime = Date.now() try { this.logInfo("Starting get_order_blocks tool call") // Parse and validate input const validationResult = inputSchema.safeParse(request.params.arguments) if (!validationResult.success) { const errorDetails = validationResult.error.errors.map(err => ({ field: err.path.join('.'), message: err.message, code: err.code })) throw new Error(`Invalid input: ${JSON.stringify(errorDetails)}`) } const args = validationResult.data // Fetch kline data const klineData = await this.fetchKlineData(args) if (klineData.length < args.volumePivotLength * 2 + 10) { throw new Error(`Insufficient data. Need at least ${args.volumePivotLength * 2 + 10} data points, got ${klineData.length}`) } // Configure volume analysis const config: VolumeAnalysisConfig = { volumePivotLength: args.volumePivotLength, bullishBlocks: args.bullishBlocks, bearishBlocks: args.bearishBlocks, mitigationMethod: args.mitigationMethod } // Detect order blocks const { bullishBlocks, bearishBlocks } = detectOrderBlocks(klineData, config) // Get active support and resistance levels const { support, resistance } = getActiveLevels([...bullishBlocks, ...bearishBlocks]) // Calculate statistics const stats = calculateOrderBlockStats(bullishBlocks, bearishBlocks) const calculationTime = Date.now() - startTime const response: OrderBlockResponse = { symbol: args.symbol, interval: args.interval, bullishBlocks: bullishBlocks.map(block => ({ id: block.id, timestamp: block.timestamp, top: block.top, bottom: block.bottom, average: block.average, volume: block.volume, mitigated: block.mitigated, mitigationTime: block.mitigationTime })), bearishBlocks: bearishBlocks.map(block => ({ id: block.id, timestamp: block.timestamp, top: block.top, bottom: block.bottom, average: block.average, volume: block.volume, mitigated: block.mitigated, mitigationTime: block.mitigationTime })), currentSupport: support.slice(0, 5), // Top 5 support levels currentResistance: resistance.slice(0, 5), // Top 5 resistance levels metadata: { volumePivotLength: args.volumePivotLength, mitigationMethod: args.mitigationMethod, blocksDetected: stats.totalBlocks, activeBullishBlocks: stats.activeBullishBlocks, activeBearishBlocks: stats.activeBearishBlocks, averageVolume: stats.averageVolume, calculationTime } } this.logInfo(`Order block detection completed in ${calculationTime}ms. Found ${stats.totalBlocks} blocks (${stats.activeBullishBlocks} bullish, ${stats.activeBearishBlocks} bearish active)`) return this.formatResponse(response) } catch (error) { this.logInfo(`Order block detection failed: ${error instanceof Error ? error.message : String(error)}`) return this.handleError(error) } } private async fetchKlineData(args: ToolArguments): Promise<KlineData[]> { const params: GetKlineParamsV5 = { category: args.category, symbol: args.symbol, interval: args.interval as KlineIntervalV3, limit: args.limit } const response = await this.executeRequest(() => this.client.getKline(params)) if (!response.list || response.list.length === 0) { throw new Error("No kline data received from API") } // Convert API response to KlineData format return response.list.map(kline => ({ timestamp: parseInt(kline[0]), open: parseFloat(kline[1]), high: parseFloat(kline[2]), low: parseFloat(kline[3]), close: parseFloat(kline[4]), volume: parseFloat(kline[5]) })).reverse() // Reverse to get chronological order } }
  • Zod input validation schema defining parameters for the get_order_blocks tool: symbol, category, interval, volume analysis params, etc.
    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"]), interval: z.enum(["1", "3", "5", "15", "30", "60", "120", "240", "360", "720", "D", "W", "M"]), volumePivotLength: z.number().min(1).max(20).optional().default(5), bullishBlocks: z.number().min(1).max(10).optional().default(3), bearishBlocks: z.number().min(1).max(10).optional().default(3), mitigationMethod: z.enum(["wick", "close"]).optional().default("wick"), limit: z.number().min(100).max(1000).optional().default(200) })
  • Dynamic tool registration loader that discovers, imports, instantiates, and collects all tool implementations from src/tools/*.ts (including GetOrderBlocks), used by both stdio and HTTP servers.
    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 [] } }
  • src/index.ts:134-136 (registration)
    In stdio MCP server initialization (src/index.ts), loads tools via toolLoader and creates toolsMap used for handling listTools and callTool requests.
    const tools = await loadTools() toolsMap = createToolsMap(tools)
  • Imports helper functions from volumeAnalysis.ts used in order block detection: detectOrderBlocks (main logic), getActiveLevels, calculateOrderBlockStats.
    import { detectOrderBlocks, getActiveLevels, calculateOrderBlockStats, OrderBlock,

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