Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install lightweight-charts-react-components@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin lightweight-charts-react-components v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install lightweight-charts-react-components

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/lightweight-charts-react-components/

Extract the ZIP to .github/skills/ in your repo. The folder name must match lightweight-charts-react-components for Copilot to auto-discover it.

Skill Files (11)

LICENSE 1.0 KB
MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
SKILL.md 10.1 KB
---
name: lightweight-charts-react-components
description: lightweight-charts-react-components recipes for TradingView lightweight-charts in React. Candlestick, line, and area series; volume and indicator panes; realtime WebSocket updates; infinite history on scroll; crosshair OHLC legends and tooltips; trade markers and price lines; synchronized charts; numeric options and yield-curve axes. Use when adding or fixing a financial or trading chart in a React app, or when the user mentions lightweight-charts, TradingView charts in React, or this package.
license: MIT
metadata:
  author: ukorvl
  version: "1.0"
  source: "https://github.com/ukorvl/lightweight-charts-react-components/tree/0368191127568e48aef6f7bda2ff3900e8e24756/skills/lightweight-charts-react-components"
---

# lightweight-charts-react-components guide

## Quick Start

Let the components manage chart and series creation and cleanup. Import components
and ref types from `lightweight-charts-react-components`; import native data, option,
and event types from `lightweight-charts`.

1. Check versions against the compatibility table below. Read declared ranges
   from the app's `package.json`, then the installed versions from the `version`
   field of `node_modules/<package>/package.json` for
   `lightweight-charts-react-components`, `lightweight-charts`, `react`, and
   `react-dom`. If the library is not installed, follow
   [Installation](#installation). Ensure chart rendering runs in the browser,
   within the app's client boundary.
2. For a basic static chart, start from the minimal chart below. Otherwise, read the
   reference matching the requested behavior. Adapt its feed and UI; preserve its
   data contract, component nesting, and API readiness handling.
3. Choose one data owner: pass the complete dataset through `data` for React-owned
   updates, or use `reactive={false}` and the series API for frequent ticks.

### Installation

Install the wrapper together with its `lightweight-charts` peer dependency, using
the project's package manager. React and React DOM must already be installed.

```sh
npm install lightweight-charts-react-components lightweight-charts
```

### Minimal chart

```tsx
import type { LineData, UTCTimestamp } from "lightweight-charts";
import {
  Chart,
  LineSeries,
  TimeScale,
  TimeScaleFitContentTrigger,
} from "lightweight-charts-react-components";

// Data must be sorted ascending by time with unique times (UTC seconds here).
export function SimpleLineChart({ data }: { data: LineData<UTCTimestamp>[] }) {
  return (
    // autoSize follows the container, which needs a nonzero height.
    <Chart
      options={{ autoSize: true }}
      containerProps={{ style: { height: 300, width: "100%" } }}
    >
      <LineSeries data={data} />
      <TimeScale>
        <TimeScaleFitContentTrigger deps={[]} />
      </TimeScale>
    </Chart>
  );
}
```

## Examples and snippets (reference files)

Read the reference matching the user's outcome. Each contains a complete TypeScript
recipe, data and integration contracts, reasons for the architecture, failure modes,
and acceptance checks. Combine references when a task spans several outcomes; do
not load every reference for a simple chart.

| User request                                                                         | Reference                                                                        |
| ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- |
| WebSocket candles, updating the current bar, stale history, excessive chart renders  | [Market data and live updates](references/market-data-and-live-updates.md)       |
| Older history on scroll, viewport jumps, symbol/interval changes, late API responses | [History and range selection](references/history-and-range-selection.md)         |
| Candles plus volume, moving averages, oscillator panes, independent price scales     | [Price, volume, and indicators](references/price-volume-and-indicators.md)       |
| OHLC legend, hover details, missing data, tooltip positioning                        | [Hover legends and tooltips](references/hover-legends-and-tooltips.md)           |
| Executions and signals, stop/target levels, click-to-place price lines               | [Trade markers and price levels](references/trade-markers-and-price-levels.md)   |
| Compare assets with different prices, fixed-baseline returns, toggle comparisons     | [Performance comparison](references/performance-comparison.md)                   |
| Separate charts that share scrolling, zooming, and a crosshair                       | [Synchronized charts](references/synchronized-charts.md)                         |
| Trading-session shading, pane backgrounds, custom drawing that follows zoom          | [Session overlays and primitives](references/session-overlays-and-primitives.md) |
| Options strikes, yield maturities, choosing a numeric or custom horizontal axis      | [Numeric axes and chart types](references/numeric-axes-and-chart-types.md)       |

If no reference matches the request, tell the user that the skill has no recipe
for it. Then build the solution from the public components and the upstream
`lightweight-charts` API, applying the Quick Start rules and the edge cases below.

### Skill compatibility

The recipes are verified against the reference versions below. These are the
tested baseline, not the latest available releases.

If an installed version differs from the reference version, compare it with the
compatibility range. Inside the range, recipes apply as written. Outside it,
tell the user about the mismatch before writing code, because breaking API
changes can affect the recipes, and verify every API the recipe uses against
the installed package.

| Dependency or environment             | Reference version | Compatibility range and checks                                                                                                                       |
| ------------------------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `lightweight-charts-react-components` | `2.6.1`           | Recipe target: `>=2.6.1 <3`. Other versions require checking installed exports, chart API refs, and reactive data behavior before adapting a recipe. |
| `lightweight-charts`                  | `5.2.1`           | Declared peer: `>=5.0.8 <6`.                                                                                                                         |
| React and React DOM                   | `19.2.6`          | Declared peers: `>=18.2 <20`. Keep `react` and `react-dom` on matching versions and use the application's existing React instance.                   |
| Node.js                               | —                 | Package engines: `>=18.14.0`. The app's build tools can require a newer version.                                                                     |
| Module system                         | ESM               | ESM `import` entry only; there is no CommonJS `require` entry.                                                                                       |
| Rendering                             | Browser           | Charts need the DOM and canvas. Render them on the client, never during server rendering.                                                            |

## Common edge cases

- **Chart sizing:** Put DOM styles on `containerProps` and give the chart a
  nonzero height.
- **Required ancestors:** Headless chart children need a chart wrapper ancestor.
  `Markers`, `PriceLine`, and `SeriesPrimitive` belong inside their series;
  `PriceScale`, `Watermark`, and `PanePrimitive` require a `Pane`;
  `TimeScaleFitContentTrigger` requires a `TimeScale`.
- **API refs and readiness:** Use `ref.current?.api()` for the native API and
  `containerRef` for the div. For `Chart`, use `ChartApiRef<Time, IChartApi>`.
  `.api()` can initially return null; follow the recipe's readiness step before
  imperative setup.
- **Viewport resets:** To preserve scroll/zoom, keep the chart's key stable and
  live/history updates out of fit-trigger dependencies. Fit on initial load or a
  deliberate reset. See [range handling](references/history-and-range-selection.md).
- **Data updates:** Use `data` for React-owned updates, or `reactive={false}` and the
  series API when per-tick React renders are measurably costly. Avoid mixing both.
  Reactive `data` is always the complete dataset. With wrapper 2.6.1 and
  Lightweight Charts 5.2.1, `series.data()` reconstructs candle and line objects;
  the wrapper's earlier-item reference comparison therefore sends multi-bar tail
  updates through `setData()`, even when React keeps earlier references stable.
  Keep data immutable, but use the chart-owned `reactive={false}` recipe and
  explicit `series.update(bar)` when incremental writes are required. See
  [live updates](references/market-data-and-live-updates.md).

## Source

Adapted from [ukorvl/lightweight-charts-react-components](https://github.com/ukorvl/lightweight-charts-react-components/tree/0368191127568e48aef6f7bda2ff3900e8e24756/skills/lightweight-charts-react-components)
at commit `0368191127568e48aef6f7bda2ff3900e8e24756`. Original author: ukorvl.
The [MIT license](LICENSE) and all nine reference recipes are retained. Local
corrections in [live updates](references/market-data-and-live-updates.md) reject
malformed timestamps and explain the tested versions' reactive-update limitation;
[session overlays](references/session-overlays-and-primitives.md) clarifies the
primitive update callback.
The other seven references and MIT notice are unchanged. This catalog copy adds
source attribution and operational boundaries; it does not imply TradingView
endorsement.

Recipes generate application code and can change dependencies. Follow the user's
requested scope and the host's approval policy. Feed access belongs to the app's
separately authorized adapter; keep credentials out of client code. Trade markers
are visual annotations, not order execution or server-side alerts. Use synthetic
data for local checks and report browser/feed behavior that remains untested.
references/
history-and-range-selection.md 11.5 KB
# History and range selection

Use this when a user scrolls left to fetch older bars, selects a different symbol
or interval, or switches between preset viewing windows. These are distinct
operations: adding history should preserve the view, changing dataset identity
should reset it, and choosing a window should change only the visible range when
the required data is already loaded.

## Recipe: prepend older history without losing the viewed bars

This is a **single-series intraday chart**. `initialData` is a nonempty ascending,
unique array of UTC-second line points. `loadOlder(before, signal)` returns
normalized ascending points and an explicit `hasMore`. Its cursor is exclusive;
the recipe also discards overlap defensively. Mount with a new key for a new
dataset. The adapter owns transport, authentication, and response validation.

Use chart-owned data for this recipe so `setData()` and range restoration occur
together. Capturing the range when a request starts would undo any panning the
user performs while waiting; capture it immediately before applying the response.

```tsx
import { useCallback, useEffect, useRef, useState } from "react";
import type {
  IChartApi,
  LineData,
  LogicalRange,
  Time,
  UTCTimestamp,
} from "lightweight-charts";
import {
  Chart,
  LineSeries,
  TimeScale,
  type ChartApiRef,
  type SeriesApiRef,
} from "lightweight-charts-react-components";

type Point = LineData<UTCTimestamp>;
type HistoryPage = { data: Point[]; hasMore: boolean };
type LoadOlder = (before: UTCTimestamp, signal: AbortSignal) => Promise<HistoryPage>;

export function PaginatedHistory({
  initialData,
  loadOlder,
}: {
  initialData: Point[];
  loadOlder: LoadOlder;
}) {
  const [seed] = useState(() => initialData.map(point => ({ ...point })));
  const rows = useRef(seed);
  const chartRef = useRef<ChartApiRef<Time, IChartApi>>(null);
  const seriesRef = useRef<SeriesApiRef<"Line">>(null);
  const alive = useRef(false);
  const inFlight = useRef<AbortController | null>(null);
  const exhausted = useRef(false);
  const failed = useRef(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const requestOlder = useCallback(async () => {
    const series = seriesRef.current?.api();
    const scale = chartRef.current?.api()?.timeScale();
    const first = rows.current[0];
    if (!alive.current || !series || !scale || !first) return;
    if (inFlight.current || exhausted.current || failed.current) return;

    // A ref locks synchronously; React loading state alone allows duplicate
    // requests when several range events arrive before a render.
    const controller = new AbortController();
    inFlight.current = controller;
    setLoading(true);
    setError(null);
    try {
      const page = await loadOlder(first.time, controller.signal);
      if (!alive.current || controller.signal.aborted) return;

      const byTime = new Map<UTCTimestamp, Point>();
      for (const point of page.data) {
        if (point.time < first.time) byTime.set(point.time, { ...point });
      }
      const older = [...byTime.values()].sort((a, b) => a.time - b.time);
      if (older.length === 0 && page.hasMore) {
        throw new Error("History cursor made no progress");
      }

      if (older.length > 0) {
        const visible = scale.getVisibleLogicalRange();
        rows.current = [...older, ...rows.current];
        series.setData(rows.current);
        if (visible) {
          // Each inserted point shifts the old point's index by one. Translate
          // both bounds to keep the same old bars and the same zoom width.
          scale.setVisibleLogicalRange({
            from: visible.from + older.length,
            to: visible.to + older.length,
          });
        }
      }
      exhausted.current = !page.hasMore;
    } catch (cause) {
      if (alive.current && !controller.signal.aborted) {
        // Stop event-driven retries after a failure. Let the user retry once
        // instead of turning a drag into a loop of failed network requests.
        failed.current = true;
        setError(cause instanceof Error ? cause.message : "History load failed");
      }
    } finally {
      if (inFlight.current === controller) inFlight.current = null;
      if (alive.current) setLoading(false);
    }
  }, [loadOlder]);

  const onRange = useCallback(
    (range: LogicalRange | null) => {
      if (!range) return;
      const bars = seriesRef.current?.api()?.barsInLogicalRange(range);
      if (bars && bars.barsBefore < 20) void requestOlder();
    },
    [requestOlder]
  );

  useEffect(() => {
    alive.current = true;
    let frame = 0;
    const initializeView = () => {
      const series = seriesRef.current?.api();
      const scale = chartRef.current?.api()?.timeScale();
      if (!series || !scale) {
        frame = requestAnimationFrame(initializeView);
        return;
      }
      // Start near the tail. No fit trigger runs after a page is prepended.
      scale.setVisibleLogicalRange({
        from: Math.max(0, seed.length - 80),
        to: seed.length - 1 + 5,
      });
      onRange(scale.getVisibleLogicalRange());
    };
    initializeView();
    return () => {
      alive.current = false;
      cancelAnimationFrame(frame);
      inFlight.current?.abort();
    };
  }, [seed, onRange]);

  return (
    <section>
      <p>{loading ? "Loading older history…" : "Scroll left for older history"}</p>
      {error && (
        <button
          onClick={() => {
            failed.current = false;
            void requestOlder();
          }}
        >
          Retry: {error}
        </button>
      )}
      <Chart
        ref={chartRef}
        options={{ autoSize: true, timeScale: { timeVisible: true } }}
        containerProps={{ style: { height: 360 } }}
      >
        <LineSeries ref={seriesRef} data={seed} reactive={false} />
        <TimeScale onVisibleLogicalRangeChange={onRange} />
      </Chart>
    </section>
  );
}
```

Keep `loadOlder` stable for one dataset. Changing it restarts the view initialization
effect; changing the dataset should instead remount with a new key. The cancellation
check protects against transports that resolve even after abort.

The index translation above assumes each prepended point adds one chart timeline
position. With several series, logical indices refer to their **union of times**.
Build one aligned timeline for all series and calculate the number of newly added
timeline positions. Do not shift by the page length of an arbitrary indicator.
If a live feed also owns the tail, merge against the current history at response
time and apply updates through the same data owner; do not let the captured request
snapshot overwrite newer ticks.

## Recipe: symbol or interval replacement with stale-response protection

Here the API returns a complete normalized OHLC snapshot. Copy this as a separate
module. A selection ID labels each response, and a chart is mounted only for the
matching result. This prevents showing the prior symbol under the new label and
gives the new dataset its own initial fit.

```tsx
import { useEffect, useState } from "react";
import type { CandlestickData, UTCTimestamp } from "lightweight-charts";
import {
  CandlestickSeries,
  Chart,
  TimeScale,
  TimeScaleFitContentTrigger,
} from "lightweight-charts-react-components";

type Interval = "1h" | "1d";
type Selection = { symbol: string; interval: Interval };
type Snapshot = CandlestickData<UTCTimestamp>[];
type LoadSnapshot = (selection: Selection, signal: AbortSignal) => Promise<Snapshot>;

export function InstrumentHistory({ loadSnapshot }: { loadSnapshot: LoadSnapshot }) {
  const [selection, setSelection] = useState<Selection>({
    symbol: "ASSET_A",
    interval: "1d",
  });
  // The effect depends on these values: re-clicking the current interval creates a
  // new selection object but must not refetch or reset the view.
  const { symbol, interval } = selection;
  const id = `${symbol}:${interval}`;
  const [result, setResult] = useState<{ id: string; data: Snapshot } | null>(null);
  const [error, setError] = useState<{ id: string; message: string } | null>(null);
  const [retry, setRetry] = useState(0);

  useEffect(() => {
    const controller = new AbortController();
    let active = true;
    setResult(null);
    setError(null);
    void loadSnapshot({ symbol, interval }, controller.signal).then(
      data => {
        if (active) setResult({ id, data });
      },
      cause => {
        if (active) {
          setError({
            id,
            message: cause instanceof Error ? cause.message : "Load failed",
          });
        }
      }
    );
    return () => {
      active = false;
      controller.abort();
    };
  }, [id, symbol, interval, loadSnapshot, retry]);

  const current = result?.id === id ? result : null;
  return (
    <section>
      <select
        aria-label="Instrument"
        value={selection.symbol}
        onChange={event =>
          setSelection(previous => ({ ...previous, symbol: event.target.value }))
        }
      >
        <option value="ASSET_A">Asset A</option>
        <option value="ASSET_B">Asset B</option>
      </select>
      <button onClick={() => setSelection(previous => ({ ...previous, interval: "1h" }))}>
        Hourly
      </button>
      <button onClick={() => setSelection(previous => ({ ...previous, interval: "1d" }))}>
        Daily
      </button>
      {error?.id === id ? (
        <button onClick={() => setRetry(value => value + 1)}>
          Retry: {error.message}
        </button>
      ) : !current ? (
        <p>Loading {id}…</p>
      ) : current.data.length === 0 ? (
        <p>No history for {id}</p>
      ) : (
        <Chart
          key={id}
          options={{
            autoSize: true,
            timeScale: { timeVisible: selection.interval === "1h" },
          }}
          containerProps={{ style: { height: 360 } }}
        >
          <CandlestickSeries data={current.data} alwaysReplaceData />
          <TimeScale>
            <TimeScaleFitContentTrigger deps={[]} />
          </TimeScale>
        </Chart>
      )}
    </section>
  );
}
```

Supply a stable `loadSnapshot` adapter. If a same-symbol refresh should preserve
zoom, keep the chart mounted, replace the full data array, and avoid a new fit
trigger. The recipe intentionally resets on selection because the data identity
and interval changed.

For a preset such as “last month” over already-loaded data, keep the series data
intact and call `timeScale.setVisibleRange({ from, to })` with matching time types,
or update `TimeScale`'s `visibleRange` prop after initialization. For “last 100
bars,” use logical bounds. Do not pass visible-range bounds and a fit trigger for
the same interaction: the fit trigger can overwrite the requested range.
Changing `timeVisible` formats an axis; it does not aggregate daily bars into
hourly bars. The data adapter must return the chosen granularity.

## Acceptance checks

- Drag left rapidly: one request is in flight, overlapping timestamps are not
  duplicated, and the bars visible at response time stay visible after prepend.
- Pan again before the response arrives; the eventual response preserves that
  later view. Keep scrolling until `hasMore` is false; requests stop.
- Simulate an error: the chart remains usable and retry is explicit. Unmount
  while fetching: no response updates a removed chart.
- Select A, B, and a new interval rapidly. Return A's response last and verify
  that only the final selection renders. Cover empty snapshots and retry.
- Click the interval that is already selected: no request starts and the chart
  keeps its zoom and scroll position.
hover-legends-and-tooltips.md 8.1 KB
# Hover legends and tooltips

Use this for “show OHLC under the cursor,” a persistent latest-bar legend, or a
floating details box. The chart renders a canvas; the wrapper supplies event
handlers but no tooltip or legend UI. Keep the HTML details alongside the chart
in a positioned application container.

## Architecture choices

- Use `onCrosshairMove` on `Chart`; the wrapper owns subscription and cleanup.
  Do not also call `subscribeCrosshairMove()` for the same handler.
- Look up `param.seriesData` by the **native series API** returned by
  `seriesRef.current.api()`. The map is not keyed by wrapper refs or string IDs.
- The map can omit a series at a given time. Check presence and the appropriate
  shape (`close` for candles, `value` for lines/histograms) before reading values.
- Keep selection by time and read current data from the application snapshot.
  Updating the currently hovered candle then updates the legend even when the
  pointer stays still. Comparing only timestamps would leave stale OHLC values.
- Ignore identical selection/position updates. Native option/data updates can
  emit crosshair events; always creating new React state can feed back into
  another options update and cause a render loop. Selection equality is safe
  here because displayed OHLC comes from current data, not cached event values.
- `param.point` is local to the chart pane, not the viewport. This recipe is for
  one pane; add each pane's DOM offset for tooltips over a multi-pane chart.

## Recipe: live OHLC legend and clamped tooltip

`data` is normalized, ascending, unique UTC-second candles; the initial snapshot
is ready before mounting. The application owns live updates through the complete
array. Copy this as one component module. The details are React text, so symbol
labels and values are not interpolated into `innerHTML`.

```tsx
import { useCallback, useMemo, useRef, useState } from "react";
import type { CandlestickData, MouseEventParams, UTCTimestamp } from "lightweight-charts";
import {
  CandlestickSeries,
  Chart,
  TimeScale,
  TimeScaleFitContentTrigger,
  type SeriesApiRef,
} from "lightweight-charts-react-components";

type Hover = { time: UTCTimestamp; x: number; y: number };
const tooltipWidth = 190;
const tooltipHeight = 96;
const chartOptions = { autoSize: true, timeScale: { timeVisible: true } };

export function CandleDetails({
  symbol,
  data,
}: {
  symbol: string;
  data: CandlestickData<UTCTimestamp>[];
}) {
  const seriesRef = useRef<SeriesApiRef<"Candlestick">>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [hover, setHover] = useState<Hover | null>(null);
  const byTime = useMemo(() => new Map(data.map(bar => [bar.time, bar])), [data]);
  const selected = hover ? byTime.get(hover.time) : undefined;
  // Leaving the plot, missing data, and an empty dataset are distinct states.
  const legend = selected ?? data[data.length - 1];

  const onCrosshairMove = useCallback((param: MouseEventParams) => {
    const series = seriesRef.current?.api();
    const container = containerRef.current;
    const point = param.point;
    if (
      !series ||
      !container ||
      !point ||
      typeof param.time !== "number" ||
      point.x < 0 ||
      point.y < 0 ||
      point.x > container.clientWidth ||
      point.y > container.clientHeight
    ) {
      setHover(null);
      return;
    }
    const bar = param.seriesData.get(series);
    if (!bar || !("close" in bar)) {
      setHover(null);
      return;
    }
    // Clamp in the same coordinate system as the positioned chart container.
    // If the card is narrower than the tooltip, CSS also shrinks its width.
    const width = Math.min(tooltipWidth, container.clientWidth);
    const x = Math.max(0, Math.min(point.x + 12, container.clientWidth - width));
    const y = Math.max(0, Math.min(point.y + 12, container.clientHeight - tooltipHeight));
    const next = { time: param.time as UTCTimestamp, x, y };
    // Native updates can emit the same crosshair event without pointer movement.
    // Preserve state identity in that case; current data still refreshes OHLC.
    setHover(previous =>
      previous?.time === next.time && previous.x === x && previous.y === y
        ? previous
        : next
    );
  }, []);

  const describe = (bar: CandlestickData<UTCTimestamp>) =>
    `O ${bar.open.toFixed(2)} · H ${bar.high.toFixed(2)} · L ${bar.low.toFixed(2)} · C ${bar.close.toFixed(2)}`;

  return (
    <section style={{ minWidth: 0 }}>
      <p>
        {symbol}: {legend ? describe(legend) : "No data"}
      </p>
      <div style={{ position: "relative" }}>
        <Chart
          containerRef={containerRef}
          containerProps={{ style: { height: 360 } }}
          options={chartOptions}
          onCrosshairMove={onCrosshairMove}
        >
          <CandlestickSeries ref={seriesRef} data={data} />
          <TimeScale>
            <TimeScaleFitContentTrigger deps={[]} />
          </TimeScale>
        </Chart>
        {hover && selected && (
          <div
            style={{
              position: "absolute",
              left: hover.x,
              top: hover.y,
              width: tooltipWidth,
              maxWidth: "100%",
              height: tooltipHeight,
              boxSizing: "border-box",
              padding: 10,
              background: "#0f172a",
              color: "white",
              borderRadius: 4,
              pointerEvents: "none", // Hover details must not steal chart pointer events.
              zIndex: 2,
            }}
          >
            <strong>{symbol}</strong>
            <div>{new Date(selected.time * 1000).toISOString().slice(0, 16)} UTC</div>
            <div style={{ fontSize: 12 }}>{describe(selected)}</div>
          </div>
        )}
      </div>
    </section>
  );
}
```

The plain 2-decimal formatter is appropriate only for assets with that precision.
Use the same precision as the series' `priceFormat` for other tick sizes. For
business dates, format the date fields directly; a numeric timestamp is epoch
seconds and requires multiplying by 1000 before constructing a `Date`.

This recipe falls back to the latest candle when the hovered series has no
data. If the user wants to distinguish a gap from leaving the chart, keep an
explicit “gap” state and show “No bar at this time” instead. A timezone or locale
formatter changes labels, never the underlying bar timestamps.

## Adaptation: several series or a fixed legend

For several lines, keep refs indexed by a stable application series ID. For each
series, retrieve its native API, then read `param.seriesData.get(api)`. Display
`—` when the map has no point; do not show another asset's value at the same
logical index. Derive labels/colors from the application's ID mapping, not the
order in which map entries happen to appear.

For a fixed legend, omit the floating box and position updates. Keep the selected
time and derive the displayed values from the latest data, as above. For very
high pointer-event rates, batch the HTML update with `requestAnimationFrame`;
cancel the pending frame on cleanup. Avoid writing React state for every series
separately within one crosshair callback.

For a tooltip in a scrollable portal attached to `document.body`, convert the
chart-local coordinate using `getBoundingClientRect()` and the portal's positioning
model. Do not reuse the local x/y unchanged as page coordinates. With multiple
panes, `param.paneIndex` identifies the source pane; compute its offset or put the
tooltip inside the appropriate pane container.

## Acceptance checks

- Hover first/last bars and whitespace; leave the canvas and price axis. Missing
  map entries never throw, the floating box disappears, and the legend falls back.
- Update a hovered candle at the same timestamp without moving the pointer.
  Its OHLC changes in the legend and tooltip.
- Hover near all four edges at a narrow width. The box remains inside the chart
  and does not prevent dragging, scrolling, or crosshair movement.
- Do not suppress legend updates when only the hovered timestamp matches: a live
  same-bar revision keeps the time but changes the values. Guard against a
  missing lookup entry before reading candle fields.
- For multi-series adaptation, test different calendars and missing points.
market-data-and-live-updates.md 11.9 KB
# Market data and live updates

Use this for a quote screen or trading terminal that loads OHLC history and then
receives bar snapshots from a socket. The usual pains are duplicate timestamps,
milliseconds treated as seconds, stale candles after a refetch, and a chart that
keeps zooming out while the user reads history.

## Decide who owns the complete history

| Data flow                                                    | Implementation                                            | Reason                                                  |
| ------------------------------------------------------------ | --------------------------------------------------------- | ------------------------------------------------------- |
| Modest update rate; other React UI needs the history         | Full array in `data`, default `reactive`                  | One source of truth for the chart and application       |
| A snapshot, refetch, prepend, trim, or historical correction | Replace the full array; optionally `alwaysReplaceData`    | The chart must match the supplied history exactly       |
| Frequent ticks; chart does not need to render React per tick | `reactive={false}`, then `ref.current.api()?.update(bar)` | The chart owns ongoing updates; React owns its lifetime |

Reactive `data` always means the **entire desired dataset**. Passing `[latestBar]`
replaces history. The wrapper's incremental path compares earlier item references
against `series.data()`. With wrapper **2.6.1** and Lightweight Charts **5.2.1**,
that API reconstructs candle and line objects, so multi-bar tail replacements and
appends use `setData()` even when React preserves earlier object references.
Treat the React-owned recipe as complete-history replacement on this baseline.
For frequent incremental writes, use the chart-owned recipe below with
`reactive={false}` and explicit `series.update(bar)`.

`reactive={false}` still calls `setData(data)` during initialization. It ignores
subsequent data prop changes. Do not combine imperative ticks with a reactive
snapshot that can overwrite them.

## Normalize the feed at the boundary

This adapter expects **complete candle snapshots**, not individual trades. Build
OHLC aggregation upstream if the feed contains trade prices. `timestampMs` is the
bar-open instant in UTC milliseconds. A payload that revises the same bar appears
later in the response and wins. Invalid data is rejected rather than plotted.

```ts file=market-data.ts
import type { CandlestickData, UTCTimestamp } from "lightweight-charts";

export type Candle = CandlestickData<UTCTimestamp>;
export type WireCandle = {
  timestampMs: number;
  open: number | string;
  high: number | string;
  low: number | string;
  close: number | string;
};

export function normalizeCandle(row: WireCandle): Candle {
  // Reject runtime coercion of null, strings, and booleans to epoch seconds.
  if (typeof row.timestampMs !== "number") {
    throw new Error("Invalid candle timestamp");
  }
  const seconds = row.timestampMs / 1000;
  const prices = [row.open, row.high, row.low, row.close].map(value => {
    // The wire type is not a runtime guarantee, and Number() turns null and blank
    // strings into 0, which would pass the range checks below.
    if (typeof value === "number") return value;
    if (typeof value === "string" && value.trim() !== "") return Number(value);
    throw new Error("Missing OHLC price");
  });
  const [open, high, low, close] = prices;
  if (
    !Number.isSafeInteger(seconds) ||
    !prices.every(Number.isFinite) ||
    low > Math.min(open, close) ||
    high < Math.max(open, close) ||
    low > high
  ) {
    throw new Error("Invalid candle snapshot");
  }
  // The brand expresses validated epoch seconds; it does not perform conversion.
  return { time: seconds as UTCTimestamp, open, high, low, close };
}

export function normalizeHistory(rows: WireCandle[]): Candle[] {
  const byTime = new Map<UTCTimestamp, Candle>();
  for (const row of rows) {
    const candle = normalizeCandle(row);
    byTime.set(candle.time, candle);
  }
  return [...byTime.values()].sort((a, b) => a.time - b.time);
}

export function upsertLatest(history: Candle[], bar: Candle): Candle[] {
  const last = history[history.length - 1];
  if (!last || bar.time > last.time) return [...history, bar];
  if (bar.time === last.time) return [...history.slice(0, -1), bar];
  // This tail-only path rejects late history. Reconcile corrections separately
  // into a complete snapshot, then replace data instead of appending them.
  return history;
}
```

Keep daily business dates as `YYYY-MM-DD` or `BusinessDay` when the source is a
calendar-day series. Do not convert those dates through the browser's local time
zone. An intraday feed should consistently use UTC seconds. Do not mix time
representations or infer seconds versus milliseconds from an arbitrary threshold.

## Recipe: React-owned live candles

Save the adapter above as `market-data.ts`, then this component as
`LiveCandles.tsx`. The subscription adapter delivers normalized complete candles
and returns an unsubscribe function. It must cover the snapshot-to-subscription
gap using the provider's cursor/replay protocol. It must also reject stale same-bar
revisions using the provider's sequence number when one exists; timestamp order
alone cannot order revisions of one candle.

```tsx file=LiveCandles.tsx
import { useEffect, useState } from "react";
import {
  CandlestickSeries,
  Chart,
  TimeScale,
  TimeScaleFitContentTrigger,
} from "lightweight-charts-react-components";
import { upsertLatest, type Candle } from "./market-data";

export type SubscribeBars = (receive: (bar: Candle) => void) => () => void;

export function LiveCandles({
  initialData,
  subscribe,
}: {
  initialData: Candle[];
  subscribe: SubscribeBars;
}) {
  // Mount with a key containing symbol + interval + snapshot revision when the
  // dataset identity changes. initialData is intentionally a mount-time seed.
  const [data, setData] = useState<Candle[]>(() => initialData.map(bar => ({ ...bar })));

  useEffect(() => {
    let active = true;
    const unsubscribe = subscribe(bar => {
      if (active) setData(previous => upsertLatest(previous, { ...bar }));
    });
    return () => {
      active = false;
      unsubscribe();
    };
  }, [subscribe]);

  return (
    <section style={{ minWidth: 0 }}>
      <Chart
        containerProps={{ style: { height: 360, width: "100%" } }}
        options={{
          autoSize: true,
          timeScale: { timeVisible: true, secondsVisible: false },
        }}
      >
        <CandlestickSeries data={data} />
        <TimeScale>
          {/* A stable trigger fits once. Every tick must preserve user zoom. */}
          <TimeScaleFitContentTrigger deps={[]} />
        </TimeScale>
      </Chart>
    </section>
  );
}
```

The wrapper itself defaults only `addDefaultPane` to `false`; it does **not**
enable `autoSize`. Set `autoSize: true` explicitly and give the wrapper a nonzero
height. Width can follow its parent. Flex/grid cards often need `minWidth: 0` on
the card to allow shrinking. Use `containerRef` for the DOM node and the chart
`ref` for its API wrapper; these are different references.

For a Next.js App Router integration, put `"use client"` at the top of the chart's
client module. If its surrounding setup still cannot prerender the chart, load
that module through a client-side dynamic boundary with `ssr: false`. Do not access
`window` or create chart APIs during server rendering. See the
[Next.js client-only loading guidance](https://nextjs.org/docs/app/guides/lazy-loading#skipping-ssr)
for placement of that boundary.

## Recipe: chart-owned ticks

Use this alternative when the chart must consume many snapshots without a React
render for each one. The subscription contract remains the same. The chart and
series refs expose wrapper objects: the native APIs are returned by `.api()`.
A non-null wrapper ref can still contain a null API until initialization finishes.

```tsx
import { useEffect, useRef, useState } from "react";
import type { IChartApi, Time, UTCTimestamp } from "lightweight-charts";
import {
  CandlestickSeries,
  Chart,
  type ChartApiRef,
  type SeriesApiRef,
} from "lightweight-charts-react-components";
import type { Candle } from "./market-data";
import type { SubscribeBars } from "./LiveCandles";

export function ImperativeCandles({
  initialData,
  subscribe,
}: {
  initialData: Candle[];
  subscribe: SubscribeBars;
}) {
  const chartRef = useRef<ChartApiRef<Time, IChartApi>>(null);
  const seriesRef = useRef<SeriesApiRef<"Candlestick">>(null);
  // The seed stays stable; mount with a new key for another dataset identity.
  const [seed] = useState(() => initialData.map(bar => ({ ...bar })));

  const fitted = useRef(false);

  useEffect(() => {
    let active = true;
    let frame = 0;
    let unsubscribe: (() => void) | undefined;

    const startWhenReady = () => {
      if (!active) return;
      const chart = chartRef.current?.api();
      const series = seriesRef.current?.api();
      if (!chart || !series) {
        frame = requestAnimationFrame(startWhenReady);
        return;
      }
      // Fit after initialization, then leave the viewport to the user.
      if (!fitted.current) {
        fitted.current = true;
        chart.timeScale().fitContent();
      }
      // After a resubscribe the series can hold newer bars than the seed, and
      // update() throws on a bar older than the series tail.
      const current = series.data();
      let lastTime = current[current.length - 1]?.time as UTCTimestamp | undefined;
      unsubscribe = subscribe(bar => {
        if (!active || (lastTime !== undefined && bar.time < lastTime)) return;
        series.update({ ...bar });
        lastTime = bar.time;
      });
    };
    startWhenReady();
    return () => {
      active = false;
      cancelAnimationFrame(frame);
      unsubscribe?.();
    };
  }, [subscribe]);

  return (
    <Chart
      ref={chartRef}
      options={{ autoSize: true, timeScale: { timeVisible: true } }}
      containerProps={{ style: { height: 360 } }}
    >
      <CandlestickSeries ref={seriesRef} data={seed} reactive={false} />
    </Chart>
  );
}
```

Keep `subscribe` stable: each new function closes and reopens the feed.

For explicit “Live” controls, call `chartRef.current?.api()?.timeScale().scrollToRealTime()`
from the control handler. `fitContent()` shows the entire dataset; it does not mean
“follow the last bar.” Upstream `shiftVisibleRangeOnNewBar` normally shifts only
when the last bar is visible. For controlled follow mode, turn automatic shifting
off and scroll after accepted updates only when follow mode is enabled.

## Failure modes and acceptance checks

- Rebuild the full snapshot when older bars are corrected. Tail-only examples
  deliberately ignore older updates; reconnect recovery must replace history.
- Pause drawing by stopping/buffering feed application if desired. Toggling
  `reactive` does not stop the socket or give an imperative chart a replay buffer.
- A trim or a batch append may call `setData()`; do not mutate earlier objects in
  place and expect the wrapper to detect that mutation.
- Avoid cloning the complete dataset on every render (for example `data.map(...)`
  in JSX): it allocates unnecessarily and can retrigger the reactive data effect.
  Preserving references does not bypass the baseline's `setData()` limitation
  above. Use the chart-owned recipe when frequent full replacements are costly.
- Confirm initial data is sorted and unique; a same-time update replaces exactly
  one bar; a later-time update adds one; an older-time update follows the chosen
  correction policy. Pan left, update, and verify the user's viewport remains.
- In the chart-owned recipe, change `subscribe` after live bars arrive and replay
  an older bar: nothing throws, the bar is ignored, and the viewport does not move.
- Change symbol/interval and verify the old subscription is disposed and no old
  bars enter the new chart. Check a narrow card and a client-rendered route for a
  nonzero canvas size.
numeric-axes-and-chart-types.md 10.3 KB
# Numeric axes and chart types

Use this for an options surface slice over strikes, a payoff profile over
underlying prices, a yield curve over maturities, or a custom horizontal scale.
The misleading part is that upstream series call the x field `time` even when
the horizontal item is a **number representing a strike or maturity**.

## Choose the chart constructor from the horizontal domain

| Horizontal domain                            | Wrapper                 | Series/type contract                               |
| -------------------------------------------- | ----------------------- | -------------------------------------------------- |
| Dates or UTC time                            | `Chart`                 | `Time`, including UTC-second timestamps            |
| Strike / underlying price                    | `OptionsChart`          | `number`, e.g. `LineData<number>`                  |
| Time to maturity in one numeric unit         | `YieldCurveChart`       | `number`; only `LineSeries` and `AreaSeries`       |
| A genuinely different horizontal behavior    | `CustomChart`           | Explicit `IHorzScaleBehavior<HorzScaleItem>`       |
| Existing dates with a different label format | Usually `Chart` options | A formatter may be enough; no new domain is needed |

Do not convert strikes into `UTCTimestamp` just to satisfy `Chart` typings.
For yield curves, decide whether one x unit is a month or a year and keep every
dataset and formatter consistent. All numeric x values must be finite, ascending,
and unique. A refreshed curve is normally a full snapshot, not an appended tick.

## Recipe: implied volatility by strike

The pricing/market-data layer supplies volatility **in percentage points**, so
24.5 means 24.5%, not 0.245. This component visualizes those observations; it does
not price options or calculate volatility. Different expiries can be represented
by separate line series when they use the same strike domain.

```tsx
import type { DeepPartial, LineData, PriceChartOptions } from "lightweight-charts";
import {
  LineSeries,
  OptionsChart,
  TimeScale,
  TimeScaleFitContentTrigger,
} from "lightweight-charts-react-components";

const strikeOptions = {
  autoSize: true,
  // Built-in horizontal ticks use precision. timeFormatter formats the
  // horizontal crosshair label; the series controls the vertical value format.
  localization: {
    precision: 0,
    timeFormatter: (strike: number) => `$${strike.toFixed(0)}`,
  },
} satisfies DeepPartial<PriceChartOptions>;

export function VolatilitySmile({
  data,
  expiryId,
}: {
  data: LineData<number>[];
  expiryId: string;
}) {
  return (
    <OptionsChart
      key={expiryId}
      options={strikeOptions}
      containerProps={{ style: { height: 320 } }}
    >
      <LineSeries<number>
        data={data}
        alwaysReplaceData
        options={{
          color: "#2563eb",
          priceLineVisible: false,
          priceFormat: {
            type: "custom",
            minMove: 0.01,
            formatter: (value: number) => `${value.toFixed(2)}%`,
          },
        }}
      />
      <TimeScale<number>>
        <TimeScaleFitContentTrigger deps={[]} />
      </TimeScale>
    </OptionsChart>
  );
}

export const exampleSmile: LineData<number>[] = [
  { time: 80, value: 31.2 },
  { time: 90, value: 26.5 },
  { time: 100, value: 24.5 },
  { time: 110, value: 25.7 },
  { time: 120, value: 29.1 },
];
```

`expiryId` changes dataset identity and resets the chart's initial view. Routine
quote refreshes keep it stable and replace data without fitting each refresh.
Choose strike precision from the instrument; whole-dollar labels here are merely
the sample domain. Numeric x ticks are whole strikes, and the horizontal crosshair
label includes the currency prefix. A payoff chart uses the same wrapper with y
values and a formatter representing payoff currency instead of volatility.

Do not use `localization.priceFormatter` to label strikes: it overrides the
**vertical** price-scale formatter, including a series custom price formatter.
The built-in numeric horizontal behavior uses `localization.precision` for ticks
and `localization.timeFormatter` for the horizontal crosshair label. Formatting
every horizontal tick with a prefix requires an appropriate custom behavior.

## Recipe: current and previous yield curves

Both datasets use **months to maturity** for x and percentage points for y. The
wrapper configures upstream yield-curve semantics; it is not a date-time chart
with labels renamed. The two lines share a scale so their levels are comparable.

```tsx
import type { DeepPartial, LineData, YieldCurveChartOptions } from "lightweight-charts";
import {
  LineSeries,
  TimeScale,
  TimeScaleFitContentTrigger,
  YieldCurveChart,
} from "lightweight-charts-react-components";

const yieldOptions = {
  autoSize: true,
  localization: { priceFormatter: (value: number) => `${value.toFixed(2)}%` },
  yieldCurve: {
    startTimeRange: 0,
    minimumTimeRange: 360,
    formatTime: (months: number) => (months < 12 ? `${months}M` : `${months / 12}Y`),
  },
} satisfies DeepPartial<YieldCurveChartOptions>;

export function YieldComparison({
  current,
  previous,
  curveId,
}: {
  current: LineData<number>[];
  previous: LineData<number>[];
  curveId: string;
}) {
  return (
    <YieldCurveChart
      key={curveId}
      options={yieldOptions}
      containerProps={{ style: { height: 320 } }}
    >
      <LineSeries<number>
        data={current}
        alwaysReplaceData
        options={{ color: "#2563eb", priceLineVisible: false }}
      />
      <LineSeries<number>
        data={previous}
        alwaysReplaceData
        options={{ color: "#94a3b8", lineStyle: 2, priceLineVisible: false }}
      />
      <TimeScale<number>>
        <TimeScaleFitContentTrigger deps={[]} />
      </TimeScale>
    </YieldCurveChart>
  );
}

export const exampleYields: LineData<number>[] = [
  { time: 1, value: 4.8 },
  { time: 6, value: 4.5 },
  { time: 12, value: 4.1 },
  { time: 60, value: 3.7 },
  { time: 120, value: 3.6 },
  { time: 360, value: 3.8 },
];
```

`YieldCurveChart` accepts only line and area series through the wrapper's runtime
guard. Do not add candle, bar, histogram, or custom series to this chart. The
minimum 360-month span is an explicit display choice here; adapt it to the
product's intended tenor domain. Negative yield values remain legitimate y data;
do not clamp them to zero.

## Recipe: reuse upstream time behavior for quarterly labels

This is a custom behavior example when an application chooses to package its
quarterly formatting as an upstream horizontal-scale behavior. For simple label
changes, ordinary `timeScale.tickMarkFormatter` and `localization.timeFormatter`
on `Chart` are smaller. Extend the default behavior instead of reimplementing
sorting, time conversion, caching, and tick generation.

```tsx
import { useState } from "react";
import { defaultHorzScaleBehavior } from "lightweight-charts";
import type { LineData, LocalizationOptions, TickMark, Time } from "lightweight-charts";
import {
  CustomChart,
  LineSeries,
  TimeScale,
  TimeScaleFitContentTrigger,
} from "lightweight-charts-react-components";

function quarterLabel(time: Time): string {
  const date =
    typeof time === "number"
      ? new Date(time * 1000)
      : typeof time === "string"
        ? new Date(`${time}T00:00:00Z`)
        : new Date(Date.UTC(time.year, time.month - 1, time.day));
  return `Q${Math.floor(date.getUTCMonth() / 3) + 1} ${date.getUTCFullYear()}`;
}

const DefaultTimeBehavior = defaultHorzScaleBehavior();
function isTime(time: unknown): time is Time {
  return (
    typeof time === "number" ||
    typeof time === "string" ||
    (typeof time === "object" &&
      time !== null &&
      "year" in time &&
      typeof time.year === "number" &&
      "month" in time &&
      typeof time.month === "number" &&
      "day" in time &&
      typeof time.day === "number")
  );
}

class QuarterBehavior extends DefaultTimeBehavior {
  override formatTickmark(
    mark: TickMark,
    _localization: LocalizationOptions<Time>
  ): string {
    // TickMark.originalTime is unknown; narrow it before formatting.
    return isTime(mark.originalTime)
      ? quarterLabel(mark.originalTime)
      : super.formatTickmark(mark, _localization);
  }
}

export function QuarterlyChart({ data }: { data: LineData<Time>[] }) {
  // This constructor behavior belongs to one chart instance. Changing the
  // behavior later requires a chart remount rather than an options update.
  const [behavior] = useState(() => new QuarterBehavior());
  return (
    <CustomChart<Time, QuarterBehavior>
      horzScaleBehavior={behavior}
      options={{ autoSize: true, localization: { timeFormatter: quarterLabel } }}
      containerProps={{ style: { height: 320 } }}
    >
      <LineSeries data={data} />
      <TimeScale>
        <TimeScaleFitContentTrigger deps={[]} />
      </TimeScale>
    </CustomChart>
  );
}
```

Use quarterly observations for quarterly labels; applying this formatter to
daily observations can produce repeated quarter labels. The `time` field still
contains valid dates/UTC times. For a non-time domain, implement its actual
`IHorzScaleBehavior` contract and pass the matching horizontal type through
`CustomChart`, series, `TimeScale`, refs, and handlers. Do not use a cast to mask
an incompatible horizontal domain.

## Refs, events, and acceptance checks

Numeric charts' handlers receive `MouseEventParams<number>`. A hovered `param.time`
is a strike or tenor, not epoch seconds. Format it with that domain's formatter;
do not call `new Date(param.time * 1000)`. Numeric series refs use
`SeriesApiRef<"Line", number>`; numeric scale refs use `TimeScaleApiRef<number>`.
For native chart methods, type the wrapper ref with the corresponding upstream
`IChartApiBase<number>` or `IYieldCurveChartApi` API type.

- Verify a strike at 100 is labeled as a strike and volatility 24.5 as 24.5%.
  Refresh the entire smile and ensure removed strikes disappear.
- Verify tenors 6, 12, and 120 mean 6M, 1Y, and 10Y. Test negative yields and
  both curves on one scale. Change curve identity and verify the initial range.
- Confirm non-line/area series are rejected for yield curves. Check that custom
  behavior instances remain stable during unrelated application renders.
- Hover every chart type and verify the correct horizontal item type reaches
  the tooltip. Test quarterly labels around year and timezone boundaries.
performance-comparison.md 7.2 KB
# Performance comparison

Use this when users want to compare several assets whose raw prices differ by
orders of magnitude. A line at 200 and a line at 2 are rarely a useful performance
comparison. Choose and name the comparison baseline before picking a scale mode.

## Two meanings of percentage comparison

| Product requirement                            | Data and scale                                              | Consequence                                             |
| ---------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------- |
| Relative movement from the first visible value | Raw prices with `PriceScaleMode.Percentage`                 | Baseline can move when the viewport moves               |
| Return since a fixed date or session open      | Calculate returns upstream, plot on `PriceScaleMode.Normal` | Panning cannot change the meaning of the plotted return |

The recipe below uses a fixed shared baseline. Do not apply percentage scale mode
again to already-calculated returns. It would normalize data a second time and
the starting zero is unsuitable as a percentage denominator.

## Recipe: aligned, fixed-baseline return comparison

Each asset supplies ascending unique UTC-second prices on the desired calendar.
Every value is finite; baseline prices must be positive. Inputs should use the
same currency and adjustment policy when that matters to the requested comparison.
This code displays **price return**, not total return including dividends.

Choose the earliest loaded timestamp present in all assets as the shared baseline.
Keep later gaps as gaps; never invent a price by filling from a different date.
For a contractual “since date X” requirement, have the adapter supply a common
baseline observation at X or report the missing baseline instead of silently
moving it. Mount with a stable dataset key so the initial fit corresponds to the
completed snapshot.

```tsx
import { useMemo, useState } from "react";
import { PriceScaleMode } from "lightweight-charts";
import type { LineData, UTCTimestamp } from "lightweight-charts";
import {
  Chart,
  LineSeries,
  Pane,
  TimeScale,
  TimeScaleFitContentTrigger,
} from "lightweight-charts-react-components";

export type Asset = {
  id: string;
  label: string;
  color: string;
  data: LineData<UTCTimestamp>[];
};

export function buildComparison(assets: Asset[]) {
  if (assets.length === 0) return null;
  const indexes = assets.map(
    asset => new Map(asset.data.map(point => [point.time, point.value]))
  );
  const baselineTime = assets[0].data.find(point =>
    indexes.every(index => index.has(point.time))
  )?.time;
  if (baselineTime === undefined) return null;

  const series = assets.map((asset, index) => {
    const baseline = indexes[index].get(baselineTime);
    if (baseline === undefined || !Number.isFinite(baseline) || baseline <= 0) {
      throw new Error(`Invalid baseline for ${asset.id}`);
    }
    const data = asset.data
      .filter(point => point.time >= baselineTime)
      .map(point => ({ time: point.time, value: (point.value / baseline - 1) * 100 }));
    return { ...asset, data };
  });
  return { baselineTime, series };
}

export function ReturnComparison({ assets }: { assets: Asset[] }) {
  const comparison = useMemo(() => buildComparison(assets), [assets]);
  const [hidden, setHidden] = useState<Set<string>>(() => new Set());
  if (!comparison) return <p>No common baseline observation</p>;
  const baselineLabel = new Date(comparison.baselineTime * 1000)
    .toISOString()
    .slice(0, 10);

  return (
    <section>
      <p>Price return since {baselineLabel} UTC</p>
      {comparison.series.map(asset => (
        <button
          key={asset.id}
          aria-pressed={!hidden.has(asset.id)}
          onClick={() =>
            setHidden(previous => {
              const next = new Set(previous);
              if (next.has(asset.id)) next.delete(asset.id);
              else next.add(asset.id);
              return next;
            })
          }
        >
          {asset.label}
        </button>
      ))}
      <Chart
        options={{ autoSize: true, rightPriceScale: { mode: PriceScaleMode.Normal } }}
        containerProps={{ style: { height: 360 } }}
      >
        <Pane>
          {comparison.series.map(asset => (
            <LineSeries
              key={asset.id}
              data={asset.data}
              options={{
                color: asset.color,
                visible: !hidden.has(asset.id),
                priceScaleId: "right",
                priceLineVisible: false,
                priceFormat: {
                  type: "custom",
                  minMove: 0.01,
                  formatter: (value: number) =>
                    `${value >= 0 ? "+" : ""}${value.toFixed(2)}%`,
                },
              }}
            />
          ))}
        </Pane>
        <TimeScale>
          {/* Toggling a comparison changes visibility, not its baseline or view. */}
          <TimeScaleFitContentTrigger deps={[comparison.baselineTime]} />
        </TimeScale>
      </Chart>
    </section>
  );
}
```

All lines share one price scale because the transformed values have the same
unit. A stable series ID preserves the upstream series when labels change or
input order changes. `visible` keeps series mounted; conditional mounting is also
valid when removing the series is intended, but may change the shared timeline.
Keeping a hidden series can retain its time positions in that timeline.

## Adaptation boundaries

The earliest-common baseline is suitable for a complete, fixed initial snapshot.
Prepending older history can change it. If the product promises a fixed baseline,
store the chosen baseline time/prices in the application's comparison state and
reuse them for subsequent snapshots; loading history must not redefine “return.”
Likewise, toggling visibility must not recalculate the baseline from only the
visible subset. The recipe always calculates across the full asset list.

If calendars differ, choose the intersection baseline explicitly and leave later
missing observations absent or insert whitespace points on a shared calendar.
Do not align by array index. Crosshair details should read each series' event
entry and show `—` when it is missing; see [hover details](hover-legends-and-tooltips.md).

If the task is explicitly “percentage change relative to the currently visible
window,” use raw price arrays and `rightPriceScale.mode: PriceScaleMode.Percentage`
instead. Label this behavior because zooming and panning can change the displayed
percentage baseline. Use separate axes or panes for metrics with different units.

## Acceptance checks

- At the shared baseline all assets equal 0%. A price moving from 100 to 110
  yields +10%, and from 100 to 90 yields −10%.
- Compare assets priced at 1 and 1000 with the same proportional movement.
  Their return lines coincide. Pan and verify the fixed values do not change.
- Toggle one asset, change input ordering, and update a last price. IDs, colors,
  and the baseline retain their intended meaning.
- Test no common time, missing observations, and an invalid baseline. Do not
  substitute zero or forward-fill a missing price without a product requirement.
price-volume-and-indicators.md 9.9 KB
# Price, volume, and indicators

Use this for a technical-analysis view with candles, a moving average, volume,
and optionally an oscillator. The architecture depends on **units**, not on
series type: an SMA shares the price axis; volume needs a separate scale; RSI
usually needs its own pane. Indicators are data series supplied by the application;
the wrapper does not calculate them or fetch market data.

## Choose the layout before adding series

| Desired result               | Placement and scale                            | Why                                           |
| ---------------------------- | ---------------------------------------------- | --------------------------------------------- |
| Candles and SMA              | Same `Pane`, `priceScaleId: "right"`           | Both values are prices                        |
| Readable volume panel        | Separate `Pane`, its own right scale           | Volume cannot compress the price scale        |
| Compact volume under candles | Same pane, `priceScaleId: "volume"` for volume | Independent overlay scale with bottom margins |
| RSI with threshold lines     | Separate pane; RSI series owns the lines       | Different units and useful fixed bounds       |

Prefer one chart with multiple panes when the plots share an instrument and
timeline. They automatically share the horizontal scale and crosshair; no
two-chart synchronization code is needed. `stretchFactor` is a relative weight,
not pixels. Explicit `Pane` components also give watermarks and pane primitives
a valid pane context.

## Recipe: price/SMA, volume, optional RSI

The component expects normalized ascending unique UTC-second candles with volume
attached to every candle. It takes RSI from an upstream calculation (such as
Wilder RSI-14) rather than quietly implementing a different RSI formula. Values
are numbers in the range 0–100. Their timestamps must refer to this candle grid;
the indicator can omit its initial warm-up period.

The local SMA is a simple trailing arithmetic mean, including the current candle.
Its warm-up points are whitespace, not zero prices. Recomputing is suitable for
moderate histories; a high-rate application can calculate incrementally in its
data layer using the same period and timestamp contract.

```tsx
import { useMemo, useState } from "react";
import type {
  CandlestickData,
  HistogramData,
  LineData,
  UTCTimestamp,
  WhitespaceData,
} from "lightweight-charts";
import {
  CandlestickSeries,
  Chart,
  HistogramSeries,
  LineSeries,
  Pane,
  PriceLine,
  TimeScale,
  TimeScaleFitContentTrigger,
  WatermarkText,
} from "lightweight-charts-react-components";

type CandleWithVolume = CandlestickData<UTCTimestamp> & { volume: number };
type SmaPoint = LineData<UTCTimestamp> | WhitespaceData<UTCTimestamp>;

export function trailingSma(candles: CandleWithVolume[], period: number): SmaPoint[] {
  if (!Number.isInteger(period) || period < 1) throw new Error("Invalid SMA period");
  let sum = 0;
  return candles.map((bar, index) => {
    sum += bar.close;
    if (index >= period) sum -= candles[index - period].close;
    return index + 1 < period
      ? { time: bar.time }
      : { time: bar.time, value: sum / period };
  });
}

export function AnalysisChart({
  candles,
  rsi,
  datasetId,
}: {
  candles: CandleWithVolume[];
  rsi: LineData<UTCTimestamp>[];
  datasetId: string;
}) {
  const [showRsi, setShowRsi] = useState(true);
  const price = useMemo(
    () =>
      candles.map(({ time, open, high, low, close }) => ({
        time,
        open,
        high,
        low,
        close,
      })),
    [candles]
  );
  const volume = useMemo<HistogramData<UTCTimestamp>[]>(
    () =>
      candles.map(bar => ({
        time: bar.time,
        value: bar.volume,
        color: bar.close >= bar.open ? "#26a69a80" : "#ef535080",
      })),
    [candles]
  );
  const sma = useMemo(() => trailingSma(candles, 20), [candles]);

  return (
    <section>
      <button onClick={() => setShowRsi(value => !value)}>
        {showRsi ? "Hide RSI" : "Show RSI"}
      </button>
      <Chart
        key={datasetId}
        options={{ autoSize: true, layout: { panes: { enableResize: true } } }}
        containerProps={{ style: { height: 540 } }}
      >
        <Pane stretchFactor={3}>
          <CandlestickSeries data={price} options={{ priceScaleId: "right" }} />
          <LineSeries
            data={sma}
            options={{
              priceScaleId: "right",
              color: "#2962ff",
              lineWidth: 2,
              priceLineVisible: false,
            }}
          />
          <WatermarkText
            lines={[{ text: "PRICE + SMA 20", color: "#64748b80", fontSize: 14 }]}
          />
        </Pane>
        <Pane stretchFactor={1}>
          <HistogramSeries
            data={volume}
            options={{ priceFormat: { type: "volume" }, priceLineVisible: false }}
          />
          <WatermarkText lines={[{ text: "VOLUME", color: "#64748b80", fontSize: 14 }]} />
        </Pane>
        {showRsi && (
          <Pane stretchFactor={1}>
            <LineSeries
              data={rsi}
              options={{
                color: "#a855f7",
                priceLineVisible: false,
                // Supply bounds through the series, so the correct pane scale
                // is constrained without a chart-level scale lookup.
                autoscaleInfoProvider: () => ({
                  priceRange: { minValue: 0, maxValue: 100 },
                }),
              }}
            >
              <PriceLine
                price={70}
                options={{ title: "70", color: "#a855f7", lineStyle: 2 }}
              />
              <PriceLine
                price={30}
                options={{ title: "30", color: "#a855f7", lineStyle: 2 }}
              />
            </LineSeries>
            <WatermarkText
              lines={[{ text: "RSI 14", color: "#64748b80", fontSize: 14 }]}
            />
          </Pane>
        )}
        <TimeScale>
          {/* Pane visibility changes should not reset horizontal zoom. */}
          <TimeScaleFitContentTrigger deps={[]} />
        </TimeScale>
      </Chart>
    </section>
  );
}
```

Mount this after the initial snapshot is ready. `datasetId` changes only when the
symbol, interval, or intended initial view changes, not on every live tick. Fresh
indicator arrays legitimately cause full replacements. If frequent recalculation
is expensive, move it into the data owner rather than mutating chart input objects.

## Recipe: compact volume overlay with the correct scale owner

The current `PriceScale` component requires a `Pane`, but its implementation
calls `chart.priceScale(id)` without a pane index. In later panes this can target
pane zero, and a named overlay scale may not exist there. Do not use
`<PriceScale id="volume" />` as the mechanism for creating the overlay scale.
Creating the volume series with `priceScaleId: "volume"` creates/uses that scale;
then `volumeSeries.api().priceScale()` targets its actual pane.

Copy this alternative as its own module. The ready loop handles the wrapper ref
being assigned before the native series exists. The cleanup cancels only that
loop; the wrapper owns removal of the series and chart.

```tsx
import { useEffect, useRef } from "react";
import type { CandlestickData, HistogramData, UTCTimestamp } from "lightweight-charts";
import {
  CandlestickSeries,
  Chart,
  HistogramSeries,
  Pane,
  TimeScale,
  TimeScaleFitContentTrigger,
  type SeriesApiRef,
} from "lightweight-charts-react-components";

export function PriceWithVolumeOverlay({
  price,
  volume,
}: {
  price: CandlestickData<UTCTimestamp>[];
  volume: HistogramData<UTCTimestamp>[];
}) {
  const priceRef = useRef<SeriesApiRef<"Candlestick">>(null);
  const volumeRef = useRef<SeriesApiRef<"Histogram">>(null);

  useEffect(() => {
    let frame = 0;
    const configureScales = () => {
      const priceSeries = priceRef.current?.api();
      const volumeSeries = volumeRef.current?.api();
      if (!priceSeries || !volumeSeries) {
        frame = requestAnimationFrame(configureScales);
        return;
      }
      priceSeries
        .priceScale()
        .applyOptions({ scaleMargins: { top: 0.05, bottom: 0.25 } });
      volumeSeries.priceScale().applyOptions({ scaleMargins: { top: 0.8, bottom: 0 } });
    };
    configureScales();
    return () => cancelAnimationFrame(frame);
  }, []);

  return (
    <Chart options={{ autoSize: true }} containerProps={{ style: { height: 360 } }}>
      <Pane>
        <CandlestickSeries
          ref={priceRef}
          data={price}
          options={{ priceScaleId: "right" }}
        />
        <HistogramSeries
          ref={volumeRef}
          data={volume}
          options={{
            priceScaleId: "volume",
            priceFormat: { type: "volume" },
            priceLineVisible: false,
            lastValueVisible: false,
          }}
        />
      </Pane>
      <TimeScale>
        <TimeScaleFitContentTrigger deps={[]} />
      </TimeScale>
    </Chart>
  );
}
```

An overlay scale named `volume` has no visible price axis of its own. Use a
separate pane or visible left axis when users need volume axis labels. Margins
reserve vertical regions on independent scales; they do not rescale or normalize
the input data. If moving a series to another pane imperatively, reacquire its
`priceScale()` after the move rather than keeping a prior scale handle.

## Acceptance checks

- Price remains readable when volume increases by orders of magnitude. Confirm
  the SMA uses the same units and right scale as candles.
- With fewer than 20 candles, SMA is whitespace. At the twentieth bar it equals
  the mean of the first 20 closes. Replacing the last candle recomputes its SMA.
- RSI stays on a 0–100 axis; 30/70 lines belong only to RSI. Toggle its pane and
  verify existing series remain on their original panes and zoom stays intact.
- Render the overlay in a later pane while adapting the recipe: its scale must
  come from the volume series, with no incorrect-ID error on pane zero.
session-overlays-and-primitives.md 10.1 KB
# Session overlays and primitives

Use this for market-session shading, selected backtest intervals, maintenance
windows, or custom annotations that must follow chart scrolling and zooming.
The overlay should stay attached to chart coordinates rather than a DOM pixel
rectangle captured once.

## Choose the narrowest extension

| Needed visual                                            | Implementation                                        | Reason                                                      |
| -------------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------------- |
| Event on one bar                                         | `Markers`                                             | Built-in marker layout                                      |
| Horizontal threshold                                     | `PriceLine`                                           | Built-in price conversion and axis label                    |
| Background across a pane                                 | `PanePrimitive`                                       | It belongs to the pane, not one series' price scale         |
| Price-dependent drawing, series axis labels, hit testing | `SeriesPrimitive`                                     | Native attachment supplies the owning series                |
| A new data series renderer                               | `CustomSeries` with an `ICustomSeriesPaneView` plugin | It participates as a series, including data and autoscaling |
| New horizontal-axis semantics                            | `CustomChart`                                         | A renderer is not a horizontal-scale behavior               |

## Recipe: reusable session bands on price and volume panes

Session boundaries are prepared by the application's market-calendar adapter as
UTC-second timestamps. Do not hard-code a fixed UTC offset for exchanges that
observe daylight saving time. The example shades from `from` to `to` between
the **centers** of two loaded timeline observations; it does not extend through
half a bar on either side.

This concrete plugin skips bands whose endpoints cannot be converted by
`timeToCoordinate()`. For windows beginning outside loaded history, clip to the
loaded timeline in the adapter. If the product needs exact boundaries between
bars, provide an explicit boundary-to-coordinate interpolation policy instead of
pretending an unknown time maps automatically.

Save this as `SessionBands.ts`. Inferring the draw target's type from the upstream
renderer interface avoids introducing a direct runtime dependency on
`fancy-canvas`. Media coordinate space uses CSS pixels and handles device pixel
ratios through the target; bitmap coordinate space would require explicit x/y
pixel-ratio conversion.

```ts file=SessionBands.ts
import type {
  IChartApiBase,
  IPanePrimitive,
  IPanePrimitivePaneView,
  IPrimitivePaneRenderer,
  PaneAttachedParameter,
  Time,
  UTCTimestamp,
} from "lightweight-charts";

export type SessionBand = {
  id: string;
  from: UTCTimestamp;
  to: UTCTimestamp;
  color: string;
};
type DrawTarget = Parameters<IPrimitivePaneRenderer["draw"]>[0];
type Rect = { x: number; width: number; color: string };

export class SessionBands implements IPanePrimitive<Time> {
  private rects: Rect[] = [];
  private requestUpdate: (() => void) | undefined;
  private readonly views: IPanePrimitivePaneView[];

  constructor(
    private readonly chart: IChartApiBase<Time>,
    private bands: SessionBand[]
  ) {
    this.views = [
      {
        zOrder: () => "bottom", // Shading remains behind candles and volume.
        renderer: () => ({ draw: target => this.draw(target) }),
      },
    ];
  }

  attached({ requestUpdate }: PaneAttachedParameter<Time>) {
    this.requestUpdate = requestUpdate;
  }

  detached() {
    this.requestUpdate = undefined;
  }

  setBands(bands: SessionBand[]) {
    this.bands = bands;
    this.requestUpdate?.(); // External plugin mutations need a redraw request.
  }

  updateAllViews() {
    const scale = this.chart.timeScale();
    this.rects = this.bands.flatMap(band => {
      const from = scale.timeToCoordinate(band.from);
      const to = scale.timeToCoordinate(band.to);
      if (from === null || to === null) return [];
      return [{ x: Math.min(from, to), width: Math.abs(to - from), color: band.color }];
    });
  }

  paneViews() {
    return this.views;
  }

  private draw(target: DrawTarget) {
    target.useMediaCoordinateSpace(({ context, mediaSize }) => {
      context.save();
      for (const rect of this.rects) {
        context.fillStyle = rect.color;
        context.fillRect(rect.x, 0, rect.width, mediaSize.height);
      }
      context.restore();
    });
  }
}
```

Save the following as `SessionChart.tsx`. `candles` and `volume` share the same
normalized ascending UTC-second grid. A stable `bands` array preserves the
render callback's identity. A new array intentionally recreates the primitives
with the new session definition.

```tsx
import { useCallback, useState } from "react";
import type { CandlestickData, HistogramData, UTCTimestamp } from "lightweight-charts";
import {
  CandlestickSeries,
  Chart,
  HistogramSeries,
  Pane,
  PanePrimitive,
  TimeScale,
  TimeScaleFitContentTrigger,
  type RenderPanePrimitive,
} from "lightweight-charts-react-components";
import { SessionBands, type SessionBand } from "./SessionBands";

export function SessionChart({
  candles,
  volume,
  bands,
}: {
  candles: CandlestickData<UTCTimestamp>[];
  volume: HistogramData<UTCTimestamp>[];
  bands: SessionBand[];
}) {
  const [showBands, setShowBands] = useState(true);
  const renderBands = useCallback<RenderPanePrimitive>(
    ({ chart }) => new SessionBands(chart, bands),
    [bands]
  );

  return (
    <section>
      <button onClick={() => setShowBands(value => !value)}>
        {showBands ? "Hide sessions" : "Show sessions"}
      </button>
      <Chart options={{ autoSize: true }} containerProps={{ style: { height: 450 } }}>
        <Pane stretchFactor={3}>
          <CandlestickSeries data={candles} />
          {/* Each invocation constructs a separate attachment instance. */}
          {showBands && <PanePrimitive render={renderBands} />}
        </Pane>
        <Pane stretchFactor={1}>
          <HistogramSeries data={volume} options={{ priceFormat: { type: "volume" } }} />
          {showBands && <PanePrimitive render={renderBands} />}
        </Pane>
        <TimeScale>
          <TimeScaleFitContentTrigger deps={[]} />
        </TimeScale>
      </Chart>
    </section>
  );
}
```

`PanePrimitive` requires a `Pane` ancestor; it throws outside one. A primitive
can be passed as `plugin` **or** created with `render`, not both. The render
factory receives initialized `{ chart, pane }`; it is useful when construction
needs those APIs. The wrapper attaches it and detaches it on unmount.

## Identity and updating choices

The wrapper uses `plugin ?? render` identity as the attachment identity. A new
plugin object or callback detaches the previous instance and attaches a new one.
Do not inline a new factory on every pointer move or tick. The recipe memoizes
it by the session definition, so intentional definition changes recreate it.
Do not reuse one stateful plugin instance across two panes/charts: its attached
state and redraw callback belong to one attachment.

For frequent changes, create a stable plugin and call its own `setBands()` method
through an application-owned instance or ref. The wrapper's primitive ref exposes
the upstream interface, not custom methods; keep the concrete plugin typed in
application code when calling those methods. `setBands()` above requests a redraw;
changing a class field without that request need not repaint immediately.

Compute coordinates in `updateAllViews()`, then draw the cached views. Upstream
invokes this during relevant chart updates, so scrolling/zooming refreshes the
geometry. Do not calculate x once in a React effect and retain it through zoom.
If the plugin subscribes to external events, unsubscribe in `detached()` using
the same handler identity. This recipe has no custom event subscriptions.

## Series-specific drawings and custom-series boundaries

For a vertical event line with a time-axis label, use a `SeriesPrimitive` under
the target series. Implement `ISeriesPrimitive.updateAllViews()` to recalculate
and cache `chart.timeScale().timeToCoordinate(time)`, or delegate that work to a
pane view's own `update()` method. Lightweight Charts invokes the primitive's
`updateAllViews()` callback during chart updates. Return one `IPrimitivePaneView`
whose renderer fills a full-height rectangle in bitmap coordinate space (scale
x and width by `horizontalPixelRatio`), plus one `ISeriesPrimitiveAxisView` from
`timeAxisViews()` for the label. Format the label explicitly for UTC timestamps
or business dates; `.toString()` on a `BusinessDay` object does not give a useful
date. The `SeriesPrimitive` render factory receives `{ chart, series }`; use the
series API for price conversion when drawing price-dependent shapes.

For grouped volume bars or a genuinely new plot type, use `CustomSeries` with a
plugin implementing upstream `ICustomSeriesPaneView`. The plugin supplies
`renderer`, `update`, `priceValueBuilder`, `isWhitespace`, and `defaultOptions`.
The price-value builder must include all values that should participate in
autoscaling. Keep custom payloads in `customValues` and preserve
the custom data shape when updating. `CustomSeries` requires a plugin instance;
`CustomChart` instead changes the horizontal scale and is a different extension.

## Acceptance checks

- Pan, zoom, resize, and change device pixel ratio: bands remain attached to
  the intended bars and fill only their owning pane.
- Toggle sessions on/off repeatedly and change the bands array. Old attachments
  disappear and no stale background persists.
- Test missing/off-history endpoints and zero-width intervals against the stated
  clipping policy. Verify daylight-saving changes in the calendar adapter.
- For an external plugin update, call `setBands()` and verify it repaints without
  requiring the user to move the chart. Confirm each pane has its own instance.
synchronized-charts.md 8.7 KB
# Synchronized charts

Use this when independent chart cards need shared scrolling, zoom, and a cursor:
for example a price chart beside a benchmark or two separate dashboard widgets.
For price, volume, and indicators in a vertically stacked view, first use
[one chart with panes](price-volume-and-indicators.md); the shared horizontal scale
already provides that coordination.

The library has no dedicated synchronization component; the recipe below combines
the public chart and time-scale APIs.

## Choose the synchronization coordinate

| Relationship                        | Range to synchronize          | Constraint                                   |
| ----------------------------------- | ----------------------------- | -------------------------------------------- |
| Identical timestamp grid            | Time bounds or logical bounds | Same time/index meaning in both charts       |
| Different calendars or missing bars | Time bounds                   | Logical index 50 need not mean the same date |
| Same visible bar count only         | Logical bounds                | This is not necessarily calendar alignment   |

The recipe below requires the **same complete UTC-second grid in both charts**.
Use time bounds so the intended calendar window is explicit. With differing
histories, upstream range clamping can produce competing ranges; normalize the
shared domain first or use a designated leader and a documented follower-clamping
policy. Do not blindly use bidirectional callbacks over incompatible domains.

## Recipe: two line charts with range and crosshair synchronization

`first` and `second` contain sorted unique real-valued points with identical
timestamps. Mount by dataset identity after both snapshots load. Chart widths
can differ: time bounds synchronize the displayed dates, not pixel spacing.
`CrosshairMode.Normal` keeps cursor behavior predictable when transferring a
time/value to another series.

```tsx
import { useCallback, useEffect, useMemo, useRef } from "react";
import { CrosshairMode } from "lightweight-charts";
import type {
  IChartApi,
  IRange,
  LineData,
  MouseEventParams,
  Time,
  UTCTimestamp,
} from "lightweight-charts";
import {
  Chart,
  LineSeries,
  TimeScale,
  type ChartApiRef,
  type SeriesApiRef,
} from "lightweight-charts-react-components";

type Side = "first" | "second";
type Point = LineData<UTCTimestamp>;

export function SynchronizedCharts({
  first,
  second,
}: {
  first: Point[];
  second: Point[];
}) {
  const firstChart = useRef<ChartApiRef<Time, IChartApi>>(null);
  const secondChart = useRef<ChartApiRef<Time, IChartApi>>(null);
  const firstSeries = useRef<SeriesApiRef<"Line">>(null);
  const secondSeries = useRef<SeriesApiRef<"Line">>(null);
  const forwardingRange = useRef(false);
  const pointerOwner = useRef<Side | null>(null);
  const firstValues = useMemo(
    () => new Map(first.map(point => [point.time, point.value])),
    [first]
  );
  const secondValues = useMemo(
    () => new Map(second.map(point => [point.time, point.value])),
    [second]
  );

  const forwardRange = useCallback((source: Side, range: IRange<Time> | null) => {
    if (!range || forwardingRange.current) return;
    const target = (source === "first" ? secondChart : firstChart).current
      ?.api()
      ?.timeScale();
    if (!target) return;
    const existing = target.getVisibleRange();
    // Equality also stops deferred notifications after the synchronous guard
    // has been cleared. Inputs here use numeric timestamps exclusively.
    if (existing?.from === range.from && existing?.to === range.to) return;
    forwardingRange.current = true;
    try {
      target.setVisibleRange(range);
    } finally {
      forwardingRange.current = false;
    }
  }, []);

  const forwardCrosshair = useCallback(
    (source: Side, param: MouseEventParams) => {
      // Only a chart currently under the user's pointer can lead. Programmatic
      // changes on the follower must not become new input on the source.
      if (pointerOwner.current !== source) return;
      const targetChart = (source === "first" ? secondChart : firstChart).current?.api();
      const targetSeries = (
        source === "first" ? secondSeries : firstSeries
      ).current?.api();
      const values = source === "first" ? secondValues : firstValues;
      if (!targetChart || !targetSeries) return;
      const value =
        typeof param.time === "number"
          ? values.get(param.time as UTCTimestamp)
          : undefined;
      if (!param.point || value === undefined || typeof param.time !== "number") {
        targetChart.clearCrosshairPosition();
        return;
      }
      // A matching time uses the target's own value, never the source's price or
      // y pixel. The target series provides the correct price scale and pane.
      targetChart.setCrosshairPosition(value, param.time, targetSeries);
    },
    [firstValues, secondValues]
  );

  useEffect(() => {
    let frame = 0;
    const initialize = () => {
      const a = firstChart.current?.api();
      const b = secondChart.current?.api();
      if (!a || !b || !firstSeries.current?.api() || !secondSeries.current?.api()) {
        frame = requestAnimationFrame(initialize);
        return;
      }
      a.timeScale().fitContent();
      const range = a.timeScale().getVisibleRange();
      if (range) b.timeScale().setVisibleRange(range);
    };
    initialize();
    return () => cancelAnimationFrame(frame);
  }, []);

  const leave = () => {
    pointerOwner.current = null;
    firstChart.current?.api()?.clearCrosshairPosition();
    secondChart.current?.api()?.clearCrosshairPosition();
  };

  return (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 320px), 1fr))",
        gap: 16,
      }}
    >
      <Chart
        ref={firstChart}
        options={{ autoSize: true, crosshair: { mode: CrosshairMode.Normal } }}
        containerProps={{
          style: { height: 300 },
          onPointerEnter: () => {
            pointerOwner.current = "first";
          },
          onPointerLeave: leave,
        }}
        onCrosshairMove={param => forwardCrosshair("first", param)}
      >
        <LineSeries ref={firstSeries} data={first} options={{ color: "#2563eb" }} />
        <TimeScale onVisibleTimeRangeChange={range => forwardRange("first", range)} />
      </Chart>
      <Chart
        ref={secondChart}
        options={{ autoSize: true, crosshair: { mode: CrosshairMode.Normal } }}
        containerProps={{
          style: { height: 300 },
          onPointerEnter: () => {
            pointerOwner.current = "second";
          },
          onPointerLeave: leave,
        }}
        onCrosshairMove={param => forwardCrosshair("second", param)}
      >
        <LineSeries ref={secondSeries} data={second} options={{ color: "#ea580c" }} />
        <TimeScale onVisibleTimeRangeChange={range => forwardRange("second", range)} />
      </Chart>
    </div>
  );
}
```

Use `onPointerDown` as another owner-setting signal when adapting to touch input
whose hover behavior differs. The wrapper cleans up `TimeScale` and chart
subscriptions; this recipe cleans up only its own readiness frame. Do not remove
wrapper-owned native charts in a separate effect.

## Adaptation and failure modes

For intrabar precision or future right-side whitespace on identical grids, logical
bounds can preserve fractional bar positions better than time bounds. Replace
both range callbacks and getters/setters consistently with their logical variants,
and compare both numeric endpoints before setting. Keep a reentrancy guard as well.

For different calendars, resolve the target crosshair by exact time and clear it
when missing, as above. If the product wants nearest-previous matching, implement
that search deliberately and indicate the actual matched timestamp in hover UI.
Never copy the source y pixel or use its price on a target with different units.

Two independently fitting charts can undo synchronization after data changes.
Let a selected leader choose the view after both datasets update; follower charts
should not also fit on each tick. For large dashboard grids, store one shared
range in the application and broadcast only when endpoints change.

## Acceptance checks

- Pan/zoom either chart and verify the other shows matching dates without an
  event loop. Test differing widths and a resize of the cards.
- Move the crosshair in both directions. The target selects its own value at the
  same time, even when one series' values are 100 times larger.
- Leave a card or hover missing data: the follower cursor clears. Programmatic
  updates never become a new crosshair leader.
- Remount under a new dataset key and verify old callbacks/frames do not retain
  the removed chart. Test any calendar policy added during adaptation.
trade-markers-and-price-levels.md 10.1 KB
# Trade markers and price levels

Use this for execution history, strategy signals, entry/stop/target overlays, or
click-to-place horizontal levels. These are visual annotations. The chart does
not execute orders, persist edits, or turn a marker into a drawing tool.

## Choose the annotation by what it represents

| Requirement                                                | Primitive                           | Ownership                                                  |
| ---------------------------------------------------------- | ----------------------------------- | ---------------------------------------------------------- |
| An execution or signal at a candle                         | `Markers`                           | Child of the candle series                                 |
| A horizontal entry, stop, target, or alert level           | `PriceLine`                         | Child of the series whose price scale it uses              |
| A vertical event line, region, or arbitrary custom drawing | `SeriesPrimitive` / `PanePrimitive` | See [session overlays](session-overlays-and-primitives.md) |

Keep domain IDs stable. A level's React key must be its ID, not its changing price,
so edits update an existing price line. Marker order must be ascending by time;
multiple markers can belong to one candle. `Markers` expects the **complete list**
on every reactive change, including `[]` to clear it.

## Recipe: executions, editable levels, and click-to-place alerts

`candles` is an ascending unique UTC-second snapshot. Each execution's `barTime`
already identifies its containing candle on that exact timeline. The market-data
adapter must map an execution instant to a bar using the venue's interval and
session rules. A naive local-time rounding operation is unsafe for session-based
bars. Events outside loaded history are retained upstream and become visible
when that history is loaded.

```tsx
import { useCallback, useMemo, useRef, useState } from "react";
import { LineStyle } from "lightweight-charts";
import type {
  CandlestickData,
  MouseEventParams,
  SeriesMarker,
  UTCTimestamp,
} from "lightweight-charts";
import {
  CandlestickSeries,
  Chart,
  Markers,
  Pane,
  PriceLine,
  TimeScale,
  TimeScaleFitContentTrigger,
  type SeriesApiRef,
} from "lightweight-charts-react-components";

type Execution = {
  id: string;
  barTime: UTCTimestamp;
  side: "buy" | "sell";
  quantity: number;
};
type Level = { id: string; price: number; title: string; color: string };

const quantize = (rawPrice: number, tickSize: number, precision: number) =>
  Number((Math.round(rawPrice / tickSize) * tickSize).toFixed(precision));

function PriceInput({
  price,
  tickSize,
  precision,
  onCommit,
}: {
  price: number;
  tickSize: number;
  precision: number;
  onCommit: (price: number) => void;
}) {
  // Hold the typed text and round on commit. Rounding each keystroke would rewrite
  // the field mid-entry: with a tick of 5, typing "105" would turn "1" into 0.
  const [draft, setDraft] = useState<string | null>(null);
  const commit = () => {
    if (draft === null) return;
    setDraft(null);
    const rawPrice = Number(draft);
    if (draft !== "" && Number.isFinite(rawPrice)) {
      onCommit(quantize(rawPrice, tickSize, precision));
    }
  };
  return (
    <input
      type="number"
      step={tickSize}
      value={draft ?? price}
      onChange={event => setDraft(event.target.value)}
      onBlur={commit}
      onKeyDown={event => {
        if (event.key === "Enter") commit();
      }}
    />
  );
}

export function TradeAnnotations({
  candles,
  executions,
  initialLevels,
  tickSize,
  precision,
}: {
  candles: CandlestickData<UTCTimestamp>[];
  executions: Execution[];
  initialLevels: Level[];
  tickSize: number;
  precision: number;
}) {
  const seriesRef = useRef<SeriesApiRef<"Candlestick">>(null);
  const [levels, setLevels] = useState(initialLevels);
  const [showExecutions, setShowExecutions] = useState(true);
  const [placing, setPlacing] = useState(false);

  const markers = useMemo<SeriesMarker<UTCTimestamp>[]>(() => {
    if (!showExecutions) return [];
    const loadedTimes = new Set(candles.map(bar => bar.time));
    return executions
      .filter(execution => loadedTimes.has(execution.barTime))
      .map(execution => ({
        id: execution.id,
        time: execution.barTime,
        position:
          execution.side === "buy" ? ("belowBar" as const) : ("aboveBar" as const),
        shape: execution.side === "buy" ? ("arrowUp" as const) : ("arrowDown" as const),
        color: execution.side === "buy" ? "#16a34a" : "#dc2626",
        text: `${execution.side.toUpperCase()} ${execution.quantity}`,
      }))
      .sort((a, b) => a.time - b.time || a.id.localeCompare(b.id));
  }, [candles, executions, showExecutions]);

  const onClick = useCallback(
    (param: MouseEventParams) => {
      if (!placing || !param.point || !(tickSize > 0) || !Number.isFinite(tickSize))
        return;
      const series = seriesRef.current?.api();
      if (!series || param.paneIndex !== series.getPane().paneIndex()) return;
      // Convert from pane-local pixels using the target series' actual scale.
      // point.y is not a price and may refer to an unrelated pane.
      const rawPrice = series.coordinateToPrice(param.point.y);
      if (rawPrice === null || !Number.isFinite(rawPrice)) return;
      const price = quantize(rawPrice, tickSize, precision);
      const id = crypto.randomUUID();
      setLevels(previous => [
        ...previous,
        { id, price, title: "Alert", color: "#f59e0b" },
      ]);
      setPlacing(false);
    },
    [placing, tickSize, precision]
  );

  return (
    <section>
      <button onClick={() => setShowExecutions(value => !value)}>
        {showExecutions ? "Hide executions" : "Show executions"}
      </button>
      <button onClick={() => setPlacing(value => !value)}>
        {placing ? "Cancel placement" : "Place alert level"}
      </button>
      <Chart
        options={{ autoSize: true }}
        containerProps={{ style: { height: 360 } }}
        onClick={onClick}
      >
        <Pane>
          <CandlestickSeries
            ref={seriesRef}
            data={candles}
            options={{
              priceLineVisible: false,
              priceFormat: { type: "price", minMove: tickSize, precision },
            }}
          >
            <Markers markers={markers} options={{ zOrder: "normal" }} />
            {levels.map(level => (
              <PriceLine
                key={level.id}
                price={level.price}
                options={{
                  title: level.title,
                  color: level.color,
                  lineStyle: LineStyle.Dashed,
                  axisLabelVisible: true,
                }}
              />
            ))}
          </CandlestickSeries>
        </Pane>
        <TimeScale>
          <TimeScaleFitContentTrigger deps={[]} />
        </TimeScale>
      </Chart>
      {levels.map(level => (
        <label key={level.id} style={{ display: "block" }}>
          {level.title}
          <PriceInput
            price={level.price}
            tickSize={tickSize}
            precision={precision}
            onCommit={price =>
              setLevels(previous =>
                previous.map(item => (item.id === level.id ? { ...item, price } : item))
              )
            }
          />
          <button
            onClick={() =>
              setLevels(previous => previous.filter(item => item.id !== level.id))
            }
          >
            Remove
          </button>
        </label>
      ))}
    </section>
  );
}
```

Validate `tickSize` as a positive finite number and `precision` as the instrument's
supported nonnegative integer before rendering. The rounding above is display
rounding for a tick grid starting at zero. Instruments with different price-band
rules need the venue-specific quantizer; do not reuse this as an order validator.
`initialLevels` is a mount-time seed. Mount by instrument ID or replace it with a
controlled `levels`/`onLevelsChange` contract when annotation state lives upstream.

## Lifecycle and adaptation details

`PriceLine` reacts to both `price` and `options` changes and removes its upstream
line when unmounted. The explicit `price` prop is separate from `options`; do
not put the price only inside options. Disabling the candle series' default last
price line reduces visual confusion with domain levels.

`Markers` creates the upstream plugin and updates marker lists reactively, but
the current hook does not apply new `options` after creation. To change a plugin
option such as `zOrder`, remount `Markers` with a key identifying that option or
call `markersRef.current?.api()?.applyOptions(...)`. The latter requires a
`MarkersApiRef` and initialized API. Showing/hiding the list uses `markers={[]}`
without recreating the plugin.

For marker click details, `MouseEventParams.hoveredObjectId` can identify a marker
whose `id` was supplied. Resolve it against application execution IDs. For
draggable lines or regions, implement interaction and hit testing in a drawing
plugin; `PriceLine` alone has no drag callbacks.

Keep persistence and network changes in the application's annotation store.
Changing local chart state should not imply placing a live order or registering
an alert on a server. Add the application's explicit save/submit flow if requested.

## Acceptance checks

- Add two executions to the same candle, reorder input, and verify sorted markers
  remain. Hide them and verify the complete list is cleared; show them again.
- With a tick of 5, type 105 into a level's price: the field keeps each digit, and
  the line moves on blur or Enter. Clear the field and blur: the price is restored.
- Edit a level's price and title without changing its ID. Remove it and verify the
  line disappears. Change instrument and verify annotations do not leak across it.
- In placement mode, click the price pane at a known price. Verify tick rounding.
  Add another pane and verify clicks there do not create levels on the price series.
- Change marker options and verify the chosen remount/API path actually applies
  them; simply changing the options prop is insufficient in the current hook.

License (MIT)

View full license text
MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.