{"spec_id":"kagi-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// kagi-basic: Basic Kagi Chart\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/100 | Updated: 2026-11-08\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst REVERSAL_SHARE = 0.04; // a move of 4 % against the running extreme turns the line\nconst Y_PAD_SHARE = 0.06; // share of the price range added above and below the outermost turn\nconst X_PAD_LINES = 0.5; // half a column of room beside the first and the last vertical line\nconst YANG = \"Yang: thick, rising above the previous shoulder\";\nconst YIN = \"Yin: thin, falling below the previous waist\";\n\n// Columns: set these to your data's column names\nconst DATE = \"Trading date\"; // role: date\nconst CLOSE = \"Close (USD)\"; // role: close\n\n// Data: replace this block with your own records, one object per observation\n// 240 weekday closes of a mid-cap stock from 2 Jan 2024: a random walk of daily returns\n// with a mild upward drift and a daily volatility of 1.6 %.\nconst data = (() => {\n  let state = 42;\n  const rand = () => {\n    state = (state * 1664525 + 1013904223) % 4294967296;\n    return state / 4294967296;\n  };\n  const records: { [DATE]: string; [CLOSE]: number }[] = [];\n  const cursor = new Date(Date.UTC(2024, 0, 2));\n  let price = 180;\n  while (records.length < 240) {\n    if (cursor.getUTCDay() % 6 !== 0) {\n      if (records.length > 0) {\n        const z = Math.sqrt(-2 * Math.log(Math.max(rand(), 1e-9))) * Math.cos(2 * Math.PI * rand());\n        price *= 1 + 0.0006 + 0.016 * z;\n      }\n      records.push({ [DATE]: cursor.toISOString().slice(0, 10), [CLOSE]: Math.round(price * 100) / 100 });\n    }\n    cursor.setUTCDate(cursor.getUTCDate() + 1);\n  }\n  return records;\n})();\n\n// Plot: reads only data and the constants above\nconst rows = [...data].sort((a, b) => Date.parse(a[DATE]) - Date.parse(b[DATE]));\nconst closes = rows.map((d) => d[CLOSE]).filter((v) => v != null);\n\n// Turning points: the line extends while the price keeps its direction and turns only\n// after a move of REVERSAL_SHARE against the running extreme\nconst turns = [closes[0]];\nlet direction = 0;\nlet extreme = closes[0];\nfor (const price of closes.slice(1)) {\n  if (direction === 0) {\n    const change = (price - extreme) / extreme;\n    if (Math.abs(change) >= REVERSAL_SHARE) {\n      direction = Math.sign(change);\n      extreme = price;\n      turns.push(price);\n    }\n  } else if ((price - extreme) * direction > 0) {\n    extreme = price;\n    turns[turns.length - 1] = price;\n  } else if (Math.abs(price - extreme) / extreme >= REVERSAL_SHARE) {\n    direction = -direction;\n    extreme = price;\n    turns.push(price);\n  }\n}\nconst lineCount = turns.length - 1;\n\n// Path: vertical line k runs from turn k to turn k + 1 in column k, and a horizontal\n// shoulder or waist joins it to column k + 1. The line turns yang where a rise passes the\n// previous shoulder and yin where a fall passes the previous waist, so a vertical that\n// breaks out is split at that level.\nconst pathX = [0];\nconst pathY = [turns[0]];\nconst edgeYang: boolean[] = [];\nlet yang = turns[1] > turns[0];\nlet priorShoulder: number | null = null;\nlet priorWaist: number | null = null;\nfor (let k = 0; k < lineCount; k += 1) {\n  const from = turns[k];\n  const to = turns[k + 1];\n  const rising = to > from;\n  const level = rising ? priorShoulder : priorWaist;\n  if (level != null && yang !== rising && (rising ? to > level : to < level)) {\n    pathX.push(k);\n    pathY.push(level);\n    edgeYang.push(yang);\n    yang = rising;\n  }\n  pathX.push(k);\n  pathY.push(to);\n  edgeYang.push(yang);\n  if (rising) priorShoulder = to;\n  else priorWaist = to;\n  if (k < lineCount - 1) {\n    pathX.push(k + 1);\n    pathY.push(to);\n    edgeYang.push(yang);\n  }\n}\n\n// One series per state; a vertex carries a value when an edge of that state touches it, so\n// the thick and the thin line meet at every change\nconst yangY = pathY.map((y, i) => (edgeYang[i - 1] === true || edgeYang[i] === true ? y : null));\nconst yinY = pathY.map((y, i) => (edgeYang[i - 1] === false || edgeYang[i] === false ? y : null));\n\nconst yLow = Math.min(...turns);\nconst yHigh = Math.max(...turns);\nconst yPad = (yHigh - yLow) * Y_PAD_SHARE;\n\nconst dateFormat = new Intl.DateTimeFormat(\"en-US\", { month: \"short\", day: \"numeric\", year: \"numeric\", timeZone: \"UTC\" });\nconst TITLE = \"kagi-basic · javascript · muix · anyplot.ai\";\nconst SUBTITLE =\n  `${closes.length} closes, ${dateFormat.format(new Date(rows[0][DATE]))} – ` +\n  `${dateFormat.format(new Date(rows[rows.length - 1][DATE]))} · reversal amount ${REVERSAL_SHARE * 100} % · ` +\n  `${lineCount} vertical lines`;\nconst HEADER_H = 84;\nconst LEGEND_H = 48;\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <Box sx={{ width, height, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\", overflow: \"hidden\" }}>\n      <Box sx={{ height: HEADER_H, pt: \"14px\", textAlign: \"center\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.3 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, lineHeight: 1.6 }}>{SUBTITLE}</Typography>\n      </Box>\n      <LineChart\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        skipAnimation\n        grid={{ horizontal: true }}\n        margin={{ top: 16, right: 40, bottom: 8, left: 20 }}\n        axisHighlight={{ x: \"none\" }}\n        series={[\n          {\n            id: \"yang\",\n            data: yangY,\n            label: YANG,\n            color: t.palette[0],\n            curve: \"linear\",\n            showMark: false,\n            labelMarkType: \"line\",\n          },\n          {\n            id: \"yin\",\n            data: yinY,\n            label: YIN,\n            color: t.palette[4],\n            curve: \"linear\",\n            showMark: false,\n            labelMarkType: \"line\",\n          },\n        ]}\n        xAxis={[\n          {\n            data: pathX,\n            scaleType: \"linear\",\n            min: -X_PAD_LINES,\n            max: lineCount - 1 + X_PAD_LINES,\n            tickMinStep: 1,\n            valueFormatter: (v: number) => String(Math.round(v) + 1),\n            label: \"Kagi line (one column per reversal)\",\n            height: 64,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: yLow - yPad,\n            max: yHigh + yPad,\n            width: 84,\n            label: CLOSE,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"bottom\", horizontal: \"center\" },\n            sx: {\n              fontSize: 15,\n              color: t.ink,\n              gap: \"36px\",\n              pt: \"8px\",\n              \"& .MuiChartsLabelMark-line\": { width: 28, height: 10 },\n              '& [data-series=\"yang\"] path': { strokeWidth: 6 },\n              '& [data-series=\"yin\"] path': { strokeWidth: 2 },\n            },\n          },\n        }}\n        sx={{\n          '& .MuiLineChart-line[data-series=\"yang\"]': { strokeWidth: 6 },\n          '& .MuiLineChart-line[data-series=\"yin\"]': { strokeWidth: 2 },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid },\n        }}\n      />\n    </Box>\n  );\n}\n"}