@getcandlekit/charts

中文文档
0.2.1发布于 2026/10/20MITTypeScriptESM + CJS零依赖近 30 天下载 2559

Tree-shakeable financial charting toolkit: candlestick/OHLC/line/area/volume, drawing tools, pluggable indicators, measurement tools, and a deterministic replay engine. Built on lightweight-charts. Framework-agnostic core + optional React bindings.

原始使用文档
文档目录24 节
  1. The all in one unification layer built on Lightweight Chart…
  2. Stop stitching together repositories.
  3. Overview
  4. Features
  5. Replay
  6. Lab — Sketch Search & Echoes
  7. Installation
  8. Quick Start
  9. Vanilla JS / TypeScript
  10. React
  11. Basic Examples
  12. Advanced Examples
  13. Replay Examples
  14. Drawing Tool Examples
  15. Indicator Examples
  16. Lab Examples
  17. Plugin Examples
  18. API Overview
  19. Performance Notes
  20. Browser Support
  21. Roadmap
  22. Star History
  23. Contributing
  24. License
candlekit/charts — the all-in-one financial charting toolkit

The all in one unification layer built on Lightweight Charts™.

CandleKit unifies the charting tools and extensions developers repeatedly source, adapt, and maintain from across the Lightweight Charts ecosystem.

Drawing Tools • Technical Indicators • Replay Engine • Measurement Tools • Synced Multipane System • Broker Integration

Stop stitching together repositories.

Get a cohesive toolkit, consistent APIs, and an extensible architecture built for production-grade financial charting.

Everything you keep rebuilding around Lightweight Charts™ — packaged once.

CI npm version types License: MIT

[!NOTE] Candlekit is a vibe-coded project — designed and built rapidly and iteratively with AI-assisted development. It is functional, tested (CI green, with a Vitest suite under /tests), and documented, but treat it as early-stage software: pin a version, read the changelog before upgrading, and open an issue if something looks off.

Drawing a trendline, rectangle and Fibonacci retracement on a candlestick chart
Drawing tools — trendline, rectangle, Fibonacci, measurement ruler

Toggling Bollinger Bands, MACD, SMA and Stochastic indicators
Built-in indicators — Bollinger, EMA/SMA, RSI, MACD, Stochastic — toggled live

Shift-drag measurement ruler showing percentage move, points and bar and time delta
Measurement ruler — Shift-drag for % move, points, bars · time

▶ Open the live demo — drawing, indicators, measurement and replay in one chart


Overview

candlekit/charts wraps lightweight-charts with the pieces a real trading UI needs but the base library leaves to you: a stable chart controller, a runtime-agnostic drawing engine, an extensible indicator framework, a Shift-drag measurement ruler, multi-chart sync, broker integration and a deterministic historical replay engine. The core is framework-agnostic (no React, no DOM framework); the optional /react entry adds components and hooks.

It is plugin-first: drawing, indicators, and measurement are all ChartPlugins you can swap, extend, or omit. Drawing tools and indicators are original code built on lightweight-charts canvas primitives — no third-party drawing or indicator runtime — and the side-effect-free modules let tree-shaking drop whatever you don't import.

Features

  • Core charting — candlestick, OHLC bars, line, area, volume; multiple timeframes via a session-aware resampler; responsive auto-resize; light/dark themes with full color override.
  • Drawing tools — trend line, ray, extended line, horizontal/vertical line, arrow, rectangle, circle, Fibonacci retracement, with selection, drag-to-move, handle reshaping, locking, and persistence. Original engine rendered on lightweight-charts canvas primitives — no third-party drawing runtime.
  • Indicators — extensible registry + a built-in catalog (SMA, EMA, WMA, VWAP, Bollinger Bands, RSI, MACD, ATR, Stochastic), all original implementations. Register your own with one call.
  • Measurement — price, percentage, bar-distance, time-delta, and risk/reward, painted as a canvas ruler.
  • Replay — deterministic playback over historical bars: play/pause, step ±1, speed control, seek/jump, per-bar event hooks, per-day LRU cache with pre-fetch.
  • Lab (experimental) — pattern-similarity analytics over your own bars. Echoes ("market déjà vu") finds historical windows that look like the recent price action, bands them, and projects the median of what happened next; Sketch Search matches a freehand shape you draw against history. Pure, dependency-free math + optional plugins and a React panel.
  • Architecture — TypeScript, fully typed public API, tree-shakeable ESM + CJS, event system, plugin system, and extensible data-source / indicator / drawing frameworks.

Replay

Deterministic historical replay stepping and seeking over candlestick bars
Deterministic replay — play/pause, step ±1, speed control, seek/jump

Lab — Sketch Search & Echoes

Echoes highlights historical windows that look like the recent price action and projects the median of what happened next; Sketch Search matches a freehand shape against history
Echoes — similar past windows + median projection · Sketch Search — draw a shape, find look-alikes

Two experimental pattern-similarity tools, computed on z-normalized closes (shape, not price level), so look-alikes are found across regimes:

  • Echoes — takes the last N closes as a query, finds the most similar non-overlapping windows in history, bands them on the chart, and projects the median of what happened next forward from the last bar.
  • Sketch Search — draw a freehand shape across the chart; it is resampled and matched against history the same way.

The math (zNormalize, findSimilar, buildEchoScan, resampleStroke) is pure and dependency-free; the chart plugins (SketchSearchController, EchoesController) and the React <EchoesPanel> / <SketchSearchButton> are optional. See Lab Examples below, the full Lab guide, and examples/lab for a runnable demo.

Try it live in examples/lab (cd examples/lab && npm i && npm run dev). The GIF above is regenerated by SCENE=lab node scripts/capture-demo.mjs.

Installation

npm install @getcandlekit/charts lightweight-charts
# React bindings (optional):
npm install react react-dom

That's it. lightweight-charts is the only runtime dependency (a peer, so you control its version); react/react-dom are needed only for @getcandlekit/charts/react. Drawing tools and indicators are built in — no extra packages, no git installs.

Quick Start

Vanilla JS / TypeScript

import { ChartController, toBars } from "@getcandlekit/charts";

const el = document.getElementById("chart")!;
const chart = new ChartController(el, { theme: "dark", seriesType: "candlestick" });

chart.setData(toBars(myRows)); // myRows: { ts, open, high, low, close, volume }[]

React

import { ChartView } from "@getcandlekit/charts/react";
import "@getcandlekit/charts/styles.css";

export function App({ bars }) {
  return (
    <div style={{ height: 480 }}>
      <ChartView data={bars} seriesType="candlestick" theme="dark" />
    </div>
  );
}

Basic Examples

Switch series type and timeframe:

chart.setSeriesType("area");       // candlestick | ohlc | line | area
chart.setData(resample(rows, 5));  // 5-minute candles from 1-minute rows
chart.setTheme("light");

Live updates:

ws.onBar((bar) => chart.updateBar(bar)); // appends or replaces the last bar

Advanced Examples

Session-aware resampling (align buckets to a 09:30 market open instead of UTC midnight):

import { resample } from "@getcandlekit/charts";
const candles = resample(rows, 15, { sessionOpenMinutes: 9 * 60 + 30 });

Fixed-offset exchange time (render an always-UTC+5:30 market in wall-clock):

import { applyFixedOffset } from "@getcandlekit/charts";
const shifted = rows.map((r) => ({ ...r, ts: applyFixedOffset(r.ts, 330) }));

Replay Examples

import { createReplayController } from "@getcandlekit/charts";

const replay = createReplayController();
replay.onBar((e) => chart.updateBar(e.bar));
await replay.load({
  id: "demo",
  series: [{ symbol: "AAPL", interval: "1m" }],
  start: Date.parse("2024-01-02T14:30:00Z"),
  end: Date.parse("2024-01-03T21:00:00Z"),
  source: myReplayDataSource, // implements ReplayDataSource
});
replay.setSpeed(8);
replay.play();

React transport bar:

import { ReplayControls } from "@getcandlekit/charts/react";
<ReplayControls controller={replay} />

Drawing Tool Examples

import { ChartView, DrawingToolbar } from "@getcandlekit/charts/react";

// `drawing` accepts true, an options object, or a DrawingController instance.
<ChartView data={bars} drawing={{ storageKey: "drawings:AAPL" }}>
  <DrawingToolbar />
</ChartView>;

Imperative (vanilla):

import { ChartController, DrawingController } from "@getcandlekit/charts";

const chart = new ChartController(el);
const drawing = new DrawingController({ storageKey: "drawings:AAPL" });
chart.use(drawing);
drawing.engine.startTool("TrendLine");

Indicator Examples

import { ChartView, IndicatorPicker, IndicatorController, createBuiltinRegistry } from "@getcandlekit/charts/react";

const indicators = new IndicatorController(createBuiltinRegistry());
indicators.add("RSI", { length: 14 });
indicators.add("EMA", { length: 21 });

<ChartView data={bars} indicators={indicators}>
  <IndicatorPicker />
</ChartView>;

Register a custom indicator (the extension point):

import { IndicatorRegistry } from "@getcandlekit/charts";

const registry = new IndicatorRegistry().register({
  name: "PriceMid",
  title: "HL/2",
  shortTitle: "MID",
  category: "overlay",
  defaultInputs: {},
  inputConfig: [],
  plotConfig: [{ id: "mid", color: "#f59e0b" }],
  hlineConfig: [],
  calculate: (bars) => ({
    plots: { mid: bars.map((b) => ({ time: b.time, value: (b.high + b.low) / 2 })) },
  }),
});

Lab Examples

React (<ChartView> hosts the plugins; the components drive them):

import { ChartView, SketchSearchButton, EchoesPanel } from "@getcandlekit/charts/react";
import "@getcandlekit/charts/styles.css";

<ChartView data={bars} sketch echoes={{ windowLen: 30, horizon: 30, k: 8 }}>
  <SketchSearchButton />  {/* toggle, then drag a shape on the chart */}
  <EchoesPanel />         {/* Scan → bands + median projection + stats */}
</ChartView>;

Imperative (vanilla — same plugins, your own UI):

import { ChartController, EchoesController, SketchSearchController } from "@getcandlekit/charts";

const chart = new ChartController(el);
chart.setData(bars);

const echoes = new EchoesController({ windowLen: 30, horizon: 30, k: 8 });
chart.use(echoes);
echoes.subscribe((scan) => scan && console.log(scan.stats)); // { count, upCount, medianEndPct, ... }
echoes.run();

const sketch = new SketchSearchController({ onResult: (r) => console.log(r?.matches) });
chart.use(sketch);
sketch.setActive(true); // arm; drag a freehand shape, release to search

Pure math, no chart (search any series of closes):

import { findSimilar, buildEchoScan } from "@getcandlekit/charts";

const matches = findSimilar(closes, closes.slice(-30), { k: 5 }); // [{ startIndex, endIndex, distance }]
const scan = buildEchoScan(bars, 30, 30, 8);                      // window/horizon/k → null if too little history

Plugin Examples

import type { ChartPlugin } from "@getcandlekit/charts";

const lastPriceLabel: ChartPlugin = {
  id: "last-price-label",
  init(ctx) {
    ctx.bus.on("data", ({ bars }) => {
      const last = bars[bars.length - 1];
      if (last) console.log("last close", last.close);
    });
  },
  destroy() {},
};

chart.use(lastPriceLabel);

API Overview

ExportKindPurpose
ChartControllerclassImperative chart wrapper (data, series type, theme, plugins, events).
toBars, resample, floorToBucketfnPure data normalization + session-aware resampling.
resolveTheme, lightTheme, darkThemefn/constTheme presets + resolution.
EventBusclassTyped sync event bus.
DrawingController, DrawingEngineclassBuilt-in drawing plugin + its model/state.
IndicatorRegistry, IndicatorController, createBuiltinRegistryclass/fnExtensible indicator framework + built-in catalog.
MeasurementController, RulerPrimitiveclassShift-drag measurement.
createReplayControllerfnDeterministic replay.
createSyncEnginefnMulti-chart sync.
EchoesController, SketchSearchControllerclassLab plugins — Echoes (déjà vu) + Sketch Search.
findSimilar, buildEchoScan, zNormalize, resampleStrokefnPure pattern-similarity math (no chart).
ChartView (/react)componentDeclarative chart + plugin host.
EchoesPanel, SketchSearchButton (/react)componentLab results panel + sketch toggle.

Full reference: docs/api-reference.md.

Performance Notes

  • Single offset conversion at the data boundary; drawings/replay stay in one coordinate domain (no per-render timezone math).
  • setData autoscale fits once on the first non-empty paint; later updates preserve user pan/zoom.
  • Replay uses a per-day LRU cache with backward/forward pre-fetch; the cursor drives everything (no wall-clock coupling).
  • Tree-shakeable ESM — a vanilla bundle never pulls React. Drawing and indicators are self-contained (no extra runtime deps to load).

Browser Support

Evergreen browsers (Chrome, Edge, Firefox, Safari) with Canvas + ResizeObserver. ESM and CJS builds are shipped; target: es2020.

Roadmap

  • Text + freehand/brush drawing tools
  • Indicator settings UI (param editing) in the React picker
  • Crosshair tooltip component
  • More indicators (Ichimoku, SuperTrend, Keltner)
  • Vue / Svelte bindings
  • Screenshot/export helper

Star History

If candlekit saves you from stitching repos together, a ⭐ helps others find it.

Star History Chart

Contributing

See CONTRIBUTING.md and AGENTS.md. In short: npm install, npm run typecheck && npm run lint && npm run test && npm run build.

License

MIT — see LICENSE. Third-party attributions in NOTICE. "Lightweight Charts™" is a trademark of TradingView, Inc.; this project is not affiliated with TradingView.

版本与发布记录

@getcandlekit/charts 共发布 3 个版本,首次发布于 2026/06/03;过去 12 个月发布了 3 个版本。

版本发布日期距今
0.2.1latest2026/10/2026 天前
0.2.02026/09/251 个月前
0.1.02026/06/035 个月前

关于 @getcandlekit/charts 的常见问题

@getcandlekit/charts 是什么?

Tree-shakeable financial charting toolkit: candlestick/OHLC/line/area/volume, drawing tools, pluggable indicators, measurement tools, and a deterministic replay engine. Built on lightweight-charts. Framework-agnostic core + optional React bindings.

如何安装 @getcandlekit/charts?

在项目目录运行 npm install @getcandlekit/charts,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:lightweight-charts(^5.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@getcandlekit/charts 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@getcandlekit/charts 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@getcandlekit/charts 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@getcandlekit/charts 可以商用吗?

@getcandlekit/charts 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@getcandlekit/charts 的下载量有多少?

根据 npm 官方下载统计,@getcandlekit/charts 在 2026/10/17 – 2026/11/15 这 30 天内被下载 2,559 次,日均约 85 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@getcandlekit/charts 还在维护吗?

最新版本 0.2.1 发布于 2026/10/20(26 天前);至今共发布 3 个版本,其中过去 12 个月发布了 3 个;首次发布于 2026/06/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。