{"spec_id":"candlestick-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// candlestick-basic: Basic Candlestick Chart\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 85/100 | Updated: 2026-10-24\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 { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst Y_PAD_SHARE = 0.08;\nconst BODY_WIDTH_SHARE = 0.64;\nconst X_TICK_COUNT = 12; // about this many labelled time ticks\nconst HEADER_H = 118;\n\n// Columns: set these to your data's column names\nconst DATE = \"Timestamp (UTC)\"; // role: date\nconst OPEN = \"BTC/USD open ($)\"; // role: open\nconst HIGH = \"BTC/USD high ($)\"; // role: high\nconst LOW = \"BTC/USD low ($)\"; // role: low\nconst CLOSE = \"BTC/USD close ($)\"; // role: close\nconst PRICE_LABEL = \"BTC/USD price ($)\"; // y-axis title: carries all four prices\n\n// Data: replace this block with your own records, one object per row\nconst data = (() => {\n  let seed = 42;\n  const periods = 48;\n  const start = new Date(Date.UTC(2024, 0, 8, 0, 0));\n  const rows: { [key: string]: string | number }[] = [];\n  let price = 42000;\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\n    const drift = (u1 - 0.5) * 260;\n    const c = Math.max(1000, o + drift);\n    const h = Math.max(o, c) + u2 * 140;\n    const l = Math.max(Math.min(o, c) - u3 * 140, 1);\n\n    const d = new Date(start.getTime() + i * 3600 * 1000);\n    rows.push({\n      [DATE]: d.toISOString(),\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    });\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]));\n  const label =\n    dt.getUTCHours() === 0\n      ? dt.toLocaleDateString(\"en-US\", {\n          month: \"short\",\n          day: \"numeric\",\n          timeZone: \"UTC\",\n        })\n      : dt.toLocaleTimeString(\"en-US\", {\n          hour: \"2-digit\",\n          minute: \"2-digit\",\n          hour12: false,\n          timeZone: \"UTC\",\n        });\n  return {\n    idx,\n    key: `${String(r[DATE])}-${idx}`,\n    date: dt,\n    label: `${label}#${idx}`,\n    displayLabel: label,\n    open: Number(r[OPEN]),\n    high: Number(r[HIGH]),\n    low: Number(r[LOW]),\n    close: Number(r[CLOSE]),\n  };\n});\n\nconst dateKeys = candles.map((c) => c.label);\nconst displayByKey = Object.fromEntries(\n  candles.map((c) => [c.label, c.displayLabel]),\n);\nconst tickEvery = Math.ceil(candles.length / X_TICK_COUNT);\nconst formatPrice = (v: number) => Math.round(v).toLocaleString(\"en-US\");\n\nconst yMinRaw = Math.min(...candles.map((c) => c.low));\nconst yMaxRaw = Math.max(...candles.map((c) => c.high));\nconst ySpan = yMaxRaw - yMinRaw || 1;\nconst yMin = yMinRaw - ySpan * Y_PAD_SHARE;\nconst yMax = yMaxRaw + ySpan * Y_PAD_SHARE;\n\nconst bullishCount = candles.filter((c) => c.close >= c.open).length;\nconst bearishCount = candles.length - bullishCount;\n\nconst firstDate = candles[0].date;\nconst lastDate = candles[candles.length - 1].date;\nconst rangeText = `${firstDate.toLocaleDateString(\"en-US\", { month: \"short\", day: \"numeric\", timeZone: \"UTC\" })} – ${lastDate.toLocaleDateString(\"en-US\", { month: \"short\", day: \"numeric\", year: \"numeric\", timeZone: \"UTC\" })}`;\n\nconst TITLE = \"candlestick-basic · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${candles.length} periods (${rangeText}) · Range ${formatPrice(yMinRaw)}–${formatPrice(yMaxRaw)}`;\n\nconst legendItems = [\n  {\n    label: `Bullish (close ≥ open, n=${bullishCount})`,\n    color: t.palette[0],\n  },\n  {\n    label: `Bearish (close < open, n=${bearishCount})`,\n    color: t.palette[4],\n  },\n];\n\nfunction CandlesticksLayer() {\n  const xScale = useXScale(\"time\");\n  const yScale = useYScale(\"price\");\n  const bw = xScale.bandwidth();\n  const bodyWidth = bw * BODY_WIDTH_SHARE;\n\n  return (\n    <g>\n      {candles.map((c) => {\n        const yOpen = yScale(c.open);\n        const yClose = yScale(c.close);\n        const yHigh = yScale(c.high);\n        const yLow = yScale(c.low);\n        const cx = xScale(c.label) + 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\n        return (\n          <g key={c.key}>\n            <line\n              x1={cx}\n              x2={cx}\n              y1={yHigh}\n              y2={yLow}\n              stroke={color}\n              strokeWidth={1.6}\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={0.32}\n              strokeWidth={1}\n              rx={0.5}\n            />\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const chartHeight = height - HEADER_H;\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: 8,\n          paddingTop: 6,\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            gap: 24,\n            alignItems: \"center\",\n            fontSize: 14,\n            color: t.inkSoft,\n          }}\n        >\n          {legendItems.map((item) => (\n            <div\n              key={item.label}\n              style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}\n            >\n              <span\n                style={{\n                  width: 14,\n                  height: 14,\n                  borderRadius: 3,\n                  background: item.color,\n                  display: \"inline-block\",\n                }}\n              />\n              <span style={{ color: t.ink, fontWeight: 500 }}>\n                {item.label}\n              </span>\n            </div>\n          ))}\n        </div>\n      </div>\n\n      <ChartsContainer\n        width={width}\n        height={chartHeight}\n        skipAnimation\n        series={[]}\n        margin={{ top: 20, right: 36, bottom: 20, left: 40 }}\n        xAxis={[\n          {\n            id: \"time\",\n            scaleType: \"band\",\n            data: dateKeys,\n            height: 64,\n            label: DATE,\n            valueFormatter: (v: string) => displayByKey[v],\n            tickLabelInterval: (_value: string, index: number) =>\n              index % tickEvery === 0,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"price\",\n            min: yMin,\n            max: yMax,\n            tickNumber: 7,\n            width: 96,\n            label: PRICE_LABEL,\n            valueFormatter: formatPrice,\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 />\n        <CandlesticksLayer />\n        <ChartsXAxis axisId=\"time\" />\n        <ChartsYAxis axisId=\"price\" />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}