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
| Name | Required | Description | Default |
|---|---|---|---|
| instrument | Yes | Instrument ID (e.g. BTC-USDT) | |
| bar | No | Time interval (e.g. 1m, 5m, 1H, 1D) | 1m |
| limit | No | Number of candlesticks (max 100) | |
| format | No | Output format (json, markdown, or table) | markdown |
Implementation Reference
- src/index.ts:664-858 (handler)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, }, ], }; } }
- src/index.ts:306-335 (schema)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"], }, },
- src/index.ts:31-45 (schema)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", ];