Skip to main content
Glama
badger3000

OKX MCP Server

by badger3000

get_candlesticks

Retrieve historical price data for cryptocurrency trading pairs from OKX exchange. Specify instrument, time interval, and output format to analyze market trends with candlestick charts.

Instructions

Get candlestick data for an OKX instrument with visualization options

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
instrumentYesInstrument ID (e.g. BTC-USDT)
barNoTime interval (e.g. 1m, 5m, 1H, 1D)1m
limitNoNumber of candlesticks (max 100)
formatNoOutput format (json, markdown, or table)markdown

Implementation Reference

  • The handler logic inside CallToolRequestSchema that executes the get_candlesticks tool. Calls OKX API /market/candles, processes OHLCV data, calculates changes, reverses to chronological order, and provides formatted outputs including JSON, table, and advanced markdown with ASCII candlestick chart visualization.
    } else if (request.params.name === "get_candlesticks") {
      // get_candlesticks
      console.error(
        `[API] Fetching candlesticks for instrument: ${
          args.instrument
        }, bar: ${args.bar || "1m"}, limit: ${args.limit || 100}`
      );
      const response =
        await this.axiosInstance.get<OKXCandlesticksResponse>(
          "/market/candles",
          {
            params: {
              instId: args.instrument,
              bar: args.bar || "1m",
              limit: args.limit || 100,
            },
          }
        );
    
      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");
      }
    
      // Process the candlestick data
      const processedData = response.data.data.map(
        ([time, open, high, low, close, vol, volCcy]) => ({
          timestamp: new Date(parseInt(time)).toISOString(),
          date: new Date(parseInt(time)).toLocaleString(),
          open: parseFloat(open),
          high: parseFloat(high),
          low: parseFloat(low),
          close: parseFloat(close),
          change: (
            ((parseFloat(close) - parseFloat(open)) / parseFloat(open)) *
            100
          ).toFixed(2),
          volume: parseFloat(vol),
          volumeCurrency: parseFloat(volCcy),
        })
      );
    
      // Reverse for chronological order (oldest first)
      const chronologicalData = [...processedData].reverse();
    
      if (args.format === "json") {
        // Original JSON format
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(processedData, null, 2),
            },
          ],
        };
      } else if (args.format === "table") {
        // Table format (still markdown but formatted as a table)
        let tableMarkdown = `# ${args.instrument} Candlestick Data (${
          args.bar || "1m"
        })\n\n`;
        tableMarkdown +=
          "| Time | Open | High | Low | Close | Change % | Volume |\n";
        tableMarkdown +=
          "|------|------|------|-----|-------|----------|--------|\n";
    
        // Only show last 20 entries if there are too many to avoid huge tables
        const displayData = chronologicalData.slice(-20);
    
        displayData.forEach((candle) => {
          const changeSymbol = parseFloat(candle.change) >= 0 ? "▲" : "▼";
          tableMarkdown += `| ${candle.date} | $${candle.open.toFixed(
            2
          )} | $${candle.high.toFixed(2)} | $${candle.low.toFixed(
            2
          )} | $${candle.close.toFixed(2)} | ${changeSymbol} ${Math.abs(
            parseFloat(candle.change)
          ).toFixed(2)}% | ${candle.volume.toLocaleString()} |\n`;
        });
    
        return {
          content: [
            {
              type: "text",
              text: tableMarkdown,
            },
          ],
        };
      } else {
        // Enhanced markdown format with visualization
        // Calculate some stats
        const firstPrice = chronologicalData[0]?.open || 0;
        const lastPrice =
          chronologicalData[chronologicalData.length - 1]?.close || 0;
        const overallChange = (
          ((lastPrice - firstPrice) / firstPrice) *
          100
        ).toFixed(2);
        const highestPrice = Math.max(
          ...chronologicalData.map((c) => c.high)
        );
        const lowestPrice = Math.min(
          ...chronologicalData.map((c) => c.low)
        );
    
        // Create a simple ASCII chart
        const chartHeight = 10;
        const priceRange = highestPrice - lowestPrice;
    
        // Get a subset of data points for the chart (we'll use up to 40 points)
        const step = Math.max(1, Math.floor(chronologicalData.length / 40));
        const chartData = chronologicalData.filter(
          (_, i) => i % step === 0
        );
    
        // Create the ASCII chart
        let chart = "";
        for (let row = 0; row < chartHeight; row++) {
          const priceAtRow =
            highestPrice - (row / (chartHeight - 1)) * priceRange;
          // Price label on y-axis (right aligned)
          chart += `${priceAtRow.toFixed(2).padStart(8)} |`;
    
          // Plot the points
          for (let i = 0; i < chartData.length; i++) {
            const candle = chartData[i];
            if (candle.high >= priceAtRow && candle.low <= priceAtRow) {
              // This price level is within this candle's range
              if (
                (priceAtRow <= candle.close && priceAtRow >= candle.open) ||
                (priceAtRow >= candle.close && priceAtRow <= candle.open)
              ) {
                chart += "█"; // Body of the candle
              } else {
                chart += "│"; // Wick of the candle
              }
            } else {
              chart += " ";
            }
          }
          chart += "\n";
        }
    
        // X-axis
        chart += "         " + "‾".repeat(chartData.length) + "\n";
    
        // Create the markdown with stats and chart
        let markdownText = `# ${args.instrument} Candlestick Analysis (${
          args.bar || "1m"
        })\n\n`;
        markdownText += `## Summary\n\n`;
        markdownText += `- **Period:** ${chronologicalData[0].date} to ${
          chronologicalData[chronologicalData.length - 1].date
        }\n`;
        markdownText += `- **Starting Price:** $${firstPrice.toLocaleString()}\n`;
        markdownText += `- **Ending Price:** $${lastPrice.toLocaleString()}\n`;
        markdownText += `- **Overall Change:** ${overallChange}%\n`;
        markdownText += `- **Highest Price:** $${highestPrice.toLocaleString()}\n`;
        markdownText += `- **Lowest Price:** $${lowestPrice.toLocaleString()}\n`;
        markdownText += `- **Number of Candles:** ${chronologicalData.length}\n\n`;
    
        markdownText += `## Price Chart\n\n`;
        markdownText += "```\n" + chart + "```\n\n";
    
        markdownText += `## Recent Price Action\n\n`;
    
        // Add a table of the most recent 5 candles
        markdownText += "| Time | Open | High | Low | Close | Change % |\n";
        markdownText += "|------|------|------|-----|-------|----------|\n";
    
        chronologicalData.slice(-5).forEach((candle) => {
          const changeSymbol = parseFloat(candle.change) >= 0 ? "▲" : "▼";
          markdownText += `| ${candle.date} | $${candle.open.toFixed(
            2
          )} | $${candle.high.toFixed(2)} | $${candle.low.toFixed(
            2
          )} | $${candle.close.toFixed(2)} | ${changeSymbol} ${Math.abs(
            parseFloat(candle.change)
          ).toFixed(2)}% |\n`;
        });
    
        markdownText += `\n*Note: For real-time updates, use the WebSocket subscription tools.*`;
    
        return {
          content: [
            {
              type: "text",
              text: markdownText,
            },
          ],
        };
      }
    }
  • Registration and input schema for the get_candlesticks tool in the ListToolsRequestSchema handler.
    {
      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"],
      },
    },
  • TypeScript interface defining the structure of the OKX candlesticks API response, used in the axios get call.
    interface OKXCandlesticksResponse {
      code: string;
      msg: string;
      data: Array<
        [
          time: string, // Open time
          open: string, // Open price
          high: string, // Highest price
          low: string, // Lowest price
          close: string, // Close price
          vol: string, // Trading volume
          volCcy: string // Trading volume in currency
        ]
      >;
    }
  • src/index.ts:391-396 (registration)
    List of valid tool names checked before dispatching to specific handlers, includes get_candlesticks.
      "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?

With no annotations provided, the description carries the full burden of behavioral disclosure. It hints at 'visualization options' but doesn't specify what these entail (e.g., formatting effects, rate limits, or data freshness). This leaves gaps in understanding how the tool behaves 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.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the core purpose. It could be slightly more structured by separating visualization details, but it avoids unnecessary verbosity and earns its place.

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 no annotations, no output schema, and a tool with multiple parameters for financial data retrieval, the description is incomplete. It lacks details on return values, error handling, or practical constraints (e.g., data latency), leaving significant gaps for effective agent use.

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, so parameters are well-documented there. The description adds minimal value by implying 'visualization options' relate to the 'format' parameter, but doesn't elaborate on semantics beyond what the schema provides. This meets the baseline for high schema coverage.

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 candlestick data') and resource ('for an OKX instrument'), making the purpose understandable. However, it doesn't explicitly differentiate from sibling tools like 'get_live_ticker' or 'get_price' in terms of data type or granularity, which prevents a perfect score.

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 mentions 'visualization options' but provides no guidance on when to use this tool versus alternatives like 'get_live_ticker' or 'get_price'. There are no explicit when-to-use or when-not-to-use instructions, leaving usage context unclear.

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