Skip to main content
Glama
t3rmed

Hyperliquid MCP Server

by t3rmed

get_l2_book

Retrieve Level 2 order book data for cryptocurrency trading pairs on Hyperliquid DEX to analyze market depth and liquidity for informed trading decisions.

Instructions

Get L2 order book snapshot for a specific coin

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
coinYesThe coin symbol (e.g., BTC, ETH, SOL)
nSigFigsNoNumber of significant figures for price aggregation (optional)

Implementation Reference

  • Main handler function executing the get_l2_book tool: extracts parameters, fetches L2 book via client, formats bids/asks as text response.
    async def handle_get_l2_book(client: HyperliquidClient, args: Dict[str, Any]) -> Dict[str, Any]:
        """Handle get L2 book request."""
        coin = args["coin"]
        n_sig_figs = args.get("nSigFigs")
    
        result = await client.get_l2_book(coin, n_sig_figs)
    
        if not result.success:
            raise ValueError(f"Failed to get L2 book for {coin}: {result.error}")
    
        book = result.data
        bids = book.get("levels", [[], []])[0] if book else []
        asks = book.get("levels", [[], []])[1] if book else []
    
        bids_text = "\n".join(f"{b['px']} @ {b['sz']}" for b in bids)
        asks_text = "\n".join(f"{a['px']} @ {a['sz']}" for a in asks)
    
        return {
            "content": [
                TextContent(
                    type="text",
                    text=f"L2 Order Book for {coin}:\n\nBids ({len(bids)} levels):\n{bids_text}\n\nAsks ({len(asks)} levels):\n{asks_text}",
                )
            ]
        }
  • Tool registration defining the get_l2_book MCP tool with input schema requiring 'coin' and optional 'nSigFigs'.
    get_l2_book_tool = Tool(
        name="get_l2_book",
        description="Get L2 order book snapshot for a specific coin",
        inputSchema={
            "type": "object",
            "properties": {
                "coin": {
                    "type": "string",
                    "description": "The coin symbol (e.g., BTC, ETH, SOL)",
                },
                "nSigFigs": {
                    "type": "number",
                    "description": "Number of significant figures for price aggregation (optional)",
                    "minimum": 1,
                    "maximum": 5,
                },
            },
            "required": ["coin"],
        },
    )
  • Input schema for validating tool arguments: coin (required string), nSigFigs (optional number 1-5).
    inputSchema={
        "type": "object",
        "properties": {
            "coin": {
                "type": "string",
                "description": "The coin symbol (e.g., BTC, ETH, SOL)",
            },
            "nSigFigs": {
                "type": "number",
                "description": "Number of significant figures for price aggregation (optional)",
                "minimum": 1,
                "maximum": 5,
            },
        },
        "required": ["coin"],
    },
  • Supporting method in HyperliquidClient that queries the Hyperliquid API for L2 book data, used by the handler.
    async def get_l2_book(
        self, coin: str, n_sig_figs: Optional[int] = None
    ) -> ApiResponse[L2BookResponse]:
        """Get L2 order book snapshot for a specific coin."""
        try:
            payload = {"type": "l2Book", "coin": coin}
            if n_sig_figs is not None:
                payload["nSigFigs"] = n_sig_figs
    
            response = await self.client.post("/info", json=payload)
            response.raise_for_status()
            return ApiResponse(success=True, data=response.json())
        except Exception as e:
            return ApiResponse(success=False, error=str(e))
  • MCP server registration of all tools including get_l2_book_tool in the list_tools handler.
    @app.list_tools()
    async def list_tools() -> list:
        """List all available tools."""
        return [
            # Market data tools
            get_all_mids_tool,
            get_l2_book_tool,
            get_candle_snapshot_tool,
            # Account info tools
            get_open_orders_tool,
            get_user_fills_tool,
            get_user_fills_by_time_tool,
            get_portfolio_tool,
            # Trading tools
            place_order_tool,
            place_trigger_order_tool,
            cancel_order_tool,
            cancel_all_orders_tool,
        ]

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/t3rmed/hyperliquid-mcp'

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