{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "candlestick-chart",
  "title": "Candlestick Chart",
  "description": "A trading-style candlestick chart: OHLC candles with a volume panel, a moving average, 1M / 3M / 6M range tabs, a last-price marker, and a crosshair with price and date pills plus a live OHLC readout.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/candlestick-chart/candlestick-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport type ChartTheme = \"dark\" | \"light\";\n\nexport interface Candle {\n  /** Short date label, e.g. \"Mar 4\". */\n  label: string;\n  open: number;\n  high: number;\n  low: number;\n  close: number;\n  volume?: number;\n}\n\nexport interface CandlestickRange {\n  label: string;\n  /** How many of the latest candles this range shows. */\n  count: number;\n}\n\nexport interface CandlestickChartProps extends Omit<\n  React.ComponentPropsWithoutRef<\"div\">,\n  \"title\"\n> {\n  theme?: ChartTheme;\n  /** Ticker or instrument name. */\n  symbol?: string;\n  name?: string;\n  candles?: Candle[];\n  ranges?: CandlestickRange[];\n  /** Index into `ranges` to start on. */\n  defaultRange?: number;\n  /** Period of the moving average line; 0 hides it. */\n  movingAverage?: number;\n  showVolume?: boolean;\n  upColor?: string;\n  downColor?: string;\n  /** Height of the price panel, in px. */\n  height?: number;\n  formatPrice?: (value: number) => string;\n}\n\nconst PALETTES = {\n  dark: {\n    card: \"#0E0E0E\",\n    border: \"rgba(255,255,255,0.08)\",\n    text: \"#F4F5F7\",\n    sub: \"rgba(255,255,255,0.55)\",\n    grid: \"rgba(255,255,255,0.06)\",\n    axis: \"rgba(255,255,255,0.45)\",\n    tip: \"rgba(20,20,20,0.96)\",\n    tipBorder: \"rgba(255,255,255,0.12)\",\n    chip: \"rgba(255,255,255,0.06)\",\n    pill: \"#F4F5F7\",\n    pillText: \"#0E0E0E\",\n    ma: \"#F2A841\",\n    up: \"#2EE6A8\",\n    down: \"#FF5C6C\",\n  },\n  light: {\n    card: \"#FFFFFF\",\n    border: \"rgba(0,0,0,0.07)\",\n    text: \"#111317\",\n    sub: \"rgba(17,19,23,0.55)\",\n    grid: \"rgba(17,19,23,0.07)\",\n    axis: \"rgba(17,19,23,0.5)\",\n    tip: \"rgba(255,255,255,0.98)\",\n    tipBorder: \"rgba(0,0,0,0.08)\",\n    chip: \"rgba(0,0,0,0.05)\",\n    pill: \"#111317\",\n    pillText: \"#FFFFFF\",\n    ma: \"#D9822B\",\n    up: \"#0E9F6E\",\n    down: \"#E5484D\",\n  },\n};\n\nconst MONTHS = [\n  \"Jan\",\n  \"Feb\",\n  \"Mar\",\n  \"Apr\",\n  \"May\",\n  \"Jun\",\n  \"Jul\",\n  \"Aug\",\n  \"Sep\",\n  \"Oct\",\n  \"Nov\",\n  \"Dec\",\n];\n\n// Deterministic sample: ~6 months of weekday candles from a seeded random walk (same on server and client).\nfunction sampleCandles(): Candle[] {\n  let seed = 42;\n  const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;\n  const out: Candle[] = [];\n  let price = 142;\n  const day = new Date(Date.UTC(2025, 4, 1));\n  while (out.length < 130) {\n    const dow = day.getUTCDay();\n    if (dow !== 0 && dow !== 6) {\n      const drift = 0.2 + Math.sin(out.length / 11) * 0.42;\n      const open = price;\n      const close = Math.max(20, open + drift + (rnd() - 0.5) * 4.2);\n      const high = Math.max(open, close) + rnd() * 2.2;\n      const low = Math.min(open, close) - rnd() * 2.2;\n      const volume = Math.round(\n        (18 + rnd() * 22 + Math.abs(close - open) * 6) * 1e5,\n      );\n      out.push({\n        label: `${MONTHS[day.getUTCMonth()]} ${day.getUTCDate()}`,\n        open: +open.toFixed(2),\n        high: +high.toFixed(2),\n        low: +low.toFixed(2),\n        close: +close.toFixed(2),\n        volume,\n      });\n      price = close;\n    }\n    day.setUTCDate(day.getUTCDate() + 1);\n  }\n  return out;\n}\n\nconst DEFAULT_CANDLES = sampleCandles();\nconst DEFAULT_RANGES: CandlestickRange[] = [\n  { label: \"1M\", count: 22 },\n  { label: \"3M\", count: 64 },\n  { label: \"6M\", count: 130 },\n];\n\nconst compact = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(0);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(entry.contentRect.width),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\n/** 0 → 1 (linear) once the element scrolls into view, and again whenever `key` changes. */\nfunction useReveal(\n  ref: React.RefObject<HTMLElement | null>,\n  reduce: boolean,\n  key: unknown,\n  duration = 900,\n) {\n  const [t, setT] = React.useState(0);\n  const seen = React.useRef(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el || reduce) return;\n    let raf = 0;\n    const run = () => {\n      const start = performance.now();\n      const tick = (now: number) => {\n        const k = Math.min(1, (now - start) / duration);\n        setT(k);\n        if (k < 1) raf = requestAnimationFrame(tick);\n      };\n      raf = requestAnimationFrame(tick);\n    };\n    if (seen.current) {\n      run();\n      return () => cancelAnimationFrame(raf);\n    }\n    const io = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry.isIntersecting) return;\n        io.disconnect();\n        seen.current = true;\n        run();\n      },\n      { threshold: 0.2 },\n    );\n    io.observe(el);\n    return () => {\n      io.disconnect();\n      cancelAnimationFrame(raf);\n    };\n  }, [ref, reduce, key, duration]);\n  return reduce ? 1 : t;\n}\n\nfunction niceTicks(min: number, max: number, count = 5) {\n  const span = Math.max(1e-9, max - min);\n  const raw = span / count;\n  const mag = Math.pow(10, Math.floor(Math.log10(raw)));\n  const step =\n    [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? 10 * mag;\n  const out: number[] = [];\n  for (let v = Math.ceil(min / step) * step; v <= max; v += step)\n    out.push(+v.toFixed(6));\n  return out;\n}\n\nconst M = { top: 10, right: 62, left: 8 };\n\nexport function CandlestickChart({\n  theme = \"dark\",\n  symbol = \"NRTH\",\n  name = \"Northwind Labs\",\n  candles = DEFAULT_CANDLES,\n  ranges = DEFAULT_RANGES,\n  defaultRange = 1,\n  movingAverage = 20,\n  showVolume = true,\n  upColor,\n  downColor,\n  height = 260,\n  formatPrice = (v) => `$${v.toFixed(2)}`,\n  className,\n  style,\n  ...props\n}: CandlestickChartProps) {\n  const pal = PALETTES[theme];\n  const up = upColor ?? pal.up;\n  const down = downColor ?? pal.down;\n  const reduce = useReducedMotion();\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const width = useWidth(plotRef);\n  const [range, setRange] = React.useState(\n    Math.min(defaultRange, ranges.length - 1),\n  );\n  const reveal = useReveal(plotRef, reduce, range);\n  const [active, setActive] = React.useState<number | null>(null);\n  const [crossY, setCrossY] = React.useState<number | null>(null);\n\n  // The moving average needs history from before the visible window, so compute it on the full series.\n  const ma = React.useMemo(() => {\n    if (!movingAverage) return [] as (number | null)[];\n    let sum = 0;\n    return candles.map((c, i) => {\n      sum += c.close;\n      if (i >= movingAverage) sum -= candles[i - movingAverage].close;\n      return i >= movingAverage - 1 ? sum / movingAverage : null;\n    });\n  }, [candles, movingAverage]);\n\n  const count = Math.min(\n    candles.length,\n    ranges[range]?.count ?? candles.length,\n  );\n  const start = candles.length - count;\n  const view = candles.slice(start);\n  const viewMa = ma.slice(start);\n  const volH = showVolume ? Math.round(height * 0.24) : 0;\n  const gap = showVolume ? 14 : 0;\n  const plotW = Math.max(0, width - M.left - M.right);\n  const slot = count ? plotW / count : 0;\n  const bodyW = Math.max(1.5, Math.min(14, slot * 0.64));\n  const xAt = (i: number) => M.left + slot * (i + 0.5);\n  const lo = Math.min(\n    ...view.map((c) => c.low),\n    ...viewMa.filter((v): v is number => v !== null),\n  );\n  const hi = Math.max(\n    ...view.map((c) => c.high),\n    ...viewMa.filter((v): v is number => v !== null),\n  );\n  const pad = (hi - lo) * 0.08;\n  const pMin = lo - pad;\n  const pMax = hi + pad;\n  const yAt = (v: number) =>\n    M.top + height - ((v - pMin) / (pMax - pMin)) * height;\n  const priceAt = (y: number) =>\n    pMin + ((M.top + height - y) / height) * (pMax - pMin);\n  const vMax = Math.max(1, ...view.map((c) => c.volume ?? 0));\n  const volTop = M.top + height + gap;\n  const totalH = volTop + volH + 26;\n  const ticks = niceTicks(pMin, pMax, 6);\n  const every = Math.max(1, Math.ceil(70 / Math.max(1, slot)));\n\n  const last = view[view.length - 1];\n  const first = view[0];\n  const change = last && first ? last.close - first.open : 0;\n  const changePct = first ? (change / first.open) * 100 : 0;\n  const maPath = viewMa\n    .map((v, i) =>\n      v === null ? null : `${xAt(i).toFixed(1)},${yAt(v).toFixed(1)}`,\n    )\n    .reduce((d, p) => (p === null ? d : `${d}${d ? \"L\" : \"M\"}${p}`), \"\");\n\n  const pick = (clientX: number, clientY: number) => {\n    const r = plotRef.current?.getBoundingClientRect();\n    if (!r || !count) return;\n    const i = Math.floor((clientX - r.left - M.left) / Math.max(1, slot));\n    const y = clientY - r.top;\n    setActive(i >= 0 && i < count ? i : null);\n    setCrossY(y >= M.top && y <= M.top + height ? y : null);\n  };\n  const onKey = (event: React.KeyboardEvent) => {\n    if (!count) return;\n    if (event.key === \"ArrowRight\" || event.key === \"ArrowLeft\") {\n      event.preventDefault();\n      const dir = event.key === \"ArrowRight\" ? 1 : -1;\n      setCrossY(null);\n      setActive((a) =>\n        Math.max(\n          0,\n          Math.min(count - 1, a === null ? (dir > 0 ? 0 : count - 1) : a + dir),\n        ),\n      );\n    } else if (event.key === \"Home\") setActive(0);\n    else if (event.key === \"End\") setActive(count - 1);\n    else if (event.key === \"Escape\") setActive(null);\n  };\n\n  const shown = active !== null ? view[active] : last;\n  const shownChange = shown ? shown.close - shown.open : 0;\n  const tipX = active !== null ? xAt(active) : 0;\n  const summary = `${symbol} candlestick chart, ${ranges[range]?.label}: from ${formatPrice(first?.open ?? 0)} on ${first?.label} to ${formatPrice(last?.close ?? 0)} on ${last?.label}, ${changePct >= 0 ? \"up\" : \"down\"} ${Math.abs(changePct).toFixed(1)}%. High ${formatPrice(hi)}, low ${formatPrice(lo)}.`;\n\n  return (\n    <div\n      className={cn(\n        \"w-full overflow-hidden rounded-[20px] p-5 sm:p-7\",\n        className,\n      )}\n      style={{\n        background: pal.card,\n        border: `1px solid ${pal.border}`,\n        color: pal.text,\n        fontFamily: \"Inter, -apple-system, BlinkMacSystemFont, sans-serif\",\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-4\">\n        <div className=\"min-w-0\">\n          <p\n            className=\"flex items-center gap-2 text-[13px]\"\n            style={{ color: pal.sub }}\n          >\n            <span\n              className=\"rounded-md px-1.5 py-0.5 font-mono text-[11px] font-semibold\"\n              style={{ background: pal.chip, color: pal.text }}\n            >\n              {symbol}\n            </span>\n            {name}\n          </p>\n          <p className=\"mt-2 flex items-baseline gap-2.5\">\n            <span className=\"text-[28px] leading-none font-semibold tracking-[-0.03em] tabular-nums\">\n              {formatPrice(last?.close ?? 0)}\n            </span>\n            <span\n              className=\"text-[13px] font-medium tabular-nums\"\n              style={{ color: change >= 0 ? up : down }}\n            >\n              {change >= 0 ? \"+\" : \"−\"}\n              {formatPrice(Math.abs(change))} ({changePct >= 0 ? \"+\" : \"−\"}\n              {Math.abs(changePct).toFixed(2)}%)\n            </span>\n            <span className=\"text-[12px]\" style={{ color: pal.sub }}>\n              {ranges[range]?.label}\n            </span>\n          </p>\n        </div>\n        <div\n          role=\"radiogroup\"\n          aria-label=\"Range\"\n          className=\"flex rounded-full p-0.5 text-[11.5px] font-medium\"\n          style={{ background: pal.chip }}\n        >\n          {ranges.map((r, i) => (\n            <button\n              key={r.label}\n              type=\"button\"\n              role=\"radio\"\n              aria-checked={range === i}\n              onClick={() => {\n                setActive(null);\n                setRange(i);\n              }}\n              className=\"cursor-pointer rounded-full px-3 py-1 transition-colors\"\n              style={{\n                background: range === i ? pal.card : \"transparent\",\n                color: range === i ? pal.text : pal.sub,\n                boxShadow: range === i ? \"0 1px 2px rgba(0,0,0,.2)\" : \"none\",\n              }}\n            >\n              {r.label}\n            </button>\n          ))}\n        </div>\n      </div>\n\n      <div\n        className=\"mt-4 flex flex-wrap gap-x-4 gap-y-1 font-mono text-[11.5px] tabular-nums\"\n        style={{ color: pal.sub }}\n      >\n        <span style={{ color: pal.text }}>{shown?.label}</span>\n        {shown &&\n          (\n            [\n              [\"O\", shown.open],\n              [\"H\", shown.high],\n              [\"L\", shown.low],\n              [\"C\", shown.close],\n            ] as const\n          ).map(([k, v]) => (\n            <span key={k}>\n              {k}{\" \"}\n              <span style={{ color: shownChange >= 0 ? up : down }}>\n                {v.toFixed(2)}\n              </span>\n            </span>\n          ))}\n        {movingAverage > 0 && (\n          <span>\n            <span style={{ color: pal.ma }}>MA {movingAverage}</span>{\" \"}\n            {(active !== null\n              ? viewMa[active]\n              : viewMa[viewMa.length - 1]\n            )?.toFixed(2) ?? \"–\"}\n          </span>\n        )}\n        {showVolume && shown?.volume !== undefined && (\n          <span>Vol {compact.format(shown.volume)}</span>\n        )}\n      </div>\n\n      <div\n        ref={plotRef}\n        role=\"img\"\n        aria-label={summary}\n        tabIndex={0}\n        onKeyDown={onKey}\n        onPointerMove={(e) => pick(e.clientX, e.clientY)}\n        onPointerDown={(e) => pick(e.clientX, e.clientY)}\n        onPointerLeave={(e) => {\n          if (e.pointerType !== \"mouse\") return;\n          setActive(null);\n          setCrossY(null);\n        }}\n        onBlur={() => setActive(null)}\n        className=\"relative mt-3 w-full cursor-crosshair rounded-lg outline-none focus-visible:ring-2\"\n        style={{ height: totalH }}\n      >\n        {width > 0 && (\n          <svg\n            width={width}\n            height={totalH}\n            className=\"block overflow-visible\"\n            aria-hidden=\"true\"\n          >\n            {ticks.map((t) => (\n              <g key={t}>\n                <line\n                  x1={M.left}\n                  x2={M.left + plotW}\n                  y1={yAt(t)}\n                  y2={yAt(t)}\n                  stroke={pal.grid}\n                />\n                <text\n                  x={M.left + plotW + 10}\n                  y={yAt(t) + 4}\n                  fontSize={11}\n                  fill={pal.axis}\n                  className=\"tabular-nums\"\n                >\n                  {t.toFixed(t < 10 ? 2 : 0)}\n                </text>\n              </g>\n            ))}\n            {showVolume && (\n              <line\n                x1={M.left}\n                x2={M.left + plotW}\n                y1={volTop + volH}\n                y2={volTop + volH}\n                stroke={pal.grid}\n              />\n            )}\n\n            {active !== null && (\n              <g stroke={pal.axis} strokeDasharray=\"3 3\" strokeWidth={1}>\n                <line x1={tipX} x2={tipX} y1={M.top} y2={volTop + volH} />\n                {crossY !== null && (\n                  <line\n                    x1={M.left}\n                    x2={M.left + plotW}\n                    y1={crossY}\n                    y2={crossY}\n                  />\n                )}\n              </g>\n            )}\n\n            {view.map((c, i) => {\n              // Candles appear left to right, each growing out of its open price.\n              const k = Math.min(\n                1,\n                Math.max(0, reveal * 1.5 - (i / count) * 0.5),\n              );\n              const e = 1 - Math.pow(1 - k, 3);\n              const isUp = c.close >= c.open;\n              const color = isUp ? up : down;\n              const top = yAt(\n                c.open + (Math.max(c.open, c.close) - c.open) * e,\n              );\n              const bot = yAt(\n                c.open + (Math.min(c.open, c.close) - c.open) * e,\n              );\n              const x = xAt(i);\n              const dim = active !== null && active !== i;\n              return (\n                <g key={c.label + i} opacity={k <= 0 ? 0 : dim ? 0.55 : 1}>\n                  <line\n                    x1={x}\n                    x2={x}\n                    y1={yAt(c.open + (c.high - c.open) * e)}\n                    y2={yAt(c.open + (c.low - c.open) * e)}\n                    stroke={color}\n                    strokeWidth={1}\n                  />\n                  <rect\n                    x={x - bodyW / 2}\n                    y={top}\n                    width={bodyW}\n                    height={Math.max(1, bot - top)}\n                    rx={Math.min(1.5, bodyW / 4)}\n                    fill={isUp && theme === \"dark\" ? pal.card : color}\n                    stroke={color}\n                    strokeWidth={isUp && theme === \"dark\" ? 1.2 : 0}\n                  />\n                  {showVolume && c.volume !== undefined && (\n                    <rect\n                      x={x - bodyW / 2}\n                      y={volTop + volH - (c.volume / vMax) * volH * e}\n                      width={bodyW}\n                      height={(c.volume / vMax) * volH * e}\n                      fill={color}\n                      fillOpacity={0.35}\n                    />\n                  )}\n                </g>\n              );\n            })}\n\n            {movingAverage > 0 && maPath && (\n              <path\n                d={maPath}\n                fill=\"none\"\n                stroke={pal.ma}\n                strokeWidth={1.6}\n                pathLength={1}\n                strokeDasharray=\"1 1\"\n                strokeDashoffset={1 - reveal}\n                strokeLinejoin=\"round\"\n              />\n            )}\n\n            {/* Last price marker on the axis. */}\n            {last && (\n              <g>\n                <line\n                  x1={M.left}\n                  x2={M.left + plotW}\n                  y1={yAt(last.close)}\n                  y2={yAt(last.close)}\n                  stroke={change >= 0 ? up : down}\n                  strokeDasharray=\"1 3\"\n                  strokeOpacity={0.8}\n                />\n                <rect\n                  x={M.left + plotW + 4}\n                  y={yAt(last.close) - 9}\n                  width={54}\n                  height={18}\n                  rx={4}\n                  fill={last.close >= last.open ? up : down}\n                />\n                <text\n                  x={M.left + plotW + 31}\n                  y={yAt(last.close) + 4}\n                  textAnchor=\"middle\"\n                  fontSize={10.5}\n                  fontWeight={700}\n                  fill={theme === \"dark\" ? \"#0E0E0E\" : \"#FFFFFF\"}\n                  className=\"tabular-nums\"\n                >\n                  {last.close.toFixed(2)}\n                </text>\n              </g>\n            )}\n\n            {active !== null && crossY !== null && (\n              <g>\n                <rect\n                  x={M.left + plotW + 4}\n                  y={crossY - 9}\n                  width={54}\n                  height={18}\n                  rx={4}\n                  fill={pal.pill}\n                />\n                <text\n                  x={M.left + plotW + 31}\n                  y={crossY + 4}\n                  textAnchor=\"middle\"\n                  fontSize={10.5}\n                  fontWeight={600}\n                  fill={pal.pillText}\n                  className=\"tabular-nums\"\n                >\n                  {priceAt(crossY).toFixed(2)}\n                </text>\n              </g>\n            )}\n\n            {view.map((c, i) =>\n              i % every === Math.floor(every / 2) ? (\n                <text\n                  key={`l${i}`}\n                  x={xAt(i)}\n                  y={totalH - 8}\n                  textAnchor=\"middle\"\n                  fontSize={11}\n                  fill={pal.axis}\n                >\n                  {c.label}\n                </text>\n              ) : null,\n            )}\n            {active !== null && (\n              <g>\n                <rect\n                  x={tipX - 30}\n                  y={totalH - 22}\n                  width={60}\n                  height={18}\n                  rx={4}\n                  fill={pal.pill}\n                />\n                <text\n                  x={tipX}\n                  y={totalH - 9}\n                  textAnchor=\"middle\"\n                  fontSize={10.5}\n                  fontWeight={600}\n                  fill={pal.pillText}\n                >\n                  {view[active].label}\n                </text>\n              </g>\n            )}\n          </svg>\n        )}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}