# StockChart

> A financial chart composed of Chart, RangeSelector, PeriodSelector and a toolbar with series type, indicator, trendline and export menus, with large OHLC data bucketed per pixel.

Canonical: https://salmonui.dev/docs/data-visualization/stock-chart

`StockChart` (`@salmonui/charts/stock-chart`) composes `Chart`, a
`RangeSelector` navigator, a `PeriodSelector` and a Navigation `Toolbar`
of `MenuButton`s. It imports them through their public subpaths,
so a page pays for its own code only once. Import the chart,
range-selector, menu (it carries the Button rules), toolbar and stock-chart
stylesheets (and the date-range-picker one with `customRange`).

```tsx
import { StockChart } from '@salmonui/charts/stock-chart';
import '@salmonui/charts/chart/styles.css';
import '@salmonui/charts/range-selector/styles.css';
import '@salmonui/buttons/menu/styles.css';
import '@salmonui/navigation/toolbar/styles.css';
import '@salmonui/charts/stock-chart/styles.css';

<StockChart data={prices} xField="date" openField="open" highField="high" lowField="low" closeField="close" volumeField="volume" />;
```

- `periods` (default 1M, 3M, 6M, YTD, 1Y, All) and
  `periodSelector={{ position: 'top' | 'bottom' }}`. The triad `period` /
  `defaultPeriod` / `onPeriodChange(id | null, event)` selects one: a
  selected period holds its window at the data end as data grows, moving
  the range away reports the period that matches it or `null`, and a
  controlled `range` wins over the period for the view; `defaultPeriod`
  sets the initial selection.
- `customRange` adds a `DateRangePicker` to the toolbar; it loads after
  hydration from `@salmonui/calendars/date-range-picker`, shows the visible
  range as UTC calendar days between the first and last data date, and a
  picked range calls `onRangeChange` with `reason: 'customRange'`;
  `stockText.customRange` names it.
- `navigator={false}` hides the range selector; an object passes
  `RangeSelector` props.
- `seriesType` / `defaultSeriesType` / `onSeriesTypeChange` with
  `toolbar.seriesTypes` (candle, ohlc, hilo, line, area, column).
- `indicators` / `defaultIndicators` / `onIndicatorsChange` with
  `toolbar.indicators`: SMA, EMA, TMA and Bollinger bands on the price
  axis, momentum, RSI, ATR, accumulation distribution, MACD and stochastic
  on a secondary axis.
- `trendlines` / `defaultTrendlines` / `onTrendlinesChange` with
  `toolbar.trendlines`.
- The visible range is the triad `range` / `defaultRange` /
  `onRangeChange`, shared by the chart's x zoom, the navigator and the
  period buttons.
- Every other `Chart` prop applies: `tooltip`, `crosshair`
  (`{ snap: true }` with a shared tooltip is the trackball), `zoom`,
  `legend`, `annotations` (date strings resolve on the time axis),
  `selection`, `orientation="horizontal"` (transposed), `aria-label` /
  `aria-labelledby`, `panes` with `axes`. An axis with the id `volume` or
  `indicator` refines the generated one, so
  `panes={{ rows: ['70%', '30%'] }}` with
  `axes={[{ id: 'indicator', direction: 'y', pane: { row: 1 } }]}` moves
  the indicators to their own pane.
- Large OHLC data merges candles per pixel bucket (open of the first, close
  of the last, extreme high and low) before rendering.
- `events: [{ date, label, description, shape, seriesIds }]` mark dates on
  the chart: a glyph per `shape` (circle, square, flag, pin, triangle,
  invertedTriangle, triangleRight, triangleLeft, arrowUp, arrowDown,
  arrowLeft, arrowRight, text) before the label, one marker per series in
  `seriesIds` (`'price'` by default, `'volume'` on the volume bars), and a
  visually hidden list for assistive technology; `renderEvent(event)`
  replaces the marker content.

### Live demo: StockChart with toolbar, periods and navigator

Live demo: https://salmonui.dev/demos/data-visualization/stock-chart-basic

Three years of daily prices in a StockChart with period buttons, a custom date range, a navigator, series type, indicator, trendline and export menus, a trackball and an indicator pane, all controlled.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { StockChart } from '@salmonui/charts/stock-chart';
import type { IndicatorKind, StockSeriesType, TrendlineKind } from '@salmonui/charts/stock-chart';
import { periodRange, type RangeValue } from '@salmonui/charts/range-selector';

// Three years of deterministic daily prices (UTC dates): about 1,100 candles,
// merged per pixel bucket when the whole range is visible.
const DAY = 86_400_000;
const START = Date.UTC(2023, 10, 24);
const prices = Array.from({ length: 1096 }, (_, i) => {
  const trend = 120 + i * 0.05 + 18 * Math.sin(i / 60) + 6 * Math.sin(i / 11);
  const open = trend + 2 * Math.sin(i * 1.7);
  const close = trend + 2 * Math.sin(i * 1.7 + 1.1);
  return {
    date: new Date(START + i * DAY),
    open: Math.round(open * 100) / 100,
    close: Math.round(close * 100) / 100,
    high: Math.round((Math.max(open, close) + 1 + (i % 4) * 0.4) * 100) / 100,
    low: Math.round((Math.min(open, close) - 1 - (i % 3) * 0.5) * 100) / 100,
    volume: 20_000 + ((i * 7919) % 15_000),
  };
});

const END = START + 1095 * DAY;
const initialRange: RangeValue = periodRange({ id: '6m', unit: 'month', count: 6, label: '6M' }, END, START, 'UTC');
const fmtDay = (ms: number) => new Date(ms).toISOString().slice(0, 10);

export default function StockChartBasicDemo() {
  const [period, setPeriod] = useState<string | null>('6m');
  const [range, setRange] = useState<RangeValue>(initialRange);
  const [seriesType, setSeriesType] = useState<StockSeriesType>('candle');
  const [indicators, setIndicators] = useState<readonly IndicatorKind[]>(['ema']);
  const [trendlines, setTrendlines] = useState<readonly TrendlineKind[]>([]);
  const [navigator, setNavigator] = useState(true);
  const [periodPosition, setPeriodPosition] = useState<'top' | 'bottom'>('top');
  const [lastReason, setLastReason] = useState('');
  const oscillator = indicators.includes('rsi') || indicators.includes('macd');
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <Checkbox checked={navigator} onCheckedChange={(checked) => setNavigator(checked)}>Navigator</Checkbox>
        <label>
          Period buttons
          <Select aria-label="Period buttons" data={[{ value: 'top', label: 'top' }, { value: 'bottom', label: 'bottom' }]} value={periodPosition} onValueChange={(value) => value != null && setPeriodPosition(value as 'top' | 'bottom')} />
        </label>
        <Button variant="outline" type="button" onClick={() => {
            setRange([Date.UTC(2025, 0, 1), Date.UTC(2025, 2, 31)]);
            setPeriod(null);
          }}>
          Show Q1 2025
        </Button>
      </div>
      <StockChart
        title="ACME Corp."
        data={prices}
        xField="date"
        openField="open"
        highField="high"
        lowField="low"
        closeField="close"
        volumeField="volume"
        name="ACME"
        height={420}
        timeZone="UTC"
        locale="en-US"
        period={period}
        onPeriodChange={(p) => setPeriod(p)}
        periodSelector={{ position: periodPosition }}
        range={range}
        onRangeChange={(r, event) => {
          setRange(r);
          setLastReason(event.reason);
        }}
        seriesType={seriesType}
        onSeriesTypeChange={setSeriesType}
        indicators={indicators}
        onIndicatorsChange={setIndicators}
        trendlines={trendlines}
        onTrendlinesChange={setTrendlines}
        navigator={navigator ? { height: 70 } : false}
        customRange
        toolbar={{ seriesTypes: ['candle', 'ohlc', 'hilo', 'line', 'area', 'column'], indicators: ['sma', 'ema', 'bollinger', 'rsi', 'macd'], trendlines: ['linear', 'polynomial', 'movingAverage'], export: ['png', 'svg', 'csv', 'xlsx', 'pdf', 'print'] }}
        exportWriters={{ pdf: () => import('@salmonui/export/graphics'), xlsx: () => import('@salmonui/export/xlsx') }}
        tooltip={{ mode: 'shared' }}
        crosshair={{ snap: true, axisLabels: true }}
        // RSI and MACD get a pane of their own; without them the price pane takes the whole plot.
        panes={oscillator ? { rows: ['72%', '28%'] } : undefined}
        axes={oscillator ? [{ id: 'indicator', direction: 'y', pane: { row: 1 } }] : undefined}
      />
      <p className="demo-status" aria-live="polite">
        period <code>{period ?? 'null'}</code>, range <code>{`${fmtDay(range[0])} to ${fmtDay(range[1])}`}</code>
        {lastReason ? (
          <>
            {' '}
            (last change: <code>{lastReason}</code>)
          </>
        ) : null}
        , series <code>{seriesType}</code>, indicators <code>{indicators.join(', ') || 'none'}</code>, trendlines <code>{trendlines.join(', ') || 'none'}</code>
      </p>
    </div>
  );
}
```

## Export menu

`toolbar.export` lists the export menu items: `'png' | 'jpeg' | 'svg' |
'csv' | 'xlsx' | 'pdf' | 'print'` (default PNG, SVG, CSV, XLSX, PDF and
print). PDF and XLSX go through the `exportWriters` loaders of the
underlying `Chart`, so they appear only when the matching loader is set:

```tsx
<StockChart
  {...props}
  exportWriters={{
    pdf: () => import('@salmonui/export/graphics'),
    xlsx: () => import('@salmonui/export/xlsx'),
  }}
/>
```

PDF is the vector drawing of the price chart; XLSX and CSV are its
accessible table (Rendering and colors, "Data and documents").

## Live data

`StockChart` passes `data` to its `Chart`, so live data behaves as on a
chart: a new array relays out within the live-append budget and
`ref.current.appendPoints('price', rows, { maxPoints })` streams rows into
the price series. Until the user narrows the range the chart
follows the full data, so new points stay in view; a narrowed range stays
put, and a selected period keeps its window at the data end. The navigator and period buttons read `data`, so streamed points
reach them when you pass the new array.

### Live demo: Stock events and live prices

Live demo: https://salmonui.dev/demos/data-visualization/stock-chart-events

Earnings, dividend, split and volume events marked on a StockChart with glyph shapes or custom markers, and live prices appended while the selected period keeps its window at the data end.

`Demo.tsx`:

```tsx
'use client';

import { useEffect, useState } from 'react';
import { StockChart } from '@salmonui/charts/stock-chart';
import type { StockEvent } from '@salmonui/charts/stock-chart';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';

const DAY = 86_400_000;
const START = Date.UTC(2026, 0, 1);
const candle = (i: number) => {
  const trend = 80 + 10 * Math.sin(i / 25) + i * 0.04;
  const open = trend + 1.5 * Math.sin(i * 1.3);
  const close = trend + 1.5 * Math.sin(i * 1.3 + 0.9);
  return {
    date: new Date(START + i * DAY),
    open: Math.round(open * 100) / 100,
    close: Math.round(close * 100) / 100,
    high: Math.round((Math.max(open, close) + 0.9) * 100) / 100,
    low: Math.round((Math.min(open, close) - 0.9) * 100) / 100,
    volume: 9_000 + ((i * 4241) % 6_000),
  };
};
const initial = Array.from({ length: 200 }, (_, i) => candle(i));

const events: StockEvent[] = [
  { date: '2026-02-10', label: 'E', description: 'Q4 earnings beat estimates', shape: 'flag' },
  { date: '2026-03-20', label: 'D', description: 'Dividend of 0.40 per share', shape: 'circle' },
  { date: '2026-04-15', label: 'S', description: '2-for-1 stock split announced', shape: 'pin' },
  { date: '2026-05-28', label: 'V', description: 'Record trading volume', shape: 'arrowUp', seriesIds: ['volume'] },
  { date: '2026-06-30', label: 'Q2', description: 'Half-year report', shape: 'text' },
];

export default function StockChartEventsDemo() {
  const [data, setData] = useState(initial);
  const [running, setRunning] = useState(false);
  const [custom, setCustom] = useState(false);

  useEffect(() => {
    if (!running) return undefined;
    const timer = window.setInterval(() => setData((d) => [...d, candle(d.length)]), 400);
    return () => window.clearInterval(timer);
  }, [running]);

  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <Button variant="outline" type="button" aria-pressed={running} onClick={() => setRunning((r) => !r)}>
          {running ? 'Pause' : 'Start'} live prices
        </Button>
        <Button variant="outline" type="button" onClick={() => setData(initial)}>
          Reset data
        </Button>
        <Checkbox checked={custom} onCheckedChange={(checked) => setCustom(checked)}>
          Custom event markers
        </Checkbox>
        <span className="demo-status">{data.length} trading days</span>
      </div>
      <StockChart
        title="Contoso Ltd."
        data={data}
        xField="date"
        openField="open"
        highField="high"
        lowField="low"
        closeField="close"
        volumeField="volume"
        name="Contoso"
        height={400}
        timeZone="UTC"
        locale="en-US"
        defaultPeriod="3m"
        events={events}
        renderEvent={custom ? (event) => <span className="demo-badge" data-tone="info" title={event.description}>{event.label}</span> : undefined}
        tooltip
      />
    </div>
  );
}
```

## Accessibility and SSR

The chart part is a `Chart` (one tab stop, arrow keys between candles, a
hidden data table), the navigator a multi-thumb slider, the period
buttons a radio group and the toolbar an APG Toolbar of menu buttons. The
server renders the chart, the navigator, the period buttons and the
toolbar; only the `customRange` picker loads after hydration. Set
`timeZone` and `locale` so period boundaries and labels agree between the
server and the browser.

Every prop is listed in the [API reference](https://salmonui.dev/docs/reference/charts/stock-chart).
`series` and `indicators` are reactive props, so there is no refresh
method: pass new arrays to update the chart (see
[Chart](https://salmonui.dev/docs/data-visualization/chart), "Data, state and lifecycle").
