{"spec_id":"indicator-bollinger","library":"muix","language":"javascript","code":"// anyplot.ai\n// indicator-bollinger: Bollinger Bands Indicator Chart\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/100 | Updated: 2026-11-08\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsWrapper } from \"@mui/x-charts/ChartsWrapper\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ChartsLegend } from \"@mui/x-charts/ChartsLegend\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsTooltip } from \"@mui/x-charts/ChartsTooltip\";\nimport { ChartsAxisHighlight } from \"@mui/x-charts/ChartsAxisHighlight\";\nimport { LinePlot } from \"@mui/x-charts/LineChart\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst Y_PAD_SHARE = 0.06; // share of the price range added above and below the outermost line\nconst BAND_FILL_OPACITY = 0.16;\n\n// Columns: set these to your data's column names\nconst DATE = \"Trading date\"; // role: date\nconst CLOSE = \"MRDN close (USD)\"; // role: close\nconst SMA = \"20-day SMA (USD)\"; // role: sma\nconst UPPER_BAND = \"Upper band, SMA + 2σ (USD)\"; // role: upper_band\nconst LOWER_BAND = \"Lower band, SMA − 2σ (USD)\"; // role: lower_band\n\n// Data: replace this block with your own records, one object per trading day\n// 120 weekdays of a mid-cap stock from 2 Jan 2024: a calm stretch (days 40-64) squeezes\n// the bands and a volatile run from day 90 widens them. The bands use a 20-day window and\n// the population standard deviation, so the first 19 days carry no band values.\nconst data = (() => {\n  const periods = 120;\n  const lookback = 20;\n  const sigmas = 2;\n  let seed = 42;\n  const rand = () => {\n    seed = (seed * 1664525 + 1013904223) % 4294967296;\n    return seed / 4294967296;\n  };\n  const gaussian = () => Math.sqrt(-2 * Math.log(Math.max(rand(), 1e-9))) * Math.cos(2 * Math.PI * rand());\n  const round2 = (v: number) => Math.round(v * 100) / 100;\n\n  const days: string[] = [];\n  const cursor = new Date(Date.UTC(2024, 0, 2));\n  while (days.length < periods) {\n    if (cursor.getUTCDay() % 6 !== 0) days.push(cursor.toISOString().slice(0, 10));\n    cursor.setUTCDate(cursor.getUTCDate() + 1);\n  }\n\n  const close = [162.5];\n  for (let i = 1; i < periods; i += 1) {\n    const volPct = i >= 40 && i < 65 ? 0.35 : i >= 90 ? 1.7 : 0.9;\n    close.push(close[i - 1] * (1 + (0.05 + volPct * gaussian()) / 100));\n  }\n\n  return days.map((day, i) => {\n    if (i < lookback - 1) {\n      return { [DATE]: day, [CLOSE]: round2(close[i]), [SMA]: null, [UPPER_BAND]: null, [LOWER_BAND]: null };\n    }\n    const span = close.slice(i - lookback + 1, i + 1);\n    const mean = span.reduce((s, v) => s + v, 0) / lookback;\n    const sd = Math.sqrt(span.reduce((s, v) => s + (v - mean) ** 2, 0) / lookback);\n    return {\n      [DATE]: day,\n      [CLOSE]: round2(close[i]),\n      [SMA]: round2(mean),\n      [UPPER_BAND]: round2(mean + sigmas * sd),\n      [LOWER_BAND]: round2(mean - sigmas * sd),\n    };\n  });\n})();\n\n// Plot: reads only data and the constants above\n// ISO dates are read as local midnight, the frame the time axis places its ticks in\nconst rows = [...data].sort((a, b) => Date.parse(a[DATE]) - Date.parse(b[DATE]));\nconst n = rows.length;\nconst dates = rows.map((d) => new Date(`${d[DATE]}T00:00:00`));\nconst closes = rows.map((d) => d[CLOSE] ?? null);\nconst smas = rows.map((d) => d[SMA] ?? null);\nconst uppers = rows.map((d) => d[UPPER_BAND] ?? null);\nconst lowers = rows.map((d) => d[LOWER_BAND] ?? null);\n\n// The fill between the bands is drawn for each run of consecutive days that has both bands\nconst bandRuns: number[][] = [];\nrows.forEach((_, i) => {\n  if (uppers[i] == null || lowers[i] == null) return;\n  const run = bandRuns[bandRuns.length - 1];\n  if (run && run[run.length - 1] === i - 1) run.push(i);\n  else bandRuns.push([i]);\n});\n\nconst drawn = [...closes, ...smas, ...uppers, ...lowers].filter((v) => v != null);\nconst yLow = Math.min(...drawn);\nconst yHigh = Math.max(...drawn);\nconst yPad = (yHigh - yLow) * Y_PAD_SHARE;\n\n// Band width relative to the middle band; its minimum is the tightest squeeze\nconst widthShare = rows.map((_, i) =>\n  uppers[i] != null && lowers[i] != null && smas[i] ? (uppers[i] - lowers[i]) / smas[i] : Infinity,\n);\nconst narrowest = widthShare.indexOf(Math.min(...widthShare));\n\nconst dayFormat = new Intl.DateTimeFormat(\"en-US\", { month: \"short\", day: \"numeric\" });\nconst fullFormat = new Intl.DateTimeFormat(\"en-US\", { month: \"short\", day: \"numeric\", year: \"numeric\" });\nconst squeezeNote =\n  bandRuns.length > 0\n    ? ` · narrowest band ${(widthShare[narrowest] * 100).toFixed(1)} % of the SMA on ${fullFormat.format(dates[narrowest])}`\n    : \"\";\n\nconst TITLE = \"indicator-bollinger · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${n} periods, ${fullFormat.format(dates[0])} – ${fullFormat.format(dates[n - 1])}${squeezeNote}`;\n// The y axis carries the close, the SMA and both bands, so it is titled as the price axis\nconst PRICE_AXIS = \"MRDN price (USD)\";\nconst HEADER_H = 84;\nconst LEGEND_H = 44;\nconst BAND_COLOR = t.palette[2];\n\nfunction BandFill() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return (\n    <g>\n      {bandRuns.map((run) => {\n        const top = run.map((i) => `${xScale(dates[i])},${yScale(uppers[i])}`);\n        const bottom = [...run].reverse().map((i) => `${xScale(dates[i])},${yScale(lowers[i])}`);\n        return (\n          <path\n            key={run[0]}\n            d={`M${top.join(\"L\")}L${bottom.join(\"L\")}Z`}\n            fill={BAND_COLOR}\n            fillOpacity={BAND_FILL_OPACITY}\n            stroke=\"none\"\n          />\n        );\n      })}\n    </g>\n  );\n}\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      <ChartsDataProvider\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        margin={{ top: 12, right: 40, bottom: 8, left: 20 }}\n        skipAnimation\n        series={[\n          {\n            type: \"line\",\n            id: \"close\",\n            data: closes,\n            label: CLOSE,\n            color: t.palette[0],\n            curve: \"linear\",\n            showMark: false,\n            labelMarkType: \"line\",\n          },\n          {\n            type: \"line\",\n            id: \"sma\",\n            data: smas,\n            label: SMA,\n            color: t.palette[1],\n            curve: \"linear\",\n            showMark: false,\n            labelMarkType: \"line\",\n          },\n          {\n            type: \"line\",\n            id: \"upper\",\n            data: uppers,\n            label: UPPER_BAND,\n            color: BAND_COLOR,\n            curve: \"linear\",\n            showMark: false,\n            labelMarkType: \"line\",\n          },\n          {\n            type: \"line\",\n            id: \"lower\",\n            data: lowers,\n            label: LOWER_BAND,\n            color: BAND_COLOR,\n            curve: \"linear\",\n            showMark: false,\n            labelMarkType: \"line\",\n          },\n        ]}\n        xAxis={[\n          {\n            scaleType: \"time\",\n            data: dates,\n            domainLimit: \"strict\",\n            label: DATE,\n            height: 64,\n            tickNumber: 10,\n            valueFormatter: (v: Date) => dayFormat.format(v),\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: PRICE_AXIS,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n      >\n        <ChartsWrapper legendPosition={{ vertical: \"top\", horizontal: \"center\" }} legendDirection=\"horizontal\">\n          <ChartsLegend sx={{ fontSize: 15, color: t.ink, gap: \"28px\" }} />\n          <ChartsSurface\n            sx={{\n              \"& .MuiLineChart-line\": { strokeWidth: 2 },\n              '& .MuiLineChart-line[data-series=\"close\"]': { strokeWidth: 3.5 },\n              '& .MuiLineChart-line[data-series=\"sma\"]': { strokeWidth: 2.5, strokeDasharray: \"10 6\" },\n              '& .MuiLineChart-line[data-series=\"upper\"], & .MuiLineChart-line[data-series=\"lower\"]': {\n                strokeWidth: 1.5,\n                strokeOpacity: 0.8,\n              },\n              \"& .MuiChartsGrid-line\": { stroke: t.grid },\n            }}\n          >\n            <ChartsGrid horizontal />\n            <BandFill />\n            <LinePlot skipAnimation />\n            <ChartsAxisHighlight x=\"line\" />\n            <ChartsXAxis />\n            <ChartsYAxis />\n          </ChartsSurface>\n          <ChartsTooltip trigger=\"axis\" />\n        </ChartsWrapper>\n      </ChartsDataProvider>\n    </Box>\n  );\n}\n"}