Skip to main content
Glama

get_candlesticks

Retrieve historical price data for cryptocurrency trading pairs from OKX exchange with customizable time intervals and visualization formats for market analysis.

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

  • Executes the get_candlesticks tool: fetches candlestick data from OKX REST API (/market/candles), processes timestamps/prices/volumes, reverses for chronological order, and formats output as JSON, markdown table, or enhanced markdown with summary statistics and ASCII candlestick chart.
    } 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, }, ], }; } }
  • src/index.ts:307-335 (registration)
    Registration of the get_candlesticks tool in the ListTools response, defining its name, description, input parameters (instrument required, bar/limit/format optional), and capabilities.
    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 for type-safe parsing in the handler.
    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 ] >; }

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