Skip to main content
Glama
kukapay

crypto-orderbook-mcp

compare_orderbook

Compare order book depth and imbalance for trading pairs across multiple cryptocurrency exchanges. Analyze bid/ask spreads and liquidity distribution to identify market opportunities.

Instructions

Compare order book depth and imbalance for a trading pair across multiple exchanges, returning a Markdown table.

Args:
    symbol: The trading pair (e.g., 'BTC/USDT')
    depth_percentage: Percentage range from mid-price to calculate depth and imbalance (default: 1.0%)
    exchanges: List of exchange IDs to compare (default: all supported exchanges)

Returns:
    String containing a Markdown table with exchanges as rows and bid/ask depths and imbalance as columns.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYes
depth_percentageNo
exchangesNo

Implementation Reference

  • main.py:128-178 (handler)
    The handler function for the 'compare_orderbook' tool. It orchestrates fetching order book data from multiple exchanges using the 'calculate_orderbook' helper, processes the results with pandas into a pivot table, and returns a Markdown-formatted comparison table.
    @mcp.tool()
    async def compare_orderbook(symbol: str, depth_percentage: float = 1.0, exchanges: List[str] = None, ctx: Context = None) -> str:
        """
        Compare order book depth and imbalance for a trading pair across multiple exchanges, returning a Markdown table.
        
        Args:
            symbol: The trading pair (e.g., 'BTC/USDT')
            depth_percentage: Percentage range from mid-price to calculate depth and imbalance (default: 1.0%)
            exchanges: List of exchange IDs to compare (default: all supported exchanges)
        
        Returns:
            String containing a Markdown table with exchanges as rows and bid/ask depths and imbalance as columns.
        """
        # Use all supported exchanges if none specified
        exchanges = exchanges or SUPPORTED_EXCHANGES
    
        # Validate inputs
        if not exchanges:
            await ctx.error("No exchanges specified")
            return json.dumps({"error": "No exchanges specified"})
    
        invalid_exchanges = [ex for ex in exchanges if ex.lower() not in SUPPORTED_EXCHANGES]
        if invalid_exchanges:
            await ctx.error(f"Unsupported exchanges: {invalid_exchanges}")
            return json.dumps({"error": f"Unsupported exchanges: {invalid_exchanges}"})
    
        if depth_percentage <= 0 or depth_percentage > 10:
            await ctx.error("Depth percentage must be between 0 and 10")
            return json.dumps({"error": "Depth percentage must be between 0 and 10"})
    
        results = []
        for exchange_id in exchanges:
            result = await calculate_orderbook(exchange_id, symbol, depth_percentage, ctx)
            if "error" not in result:
                results.append(result)
    
        # Create DataFrame for pivot table
        if not results:
            await ctx.error("No valid order book data retrieved")
            return json.dumps({"error": "No valid order book data retrieved"})
    
        df = pd.DataFrame(results)
        pivot_table = pd.pivot_table(
            df,
            values=['bid_depth', 'ask_depth', 'imbalance'],
            index='exchange',
            aggfunc='first'
        )
    
        # Convert pivot table to Markdown
        return pivot_table.to_markdown(floatfmt=(".2f", ".2f", ".4f"))
  • Supporting tool function called by compare_orderbook to compute order book metrics (depths and imbalance) for a single exchange.
    @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)
    Core helper function that fetches raw order book data from ccxt exchanges, handles validation, computes mid-price and price range for depth calculation.
    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)}"
  • main.py:128-128 (registration)
    Registration of the compare_orderbook tool using the FastMCP @mcp.tool() decorator.
    @mcp.tool()
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses the tool's behavior (comparison across exchanges, Markdown table output) and default values, but lacks details on potential limitations like rate limits, authentication requirements, or what happens with unsupported exchanges. It doesn't contradict any annotations.

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 efficiently structured with a clear purpose statement followed by Args and Returns sections. Every sentence adds value: the first establishes the tool's function, the parameter explanations provide necessary context, and the return statement clarifies output format. No wasted words.

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

Completeness4/5

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

Given 3 parameters with 0% schema coverage and no output schema, the description does well by explaining all parameters and the return format. However, as a comparison tool with no annotations, it could benefit from mentioning performance considerations or data freshness, though the current information is largely complete for basic usage.

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?

Schema description coverage is 0%, so the description must compensate. It adds meaningful context for all 3 parameters: explains 'symbol' as trading pair with an example, clarifies 'depth_percentage' as percentage range from mid-price with default, and describes 'exchanges' as list of IDs with default. However, it doesn't specify format for exchange IDs or valid ranges for depth_percentage.

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 specific action ('compare order book depth and imbalance'), the resource ('for a trading pair across multiple exchanges'), and the output format ('returning a Markdown table'). It distinguishes itself from the sibling tool 'calculate_orderbook' by focusing on comparison across exchanges rather than calculation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use this tool (comparing order books across exchanges) and mentions a default behavior ('default: all supported exchanges'). However, it doesn't explicitly state when NOT to use it or provide alternatives to the sibling tool 'calculate_orderbook'.

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