generate_candlestick_chart
Generate candlestick charts from OHLC financial data. Input date, open, high, low, close, and optional volume. Customize chart dimensions, theme, title, and volume display. Output as PNG, SVG, or ECharts option.
Instructions
Generate a candlestick chart for financial data visualization, such as, stock prices, cryptocurrency prices, or other OHLC (Open-High-Low-Close) data.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| data | Yes | Data for candlestick chart, such as, [{ date: '2023-01-01', open: 100, high: 110, low: 95, close: 105, volume: 10000 }]. | |
| height | No | Set the height of the chart, default is 600px. | |
| showVolume | No | Whether to show volume chart below candlestick. Default is false. | |
| theme | No | Set the theme for the chart, optional, default is 'default'. | default |
| title | No | Set the title of the chart. | |
| width | No | Set the width of the chart, default is 800px. | |
| outputType | No | The output type of the diagram. Can be 'png', 'svg' or 'option'. Default is 'png', 'png' will return the rendered PNG image, 'svg' will return the rendered SVG string, and 'option' will return the valid ECharts option. | png |
Implementation Reference
- src/tools/candlestick.ts:46-236 (handler)The run handler for the generate_candlestick_chart tool. Sorts OHLC data by date, builds candlestick and optional volume series, constructs a full ECharts option object, and delegates rendering to generateChartImage.
run: async (params: { data: Array<{ date: string; open: number; high: number; low: number; close: number; volume?: number; }>; height: number; showVolume?: boolean; theme?: "default" | "dark"; title?: string; width: number; outputType?: "png" | "svg" | "option"; }) => { const { data, height, showVolume = false, theme, title, width, outputType, } = params; // Sort data by date const sortedData = [...data].sort( (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(), ); // Extract dates and OHLC data const dates = sortedData.map((item) => item.date); const ohlcData = sortedData.map((item) => [ item.open, item.close, item.low, item.high, ]); const volumeData = sortedData.map((item) => item.volume || 0); const series: Array<SeriesOption> = [ { name: "Candlestick", type: "candlestick", data: ohlcData, itemStyle: { color: "#ef232a", color0: "#14b143", borderColor: "#ef232a", borderColor0: "#14b143", }, emphasis: { itemStyle: { color: "#ef232a", color0: "#14b143", borderColor: "#ef232a", borderColor0: "#14b143", }, }, }, ]; // Add volume series if requested if (showVolume && volumeData.some((v) => v > 0)) { series.push({ name: "Volume", type: "bar", xAxisIndex: 1, yAxisIndex: 1, data: volumeData, barWidth: "60%", itemStyle: { color: (params: { dataIndex: number }) => { const dataIndex = params.dataIndex; return sortedData[dataIndex].close >= sortedData[dataIndex].open ? "#ef232a" : "#14b143"; }, }, }); } const echartsOption: EChartsOption = { animation: false, legend: { bottom: 10, left: "center", data: showVolume ? ["Candlestick", "Volume"] : ["Candlestick"], }, tooltip: { trigger: "axis", axisPointer: { type: "cross", }, borderWidth: 1, borderColor: "#ccc", padding: 10, textStyle: { color: "#000", }, }, xAxis: [ { type: "category", data: dates, boundaryGap: true, axisLine: { onZero: false }, splitLine: { show: false }, min: -0.2, max: dates.length - 0.8, }, ...(showVolume ? [ { type: "category" as const, gridIndex: 1, data: dates, boundaryGap: true, axisLine: { onZero: false }, axisTick: { show: false }, splitLine: { show: false }, axisLabel: { show: false }, min: -0.2, max: dates.length - 0.8, }, ] : []), ], yAxis: [ { scale: true, splitArea: { show: true, }, }, ...(showVolume ? [ { scale: true, gridIndex: 1, splitNumber: 2, axisLabel: { show: false }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { show: false }, min: 0, }, ] : []), ], grid: showVolume ? [ { left: "12%", right: "10%", top: "15%", height: "50%", }, { left: "12%", right: "10%", top: "75%", height: "15%", }, ] : [ { left: "12%", right: "10%", top: "15%", bottom: "15%", }, ], series, title: { left: "center", text: title, }, }; return await generateChartImage( echartsOption, width, height, theme, outputType, "generate_candlestick_chart", ); }, }; - src/tools/candlestick.ts:22-45 (schema)Tool definition with name 'generate_candlestick_chart', description, and inputSchema defining data array (date, open, high, low, close, optional volume), height, showVolume, theme, title, width, and outputType.
export const generateCandlestickChartTool = { name: "generate_candlestick_chart", description: "Generate a candlestick chart for financial data visualization, such as, stock prices, cryptocurrency prices, or other OHLC (Open-High-Low-Close) data.", inputSchema: z.object({ data: z .array(data) .describe( "Data for candlestick chart, such as, [{ date: '2023-01-01', open: 100, high: 110, low: 95, close: 105, volume: 10000 }].", ) .nonempty({ message: "Candlestick chart data cannot be empty." }), height: HeightSchema, showVolume: z .boolean() .optional() .default(false) .describe( "Whether to show volume chart below candlestick. Default is false.", ), theme: ThemeSchema, title: TitleSchema, width: WidthSchema, outputType: OutputTypeSchema, }), - src/utils/schema.ts:16-49 (schema)Reusable Zod schemas (HeightSchema, WidthSchema, ThemeSchema, TitleSchema, OutputTypeSchema) used by the candlestick tool's input schema.
export const HeightSchema = z .number() .int() .positive() .optional() .default(600) .describe("Set the height of the chart, default is 600px."); export const ThemeSchema = z .enum(["default", "dark"]) .optional() .default("default") .describe("Set the theme for the chart, optional, default is 'default'."); export const OutputTypeSchema = z .enum(["png", "svg", "option"]) .optional() .default("png") .describe( "The output type of the diagram. Can be 'png', 'svg' or 'option'. Default is 'png', 'png' will return the rendered PNG image, 'svg' will return the rendered SVG string, and 'option' will return the valid ECharts option.", ); export const TitleSchema = z .string() .optional() .describe("Set the title of the chart."); export const WidthSchema = z .number() .int() .positive() .optional() .default(800) .describe("Set the width of the chart, default is 800px."); - src/tools/index.ts:20-39 (registration)The tool is registered in the exported tools array at line 34.
export const tools = [ generateEChartsTool, generateAreaChartTool, generateLineChartTool, generateBarChartTool, generatePieChartTool, generateRadarChartTool, generateScatterChartTool, generateSankeyChartTool, generateFunnelChartTool, generateGaugeChartTool, generateTreemapChartTool, generateSunburstChartTool, generateHeatmapChartTool, generateCandlestickChartTool, generateBoxplotChartTool, generateGraphChartTool, generateParallelChartTool, generateTreeChartTool, ]; - src/utils/imageHandler.ts:39-170 (helper)The generateChartImage helper function called by the handler. Renders the ECharts option to an image (PNG/SVG) or returns the option as text, with optional MinIO storage or Base64 fallback.
export async function generateChartImage( echartsOption: EChartsOption, width = 800, height = 600, theme: "default" | "dark" = "default", outputType: ImageOutputFormat = "png", toolName = "unknown", ): Promise<ImageHandlerResult> { // Debug logging if (process.env.DEBUG_MCP_ECHARTS) { console.error(`[DEBUG] ${toolName} generating chart:`, { width, height, theme, outputType, optionKeys: Object.keys(echartsOption), }); } try { // Render chart const result = await renderECharts( echartsOption, width, height, theme, outputType, ); // Determine output type const isImage = outputType !== "svg" && outputType !== "option"; if (!isImage) { // SVG or configuration options, return text directly const response = { content: [ { type: "text" as const, text: result as string, }, ], }; if (process.env.DEBUG_MCP_ECHARTS) { console.error(`[DEBUG] ${toolName} chart generated successfully:`, { contentType: "text", textLength: (result as string).length, }); } return response; } // PNG image type const buffer = result as Buffer; if (isMinIOConfigured()) { try { // Use MinIO storage, return URL const url = await storeBufferToMinIO(buffer, "png", "image/png"); const response = { content: [ { type: "text" as const, text: url, }, ], }; if (process.env.DEBUG_MCP_ECHARTS) { console.error(`[DEBUG] ${toolName} chart generated successfully:`, { contentType: "text", url: url, }); } return response; } catch (minioError) { // MinIO failed, log warning and fallback to Base64 if (process.env.DEBUG_MCP_ECHARTS) { console.error( `[DEBUG] ${toolName} MinIO storage failed, falling back to Base64:`, { error: minioError instanceof Error ? minioError.message : String(minioError), }, ); } // Continue to Base64 fallback below } } // Fallback to Base64 const base64Data = buffer.toString("base64"); const response = { content: [ { type: "image" as const, data: base64Data, mimeType: "image/png", }, ], }; if (process.env.DEBUG_MCP_ECHARTS) { console.error(`[DEBUG] ${toolName} chart generated successfully:`, { contentType: "image", dataLength: base64Data.length, }); } return response; } catch (error) { // Error logging if (process.env.DEBUG_MCP_ECHARTS) { console.error(`[DEBUG] ${toolName} chart generation failed:`, { error: error instanceof Error ? error.message : String(error), stack: error instanceof Error ? error.stack : undefined, }); } throw new Error( `Chart rendering failed: ${ error instanceof Error ? error.message : String(error) }`, ); } }