Skip to main content
Glama

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

TableJSON Schema
NameRequiredDescriptionDefault
dataYesData for candlestick chart, such as, [{ date: '2023-01-01', open: 100, high: 110, low: 95, close: 105, volume: 10000 }].
heightNoSet the height of the chart, default is 600px.
showVolumeNoWhether to show volume chart below candlestick. Default is false.
themeNoSet the theme for the chart, optional, default is 'default'.default
titleNoSet the title of the chart.
widthNoSet the width of the chart, default is 800px.
outputTypeNoThe 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

  • 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",
        );
      },
    };
  • 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,
      }),
  • 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.");
  • 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,
    ];
  • 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)
          }`,
        );
      }
    }
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. It only states the basic function without disclosing behavioral traits such as performance, limitations, side effects, or return format. This leaves the agent uninformed about important execution characteristics.

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, clear sentence that efficiently communicates the tool's purpose without unnecessary words. It is well-structured and front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the comprehensive input schema (100% coverage) and no output schema, the description fairly captures the tool's purpose. However, it could hint at the return values (PNG/SVG/option) which are defined only in the schema, but the absence is minor.

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 the description adds no additional meaning beyond what the schema already provides. The mention of 'OHLC data' is redundant with the schema's parameter descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool generates a candlestick chart specifically for financial OHLC data, such as stock or cryptocurrency prices. This clearly distinguishes it from sibling chart generators that serve different chart types.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for financial data but does not provide explicit guidance on when to use this tool versus alternatives like generate_line_chart or generate_bar_chart. No exclusions or when-not-to-use information is given.

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/hustcc/mcp-echarts'

If you have feedback or need assistance with the MCP directory API, please join our Discord server