{"spec_id":"point-and-figure-basic","library":"muix","language":"javascript","code":"// anyplot.ai\n// point-and-figure-basic: Point and Figure Chart\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 86/100 | Updated: 2026-10-24\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\nimport { Box, Typography } from \"@mui/material\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"point-and-figure-basic · javascript · muix · anyplot.ai\";\nconst X_TITLE = \"Column (price reversal, not time)\";\nconst REVERSAL_BOXES = 3;\nconst MIN_TREND_SPAN = 2;\nconst Y_PAD_BOXES = 2;\nconst TICK_EVERY_N_COLS = 5;\n\nconst RISING_SYMBOL = \"X\";\nconst FALLING_SYMBOL = \"O\";\nconst RISING_LABEL = \"Rising column\";\nconst FALLING_LABEL = \"Falling column\";\nconst SUPPORT_LABEL = \"Support\";\nconst RESISTANCE_LABEL = \"Resistance\";\n\n// Columns: set these to your data's column names\nconst SESSION = \"Trading session\"; // role: date\nconst CLOSE = \"Close (USD)\"; // role: close\n\n// Data: replace this block with your own records\nconst NUM_SESSIONS = 360;\nconst INITIAL_PRICE = 148;\nconst MIN_PRICE_FLOOR = 60;\nconst DRIFT_STEP = 0.01;\nconst VOLATILITY_STEP = 4.3;\nconst BOX_SIZE = 1.5;\n\nconst data: Array<Record<string, number>> = [];\nlet lcgState = 42 >>> 0;\nlet runningPrice = INITIAL_PRICE;\nfor (let session = 1; session <= NUM_SESSIONS; session += 1) {\n  lcgState = (Math.imul(lcgState, 1664525) + 1013904223) >>> 0;\n  const randUnit = lcgState / 4294967296;\n  runningPrice = Math.max(\n    MIN_PRICE_FLOOR,\n    runningPrice + DRIFT_STEP + (randUnit - 0.5) * VOLATILITY_STEP,\n  );\n  data.push({\n    [SESSION]: session,\n    [CLOSE]: Math.round(runningPrice * 100) / 100,\n  });\n}\n\n// Plot: reads only data and the constants above\nconst sortedRows = [...data].sort((a, b) => Number(a[SESSION]) - Number(b[SESSION]));\n\ninterface PnfColumn {\n  direction: string;\n  boxes: number[];\n}\n\nconst columns: PnfColumn[] = [];\nlet boxIndex = Math.round(Number(sortedRows[0][CLOSE]) / BOX_SIZE);\nlet direction: string | null = null;\nlet boxesInColumn: number[] = [boxIndex];\n\nfor (let i = 1; i < sortedRows.length; i += 1) {\n  const nextBox = Math.round(Number(sortedRows[i][CLOSE]) / BOX_SIZE);\n  if (direction === null) {\n    if (nextBox > boxIndex) {\n      direction = RISING_SYMBOL;\n      for (let b = boxIndex + 1; b <= nextBox; b += 1) boxesInColumn.push(b);\n      boxIndex = nextBox;\n    } else if (nextBox < boxIndex) {\n      direction = FALLING_SYMBOL;\n      for (let b = boxIndex - 1; b >= nextBox; b -= 1) boxesInColumn.push(b);\n      boxIndex = nextBox;\n    }\n    continue;\n  }\n  if (direction === RISING_SYMBOL) {\n    if (nextBox > boxIndex) {\n      for (let b = boxIndex + 1; b <= nextBox; b += 1) boxesInColumn.push(b);\n      boxIndex = nextBox;\n    } else if (nextBox <= boxIndex - REVERSAL_BOXES) {\n      columns.push({ direction, boxes: boxesInColumn });\n      direction = FALLING_SYMBOL;\n      boxesInColumn = [];\n      for (let b = boxIndex - 1; b >= nextBox; b -= 1) boxesInColumn.push(b);\n      boxIndex = nextBox;\n    }\n  } else if (nextBox < boxIndex) {\n    for (let b = boxIndex - 1; b >= nextBox; b -= 1) boxesInColumn.push(b);\n    boxIndex = nextBox;\n  } else if (nextBox >= boxIndex + REVERSAL_BOXES) {\n    columns.push({ direction, boxes: boxesInColumn });\n    direction = RISING_SYMBOL;\n    boxesInColumn = [];\n    for (let b = boxIndex + 1; b <= nextBox; b += 1) boxesInColumn.push(b);\n    boxIndex = nextBox;\n  }\n}\ncolumns.push({ direction: String(direction), boxes: boxesInColumn });\n\nconst allBoxes = columns.flatMap((column) => column.boxes);\nconst minBox = Math.min(...allBoxes);\nconst maxBox = Math.max(...allBoxes);\nconst yMinBox = minBox - Y_PAD_BOXES;\nconst yMaxBox = maxBox + Y_PAD_BOXES;\nconst columnIndices = columns.map((_, index) => index + 1);\n\n// Box lattice: one horizontal rule between every pair of price rows\nconst gridRows: number[] = [];\nfor (let box = yMinBox; box < yMaxBox; box += 1) {\n  gridRows.push(box + 0.5);\n}\n\ninterface TrendLine {\n  startIndex: number;\n  startBox: number;\n  endIndex: number;\n  endBox: number;\n}\n\nconst supportLines: TrendLine[] = [];\nconst resistanceLines: TrendLine[] = [];\nfor (let i = 1; i < columns.length; i += 1) {\n  const column = columns[i];\n  const prevColumn = columns[i - 1];\n  if (column.direction === RISING_SYMBOL && prevColumn.direction === FALLING_SYMBOL) {\n    // Drawn one box below the low so the line runs through empty boxes\n    const startBox = Math.min(...column.boxes) - 1;\n    let endIndex = i;\n    for (let j = i + 1; j < columns.length; j += 1) {\n      const projected = startBox + (j - i);\n      if (columns[j].direction === FALLING_SYMBOL && Math.min(...columns[j].boxes) <= projected)\n        break;\n      endIndex = j;\n    }\n    if (endIndex - i >= MIN_TREND_SPAN) {\n      supportLines.push({ startIndex: i, startBox, endIndex, endBox: startBox + (endIndex - i) });\n    }\n  }\n  if (column.direction === FALLING_SYMBOL && prevColumn.direction === RISING_SYMBOL) {\n    // Drawn one box above the high so the line runs through empty boxes\n    const startBox = Math.max(...column.boxes) + 1;\n    let endIndex = i;\n    for (let j = i + 1; j < columns.length; j += 1) {\n      const projected = startBox - (j - i);\n      if (columns[j].direction === RISING_SYMBOL && Math.max(...columns[j].boxes) >= projected)\n        break;\n      endIndex = j;\n    }\n    if (endIndex - i >= MIN_TREND_SPAN) {\n      resistanceLines.push({\n        startIndex: i,\n        startBox,\n        endIndex,\n        endBox: startBox - (endIndex - i),\n      });\n    }\n  }\n}\n\nconst risingColor = t.palette[0];\nconst fallingColor = t.palette[4];\n\nfunction PointAndFigureOverlay() {\n  const xScale = useXScale(\"columns\") as unknown as ((c: number) => number) & {\n    bandwidth: () => number;\n    range: () => [number, number];\n  };\n  const yScale = useYScale(\"price\") as unknown as (v: number) => number;\n\n  const [left, right] = xScale.range();\n  const half = xScale.bandwidth() / 2;\n  const rowHeight = Math.abs(yScale(1) - yScale(0));\n  const glyphFontSize = Math.max(14, Math.min(xScale.bandwidth() * 0.62, rowHeight * 0.82, 22));\n\n  return (\n    <g>\n      {gridRows.map((box) => (\n        <line\n          key={`grid-${box}`}\n          x1={left}\n          x2={right}\n          y1={yScale(box)}\n          y2={yScale(box)}\n          stroke={t.grid}\n          strokeWidth={1}\n        />\n      ))}\n      {supportLines.map((line, index) => (\n        <line\n          key={`support-${index}`}\n          x1={xScale(line.startIndex + 1) + half}\n          y1={yScale(line.startBox)}\n          x2={xScale(line.endIndex + 1) + half}\n          y2={yScale(line.endBox)}\n          stroke={risingColor}\n          strokeWidth={1.5}\n          strokeDasharray=\"7 4\"\n          strokeOpacity={0.6}\n        />\n      ))}\n      {resistanceLines.map((line, index) => (\n        <line\n          key={`resistance-${index}`}\n          x1={xScale(line.startIndex + 1) + half}\n          y1={yScale(line.startBox)}\n          x2={xScale(line.endIndex + 1) + half}\n          y2={yScale(line.endBox)}\n          stroke={fallingColor}\n          strokeWidth={1.5}\n          strokeDasharray=\"7 4\"\n          strokeOpacity={0.6}\n        />\n      ))}\n      <g style={{ fontWeight: 700 }}>\n        {columns.map((column, columnIndex) => {\n          const cx = xScale(columnIndex + 1) + half;\n          const color = column.direction === RISING_SYMBOL ? risingColor : fallingColor;\n          return column.boxes.map((box) => (\n            <text\n              key={`${columnIndex}-${box}`}\n              x={cx}\n              y={yScale(box)}\n              fontSize={glyphFontSize}\n              fill={color}\n              textAnchor=\"middle\"\n              dominantBaseline=\"central\"\n            >\n              {column.direction}\n            </text>\n          ));\n        })}\n      </g>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const size = window.ANYPLOT_SIZE;\n  const padding = { top: 28, right: 44, bottom: 20, left: 16 };\n  const headerHeight = 56;\n  const chartWidth = size.width - padding.left - padding.right;\n  const chartHeight = size.height - padding.top - padding.bottom - headerHeight;\n\n  return (\n    <Box\n      sx={{\n        width: size.width,\n        height: size.height,\n        backgroundColor: t.pageBg,\n        boxSizing: \"border-box\",\n        padding: `${padding.top}px ${padding.right}px ${padding.bottom}px ${padding.left}px`,\n        display: \"flex\",\n        flexDirection: \"column\",\n      }}\n    >\n      <Box\n        sx={{\n          display: \"flex\",\n          alignItems: \"baseline\",\n          justifyContent: \"space-between\",\n          mb: \"18px\",\n        }}\n      >\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1 }}>\n          {TITLE}\n        </Typography>\n        <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"20px\" }}>\n          <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"6px\" }}>\n            <Typography sx={{ fontSize: 16, fontWeight: 700, color: risingColor, lineHeight: 1 }}>\n              {RISING_SYMBOL}\n            </Typography>\n            <Typography sx={{ fontSize: 14, color: t.inkSoft, lineHeight: 1 }}>\n              {RISING_LABEL}\n            </Typography>\n          </Box>\n          <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"6px\" }}>\n            <Typography sx={{ fontSize: 16, fontWeight: 700, color: fallingColor, lineHeight: 1 }}>\n              {FALLING_SYMBOL}\n            </Typography>\n            <Typography sx={{ fontSize: 14, color: t.inkSoft, lineHeight: 1 }}>\n              {FALLING_LABEL}\n            </Typography>\n          </Box>\n          <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"6px\" }}>\n            <svg width=\"20\" height=\"14\" aria-hidden=\"true\">\n              <line\n                x1=\"2\"\n                y1=\"12\"\n                x2=\"18\"\n                y2=\"2\"\n                stroke={risingColor}\n                strokeWidth={2}\n                strokeDasharray=\"4 3\"\n                strokeOpacity={0.75}\n              />\n            </svg>\n            <Typography sx={{ fontSize: 14, color: t.inkSoft, lineHeight: 1 }}>\n              {SUPPORT_LABEL}\n            </Typography>\n          </Box>\n          <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"6px\" }}>\n            <svg width=\"20\" height=\"14\" aria-hidden=\"true\">\n              <line\n                x1=\"2\"\n                y1=\"2\"\n                x2=\"18\"\n                y2=\"12\"\n                stroke={fallingColor}\n                strokeWidth={2}\n                strokeDasharray=\"4 3\"\n                strokeOpacity={0.75}\n              />\n            </svg>\n            <Typography sx={{ fontSize: 14, color: t.inkSoft, lineHeight: 1 }}>\n              {RESISTANCE_LABEL}\n            </Typography>\n          </Box>\n        </Box>\n      </Box>\n      <ChartsContainer\n        width={chartWidth}\n        height={chartHeight}\n        series={[]}\n        skipAnimation\n        margin={{ top: 10, right: 16, bottom: 12, left: 12 }}\n        xAxis={[\n          {\n            id: \"columns\",\n            scaleType: \"band\",\n            data: columnIndices,\n            categoryGapRatio: 0.12,\n            height: 56,\n            label: X_TITLE,\n            labelStyle: { fontSize: 15, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            tickLabelInterval: (_value, index) => index % TICK_EVERY_N_COLS === 0,\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"price\",\n            scaleType: \"linear\",\n            min: yMinBox,\n            max: yMaxBox,\n            width: 82,\n            label: CLOSE,\n            labelStyle: { fontSize: 15, fill: t.ink },\n            valueFormatter: (boxValue: number) => (Number(boxValue) * BOX_SIZE).toFixed(1),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            tickNumber: 10,\n          },\n        ]}\n      >\n        <PointAndFigureOverlay />\n        <ChartsXAxis axisId=\"columns\" />\n        <ChartsYAxis axisId=\"price\" />\n      </ChartsContainer>\n    </Box>\n  );\n}\n"}