Skip to content

Chart libraries ​

A read's columns are what chart libraries take: one Float64Array of timestamps and one typed array per field, equal lengths, no holes. Ranges are inclusive at both ends, as Lightweight Charts' setVisibleRange and uPlot's scale min/max report them, so a chart's visible range goes straight into get. Two adaptations remain: the time unit (tscache uses milliseconds; Lightweight Charts takes seconds, and uPlot takes milliseconds once its ms option is 1) and the row shape a library wants.

The reference clients draw with either library behind one small interface:

ts
// A candle chart as the reference clients use it, whichever library draws
// it. A client hands it each answer of the cache and listens for the user
// scrolling, which asks the cache for the range then on screen. Copy the
// one implementation you use (lightweight.ts or uplot.ts) with this file;
// load.ts picks between them for a page that offers both.

import type { GetResult, Range } from "@anishbenji/tscache";

export interface ChartView {
  /**
   * Shows the answer's bars in place of the ones drawn. The time on screen
   * stays where it was, so bars loaded to the left of it do not move the
   * view. The first answer with bars shows the opening range. An answer
   * that differs from the last one only in its newest bars, as a live bar
   * does, redraws only those where the library can (appendedFrom).
   */
  draw(result: GetResult): void;
  /**
   * Calls `listener` with the time range on screen (ms, inclusive) each
   * time the user scrolls or zooms. Never for a change made by draw().
   * Returns the unsubscribe.
   */
  onScroll(listener: (visible: Range) => void): () => void;
  /** The time range on screen, once bars are drawn. */
  visible(): Range | undefined;
  /** Removes the chart from its element. */
  dispose(): void;
}

export interface ChartOptions {
  /** The cache's interval, in ms. */
  interval: number;
  /** The time range the first bars are shown at. */
  opening: Range;
}

export type CreateChart = (
  element: HTMLElement,
  options: ChartOptions,
) => ChartView;

/**
 * Whether two time ranges differ by more than half an interval: a view
 * reports a scroll only then, so its own redraws, which may report the
 * range they kept, are not taken for one.
 */
export function moved(a: Range | undefined, b: Range, interval: number) {
  return (
    a === undefined ||
    Math.abs(a.start - b.start) > interval / 2 ||
    Math.abs(a.end - b.end) > interval / 2
  );
}

/** Equal, taking NaN (a value the answer lacks) for equal to NaN. */
function same(a: number | undefined, b: number | undefined): boolean {
  return a === b || (Number.isNaN(a) && Number.isNaN(b));
}

/**
 * Where a chart that drew `before` starts to redraw for `after`, when
 * `after` differs from it only in its newest bars: the index in `after` of
 * the first bar to draw, which is `before`'s last bar when that bar (the
 * one forming) changed, and `before`'s length when nothing but new bars
 * did. Undefined when every bar must be drawn again: nothing drawn yet, an
 * answer without bars, other fields, or a change before the last bar
 * (a range that moved, a gap filled or opened, an earlier bar's values).
 *
 * It goes by the bars alone, so a new dataset version is caught by what it
 * changes: its cleared cache answers fewer bars, and its history other
 * values.
 */
export function appendedFrom(
  before: GetResult | undefined,
  after: GetResult,
): number | undefined {
  const count = before?.timestamps.length ?? 0;
  if (before === undefined || count === 0) return undefined;
  if (after.timestamps.length < count) return undefined;
  const names = Object.keys(after.fields);
  if (names.length !== Object.keys(before.fields).length) return undefined;
  const last = count - 1;
  for (let i = 0; i < count; i++) {
    if (before.timestamps[i] !== after.timestamps[i]) return undefined;
  }
  let from = count;
  for (const name of names) {
    const was = before.fields[name];
    const now = after.fields[name];
    if (was === undefined || now === undefined) return undefined;
    for (let i = 0; i < last; i++) {
      if (!same(was[i], now[i])) return undefined;
    }
    if (!same(was[last], now[last])) from = last;
  }
  return from;
}

/**
 * Counts a view's draws on its element, in `data-draws-full` (every bar
 * drawn) and `data-draws-appended` (only the newest, appendedFrom): what a
 * test reads to see that a live bar redraws only the bars it changed.
 */
export function countDraw(element: HTMLElement, appended: boolean): void {
  const key = appended ? "drawsAppended" : "drawsFull";
  element.dataset[key] = String(Number(element.dataset[key] ?? 0) + 1);
}

/**
 * The range to show after a redraw: where it was, or moved on with the
 * newest bar when the view showed that bar, so a live chart follows the
 * market while the user looks at its end and stays put while they read
 * history.
 */
export function keptRange(
  shown: Range,
  lastBefore: number | undefined,
  lastNow: number | undefined,
): Range {
  if (lastBefore === undefined || lastNow === undefined) return shown;
  if (shown.end < lastBefore) return shown;
  const shift = lastNow - lastBefore;
  return { start: shown.start + shift, end: shown.end + shift };
}

Reading around the screen ​

Read a little more than is on screen, so a short scroll is answered from the cache, and only after the user pauses (the reference clients wait 150 ms). The cache fetches only what it does not hold, and the grid snap means a fractional visible range needs no rounding.

ts
// The series every reference client charts: one-minute candles of a market
// that trades around the clock, so the live feed moves at any hour. The
// cache id names the series for the fetcher as `<dataset>/<symbol>`, and
// the interval in the id keeps another resolution's cache apart.

import type { CacheConfig, GetResult, Range } from "@anishbenji/tscache";
import { nextSlotStart, slotStart } from "@anishbenji/tscache/grid";
import { datasets } from "@examples/mock-backend/datasets";

export const MINUTE = 60_000;
const HOUR = 60 * MINUTE;

// The market's interval is a fixed one: the type says so, so the chart
// adapters, which step by whole intervals, take it without narrowing.
export const market: CacheConfig & { interval: number } = {
  id: "crypto/BTC/1m",
  interval: MINUTE,
  fields: datasets.crypto.fields,
};

/** The live feed's URL for the market (the mock backend's SSE route). */
export const feedUrl = `/api/stream/crypto/BTC?interval=${MINUTE}`;

/** The live socket's URL, and the market's subscription on it. */
export const socketUrl = "/api/live";
export const socketSubscription = {
  type: "subscribe",
  dataset: "crypto",
  symbol: "BTC",
  interval: MINUTE,
} as const;

/** The range a page opens on: the last six hours up to `now`. */
export function openingRange(now: number): Range {
  return { start: now - 6 * HOUR, end: now };
}

/**
 * The start of the bar forming at `now` on the grid of `config` (the
 * market's by default). A range that ends at `now` itself would end
 * between grid points, and the cache snaps such an end outward to the next
 * one, a bar that cannot exist yet: a read crossing a minute boundary would
 * then fetch three minutes instead of two.
 */
export function formingBar(
  now: number,
  { interval, alignmentOffset }: CacheConfig = market,
): number {
  return slotStart(now, interval, alignmentOffset);
}

/**
 * One bar past `t` on the grid of `config` (the market's by default): `t`
 * plus the length of the slot that holds it, which on a calendar grid
 * differs from slot to slot.
 */
export function oneBarPast(
  t: number,
  { interval, alignmentOffset }: CacheConfig = market,
): number {
  return (
    t +
    nextSlotStart(t, interval, alignmentOffset) -
    slotStart(t, interval, alignmentOffset)
  );
}

/**
 * The range to read for `visible` on screen: one screen more on each side,
 * so a short scroll is answered from the cache. Never past the bar forming
 * now (formingBar), where the backend has nothing yet.
 */
export function readRange(visible: Range, now: number): Range {
  const span = visible.end - visible.start;
  const end = Math.min(visible.end + span, formingBar(now));
  return { start: Math.min(visible.start - span, end), end };
}

/**
 * One line about an answer, the same on the server and in the browser for
 * the same answer: no locale, no time zone.
 */
export function summarize({ timestamps, fields }: GetResult): string {
  const close = fields.close?.at(-1);
  const last = Number.isFinite(close) ? (close as number).toFixed(2) : "–";
  return `${timestamps.length} bars, last close ${last}`;
}

Lightweight Charts ​

reference/shared/src/chart/lightweight.ts turns a result into candlestick rows and keeps the visible range across redraws.

ts
// The candle chart on Lightweight Charts v5: candles in the main pane,
// volume in a pane of its own below.
//
// Lightweight Charts places bars by index (its "logical" range), not by
// time, so bars loaded to the left of the view would push it right. Each
// draw notes the time on screen and restores it on the new bars, and a
// scroll is reported as times, past the first or last bar included: the
// range beyond the bars is what the cache is asked to load.
//
// The chart also changes its range by itself, after a draw or a resize,
// and tells no difference; so a change counts as a scroll only while the
// user is working the chart (and for a moment after, while a flick
// coasts).
//
// A live bar changes only the newest bars of the answer: those go to the
// series with update(), which redraws the bar it is given, not every bar.

import type { GetResult, Range } from "@anishbenji/tscache";
import {
  type CandlestickData,
  CandlestickSeries,
  createChart,
  type HistogramData,
  HistogramSeries,
  type LogicalRange,
  type UTCTimestamp,
} from "lightweight-charts";
import {
  appendedFrom,
  type ChartOptions,
  type ChartView,
  countDraw,
  keptRange,
  moved,
} from "./view";

const UP = "#2a78d6";
const DOWN = "#eb6834";

/** How long after the user's last input a range change is still theirs. */
const USER_MS = 1000;

/** Lightweight Charts takes times in seconds. */
const seconds = (t: number) => (t / 1000) as UTCTimestamp;

interface Bars {
  bars: CandlestickData<UTCTimestamp>[];
  volumes: HistogramData<UTCTimestamp>[];
}

/**
 * The answer's bars from `from` on as the chart's, one object per bar, as
 * it requires.
 */
function toBars(
  { timestamps, fields }: GetResult,
  from: number,
): Bars | undefined {
  const { open, high, low, close, volume } = fields;
  if (!open || !high || !low || !close || !volume) return undefined;
  const out: Bars = { bars: [], volumes: [] };
  for (let i = from; i < timestamps.length; i++) {
    const time = seconds(timestamps[i] ?? 0);
    const o = open[i] ?? Number.NaN;
    const c = close[i] ?? Number.NaN;
    const h = high[i] ?? o;
    const l = low[i] ?? o;
    out.bars.push({ time, open: o, high: h, low: l, close: c });
    out.volumes.push({
      time,
      value: volume[i] ?? 0,
      color: c >= o ? UP : DOWN,
    });
  }
  return out;
}

export function createLightweightChart(
  element: HTMLElement,
  { interval, opening }: ChartOptions,
): ChartView {
  const chart = createChart(element, {
    autoSize: true,
    layout: { textColor: "#52514e", panes: { separatorColor: "#e4e4e0" } },
    grid: {
      vertLines: { color: "#f0f0ec" },
      horzLines: { color: "#f0f0ec" },
    },
    timeScale: { timeVisible: true, secondsVisible: false },
  });
  const candles = chart.addSeries(CandlestickSeries, {
    upColor: UP,
    downColor: DOWN,
    wickUpColor: UP,
    wickDownColor: DOWN,
    borderVisible: false,
  });
  const volume = chart.addSeries(
    HistogramSeries,
    { priceFormat: { type: "volume" }, priceLineVisible: false },
    1,
  );
  chart.panes()[1]?.setStretchFactor(0.25);
  const scale = chart.timeScale();

  /** The timestamps of the bars drawn, in ms. */
  let times: ArrayLike<number> & { at(i: number): number | undefined } =
    new Float64Array(0);
  /** The answer drawn last. */
  let drawn: GetResult | undefined;
  /** The range on screen as last drawn or reported. */
  let shown: Range | undefined;
  const listeners = new Set<(visible: Range) => void>();

  /** The time at a logical index, extrapolated past either end. */
  function timeAt(logical: number): number {
    const last = times.length - 1;
    const first = times[0] ?? 0;
    if (logical <= 0) return first + logical * interval;
    if (logical >= last)
      return (times[last] ?? 0) + (logical - last) * interval;
    const i = Math.floor(logical);
    const t = times[i] ?? 0;
    return t + (logical - i) * ((times[i + 1] ?? t) - t);
  }

  /** The logical index of a time: the inverse of timeAt. */
  function logicalAt(t: number): number {
    const last = times.length - 1;
    const first = times[0] ?? 0;
    if (t <= first) return (t - first) / interval;
    if (t >= (times[last] ?? 0))
      return last + (t - (times[last] ?? 0)) / interval;
    let lo = 0;
    let hi = last;
    while (hi - lo > 1) {
      const mid = (lo + hi) >> 1;
      if ((times[mid] ?? 0) <= t) lo = mid;
      else hi = mid;
    }
    const a = times[lo] ?? 0;
    const b = times[hi] ?? a;
    return lo + (b === a ? 0 : (t - a) / (b - a));
  }

  function toRange({ from, to }: LogicalRange): Range {
    return { start: timeAt(from), end: timeAt(to) };
  }

  /** Until when (performance.now()) a range change is the user's. */
  let userUntil = 0;
  const interacting = (event: Event) => {
    // A pointer moving with no button down is hovering, not scrolling.
    const hovering = event instanceof PointerEvent && event.buttons === 0;
    if (event.type === "pointermove" && hovering) return;
    userUntil = performance.now() + USER_MS;
  };
  const inputs = ["pointerdown", "pointermove", "wheel", "keydown"] as const;
  for (const type of inputs) {
    element.addEventListener(type, interacting, { passive: true });
  }

  function onRangeChange(logical: LogicalRange | null): void {
    if (logical === null || times.length === 0) return;
    const visible = toRange(logical);
    const user = performance.now() < userUntil;
    if (user && !moved(shown, visible, interval)) return;
    shown = visible;
    if (!user) return;
    for (const listener of listeners) listener(visible);
  }
  scale.subscribeVisibleLogicalRangeChange(onRangeChange);

  /** Shows `range` on the bars drawn. */
  function showRange(range: Range): void {
    shown = range;
    scale.setVisibleLogicalRange({
      from: logicalAt(range.start),
      to: logicalAt(range.end),
    });
  }

  // A resize keeps the bar spacing, and so would narrow the time on
  // screen (the first layout does it too); keep the time instead.
  const onResize = () => {
    if (shown !== undefined && times.length > 0) showRange(shown);
  };
  scale.subscribeSizeChange(onResize);

  return {
    draw(result) {
      const from = appendedFrom(drawn, result);
      const data = toBars(result, from ?? 0);
      if (data === undefined) return;
      // Decided before the bars change, which reports the chart's own range.
      const target =
        shown === undefined
          ? opening
          : keptRange(shown, times.at(-1), result.timestamps.at(-1));
      times = result.timestamps;
      drawn = result;
      if (from === undefined) {
        candles.setData(data.bars);
        volume.setData(data.volumes);
      } else {
        // The forming bar replaces the last one; later bars are added.
        for (const bar of data.bars) candles.update(bar);
        for (const bar of data.volumes) volume.update(bar);
      }
      countDraw(element, from !== undefined);
      // An answer without bars clears the chart and keeps the time on
      // screen, so the bars of a later answer appear where the user was.
      if (times.length === 0) return;
      showRange(target);
    },
    visible: () => shown,
    onScroll(listener) {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
    dispose() {
      listeners.clear();
      for (const type of inputs) {
        element.removeEventListener(type, interacting);
      }
      scale.unsubscribeVisibleLogicalRangeChange(onRangeChange);
      scale.unsubscribeSizeChange(onResize);
      chart.remove();
    },
  };
}

uPlot ​

reference/shared/src/chart/uplot.ts gives uPlot columnar data directly, with ms: 1, so the timestamps go in as they are.

ts
// The candle chart on uPlot: candles drawn on the price scale, volume as
// bars on a scale of its own along the bottom. uPlot takes the cache's
// typed arrays as they are, with no copy and no object per bar.
//
// uPlot has no candle series and no panning of its own: a draw hook paints
// the candles, and the wheel zooms and a drag pans the time axis.
//
// Nor has it a call that adds bars: it draws its canvas again from the
// arrays on any change, and its own streaming demos call setData on each
// one. So a live bar takes the same setData as any answer, on the cache's
// arrays as they are, and only the count of draws (countDraw) tells it
// from a change of history.

import type { GetResult, Range } from "@anishbenji/tscache";
import uPlot from "uplot";
import "uplot/dist/uPlot.min.css";
import {
  appendedFrom,
  type ChartOptions,
  type ChartView,
  countDraw,
  keptRange,
  moved,
} from "./view";

const UP = "#2a78d6";
const DOWN = "#eb6834";
const HEIGHT = 360;

/** The columns uPlot draws, in its order: time first. */
const COLUMNS = ["open", "high", "low", "close", "volume"] as const;

function drawCandles(u: uPlot): void {
  const [time, open, high, low, close] = u.data;
  if (!time || !open || !high || !low || !close) return;
  const [first = 0, last = time.length - 1] = u.series[0]?.idxs ?? [];
  const { ctx, bbox } = u;
  const column = bbox.width / Math.max(1, last - first + 1);
  const body = Math.max(1, Math.round(column * 0.7));
  const wick = Math.max(1, Math.round(uPlot.pxRatio));
  ctx.save();
  ctx.beginPath();
  ctx.rect(bbox.left, bbox.top, bbox.width, bbox.height);
  ctx.clip();
  for (let i = first; i <= last; i++) {
    const o = open[i];
    const c = close[i];
    const h = high[i];
    const l = low[i];
    if (o == null || c == null || h == null || l == null) continue;
    const x = Math.round(u.valToPos(time[i] ?? 0, "x", true));
    const top = u.valToPos(Math.max(o, c), "price", true);
    const bottom = u.valToPos(Math.min(o, c), "price", true);
    ctx.fillStyle = c >= o ? UP : DOWN;
    const yh = u.valToPos(h, "price", true);
    ctx.fillRect(x - wick / 2, yh, wick, u.valToPos(l, "price", true) - yh);
    ctx.fillRect(x - body / 2, top, body, Math.max(1, bottom - top));
  }
  ctx.restore();
}

/** The wheel zooms around the pointer; a drag pans. */
function panAndZoom(u: uPlot): void {
  const span = () => {
    const { min = 0, max = 0 } = u.scales.x ?? {};
    return { min, max };
  };
  u.over.addEventListener(
    "wheel",
    (event) => {
      event.preventDefault();
      const { min, max } = span();
      const at = u.posToVal(event.offsetX, "x");
      const factor = event.deltaY < 0 ? 0.8 : 1.25;
      u.setScale("x", {
        min: at - (at - min) * factor,
        max: at + (max - at) * factor,
      });
    },
    { passive: false },
  );
  u.over.addEventListener("pointerdown", (event) => {
    const from = event.clientX;
    const { min, max } = span();
    const perPixel = (max - min) / u.over.clientWidth;
    u.over.setPointerCapture(event.pointerId);
    const move = (next: PointerEvent) => {
      const shift = (from - next.clientX) * perPixel;
      u.setScale("x", { min: min + shift, max: max + shift });
    };
    const up = () => {
      u.over.removeEventListener("pointermove", move);
      u.over.removeEventListener("pointerup", up);
    };
    u.over.addEventListener("pointermove", move);
    u.over.addEventListener("pointerup", up);
  });
}

export function createUplotChart(
  element: HTMLElement,
  { interval, opening }: ChartOptions,
): ChartView {
  const listeners = new Set<(visible: Range) => void>();
  /** The range on screen as last drawn or reported. */
  let shown: Range | undefined;
  /** Set while draw() moves the scale, which is not the user scrolling. */
  let drawing = false;
  let times: ArrayLike<number> = [];
  /** The answer drawn last. */
  let drawn: GetResult | undefined;

  function onScale(u: uPlot, key: string): void {
    if (key !== "x" || drawing) return;
    const { min, max } = u.scales.x ?? {};
    if (min == null || max == null) return;
    const visible = { start: min, end: max };
    if (!moved(shown, visible, interval)) return;
    shown = visible;
    for (const listener of listeners) listener(visible);
  }

  const volumeBars = uPlot.paths.bars?.({ size: [0.7, 40] });
  const plot = new uPlot(
    {
      width: element.clientWidth,
      height: HEIGHT,
      ms: 1,
      // UTC, as Lightweight Charts shows it.
      tzDate: (t) => uPlot.tzDate(new Date(t), "Etc/UTC"),
      cursor: { drag: { x: false, y: false, setScale: false } },
      legend: { show: false },
      scales: {
        x: { time: true, auto: false },
        // Candles keep to the top three quarters, volume to the bottom.
        price: {
          range: (_u, min, max) => {
            const span = Math.max(max - min, Math.abs(max) * 1e-6, 1e-9);
            return [min - span / 3, max + span * 0.05];
          },
        },
        volume: { range: (_u, _min, max) => [0, Math.max(1, max) * 4] },
      },
      series: [
        {},
        // The candle columns set the price scale; the draw hook paints them.
        ...COLUMNS.slice(0, 4).map((label) => ({
          label,
          scale: "price",
          paths: () => null,
          points: { show: false },
        })),
        {
          label: "volume",
          scale: "volume",
          fill: "rgba(82, 81, 78, 0.18)",
          ...(volumeBars && { paths: volumeBars }),
        },
      ],
      axes: [
        {},
        { scale: "price", size: 64 },
        { scale: "volume", show: false },
      ],
      hooks: {
        draw: [drawCandles],
        setScale: [onScale],
        ready: [panAndZoom],
      },
    },
    [[], [], [], [], [], []],
    element,
  );

  const resize = new ResizeObserver(() => {
    plot.setSize({ width: element.clientWidth, height: HEIGHT });
  });
  resize.observe(element);

  return {
    draw(result) {
      const { timestamps, fields } = result;
      const columns = COLUMNS.map((name) => fields[name]);
      if (columns.some((column) => column === undefined)) return;
      countDraw(element, appendedFrom(drawn, result) !== undefined);
      drawn = result;
      const before = times.length > 0 ? times[times.length - 1] : undefined;
      times = timestamps;
      // An answer without bars clears the chart and keeps the time on
      // screen, so the bars of a later answer appear where the user was.
      const target =
        shown === undefined
          ? opening
          : keptRange(shown, before, timestamps.at(-1));
      shown = target;
      drawing = true;
      plot.batch(() => {
        plot.setData([timestamps, ...columns] as uPlot.AlignedData, false);
        // Setting x again re-ranges the price scale to the bars on screen.
        plot.setScale("x", { min: target.start, max: target.end });
      });
      drawing = false;
    },
    visible: () => shown,
    onScroll(listener) {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
    dispose() {
      listeners.clear();
      resize.disconnect();
      plot.destroy();
    },
  };
}

Gaps on a chart ​

A confirmed gap has no points, so a chart draws nothing there; a time-scaled axis (uPlot) shows the gap, an index-scaled one (Lightweight Charts) closes it up. misses tells you which stretches are merely not loaded yet, if you want to mark them.