Candlestick
ChartsFinancial candlestick OHLC chart.
Preview
Usage
example.jsx
import { Candlestick } from "@/components/ui/candlestick";
export default function Example() {
return <Candlestick />;
}Source Code
Copy this file into components/ui/candlestick.jsx in your project.
candlestick.jsx
"use client";
import { forwardRef } from "react";
import { cn } from "@/lib/utils";
const Candlestick = forwardRef(({ className, data = [], width = 500, height = 300, ...props }, ref) => {
const allVals = data.flatMap((d) => [d.open, d.close, d.high, d.low]);
const maxVal = Math.max(...allVals, 1);
const minVal = Math.min(...allVals, 0);
const range = maxVal - minVal || 1;
const padX = 40, padY = 20;
const chartW = width - padX - 10;
const chartH = height - padY * 2;
const candleW = Math.max(6, chartW / data.length - 4);
const yScale = (v) => padY + chartH - ((v - minVal) / range) * chartH;
return (
<div ref={ref} className={cn("inline-block", className)} {...props}>
<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
{data.map((d, i) => {
const x = padX + (i / (data.length || 1)) * chartW + candleW / 2;
const isUp = d.close >= d.open;
const bodyTop = yScale(Math.max(d.open, d.close));
const bodyBot = yScale(Math.min(d.open, d.close));
const bodyH = Math.max(1, bodyBot - bodyTop);
return (
<g key={i}>
<line x1={x} y1={yScale(d.high)} x2={x} y2={yScale(d.low)} stroke={isUp ? "#10b981" : "#ef4444"} strokeWidth="1" />
<rect x={x - candleW / 2} y={bodyTop} width={candleW} height={bodyH}
fill={isUp ? "#10b981" : "#ef4444"} rx="1"
/>
</g>
);
})}
</svg>
</div>
);
});
Candlestick.displayName = "Candlestick";
export { Candlestick };
Quick Install
Make sure you have the cn() utility set up. It requires clsx and tailwind-merge.
npm install clsx tailwind-merge