Skip to main content
Glama
badger3000

OKX MCP Server

by badger3000

get_price

Retrieve current cryptocurrency prices from OKX exchange with formatted visual output for trading analysis and decision-making.

Instructions

Get latest price for an OKX instrument with formatted visualization

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
instrumentYesInstrument ID (e.g. BTC-USDT)
formatNoOutput format (json or markdown)markdown

Implementation Reference

  • The handler function for the 'get_price' tool within the CallToolRequestSchema handler. It fetches the latest ticker data from the OKX REST API, handles JSON or Markdown formatting, calculates price changes, and generates a visual price range bar.
    if (request.params.name === "get_price") {
      console.error(
        `[API] Fetching price for instrument: ${args.instrument}`
      );
      const response = await this.axiosInstance.get<OKXTickerResponse>(
        "/market/ticker",
        {
          params: {instId: args.instrument},
        }
      );
    
      if (response.data.code !== "0") {
        throw new Error(`OKX API error: ${response.data.msg}`);
      }
    
      if (!response.data.data || response.data.data.length === 0) {
        throw new Error("No data returned from OKX API");
      }
    
      const ticker = response.data.data[0];
    
      if (args.format === "json") {
        // Original JSON format
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(
                {
                  instrument: ticker.instId,
                  lastPrice: ticker.last,
                  bid: ticker.bidPx,
                  ask: ticker.askPx,
                  high24h: ticker.high24h,
                  low24h: ticker.low24h,
                  volume24h: ticker.vol24h,
                  timestamp: new Date(parseInt(ticker.ts)).toISOString(),
                },
                null,
                2
              ),
            },
          ],
        };
      } else {
        // Enhanced markdown format with visualization elements
        const priceChange =
          parseFloat(ticker.last) - parseFloat(ticker.open24h);
        const priceChangePercent =
          (priceChange / parseFloat(ticker.open24h)) * 100;
        const changeSymbol = priceChange >= 0 ? "▲" : "▼";
        const changeColor = priceChange >= 0 ? "green" : "red";
    
        // Create price range visual
        const low24h = parseFloat(ticker.low24h);
        const high24h = parseFloat(ticker.high24h);
        const range = high24h - low24h;
        const currentPrice = parseFloat(ticker.last);
        const position =
          Math.min(Math.max((currentPrice - low24h) / range, 0), 1) * 100;
    
        const priceBar = `Low ${low24h.toFixed(2)} [${"▮".repeat(
          Math.floor(position / 5)
        )}|${"▯".repeat(20 - Math.floor(position / 5))}] ${high24h.toFixed(
          2
        )} High`;
    
        return {
          content: [
            {
              type: "text",
              text:
                `# ${ticker.instId} Price Summary\n\n` +
                `## Current Price: $${parseFloat(
                  ticker.last
                ).toLocaleString()}\n\n` +
                `**24h Change:** ${changeSymbol} $${Math.abs(
                  priceChange
                ).toLocaleString()} (${
                  priceChangePercent >= 0 ? "+" : ""
                }${priceChangePercent.toFixed(2)}%)\n\n` +
                `**Bid:** $${parseFloat(
                  ticker.bidPx
                ).toLocaleString()} | **Ask:** $${parseFloat(
                  ticker.askPx
                ).toLocaleString()}\n\n` +
                `### 24-Hour Price Range\n\n` +
                `\`\`\`\n${priceBar}\n\`\`\`\n\n` +
                `**24h High:** $${parseFloat(
                  ticker.high24h
                ).toLocaleString()}\n` +
                `**24h Low:** $${parseFloat(
                  ticker.low24h
                ).toLocaleString()}\n\n` +
                `**24h Volume:** ${parseFloat(
                  ticker.vol24h
                ).toLocaleString()} units\n\n` +
                `**Last Updated:** ${new Date(
                  parseInt(ticker.ts)
                ).toLocaleString()}\n\n` +
                `*Note: For real-time updates, use the subscribe_ticker and get_live_ticker tools.*`,
            },
          ],
        };
      }
  • src/index.ts:287-305 (registration)
    Registration of the 'get_price' tool in the ListToolsRequestSchema response, defining its name, description, and input schema.
      name: "get_price",
      description:
        "Get latest price for an OKX instrument with formatted visualization",
      inputSchema: {
        type: "object",
        properties: {
          instrument: {
            type: "string",
            description: "Instrument ID (e.g. BTC-USDT)",
          },
          format: {
            type: "string",
            description: "Output format (json or markdown)",
            default: "markdown",
          },
        },
        required: ["instrument"],
      },
    },
  • Input schema for the 'get_price' tool, defining required 'instrument' parameter and optional 'format' parameter.
    inputSchema: {
      type: "object",
      properties: {
        instrument: {
          type: "string",
          description: "Instrument ID (e.g. BTC-USDT)",
        },
        format: {
          type: "string",
          description: "Output format (json or markdown)",
          default: "markdown",
        },
      },
      required: ["instrument"],
    },
  • TypeScript interface defining the OKX ticker API response structure used in the get_price handler for type safety.
    interface OKXTickerResponse {
      code: string;
      msg: string;
      data: Array<{
        instId: string;
        last: string;
        askPx: string;
        bidPx: string;
        open24h: string;
        high24h: string;
        low24h: string;
        volCcy24h: string;
        vol24h: string;
        ts: string;
      }>;
  • src/index.ts:390-396 (registration)
    Validation registration listing 'get_price' as an allowed tool name in the CallToolRequestSchema dispatcher.
    const validTools = [
      "get_price",
      "get_candlesticks",
      "subscribe_ticker",
      "get_live_ticker",
      "unsubscribe_ticker",
    ];
Behavior2/5

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

No annotations are provided, so the description must fully disclose behavioral traits. It mentions 'formatted visualization,' which hints at output behavior, but lacks details on critical aspects like whether this is a read-only operation, potential rate limits, authentication needs, or error handling. The description is too vague to adequately inform the agent about how the tool behaves beyond its basic function.

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 a single, efficient sentence that directly states the tool's purpose without unnecessary words. It is front-loaded with the core action ('Get latest price') and includes the key feature ('formatted visualization'). There is no wasted information, making it highly concise and well-structured.

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?

Given the lack of annotations and output schema, the description is incomplete for a tool that retrieves financial data. It does not address important contextual elements such as the source of the data (e.g., real-time vs. cached), potential limitations, error scenarios, or the structure of the formatted output. This leaves gaps in understanding the tool's full behavior and constraints.

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 input schema has 100% description coverage, with clear documentation for both parameters ('instrument' and 'format'). The description adds minimal value beyond the schema, as it does not explain parameter semantics further (e.g., what 'formatted visualization' entails for the 'format' parameter). With high schema coverage, the baseline score of 3 is appropriate, as the description does not compensate with additional insights.

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: 'Get latest price for an OKX instrument with formatted visualization.' It specifies the verb ('Get'), resource ('latest price for an OKX instrument'), and includes the unique aspect of 'formatted visualization.' However, it does not explicitly differentiate from siblings like 'get_candlesticks' or 'get_live_ticker,' which might also retrieve price-related data, preventing a score of 5.

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 does not mention sibling tools like 'get_candlesticks' (for historical data) or 'get_live_ticker' (for real-time updates), nor does it specify contexts or exclusions. This lack of comparative usage information limits the agent's ability to select the correct tool.

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/badger3000/okx-mcp-server'

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