Skip to main content
Glama
badger3000

OKX MCP Server

by badger3000

get_live_ticker

Retrieve real-time cryptocurrency ticker data from OKX exchange WebSocket subscriptions for trading analysis and price monitoring.

Instructions

Get the latest ticker data from WebSocket subscription

Input Schema

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

Implementation Reference

  • The core handler logic for the 'get_live_ticker' tool. It checks if subscribed to the ticker channel, auto-subscribes if not, retrieves the latest data from the WebSocket cache, and returns formatted JSON or rich Markdown visualization.
    if (request.params.name === "get_live_ticker") {
      const isSubscribed = this.wsClient.isSubscribed(
        "tickers",
        args.instrument
      );
    
      if (!isSubscribed) {
        console.error(
          `[WebSocket] Auto-subscribing to ticker for ${args.instrument}`
        );
        this.wsClient.subscribe("tickers", args.instrument);
    
        // Give it a moment to connect and receive data
        await new Promise((resolve) => setTimeout(resolve, 1000));
      }
    
      const tickerData = this.wsClient.getLatestData(
        "tickers",
        args.instrument
      );
    
      if (!tickerData || tickerData.length === 0) {
        return {
          content: [
            {
              type: "text",
              text: `No live data available yet for ${args.instrument}. If you just subscribed, please wait a moment and try again.`,
            },
          ],
        };
      }
    
      const ticker = tickerData[0];
    
      if (args.format === "json") {
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(ticker, null, 2),
            },
          ],
        };
      } else {
        // Calculate change for markdown formatting
        const last = parseFloat(ticker.last);
        const open24h = parseFloat(ticker.open24h);
        const priceChange = last - open24h;
        const priceChangePercent = (priceChange / open24h) * 100;
        const changeSymbol = priceChange >= 0 ? "▲" : "▼";
    
        // Create price range visual
        const low24h = parseFloat(ticker.low24h);
        const high24h = parseFloat(ticker.high24h);
        const range = high24h - low24h;
        const position =
          Math.min(Math.max((last - 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:
                `# ${args.instrument} Live Price Data\n\n` +
                `## Current Price: $${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` +
                `*Data source: Live WebSocket feed*`,
            },
          ],
        };
      }
    }
  • Tool schema definition including name, description, and input schema for validation (instrument required, optional format).
    {
      name: "get_live_ticker",
      description: "Get the latest ticker data from WebSocket subscription",
      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"],
      },
    },
  • src/index.ts:284-386 (registration)
    Registration of all tools including 'get_live_ticker' in the MCP listTools request handler.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        {
          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"],
          },
        },
        {
          name: "get_candlesticks",
          description:
            "Get candlestick data for an OKX instrument with visualization options",
          inputSchema: {
            type: "object",
            properties: {
              instrument: {
                type: "string",
                description: "Instrument ID (e.g. BTC-USDT)",
              },
              bar: {
                type: "string",
                description: "Time interval (e.g. 1m, 5m, 1H, 1D)",
                default: "1m",
              },
              limit: {
                type: "number",
                description: "Number of candlesticks (max 100)",
                default: 100,
              },
              format: {
                type: "string",
                description: "Output format (json, markdown, or table)",
                default: "markdown",
              },
            },
            required: ["instrument"],
          },
        },
        {
          name: "subscribe_ticker",
          description:
            "Subscribe to real-time ticker updates for an instrument",
          inputSchema: {
            type: "object",
            properties: {
              instrument: {
                type: "string",
                description: "Instrument ID (e.g. BTC-USDT)",
              },
            },
            required: ["instrument"],
          },
        },
        {
          name: "get_live_ticker",
          description: "Get the latest ticker data from WebSocket subscription",
          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"],
          },
        },
        {
          name: "unsubscribe_ticker",
          description:
            "Unsubscribe from real-time ticker updates for an instrument",
          inputSchema: {
            type: "object",
            properties: {
              instrument: {
                type: "string",
                description: "Instrument ID (e.g. BTC-USDT)",
              },
            },
            required: ["instrument"],
          },
        },
      ],
    }));
  • Helper method in OKXWebSocketClient that retrieves the latest cached WebSocket data for a specific channel and instrument, used by get_live_ticker.
    getLatestData(channel: string, instId: string): any | null {
      const key = `${channel}:${instId}`;
      return this.dataCache.get(key) || null;
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'WebSocket subscription' which implies real-time or streaming data, but doesn't specify latency, rate limits, authentication needs, or what happens if the subscription fails. For a tool with no annotations, this leaves significant gaps in understanding its operational behavior.

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 function without unnecessary words. It's front-loaded with the core action and resource, making it easy to parse quickly.

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 complexity of real-time data tools and the absence of both annotations and an output schema, the description is insufficient. It doesn't explain the return format, error conditions, or how the WebSocket integration works, leaving the agent with incomplete context for reliable tool invocation.

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, clearly documenting both parameters ('instrument' and 'format') with details like default values. The description adds no additional parameter semantics beyond what the schema provides, so it meets the baseline score of 3 where the schema does the heavy lifting.

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 action ('Get') and resource ('latest ticker data from WebSocket subscription'), making the purpose understandable. However, it doesn't explicitly differentiate from sibling tools like 'get_price' or 'get_candlesticks', which likely provide similar financial data but through different mechanisms or timeframes.

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 like 'get_price' or 'subscribe_ticker'. It mentions 'WebSocket subscription' but doesn't clarify if this is for real-time data only or how it differs from other data retrieval methods, leaving the agent to infer usage context.

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