UNPKG

candlestick-chart-generator

Version:

A Node.js library for generating candlestick chart screenshots using financial data

132 lines (120 loc) 4.2 kB
const { ChartJSNodeCanvas } = require("chartjs-node-canvas"); const { Chart, registerables } = require("chart.js"); const { CandlestickController, CandlestickElement, OhlcController, OhlcElement } = require("chartjs-chart-financial"); const { adapter } = require("chartjs-adapter-date-fns"); // Register all standard Chart.js components Chart.register(...registerables); // Register the financial chart types Chart.register(CandlestickController, CandlestickElement, OhlcController, OhlcElement); // Set the date adapter Chart.defaults.adapters.date = adapter; class ChartRendererCanvas { constructor(width = 1200, height = 600) { this.width = width; this.height = height; this.chartJSNodeCanvas = new ChartJSNodeCanvas({ width: this.width, height: this.height, backgroundColour: "#131722", // Default background plugins: { global: [ // No global plugins needed for now ] } }); } /** * Render a candlestick chart and return as a buffer. * @param {Array} data - Chart data in OHLC format. * @param {Object} options - Chart rendering options. * @returns {Promise<Buffer>} Buffer containing the chart image. */ async renderChart(data, options = {}) { const { chartOptions = {} } = options; // Transform data for Chart.js financial charts const chartJsData = data.map(d => ({ x: new Date(d.time * 1000), o: d.open, h: d.high, l: d.low, c: d.close, })); const configuration = { type: "candlestick", data: { datasets: [{ label: "Candlestick", data: chartJsData, borderColor: "#d1d4dc", borderWidth: 1, candlestick: { up: { backgroundColor: "#26a69a", borderColor: "#26a69a", }, down: { backgroundColor: "#ef5350", borderColor: "#ef5350", }, }, }], }, options: { responsive: false, maintainAspectRatio: false, scales: { x: { type: "time", time: { unit: "day", tooltipFormat: "MMM D, YYYY", }, ticks: { color: "#d1d4dc", }, grid: { color: "rgba(42, 46, 57, 0.5)", }, }, y: { ticks: { color: "#d1d4dc", }, grid: { color: "rgba(42, 46, 57, 0.5)", }, }, }, plugins: { legend: { display: false, }, title: { display: false, }, }, // Merge custom chart options ...chartOptions, }, }; return await this.chartJSNodeCanvas.renderToBuffer(configuration); } /** * Set the width and height for the chart. * @param {number} width - Chart width in pixels. * @param {number} height - Chart height in pixels. */ setWidthAndHeight(width, height) { this.width = width; this.height = height; this.chartJSNodeCanvas = new ChartJSNodeCanvas({ width: this.width, height: this.height, backgroundColour: "#131722", plugins: { global: [] } }); } } module.exports = ChartRendererCanvas;