{"spec_id":"candlestick-volume","library":"muix","language":"javascript","code":"// anyplot.ai\n// candlestick-volume: Stock Candlestick Chart with Volume\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 87/100 | Updated: 2026-10-24\nimport { useState } from \"react\";\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst PRICE_PAD_SHARE = 0.08;\nconst VOL_PAD_SHARE = 0.15;\nconst BODY_WIDTH_SHARE = 0.62;\nconst X_TICK_COUNT = 10; // about this many labelled date ticks, shared by both panes\nconst HEADER_H = 120;\nconst PANE_GAP = 10;\nconst PRICE_PANE_SHARE = 0.73; // share of the stacked plot-area height, not the container height\nconst MARGIN_LEFT = 24;\nconst MARGIN_RIGHT = 32;\nconst Y_AXIS_W = 96;\nconst X_AXIS_H = 60;\nconst PRICE_MARGIN_V = 16 + 6; // top + bottom margin of the price container\nconst VOLUME_MARGIN_V = 6 + 16; // top + bottom margin of the volume container\nconst PRICE_AXIS_LABEL = \"Price ($)\";\n\n// Columns: set these to your data's column names\nconst DATE = \"Trading date\"; // role: date\nconst OPEN = \"Open price ($)\"; // role: open\nconst HIGH = \"High price ($)\"; // role: high\nconst LOW = \"Low price ($)\"; // role: low\nconst CLOSE = \"Close price ($)\"; // role: close\nconst VOLUME = \"Volume\"; // role: volume\n\n// Data: replace this block with your own records, one object per row\nconst data = (() => {\n  let seed = 11;\n  const periods = 60;\n  const day = new Date(Date.UTC(2024, 1, 1));\n  const rows: { [key: string]: string | number }[] = [];\n  let price = 148;\n\n  for (let i = 0; i < periods; i += 1) {\n    const o = price;\n    seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n    const u1 = seed / 0x7fffffff;\n    seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n    const u2 = seed / 0x7fffffff;\n    seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n    const u3 = seed / 0x7fffffff;\n    seed = (seed * 1103515245 + 12345) & 0x7fffffff;\n    const u4 = seed / 0x7fffffff;\n\n    const drift = (u1 - 0.5) * 6.2;\n    const c = Math.max(20, o + drift);\n    const h = Math.max(o, c) + u2 * 2.4;\n    const l = Math.max(Math.min(o, c) - u3 * 2.4, 1);\n    const move = Math.abs(c - o) + (h - l);\n    const vol = Math.round(1.4e6 + move * 3.6e5 + u4 * 6e5);\n\n    // Markets close on weekends: advance to the next weekday\n    while (day.getUTCDay() === 0 || day.getUTCDay() === 6) {\n      day.setUTCDate(day.getUTCDate() + 1);\n    }\n    rows.push({\n      [DATE]: day.toISOString().split(\"T\")[0],\n      [OPEN]: Math.round(o * 100) / 100,\n      [HIGH]: Math.round(h * 100) / 100,\n      [LOW]: Math.round(l * 100) / 100,\n      [CLOSE]: Math.round(c * 100) / 100,\n      [VOLUME]: vol,\n    });\n    day.setUTCDate(day.getUTCDate() + 1);\n    price = c;\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst sorted = [...data].sort(\n  (a, b) =>\n    new Date(String(a[DATE])).getTime() - new Date(String(b[DATE])).getTime(),\n);\n\nconst candles = sorted.map((r, idx) => {\n  const dt = new Date(`${String(r[DATE])}T00:00:00Z`);\n  const shortDate = dt.toLocaleDateString(\"en-US\", {\n    month: \"short\",\n    day: \"numeric\",\n    timeZone: \"UTC\",\n  });\n  const fullDate = dt.toLocaleDateString(\"en-US\", {\n    month: \"short\",\n    day: \"numeric\",\n    year: \"numeric\",\n    timeZone: \"UTC\",\n  });\n  return {\n    idx,\n    key: `${String(r[DATE])}-${idx}`,\n    bandKey: `${shortDate}#${idx}`,\n    shortDate,\n    fullDate,\n    open: Number(r[OPEN]),\n    high: Number(r[HIGH]),\n    low: Number(r[LOW]),\n    close: Number(r[CLOSE]),\n    volume: Number(r[VOLUME]),\n  };\n});\n\nconst bandKeys = candles.map((c) => c.bandKey);\nconst shortDateByBand = Object.fromEntries(\n  candles.map((c) => [c.bandKey, c.shortDate]),\n);\nconst tickEvery = Math.ceil(candles.length / X_TICK_COUNT);\nconst showTick = (_v: string, idx: number) => idx % tickEvery === 0;\nconst formatPrice = (v: number) => v.toFixed(2);\nconst formatVolume = (v: number) => {\n  if (v === 0) return \"0\";\n  return v >= 1e6 ? `${(v / 1e6).toFixed(1)}M` : `${Math.round(v / 1e3)}K`;\n};\n\nconst priceMinRaw = Math.min(...candles.map((c) => c.low));\nconst priceMaxRaw = Math.max(...candles.map((c) => c.high));\nconst priceSpan = priceMaxRaw - priceMinRaw || 1;\nconst priceMin = priceMinRaw - priceSpan * PRICE_PAD_SHARE;\nconst priceMax = priceMaxRaw + priceSpan * PRICE_PAD_SHARE;\n\nconst volumeMaxRaw = Math.max(...candles.map((c) => c.volume)) || 1;\nconst volumeMax = volumeMaxRaw * (1 + VOL_PAD_SHARE);\n\nconst bullishCount = candles.filter((c) => c.close >= c.open).length;\nconst bearishCount = candles.length - bullishCount;\n\nconst TITLE = \"candlestick-volume · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${candles.length} periods (${candles[0].shortDate} – ${candles[candles.length - 1].fullDate}) · Price ${formatPrice(priceMinRaw)}–${formatPrice(priceMaxRaw)}`;\nconst BEAR_HATCH = `repeating-linear-gradient(135deg, color-mix(in srgb, ${t.ink} 38%, transparent) 0 1.5px, transparent 1.5px 5px)`;\n\nfunction CandlesticksLayer({ activeIdx }: { activeIdx: number | null }) {\n  const xScale = useXScale(\"xPrice\");\n  const yScale = useYScale(\"yPrice\");\n  const { top, height } = useDrawingArea();\n  const bw = xScale.bandwidth();\n  const bodyWidth = bw * BODY_WIDTH_SHARE;\n\n  return (\n    <g>\n      <defs>\n        <pattern\n          id=\"candle-bear-hatch\"\n          width={5}\n          height={5}\n          patternUnits=\"userSpaceOnUse\"\n          patternTransform=\"rotate(45)\"\n        >\n          <line\n            x1={0}\n            y1={0}\n            x2={0}\n            y2={5}\n            stroke={t.ink}\n            strokeOpacity={0.38}\n            strokeWidth={1.5}\n          />\n        </pattern>\n      </defs>\n      {activeIdx !== null && (\n        <line\n          x1={xScale(candles[activeIdx].bandKey) + bw / 2}\n          x2={xScale(candles[activeIdx].bandKey) + bw / 2}\n          y1={top}\n          y2={top + height}\n          stroke={t.inkSoft}\n          strokeWidth={1.5}\n          strokeDasharray=\"4 4\"\n          opacity={0.75}\n        />\n      )}\n      {candles.map((c) => {\n        const yOpen = yScale(c.open);\n        const yClose = yScale(c.close);\n        const cx = xScale(c.bandKey) + bw / 2;\n        const bullish = c.close >= c.open;\n        const color = bullish ? t.palette[0] : t.palette[4];\n        const bodyTop = Math.min(yOpen, yClose);\n        const bodyHeight = Math.max(Math.abs(yClose - yOpen), 2);\n        return (\n          <g key={c.key}>\n            <line\n              x1={cx}\n              x2={cx}\n              y1={yScale(c.high)}\n              y2={yScale(c.low)}\n              stroke={color}\n              strokeWidth={1.5}\n              strokeLinecap=\"round\"\n            />\n            <rect\n              x={cx - bodyWidth / 2}\n              y={bodyTop}\n              width={bodyWidth}\n              height={bodyHeight}\n              fill={color}\n              stroke={t.ink}\n              strokeOpacity={bullish ? 0.3 : 0.55}\n              strokeWidth={bullish ? 1 : 1.6}\n            />\n            {!bullish && (\n              <rect\n                x={cx - bodyWidth / 2}\n                y={bodyTop}\n                width={bodyWidth}\n                height={bodyHeight}\n                fill=\"url(#candle-bear-hatch)\"\n                pointerEvents=\"none\"\n              />\n            )}\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nfunction VolumeBarsLayer({ activeIdx }: { activeIdx: number | null }) {\n  const xScale = useXScale(\"xVolume\");\n  const yScale = useYScale(\"yVolume\");\n  const { top, height } = useDrawingArea();\n  const bw = xScale.bandwidth();\n  const barWidth = bw * BODY_WIDTH_SHARE;\n  const yZero = yScale(0);\n\n  return (\n    <g>\n      <defs>\n        <pattern\n          id=\"volume-bear-hatch\"\n          width={5}\n          height={5}\n          patternUnits=\"userSpaceOnUse\"\n          patternTransform=\"rotate(45)\"\n        >\n          <line\n            x1={0}\n            y1={0}\n            x2={0}\n            y2={5}\n            stroke={t.ink}\n            strokeOpacity={0.38}\n            strokeWidth={1.5}\n          />\n        </pattern>\n      </defs>\n      {activeIdx !== null && (\n        <line\n          x1={xScale(candles[activeIdx].bandKey) + bw / 2}\n          x2={xScale(candles[activeIdx].bandKey) + bw / 2}\n          y1={top}\n          y2={top + height}\n          stroke={t.inkSoft}\n          strokeWidth={1.5}\n          strokeDasharray=\"4 4\"\n          opacity={0.75}\n        />\n      )}\n      {candles.map((c) => {\n        const yTop = yScale(c.volume);\n        const bullish = c.close >= c.open;\n        const color = bullish ? t.palette[0] : t.palette[4];\n        const cx = xScale(c.bandKey) + bw / 2;\n        const barHeight = Math.max(yZero - yTop, 1.5);\n        return (\n          <g key={c.key}>\n            <rect\n              x={cx - barWidth / 2}\n              y={yTop}\n              width={barWidth}\n              height={barHeight}\n              fill={color}\n              fillOpacity={0.78}\n              stroke={bullish ? \"none\" : t.ink}\n              strokeOpacity={bullish ? 0 : 0.48}\n              strokeWidth={bullish ? 0 : 1.3}\n            />\n            {!bullish && (\n              <rect\n                x={cx - barWidth / 2}\n                y={yTop}\n                width={barWidth}\n                height={barHeight}\n                fill=\"url(#volume-bear-hatch)\"\n                pointerEvents=\"none\"\n              />\n            )}\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  // Cross-pane cursor and OHLCV readout: live while hovering in the HTML,\n  // absent from the static PNG, where nothing hovers.\n  const [hoverIdx, setHoverIdx] = useState<number | null>(null);\n\n  const { width, height } = window.ANYPLOT_SIZE;\n  const chartsHeight = height - HEADER_H;\n  // Split the plot areas (not the containers) so the volume pane's x-axis band\n  // and margins do not eat into its share\n  const plotAreaTotal =\n    chartsHeight - PANE_GAP - PRICE_MARGIN_V - VOLUME_MARGIN_V - X_AXIS_H;\n  const priceHeight =\n    Math.round(plotAreaTotal * PRICE_PANE_SHARE) + PRICE_MARGIN_V;\n  const volumeHeight = chartsHeight - PANE_GAP - priceHeight;\n\n  const plotLeft = MARGIN_LEFT + Y_AXIS_W;\n  const plotWidth = width - plotLeft - MARGIN_RIGHT;\n  const bandStep = plotWidth / candles.length;\n  const active = hoverIdx === null ? null : candles[hoverIdx];\n  const cursorX = hoverIdx === null ? 0 : plotLeft + (hoverIdx + 0.5) * bandStep;\n  const readoutOnRight = cursorX < plotLeft + plotWidth / 2;\n\n  return (\n    <div\n      style={{\n        width,\n        height,\n        background: t.pageBg,\n        fontFamily: \"Inter, system-ui, sans-serif\",\n        display: \"flex\",\n        flexDirection: \"column\",\n      }}\n    >\n      <div\n        style={{\n          height: HEADER_H,\n          display: \"flex\",\n          flexDirection: \"column\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 6,\n          paddingTop: 4,\n        }}\n      >\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink }}>\n          {TITLE}\n        </div>\n        <div style={{ fontSize: 15, color: t.inkSoft }}>{SUBTITLE}</div>\n        <div\n          style={{\n            display: \"flex\",\n            flexWrap: \"wrap\",\n            gap: 20,\n            alignItems: \"center\",\n            fontSize: 14,\n            color: t.inkSoft,\n          }}\n        >\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <span\n              style={{\n                width: 14,\n                height: 14,\n                borderRadius: 3,\n                background: t.palette[0],\n                display: \"inline-block\",\n              }}\n            />\n            <span style={{ color: t.ink, fontWeight: 500 }}>\n              Bullish (close ≥ open, n={bullishCount})\n            </span>\n          </div>\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n            <span\n              style={{\n                width: 14,\n                height: 14,\n                borderRadius: 3,\n                backgroundColor: t.palette[4],\n                backgroundImage: BEAR_HATCH,\n                border: `1.5px solid ${t.ink}`,\n                display: \"inline-block\",\n              }}\n            />\n            <span style={{ color: t.ink, fontWeight: 500 }}>\n              Bearish (close &lt; open, n={bearishCount})\n            </span>\n          </div>\n        </div>\n      </div>\n\n      <div\n        style={{ position: \"relative\" }}\n        onMouseMove={(event) => {\n          const rect = event.currentTarget.getBoundingClientRect();\n          const idx = Math.floor((event.clientX - rect.left - plotLeft) / bandStep);\n          setHoverIdx(idx >= 0 && idx < candles.length ? idx : null);\n        }}\n        onMouseLeave={() => setHoverIdx(null)}\n      >\n        <ChartsContainer\n          width={width}\n          height={priceHeight}\n          skipAnimation\n          series={[]}\n          margin={{\n            top: 16,\n            bottom: 6,\n            left: MARGIN_LEFT,\n            right: MARGIN_RIGHT,\n          }}\n          xAxis={[\n            {\n              id: \"xPrice\",\n              scaleType: \"band\",\n              data: bandKeys,\n              position: \"none\",\n              tickInterval: showTick,\n            },\n          ]}\n          yAxis={[\n            {\n              id: \"yPrice\",\n              min: priceMin,\n              max: priceMax,\n              tickNumber: 6,\n              width: Y_AXIS_W,\n              label: PRICE_AXIS_LABEL,\n              valueFormatter: (v: number) => v.toFixed(0),\n              tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n              labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n            },\n          ]}\n          sx={{\n            \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n            \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n            \"& .MuiChartsGrid-line\": {\n              stroke: t.grid,\n              opacity: 0.65,\n              strokeDasharray: \"3 4\",\n            },\n          }}\n        >\n          <ChartsGrid horizontal vertical />\n          <CandlesticksLayer activeIdx={hoverIdx} />\n          <ChartsYAxis axisId=\"yPrice\" />\n        </ChartsContainer>\n\n        <div\n          style={{\n            height: PANE_GAP,\n            display: \"flex\",\n            alignItems: \"center\",\n            marginLeft: plotLeft,\n            marginRight: MARGIN_RIGHT,\n          }}\n        >\n          <div style={{ flex: 1, height: 1, background: t.grid }} />\n        </div>\n\n        <ChartsContainer\n          width={width}\n          height={volumeHeight}\n          skipAnimation\n          series={[]}\n          margin={{\n            top: 6,\n            bottom: 16,\n            left: MARGIN_LEFT,\n            right: MARGIN_RIGHT,\n          }}\n          xAxis={[\n            {\n              id: \"xVolume\",\n              scaleType: \"band\",\n              data: bandKeys,\n              height: X_AXIS_H,\n              label: DATE,\n              valueFormatter: (v: string) => shortDateByBand[v],\n              tickInterval: showTick,\n              tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n              labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n            },\n          ]}\n          yAxis={[\n            {\n              id: \"yVolume\",\n              min: 0,\n              max: volumeMax,\n              tickNumber: 4,\n              width: Y_AXIS_W,\n              label: VOLUME,\n              valueFormatter: formatVolume,\n              tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n              labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n            },\n          ]}\n          sx={{\n            \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n            \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n            \"& .MuiChartsGrid-line\": {\n              stroke: t.grid,\n              opacity: 0.65,\n              strokeDasharray: \"3 4\",\n            },\n          }}\n        >\n          <ChartsGrid horizontal vertical />\n          <VolumeBarsLayer activeIdx={hoverIdx} />\n          <ChartsXAxis axisId=\"xVolume\" />\n          <ChartsYAxis axisId=\"yVolume\" />\n        </ChartsContainer>\n\n        {active && (\n          <div\n            style={{\n              position: \"absolute\",\n              top: 8,\n              left: readoutOnRight ? cursorX + 12 : undefined,\n              right: readoutOnRight ? undefined : width - cursorX + 12,\n              padding: \"6px 12px\",\n              borderRadius: 6,\n              background: t.elevatedBg,\n              border: `1px solid ${t.grid}`,\n              color: t.ink,\n              fontSize: 14,\n              whiteSpace: \"nowrap\",\n              pointerEvents: \"none\",\n            }}\n          >\n            <strong>{active.fullDate}</strong> · O {formatPrice(active.open)} · H{\" \"}\n            {formatPrice(active.high)} · L {formatPrice(active.low)} · C{\" \"}\n            {formatPrice(active.close)} · Vol {formatVolume(active.volume)}\n          </div>\n        )}\n      </div>\n    </div>\n  );\n}\n"}