candlestick-chart-generator
Version:
A Node.js library for generating candlestick chart screenshots using financial data
137 lines (125 loc) • 3.19 kB
JavaScript
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");
Chart.register(...registerables);
Chart.register(
CandlestickController,
CandlestickElement,
OhlcController,
OhlcElement
);
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",
plugins: {
global: [],
},
});
}
/**
* 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;
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,
},
},
...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;