Skip to main content
Glama
sammcj

Bybit MCP Server

by sammcj

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,
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the analysis method (volume peaks) and tracks mitigation status, but doesn't describe what the tool returns (e.g., data format, structure), whether it's a read-only operation, potential rate limits, or error conditions. For a tool with 8 parameters and complex financial analysis, this leaves significant behavioral gaps.

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

Conciseness4/5

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

The description is efficiently structured in two sentences that directly state the tool's purpose and methodology. There's no wasted language, though it could be slightly more front-loaded by explicitly stating this is for technical analysis of trading data.

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 complex financial analysis tool with 8 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain what the output looks like (critical for order block data), doesn't mention performance characteristics, and provides minimal behavioral context. The description should do more to compensate for the lack of structured metadata.

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?

The description mentions 'volume analysis', 'volume peaks', and 'mitigation status', which loosely relate to parameters like volumePivotLength and mitigationMethod. However, with 100% schema description coverage, all parameters are already documented in the schema. The description adds minimal semantic context beyond what the schema provides, meeting the baseline for high schema coverage.

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

Purpose4/5

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

The description clearly states the tool's purpose: detecting institutional order accumulation zones using volume analysis, identifying bullish/bearish order blocks, and tracking mitigation status. It uses specific verbs ('detect', 'identifies', 'tracks') and mentions the resource (order blocks). However, it doesn't explicitly differentiate from sibling tools like get_market_structure or get_kline, which might also analyze market data.

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 sibling tools like get_market_structure or get_kline that might provide related market analysis, nor does it specify prerequisites or appropriate contexts for order block detection versus other market indicators.

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

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