Skip to main content
Glama
kukapay

crypto-orderbook-mcp

calculate_orderbook

Analyze cryptocurrency order book depth and imbalance for trading pairs on exchanges like Binance or Kraken to identify market liquidity and price pressure.

Instructions

Calculate the order book depth and imbalance for a given trading pair on a specified exchange.

Args:
    exchange_id: The exchange identifier (e.g., 'binance', 'kraken')
    symbol: The trading pair (e.g., 'BTC/USDT')
    depth_percentage: Percentage range from mid-price to calculate depth and imbalance (default: 1.0%)

Returns:
    Dictionary containing bid depth, ask depth, imbalance, mid-price, and timestamp.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
exchange_idYes
symbolYes
depth_percentageNo

Implementation Reference

  • main.py:78-127 (handler)
    The main handler function for the 'calculate_orderbook' tool. Decorated with @mcp.tool(), it fetches order book data using a helper function, calculates bid and ask volumes within the specified depth percentage around the mid-price, computes the imbalance ratio, and returns the results or error.
    @mcp.tool()
    async def calculate_orderbook(exchange_id: str, symbol: str, depth_percentage: float = 1.0, ctx: Context = None) -> Dict:
        """
        Calculate the order book depth and imbalance for a given trading pair on a specified exchange.
        
        Args:
            exchange_id: The exchange identifier (e.g., 'binance', 'kraken')
            symbol: The trading pair (e.g., 'BTC/USDT')
            depth_percentage: Percentage range from mid-price to calculate depth and imbalance (default: 1.0%)
        
        Returns:
            Dictionary containing bid depth, ask depth, imbalance, mid-price, and timestamp.
        """
        exchange, order_book, mid_price, price_range, error = await fetch_order_book_data(exchange_id, symbol, depth_percentage, ctx)
        
        if error:
            return {"error": error}
    
        try:
            # Calculate depth and imbalance, handling both [price, vol] and [price, vol, 0] formats
            bids = order_book.get('bids', [])
            asks = order_book.get('asks', [])
            bid_volume = sum(entry[1] for entry in bids if len(entry) >= 2 and entry[0] >= mid_price - price_range)
            ask_volume = sum(entry[1] for entry in asks if len(entry) >= 2 and entry[0] <= mid_price + price_range)
    
            # Calculate imbalance: (bid_volume - ask_volume) / (bid_volume + ask_volume)
            total_volume = bid_volume + ask_volume
            if total_volume == 0:
                await ctx.error("Zero total volume in order book")
                return {"error": "Zero total volume in order book"}
    
            imbalance = (bid_volume - ask_volume) / total_volume
    
            return {
                "exchange": exchange_id,
                "symbol": symbol,
                "bid_depth": bid_volume,
                "ask_depth": ask_volume,
                "imbalance": imbalance,
                "mid_price": mid_price,
                "timestamp": order_book['timestamp'] or int(asyncio.get_event_loop().time() * 1000)
            }
    
        except Exception as e:
            await ctx.error(f"Error calculating order book metrics: {str(e)}")
            return {"error": f"Error calculating order book metrics: {str(e)}"}
        finally:
            if exchange:
                await exchange.close()
  • main.py:14-77 (helper)
    Helper utility function used by the calculate_orderbook tool to validate inputs, initialize the exchange, load markets, fetch the order book, calculate mid-price and price range, and handle errors.
    async def fetch_order_book_data(exchange_id: str, symbol: str, depth_percentage: float, ctx: Context) -> Tuple[Optional[ccxt.Exchange], Optional[Dict], Optional[float], Optional[float], Optional[str]]:
        """
        Common function to validate inputs, fetch order book, and calculate mid-price and price range.
        
        Args:
            exchange_id: The exchange identifier (e.g., 'binance', 'kraken')
            symbol: The trading pair (e.g., 'BTC/USDT')
            depth_percentage: Percentage range from mid-price (default: 1.0%)
            ctx: MCP context for error reporting
        
        Returns:
            Tuple containing (exchange object, order book, mid_price, price_range, error) or (None, None, None, None, error) on error.
        """
        # Validate exchange
        if exchange_id.lower() not in SUPPORTED_EXCHANGES:
            await ctx.error(f"Unsupported exchange: {exchange_id}")
            return None, None, None, None, f"Unsupported exchange: {exchange_id}"
        
        # Validate depth percentage
        if depth_percentage <= 0 or depth_percentage > 10:
            await ctx.error("Depth percentage must be between 0 and 10")
            return None, None, None, None, "Depth percentage must be between 0 and 10"
    
        # Initialize exchange
        try:
            exchange = getattr(ccxt, exchange_id.lower())()
        except AttributeError:
            await ctx.error(f"Failed to initialize exchange: {exchange_id}")
            return None, None, None, None, f"Failed to initialize exchange: {exchange_id}"
    
        try:
            # Validate symbol
            try:
                markets = await exchange.load_markets()
                if symbol not in markets:
                    await ctx.error(f"Invalid symbol {symbol} for exchange {exchange_id}")
                    return None, None, None, None, f"Invalid symbol {symbol} for exchange {exchange_id}"
            except Exception as e:
                await ctx.error(f"Error validating symbol {symbol}: {str(e)}")
                return None, None, None, None, f"Error validating symbol {symbol}: {str(e)}"
    
            # Fetch order book
            try:
                order_book = await exchange.fetch_order_book(symbol, limit=100)
            except ccxt.BaseError as e:
                await ctx.error(f"Failed to fetch order book for {symbol}: {str(e)}")
                return None, None, None, None, f"Failed to fetch order book for {symbol}: {str(e)}"
    
            # Calculate mid-price
            bids = order_book.get('bids', [])
            asks = order_book.get('asks', [])
            if not bids or not asks:
                await ctx.error("Empty order book")
                return None, None, None, None, "Empty order book"
    
            mid_price = (bids[0][0] + asks[0][0]) / 2
            price_range = mid_price * (depth_percentage / 100)
    
            return exchange, order_book, mid_price, price_range, None
    
        except Exception as e:
            await ctx.error(f"Error fetching order book data: {str(e)}")
            return None, None, None, None, f"Error fetching order book data: {str(e)}"
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions what the tool returns but lacks details on rate limits, authentication needs, error handling, or whether it's a read-only operation. The description is minimal beyond basic functionality.

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 well-structured and concise, with a clear purpose statement followed by parameter and return value sections. Every sentence adds value without redundancy, making it easy to parse.

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

Completeness3/5

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

Given the complexity of a financial calculation tool with no annotations and no output schema, the description is moderately complete. It covers parameters and return values but lacks behavioral context like performance implications or error conditions, which are important for such operations.

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

Parameters4/5

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

The description adds significant meaning beyond the input schema, which has 0% description coverage. It explains each parameter's purpose with examples (e.g., 'binance', 'BTC/USDT', '1.0%'), clarifying semantics that the schema alone does not provide.

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 tool's purpose with specific verbs ('calculate') and resources ('order book depth and imbalance'), specifying it's for a trading pair on an exchange. It distinguishes from the sibling tool 'compare_orderbook' by focusing on calculation rather than comparison.

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 the sibling 'compare_orderbook' or other alternatives. It mentions the parameters but offers no context about appropriate use cases or exclusions.

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/kukapay/crypto-orderbook-mcp'

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