components/tanstack-charts/bar/candlestick.tsx
import { type ChartPoint, defineChart, link } from "@tanstack/charts";
import { motion } from "@tanstack/charts/motion";
import { tooltip } from "@tanstack/charts/tooltip";
import { Chart } from "@tanstack/react-charts/core";
import { useMemo } from "react";
import { scaleLinear, scaleUtc } from "d3-scale";
import { CandlestickChart as CandlestickIcon } from "lucide-react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
interface CandleDatum {
Date: Date;
Open: number;
High: number;
Low: number;
Close: number;
}
const motionRenderer = motion({
initial: "always",
transition: { type: "spring", stiffness: 170, damping: 18, mass: 1 },
});
function generateDemoData(): CandleDatum[] {
const baseDate = new Date(2025, 0, 1);
const results: CandleDatum[] = [];
let prevClose = 220;
for (let i = 0; i < 20; i++) {
const d = new Date(baseDate);
d.setDate(baseDate.getDate() + i);
const open = prevClose + Math.sin(i * 0.7) * 4;
const delta = Math.cos(i * 0.9) * 8 + (i % 2 === 0 ? 3 : -3);
const close = open + delta;
const high = Math.max(open, close) + Math.abs(Math.sin(i)) * 5;
const low = Math.min(open, close) - Math.abs(Math.cos(i)) * 5;
prevClose = close;
results.push({ Date: d, Open: open, High: high, Low: low, Close: close });
}
return results;
}
function shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {
if (points.length === 0) return { title: "", rows: [] };
const d = points[0].datum as CandleDatum;
if (!d || !d.Date) return { title: "", rows: [] };
const dateObj = d.Date instanceof Date ? d.Date : new Date(d.Date);
const dateStr = isNaN(dateObj.getTime())
? ""
: dateObj.toLocaleDateString("en-US", { month: "short", day: "numeric" });
const isGain = d.Close >= d.Open;
return {
title: dateStr,
rows: [
{ label: "Open", value: `$${d.Open.toFixed(2)}`, color: "var(--foreground)" },
{ label: "High", value: `$${d.High.toFixed(2)}`, color: "var(--foreground)" },
{ label: "Low", value: `$${d.Low.toFixed(2)}`, color: "var(--foreground)" },
{ label: "Close", value: `$${d.Close.toFixed(2)}`, color: isGain ? "var(--chart-1)" : "var(--chart-2)" },
],
};
}
export function Candlestick() {
const data = useMemo(() => generateDemoData(), []);
const { gains, losses } = useMemo(() => {
return {
gains: data.filter((d) => d.Close >= d.Open),
losses: data.filter((d) => d.Close < d.Open),
};
}, [data]);
const definition = useMemo(
() =>
defineChart(
{
renderer: motionRenderer,
marks: [
link(data, {
id: "candle-wicks",
x1: "Date",
y1: "Low",
x2: "Date",
y2: "High",
stroke: "var(--border)",
strokeWidth: 1.5,
}),
link(gains, {
id: "candle-gains",
x1: "Date",
y1: "Open",
x2: "Date",
y2: "Close",
stroke: "var(--chart-1)",
strokeWidth: 6,
}),
link(losses, {
id: "candle-losses",
x1: "Date",
y1: "Open",
x2: "Date",
y2: "Close",
stroke: "var(--chart-2)",
strokeWidth: 6,
}),
],
scales: {
x: {
scale: scaleUtc,
axis: {
line: false,
label: "Date",
ticks: {
size: 0,
padding: 10,
format: (d: any) => {
const dateObj = d instanceof Date ? d : new Date(d);
return isNaN(dateObj.getTime())
? ""
: dateObj.toLocaleDateString("en-US", { month: "short", day: "numeric" });
},
},
},
},
y: {
scale: scaleLinear().domain([190, 260]),
grid: true,
axis: {
line: false,
label: "Price ($)",
ticks: { size: 0 },
},
},
},
margin: { top: 24, right: 24, bottom: 32, left: 45 },
theme: {
foreground: "var(--muted-foreground)",
grid: "var(--border)",
background: "transparent",
},
},
{
focus: "group-x",
tooltip: {
use: tooltip,
className:
"font-sans shadow-none rounded-md bg-popover text-popover-foreground border p-2 text-xs",
anchor: "group-center",
placement: "auto",
content: (points) => shadcnTooltipContent(points),
},
},
),
[data, gains, losses],
);
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>Daily Asset Candlesticks</CardTitle>
<CardDescription>Daily Open-High-Low-Close price action candlesticks</CardDescription>
</CardHeader>
<CardContent>
<div className="h-[250px] w-full">
<Chart
definition={definition}
renderer={motionRenderer}
height={250}
ariaLabel="Daily Asset Candlesticks Chart"
/>
</div>
</CardContent>
<CardFooter className="flex-col items-start gap-2 text-sm">
<div className="flex items-center gap-2 leading-none font-medium">
Bullish candles (green) dominate recent 10 trading sessions{" "}
<CandlestickIcon className="h-4 w-4 text-emerald-500" />
</div>
<div className="text-muted-foreground leading-none">
Thin wicks indicate high/low range; thick bodies represent open/close spread
</div>
</CardFooter>
</Card>
);
}
export default Candlestick;