@tradecanvas/chart 1.7.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,910 +1,1115 @@
1
- # @tradecanvas/chart
2
-
3
- High-performance canvas trading chart with built-in indicators, drawing tools, and real-time streaming. Zero external dependencies.
4
-
5
- **[Live Demo](https://bonguynvan.github.io/tradecanvas/)** | **[GitHub](https://github.com/bonguynvan/tradecanvas)** | **[npm](https://www.npmjs.com/package/@tradecanvas/chart)**
6
-
7
- ## Why TradeCanvas?
8
-
9
- Most chart libraries make you choose: pretty charts with no trading features, or trading features with an ugly API. TradeCanvas gives you both.
10
-
11
- - **70 built-in indicators** — SMA, EMA, TEMA, VWMA, Hull MA, RSI, MACD, Bollinger, Envelope, Ichimoku, Pivot Points, Anchored VWAP, ZigZag, Linear Regression Channel, Awesome / Chaikin Oscillator, and more. No separate calculation library needed.
12
- - **69 drawing tools** — Trendlines (info line, trend angle, cross line), Fibonacci (retracement, extension, channel, time zones, speed resistance fan and arcs, circles, spiral, wedge), horizontal/vertical lines, channels, pitchforks and pitchfan, Gann fan / box / square, cycles, harmonic patterns (XABCD, cypher, ABCD, three drives, head and shoulders), Elliott waves, notes, callouts and marks, brush and path, forecast and projection, Long/Short Position with position sizing, Volume Profile range. Each with its own settings, alerts on trend lines, groups and layers, undo/redo and full serialization.
13
- - **18 chart types** — Candlestick, line, area, bar, hollow candle, baseline, High-Low, Heikin-Ashi, Renko, Kagi, Line Break, Point & Figure, Range Bars, Volume Candles, **Equivolume**, HLC Area, Step Line, Line+Markers. Renko's box, Kagi's reversal and the like are yours to set.
14
- - **Pro-grade interaction** — pan freely past the last bar into empty future space (drawings can go there too), drag the price/time axes to scale, double-click to auto-fit, `Ctrl/⌘+drag` to select several drawings (then move, restyle or delete them together), `Shift+drag` to measure (bars × price Δ × %), `Alt+click` to pin a comparison tooltip, context cursors (crosshair, grabbing hand, resize arrows), axis-following price/time pill labels under the cursor, bar-hover highlight.
15
- - **Trading overlay** — Render open positions with entry line, P&L zone, and SL/TP markers. Orders as dashed lines. Drag SL/TP to modify, cancel / close / reverse from the buttons on each line, and see every fill marked on its bar. ChartWidget adds an order ticket that checks the order as you fill it in, and an account panel with positions, working orders and history. Cleanly opt-out via `features.trading: false` for non-trading projects.
16
- - **Real-time streaming** — Built-in Binance adapter. Plug in your own data source with the adapter interface.
17
- - **Strategy backtester** — `@tradecanvas/analytics` ships a bar-by-bar `Backtester` with virtual fills, commission/slippage models, portfolio tracking, and risk metrics (Sharpe, Sortino, Calmar, max drawdown). **Now with 4 ready-to-use reference strategies + Monte Carlo path-dependence analysis.**
18
- - **Replay mode** — replay the chart's own bars from any point, in finer steps if you like (an hourly chart forming from 5-minute bars), with play / pause / step / seek / speed, and paper-trade on the replayed prices. The widget has a replay bar for it; `ReplayController` drives bars headless too.
19
- - **Alerts** — on a price level, an indicator line, a drawing, or one line crossing another; on a move of some percent within some bars; only on closed bars; with an expiry. The widget's alerts panel sets all of them.
20
- - **Compare and spread** — other symbols in percent on the price scale, on a scale or pane of their own, or as a spread or ratio, lined up with the chart by time.
21
- - **Price formats** — prices in your own format or in fractions of a point (a bond in 32nds: 110'165) on every label; times your way; extended hours on or off; data export with the indicator lines.
22
- - **Volume Profile** *(new in 0.9)* — optional horizontal histogram of traded volume bucketed by price over the visible range, with point-of-control highlighting.
23
- - **Watchlist sidebar** *(new in 0.9)* — opt-in vertical panel listing symbols with last price, % change, mini sparkline. Click a row to switch chart.
24
- - **CSV / JSON drag-and-drop** *(new in 0.9)* — drop a file onto the chart, it parses and loads instantly. Detects header layouts, ISO/unix-s/unix-ms timestamps, and array-vs-object JSON shapes.
25
- - **Named layouts** — save the chart under a name (symbol, interval, scale, indicators, drawings, alerts), open, rename, delete, auto-save the open one, `Ctrl/⌘+S`. Kept in the browser, or on your server through a four-call `LayoutStorage`. Per-symbol auto-persistence (`persistLayouts`) is there too.
26
- - **Multi-chart** — `ChartWidgetGrid` puts up to six full widgets side by side, linked by symbol, interval, crosshair, time or drawings as you choose, and saves them as one layout. `ChartGrid` does the same for bare charts.
27
- - **Signal markers & trade zones** — render bot/algorithm output (directional arrows, entry→exit rectangles) as a first-class chart layer.
28
- - **Hotkey sheet** *(new in 0.9)* — press `?` in the widget to open a categorized keyboard-shortcut reference.
29
- - **Extensible widget** — add your own toolbar buttons and right-click menu entries (`addToolbarButton`, `chartMenuItems`).
30
- - **Save/load chart state** — Persist drawings, indicators, theme, and chart type to JSON. Restore with one call.
31
- - **Zero dependencies** — The entire library is self-contained. No `d3`, no `chart.js`, no `fancy-canvas`.
32
-
33
- ## Install
34
-
35
- ```bash
36
- npm install @tradecanvas/chart
37
- # or
38
- pnpm add @tradecanvas/chart
39
- # or
40
- yarn add @tradecanvas/chart
41
- ```
42
-
43
- ## Quick Start
44
-
45
- The fastest path is `ChartWidget` — drop-in component with a full trading UI (toolbar, drawing sidebar, settings dialog, status bar). Zero framework dependency.
46
-
47
- ```typescript
48
- import { ChartWidget } from '@tradecanvas/chart/widget'
49
- import { BinanceAdapter } from '@tradecanvas/chart'
50
-
51
- const widget = new ChartWidget(document.getElementById('chart')!, {
52
- symbol: 'BTCUSDT',
53
- timeframe: '5m',
54
- theme: 'dark',
55
- adapter: new BinanceAdapter(),
56
- trading: true,
57
- })
58
- ```
59
-
60
- That's it. Live data, all 95 indicators, all 69 drawing tools, command palette (`Ctrl+K`), symbol search (`Ctrl+P`), hotkey sheet (`?`), shift-drag measure, alt-click tooltip pin, and drag-drop CSV/JSON loading.
61
-
62
- ## Headless Chart
63
-
64
- For projects that want to own the surrounding UI (custom toolbar, framework-specific controls), use the lower-level `Chart` class directly:
65
-
66
- ```typescript
67
- import { Chart, BinanceAdapter } from '@tradecanvas/chart'
68
-
69
- const chart = new Chart(document.getElementById('chart')!, {
70
- theme: 'dark',
71
- autoScale: true,
72
- features: {
73
- drawings: true,
74
- indicators: true,
75
- trading: true, // set false to disable orders/positions entirely
76
- tradingContextMenu: true, // opt-in right-click order menu (off by default)
77
- volume: true,
78
- },
79
- })
80
-
81
- const adapter = new BinanceAdapter()
82
- chart.connect({ adapter, symbol: 'BTCUSDT', timeframe: '5m', historyLimit: 300 })
83
- ```
84
-
85
- ### Widget Options
86
-
87
- | Option | Type | Default | Description |
88
- |---|---|---|---|
89
- | `symbol` | `string` | `'BTCUSDT'` | Initial trading symbol |
90
- | `timeframe` | `TimeFrame` | `'5m'` | Initial timeframe |
91
- | `theme` | `'dark' \| 'light' \| Theme` | `'dark'` | Chart theme |
92
- | `adapter` | `DataAdapter` | — | Data source adapter |
93
- | `toolbar` | `boolean` | `true` | Show top toolbar |
94
- | `drawingTools` | `boolean` | `true` | Show left drawing sidebar |
95
- | `settings` | `boolean` | `true` | Show settings button |
96
- | `trading` | `boolean` | `true` | Enable trading overlay |
97
- | `statusBar` | `boolean` | `true` | Show bottom status bar |
98
- | `rangeBar` | `boolean` | `true` | Range presets (1D … All) and go to date (Alt+G) on the status bar |
99
- | `indicatorLegend` | `boolean` | `true` | Indicators listed on the chart (under the OHLCV legend and atop their panes) with show / settings / remove |
100
- | `fullscreen` | `boolean` | `true` | Fullscreen button in the toolbar |
101
- | `symbols` | `string[]` | BTC/ETH/SOL/BNB | Searchable symbol catalog |
102
- | `timeframes` | `TimeFrame[]` | 1m to 1M | Timeframes on offer; pin favourites from the ▾ menu |
103
- | `chartTypes` | `ChartType[]` | 18 types | Available chart types |
104
- | `watchlist` | `boolean` | `false` | Right-side watchlist sidebar |
105
- | `dragDropImport` | `boolean` | `true` | Drop CSV / JSON files onto the chart to load data |
106
- | `persistLayouts` | `boolean \| { keyPrefix, debounceMs }` | `false` | Save per-symbol indicators / drawings / chart type to localStorage |
107
- | `onSymbolChange` | `(symbol) => void` | — | Symbol change callback |
108
- | `onTimeframeChange` | `(tf) => void` | — | Timeframe change callback |
109
- | `onReady` | `(chart) => void` | — | Fired when chart is ready |
110
- | `locale` | `string` | `'en'` | UI chrome language — built-in `'en'` / `'vi'`, see **Widget i18n** below |
111
- | `messages` | `Partial<Record<MessageKey, string>>` | — | Override or add individual UI strings on top of `locale` |
112
-
113
- ### Icons
114
-
115
- The widget's icon set is exported for your own UI: `createIcon(name)`,
116
- `createToolIcon(drawingTool)`, `createChartTypeIcon(chartType)` return inline
117
- SVG strings drawn in `currentColor` (24 px grid, 1.75 px strokes).
118
-
119
- ```ts
120
- import { createToolIcon } from '@tradecanvas/chart/widget'
121
- button.innerHTML = createToolIcon('fibRetracement', 16)
122
- ```
123
-
124
- ### Widget i18n
125
-
126
- `locale` and `messages` translate `ChartWidget`'s own chrome — toolbar, watchlist, indicator-picker section headers (Popular/All, overlay/panel tags), status bar, settings panel (titles/tabs/section headers), and hotkey sheet (title/group headers). Set at construction; not currently hot-swappable at runtime.
127
-
128
- ```ts
129
- new ChartWidget(el, {
130
- locale: 'vi', // built-in Vietnamese table
131
- messages: { 'watchlist.title': 'Theo dõi' }, // override/add individual keys — always wins
132
- chartOptions: { numberLocale: 'vi-VN' }, // separate: number/date formatting (see below)
133
- });
134
- ```
135
-
136
- `locale`/`messages` only cover chrome **text**; they're independent of `chartOptions.numberLocale`, which controls number/date **formatting** (price axis, legend, watchlist prices, current-price tag, session-break dates) via `Intl`/`toLocaleString`.
137
-
138
- Not yet covered by `locale` (still English; PRs welcome, or override via `messages`/your own CSS):
139
- - Indicator and drawing-tool **names** (SMA, Bollinger Bands, Trend Line, …) — these come from `widgetConfig.ts`'s data tables, not the message catalog.
140
- - Individual settings rows beyond the tab/section level (e.g. "Up Body", "Grid Lines").
141
- - Individual hotkey-sheet shortcut labels and key-cap text (group titles are translated).
142
- - Alerts panel, symbol search, command palette, data window, depth ladder, bracket bar, replay bar, drawing-style panel, object tree.
143
-
144
- See `packages/library/src/widget/i18n.ts` for the full key list (`MessageKey`) and the English/Vietnamese tables.
145
-
146
- ### Widget vs Headless
147
-
148
- | | `Chart` (headless) | `ChartWidget` |
149
- |---|---|---|
150
- | Import | `@tradecanvas/chart` | `@tradecanvas/chart/widget` |
151
- | UI included | None — build your own | Complete toolbar, sidebar, settings |
152
- | Bundle impact | ~50 KB gzip | ~65 KB gzip (includes UI) |
153
- | Framework | Any (React, Vue, Svelte, vanilla) | Vanilla JS DOM (works everywhere) |
154
- | Customization | Full control | Toggle sections on/off |
155
- | Advanced access | Direct API | `widget.getChart()` for direct API |
156
-
157
- ### Widget Look
158
-
159
- The widget's shapes and sizes — corners, control heights, type, borders, shadows, how a chosen button shows, bars docked or floating — are a look of their own, apart from the colours. Three presets: **Studio** (the default), **Terminal** (dense and square) and **Capsule** (pills, floating bars). Start from one and change what you like:
160
-
161
- ```ts
162
- const widget = new ChartWidget(host, { ui: 'terminal' });
163
- widget.setUI({ preset: 'studio', radius: { md: 10 }, density: 'compact', toolbar: 'floating', active: 'solid' });
164
- ```
165
-
166
- The chart's price tags take the same corners (`tagRadius`; on a bare `Chart`, `chart.setShapes({ tagRadius })`). The widget loads no fonts: load the ones a look names. See [Styling](https://bonguynvan.github.io/tradecanvas/docs/styling).
167
-
168
- ### Widget Theming
169
-
170
- `ChartWidget`'s own chrome (toolbar, sidebars, settings panel, watchlist — everything *outside* the canvas) is styled entirely through CSS custom properties on `.tcw-root`, the widget's own root element. These are a **stable, documented contract**: additive-only across minor/patch releases — a property is never renamed or removed without a major version bump. Override them from the host page; no build step or theme object needed.
171
-
172
- ```css
173
- /* Dark is the default (no attribute needed); light sets data-tcw-theme="light" */
174
- .my-app .tcw-root:not([data-tcw-theme="light"]) {
175
- --tcw-bg: #0a0a0f;
176
- --tcw-accent: #7c5cff;
177
- --tcw-radius: 0px;
178
- --tcw-radius-lg: 0px;
179
- }
180
- ```
181
-
182
- | Variable | Default (dark) | Purpose |
183
- |---|---|---|
184
- | `--tcw-bg` | `#080b10` | Root background |
185
- | `--tcw-bg-surface` | `#0c1016` | Panel / toolbar surface |
186
- | `--tcw-bg-elevated` | `#141922` | Popovers, dropdowns, modals |
187
- | `--tcw-bg-overlay` | `rgba(20,25,34,.5)` | Backdrop behind overlays |
188
- | `--tcw-border` | `#1f2630` | Default border |
189
- | `--tcw-border-strong` | `#2a323e` | Emphasized border (focus rings, dividers) |
190
- | `--tcw-text` | `#e7e9ee` | Primary text |
191
- | `--tcw-text-dim` | `#aab1bd` | Secondary text |
192
- | `--tcw-text-muted` | `#758091` | Tertiary / placeholder text |
193
- | `--tcw-accent` | `#f2a93b` | Primary accent (active tab, focus, links) |
194
- | `--tcw-accent-ink` | `#1a1204` | Text and icons on an accent fill |
195
- | `--tcw-accent-hover` | `#f5b95c` | Accent hover state |
196
- | `--tcw-accent-soft` | `rgba(242,169,59,.14)` | Accent tint (selected row background) |
197
- | `--tcw-accent-glow` | `rgba(242,169,59,.22)` | Accent glow (focus halo) |
198
- | `--tcw-accent-line` | `rgba(242,169,59,.55)` | Accent border/underline |
199
- | `--tcw-red` / `--tcw-red-soft` | `#e8505b` / tint | Down/sell/negative |
200
- | `--tcw-green` / `--tcw-green-soft` | `#1fa874` / tint | Up/buy/positive |
201
- | `--tcw-amber` | `#ff9f43` | Warning |
202
- | `--tcw-hover-bg` | `rgba(255,255,255,.05)` | Row/button hover background |
203
- | `--tcw-active-bg` | `rgba(255,255,255,.08)` | Row/button pressed background |
204
- | `--tcw-divider` | `rgba(255,255,255,.06)` | Hairline dividers |
205
- | `--tcw-ease` / `--tcw-ease-out` | cubic-bezier | Transition easing |
206
- | `--tcw-dur-fast` / `-normal` / `-slow` | `120ms` / `180ms` / `260ms` | Transition durations |
207
- | `--tcw-radius-xs` / `-sm` / `--tcw-radius` / `-lg` / `-xl` | `3px` / `5px` / `7px` / `11px` / `16px` | The corner scale — set to `0` for a square look |
208
- | `--tcw-control-radius` / `--tcw-input-radius` / `--tcw-menu-radius` / `--tcw-dialog-radius` / `--tcw-panel-radius` / `--tcw-tooltip-radius` / `--tcw-tag-radius` / `--tcw-toast-radius` | from the scale | Each kind of part's corners |
209
- | `--tcw-toolbar-h` / `--tcw-control-h` / `--tcw-control-h-sm` / `--tcw-icon` / `--tcw-sidebar-w` / `--tcw-menu-item-h` | `46px` / `30px` / `24px` / `18px` / `48px` / `30px` | Sizes |
210
- | `--tcw-font` / `--tcw-font-size` / `--tcw-weight` / `--tcw-weight-strong` | `'Manrope', 'Inter', …` / `13px` / `500` / `600` | Type |
211
- | `--tcw-label-case` / `--tcw-label-tracking` | `none` / `0em` | Small labels (section titles) |
212
- | `--tcw-border-w` / `--tcw-sep-w` | `1px` / `0px` | Border width; rules between toolbar groups |
213
- | `--tcw-menu-shadow` / `--tcw-dialog-shadow` / `--tcw-tooltip-shadow` | the elevation shadows | Shadows of menus, dialogs, tooltips |
214
- | `--tcw-blur` / `--tcw-surface-opacity` | `0px` / `100%` | Frosted menus |
215
- | `--tcw-shadow-sm` / `-md` / `-lg` / `-xl` | box-shadow values | Elevation |
216
- | `--tcw-ring` | `0 0 0 2px rgba(242,169,59,.45)` | Focus ring |
217
- | `--tcw-font-mono` | `'JetBrains Mono', …` | Monospace font stack (price ladder, code) |
218
-
219
- Light theme (`[data-tcw-theme="light"]`) redefines the color group (`--tcw-bg*`, `--tcw-border*`, `--tcw-text*`, `--tcw-accent*`, `--tcw-hover-bg`, `--tcw-active-bg`, `--tcw-divider`, `--tcw-shadow*`) with its own defaults — override both selectors if you support both themes. With the `ui` option set, the widget writes its look's variables on the element, so they win over your CSS; without it they stay yours to set.
220
-
221
- ## Features
222
-
223
- ### Chart Types
224
-
225
- | Type | Description |
226
- |---|---|
227
- | Candlestick | Standard OHLC candles |
228
- | Hollow Candle | Open/close determines fill |
229
- | Bar (OHLC) | Classic open-high-low-close bars |
230
- | Line | Close price line |
231
- | Area | Filled area below close |
232
- | Baseline | Two-tone area split at a reference price |
233
- | Heikin-Ashi | Smoothed candles for trend identification |
234
- | Renko | Fixed-size bricks that ignore time |
235
- | Kagi | Reversal-based line chart |
236
- | Point & Figure | X/O columns for supply/demand analysis |
237
- | Line Break | Three-line break charts |
238
- | Range Bars | Fixed price-range bars — each bar's high − low equals a configured range |
239
- | Volume Candles | Candlesticks with width proportional to volume |
240
- | Equivolume | Full-range boxes with width proportional to volume share (Richard Arms style) |
241
- | HLC Area | High-low-close area band with close line |
242
- | Step Line | Staircase/step pattern from close prices |
243
- | Line with Markers | Close line with circular markers at each data point |
244
-
245
- ### Multi-Chart Grid
246
-
247
- Display multiple synchronized charts side-by-side with linked crosshairs and time axis:
248
-
249
- ```typescript
250
- import { ChartGrid, BinanceAdapter } from '@tradecanvas/chart'
251
-
252
- const grid = new ChartGrid(document.getElementById('grid')!, {
253
- layout: '2x2',
254
- syncCrosshair: true,
255
- syncTimeAxis: true,
256
- })
257
-
258
- // An adapter keeps one stream: give each chart its own
259
- grid.connectAll(() => new BinanceAdapter(), ['BTCUSDT', 'ETHUSDT', 'SOLUSDT', 'BNBUSDT'], '5m')
260
- ```
261
-
262
- With the full widget on each chart, a bar to pick the arrangement and sync, and the whole grid saved as a named layout:
263
-
264
- ```typescript
265
- import { ChartWidgetGrid } from '@tradecanvas/chart/widget'
266
-
267
- const workspace = new ChartWidgetGrid(document.getElementById('grid')!, {
268
- layout: '1x2',
269
- adapter: () => new BinanceAdapter(),
270
- cells: [{ symbol: 'BTCUSDT' }, { symbol: 'ETHUSDT', timeframe: '1h' }],
271
- sync: { crosshair: true, interval: false, symbol: false, time: false, drawings: false },
272
- })
273
- workspace.setSync({ time: true })
274
- ```
275
-
276
- Supported layouts: `'1x1'`, `'1x2'`, `'2x1'`, `'2x2'`, `'1x3'`, `'3x1'`, `'2x3'`, `'3x2'`.
277
-
278
- ### Command Palette
279
-
280
- Press `Ctrl+K` (or `Cmd+K`) inside ChartWidget to open a searchable command palette. Quickly find and toggle indicators, change chart types, activate drawing tools, switch timeframes, or trigger actions (screenshot, theme toggle, settings).
281
-
282
- ### Finance Charts
283
-
284
- | Chart | Description |
285
- |---|---|
286
- | SparklineChart | Tiny inline line/area chart from a number array — for dashboards and KPI cards |
287
- | DepthChart | Bid/ask order book visualization with cumulative volume areas |
288
- | EquityCurveChart | Portfolio equity line with drawdown shading and benchmark comparison |
289
- | HeatmapChart | Colored cell grid with treemap layout — for sector/market performance |
290
- | WaterfallChart | Running cumulative bars — P&L attribution, revenue bridge, cash flow |
291
- | GaugeChart | Speedometer-style gauge — KPIs, risk scores, Fear & Greed index |
292
-
293
- ```typescript
294
- import {
295
- SparklineChart, DepthChart, EquityCurveChart, HeatmapChart,
296
- WaterfallChart, GaugeChart,
297
- } from '@tradecanvas/chart'
298
-
299
- // Sparkline in a 120x48 container
300
- new SparklineChart(el, { data: [100, 102, 98, 105, 103], mode: 'area', color: '#1fa874' })
301
-
302
- // Equity curve with drawdown
303
- new EquityCurveChart(el, { data: equityPoints, drawdown: true, benchmark: spyData })
304
-
305
- // Order book depth
306
- new DepthChart(el, { data: { bids, asks }, crosshair: true })
307
-
308
- // Market heatmap (treemap weighted by market cap)
309
- new HeatmapChart(el, { data: cells, weighted: true })
310
-
311
- // P&L waterfall
312
- new WaterfallChart(el, {
313
- data: [
314
- { label: 'Start', value: 10000, type: 'total' },
315
- { label: 'Gain', value: 1850 },
316
- { label: 'Loss', value: -620 },
317
- { label: 'End', value: 11230, type: 'total' },
318
- ],
319
- })
320
-
321
- // Fear & Greed gauge: zones light up to the value, the label shows the current zone
322
- const gauge = new GaugeChart(el, {
323
- value: 72,
324
- label: 'Fear & Greed',
325
- zones: [
326
- { from: 0, to: 25, color: '#e8505b', label: 'Extreme fear' },
327
- { from: 25, to: 45, color: '#f2a93b', label: 'Fear' },
328
- { from: 45, to: 55, color: '#8a93a3', label: 'Neutral' },
329
- { from: 55, to: 75, color: '#62c895', label: 'Greed' },
330
- { from: 75, to: 100, color: '#1fa874', label: 'Extreme greed' },
331
- ],
332
- // pointer: 'needle', // classic needle instead of the ring marker
333
- })
334
- gauge.setValue(85) // animates smoothly
335
- ```
336
-
337
- ### Indicators (built-in)
338
-
339
- 95 indicators — moving averages (SMA, EMA, WMA, Hull, DEMA, TEMA, ALMA, KAMA,
340
- LSMA, McGinley, SMMA, MA Cross, MTF MA), bands and channels (Bollinger,
341
- Keltner, Donchian, Envelope, Linear Regression), trend and stops (Ichimoku,
342
- Supertrend, Parabolic SAR, Chandelier, Chande Kroll Stop, Alligator, ZigZag,
343
- Fractals, Pivot Points), VWAPs and Volume Profile on the price pane; RSI, MACD,
344
- Stochastic, ATR, ADX, CCI, OBV, MFI, Bollinger %B and BandWidth, Historical
345
- Volatility, Ulcer Index and 40 more oscillators, volume and volatility
346
- indicators in panes. The [indicator catalog](https://bonguynvan.github.io/tradecanvas/docs/indicators)
347
- lists every id with its inputs, lines and levels.
348
-
349
- ```typescript
350
- import { indicatorSource } from '@tradecanvas/chart'
351
-
352
- const rsi = chart.addIndicator('rsi', { period: 14 })!
353
- chart.addIndicator('ema', { period: 21, source: 'hlc3' }) // another price
354
- chart.addIndicator('sma', { period: 9, source: indicatorSource(rsi, 'value') }) // RSI's own average, in RSI's pane
355
- chart.setIndicatorLevels(rsi, [20, 50, 80])
356
- ```
357
-
358
- - **Sources**: close, open, high, low, hl2, hlc3, ohlc4, hlcc4, or another indicator's line.
359
- - **Panes**: one value scale per pane for lines, levels, axis and crosshair; move an indicator into another pane, a new one or back to the price pane; fold, maximise and reorder panes (`moveIndicatorToPane`, `setPaneCollapsed`, `setMaximizedPane`, `movePane`).
360
- - **Undo and templates**: Ctrl/Cmd+Z undoes indicator changes, in the same history as drawings; ChartWidget saves the indicators as named templates (`getIndicatorSetup` / `applyIndicatorSetup`).
361
- - **Levels**: editable per instance (RSI 30/70, CCI ±100 …), kept in saved layouts.
362
- - **Value tags**: each line's latest value on its axis, in its colour.
363
- - **Custom indicators** declare their lines (`plots`), scale, levels and inputs; the chart draws and labels them.
364
-
365
- Invalid parameters (NaN, Infinity, non-numeric strings, missing keys) fall back
366
- to the defaults instead of reaching the calculations.
367
-
368
- ### Drawing Tools
369
-
370
- Trendline, Horizontal Line, Vertical Line, Ray, Extended Line, Parallel Channel, Fibonacci Retracement, Fibonacci Extension, **Fibonacci Time Zones**, Rectangle, Ellipse, Triangle, Arrow, Pitchfork, Gann Fan, Gann Box, Elliott Wave, Regression Channel, Date Range, Price Range, Measure, Anchored VWAP, Volume Profile Range, Text Annotation
371
-
372
- All drawing tools support:
373
- - Click-to-place with magnet snapping to OHLC values
374
- - Undo / redo (Ctrl+Z / Ctrl+Y)
375
- - Serialization for save/load
376
- - Custom styles (color, width, dash pattern)
377
-
378
- ### Trading Overlay
379
-
380
- Render open positions and pending orders directly on the chart, like MT4/MT5.
381
-
382
- ```typescript
383
- import type { TradingPosition, TradingOrder } from '@tradecanvas/chart'
384
-
385
- chart.setPositions([{
386
- id: 'pos-1',
387
- side: 'buy',
388
- entryPrice: 3500,
389
- quantity: 1.5,
390
- closedQuantity: 0.5, // partial close — visualized as a left-edge dim band
391
- stopLoss: 3400,
392
- takeProfit: 3700,
393
- }])
394
-
395
- chart.setOrders([{
396
- id: 'order-1',
397
- side: 'sell',
398
- type: 'limit',
399
- price: 3800,
400
- quantity: 0.5,
401
- label: 'TP',
402
- draggable: true,
403
- }])
404
-
405
- // Customize the position zone color via P&L thresholds
406
- chart.setTradingConfig({
407
- pnlThresholds: [
408
- { pnl: -Infinity, color: '#b91c1c' },
409
- { pnl: 0, color: '#94a3b8' },
410
- { pnl: 50, color: '#16a34a' },
411
- { pnl: 200, color: '#15803d' },
412
- ],
413
- // Custom label template — tokens: {side} {qty} {openQty} {closedQty} {entry} {price} {pnl} {pnlPct} {pnlSign}
414
- positionLabel: '{side} {openQty}/{qty} @ {entry} | {pnlSign}{pnl} ({pnlPct})',
415
- })
416
-
417
- // Listen for user drag-to-modify
418
- chart.on('positionModify', (e) => console.log('SL/TP moved:', e.payload))
419
- chart.on('orderModify', (e) => console.log('Order moved:', e.payload))
420
-
421
- // The × and ⇅ buttons on the lines raise these; so can your own UI
422
- chart.cancelOrderIntent('order-1')
423
- chart.reversePositionIntent('pos-1')
424
- chart.on('executionFill', (e) => console.log(e.payload.reason, e.payload.pnl))
425
- ```
426
-
427
- ### Signal Markers
428
-
429
- Visualize buy/sell signals from bots, indicators, or manual analysis.
430
-
431
- ```typescript
432
- chart.addSignalMarker({
433
- time: 1715692800000,
434
- price: 62500,
435
- direction: 'long',
436
- confidence: 0.85,
437
- source: 'ema-crossover',
438
- label: 'EMA Cross',
439
- })
440
-
441
- // Color-code by source
442
- chart.setSignalMarkerStyle({
443
- sourceColors: {
444
- 'ema-crossover': '#4c8dff',
445
- 'rsi-divergence': '#f2a93b',
446
- 'whale-flow': '#9C27B0',
447
- },
448
- })
449
- ```
450
-
451
- ### Trade Zones
452
-
453
- Render entry→exit rectangles with P&L coloring for executed trades.
454
-
455
- ```typescript
456
- const zoneId = chart.addTradeZone({
457
- entryTime: 1715692800000,
458
- entryPrice: 62500,
459
- exitTime: 1715700000000,
460
- exitPrice: 63200,
461
- direction: 'long',
462
- pnl: 140,
463
- pnlPercent: 1.12,
464
- })
465
-
466
- // Update a live trade when it closes
467
- chart.updateTradeZone(zoneId, {
468
- exitTime: Date.now(),
469
- exitPrice: 63500,
470
- pnl: 200,
471
- })
472
- ```
473
-
474
- ### Real-Time Streaming
475
-
476
- ```typescript
477
- // Built-in Binance adapter (free, no API key)
478
- chart.connect({
479
- adapter: new BinanceAdapter(),
480
- symbol: 'ETHUSDT',
481
- timeframe: '1m',
482
- historyLimit: 500,
483
- })
484
-
485
- // Or manual data feed
486
- chart.setData(historicalBars)
487
- chart.appendBar(newBar)
488
- chart.updateLastBar(updatedBar)
489
- chart.setCurrentPrice(3500.42)
490
- ```
491
-
492
- ### Indicators outside the chart
493
-
494
- `IndicatorWorkerHost` computes an indicator from bars with the same messages a
495
- Web Worker would use. The worker script is not part of the published packages
496
- yet; pass `null` and register the plugins to compute in place (SSR, tests,
497
- scripts):
498
-
499
- ```typescript
500
- import { IndicatorWorkerHost, RSIIndicator } from '@tradecanvas/core'
501
-
502
- const host = new IndicatorWorkerHost(null)
503
- host.registerFallbackPlugin(new RSIIndicator())
504
- const output = await host.calculate('rsi', { id: 'rsi', instanceId: 'rsi-1', params: { period: 14 } }, bars)
505
- ```
506
-
507
- ### Save / Load
508
-
509
- ```typescript
510
- const json = chart.saveState()
511
- localStorage.setItem('my-chart', json!)
512
-
513
- chart.loadState(localStorage.getItem('my-chart')!)
514
-
515
- // Download / upload files
516
- chart.downloadState('my-chart.json')
517
- await chart.loadStateFromFile()
518
-
519
- // Or keep a layout saved as it changes (debounced)
520
- chart.setAutoSave('my-chart', 1500)
521
- ```
522
-
523
- A saved layout holds the chart type, theme, drawings, indicators (inputs, pane,
524
- colours, visibility) and alerts, including alerts on indicator lines.
525
-
526
- ### Themes
527
-
528
- ```typescript
529
- import { DARK_THEME, LIGHT_THEME, DARK_TERMINAL } from '@tradecanvas/chart'
530
-
531
- // Built-in presets: DARK_THEME, LIGHT_THEME, DARK_TERMINAL
532
- chart.setTheme(DARK_TERMINAL) // fintech terminal: #0E0E0E bg, #00FF87/#FF3B4D candles, monospace
533
-
534
- // Or customize any preset
535
- chart.setTheme({
536
- ...DARK_THEME,
537
- candleUp: '#1fa874',
538
- candleDown: '#e8505b',
539
- background: '#0a0a0f',
540
- })
541
- ```
542
-
543
- ### Events
544
-
545
- ```typescript
546
- chart.on('crosshairMove', (e) => { /* { point, bar, barIndex, indicatorValues } — also over indicator panes */ })
547
- chart.on('crosshairLeave', () => { /* the pointer left the plot */ })
548
- chart.on('drawingToolChange', (e) => { /* { tool } — null once a drawing is finished or cancelled */ })
549
- chart.on('indicatorUpdate', (e) => { /* { from } — indicator values recomputed from this bar on */ })
550
- chart.on('paneResize', (e) => { /* { instanceId, size } — an indicator pane was resized */ })
551
- chart.on('indicatorChange', (e) => { /* { instanceId, change } — shown/hidden, restyled, levels, inputs or pane changed */ })
552
- chart.on('barClick', (e) => { /* { bar, barIndex, point } */ })
553
- chart.on('visibleRangeChange', (e) => { /* { from, to } — bar indices, not timestamps */ })
554
- chart.on('priceRangeChange', (e) => { /* { min, max } — visible price bounds */ })
555
- chart.on('zoomChange', (e) => { /* { barWidth } — pixels per bar */ })
556
- chart.on('drawingCreate', (e) => { /* ... */ })
557
- chart.on('orderModify', (e) => { /* ... */ })
558
- chart.on('positionModify', (e) => { /* ... */ })
559
- ```
560
-
561
- `visibleRangeChange`, `priceRangeChange`, and `zoomChange` fire on every pan,
562
- zoom, resize, and data update — but only when that piece of viewport state
563
- actually changed. Resolve a `visibleRangeChange` index to time with
564
- `chart.getData()[e.payload.from].time`.
565
-
566
- ### Replay Mode
567
-
568
- `ReplayController` plays a historical `DataSeries` forward at controlled speed. Decoupled from `Chart` — wire it into any sink (chart for UI playback, or a strategy fn for headless backtests).
569
-
570
- ```typescript
571
- import { ReplayController } from '@tradecanvas/chart'
572
-
573
- const replay = new ReplayController({
574
- data: historicalBars,
575
- speed: 10, // bars per second
576
- startIndex: 0,
577
- })
578
-
579
- // Seed the chart with the prefix before replay starts
580
- chart.setData(replay.getPrefix())
581
-
582
- // Each emitted bar drives the chart forward
583
- replay.on('bar', ({ bar }) => chart.appendBar(bar))
584
- replay.on('finished', () => console.log('done'))
585
-
586
- replay.start()
587
- // replay.pause(); replay.resume(); replay.step(5); replay.seek(200); replay.setSpeed(20)
588
- ```
589
-
590
- ### Chart Interaction
591
-
592
- Every gesture you'd expect from a desktop trading chart is built in:
593
-
594
- | Gesture | Result |
595
- |---|---|
596
- | Drag chart body left/right | Pan through time |
597
- | Drag chart body up/down | Pan the price scale (freezes auto-scale; double-click price axis to restore) |
598
- | Drag price axis up/down | Compress / expand vertical scale (freezes auto-scale) |
599
- | Drag time axis left/right | Zoom time axis |
600
- | Double-click price axis | Re-enable auto-scale |
601
- | Double-click time axis | Fit all data to viewport |
602
- | Wheel | Zoom around cursor |
603
- | `Shift` + drag | Measure ruler (bars × time × price Δ × %) |
604
- | `Alt` + click | Pin OHLC tooltip; live crosshair shows Δ to pinned bar |
605
- | Hover | Price + time pill labels follow on both axes |
606
- | `Esc` | Unpin tooltip / cancel drawing |
607
- | `?` | Show keyboard-shortcut sheet *(widget)* |
608
- | `Ctrl/⌘ + K` | Command palette *(widget)* |
609
- | `Ctrl/⌘ + P` | Symbol search *(widget)* |
610
- | `Ctrl/⌘ + Z` / `Shift + Z` | Undo / redo drawings |
611
-
612
- ### Data import — drag-and-drop or programmatic
613
-
614
- ```typescript
615
- import { parseOHLCV } from '@tradecanvas/chart'
616
-
617
- const { data, rowCount, skipped } = parseOHLCV(csvText)
618
- chart.setData(data)
619
- ```
620
-
621
- Drop a CSV or JSON file onto the widget and it loads instantly. Auto-detects
622
- delimiter (`,` / `;` / tab / `|`), header vs. headerless, ISO 8601 timestamps,
623
- and array-of-arrays vs. array-of-objects JSON.
624
-
625
- ### Backtesting (`@tradecanvas/analytics`)
626
-
627
- Bar-by-bar strategy backtester with virtual fills, commission/slippage models, and a full risk-metrics report.
628
-
629
- ```typescript
630
- import { Backtester, PercentCommission, PercentSlippage } from '@tradecanvas/analytics'
631
-
632
- const bt = new Backtester({
633
- initialCash: 10_000,
634
- commission: new PercentCommission(0.0005),
635
- slippage: new PercentSlippage(0.0003),
636
- })
637
-
638
- const result = bt.run(historicalBars, (ctx) => {
639
- // Strategy fn runs at close of each bar; orders fill on the NEXT bar.
640
- if (!ctx.position && smaFast > smaSlow) {
641
- ctx.placeOrder({ side: 'long', type: 'market', quantity: 1 })
642
- } else if (ctx.position && smaFast < smaSlow) {
643
- ctx.close()
644
- }
645
- })
646
-
647
- console.log(result.metrics.sharpe) // 1.42
648
- console.log(result.metrics.maxDrawdownPct) // 0.087
649
- console.log(result.equityCurve) // → feed into the chart via EquityCurveRenderer
650
- ```
651
-
652
- Returns: `fills`, closed `trades`, `equityCurve`, `metrics` (Sharpe, Sortino, Calmar, CAGR, max drawdown, win rate, profit factor, expectancy). See the [live backtest demo](https://bonguynvan.github.io/tradecanvas/docs/analytics/).
653
-
654
- #### Strategy library (new in 0.9)
655
-
656
- Four drop-in reference strategies — each returns a `StrategyFn` ready to feed
657
- `Backtester.run()`:
658
-
659
- ```typescript
660
- import {
661
- Backtester,
662
- smaCrossStrategy,
663
- rsiReversionStrategy,
664
- donchianBreakoutStrategy,
665
- bollingerReversionStrategy,
666
- } from '@tradecanvas/analytics'
667
-
668
- const bt = new Backtester({ initialCash: 10_000 })
669
- bt.run(bars, smaCrossStrategy({ fastPeriod: 10, slowPeriod: 30 }))
670
- bt.run(bars, donchianBreakoutStrategy({ entryPeriod: 20, exitPeriod: 10 }))
671
- ```
672
-
673
- #### Monte Carlo path-dependence (new in 0.9)
674
-
675
- Shuffle realised trade order N times to expose whether a strategy depends on
676
- lucky sequencing. Tight P5/P95 band = robust edge; wide band = path-dependent.
677
-
678
- ```typescript
679
- import { runMonteCarlo } from '@tradecanvas/analytics'
680
-
681
- const result = bt.run(bars, smaCrossStrategy())
682
- const mc = runMonteCarlo(10_000, result.trades, { simulations: 1000, seed: 42 })
683
-
684
- mc.equityBands // [{ step, p5, p25, p50, p75, p95 }, …]
685
- mc.finalEquityPercentiles // { p5, p25, p50, p75, p95 }
686
- mc.probabilityProfitable // 0..1
687
- mc.worstMaxDrawdownPct
688
- ```
689
-
690
- ## Comparison
691
-
692
- | Feature | @tradecanvas/chart | lightweight-charts | chart.js | Highcharts Stock |
693
- |---|---|---|---|---|
694
- | Chart types | 18 + 6 finance | 4 | 8 (non-financial) | 10+ |
695
- | Finance charts | Sparkline, Depth, Equity, Heatmap, Waterfall, Gauge | None | None | Some |
696
- | Built-in indicators | 33 | 0 | 0 | ~30 |
697
- | Drawing tools | 24 | 0 | 0 | Some |
698
- | Trading overlay | Full (pos + orders + drag) | None | None | None |
699
- | Real-time streaming | Built-in (Binance) | Manual | Manual | Built-in |
700
- | Save/load state | Yes | No | No | Yes |
701
- | Replay mode | Yes (`ReplayController`) | No | No | No |
702
- | Backtester | Yes (`@tradecanvas/analytics`) | No | No | No |
703
- | Multi-chart grid | Yes (`ChartGrid`) | No | No | Yes |
704
- | Bundle (gzip) | ~56 KB core | ~45 KB | ~70 KB | ~200 KB |
705
- | Dependencies | 0 | 1 | 0 | 0 |
706
- | Widget (complete UI) | Yes (`ChartWidget`) | No | No | No |
707
- | License | MIT | Apache 2.0 | MIT | Commercial |
708
-
709
- ## API Overview
710
-
711
- ### `new Chart(container, options)`
712
-
713
- ```typescript
714
- const chart = new Chart(element, {
715
- chartType: 'candlestick',
716
- theme: DARK_THEME,
717
- autoScale: true,
718
- rightMargin: 5,
719
- numberLocale: 'en-US', // or 'de-DE', 'vi-VN', etc. — BCP 47 locale
720
- crosshair: { mode: 'magnet' },
721
- features: { drawings: true, indicators: true, trading: true, volume: true },
722
- })
723
-
724
- // Change locale at runtime
725
- chart.setNumberLocale('de-DE') // 65.234,00
726
- ```
727
-
728
- ### Key Methods
729
-
730
- | Method | Description |
731
- |---|---|
732
- | `setData(bars)` | Load historical OHLCV data |
733
- | `appendBar(bar)` | Append a new candle |
734
- | `appendBars(bars)` | Bulk append (reconnect catch-up) |
735
- | `updateLastBar(bar)` | Update the in-progress candle |
736
- | `setCurrentPrice(price, pulseColor?)` | Show a live price line |
737
- | `connect(config)` | Connect to a real-time data source |
738
- | `setTimeframe(tf)` | Switch timeframe on active stream |
739
- | `setChartType(type)` | Switch chart type |
740
- | `setTheme(theme)` | Apply a theme (DARK_THEME, LIGHT_THEME, DARK_TERMINAL) |
741
- | `setNumberLocale(locale)` | Set number format locale (en-US, de-DE, vi-VN) |
742
- | `setStatusText(text)` | Show status in legend area ("LIVE · 8ms") |
743
- | `addIndicator(id, params?)` | Add a technical indicator |
744
- | `removeIndicator(instanceId)` | Remove an indicator |
745
- | `setDrawingTool(tool)` | Activate a drawing tool |
746
- | `setPositions(positions)` | Render trading positions |
747
- | `setOrders(orders)` | Render pending orders |
748
- | `setVolumeProfileVisible(v)` | Toggle the horizontal volume-profile overlay |
749
- | `setVolumeProfileConfig({ buckets, widthRatio, opacity, highlightPoC })` | Tune the volume profile |
750
- | `setAutoScale(v)` / `setLogScale(v)` | Lock or change price-scale mode |
751
- | `setInvertScale(v)` | Turn the price scale upside down |
752
- | `fitContent()` / `scrollToEnd()` | Fit all data / jump to live edge |
753
- | `setVisibleRangePreset(p)` | Show `1D`, `5D`, `1M`, `3M`, `6M`, `YTD`, `1Y`, `5Y` or `All` |
754
- | `goToTime(time)` | Centre the bar at a time |
755
- | `setCrosshairTime(time)` | Mirror another chart's crosshair (vertical line only) |
756
- | `copyDrawings()` / `pasteDrawings()` | Copy the selection, paste into this or another chart |
757
- | `setStayInDrawingMode(v)` | Keep the drawing tool after each drawing |
758
- | `saveState(key?)` | Serialize chart state |
759
- | `loadState(json)` | Restore chart state |
760
- | `screenshot()` | Download chart as image |
761
- | `on(event, handler)` | Subscribe to events |
762
- | `destroy()` | Clean up all resources |
763
-
764
- ### Data Format
765
-
766
- ```typescript
767
- interface OHLCBar {
768
- time: number // Unix time in ms or seconds (up to 1e12 is read as seconds); ascending
769
- open: number
770
- high: number
771
- low: number
772
- close: number
773
- volume: number
774
- }
775
- ```
776
-
777
- ## Examples
778
-
779
- | Example | Description |
780
- |---|---|
781
- | [Live demo](https://bonguynvan.github.io/tradecanvas/) | Feature Lab: drawing tools, indicators, trading, replay, sub-cent prices + Vietnamese UI, 200k bars, slow-network switching — each on a live chart |
782
- | [StackBlitz sandboxes](https://bonguynvan.github.io/tradecanvas/examples/) | One-click, forkable: vanilla `Chart`, `ChartWidget`, React / Vue / Svelte wrappers, finance charts |
783
- | [`@tradecanvas/react`](https://www.npmjs.com/package/@tradecanvas/react) · [`/vue`](https://www.npmjs.com/package/@tradecanvas/vue) · [`/svelte`](https://www.npmjs.com/package/@tradecanvas/svelte) | Framework components — reactive props, typed, zero boilerplate |
784
-
785
- ## AI coding tools
786
-
787
- - [`llms.txt`](https://bonguynvan.github.io/tradecanvas/llms.txt) and
788
- [`llms-full.txt`](https://bonguynvan.github.io/tradecanvas/llms-full.txt) give
789
- assistants the docs in one place.
790
- - An agent skill, [`skills/tradecanvas`](https://github.com/bonguynvan/tradecanvas/blob/main/skills/tradecanvas/SKILL.md), teaches
791
- coding agents to build with TradeCanvas: the entry points, the rules that
792
- avoid most bugs, and worked examples that CI type-checks against the library.
793
- Copy the folder into your project's `.claude/skills/` (or your agent's skills
794
- folder) to use it.
795
-
796
- ## Browser Support
797
-
798
- Chrome 80+, Firefox 80+, Safari 14+, Edge 80+
799
-
800
- ## Framework Integration
801
-
802
- TradeCanvas is framework-agnostic. The `Chart` class takes a DOM element and manages its own canvas layers.
803
-
804
- **React:**
805
-
806
- ```tsx
807
- import { useEffect, useRef } from 'react'
808
- import { Chart, BinanceAdapter } from '@tradecanvas/chart'
809
-
810
- function TradingChart() {
811
- const ref = useRef<HTMLDivElement>(null)
812
-
813
- useEffect(() => {
814
- const chart = new Chart(ref.current!, {
815
- theme: 'dark',
816
- features: { indicators: true, drawings: true },
817
- })
818
- chart.connect({
819
- adapter: new BinanceAdapter(),
820
- symbol: 'BTCUSDT',
821
- timeframe: '5m',
822
- })
823
- return () => chart.destroy()
824
- }, [])
825
-
826
- return <div ref={ref} style={{ width: '100%', height: 500 }} />
827
- }
828
- ```
829
-
830
- **Svelte:**
831
-
832
- ```svelte
833
- <script lang="ts">
834
- import { onMount, onDestroy } from 'svelte'
835
- import { Chart, BinanceAdapter, DARK_THEME } from '@tradecanvas/chart'
836
- import type { TimeFrame } from '@tradecanvas/chart'
837
-
838
- interface Props { symbol?: string; timeframe?: TimeFrame }
839
- let { symbol = 'BTCUSDT', timeframe = '5m' }: Props = $props()
840
-
841
- let container: HTMLDivElement
842
- let chart: Chart | null = null
843
-
844
- onMount(() => {
845
- chart = new Chart(container, {
846
- chartType: 'candlestick',
847
- theme: DARK_THEME,
848
- autoScale: true,
849
- features: { indicators: true, drawings: true, volume: true },
850
- })
851
- chart.connect({ adapter: new BinanceAdapter(), symbol, timeframe })
852
- })
853
-
854
- onDestroy(() => chart?.destroy())
855
-
856
- $effect(() => {
857
- if (!chart) return
858
- chart.disconnectStream()
859
- chart.connect({ adapter: new BinanceAdapter(), symbol, timeframe })
860
- })
861
- </script>
862
-
863
- <div bind:this={container} style="width: 100%; height: 600px" />
864
- ```
865
-
866
- **Vue:**
867
-
868
- ```vue
869
- <template>
870
- <div ref="chartContainer" style="width: 100%; height: 600px" />
871
- </template>
872
-
873
- <script setup lang="ts">
874
- import { ref, onMounted, onUnmounted } from 'vue'
875
- import { Chart, BinanceAdapter, DARK_THEME } from '@tradecanvas/chart'
876
-
877
- const chartContainer = ref<HTMLDivElement>()
878
- let chart: Chart | null = null
879
-
880
- onMounted(() => {
881
- if (!chartContainer.value) return
882
- chart = new Chart(chartContainer.value, {
883
- chartType: 'candlestick',
884
- theme: DARK_THEME,
885
- autoScale: true,
886
- features: { indicators: true, drawings: true, volume: true },
887
- })
888
- chart.connect({ adapter: new BinanceAdapter(), symbol: 'BTCUSDT', timeframe: '5m' })
889
- })
890
-
891
- onUnmounted(() => chart?.destroy())
892
- </script>
893
- ```
894
-
895
- ## Architecture
896
-
897
- Two stacked canvases — a hover repaints only the thin top one:
898
-
899
- ```
900
- Top canvas (crosshair + axis pills, legend, countdown, measure) z=1
901
- Scene canvas (grid, candles, indicators, drawings, orders, axes) z=0
902
- ```
903
-
904
- ## Related projects
905
-
906
- - **[bo-grid](https://github.com/bonguynvan/bo-grid)** — tiny, fast **Svelte 5** data grid for fintech UIs: canvas sparklines, batched realtime cell updates, virtual scrolling, grouping / pivot / tree data, and Excel export, with a core that gzips to ~32 KB. The table half of the same toolkit — pair it with TradeCanvas for a full trading desk. **[Live demo](https://bonguynvan.github.io/bo-grid/)**
907
-
908
- ## License
909
-
910
- [MIT](./LICENSE)
1
+ <p align="center">
2
+ <a href="https://bonguynvan.github.io/tradecanvas/"><img src="https://raw.githubusercontent.com/bonguynvan/tradecanvas/main/.github/assets/banner.png" alt="TradeCanvas, the chart engine for trading apps" width="100%"></a>
3
+ </p>
4
+
5
+ <p align="center">
6
+ <a href="https://www.npmjs.com/package/@tradecanvas/chart"><img src="https://img.shields.io/npm/v/@tradecanvas/chart?style=flat-square&labelColor=0b0e13&color=f2a93b&label=npm" alt="npm version"></a>
7
+ <a href="https://www.npmjs.com/package/@tradecanvas/chart"><img src="https://img.shields.io/npm/dm/@tradecanvas/chart?style=flat-square&labelColor=0b0e13&color=3ccf91" alt="npm downloads"></a>
8
+ <a href="https://github.com/bonguynvan/tradecanvas/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/bonguynvan/tradecanvas/ci.yml?branch=main&style=flat-square&labelColor=0b0e13&label=CI" alt="CI status"></a>
9
+ <img src="https://img.shields.io/badge/third--party%20deps-0-3ccf91?style=flat-square&labelColor=0b0e13" alt="No third-party dependencies">
10
+ <img src="https://img.shields.io/badge/TypeScript-strict-4c8dff?style=flat-square&labelColor=0b0e13" alt="TypeScript">
11
+ <a href="https://github.com/bonguynvan/tradecanvas/blob/main/LICENSE"><img src="https://img.shields.io/github/license/bonguynvan/tradecanvas?style=flat-square&labelColor=0b0e13&color=a9b0bd" alt="MIT license"></a>
12
+ <a href="https://github.com/bonguynvan/tradecanvas/stargazers"><img src="https://img.shields.io/github/stars/bonguynvan/tradecanvas?style=flat-square&labelColor=0b0e13&color=f2a93b" alt="GitHub stars"></a>
13
+ </p>
14
+
15
+ <p align="center">
16
+ <b><a href="https://bonguynvan.github.io/tradecanvas/">Live demo</a></b> ·
17
+ <a href="https://bonguynvan.github.io/tradecanvas/docs/getting-started/">Docs</a> ·
18
+ <a href="https://bonguynvan.github.io/tradecanvas/examples/">Examples</a> ·
19
+ <a href="https://bonguynvan.github.io/tradecanvas/playground/">Playground</a> ·
20
+ <a href="https://github.com/bonguynvan/tradecanvas/blob/main/CHANGELOG.md">Changelog</a>
21
+ </p>
22
+
23
+ <p align="center">
24
+ <b>English</b> · <a href="https://github.com/bonguynvan/tradecanvas/blob/main/README.vi.md">Tiếng Việt</a> · <a href="https://github.com/bonguynvan/tradecanvas/blob/main/README.zh-CN.md">简体中文</a> · <a href="https://github.com/bonguynvan/tradecanvas/blob/main/README.ja.md">日本語</a> · <a href="https://github.com/bonguynvan/tradecanvas/blob/main/README.ko.md">한국어</a> · <a href="https://github.com/bonguynvan/tradecanvas/blob/main/README.es.md">Español</a>
25
+ </p>
26
+
27
+ **A complete trading chart for the web.** Candlesticks to Renko, 95 indicators, 69 drawing tools, live exchange feeds and orders on the chart, drawn on Canvas2D with zero dependencies. Drop in the full `ChartWidget`, or build your own UI on the headless `Chart`, in plain TypeScript, React, Vue or Svelte.
28
+
29
+ <p align="center">
30
+ <a href="https://bonguynvan.github.io/tradecanvas/"><img src="https://raw.githubusercontent.com/bonguynvan/tradecanvas/main/.github/assets/hero.png" alt="ChartWidget with live BTCUSDT from Binance: EMA 21 and 55, RSI, a trend line, a long position and a watchlist with live quotes" width="100%"></a>
31
+ </p>
32
+
33
+ ## Quick Start
34
+
35
+ ```bash
36
+ npm install @tradecanvas/chart # or: pnpm add / yarn add
37
+ ```
38
+
39
+ `ChartWidget` is the whole trading UI in one component: toolbar, drawing sidebar, settings dialog and status bar.
40
+
41
+ ```typescript
42
+ import { ChartWidget } from '@tradecanvas/chart/widget'
43
+ import { BinanceAdapter } from '@tradecanvas/chart'
44
+
45
+ const widget = new ChartWidget(document.getElementById('chart')!, {
46
+ symbol: 'BTCUSDT',
47
+ timeframe: '5m',
48
+ theme: 'dark',
49
+ adapter: new BinanceAdapter(), // live data, no API key
50
+ trading: true,
51
+ })
52
+ ```
53
+
54
+ That's it. Live data, all 95 indicators, all 69 drawing tools, command palette (`Ctrl+K`), symbol search (`Ctrl+P`), hotkey sheet (`?`), shift-drag measure, alt-click tooltip pin, and drag-drop CSV/JSON loading.
55
+
56
+ Using a framework? [`@tradecanvas/react`](https://github.com/bonguynvan/tradecanvas/tree/main/packages/react/), [`@tradecanvas/vue`](https://github.com/bonguynvan/tradecanvas/tree/main/packages/vue/) and [`@tradecanvas/svelte`](https://github.com/bonguynvan/tradecanvas/tree/main/packages/svelte/) wrap the headless `Chart` as a component, and the widget above mounts the same way in any framework; see [Framework Integration](#framework-integration). Or fork a [StackBlitz sandbox](https://bonguynvan.github.io/tradecanvas/examples/) and start from there.
57
+
58
+ ## A Look Around
59
+
60
+ <table>
61
+ <tr>
62
+ <td width="50%" valign="top">
63
+ <a href="https://raw.githubusercontent.com/bonguynvan/tradecanvas/main/.github/assets/drawings.png"><img src="https://raw.githubusercontent.com/bonguynvan/tradecanvas/main/.github/assets/drawings.png" alt="Drawing tools: a Fibonacci retracement with a note, a trend line, an Elliott impulse wave and a long position"></a>
64
+ <br><b>69 drawing tools</b><br>
65
+ Fibonacci, Gann, pitchforks, Elliott waves, harmonic patterns, notes and brushes, and a Long/Short position that sizes the trade. Alerts on trend lines, groups, undo and redo.
66
+ </td>
67
+ <td width="50%" valign="top">
68
+ <a href="https://raw.githubusercontent.com/bonguynvan/tradecanvas/main/.github/assets/trading.png"><img src="https://raw.githubusercontent.com/bonguynvan/tradecanvas/main/.github/assets/trading.png" alt="Trading on the chart: a long position with stop-loss and take-profit, a buy stop and a sell limit, and the account panel"></a>
69
+ <br><b>Trading on the chart</b><br>
70
+ Positions with live P&amp;L, orders you drag to a new price, SL and TP, reverse and close buttons, an order ticket and an account panel. A paper broker is built in; connect your own.
71
+ </td>
72
+ </tr>
73
+ <tr>
74
+ <td width="50%" valign="top">
75
+ <a href="https://raw.githubusercontent.com/bonguynvan/tradecanvas/main/.github/assets/grid.png"><img src="https://raw.githubusercontent.com/bonguynvan/tradecanvas/main/.github/assets/grid.png" alt="A two-by-two workspace of BTC, ETH, SOL and BNB charts on mixed intervals"></a>
76
+ <br><b>Multi-chart workspace</b><br>
77
+ Up to six full charts side by side, linked by symbol, interval, crosshair, time or drawings, and saved as one layout.
78
+ </td>
79
+ <td width="50%" valign="top">
80
+ <a href="https://raw.githubusercontent.com/bonguynvan/tradecanvas/main/.github/assets/looks.png"><img src="https://raw.githubusercontent.com/bonguynvan/tradecanvas/main/.github/assets/looks.png" alt="One chart in three looks: studio, terminal, and capsule on the light theme"></a>
81
+ <br><b>Your own look</b><br>
82
+ Three presets (studio, terminal, capsule) or your own corner radius, density, fonts, toolbar and price tags, on light and dark themes.
83
+ </td>
84
+ </tr>
85
+ </table>
86
+
87
+ ## Why TradeCanvas?
88
+
89
+ Most chart libraries make you choose: pretty charts with no trading features, or trading features with an ugly API. TradeCanvas gives you both.
90
+
91
+ - **95 built-in indicators** — SMA, EMA, TEMA, VWMA, Hull MA, RSI, MACD, Bollinger, Envelope, Ichimoku, Pivot Points, Anchored VWAP, ZigZag, Linear Regression Channel, Awesome / Chaikin Oscillator, and more. Any indicator can read another one's line (an SMA of RSI). No separate calculation library needed.
92
+ - **69 drawing tools** — Trendlines (info line, trend angle, cross line), Fibonacci (retracement, extension, channel, time zones, speed resistance fan and arcs, circles, spiral, wedge), horizontal/vertical lines, channels, pitchforks and pitchfan, Gann fan / box / square, cycles, harmonic patterns (XABCD, cypher, ABCD, three drives, head and shoulders), Elliott waves, notes, callouts and marks, brush and path, forecast and projection, Long/Short Position with position sizing, Volume Profile range. Each with its own settings, alerts on trend lines, groups and layers, undo/redo and full serialization.
93
+ - **18 chart types** — Candlestick, line, area, bar, hollow candle, baseline, High-Low, Heikin-Ashi, Renko, Kagi, Line Break, Point & Figure, Range Bars, Volume Candles, **Equivolume**, HLC Area, Step Line, Line+Markers. Renko's box, Kagi's reversal and the like are yours to set.
94
+ - **Pro-grade interaction** — pan freely past the last bar into empty future space (drawings can go there too), drag the price/time axes to scale, double-click to auto-fit, `Ctrl/⌘+drag` to select several drawings (then move, restyle or delete them together), `Shift+drag` to measure (bars × price Δ × %), `Alt+click` to pin a comparison tooltip, context cursors (crosshair, grabbing hand, resize arrows), axis-following price/time pill labels under the cursor, bar-hover highlight.
95
+ - **Trading overlay** — Render open positions with entry line, P&L zone, and SL/TP markers. Orders as dashed lines. Drag SL/TP to modify, cancel / close / reverse from the buttons on each line, and see every fill marked on its bar. ChartWidget adds an order ticket that checks the order as you fill it in, and an account panel with positions, working orders and history. Cleanly opt-out via `features.trading: false` for non-trading projects.
96
+ - **Real-time streaming** — Built-in Binance, Coinbase, Bybit, and Kraken adapters, plus generic `WebSocketAdapter` / `PollingAdapter` bases so any feed plugs in with ~20 lines. Older bars load as you scroll back, any interval (`7m`, `90m`, `2d`) is built from the feed's own, tick charts (`100T`) from its trades, and symbol search and quotes come from the feed.
97
+ - **Time zones** — any IANA zone with daylight saving time (`'America/New_York'`), a fixed offset, or the exchange's own zone, for the axis, crosshair, day breaks and session hours.
98
+ - **16 languages** — `ChartWidget` in English, Vietnamese, Simplified and Traditional Chinese, Japanese, Korean, Spanish, Portuguese, French, German, Russian, Turkish, Indonesian, Thai, Arabic and Hebrew; Arabic and Hebrew mirror right to left.
99
+ - **Accessible** — keyboard navigation, zoom and scroll buttons over the chart, and a screen-reader summary that reads the view and the bars one at a time.
100
+ - **Live execution** — connect an `ExecutionAdapter` to turn the trading overlay into a real trading surface, drag on the chart to create orders, and reconcile fills. Ships a `PaperExecutionAdapter` sandbox.
101
+ - **Plugin SDK** — register custom indicators, drawing tools, chart types, and overlays — globally or per-chart.
102
+ - **Strategy backtester** — `@tradecanvas/analytics` ships a bar-by-bar `Backtester` with virtual fills, commission/slippage models, portfolio tracking, and risk metrics (Sharpe, Sortino, Calmar, max drawdown). **Now with 4 ready-to-use reference strategies + Monte Carlo path-dependence analysis.**
103
+ - **Replay mode** — replay the chart's own bars from any point, in finer steps if you like (an hourly chart forming from 5-minute bars), with play / pause / step / seek / speed, and paper-trade on the replayed prices. The widget has a replay bar for it; `ReplayController` drives bars headless too.
104
+ - **Alerts** — on a price level, an indicator line, a drawing, or one line crossing another; on a move of some percent within some bars; only on closed bars; with an expiry. The widget's alerts panel sets all of them.
105
+ - **Compare and spread** — other symbols in percent on the price scale, on a scale or pane of their own, or as a spread or ratio, lined up with the chart by time.
106
+ - **Price formats** — prices in your own format or in fractions of a point (a bond in 32nds: 110'165) on every label; times your way; extended hours on or off; data export with the indicator lines.
107
+ - **Volume Profile** — optional horizontal histogram of traded volume bucketed by price over the visible range, with point-of-control highlighting.
108
+ - **Watchlists and symbol info** — lists of symbols to switch between, edit and reorder, with live quotes; a symbol panel with price, the market's status, the day's numbers, hours and news.
109
+ - **CSV / JSON drag-and-drop** — drop a file onto the chart, it parses and loads instantly. Detects header layouts, ISO/unix-s/unix-ms timestamps, and array-vs-object JSON shapes.
110
+ - **Named layouts** — save the chart under a name (symbol, interval, scale, indicators, drawings, alerts), open, rename, delete, auto-save the open one, `Ctrl/⌘+S`. Kept in the browser, or on your server through a four-call `LayoutStorage`. Per-symbol auto-persistence (`persistLayouts`) is there too.
111
+ - **Multi-chart** — `ChartWidgetGrid` puts up to six full widgets side by side, linked by symbol, interval, crosshair, time or drawings as you choose, and saves them as one layout. `ChartGrid` does the same for bare charts.
112
+ - **Signal markers & trade zones** — render bot/algorithm output (directional arrows, entry→exit rectangles) as a first-class chart layer.
113
+ - **Hotkey sheet** — press `?` in the widget to open a categorized keyboard-shortcut reference.
114
+ - **Extensible widget** — add your own toolbar buttons and right-click menu entries (`addToolbarButton`, `chartMenuItems`).
115
+ - **Save/load chart state** — Persist drawings, indicators, theme, and chart type to JSON. Restore with one call.
116
+ - **Zero dependencies** — The entire library is self-contained. No `d3`, no `chart.js`, no `fancy-canvas`.
117
+
118
+ ## Headless Chart
119
+
120
+ For projects that want to own the surrounding UI (custom toolbar, framework-specific controls), use the lower-level `Chart` class directly:
121
+
122
+ ```typescript
123
+ import { Chart, BinanceAdapter } from '@tradecanvas/chart'
124
+
125
+ const chart = new Chart(document.getElementById('chart')!, {
126
+ theme: 'dark',
127
+ autoScale: true,
128
+ features: {
129
+ drawings: true,
130
+ indicators: true,
131
+ trading: true, // set false to disable orders/positions entirely
132
+ tradingContextMenu: true, // opt-in right-click order menu (off by default)
133
+ volume: true,
134
+ },
135
+ })
136
+
137
+ const adapter = new BinanceAdapter()
138
+ chart.connect({ adapter, symbol: 'BTCUSDT', timeframe: '5m', historyLimit: 300 })
139
+ ```
140
+
141
+ ### Widget Options
142
+
143
+ | Option | Type | Default | Description |
144
+ |---|---|---|---|
145
+ | `symbol` | `string` | `'BTCUSDT'` | Initial trading symbol |
146
+ | `timeframe` | `TimeFrame` | `'5m'` | Initial timeframe |
147
+ | `theme` | `'dark' \| 'light' \| Theme` | `'dark'` | Chart theme |
148
+ | `adapter` | `DataAdapter` | — | Data source adapter |
149
+ | `toolbar` | `boolean` | `true` | Show top toolbar |
150
+ | `drawingTools` | `boolean` | `true` | Show left drawing sidebar |
151
+ | `settings` | `boolean` | `true` | Show settings button |
152
+ | `trading` | `boolean` | `true` | Enable trading overlay |
153
+ | `statusBar` | `boolean` | `true` | Show bottom status bar |
154
+ | `rangeBar` | `boolean` | `true` | Range presets (1D … All) and go to date (Alt+G) on the status bar |
155
+ | `indicatorLegend` | `boolean` | `true` | Indicators listed on the chart (under the OHLCV legend and atop their panes) with show / settings / remove |
156
+ | `fullscreen` | `boolean` | `true` | Fullscreen button in the toolbar |
157
+ | `symbols` | `string[]` | BTC/ETH/SOL/BNB | Searchable symbol catalog |
158
+ | `timeframes` | `TimeFrame[]` | 1m to 1M | Timeframes on offer; pin favourites from the ▾ menu |
159
+ | `chartTypes` | `ChartType[]` | 18 types | Available chart types |
160
+ | `watchlist` | `boolean` | `false` | Right-side watchlist sidebar |
161
+ | `dragDropImport` | `boolean` | `true` | Drop CSV / JSON files onto the chart to load data |
162
+ | `persistLayouts` | `boolean \| { keyPrefix, debounceMs }` | `false` | Save per-symbol indicators / drawings / chart type to localStorage |
163
+ | `onSymbolChange` | `(symbol) => void` | — | Symbol change callback |
164
+ | `onTimeframeChange` | `(tf) => void` | — | Timeframe change callback |
165
+ | `onReady` | `(chart) => void` | — | Fired when chart is ready |
166
+ | `locale` | `string` | `'en'` | UI language — `'en'` and `'vi'` built in, 12 more from the locales entry, see **Widget i18n** below |
167
+ | `messages` | `Partial<Record<MessageKey, string>>` | — | Override or add individual UI strings on top of `locale` |
168
+
169
+ ### Icons
170
+
171
+ The widget's icon set is exported for your own UI: `createIcon(name)`,
172
+ `createToolIcon(drawingTool)`, `createChartTypeIcon(chartType)` return inline
173
+ SVG strings drawn in `currentColor` (24 px grid, 1.75 px strokes).
174
+
175
+ ```ts
176
+ import { createToolIcon } from '@tradecanvas/chart/widget'
177
+ button.innerHTML = createToolIcon('fibRetracement', 16)
178
+ ```
179
+
180
+ ### Widget i18n
181
+
182
+ `ChartWidget` speaks 16 languages: English, Vietnamese, Simplified and Traditional Chinese, Japanese, Korean, Spanish, Portuguese, French, German, Russian, Turkish, Indonesian, Thai, Arabic and Hebrew (the last two right to left; `dir` sets the direction yourself). Every string it shows is translated: toolbar, settings, drawing tools, alerts, dialogs, the command palette, the hotkey sheet and notices. Indicator names (SMA, RSI…) stay as they are. Set at construction.
183
+
184
+ English and Vietnamese are built in. The others load from `@tradecanvas/chart/widget/locales`, so a page ships only the languages it imports:
185
+
186
+ ```ts
187
+ import { ja } from '@tradecanvas/chart/widget/locales'
188
+
189
+ new ChartWidget(el, {
190
+ locale: 'ja',
191
+ messages: ja, // or registerWidgetLocales() for all of them
192
+ chartOptions: { numberLocale: 'ja-JP' }, // separate: number/date formatting (see below)
193
+ });
194
+ ```
195
+
196
+ `messages` also overrides single keys on top of `locale` (`{ 'watchlist.title': 'Theo dõi' }`). A locale with a region falls back to its language (`ja-JP` → `ja`; `zh-TW` → Traditional Chinese).
197
+
198
+ `locale`/`messages` cover the **text**; `chartOptions.numberLocale` controls number and date **formatting** (price axis, legend, watchlist prices, current-price tag, session-break dates) via `Intl`.
199
+
200
+ See `packages/library/src/widget/locales/en.ts` for the full key list (`MessageKey`).
201
+
202
+ ### Widget vs Headless
203
+
204
+ | | `Chart` (headless) | `ChartWidget` |
205
+ |---|---|---|
206
+ | Import | `@tradecanvas/chart` | `@tradecanvas/chart/widget` |
207
+ | UI included | None — build your own | Complete toolbar, sidebar, settings |
208
+ | Bundle impact | ~50 KB gzip | ~65 KB gzip (includes UI) |
209
+ | Framework | Any (React, Vue, Svelte, vanilla) | Vanilla JS DOM (works everywhere) |
210
+ | Customization | Full control | Toggle sections on/off |
211
+ | Advanced access | Direct API | `widget.getChart()` for direct API |
212
+
213
+ ### Widget Look
214
+
215
+ The widget's shapes and sizes — corners, control heights, type, borders, shadows, how a chosen button shows, bars docked or floating — are a look of their own, apart from the colours. Three presets: **Studio** (the default), **Terminal** (dense and square) and **Capsule** (pills, floating bars). Start from one and change what you like:
216
+
217
+ ```ts
218
+ const widget = new ChartWidget(host, { ui: 'terminal' });
219
+ widget.setUI({ preset: 'studio', radius: { md: 10 }, density: 'compact', toolbar: 'floating', active: 'solid' });
220
+ ```
221
+
222
+ The chart's price tags take the same corners (`tagRadius`; on a bare `Chart`, `chart.setShapes({ tagRadius })`). The widget loads no fonts: load the ones a look names. See [Styling](https://bonguynvan.github.io/tradecanvas/docs/styling).
223
+
224
+ ### Widget Theming
225
+
226
+ `ChartWidget`'s own chrome (toolbar, sidebars, settings panel, watchlist — everything *outside* the canvas) is styled entirely through CSS custom properties on `.tcw-root`, the widget's own root element. These are a **stable, documented contract**: additive-only across minor/patch releases — a property is never renamed or removed without a major version bump. Override them from the host page; no build step or theme object needed.
227
+
228
+ ```css
229
+ /* Dark is the default (no attribute needed); light sets data-tcw-theme="light" */
230
+ .my-app .tcw-root:not([data-tcw-theme="light"]) {
231
+ --tcw-bg: #0a0a0f;
232
+ --tcw-accent: #7c5cff;
233
+ --tcw-radius: 0px;
234
+ --tcw-radius-lg: 0px;
235
+ }
236
+ ```
237
+
238
+ | Variable | Default (dark) | Purpose |
239
+ |---|---|---|
240
+ | `--tcw-bg` | `#080b10` | Root background |
241
+ | `--tcw-bg-surface` | `#0c1016` | Panel / toolbar surface |
242
+ | `--tcw-bg-elevated` | `#141922` | Popovers, dropdowns, modals |
243
+ | `--tcw-bg-overlay` | `rgba(20,25,34,.5)` | Backdrop behind overlays |
244
+ | `--tcw-border` | `#1f2630` | Default border |
245
+ | `--tcw-border-strong` | `#2a323e` | Emphasized border (focus rings, dividers) |
246
+ | `--tcw-text` | `#e7e9ee` | Primary text |
247
+ | `--tcw-text-dim` | `#aab1bd` | Secondary text |
248
+ | `--tcw-text-muted` | `#758091` | Tertiary / placeholder text |
249
+ | `--tcw-accent` | `#f2a93b` | Primary accent (active tab, focus, links) |
250
+ | `--tcw-accent-ink` | `#1a1204` | Text and icons on an accent fill |
251
+ | `--tcw-accent-hover` | `#f5b95c` | Accent hover state |
252
+ | `--tcw-accent-soft` | `rgba(242,169,59,.14)` | Accent tint (selected row background) |
253
+ | `--tcw-accent-glow` | `rgba(242,169,59,.22)` | Accent glow (focus halo) |
254
+ | `--tcw-accent-line` | `rgba(242,169,59,.55)` | Accent border/underline |
255
+ | `--tcw-red` / `--tcw-red-soft` | `#e8505b` / tint | Down/sell/negative |
256
+ | `--tcw-green` / `--tcw-green-soft` | `#1fa874` / tint | Up/buy/positive |
257
+ | `--tcw-amber` | `#ff9f43` | Warning |
258
+ | `--tcw-hover-bg` | `rgba(255,255,255,.05)` | Row/button hover background |
259
+ | `--tcw-active-bg` | `rgba(255,255,255,.08)` | Row/button pressed background |
260
+ | `--tcw-divider` | `rgba(255,255,255,.06)` | Hairline dividers |
261
+ | `--tcw-ease` / `--tcw-ease-out` | cubic-bezier | Transition easing |
262
+ | `--tcw-dur-fast` / `-normal` / `-slow` | `120ms` / `180ms` / `260ms` | Transition durations |
263
+ | `--tcw-radius-xs` / `-sm` / `--tcw-radius` / `-lg` / `-xl` | `3px` / `5px` / `7px` / `11px` / `16px` | The corner scale — set to `0` for a square look |
264
+ | `--tcw-control-radius` / `--tcw-input-radius` / `--tcw-menu-radius` / `--tcw-dialog-radius` / `--tcw-panel-radius` / `--tcw-tooltip-radius` / `--tcw-tag-radius` / `--tcw-toast-radius` | from the scale | Each kind of part's corners |
265
+ | `--tcw-toolbar-h` / `--tcw-control-h` / `--tcw-control-h-sm` / `--tcw-icon` / `--tcw-sidebar-w` / `--tcw-menu-item-h` | `46px` / `30px` / `24px` / `18px` / `48px` / `30px` | Sizes |
266
+ | `--tcw-font` / `--tcw-font-size` / `--tcw-weight` / `--tcw-weight-strong` | `'Manrope', 'Inter', …` / `13px` / `500` / `600` | Type |
267
+ | `--tcw-label-case` / `--tcw-label-tracking` | `none` / `0em` | Small labels (section titles) |
268
+ | `--tcw-border-w` / `--tcw-sep-w` | `1px` / `0px` | Border width; rules between toolbar groups |
269
+ | `--tcw-menu-shadow` / `--tcw-dialog-shadow` / `--tcw-tooltip-shadow` | the elevation shadows | Shadows of menus, dialogs, tooltips |
270
+ | `--tcw-blur` / `--tcw-surface-opacity` | `0px` / `100%` | Frosted menus |
271
+ | `--tcw-shadow-sm` / `-md` / `-lg` / `-xl` | box-shadow values | Elevation |
272
+ | `--tcw-ring` | `0 0 0 2px rgba(242,169,59,.45)` | Focus ring |
273
+ | `--tcw-font-mono` | `'JetBrains Mono', …` | Monospace font stack (price ladder, code) |
274
+
275
+ Light theme (`[data-tcw-theme="light"]`) redefines the color group (`--tcw-bg*`, `--tcw-border*`, `--tcw-text*`, `--tcw-accent*`, `--tcw-hover-bg`, `--tcw-active-bg`, `--tcw-divider`, `--tcw-shadow*`) with its own defaults — override both selectors if you support both themes. With the `ui` option set, the widget writes its look's variables on the element, so they win over your CSS; without it they stay yours to set.
276
+
277
+ ## Features
278
+
279
+ ### Chart Types
280
+
281
+ | Type | Description |
282
+ |---|---|
283
+ | Candlestick | Standard OHLC candles |
284
+ | Hollow Candle | Open/close determines fill |
285
+ | Bar (OHLC) | Classic open-high-low-close bars |
286
+ | Line | Close price line |
287
+ | Area | Filled area below close |
288
+ | Baseline | Two-tone area split at a reference price |
289
+ | Heikin-Ashi | Smoothed candles for trend identification |
290
+ | Renko | Fixed-size bricks that ignore time |
291
+ | Kagi | Reversal-based line chart |
292
+ | Point & Figure | X/O columns for supply/demand analysis |
293
+ | Line Break | Three-line break charts |
294
+ | Range Bars | Fixed price-range bars — each bar's high − low equals a configured range |
295
+ | Volume Candles | Candlesticks with width proportional to volume |
296
+ | Equivolume | Full-range boxes with width proportional to volume share (Richard Arms style) |
297
+ | HLC Area | High-low-close area band with close line |
298
+ | Step Line | Staircase/step pattern from close prices |
299
+ | Line with Markers | Close line with circular markers at each data point |
300
+
301
+ ### Multi-Chart Grid
302
+
303
+ Display multiple synchronized charts side-by-side with linked crosshairs and time axis:
304
+
305
+ ```typescript
306
+ import { ChartGrid, BinanceAdapter } from '@tradecanvas/chart'
307
+
308
+ const grid = new ChartGrid(document.getElementById('grid')!, {
309
+ layout: '2x2',
310
+ syncCrosshair: true,
311
+ syncTimeAxis: true,
312
+ })
313
+
314
+ // An adapter keeps one stream: give each chart its own
315
+ grid.connectAll(() => new BinanceAdapter(), ['BTCUSDT', 'ETHUSDT', 'SOLUSDT', 'BNBUSDT'], '5m')
316
+ ```
317
+
318
+ With the full widget on each chart, a bar to pick the arrangement and sync, and the whole grid saved as a named layout:
319
+
320
+ ```typescript
321
+ import { ChartWidgetGrid } from '@tradecanvas/chart/widget'
322
+
323
+ const workspace = new ChartWidgetGrid(document.getElementById('grid')!, {
324
+ layout: '1x2',
325
+ adapter: () => new BinanceAdapter(),
326
+ cells: [{ symbol: 'BTCUSDT' }, { symbol: 'ETHUSDT', timeframe: '1h' }],
327
+ sync: { crosshair: true, interval: false, symbol: false, time: false, drawings: false },
328
+ })
329
+ workspace.setSync({ time: true })
330
+ ```
331
+
332
+ Supported layouts: `'1x1'`, `'1x2'`, `'2x1'`, `'2x2'`, `'1x3'`, `'3x1'`, `'2x3'`, `'3x2'`.
333
+
334
+ ### Command Palette
335
+
336
+ Press `Ctrl+K` (or `Cmd+K`) inside ChartWidget to open a searchable command palette. Quickly find and toggle indicators, change chart types, activate drawing tools, switch timeframes, or trigger actions (screenshot, theme toggle, settings).
337
+
338
+ ### Finance Charts
339
+
340
+ | Chart | Description |
341
+ |---|---|
342
+ | SparklineChart | Tiny inline line/area chart from a number array — for dashboards and KPI cards |
343
+ | DepthChart | Bid/ask order book visualization with cumulative volume areas |
344
+ | EquityCurveChart | Portfolio equity line with drawdown shading and benchmark comparison |
345
+ | HeatmapChart | Colored cell grid with treemap layout — for sector/market performance |
346
+ | WaterfallChart | Running cumulative bars — P&L attribution, revenue bridge, cash flow |
347
+ | GaugeChart | Speedometer-style gauge — KPIs, risk scores, Fear & Greed index |
348
+
349
+ ```typescript
350
+ import {
351
+ SparklineChart, DepthChart, EquityCurveChart, HeatmapChart,
352
+ WaterfallChart, GaugeChart,
353
+ } from '@tradecanvas/chart'
354
+
355
+ // Sparkline in a 120x48 container
356
+ new SparklineChart(el, { data: [100, 102, 98, 105, 103], mode: 'area', color: '#1fa874' })
357
+
358
+ // Equity curve with drawdown
359
+ new EquityCurveChart(el, { data: equityPoints, drawdown: true, benchmark: spyData })
360
+
361
+ // Order book depth
362
+ new DepthChart(el, { data: { bids, asks }, crosshair: true })
363
+
364
+ // Market heatmap (treemap weighted by market cap)
365
+ new HeatmapChart(el, { data: cells, weighted: true })
366
+
367
+ // P&L waterfall
368
+ new WaterfallChart(el, {
369
+ data: [
370
+ { label: 'Start', value: 10000, type: 'total' },
371
+ { label: 'Gain', value: 1850 },
372
+ { label: 'Loss', value: -620 },
373
+ { label: 'End', value: 11230, type: 'total' },
374
+ ],
375
+ })
376
+
377
+ // Fear & Greed gauge: zones light up to the value, the label shows the current zone
378
+ const gauge = new GaugeChart(el, {
379
+ value: 72,
380
+ label: 'Fear & Greed',
381
+ zones: [
382
+ { from: 0, to: 25, color: '#e8505b', label: 'Extreme fear' },
383
+ { from: 25, to: 45, color: '#f2a93b', label: 'Fear' },
384
+ { from: 45, to: 55, color: '#8a93a3', label: 'Neutral' },
385
+ { from: 55, to: 75, color: '#62c895', label: 'Greed' },
386
+ { from: 75, to: 100, color: '#1fa874', label: 'Extreme greed' },
387
+ ],
388
+ // pointer: 'needle', // classic needle instead of the ring marker
389
+ })
390
+ gauge.setValue(85) // animates smoothly
391
+ ```
392
+
393
+ ### Indicators (built-in)
394
+
395
+ 95 indicators — moving averages (SMA, EMA, WMA, Hull, DEMA, TEMA, ALMA, KAMA,
396
+ LSMA, McGinley, SMMA, MA Cross, MTF MA), bands and channels (Bollinger,
397
+ Keltner, Donchian, Envelope, Linear Regression), trend and stops (Ichimoku,
398
+ Supertrend, Parabolic SAR, Chandelier, Chande Kroll Stop, Alligator, ZigZag,
399
+ Fractals, Pivot Points), VWAPs and Volume Profile on the price pane; RSI, MACD,
400
+ Stochastic, ATR, ADX, CCI, OBV, MFI, Bollinger %B and BandWidth, Historical
401
+ Volatility, Ulcer Index and 40 more oscillators, volume and volatility
402
+ indicators in panes. The [indicator catalog](https://bonguynvan.github.io/tradecanvas/docs/indicators)
403
+ lists every id with its inputs, lines and levels.
404
+
405
+ ```typescript
406
+ import { indicatorSource } from '@tradecanvas/chart'
407
+
408
+ const rsi = chart.addIndicator('rsi', { period: 14 })!
409
+ chart.addIndicator('ema', { period: 21, source: 'hlc3' }) // another price
410
+ chart.addIndicator('sma', { period: 9, source: indicatorSource(rsi, 'value') }) // RSI's own average, in RSI's pane
411
+ chart.setIndicatorLevels(rsi, [20, 50, 80])
412
+ ```
413
+
414
+ - **Sources**: close, open, high, low, hl2, hlc3, ohlc4, hlcc4, or another indicator's line.
415
+ - **Panes**: one value scale per pane for lines, levels, axis and crosshair; move an indicator into another pane, a new one or back to the price pane; fold, maximise and reorder panes (`moveIndicatorToPane`, `setPaneCollapsed`, `setMaximizedPane`, `movePane`).
416
+ - **Undo and templates**: Ctrl/Cmd+Z undoes indicator changes, in the same history as drawings; ChartWidget saves the indicators as named templates (`getIndicatorSetup` / `applyIndicatorSetup`).
417
+ - **Levels**: editable per instance (RSI 30/70, CCI ±100 …), kept in saved layouts.
418
+ - **Value tags**: each line's latest value on its axis, in its colour.
419
+ - **Custom indicators** declare their lines (`plots`), scale, levels and inputs; the chart draws and labels them.
420
+
421
+ Invalid parameters (NaN, Infinity, non-numeric strings, missing keys) fall back
422
+ to the defaults instead of reaching the calculations.
423
+
424
+ ### Drawing Tools
425
+
426
+ Trendline, Horizontal Line, Vertical Line, Ray, Extended Line, Parallel Channel, Fibonacci Retracement, Fibonacci Extension, **Fibonacci Time Zones**, Rectangle, Ellipse, Triangle, Arrow, Pitchfork, Gann Fan, Gann Box, Elliott Wave, Regression Channel, Date Range, Price Range, Measure, Anchored VWAP, Volume Profile Range, Text Annotation
427
+
428
+ All drawing tools support:
429
+ - Click-to-place with magnet snapping to OHLC values
430
+ - Undo / redo (Ctrl+Z / Ctrl+Y)
431
+ - Serialization for save/load
432
+ - Custom styles (color, width, dash pattern)
433
+
434
+ ### Trading Overlay
435
+
436
+ Render open positions and pending orders directly on the chart, like MT4/MT5.
437
+
438
+ ```typescript
439
+ import type { TradingPosition, TradingOrder } from '@tradecanvas/chart'
440
+
441
+ chart.setPositions([{
442
+ id: 'pos-1',
443
+ side: 'buy',
444
+ entryPrice: 3500,
445
+ quantity: 1.5,
446
+ closedQuantity: 0.5, // partial close — visualized as a left-edge dim band
447
+ stopLoss: 3400,
448
+ takeProfit: 3700,
449
+ }])
450
+
451
+ chart.setOrders([{
452
+ id: 'order-1',
453
+ side: 'sell',
454
+ type: 'limit',
455
+ price: 3800,
456
+ quantity: 0.5,
457
+ label: 'TP',
458
+ draggable: true,
459
+ }])
460
+
461
+ // Customize the position zone color via P&L thresholds
462
+ chart.setTradingConfig({
463
+ pnlThresholds: [
464
+ { pnl: -Infinity, color: '#b91c1c' },
465
+ { pnl: 0, color: '#94a3b8' },
466
+ { pnl: 50, color: '#16a34a' },
467
+ { pnl: 200, color: '#15803d' },
468
+ ],
469
+ // Custom label template — tokens: {side} {qty} {openQty} {closedQty} {entry} {price} {pnl} {pnlPct} {pnlSign}
470
+ positionLabel: '{side} {openQty}/{qty} @ {entry} | {pnlSign}{pnl} ({pnlPct})',
471
+ })
472
+
473
+ // Listen for user drag-to-modify
474
+ chart.on('positionModify', (e) => console.log('SL/TP moved:', e.payload))
475
+ chart.on('orderModify', (e) => console.log('Order moved:', e.payload))
476
+
477
+ // The × and ⇅ buttons on the lines raise these; so can your own UI
478
+ chart.cancelOrderIntent('order-1')
479
+ chart.reversePositionIntent('pos-1')
480
+ chart.on('executionFill', (e) => console.log(e.payload.reason, e.payload.pnl))
481
+ ```
482
+
483
+ ### Signal Markers
484
+
485
+ Visualize buy/sell signals from bots, indicators, or manual analysis.
486
+
487
+ ```typescript
488
+ chart.addSignalMarker({
489
+ time: 1715692800000,
490
+ price: 62500,
491
+ direction: 'long',
492
+ confidence: 0.85,
493
+ source: 'ema-crossover',
494
+ label: 'EMA Cross',
495
+ })
496
+
497
+ // Color-code by source
498
+ chart.setSignalMarkerStyle({
499
+ sourceColors: {
500
+ 'ema-crossover': '#4c8dff',
501
+ 'rsi-divergence': '#f2a93b',
502
+ 'whale-flow': '#9C27B0',
503
+ },
504
+ })
505
+ ```
506
+
507
+ ### Trade Zones
508
+
509
+ Render entry→exit rectangles with P&L coloring for executed trades.
510
+
511
+ ```typescript
512
+ const zoneId = chart.addTradeZone({
513
+ entryTime: 1715692800000,
514
+ entryPrice: 62500,
515
+ exitTime: 1715700000000,
516
+ exitPrice: 63200,
517
+ direction: 'long',
518
+ pnl: 140,
519
+ pnlPercent: 1.12,
520
+ })
521
+
522
+ // Update a live trade when it closes
523
+ chart.updateTradeZone(zoneId, {
524
+ exitTime: Date.now(),
525
+ exitPrice: 63500,
526
+ pnl: 200,
527
+ })
528
+ ```
529
+
530
+ ### Real-Time Streaming
531
+
532
+ ```typescript
533
+ // Built-in Binance adapter (free, no API key)
534
+ chart.connect({
535
+ adapter: new BinanceAdapter(),
536
+ symbol: 'ETHUSDT',
537
+ timeframe: '1m',
538
+ historyLimit: 500,
539
+ })
540
+
541
+ // Or manual data feed
542
+ chart.setData(historicalBars)
543
+ chart.appendBar(newBar)
544
+ chart.updateLastBar(updatedBar)
545
+ chart.setCurrentPrice(3500.42)
546
+ ```
547
+
548
+ **Built-in adapters** (all free, no API key): `BinanceAdapter`, `CoinbaseAdapter`, `BybitAdapter`, `KrakenAdapter`, plus `MockAdapter` for offline/testing.
549
+
550
+ ```typescript
551
+ import { BybitAdapter, KrakenAdapter, CoinbaseAdapter } from '@tradecanvas/chart'
552
+
553
+ chart.connect({ adapter: new BybitAdapter(), symbol: 'BTCUSDT', timeframe: '1m' })
554
+ chart.connect({ adapter: new KrakenAdapter(), symbol: 'BTC/USD', timeframe: '5m' })
555
+ chart.connect({ adapter: new CoinbaseAdapter(), symbol: 'BTC-USD', timeframe: '15m' })
556
+ ```
557
+
558
+ **Any feed in ~20 lines.** Extend `WebSocketAdapter` (live + REST history) or `PollingAdapter` (REST-only feeds) — the base handles the connection lifecycle, reconnect, decoding, and event emission. You supply a URL and a parse function:
559
+
560
+ ```typescript
561
+ import { WebSocketAdapter } from '@tradecanvas/chart'
562
+
563
+ const myAdapter = new WebSocketAdapter({
564
+ name: 'myexchange',
565
+ wsUrl: (c) => `wss://api.myexchange.com/ws/${c.symbol}@kline_${c.timeframe}`,
566
+ fetchHistory: (symbol, tf, limit) => fetch(`/candles?...`).then((r) => r.json()),
567
+ parseMessage: (raw) => ({ bar: toBar(raw), closed: raw.k.x }),
568
+ })
569
+ ```
570
+
571
+ ### Live Execution
572
+
573
+ Connect an `ExecutionAdapter` to turn the display-only trading overlay into a real trading surface. The chart routes its order/position intents into the adapter, and renders the authoritative `orders` / `positions` the adapter emits back — the **adapter is the single source of truth**. With no adapter connected, those intents stay plain events (backward-compatible).
574
+
575
+ ```typescript
576
+ import { PaperExecutionAdapter } from '@tradecanvas/chart'
577
+
578
+ chart.connectExecution(new PaperExecutionAdapter({ markPrice: 64000 }))
579
+
580
+ // Drag-to-create an order, then confirm:
581
+ chart.startOrderDraft('buy') // draggable line at the latest close
582
+ chart.confirmOrderDraft() // emits orderPlace → adapter fills → chart renders the position
583
+ // chart.cancelOrderDraft()
584
+
585
+ // One channel for failures (adapter-reported or a failed command):
586
+ chart.on('executionError', (e) => toast(e.payload.message))
587
+ ```
588
+
589
+ Implement `ExecutionAdapter` (it mirrors `DataAdapter`) to wire a real broker / OMS: `placeOrder`, `modifyOrder`, `cancelOrder`, `modifyPosition`, `closePosition`, plus `orders` / `positions` / `fill` / `error` events. `PaperExecutionAdapter` is a virtual-fill sandbox for demos and tests. The order type of a drag-to-create order (limit vs stop) is inferred from where you drop the line relative to the current price.
590
+
591
+ ### Plugins — extend the chart
592
+
593
+ Register custom **indicators**, **drawing tools**, **chart types**, and **overlays** — globally (every chart created afterward inherits) or per-chart.
594
+
595
+ ```typescript
596
+ import { Chart, registerPlugin, IndicatorBase } from '@tradecanvas/chart'
597
+
598
+ class MyIndicator extends IndicatorBase { /* descriptor, calculate(), render() */ }
599
+
600
+ // 1) Global — available to every chart created afterward:
601
+ registerPlugin({ kind: 'indicator', plugin: new MyIndicator() })
602
+
603
+ // 2) Per-chart at construction:
604
+ const chart = new Chart(el, { plugins: [{ kind: 'overlay', plugin: myHeatmap }] })
605
+
606
+ // 3) Imperative on an instance:
607
+ chart.plugins.register({ kind: 'chartType', plugin: myCustomCandles })
608
+ chart.setChartType('my-custom-candles') // custom chart types render via the plugin
609
+ ```
610
+
611
+ | Plugin kind | Contract |
612
+ |---|---|
613
+ | `indicator` | `IndicatorPlugin` — `calculate()` + `render()` |
614
+ | `drawing` | `DrawingPlugin` — `render()` + `hitTest()` |
615
+ | `chartType` | `ChartTypePlugin` — `createRenderer()` + optional `transform()` |
616
+ | `overlay` | `OverlayPlugin` — `render(ctx, { viewport, data, theme })` on the `main` / `overlay` / `ui` layer |
617
+
618
+ ### Indicators outside the chart
619
+
620
+ `IndicatorWorkerHost` computes an indicator from bars with the same messages a
621
+ Web Worker would use. The worker script is not part of the published packages
622
+ yet; pass `null` and register the plugins to compute in place (SSR, tests,
623
+ scripts):
624
+
625
+ ```typescript
626
+ import { IndicatorWorkerHost, RSIIndicator } from '@tradecanvas/core'
627
+
628
+ const host = new IndicatorWorkerHost(null)
629
+ host.registerFallbackPlugin(new RSIIndicator())
630
+ const output = await host.calculate('rsi', { id: 'rsi', instanceId: 'rsi-1', params: { period: 14 } }, bars)
631
+ ```
632
+
633
+ ### Save / Load
634
+
635
+ ```typescript
636
+ const json = chart.saveState()
637
+ localStorage.setItem('my-chart', json!)
638
+
639
+ chart.loadState(localStorage.getItem('my-chart')!)
640
+
641
+ // Download / upload files
642
+ chart.downloadState('my-chart.json')
643
+ await chart.loadStateFromFile()
644
+
645
+ // Or keep a layout saved as it changes (debounced)
646
+ chart.setAutoSave('my-chart', 1500)
647
+ ```
648
+
649
+ A saved layout holds the chart type, theme, drawings, indicators (inputs, pane,
650
+ colours, visibility) and alerts, including alerts on indicator lines.
651
+
652
+ ### Themes
653
+
654
+ ```typescript
655
+ import { DARK_THEME, LIGHT_THEME, DARK_TERMINAL, volumeColor } from '@tradecanvas/chart'
656
+
657
+ // Built-in presets: DARK_THEME, LIGHT_THEME, DARK_TERMINAL
658
+ chart.setTheme(DARK_TERMINAL) // fintech terminal: #0E0E0E bg, #00FF87/#FF3B4D candles, monospace
659
+
660
+ // Or customize any preset
661
+ chart.setTheme({
662
+ ...DARK_THEME,
663
+ candleUp: '#1fa874',
664
+ candleDown: '#e8505b',
665
+ volumeUp: volumeColor('#1fa874'), // volume bars: the candle colour, see-through
666
+ volumeDown: volumeColor('#e8505b'),
667
+ background: '#0a0a0f',
668
+ })
669
+ ```
670
+
671
+ ### Events
672
+
673
+ ```typescript
674
+ chart.on('crosshairMove', (e) => { /* { point, bar, barIndex, indicatorValues } — also over indicator panes */ })
675
+ chart.on('crosshairLeave', () => { /* the pointer left the plot */ })
676
+ chart.on('drawingToolChange', (e) => { /* { tool } — null once a drawing is finished or cancelled */ })
677
+ chart.on('indicatorUpdate', (e) => { /* { from } — indicator values recomputed from this bar on */ })
678
+ chart.on('paneResize', (e) => { /* { instanceId, size } — an indicator pane was resized */ })
679
+ chart.on('indicatorChange', (e) => { /* { instanceId, change } — shown/hidden, restyled, levels, inputs or pane changed */ })
680
+ chart.on('barClick', (e) => { /* { bar, barIndex, point } */ })
681
+ chart.on('visibleRangeChange', (e) => { /* { from, to } — bar indices, not timestamps */ })
682
+ chart.on('priceRangeChange', (e) => { /* { min, max } — visible price bounds */ })
683
+ chart.on('zoomChange', (e) => { /* { barWidth } — pixels per bar */ })
684
+ chart.on('drawingCreate', (e) => { /* ... */ })
685
+ chart.on('orderModify', (e) => { /* ... */ })
686
+ chart.on('positionModify', (e) => { /* ... */ })
687
+ ```
688
+
689
+ `visibleRangeChange`, `priceRangeChange`, and `zoomChange` fire on every pan,
690
+ zoom, resize, and data update — but only when that piece of viewport state
691
+ actually changed. Resolve a `visibleRangeChange` index to time with
692
+ `chart.getData()[e.payload.from].time`.
693
+
694
+ ### Replay Mode
695
+
696
+ `ReplayController` plays a historical `DataSeries` forward at controlled speed. Decoupled from `Chart` — wire it into any sink (chart for UI playback, or a strategy fn for headless backtests).
697
+
698
+ ```typescript
699
+ import { ReplayController } from '@tradecanvas/chart'
700
+
701
+ const replay = new ReplayController({
702
+ data: historicalBars,
703
+ speed: 10, // bars per second
704
+ startIndex: 0,
705
+ })
706
+
707
+ // Seed the chart with the prefix before replay starts
708
+ chart.setData(replay.getPrefix())
709
+
710
+ // Each emitted bar drives the chart forward
711
+ replay.on('bar', ({ bar }) => chart.appendBar(bar))
712
+ replay.on('finished', () => console.log('done'))
713
+
714
+ replay.start()
715
+ // replay.pause(); replay.resume(); replay.step(5); replay.seek(200); replay.setSpeed(20)
716
+ ```
717
+
718
+ ### Chart Interaction
719
+
720
+ Every gesture you'd expect from a desktop trading chart is built in:
721
+
722
+ | Gesture | Result |
723
+ |---|---|
724
+ | Drag chart body left/right | Pan through time |
725
+ | Drag chart body up/down | Pan the price scale (freezes auto-scale; double-click price axis to restore) |
726
+ | Drag price axis up/down | Compress / expand vertical scale (freezes auto-scale) |
727
+ | Drag time axis left/right | Zoom time axis |
728
+ | Double-click price axis | Re-enable auto-scale |
729
+ | Double-click time axis | Fit all data to viewport |
730
+ | Wheel | Zoom around cursor |
731
+ | Drag a pane divider | Resize the indicator pane (`ns-resize` cursor on hover) |
732
+ | `Shift` + drag | Measure ruler (bars × time × price Δ × %) |
733
+ | `Alt` + click | Pin OHLC tooltip; live crosshair shows Δ to pinned bar |
734
+ | Hover | Price + time pill labels follow on both axes |
735
+ | `Esc` | Unpin tooltip / cancel drawing |
736
+ | `?` | Show keyboard-shortcut sheet *(widget)* |
737
+ | `Ctrl/⌘ + K` | Command palette *(widget)* |
738
+ | `Ctrl/⌘ + P` | Symbol search *(widget)* |
739
+ | `Ctrl/⌘ + Z` / `Shift + Z` | Undo / redo drawings |
740
+
741
+ ### Data import — drag-and-drop or programmatic
742
+
743
+ ```typescript
744
+ import { parseOHLCV } from '@tradecanvas/chart'
745
+
746
+ const { data, rowCount, skipped } = parseOHLCV(csvText)
747
+ chart.setData(data)
748
+ ```
749
+
750
+ Drop a CSV or JSON file onto the widget and it loads instantly. Auto-detects
751
+ delimiter (`,` / `;` / tab / `|`), header vs. headerless, ISO 8601 timestamps,
752
+ and array-of-arrays vs. array-of-objects JSON.
753
+
754
+ ### Backtesting (`@tradecanvas/analytics`)
755
+
756
+ Bar-by-bar strategy backtester with virtual fills, commission/slippage models, and a full risk-metrics report.
757
+
758
+ ```typescript
759
+ import { Backtester, PercentCommission, PercentSlippage } from '@tradecanvas/analytics'
760
+
761
+ const bt = new Backtester({
762
+ initialCash: 10_000,
763
+ commission: new PercentCommission(0.0005),
764
+ slippage: new PercentSlippage(0.0003),
765
+ })
766
+
767
+ const result = bt.run(historicalBars, (ctx) => {
768
+ // Strategy fn runs at close of each bar; orders fill on the NEXT bar.
769
+ if (!ctx.position && smaFast > smaSlow) {
770
+ ctx.placeOrder({ side: 'long', type: 'market', quantity: 1 })
771
+ } else if (ctx.position && smaFast < smaSlow) {
772
+ ctx.close()
773
+ }
774
+ })
775
+
776
+ console.log(result.metrics.sharpe) // 1.42
777
+ console.log(result.metrics.maxDrawdownPct) // 0.087
778
+ console.log(result.equityCurve) // → feed into the chart via EquityCurveRenderer
779
+ ```
780
+
781
+ Returns: `fills`, closed `trades`, `equityCurve`, `metrics` (Sharpe, Sortino, Calmar, CAGR, max drawdown, win rate, profit factor, expectancy). See the [live backtest demo](https://bonguynvan.github.io/tradecanvas/docs/analytics/).
782
+
783
+ #### Strategy library
784
+ Four drop-in reference strategies — each returns a `StrategyFn` ready to feed
785
+ `Backtester.run()`:
786
+
787
+ ```typescript
788
+ import {
789
+ Backtester,
790
+ smaCrossStrategy,
791
+ rsiReversionStrategy,
792
+ donchianBreakoutStrategy,
793
+ bollingerReversionStrategy,
794
+ } from '@tradecanvas/analytics'
795
+
796
+ const bt = new Backtester({ initialCash: 10_000 })
797
+ bt.run(bars, smaCrossStrategy({ fastPeriod: 10, slowPeriod: 30 }))
798
+ bt.run(bars, donchianBreakoutStrategy({ entryPeriod: 20, exitPeriod: 10 }))
799
+ ```
800
+
801
+ #### Monte Carlo path-dependence
802
+ Shuffle realised trade order N times to expose whether a strategy depends on
803
+ lucky sequencing. Tight P5/P95 band = robust edge; wide band = path-dependent.
804
+
805
+ ```typescript
806
+ import { runMonteCarlo } from '@tradecanvas/analytics'
807
+
808
+ const result = bt.run(bars, smaCrossStrategy())
809
+ const mc = runMonteCarlo(10_000, result.trades, { simulations: 1000, seed: 42 })
810
+
811
+ mc.equityBands // [{ step, p5, p25, p50, p75, p95 }, …]
812
+ mc.finalEquityPercentiles // { p5, p25, p50, p75, p95 }
813
+ mc.probabilityProfitable // 0..1
814
+ mc.worstMaxDrawdownPct
815
+ ```
816
+
817
+ ## Comparison
818
+
819
+ | Feature | @tradecanvas/chart | lightweight-charts | chart.js | Highcharts Stock |
820
+ |---|---|---|---|---|
821
+ | Chart types | 18 + 6 finance | 4 | 8 (non-financial) | 10+ |
822
+ | Finance charts | Sparkline, Depth, Equity, Heatmap, Waterfall, Gauge | None | None | Some |
823
+ | Built-in indicators | 95 | 0 | 0 | ~30 |
824
+ | Drawing tools | 69 | 0 | 0 | Some |
825
+ | Trading overlay | Full (pos + orders + drag) | None | None | None |
826
+ | Real-time streaming | Built-in (Binance) | Manual | Manual | Built-in |
827
+ | Save/load state | Yes | No | No | Yes |
828
+ | Replay mode | Yes (`ReplayController`) | No | No | No |
829
+ | Backtester | Yes (`@tradecanvas/analytics`) | No | No | No |
830
+ | Multi-chart grid | Yes (`ChartGrid`) | No | No | Yes |
831
+ | Bundle (gzip) | ~100 KB core | ~45 KB | ~70 KB | ~200 KB |
832
+ | Dependencies | 0 | 1 | 0 | 0 |
833
+ | Widget (complete UI) | Yes (`ChartWidget`) | No | No | No |
834
+ | License | MIT | Apache 2.0 | MIT | Commercial |
835
+
836
+ ## API Overview
837
+
838
+ ### `new Chart(container, options)`
839
+
840
+ ```typescript
841
+ const chart = new Chart(element, {
842
+ chartType: 'candlestick',
843
+ theme: DARK_THEME,
844
+ autoScale: true,
845
+ rightMargin: 5,
846
+ numberLocale: 'en-US', // or 'de-DE', 'vi-VN', etc. — BCP 47 locale
847
+ crosshair: { mode: 'magnet' },
848
+ features: { drawings: true, indicators: true, trading: true, volume: true },
849
+ })
850
+
851
+ // Change locale at runtime
852
+ chart.setNumberLocale('de-DE') // 65.234,00
853
+ ```
854
+
855
+ ### Key Methods
856
+
857
+ | Method | Description |
858
+ |---|---|
859
+ | `setData(bars)` | Load historical OHLCV data |
860
+ | `appendBar(bar)` | Append a new candle |
861
+ | `appendBars(bars)` | Bulk append (reconnect catch-up) |
862
+ | `updateLastBar(bar)` | Update the in-progress candle |
863
+ | `setCurrentPrice(price, pulseColor?)` | Show a live price line |
864
+ | `connect(config)` | Connect to a real-time data source |
865
+ | `setTimeframe(tf)` | Switch timeframe on active stream |
866
+ | `setChartType(type)` | Switch chart type |
867
+ | `setTheme(theme)` | Apply a theme (DARK_THEME, LIGHT_THEME, DARK_TERMINAL) |
868
+ | `setNumberLocale(locale)` | Set number format locale (en-US, de-DE, vi-VN) |
869
+ | `setStatusText(text)` | Show status in legend area ("LIVE · 8ms") |
870
+ | `addIndicator(id, params?)` | Add a technical indicator |
871
+ | `removeIndicator(instanceId)` | Remove an indicator |
872
+ | `setDrawingTool(tool)` | Activate a drawing tool |
873
+ | `setPositions(positions)` | Render trading positions |
874
+ | `setOrders(orders)` | Render pending orders |
875
+ | `setVolumeProfileVisible(v)` | Toggle the horizontal volume-profile overlay |
876
+ | `setVolumeProfileConfig({ buckets, widthRatio, opacity, highlightPoC })` | Tune the volume profile |
877
+ | `setAutoScale(v)` / `setLogScale(v)` | Lock or change price-scale mode |
878
+ | `setInvertScale(v)` | Turn the price scale upside down |
879
+ | `fitContent()` / `scrollToEnd()` | Fit all data / jump to live edge |
880
+ | `setVisibleRangePreset(p)` | Show `1D`, `5D`, `1M`, `3M`, `6M`, `YTD`, `1Y`, `5Y` or `All` |
881
+ | `goToTime(time)` | Centre the bar at a time |
882
+ | `setCrosshairTime(time)` | Mirror another chart's crosshair (vertical line only) |
883
+ | `copyDrawings()` / `pasteDrawings()` | Copy the selection, paste into this or another chart |
884
+ | `setStayInDrawingMode(v)` | Keep the drawing tool after each drawing |
885
+ | `saveState(key?)` | Serialize chart state |
886
+ | `loadState(json)` | Restore chart state |
887
+ | `screenshot()` | Download chart as image |
888
+ | `setRenderer(mode)` | Draw with `'canvas'` (default), `'webgl'` or `'auto'`; resolves to what draws now |
889
+ | `getRenderer()` | `'canvas'` or `'webgl'` |
890
+ | `on(event, handler)` | Subscribe to events |
891
+ | `destroy()` | Clean up all resources |
892
+
893
+ ### Data Format
894
+
895
+ ```typescript
896
+ interface OHLCBar {
897
+ time: number // Unix time in ms or seconds (up to 1e12 is read as seconds); ascending
898
+ open: number
899
+ high: number
900
+ low: number
901
+ close: number
902
+ volume: number
903
+ }
904
+ ```
905
+
906
+ ## Examples
907
+
908
+ | Example | Description |
909
+ |---|---|
910
+ | [Live demo](https://bonguynvan.github.io/tradecanvas/) | Feature Lab: drawing tools, indicators, trading, ranges, paged history, replay, 16 languages with sub-cent prices, watchlists with live quotes, 200k bars, slow-network switching — each on a live chart. The site and docs are also in Vietnamese, Chinese, Japanese, Korean and Spanish |
911
+ | [StackBlitz sandboxes](https://bonguynvan.github.io/tradecanvas/examples/) | One-click, forkable: vanilla `Chart`, `ChartWidget`, React / Vue / Svelte wrappers, finance charts |
912
+ | [`@tradecanvas/react`](https://github.com/bonguynvan/tradecanvas/tree/main/packages/react/) · [`/vue`](https://github.com/bonguynvan/tradecanvas/tree/main/packages/vue/) · [`/svelte`](https://github.com/bonguynvan/tradecanvas/tree/main/packages/svelte/) | Framework components — reactive props, typed, zero boilerplate |
913
+
914
+ ## AI coding tools
915
+
916
+ - [`llms.txt`](https://bonguynvan.github.io/tradecanvas/llms.txt) and
917
+ [`llms-full.txt`](https://bonguynvan.github.io/tradecanvas/llms-full.txt) give
918
+ assistants the docs in one place.
919
+ - An agent skill, [`skills/tradecanvas`](https://github.com/bonguynvan/tradecanvas/blob/main/skills/tradecanvas/SKILL.md), teaches
920
+ coding agents to build with TradeCanvas: the entry points, the rules that
921
+ avoid most bugs, and worked examples that CI type-checks against the library.
922
+ Copy the folder into your project's `.claude/skills/` (or your agent's skills
923
+ folder) to use it.
924
+
925
+ ## Browser Support
926
+
927
+ Chrome 80+, Firefox 80+, Safari 14+, Edge 80+
928
+
929
+ ## Framework Integration
930
+
931
+ Official wrapper components — reactive props, refs, zero boilerplate. Published at `1.x` alongside the core:
932
+
933
+ ```bash
934
+ npm install @tradecanvas/react # or @tradecanvas/vue · @tradecanvas/svelte
935
+ ```
936
+
937
+ ```tsx
938
+ import { TradeCanvas } from '@tradecanvas/react'
939
+
940
+ <TradeCanvas symbol="BTCUSDT" timeframe="5m" theme="dark" indicators={['rsi', 'macd']} />
941
+ ```
942
+
943
+ All three share the same prop surface and hand you the underlying `Chart` (for drawings, trading, execution, plugins) via `onReady` / ref / `bind:chart`. See the [frameworks docs](https://bonguynvan.github.io/tradecanvas/docs/frameworks).
944
+
945
+ ### Headless (own the lifecycle)
946
+
947
+ The `Chart` class also takes a DOM element directly — framework-agnostic:
948
+
949
+ **React:**
950
+
951
+ ```tsx
952
+ import { useEffect, useRef } from 'react'
953
+ import { Chart, BinanceAdapter } from '@tradecanvas/chart'
954
+
955
+ function TradingChart() {
956
+ const ref = useRef<HTMLDivElement>(null)
957
+
958
+ useEffect(() => {
959
+ const chart = new Chart(ref.current!, {
960
+ theme: 'dark',
961
+ features: { indicators: true, drawings: true },
962
+ })
963
+ chart.connect({
964
+ adapter: new BinanceAdapter(),
965
+ symbol: 'BTCUSDT',
966
+ timeframe: '5m',
967
+ })
968
+ return () => chart.destroy()
969
+ }, [])
970
+
971
+ return <div ref={ref} style={{ width: '100%', height: 500 }} />
972
+ }
973
+ ```
974
+
975
+ **Svelte:**
976
+
977
+ ```svelte
978
+ <script lang="ts">
979
+ import { onMount, onDestroy } from 'svelte'
980
+ import { Chart, BinanceAdapter, DARK_THEME } from '@tradecanvas/chart'
981
+ import type { TimeFrame } from '@tradecanvas/chart'
982
+
983
+ interface Props { symbol?: string; timeframe?: TimeFrame }
984
+ let { symbol = 'BTCUSDT', timeframe = '5m' }: Props = $props()
985
+
986
+ let container: HTMLDivElement
987
+ let chart: Chart | null = null
988
+
989
+ onMount(() => {
990
+ chart = new Chart(container, {
991
+ chartType: 'candlestick',
992
+ theme: DARK_THEME,
993
+ autoScale: true,
994
+ features: { indicators: true, drawings: true, volume: true },
995
+ })
996
+ chart.connect({ adapter: new BinanceAdapter(), symbol, timeframe })
997
+ })
998
+
999
+ onDestroy(() => chart?.destroy())
1000
+
1001
+ $effect(() => {
1002
+ if (!chart) return
1003
+ chart.disconnectStream()
1004
+ chart.connect({ adapter: new BinanceAdapter(), symbol, timeframe })
1005
+ })
1006
+ </script>
1007
+
1008
+ <div bind:this={container} style="width: 100%; height: 600px" />
1009
+ ```
1010
+
1011
+ **Vue:**
1012
+
1013
+ ```vue
1014
+ <template>
1015
+ <div ref="chartContainer" style="width: 100%; height: 600px" />
1016
+ </template>
1017
+
1018
+ <script setup lang="ts">
1019
+ import { ref, onMounted, onUnmounted } from 'vue'
1020
+ import { Chart, BinanceAdapter, DARK_THEME } from '@tradecanvas/chart'
1021
+
1022
+ const chartContainer = ref<HTMLDivElement>()
1023
+ let chart: Chart | null = null
1024
+
1025
+ onMounted(() => {
1026
+ if (!chartContainer.value) return
1027
+ chart = new Chart(chartContainer.value, {
1028
+ chartType: 'candlestick',
1029
+ theme: DARK_THEME,
1030
+ autoScale: true,
1031
+ features: { indicators: true, drawings: true, volume: true },
1032
+ })
1033
+ chart.connect({ adapter: new BinanceAdapter(), symbol: 'BTCUSDT', timeframe: '5m' })
1034
+ })
1035
+
1036
+ onUnmounted(() => chart?.destroy())
1037
+ </script>
1038
+ ```
1039
+
1040
+ ## Performance
1041
+
1042
+ A two-canvas Canvas2D pipeline: a hover repaints only the thin top canvas, never the scene. Five things keep large data fast:
1043
+
1044
+ - **LTTB downsampling** — line / area charts automatically downsample the visible range to ~2 points per pixel using Largest-Triangle-Three-Buckets when there are far more bars than pixels. The line stays visually identical while drawing dozens of times fewer points; a no-op at normal zoom. The `lttbDownsample` utility is exported for your own use.
1045
+ - **Indicators zoomed out** — below a pixel per bar, indicator lines, bands and histograms draw one span per pixel column instead of a stroke through thousands of points: much the same look for a fraction of the raster work (about 54 → 21 ms a frame zoomed out on 200,000 bars with four indicators, on integrated graphics). `node scripts/bench-render.mjs` measures it on your machine.
1046
+ - **Visible-range rendering** — every renderer iterates only the bars in view, never the whole series. Hover and pan frame cost stays flat from 500 to 100,000 loaded bars.
1047
+ - **Incremental indicators on live ticks** — a tick only changes the forming bar, so built-in indicators that implement `update()` (SMA, EMA, WMA, VWMA, Bollinger, Envelope, RSI, MACD, ATR, OBV, Stochastic) recompute just that bar instead of the whole history. Others fall back to a full recalculation. Custom plugins can opt in via `IndicatorPlugin.update`.
1048
+ - **Cheap full loads** — a symbol/timeframe switch recomputes every indicator once. Their per-bar `values` lookup is an `IndicatorValueMap` (array-backed while bars arrive in time order, ~3x cheaper to build than a `Map` keyed by timestamps), and `setData` reuses already well-formed bars instead of copying each one.
1049
+
1050
+ BB + EMA + RSI + MACD (`pnpm bench`, single core):
1051
+
1052
+ | History | Full recalculation (switch / `setData`) | Incremental `update()` (live tick) |
1053
+ |---|---|---|
1054
+ | 20,000 bars | ~5 ms | ~0.0005 ms |
1055
+ | 100,000 bars | ~27 ms | ~0.001 ms |
1056
+
1057
+ Downsampling throughput (`pnpm bench`, single core):
1058
+
1059
+ | Visible points → 1600 | Time / frame | Throughput |
1060
+ |---|---|---|
1061
+ | 10,000 | ~0.025 ms | 39,600 / s |
1062
+ | 100,000 | ~0.32 ms | 3,100 / s |
1063
+ | 1,000,000 | ~2.6 ms | 380 / s |
1064
+
1065
+ A 100k-bar line chart downsamples in ~0.3 ms — well inside a 16.6 ms frame budget — then draws ~62× fewer points (100k → 1600).
1066
+
1067
+ ### WebGL renderer (preview)
1068
+
1069
+ `renderer: 'webgl'` draws the plot and indicator panes with WebGL 2, on a canvas under the 2D scene: the grid, sessions, candles and volume directly, and the Canvas 2D drawing of indicators, compare lines and most chart types recorded as GPU strokes, fills and rectangles, antialiased at their edges as Canvas 2D is. Text, drawings, orders, axes and the crosshair stay on Canvas 2D, as does anything the GPU wouldn't draw the same (left to Canvas 2D in order, so the stacking doesn't change); custom indicator plugins come along without changes. Candles match Canvas 2D to within 2/255; lines and fills differ only on a few antialiased edge pixels. The WebGL code is a chunk of its own (about 17 KB gzipped), loaded on first use; where WebGL 2 is missing, or its context is lost, the chart carries on with Canvas 2D.
1070
+
1071
+ ```typescript
1072
+ const chart = new Chart(el, { renderer: 'webgl' }) // or 'auto': WebGL on a hardware GPU only
1073
+
1074
+ chart.on('rendererChange', (e) => console.log(e.payload))
1075
+ // { renderer: 'webgl' }, or { renderer: 'canvas', reason: 'unsupported' | 'contextLost' }
1076
+
1077
+ await chart.setRenderer('canvas') // resolves to what draws now
1078
+ ```
1079
+
1080
+ Frame time while panning, on integrated graphics (Intel UHD; 16.7 ms is 60 fps):
1081
+
1082
+ | Chart | Pixel ratio | Canvas 2D | WebGL |
1083
+ |---|---|---|---|
1084
+ | 1600×900, 500 candles + 4 indicators | 2 | 27.4 ms | 19.6 ms |
1085
+ | 1600×900, zoomed out on 200,000 bars + 4 indicators | 2 | 34.5 ms | 20.2 ms |
1086
+ | Six charts, 500 candles and two indicators each | 2 | 23.5 ms | 17.2 ms |
1087
+ | 2560×1400, 2,000 candles + 4 indicators | 1 | 41.6 ms | 17.7 ms |
1088
+ | 2560×1400, 2,000 candles + 4 indicators | 1.5 | 70.8 ms | 17.6 ms |
1089
+ | 2560×1400, 2,000 candles + 4 indicators | 2 | 114.5 ms | 29.1 ms |
1090
+ | 2560×1400, 2,000 candles | 2 | 33.1 ms | 20.9 ms |
1091
+
1092
+ Most WebGL frames above land on 16.7 ms; the averages carry a few longer ones. At a pixel ratio of 2 on a 2560×1400 chart, the browser's compositing of the full-size layers alone takes about 23 ms on this GPU. `node scripts/bench-render.mjs --renderer=webgl` runs these numbers on your own machine.
1093
+
1094
+ ## Architecture
1095
+
1096
+ Two stacked canvases — a hover repaints only the thin top one:
1097
+
1098
+ ```
1099
+ Top canvas (crosshair + axis pills, legend, countdown, measure) z=1
1100
+ Scene canvas (grid, candles, indicators, drawings, orders, axes) z=0
1101
+ ```
1102
+
1103
+ ## Related projects
1104
+
1105
+ - **[bo-grid](https://github.com/bonguynvan/bo-grid)** — tiny, fast **Svelte 5** data grid for fintech UIs: canvas sparklines, batched realtime cell updates, virtual scrolling, grouping / pivot / tree data, and Excel export, with a core that gzips to ~32 KB. The table half of the same toolkit — pair it with TradeCanvas for a full trading desk. **[Live demo](https://bonguynvan.github.io/bo-grid/)**
1106
+
1107
+ ## Contributing
1108
+
1109
+ Bug reports, ideas and pull requests are welcome. [CONTRIBUTING.md](https://github.com/bonguynvan/tradecanvas/blob/main/CONTRIBUTING.md) covers the setup (`pnpm install && pnpm build && pnpm test`), how the repo is laid out and what a pull request needs. Found a security issue? Please follow [SECURITY.md](https://github.com/bonguynvan/tradecanvas/blob/main/SECURITY.md) instead of opening an issue.
1110
+
1111
+ If TradeCanvas saves you time, a star on GitHub helps other developers find it.
1112
+
1113
+ ## License
1114
+
1115
+ [MIT](https://github.com/bonguynvan/tradecanvas/blob/main/LICENSE)