acttrader-charts 1.3.0-beta.9 → 1.4.0-beta.1

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
@@ -58,12 +58,15 @@ chart.on('durationChange', ({ duration, timeframe }) => {
58
58
  ```ts
59
59
  const chart = new ChartEngine({
60
60
  container,
61
- dataLoader: async ({ start, end, interval }) => {
62
- const res = await fetch(`/api/bars?from=${start.getTime()}&to=${end.getTime()}&tf=${interval}`);
61
+ dataLoader: async ({ start, end, interval, priceSource }) => {
62
+ // `priceSource` ('bid' | 'ask' | 'ltp') is the candle source the chart is showing —
63
+ // pass it to your history API so the bars match (dealing feeds: LTP vs BID candles).
64
+ const res = await fetch(`/api/bars?from=${start.getTime()}&to=${end.getTime()}&tf=${interval}&source=${priceSource}`);
63
65
  return res.json(); // OHLCVBar[]
64
66
  },
65
67
  });
66
- // No manual loadData() needed — the engine calls dataLoader on start and on timeframe/duration changes.
68
+ // No manual loadData() needed — the engine calls dataLoader on start, on timeframe/duration
69
+ // changes, and (unless `reloadOnPriceSourceChange: false`) whenever the price source changes.
67
70
  ```
68
71
 
69
72
  If the first fetch returns fewer than `minInitialBars` (default `10`), the engine automatically widens the lookback window and calls `dataLoader` again — up to the `maxLookbackMs` ceiling (default 365 days). This keeps the chart useful on weekends, holidays, or for instruments that just listed. If retries still yield zero bars, the engine shows a **"No data available"** overlay (customise the text via `labels.chart.noData`).
@@ -152,6 +155,9 @@ const dealingChart = new ChartEngine({
152
155
  container,
153
156
  // "Show chart by" toggle: 'ltp' | 'ask' | 'bid' (candle close/high/low source)
154
157
  tickClosePriceSource: 'ltp',
158
+ // Header dropdown so the user can switch the source on the chart itself
159
+ // (rendered next to the timeframe dropdown; omit to hide):
160
+ priceSourceSelector: ['ltp', 'bid'],
155
161
  // Chart line checkboxes — each price line is independent:
156
162
  showAskLine: true, // Show AskLine
157
163
  showBidLine: true, // Show BidLine
@@ -161,8 +167,15 @@ const dealingChart = new ChartEngine({
161
167
  dealingChart.setShowAskLine(false); // hide the ask line
162
168
  dealingChart.setShowBidLine(true); // show the bid line
163
169
  dealingChart.setShowLtpPrice(true); // show the LTP line
170
+ // Switch the candle source programmatically (e.g. from a trade-settings page);
171
+ // the header dropdown label follows automatically:
172
+ dealingChart.setTickClosePriceSource('bid');
173
+ // A user pick from the dropdown emits `priceSourceChange` — persist it:
174
+ dealingChart.on('priceSourceChange', ({ source }) => saveTradeSetting(source));
164
175
  ```
165
176
 
177
+ **History follows the source.** Switching the source (dropdown pick or `setTickClosePriceSource()`) does not just change how live ticks extend the last candle — the engine re-runs your `dataLoader` with `params.priceSource` set to the new value and replaces the loaded bars, keeping the visible time window. Forward `priceSource` to your charting API (e.g. as a query parameter) so it returns LTP-built or BID-built candles accordingly; without it the API keeps serving the old source and the chart cannot change. Set `reloadOnPriceSourceChange: false` to opt out of the re-fetch.
178
+
166
179
  ### Compare symbols
167
180
 
168
181
  Overlay one or more comparison instruments on the main chart, normalized to
@@ -249,6 +262,12 @@ chart.setLevels(
249
262
  );
250
263
  ```
251
264
 
265
+ **Trailing stop:** a trade with a trail always has a working stop, so keep passing its price as `stopLossPrice` and set `stopLossTrailing: true`. The line renders as usual but its pill reads **TSL** instead of SL, and it is read-only on the chart — no drag handle, no × — because the trail is a pip distance edited from the host's own panel. The level's TP stays fully editable.
266
+
267
+ ```ts
268
+ { label: 'POS-2', price: 1.0850, side: 'buy', lots: 1, stopLossPrice: 1.0800, stopLossTrailing: true }
269
+ ```
270
+
252
271
  **Bracket orders via `ToClose`** — link a separate SL/TP pending order to a parent level:
253
272
 
254
273
  ```ts
@@ -312,6 +331,37 @@ chart.on('tradeLevelQtyChange', ({ label, type, newLots, previousLots }) => {
312
331
 
313
332
  When a trade level's entry, SL, or TP price lies outside the visible price range, a small pill (`▲ N` / `▼ N`) appears near the right edge of the chart showing the count of off-screen markers per direction. Clicking the pill smooth-scrolls the nearest off-viewport marker to the vertical center of the chart. This requires no configuration — it activates automatically whenever levels are present.
314
333
 
334
+ **Clustered price-axis tags and the trade list (TradingView-style):**
335
+
336
+ Every open position puts a price tag on the right-hand scale. Tags that would
337
+ overlap used to be pushed down the axis one after another, so a bulk fill of
338
+ fifteen positions became a column of tags covering the whole scale. With
339
+ `levelClusteringEnabled` (the default) tags closer than `clusterThresholdDistance`
340
+ now merge into **one tag at their average price with a count bubble** on its
341
+ left edge — buy-coloured when every member is a buy, sell-coloured when every
342
+ member is a sell, the neutral position colour for a mixed run.
343
+
344
+ Hovering a merged tag (tapping it on touch — a tap elsewhere dismisses it)
345
+ opens a trade list beside it, the way TradingView summarises a stack of
346
+ executions:
347
+
348
+ ```
349
+ ┃ (12) Sell
350
+ ┃ 130 @ 1.11848 avg price
351
+ ┃ TRADES
352
+ ┃ 10 @ 1.11811 Tue, Oct 13, 12:41
353
+ ┃ 10 @ 1.11828 Tue, Oct 13, 12:46
354
+ ┃ …
355
+ ```
356
+
357
+ The header counts the members and names the side (`8 Buy · 4 Sell` for a mixed
358
+ run); the second line is the summed `lots` at the lots-weighted average price
359
+ (plain mean, and no size, when a member has no `lots`); the rows are each
360
+ position's `lots @ price` and its `timestamp` in the chart's timezone (its
361
+ `pnlText` instead when there is no timestamp), oldest first, twelve rows then
362
+ `+N more`. The same list opens when hovering an on-chart cluster badge. With
363
+ `levelClusteringEnabled: false` the axis is drawn exactly as before.
364
+
315
365
  **Drag constraints (enforced live):**
316
366
 
317
367
  | Order side | Stop Loss | Take Profit |
@@ -333,13 +383,15 @@ When `enableTrading` is on and live BID/ASK data is streaming, hovering / activa
333
383
 
334
384
  ### Horizontal (time-axis) order-line dragging
335
385
 
336
- Opt-in via `features.orderLineTimeDrag` (off by default; enable it per broker from the host app — e.g. only for Hankotrade users). When enabled, any level flagged `timeDraggable: true` can have its **info-box badge** dragged left/right to re-anchor the order to a different candle. The **price line stays locked** — only the time anchor moves. Grab the badge for horizontal drag (`grab` / `grabbing` cursor); the price line itself still drags vertically as before.
386
+ Opt-in via `features.orderLineTimeDrag` (off by default; enable it per broker from the host app — e.g. only for Hankotrade users). When enabled, any level flagged `timeDraggable: true` — open positions **and pending orders** alike — can have its **info-box badge** dragged left/right to re-anchor the order to a different candle. During a horizontal drag the **price line stays locked** — only the time anchor moves. A fixed-price position's badge grabs horizontally at once (`grab` / `grabbing` cursor). A pending order (or entry-editable position) keeps its price drag: its badge shows a `move` cursor and the **first movement decides the axis** — sideways moves the time anchor, up/down moves the entry price exactly as before, and the full-width line still drags vertically.
337
387
 
338
388
  ```ts
339
389
  const chart = new ChartEngine({
340
390
  container,
341
391
  features: { orderLineTimeDrag: true }, // host enables this only for the gated broker
342
392
  orderLineDragSnap: true, // snap to nearest candle on release (default)
393
+ orderLineAnchorPersistence: true, // remember dropped positions in localStorage (default)
394
+ orderLineDefaultAnchor: 'center', // un-dragged badges start mid-chart (default: 'timestamp')
343
395
  });
344
396
 
345
397
  chart.setLevels(
@@ -354,13 +406,101 @@ chart.on('orderLineMoved', ({ label, fromTimestamp, toTimestamp, data }) => {
354
406
  ```
355
407
 
356
408
  - **Bounds:** the badge is clamped to the visible viewport — it can't be dragged past the left/right edge.
409
+ - **Pending orders:** flag them `timeDraggable: true` too. The pill follows the drag direction — a sideways pull re-anchors the order in time (price locked, `orderLineMoved` on release), a vertical pull moves the entry price and its SL/TP brackets as usual (`tradeLevelDrag` / `tradeLevelEdit`). The axis is fixed after about 6px of movement and does not change mid-drag. Touch follows the same rule, and a tap that never moves still opens the edit form.
357
410
  - **Snap:** controlled by `orderLineDragSnap` (default `true`); set `false` to keep the exact released time.
358
411
  - **Escape / touch-cancel:** reverts the badge to its starting candle without emitting `orderLineMoved`.
359
412
  - **Stays put after release:** the chart holds the dropped position across `setLevels` refreshes until you echo the new `timestamp` back (auto-released on match).
413
+ - **Survives reloads:** with `orderLineAnchorPersistence` (default `true`) the dropped candle time is saved in `localStorage` under `finchart.orderLineTimeAnchors`, keyed by the level's label. After a page reload the badge returns to that candle even if your `setLevels()` payload still carries the order's original `timestamp` — the persisted anchor wins until the badge is dragged again. Capped at the 500 most recently dragged labels; set `false` if you persist anchors server-side instead.
414
+ - **New orders at the center:** with `orderLineDefaultAnchor: 'center'` a `timeDraggable` level that has never been dragged ignores its `timestamp` and renders mid-chart — so a freshly filled market order arrives in the middle of the chart rather than pinned to the latest candle at the right edge. Levels that are not `timeDraggable` still honor `timestamp`. Default `'timestamp'` keeps the previous behavior.
360
415
  - A level **without** `timestamp` renders exactly as before (badge centered), so existing consumers are unaffected.
361
416
 
362
417
  ---
363
418
 
419
+ ### Trade action bar — `features.tradeActionBar`
420
+
421
+ With the flag on, the floating trade button opens a segmented bar at the clicked
422
+ price instead of the two-row Buy/Sell popup:
423
+
424
+ ```
425
+ Alert | Pending | SL | TP | TSL | ×
426
+ ```
427
+
428
+ - No price readout — the axis already shows the price at that point.
429
+ - **Alert** calls `onAddAlert(price)`. The chip is only rendered when that callback is set. The same callback also backs the **Alert** entry of the advanced header's ⋯ menu (`headerOverflowMenu`), which passes the current market price (live ask, else bid, else last close) so the host opens the same form.
430
+ - **Pending** opens a sub-menu just above the bar — an `Above · 1.17586` / `Below · …`
431
+ header, then the two orders that make sense at that price (`Buy Limit` / `Sell Stop`
432
+ below the market, `Sell Limit` / `Buy Stop` above), each with its `@ price`. Picking a
433
+ row creates the draft order exactly as before and closes both.
434
+ - **SL / TP / TSL** emit `bulkLevelsRequested` with `{ kind, price }` and close the
435
+ bar — the host opens its Bulk Levels dialog pre-focused on that kind. The chart
436
+ never calls a broker. The chips grey out, with a tooltip saying why, when the
437
+ symbol has no open positions or has buys and sells open at once — one stop or
438
+ target price cannot sit on the right side of the market for both directions.
439
+ - **×**, a click elsewhere, Escape, TFC off and `dismissAllUI()` all close it.
440
+
441
+ Chip labels and the × tooltip live under `labels.trade` (`actionAlert`, `actionPending`,
442
+ `actionSl`, `actionTp`, `actionTsl`, `actionCloseTitle`).
443
+
444
+ ### On-chart P/L pill — `features.pnlPill`
445
+
446
+ A floating summary of the open positions on the chart, for the trader who wants
447
+ the total without opening the positions panel:
448
+
449
+ ```
450
+ ⋮⋮ 3 POS +72.65 USD | ◎ ✕
451
+ ```
452
+
453
+ - **`3 POS`** — how many position levels are on the chart. Pending orders,
454
+ position-style entry orders (`entryPriceEditable`) and an unconfirmed draft
455
+ are not counted.
456
+ - **`+72.65 USD`** — the sum of the numeric `pnl` those levels carry, i.e. the
457
+ `pnlKey` column you pass to `setLevels`. The chart computes no money itself;
458
+ while no position has a `pnl` yet the pill shows `—`. Profit is drawn in the
459
+ buy colour, loss in the sell colour.
460
+ - **Click the body** (the grip, the count or the amount) to fan every position
461
+ badge out on the chart — clustered levels expand, and TFC is switched on if it
462
+ was off — with an accent ring on the pill while they are shown. Click again to
463
+ collapse.
464
+ - **◎** (the same target glyph as the Bulk Levels dialog header) emits
465
+ `bulkLevelsRequested` with `source: 'pill'` and a `null` price, so your Bulk Levels
466
+ dialog opens pre-scoped to every open position on the symbol. Tooltip:
467
+ "Set SL · TP · TSL on all N {symbol} positions". Greyed out while buys and sells are
468
+ both open ("Bulk levels need all N {symbol} positions in one direction").
469
+ - **✕** (amber) emits `pnlPillCloseAll` with every counted position. Your app
470
+ confirms and closes them; the chart never calls a broker.
471
+
472
+ The pill sits top-right of the plot, clear of the price axis. Drag it anywhere
473
+ inside the plot; double-click puts it back. It hides itself while the chart has
474
+ no positions and follows the chart theme. Every element sits on one shared row
475
+ height, and the grip and both buttons have fixed widths, so a long or negative
476
+ amount never shifts or squeezes them.
477
+
478
+ With the feature on, the header (advanced toolbar and default top bar) also gets a
479
+ **P/L** switch — wallet icon, `P/L`, the same 24px `rounded-sm` button tinted while the
480
+ pill is shown. It hides or shows the pill on the user's say-so, wins over the position
481
+ count, and emits `pnlPillToggle` so you can persist the choice; `pnlPill.visible` seeds
482
+ it and `setPnlPillVisible()` drives it from code.
483
+
484
+ ```ts
485
+ const chart = new ChartEngine({
486
+ container,
487
+ features: { pnlPill: true },
488
+ pnlPill: { currency: 'USD' }, // → "+72.65 USD"; or format: (pnl) => myMoney(pnl)
489
+ });
490
+
491
+ chart.setLevels(positions, 'TradeID', 'Price', 'position', 'pnl', 'pnlText');
492
+
493
+ chart.on('pnlPillCloseAll', async ({ count, pnl, data }) => {
494
+ if (!(await confirmDialog(`Close all ${count} positions?`))) return;
495
+ for (const row of data) closeTrade(row);
496
+ });
497
+ ```
498
+
499
+ Labels live under `labels.pnlPill`: `positionsAbbrev` (`'POS'`), `showPositionsTitle`,
500
+ `hidePositionsTitle`, `bulkLevelsTitle`, `closeAllTitle` — titles may
501
+ use `{symbol}` and `{count}`. The maths behind the pill is exported as
502
+ `summarisePositionLevels(levels, draftLabel?)` and `formatPnlPillValue(pnl, currency?)`.
503
+
364
504
  ## Default Configuration
365
505
 
366
506
  ### `ChartConfig`
@@ -375,9 +515,13 @@ chart.on('orderLineMoved', ({ label, fromTimestamp, toTimestamp, data }) => {
375
515
  | `hideHeader` | | `false` | Hide only the chart header (TopBar / AdvancedToolbar / CompactToolbar, per `headerLayout`). Bottom bar, left drawing tools, and on-canvas overlays remain on their own flags. Drive the chart from your own UI via `setTimeframe(tf)`, `setSeries(type)`, `addIndicatorByName(name)`, `removeIndicator(name)` |
376
516
  | `showDrawingTools` | | `true` | Show drawing toolbar and pencil button |
377
517
  | `showFullscreenButton` | | `true` | Show the fullscreen toggle button in the top bar. Set to `false` to hide it entirely. Mobile wrappers (Android / iOS) default this to `false` |
378
- | `timeframe` | | `"1D"` | Initial timeframe |
518
+ | `timeframe` | | `"1D"` | Initial timeframe. Values: `1m` `3m` `4m` `5m` `10m` `15m` `30m` `1h` `2h` `4h` `8h` `1D` `1W` `1M`; `3m` / `4m` / `10m` / `30m` are requested from `dataLoader` as `3min` / `4min` / `10min` / `30min`. If your API lacks them, point `aggregateFrom` at a finer interval it does serve, e.g. `{ '3m': '1m', '4m': '1m', '10m': '5m', '30m': '15m' }` — the chart merges the candles |
519
+ | `timeframes` | | classic set | Timeframes offered in the header, in order: the advanced row's pills, the classic dropdown, and the rest of the reference header's ⌄ menu after its six fixed pills. Omit to keep `1m 5m 15m 1h 4h 1D 1W` (row) / `… 30m 2h 8h 1M` (dropdown, ⌄), so the newer minute timeframes only appear for hosts that list them |
379
520
  | `duration` | | — | Initial active duration button |
380
521
  | `symbol` | | — | Symbol name shown in the top bar |
522
+ | `features` | | `{}` | Opt-in feature gates. See [Feature flags](#feature-flags) |
523
+ | `instrument` | | — | Contract specs for `symbol` — pip size, contract size, money conversion. See [`InstrumentSpec`](#instrumentspec) |
524
+ | `account` | | — | Account equity and per-trade risk used to size the position tools. See [`AccountSpec`](#accountspec) |
381
525
  | `isins` | | — | Symbol list for the picker modal |
382
526
  | `onIsinSelect` | | — | Called when user picks a symbol from the picker modal |
383
527
  | `padding` | | `{top:8,right:0,bottom:0,left:0}` | Canvas padding (px) |
@@ -394,7 +538,7 @@ chart.on('orderLineMoved', ({ label, fromTimestamp, toTimestamp, data }) => {
394
538
  | `momentumMaxVelocity` | | `6.0` | Max launch velocity (px/ms) — caps hard-flick speed |
395
539
  | `targetCandleWidth` | | `10` | Target px width per candle for auto-calculating initial bar count |
396
540
  | `durationTimeframeMap` | | *(see below)* | Override duration → timeframe pairings |
397
- | `dataLoader` | | — | `(params) => Promise<OHLCVBar[]>` auto-called on load / change |
541
+ | `dataLoader` | | — | `({ start, end, interval, priceSource }) => Promise<OHLCVBar[]>` auto-called on load, timeframe/duration change, and price-source change. `priceSource` is the candle source to fetch (`'bid'`, `'ask'` or `'ltp'`) |
398
542
  | `compareDataLoader` | | — | `({ symbol, start, end, interval }) => Promise<OHLCVBar[]>` — fetches bars for a compare symbol. Set this to enable the library-owned Compare flow. |
399
543
  | `initialCompares` | | — | Symbols to auto-add as compares once the initial primary range is loaded |
400
544
  | `maxCompares` | | `8` | Maximum concurrent compare symbols. Adding beyond emits `compareError` |
@@ -403,6 +547,8 @@ chart.on('orderLineMoved', ({ label, fromTimestamp, toTimestamp, data }) => {
403
547
  | `labels` | | `DEFAULT_LABELS` | Deep-partial string overrides for i18n/translation |
404
548
  | `tickClosePriceSource` | | `"bid"` | Which price drives live tick close/high/low: `"bid"`, `"ask"`, or `"ltp"` (build candles from the last traded price — exchange/dealing feeds; ticks without a valid LTP fall back to the bid) |
405
549
  | `showLtpPrice` | | unset | Show the LTP marker (dashed price line + axis tag). Unset: shown only in `"ltp"` mode. `true`: always shown when the feed supplies an LTP. `false`: hidden even in `"ltp"` mode (candles still build from the LTP). Toggle at runtime with `chart.setShowLtpPrice(show)` |
550
+ | `priceSourceSelector` | | unset | Show a price-source dropdown in the chart header listing the given sources, e.g. `["ltp", "bid"]` (dealing feeds). A user pick switches the candle source, re-fetches history via `dataLoader` (see `reloadOnPriceSourceChange`) and emits `priceSourceChange`; sync it programmatically with `chart.setTickClosePriceSource(source)`. Hidden when unset/empty. Default header layout only |
551
+ | `reloadOnPriceSourceChange` | | `true` | Re-run `dataLoader` with the new `params.priceSource` whenever the candle price source changes, so historical candles are rebuilt from the selected price (LTP vs BID) and not only the live one. The visible time window is preserved. Set `false` to keep only live ticks following the new source |
406
552
  | `showBidAskLines` | | `false` | **Deprecated** — show both bid and ask as dashed lines during a live stream. Prefer the per-line checks `showAskLine` / `showBidLine`, which override it when set |
407
553
  | `showAskLine` | | unset | Show the Ask price line (dashed line + axis tag) independently. Unset: legacy `showBidAskLines` behavior. Toggle at runtime with `chart.setShowAskLine(show)` |
408
554
  | `showBidLine` | | unset | Show the Bid price line (dashed line + axis tag) independently. Unset: legacy `showBidAskLines` behavior. Toggle at runtime with `chart.setShowBidLine(show)` |
@@ -412,31 +558,150 @@ chart.on('orderLineMoved', ({ label, fromTimestamp, toTimestamp, data }) => {
412
558
  | `showPriceAxisCountdown` | | `false` | Show candle countdown timer on the right price axis, just below the live price tag. Honours `candleCountdownTimeframes`. Toggleable from the Settings dialog (Appearance tab). |
413
559
  | `maxSubPanes` | | `3` | Max simultaneous oscillator sub-panes |
414
560
  | `tradeDisplayFilter` | | `"all"` | Which TFC levels are visible: `"all"` · `"positions"` · `"orders"` · `"none"` |
561
+ | `pnlPill` | | — | `{ currency?, format?, visible? }` for the on-chart P/L pill — currency code appended to the amount, or your own formatter. Only read when `features.pnlPill` is on |
415
562
  | `positionRenderStyle` | | auto | Force position render style: `"line"` or `"dot"` |
416
563
  | `hideLevelConfirmCancel` | | `false` | Hide on-canvas ✓/✗ confirm-cancel buttons for TFC level edits |
417
564
  | `deselectActiveOnOutsideClick` | | `false` | When `true`, clicking/tapping anywhere outside a selected trade level dismisses it (reverting any pending edits, mirroring ✗ Cancel). Default `false` keeps the level active so incidental clicks — price-axis resize, taps outside the QTY input — don't drop an in-progress edit. The level can still be dismissed via ✓/✗, tapping the level again, or `setLevels()` removing it |
418
565
  | `showTradeLevelsAlways` | | `false` | Always render SL/TP bracket lines + price pills, even when the parent level is not hovered or selected. The close (×) button stays hover-only so the chart isn't cluttered. Toggleable from the Settings dialog (Trading tab). Persisted in `localStorage`. |
566
+ | `revealNewBrackets` | | `false` | When a level gains a **new** SL/TP — placed from the host's order panel, so it arrives via `setLevels()`, `updateLevelBracket()` or `updateDraftOrderBracket()` — whose price sits outside the visible price range, widen (compress) the price axis so the new line comes into view together with the candles already on screen. Animated, and the trader can drag or reset the axis afterwards as usual. A bracket dragged on the chart is visible by construction and never triggers it. Inert in compare (percent) mode |
419
567
  | `tradeLevelButtonScale` | | `1` | Multiplier for trade-level Confirm/Cancel/Edit/Close button radii and gaps. Scales visuals **and** hit/drag areas together — raise it on touch devices for larger tap targets. Clamped to `[1, 3]`. Also settable at runtime via `chart.setTradeLevelButtonScale(scale)` |
568
+ | `tradeLevelBadgeScale` | | `1` | Shrinks the on-chart position / order tag — font, padding, grip, ✎ × buttons and their hit areas together. `0.6` is about half the default area. Clamped `[0.5, 1]` |
569
+ | `tradeLevelBadgeAnchor` | | `"auto"` | `"left"` homes the tag at the plot's left edge like an axis label, whatever the open price or time anchor, so it never covers candles until the trader drags it. With `features.orderLineTimeDrag` the tag stays draggable along the time axis and the drop is remembered as before |
420
570
  | `tfcEnabled` | | `true` | Enable the TFC toggle button in the top bar. When `false`, TFC is completely disabled — the toggle button is hidden and all trade levels, draft orders, and the floating trade button are suppressed |
421
- | `features.orderLineTimeDrag` | | `false` | Enable **horizontal (time-axis) order-line dragging**. A level with `timeDraggable: true` can have its info-box badge dragged left/right to re-anchor the order to a different candle — **price stays locked**. Emits `orderLineMoved` on release. Off by default; intended to be enabled per broker (e.g. Hankotrade) by the host app |
571
+ | `crosshairEnabled` | | `true` | Draw the mouse crosshair. `false` hides it **and** the floating "place order at this price" button that rides on its horizontal line, ignores mirrored `setCrosshair()` calls and keeps the mobile long-press crosshair from arming. Trade levels, drawings and TFC are unaffected. Runtime: `chart.setCrosshairEnabled(enabled)` |
572
+ | `enableCrossHairHeader` | | `false` | Crosshair on/off switch in the header (advanced toolbar, default top bar, the compact per-pane strip and the mobile header): the reference `rounded-sm` button. The crosshair is on by default, so the icon starts tinted; a click hides the crosshair (and the trade button riding on it) and drops the icon to its plain state, the next click brings both back. Calls `setCrosshairEnabled()` and emits `crosshairToggle` so the host can persist the choice — see [Header crosshair switch](#header-crosshair-switch--enablecrosshairheader) |
573
+ | `enableCrosshairToggle` | | `false` | **Deprecated** — alias of `enableCrossHairHeader`; either flag renders the switch |
574
+ | `headerOverflowMenu` | | `false` | Advanced header only: the reference Hanko header. A 32px bar with six lowercase timeframe pills (`1m 5m 15m 1h 4h 1d`) and a ⌄ for the rest, then crosshair · P/L · Layout (grid icon) · ⋯ · fullscreen at 24px. Draw, Chart type, Indicators, Compare, Snapshot and Chart settings fold into the ⋯ menu; each keeps its behaviour. With `onAddAlert` set the menu also offers **Alert** (own group, before Snapshot) at the current market price |
575
+ | `features.orderLineTimeDrag` | | `false` | Enable **horizontal (time-axis) order-line dragging**. A level with `timeDraggable: true` (position or pending order) can have its info-box badge dragged left/right to re-anchor the order to a different candle — **price stays locked** while dragging sideways. Pending orders keep their vertical price drag: the badge's first movement picks the axis. Emits `orderLineMoved` on release. Off by default; intended to be enabled per broker (e.g. Hankotrade) by the host app |
422
576
  | `orderLineDragSnap` | | `true` | When horizontal dragging is enabled, snap the badge to the nearest candle on release. Set `false` to keep the exact released time |
423
- | `levelClusteringEnabled` | | `true` | Enable trade-level fan-out clustering; overlapping levels group into expandable badges |
424
- | `clusterThresholdDistance` | | `20` | Pixel proximity threshold for clustering (only when `levelClusteringEnabled` is `true`) |
577
+ | `orderLineAnchorPersistence` | | `true` | When horizontal dragging is enabled, remember where each badge was dropped in `localStorage` (key `finchart.orderLineTimeAnchors`, keyed by level label) so it comes back to the same candle after a reload. A persisted anchor overrides the level's `timestamp` until the badge is dragged again. Set `false` to persist anchors yourself |
578
+ | `orderLineDefaultAnchor` | | `'timestamp'` | Where an un-dragged `timeDraggable` badge sits: `'timestamp'` = over the candle at the level's `timestamp`; `'center'` = the chart's horizontal center (ignores `timestamp`), so a new market order lands mid-chart. Non-draggable levels always honor `timestamp` |
579
+ | `levelClusteringEnabled` | | `true` | Enable trade-level clustering: overlapping levels group into expandable badges on the chart, and overlapping position tags on the price axis merge into one tag with a count whose hover shows the trade list |
580
+ | `clusterThresholdDistance` | | `20` | Pixel proximity threshold for clustering, on the chart and on the price axis (only when `levelClusteringEnabled` is `true`) |
425
581
  | `hideSymbolAndTick` | | `false` | Hide the symbol name and tick-activity (streaming) dot in the top-left overlay. Does **not** affect the OHLC(V) strip — use `hideOHLCV` for that |
426
582
  | `hideOHLCV` | | `false` | Hide the OHLC(V) data strip (`O: H: L: C: V:`) in the top-left overlay. Independent of `hideSymbolAndTick` — set both to `true` to hide the entire overlay |
427
583
  | `showBottomBar` | | `false` | Show the bottom duration-selector bar |
584
+ | `features.enableScaleControls` | | `false` | Bottom-bar **Go to date**, **timezone** and **%** / **log** / **auto** cluster, left of the duration buttons. Needs `showBottomBar: true`. Off by default — see [Bottom Bar & Price Scale](#bottom-bar--price-scale) |
585
+ | `features.enableSidePanels` | | `false` | Right-hand docked **Data Window** / **Objects** panel (232px out of the plot). Off by default; toggle at runtime with `setSidePanelVisible()` — see [Side Panels](#side-panels) |
428
586
  | `hideQtyButton` | | `false` | Hide the floating Qty input overlay on draft orders |
429
587
  | `showQuantityField` | | `false` | Render an editable QTY pill at the left of the draft order info box. Clicking the pill opens a flyout input to edit the quantity before submitting |
430
588
  | `quantityFieldConfig` | | — | Constraints for the draft order QTY field (only relevant when `showQuantityField` is `true`). Object: `{ minLots?: number, maxLots?: number }`. `minLots` also sets the initial quantity and the step value for the flyout input (default: `1`). `maxLots` caps the input (default: `100`) |
431
589
  | `tradesThresholdForHorizontalLine` | | `2` | Level count above which render auto-switches to `"dot"` mode |
432
590
  | `timezone` | | `"UTC"` | IANA timezone string for time-axis and crosshair labels. `"UTC"` (default), `"local"` (browser/device timezone), or any IANA string (`"America/New_York"`, `"Europe/London"`, etc.) |
433
- | `canvasColors` | | — | Per-theme canvas background color overrides (persisted from Settings dialog) |
591
+ | `canvasColors` | | — | Per-theme colour overrides for the **canvas only** (persisted from the Settings dialog; runtime: `chart.setCanvasColors()`). The surface picks — `background`, `grid`, `axisText`, `axisBorder`, `crosshair` — repaint the chart canvas and leave the chart chrome (top/bottom/left bars, dialogs, popovers) on the theme from `themeOverrides`. Series picks (`candleUp`/`candleDown`/`wickUp`/`wickDown`/`borderUp`/`borderDown`/`volumeUp`/`volumeDown`) apply everywhere, so legends and indicator pills keep tracking them |
434
592
  | `aggregateFrom` | | — | Fetch finer-grained data and aggregate client-side per timeframe |
435
593
  | `onOrderSubmit` | | — | Called when user submits a trade via the floating button |
436
594
  | `onLevelEdit` | | — | Called when user confirms a TFC level edit |
437
595
  | `onLotsChange` | | — | Called when user changes qty on a draft order |
438
596
  | `onLevelDragEnd` | | — | *(deprecated — use `onLevelEdit`)* |
439
597
 
598
+ ### `InstrumentSpec`
599
+
600
+ The chart reads prices, never contract specs — so a tool that reports a distance
601
+ in **pips**, or converts one to money, has to be told how. Pass `instrument` at
602
+ construction and swap it with `setInstrument()` whenever the symbol changes.
603
+
604
+ ```ts
605
+ const chart = new ChartEngine({
606
+ container,
607
+ symbol: 'EURUSD',
608
+ instrument: {
609
+ pipSize: 0.0001, // 0.01 for JPY crosses
610
+ contractSize: 100_000, // units per lot
611
+ valuePerPoint: 1, // account-currency value of one price unit per unit
612
+ currencySymbol: '$',
613
+ },
614
+ });
615
+
616
+ chart.setSymbol('USDJPY').setInstrument({ pipSize: 0.01, contractSize: 100_000 });
617
+ ```
618
+
619
+ | Field | Default | Description |
620
+ |---|---|---|
621
+ | `pipSize` | inferred | Price distance counted as one pip |
622
+ | `contractSize` | `1` | Units per lot (`100` for XAUUSD, `100000` for most FX pairs) |
623
+ | `valuePerPoint` | `1` | Account-currency value of one price unit per contract unit |
624
+ | `currencySymbol` | `'$'` | Prefixed to money figures |
625
+
626
+ **Every field is optional and the whole block can be omitted** — tools fall back
627
+ to price-only readouts, so existing integrations keep working untouched.
628
+
629
+ When `pipSize` is absent it is inferred from how many decimals the feed quotes:
630
+ five-decimal (`1.08531`) and three-decimal (`151.234`) feeds carry fractional
631
+ pips, so the pip is the second-to-last digit; two- and four-decimal feeds quote
632
+ whole pips. **That convention is wrong for metals, indices and crypto** — pass
633
+ `pipSize` explicitly if pips matter.
634
+
635
+ The same fallbacks are exported for hosts that want to compute alongside the
636
+ chart:
637
+
638
+ ```ts
639
+ import { resolveInstrument, inferPipSize, toPips, toMoney } from 'acttrader-charts';
640
+ ```
641
+
642
+ > Per-position values still travel on the individual `TradeLevel`
643
+ > (`contractSize` / `valuePerPoint`). `InstrumentSpec` is the chart-wide default
644
+ > for tools that aren't attached to a position.
645
+
646
+ ### Feature flags
647
+
648
+ Newer tools ship behind `ChartConfig.features` so each host opts in. **Every flag
649
+ defaults to `false`** — a chart that sets none behaves exactly as it did before
650
+ the flag existed, including its toolbar contents.
651
+
652
+ ```ts
653
+ const chart = new ChartEngine({
654
+ container,
655
+ features: { enableForecasting: true },
656
+ });
657
+ ```
658
+
659
+ | Flag | Default | What it changes |
660
+ |---|---|---|
661
+ | `enableForecasting` | `false` | The reworked drawing tools, as one switch — see below |
662
+ | `orderLineTimeDrag` | `false` | Horizontal (time-axis) order-line dragging for positions and pending orders — see [Horizontal order-line dragging](#horizontal-time-axis-order-line-dragging) |
663
+ | `pnlPill` | `false` | Floating on-chart P/L pill — count and summed P/L of the positions on the chart — see [On-chart P/L pill](#on-chart-pl-pill--featurespnlpill) |
664
+ | `tradeActionBar` | `false` | The trade button opens a segmented `Alert · Pending · SL · TP · TSL · ×` bar at the clicked price instead of the two-row Buy/Sell popup — see [Trade action bar](#trade-action-bar--featurestradeactionbar) |
665
+
666
+ `enableForecasting` turns on three things together:
667
+
668
+ - **Long Position** / **Short Position** in a new **Forecasting** group in the
669
+ drawing toolbar. With the flag off the group is not rendered at all.
670
+ - **Brush** and **Highlighter** draw freehand — press, drag, release. Off, they
671
+ keep the click-per-point gesture ended by a double-click.
672
+ - **Ruler** reports percent, pips, calendar duration and volume. Off, it reports
673
+ the bar count and raw price delta as before.
674
+
675
+ They share one flag because they ship and roll back together: a broker either has
676
+ the reworked drawing tools or it doesn't.
677
+
678
+ Related config, independent of the flag: the position tools show quantity and
679
+ money only when [`account`](#accountspec) is supplied, and pips on both the
680
+ position tools and the ruler come from [`instrument`](#instrumentspec) — without
681
+ it, pip size is inferred from the feed's decimal count.
682
+
683
+ ### `AccountSpec`
684
+
685
+ What the **Long / Short position** tools size themselves against.
686
+
687
+ TradingView asks the user to type these because it has no broker connection. We
688
+ do have one — so pass real equity and keep it current.
689
+
690
+ ```ts
691
+ chart.setAccount({ size: 10_000, riskPercent: 1 });
692
+ ```
693
+
694
+ | Field | Default | Description |
695
+ |---|---|---|
696
+ | `size` | — | Account equity in the account currency |
697
+ | `riskPercent` | `1` | Percent of the account risked per trade |
698
+
699
+ Omit the block and the position tools still draw — price, percent, pips and
700
+ risk/reward all render; only the quantity and money amounts are left out.
701
+
702
+ > A sketch drawn against a stale balance reports the wrong quantity rather than
703
+ > failing visibly, so push `setAccount()` whenever equity moves.
704
+
440
705
  ### `OHLCVBar`
441
706
 
442
707
  | Field | Required | Type | Description |
@@ -477,7 +742,7 @@ import { DEFAULT_UI_CONFIG } from 'acttrader-charts';
477
742
 
478
743
  | Component key | Configurable properties |
479
744
  |---|---|
480
- | `drawingToolbar` | `iconBtnSize`, `iconFontSize`, `iconFontFamily`, `flyoutLabelFontSize`, `flyoutLabelFontFamily`, `shortcutFontSize`, `soonBadgeFontSize`, `flyoutHeadingFontSize`, `flyoutHeadingLetterSpacing`, `scrollBtnHeight`, `scrollBtnFontSize`, `barPadding`, `btnGap` |
745
+ | `drawingToolbar` | `iconBtnSize`, `iconFontSize`, `iconFontFamily`, `flyoutLabelFontSize`, `flyoutLabelFontFamily`, `shortcutFontSize`, `soonBadgeFontSize`, `flyoutHeadingFontSize`, `flyoutHeadingLetterSpacing`, `scrollBtnHeight`, `scrollBtnFontSize`, `barPadding`, `btnGap`, `modernIcons`, `actionsButtonIcon` (`'default'` \| `'lock'` — lock glyph on the Actions button, for hosts that relabel Lock All as "Save Charts") |
481
746
  | `topBar` | `height`, `dropBtnFontSize`, `dropBtnFontFamily`, `drawBtnSize`, `drawBtnIconFontSize`, `iconBtnSize`, `mobileIconBtnSize`, `mobileDrawBtnIconSize`, `flyoutRowFontSize`, `flyoutRowFontFamily`, `flyoutCategoryFontSize`, `flyoutCategoryLetterSpacing`, `flyoutCheckFontSize`, `streamDotSize` |
482
747
  | `bottomBar` | `height`, `btnFontSize`, `btnFontFamily` |
483
748
  | `priceAxis` | `fontSize`, `fontFamily` |
@@ -555,6 +820,11 @@ new ChartEngine({
555
820
  | `topBar.series` | `area` | `'Area'` | |
556
821
  | `topBar` | `indicatorsBtn` | `'Indicators'` | Indicators button (no active) |
557
822
  | `topBar` | `indicatorsBtnActive` | `'Indicators ({count})'` | `{count}` replaced at runtime |
823
+ | `topBar` | `disableCrosshairTitle` | `'Disable crosshair'` | Header crosshair switch tooltip while on (`enableCrossHairHeader`) |
824
+ | `topBar` | `enableCrosshairTitle` | `'Enable crosshair'` | Header crosshair switch tooltip while off |
825
+ | `topBar` | `pnlPillBtn` | `'P/L'` | Header P/L pill switch label (`features.pnlPill`) |
826
+ | `topBar` | `hidePnlPillTitle` | `'Hide P/L pill for {symbol}'` | P/L switch tooltip while the pill is shown |
827
+ | `topBar` | `showPnlPillTitle` | `'Show P/L pill for {symbol}'` | P/L switch tooltip while the pill is hidden |
558
828
  | `topBar` | `toggleDrawingTitle` | `'Toggle Drawing Tools'` | Toolbar toggle tooltip |
559
829
  | `topBar` | `toggleFullscreenTitle` | `'Toggle Fullscreen'` | Fullscreen button tooltip |
560
830
  | `topBar` | `exitFullscreenTitle` | `'Exit Fullscreen'` | |
@@ -597,6 +867,16 @@ new ChartEngine({
597
867
  | `trade` | `market` | `'Market'` | |
598
868
  | `trade` | `qty` | `'Qty'` | Draft order qty input label |
599
869
  | `trade` | `placeOrderTitle` | `'Place order at this price'` | Trade button tooltip |
870
+ | `trade` | `actionAlert` … `actionTsl` | `'Alert'`, `'Pending'`, `'SL'`, `'TP'`, `'TSL'` | Trade action bar chips (`features.tradeActionBar`) |
871
+ | `trade` | `actionCloseTitle` | `'Close'` | Trade action bar × tooltip |
872
+ | `trade` | `directionAbove`, `directionBelow` | `'Above'`, `'Below'` | Pending sub-menu header — side of the market the clicked price is on |
873
+ | `trade` | `actionBulkNoPositionsTitle`, `actionBulkMixedTitle` | `'No open {symbol} positions'`, `'Bulk levels need all {symbol} positions in one direction'` | SL / TP / TSL chips greyed out — why |
874
+ | `pnlPill` | `positionsAbbrev` | `'POS'` | On-chart P/L pill — word after the count (`3 POS`), shown uppercase |
875
+ | `pnlPill` | `showPositionsTitle` | `'Show positions on chart · drag handle to move · double-click to reset'` | Pill tooltip while collapsed — a body click fans the positions out |
876
+ | `pnlPill` | `hidePositionsTitle` | `'Hide positions on chart · drag handle to move · double-click to reset'` | Pill tooltip while fanned out |
877
+ | `pnlPill` | `bulkLevelsTitle` | `'Set SL · TP · TSL on all {count} {symbol} positions'` | ◎ tooltip — opens the host's Bulk Levels dialog |
878
+ | `pnlPill` | `bulkLevelsMixedTitle` | `'Bulk levels need all {count} {symbol} positions in one direction'` | ◎ tooltip while greyed out for mixed sides |
879
+ | `pnlPill` | `closeAllTitle` | `'Close all {symbol} positions'` | Amber ✕ tooltip; `{symbol}` and `{count}` are filled in |
600
880
  | `dialogs.settings` | `title` | `'Chart Settings'` | Dialog title |
601
881
  | `dialogs.settings` | `tfcSection` | `'Trade from Charts'` | Section heading |
602
882
  | `dialogs.settings` | `showLabel` | `'Show'` | Radio group label |
@@ -637,8 +917,8 @@ chart.setTheme('light');
637
917
  |---|---|---|
638
918
  | `background` | `string` | Canvas background color |
639
919
  | `grid` | `string` | Grid line color |
640
- | `axisText` | `string` | Axis tick label color |
641
- | `axisBorder` | `string` | Axis border / separator color |
920
+ | `axisText` | `string` | Axis tick label color. Also the default label colour for the chart chrome (dialog text, toolbar labels) — set it via `themeOverrides` to restyle both, or via the Settings dialog to restyle the canvas axis alone |
921
+ | `axisBorder` | `string` | Axis border / separator color. Also the default border colour for the chart chrome (dialog frames, toolbar dividers) — same split as `axisText` |
642
922
  | `crosshair` | `string` | Crosshair line color |
643
923
  | `tooltip` | `{background, text, border}` | Floating label colors |
644
924
  | `candle` | `{up, down, wickUp, wickDown}` | Candlestick colors |
@@ -673,7 +953,7 @@ chart.resetData(): this
673
953
 
674
954
  **Symbol switch pattern:**
675
955
  ```ts
676
- chart.setSymbol('GBPUSD').resetData();
956
+ chart.setSymbol('GBPUSD').setInstrument({ pipSize: 0.0001 }).resetData();
677
957
  // … fetch new bars …
678
958
  chart.loadData(newBars);
679
959
  ```
@@ -682,12 +962,17 @@ chart.loadData(newBars);
682
962
 
683
963
  ```ts
684
964
  chart.setSeries(series: SeriesType): this
965
+ chart.setInstrument(spec: InstrumentSpec | undefined): this // contract specs for pips / money readouts
966
+ chart.getInstrument(): ResolvedInstrument // specs with fallbacks applied
967
+ chart.setAccount(account: AccountSpec | undefined): this // equity + risk for the position tools
968
+ chart.getAccount(): AccountSpec | undefined
685
969
  chart.setTheme('dark' | 'light'): this
686
970
  chart.setTimeframe(tf: Timeframe): this // change timeframe and reload data
687
971
  chart.setDuration(d: Duration, timeframe?: Timeframe): this // select a duration; pairs the timeframe and reloads
688
972
  chart.getDuration(): Duration | null // currently selected duration
689
973
  chart.setBracketLabelMode(mode, currencySymbol?): this // SL/TP pills: 'price' (default) or 'amount'
690
- chart.setThemeOverrides(overrides: ThemeOverrides): this // update per-theme color overrides at runtime
974
+ chart.setThemeOverrides(overrides: ThemeOverrides): this // update per-theme color overrides at runtime — canvas AND chrome
975
+ chart.setCanvasColors(colors: ChartConfig['canvasColors'] | null): this // recolour the canvas only at runtime (same picks as the Settings dialog); null clears
691
976
  chart.setTimezone(tz: string): this // change display timezone at runtime
692
977
  chart.setVolume(show: boolean): this
693
978
  ```
@@ -725,6 +1010,7 @@ chart.cancelCurrentEdit(): this // cancel the active draft order or any in-pro
725
1010
  chart.addLevelBracket(label: string, bracketType: 'sl' | 'tp'): this // auto-place a SL or TP bracket at a default offset; emits tradeLevelBracketActivated with the computed price
726
1011
  chart.setDraftBracketPnl(bracketType: 'sl' | 'tp', pnlText: string | null): this // set estimated P&L text on the active bracket host — the draft order while drafting, or the currently selected existing pending order / position while modifying; pass null to clear
727
1012
  chart.setTfcActive(enabled: boolean): this // toggle TFC on/off at runtime; hides/shows all trade levels, draft orders, and floating trade button; fires tfcToggle event
1013
+ chart.setPnlPillVisible(visible: boolean): this // show/hide the on-chart P/L pill (features.pnlPill) — what the header's P/L switch does; emits pnlPillToggle
728
1014
  ```
729
1015
 
730
1016
  > **Staging semantics for `updateLevelMainPrice` / `updateLevelBracket`.** Calls to these methods register the change in the chart's pending-edit buffer (the same buffer chart-initiated drags use), so the edit stays visible even when the host app keeps pushing fresh server state via `setLevels` (e.g. per-tick PnL refreshes). When the server echoes back the new price in a later `setLevels` call, the staged edit is auto-released (mobile, i.e. `hideLevelConfirmCancel: true`). If a panel closes without submitting, call `cancelLevelEdit(label)` or `cancelCurrentEdit()` to drop the staged edit — otherwise it will keep overriding server state on the chart.
@@ -733,8 +1019,39 @@ chart.setTfcActive(enabled: boolean): this // toggle TFC on/off at runtime; hi
733
1019
 
734
1020
  ```ts
735
1021
  chart.setOrderLots(lots: number): void // update default qty at runtime
1022
+ chart.setCrosshairEnabled(enabled: boolean): this // off hides the crosshair AND this button — it rides on the crosshair line, so it has no place once the line is gone
1023
+ ```
1024
+
1025
+ The button follows the crosshair's horizontal line, so it is only ever shown while the
1026
+ crosshair is (`crosshairEnabled`, default `true`). Hosts with a crosshair on/off control
1027
+ should call `setCrosshairEnabled()` rather than painting the crosshair transparent — the
1028
+ latter leaves the button riding an invisible line.
1029
+
1030
+ ### Header crosshair switch — `enableCrossHairHeader`
1031
+
1032
+ ```ts
1033
+ const chart = new ChartEngine({
1034
+ container,
1035
+ enableCrossHairHeader: true, // crosshair icon in the header; the crosshair itself starts on
1036
+ });
1037
+ chart.on('crosshairToggle', ({ enabled }) => saveUserPref('crosshair', enabled));
736
1038
  ```
737
1039
 
1040
+ With the flag on, a crosshair icon sits in the header's right cluster (advanced toolbar and
1041
+ default top bar) or at the end of the compact per-pane strip (`headerLayout: 'compact'`). The chart crosshair is shown as usual on load and the icon is tinted. Clicking
1042
+ the icon hides the crosshair — and the floating trade button that rides on it — and the icon
1043
+ drops to its plain state; clicking again brings both back. Each click goes through
1044
+ `setCrosshairEnabled()` and emits `crosshairToggle`, so a host can persist the choice and seed
1045
+ it on the next load with `crosshairEnabled: false`. `enableCrosshairToggle` is the deprecated
1046
+ name of the same flag and still works. Native wrappers get the same switch via their
1047
+ `enableCrossHairHeader` init option, the `onCrosshairToggle` callback and `setCrosshairEnabled()`.
1048
+
1049
+ ### Native UI catalog (webview bridge only)
1050
+
1051
+ The webview bridge used by the Android and iOS wrappers posts a **`catalog`** event right after every `init` command, and again on the **`getCatalog`** command (which also works before `init`). It lists everything a native app needs to build its own header, drawing-tools sheet, indicators list and chart-settings screen: timeframes, chart types, cursors, drawing tool groups (with point counts and style fields), drawing-toolbar options, indicators (with pane and editable settings fields), the Chart Settings dialog (tabs → sections → items with types, options and defaults), canvas colour keys, price sources and limits. Every entry carries `available` (`true` = works in this version, `false` = planned). `catalogVersion` is the library version, stamped at build time.
1052
+
1053
+ Source: `src/core/mobileCatalog.ts`. `src/__tests__/mobileCatalog.test.ts` fails the build if an `available: true` id does not exist in the engine, or an engine tool / indicator is missing from the catalog — update the catalog together with any new chart type, tool or indicator. The web `ChartEngine` API is unchanged.
1054
+
738
1055
  ### Viewport
739
1056
 
740
1057
  ```ts
@@ -893,9 +1210,11 @@ Sub-pane heights are user-resizable by dragging the separator between panes.
893
1210
 
894
1211
  ### SL/TP bracket labels — price or amount
895
1212
 
896
- By default an SL/TP pill reads `SL 4159.00`. With `bracketLabelMode: 'amount'`
897
- it reads `SL -$290.80` — the money the position gains or loses if that bracket
898
- is hit, currency symbol in front.
1213
+ By default an SL/TP pill reads `SL @4159.00` — the currency sign is never shown on
1214
+ a price. With `bracketLabelMode: 'amount'` it reads `SL -$290.80` — the money the
1215
+ position gains or loses if that bracket is hit, currency symbol in front and a
1216
+ minus only on a loss. `'priceAndAmount'` shows `SL @4159.00` at rest and
1217
+ `SL @4159.00 -$290.80` while the bracket is dragged.
899
1218
 
900
1219
  The chart has no access to contract specs or the account currency, so each level
901
1220
  supplies what the maths needs:
@@ -910,7 +1229,7 @@ chart.setLevels([{
910
1229
  valuePerPoint: 1, // account-currency value of one price unit
911
1230
  currencySymbol: '$', // optional per-level override
912
1231
  }], 'label', 'price', 'position');
913
- // pills render: SL -$290.80 TP +$189.20
1232
+ // pills render: SL -$290.80 TP $189.20
914
1233
  ```
915
1234
 
916
1235
  ```
@@ -954,10 +1273,78 @@ In a **per-drawing** style (`SerializedDrawing.style.levels`), a level may also
954
1273
 
955
1274
  `rectangle` · `rotatedRectangle` · `ellipse` · `triangle` · `circle` · `arc` · `polyline` · `path` · `brush` · `highlighter`
956
1275
 
1276
+ **`brush` and `highlighter` draw freehand** when `features.enableForecasting` is on
1277
+ (see [Feature flags](#feature-flags)): press, drag, release — the pointer
1278
+ path is sampled continuously and the finished stroke is thinned to the points
1279
+ that carry its shape. (`polyline` and `path` remain click-per-point, ended with a
1280
+ double-click.)
1281
+
957
1282
  ### Measurements & Annotations
958
1283
 
959
1284
  `priceRange` · `dateRange` · `datePriceRange` · `ruler` · `priceLabel` · `priceNote` · `priceProjection` · `projection` · `arrowUp` · `arrowDown` · `arrowMarker` · `text` · `callout` · `anchoredNote` · `flag` · `sineLine` · `regressionTrend` · `ghostFeed`
960
1285
 
1286
+ **`ruler`**, with `features.enableForecasting` on (see [Feature flags](#feature-flags)),
1287
+ draws a direction-tinted box over the span it measures and reports:
1288
+
1289
+ ```
1290
+ 0.00455 (0.80%) 45.5
1291
+ 43 bars, 9d 4h
1292
+ Vol 102.27K
1293
+ ```
1294
+
1295
+ Price delta, percent, and **pips**; bar count and calendar duration; volume
1296
+ traded across the span.
1297
+
1298
+ A pip figure is always shown — but it is only *correct* when the host supplies
1299
+ [`instrument.pipSize`](#instrumentspec). Without it the chart infers pip size
1300
+ from how many decimals the feed quotes, which follows the usual FX convention
1301
+ and is wrong for metals, indices and crypto.
1302
+
1303
+ Duration needs bar timestamps, and the volume line is omitted entirely when the
1304
+ bars carry no volume, rather than showing a `0` that would read as "no volume
1305
+ traded".
1306
+
1307
+ The box takes its colour from `candle.up` / `candle.down` so a measurement never
1308
+ disagrees with the candles underneath it; picking a colour in the style popover
1309
+ overrides that. All four corners resize.
1310
+
1311
+ With the flag off it reports the bar count and raw price delta, as it always has.
1312
+
1313
+ ### Forecasting
1314
+
1315
+ `longPosition` · `shortPosition`
1316
+
1317
+ > Requires `features.enableForecasting` — see [Feature flags](#feature-flags).
1318
+ > With the flag off the group is not rendered, on the desktop toolbar or in the
1319
+ > mobile tools sheet.
1320
+ >
1321
+ > `ghostFeed` and `projection` stay in **Advanced Tools** and are ungated — they
1322
+ > predate this group.
1323
+
1324
+ **`longPosition` / `shortPosition`** sketch a trade that hasn't been placed: a
1325
+ green profit zone from entry to target, a red risk zone from entry to stop, and
1326
+ live readouts.
1327
+
1328
+ ```
1329
+ Target: 0.00313 (0.549%) 31.3, Amount: 5622.13
1330
+ Open PnL: 0.00146, Qty: 11323
1331
+ Risk/reward ratio: 1.84
1332
+ Stop: 0.00170 (0.298%) 17.0, Amount: 2887.5
1333
+ ```
1334
+
1335
+ Two clicks place it — entry, then target — and the stop lands at a 2:1
1336
+ reward:risk for you to drag. All three prices have handles.
1337
+
1338
+ Quantity is sized so that hitting the stop costs exactly `riskPercent` of the
1339
+ account, which needs [`account`](#accountspec); the money amounts and pips also
1340
+ need [`instrument`](#instrumentspec). Without them the tool still draws and still
1341
+ reports price, percent and risk/reward.
1342
+
1343
+ > **This is a drawing, not an order.** Trade-From-Chart (`setLevels`) is what
1344
+ > puts real broker orders on the chart — see [Trade From Chart
1345
+ > (TFC)](#trade-from-chart-tfc--setlevels). Nothing on a position tool reaches
1346
+ > the broker.
1347
+
961
1348
  ### Volume Profile
962
1349
 
963
1350
  `volumeProfile` · `anchoredVP` · `fixedRangeVP`
@@ -966,6 +1353,10 @@ In a **per-drawing** style (`SerializedDrawing.style.levels`), a level may also
966
1353
 
967
1354
  `cyclicLines` · `timeCycles`
968
1355
 
1356
+ > `ghostFeed` and `projection` remain here and are ungated. TradingView files
1357
+ > them under Forecasting, but moving them would have reshuffled the toolbar for
1358
+ > hosts that never enabled the new group.
1359
+
969
1360
  ### Harmonic & Elliott Patterns
970
1361
 
971
1362
  `abcdPattern` · `headShoulders` · `trianglePattern` · `batPattern` · `butterflyPattern` · `crabPattern` · `gartleyPattern` · `cypherPattern` · `sharkPattern` · `threeDrives` · `elliottImpulse` · `elliottCorrective` · `elliottTriangle` · `elliottCombination` · `elliottWxy`
@@ -986,8 +1377,9 @@ chart.on('pan', ({ viewport }) => {});
986
1377
  chart.on('timeframeChange',({ timeframe }) => {});
987
1378
  chart.on('durationChange', ({ duration, timeframe }) => {});
988
1379
  chart.on('seriesChange', ({ series }) => {});
1380
+ chart.on('priceSourceChange', ({ source }) => {}); // header BID/ASK/LTP dropdown pick
989
1381
  chart.on('streamStatus', ({ status }) => {}); // 'connected' | 'reconnecting' | 'disconnected'
990
- chart.on('dataLoaded', ({ timeframe, interval, start, end }) => {});
1382
+ chart.on('dataLoaded', ({ timeframe, interval, start, end, priceSource }) => {});
991
1383
  chart.on('newBar', ({ completedBar, openingBar, intervalMs }) => {});
992
1384
  chart.on('indicatorAdded', ({ instanceId, shortName, params }) => {}); // a study instance was added — keep instanceId to remove it later
993
1385
  chart.on('indicatorRemoved', ({ instanceId, shortName }) => {});
@@ -1010,6 +1402,10 @@ chart.on('tradeLevelEditCancelled', ({ label, type, isFullscreen }) => {}); // E
1010
1402
  chart.on('draftInitiated', ({ side, price, orderType, isFullscreen }) => {}); // new draft order shown — open buy/sell form
1011
1403
  chart.on('draftCancelled', ({ label, isFullscreen }) => {}); // draft order dismissed without confirming
1012
1404
  chart.on('tfcToggle', ({ enabled }) => {}); // TFC toggled on or off via top bar button or setTfcActive()
1405
+ chart.on('crosshairToggle', ({ enabled }) => {}); // crosshair switched on or off — header switch (enableCrossHairHeader) or setCrosshairEnabled(); persist it here
1406
+ chart.on('pnlPillCloseAll', ({ count, pnl, labels, data, isFullscreen }) => {}); // the on-chart P/L pill's ✕ — close these positions (features.pnlPill)
1407
+ chart.on('pnlPillToggle', ({ visible }) => {}); // the header's P/L switch showed or hid the pill — persist it here (features.pnlPill)
1408
+ chart.on('bulkLevelsRequested', ({ kind, price, source, isFullscreen }) => {}); // action-bar chip (price) or the P/L pill's ◎ (price null) — open your Bulk Levels dialog for `kind`
1013
1409
  chart.on('tradeLevelDragEnd', ({ label, type, newPrice, data }) => {}); // deprecated — use tradeLevelEdit
1014
1410
  chart.on('tradeLevelBracketDrag', ({ label, bracketType, newPrice, data }) => {}); // deprecated
1015
1411
 
@@ -1018,8 +1414,8 @@ chart.on('tradeLevelBracketDrag', ({ label, bracketType, newPrice, data }) => {}
1018
1414
  chart.on('orderLineMoveStart', ({ label, fromTimestamp, fromBarIndex, isFullscreen }) => {});
1019
1415
  chart.on('orderLineMoving', ({ label, toTimestamp, toBarIndex, isFullscreen }) => {}); // fires on every move
1020
1416
  chart.on('orderLineMoved', ({ label, fromTimestamp, toTimestamp, fromBarIndex, toBarIndex, data, isFullscreen }) => {
1021
- // Persist the new time anchor for this order. Echo `timestamp: toTimestamp` back in your
1022
- // next setLevels() payload so the badge stays put across refreshes.
1417
+ // The chart already remembers the drop in localStorage (orderLineAnchorPersistence, default on).
1418
+ // Hook here only if you also want to persist the new time anchor server-side.
1023
1419
  });
1024
1420
 
1025
1421
  // Fires after addLevelBracket() auto-places a bracket, delivering the computed price back to the caller
@@ -1058,6 +1454,16 @@ chart.on('snapshot', ({ dataUrl, action }) => {
1058
1454
  });
1059
1455
  ```
1060
1456
 
1457
+ ### On mobile
1458
+
1459
+ The `'mobile'` header shows the same Layout button when `enableMultipleLayouts: true`, and
1460
+ opens the same preset popover. For apps that draw their own header, the native-UI catalog
1461
+ (`catalog` event / `getCatalog`) carries a `layouts` section — every preset above with its
1462
+ `id`, `label`, `count`, `cols`, `rows`, `areas` and `icon`, plus the five sync toggles with
1463
+ their defaults — and the `layouts` toolbar entry. The app sends `setLayoutPreset(presetId)`,
1464
+ receives `layoutChange`, and mounts that many chart views itself; see the Android and iOS
1465
+ READMEs.
1466
+
1061
1467
  ### Seeding & restoring the popover's sync toggles
1062
1468
 
1063
1469
  The layout popover's five sync toggles (`symbol` / `interval` / `crosshair` / `time` / `dateRange`) default to `DEFAULT_LAYOUT_SYNC`. To open the popover in a different state — e.g. restoring a user's saved preference — pass a **partial** `layoutSync` at construction (omitted keys keep their `DEFAULT_LAYOUT_SYNC` value):
@@ -1160,45 +1566,1505 @@ The composite excludes trade levels (positions, SL/TP) — same rule as `chart.t
1160
1566
 
1161
1567
  ---
1162
1568
 
1163
- ## Custom Indicator
1569
+ ## Icons & Drawing Toolbar Options
1164
1570
 
1165
- Implement `IIndicator` and pass it to `addIndicator()`:
1571
+ ### Icons, Emojis & Stickers — `'icon'`
1572
+
1573
+ A glyph placed at a bar and price, behind `features.enableIconTools`. **One tool,
1574
+ not three**: emojis, stickers and icons are the same drawing with a different
1575
+ character, so the picker chooses the glyph and the glyph lives in `text` like any
1576
+ other annotation's content. They serialise, re-anchor and re-style through
1577
+ machinery that already exists rather than needing three parallel implementations.
1166
1578
 
1167
1579
  ```ts
1168
- import type { IIndicator, OHLCVBar, IndicatorResult } from 'acttrader-charts';
1580
+ const chart = new ChartEngine({
1581
+ container,
1582
+ features: { enableIconTools: true },
1583
+ });
1584
+ chart.setDrawingTool('icon'); // uses the last glyph picked
1585
+ ```
1169
1586
 
1170
- class MyIndicator implements IIndicator {
1171
- name = 'MyInd';
1172
- color = '#e91e63';
1173
- pane = 'sub' as const; // 'main' = overlay, 'sub' = dedicated pane
1174
- paneHeight = 80;
1587
+ #### The picker
1175
1588
 
1176
- compute(data: OHLCVBar[]): IndicatorResult[] {
1177
- return data.map((bar, i) => ({ index: i, value: bar.close }));
1178
- }
1589
+ Opening the **Icons & Emojis** group gives a panel, not a list of rows: a row per
1590
+ glyph is unusable past a couple of dozen, and this is the one category whose
1591
+ items *are* the icon rather than being labelled by one.
1179
1592
 
1180
- render(ctx, results, scale, viewport, chartHeight) {
1181
- // draw with ctx (Canvas 2D)
1182
- }
1183
- }
1593
+ ```
1594
+ ┌────────────────────────────────┐
1595
+ │ 😊 🐻 🍔 🏀 🚀 💡 ❤️ 🏳️ │ category tabs
1596
+ ├────────────────────────────────┤
1597
+ │ 😀 😃 😄 😁 😆 😅 🤣 😂 │
1598
+ │ 🙂 🙃 😉 😊 😇 🥰 😍 🤩 │ scrolling grid
1599
+ ├────────────────────────────────┤
1600
+ │ Emojis Stickers Icons │ kind tabs
1601
+ └────────────────────────────────┘
1602
+ ```
1184
1603
 
1185
- chart.addIndicator(new MyIndicator());
1604
+ The three bottom tabs are not three copies of the same thing:
1605
+
1606
+ | Tab | Holds | Draws as |
1607
+ | --- | --- | --- |
1608
+ | **Emojis** | ~900 across the eight Unicode groups | System colour font, 22px |
1609
+ | **Stickers** | Trading-flavoured sets — bull & bear, reactions, money, warnings, awards | The same characters at 44px |
1610
+ | **Icons** | Monochrome arrows, shapes, marks, currency | Takes the drawing's colour |
1611
+
1612
+ That last row is why **Icons** is worth having at all. An emoji is a colour
1613
+ bitmap in the system font: it ignores `fillStyle`, so it can never be recoloured
1614
+ to match a palette or printed legibly in mono. Everything under Icons is a plain
1615
+ text character, and does tint.
1616
+
1617
+ The panel renders into the toolbar's existing flyout rather than adding a second
1618
+ floating layer, so it inherits that popover's positioning, outside-click
1619
+ dismissal and teardown. It remembers the tab and category per session — reopening
1620
+ a picker to find yourself back on the first page of smileys is the single most
1621
+ irritating thing a picker can do.
1622
+
1623
+ #### Resizing
1624
+
1625
+ A placed icon is selectable and **resizable by dragging any of its four corner
1626
+ handles**. Size is also in the style popover, which offers a colour swatch and a
1627
+ px picker rather than the default stroke/width/style — three controls that would
1628
+ do nothing to a glyph.
1629
+
1630
+ ```ts
1631
+ chart.getDrawings()
1632
+ .filter(d => d.type === 'icon')
1633
+ .forEach(d => { d.style = { ...d.style, fontSize: 64 }; });
1634
+ ```
1635
+
1636
+ **The size is in pixels, not price.** It does not rescale when the chart is
1637
+ zoomed. Deriving it from two data points would have fit the existing drag
1638
+ machinery with no new concepts, but a pin dropped on a bar would then become a
1639
+ billboard three zoom steps out and vanish three steps in — and the user would
1640
+ have to resize it again every time they changed the view. So `DrawingHandle`
1641
+ grew a `mode: 'size'`, and handles marked that way route to
1642
+ `IDrawing.resizeToPixel(px, py)` instead of the point writer.
1643
+
1644
+ `resizeToPixel` takes pixels because the size it sets is in pixels — converting
1645
+ through price and back would make the result depend on the zoom level it was
1646
+ dragged at. It measures against the anchor position cached during `render`,
1647
+ which is the only place a drawing is handed the scale.
1648
+
1649
+ The new size is the larger of the two axis distances, not the diagonal, so
1650
+ pulling straight out sideways grows the glyph as much as pulling corner to
1651
+ corner. A glyph is square; a user dragging one edge means "bigger", not "bigger
1652
+ by cos 45°". Clamped to 10–400px and rounded, since the value is shown in a px
1653
+ picker and round-trips through JSON.
1654
+
1655
+ Glyphs render through the system emoji font, so colour emoji stay colour on every
1656
+ platform that has them.
1657
+
1658
+ ### Drawing toolbar options
1659
+
1660
+ Five toggles in the toolbar's actions menu (⋯).
1661
+
1662
+ | Option | What it does |
1663
+ | --- | --- |
1664
+ | **Magnet Mode** | Drawing points snap to the nearest open/high/low/close of the bar under the cursor. |
1665
+ | **Keep Drawing Mode** | The tool stays armed after each drawing, so a series can be placed without returning to the toolbar. |
1666
+ | **Copy to All Charts** | New drawings are announced for replication across a layout. |
1667
+ | **Hide Drawings Toolbar** | Hides the toolbar at runtime; bring it back with `setDrawingToolbarVisible(true)`. |
1668
+ | **Zoom In** | In the Cursors group — drag a box and the chart zooms to it. |
1669
+
1670
+ ```ts
1671
+ const chart = new ChartEngine({
1672
+ container,
1673
+ magnetMode: true,
1674
+ keepDrawingMode: true,
1675
+ copyDrawingsToAllCharts: true,
1676
+ });
1677
+
1678
+ chart.setMagnetMode(false);
1679
+ chart.on('magnetModeChange', ({ enabled }) => persist(enabled));
1680
+ ```
1681
+
1682
+ **Magnet snaps within a pixel threshold, not always.** A trend line deliberately
1683
+ drawn through the middle of a range should stay there. The threshold is in
1684
+ pixels rather than price so it feels identical at every zoom — a price-space
1685
+ tolerance would snap from far away on a zoomed-out chart and never trigger on a
1686
+ zoomed-in one.
1687
+
1688
+ **Keep-drawing mode routes through one place.** There are four separate
1689
+ completion paths in the drawing manager; a mode that held for only some of them
1690
+ would look broken in exactly the cases a user reached for it.
1691
+
1692
+ **Copy-to-all is announced, not performed.** The chart emits `drawingCreated`
1693
+ with `copyToAll`, because only the host knows which other panes exist:
1694
+
1695
+ ```ts
1696
+ chart.on('drawingCreated', ({ drawing, copyToAll }) => {
1697
+ if (copyToAll) group.broadcastDrawing(drawing, thisPaneId);
1698
+ });
1186
1699
  ```
1187
1700
 
1701
+ `ChartGroup.broadcastDrawing(drawing, fromPaneId?)` hands the payload to every
1702
+ other pane's `ChartEngine.addDrawing(drawing)`. Unlike `broadcastSymbol` there
1703
+ is no `LayoutSyncState` flag gating it — the toggle already lives on the chart
1704
+ the user drew on, and that is what `copyToAll` reports.
1705
+
1706
+ `addDrawing` **appends and is undoable**, where `setState` would replace the
1707
+ list and flatten the target pane's history. Each pane's copy also gets a fresh
1708
+ id, so dragging the mirrored drawing in one pane leaves the others alone.
1709
+
1710
+ **Zoom In is a drawing internally.** It reuses the two-point press-preview-release
1711
+ gesture rather than duplicating it as a bespoke drag mode, then applies the zoom
1712
+ and removes itself — so nothing is left on the chart and it never reaches
1713
+ `ChartState`. It sets *both* axes: zooming only time would leave the chosen
1714
+ prices no larger than before, which is not what dragging a box asks for.
1715
+
1716
+ ### Native wrapper parity
1717
+
1718
+ `'icon'` and `'zoomIn'` are `DrawingToolType` strings and need no wrapper change.
1719
+ The toolbar options are new bridge commands — see
1720
+ [charts-android](../charts-android) and [charts-ios](../charts-ios).
1721
+
1188
1722
  ---
1189
1723
 
1190
- ## Build & Dev
1724
+ ## Notes & Text
1725
+
1726
+ Six annotation tools, all single-click: place, then type.
1727
+
1728
+ | Tool | `DrawingToolType` | Form |
1729
+ | --- | --- | --- |
1730
+ | **Anchored Text** | `'anchoredText'` | Free text with a dot on the bar and price it refers to. |
1731
+ | **Note** | `'note'` | A compact page marker with the text beside it. |
1732
+ | **Pin** | `'pin'` | A teardrop whose **tip** sits exactly on the price. |
1733
+ | **Table** | `'table'` | Rows of text in a bordered grid. |
1734
+ | **Comment** | `'comment'` | A rounded speech bubble with its tail on the anchor. |
1735
+ | **Signpost** | `'signpost'` | A plaque on a post, rising clear of the candles. |
1736
+
1737
+ ```ts
1738
+ chart.setDrawingTool('signpost');
1739
+ ```
1740
+
1741
+ All six anchor to a bar and price like every other drawing, so they re-anchor
1742
+ correctly after a data reload and serialise into `ChartState` unchanged.
1743
+
1744
+ ### Editing
1745
+
1746
+ | | |
1747
+ | --- | --- |
1748
+ | **Place** | Click — the editor opens focused |
1749
+ | **Re-edit** | Select, then double-click |
1750
+ | **New line** | `Enter` (multi-line tools) |
1751
+ | **Commit** | `Ctrl`/`⌘`+`Enter`, or click away |
1752
+ | **Discard** | `Escape` |
1753
+
1754
+ **Anchored Text, Note, Table, Comment and Signpost get a multi-line editor**;
1755
+ Text, Callout, Anchored Note and Pin keep the single-line field where `Enter`
1756
+ commits, exactly as before. A Table is unusable without this — its rows *are*
1757
+ newlines, so `Enter` has to insert one.
1758
+
1759
+ The box grows with its content as you type, so adding rows is visible rather
1760
+ than feeling like it has a row limit.
1761
+
1762
+ ### Why these are separate tools rather than one with options
1763
+
1764
+ The shape *is* the choice. Someone reaching for a Pin wants a precise marker at
1765
+ a level; someone reaching for a Signpost wants a dated flag that does not cover
1766
+ the candles; someone reaching for a Table wants several values at once.
1767
+ Collapsing them into "text with a style dropdown" would make each one harder to
1768
+ reach than the thing it replaced.
1769
+
1770
+ ### Details worth knowing
1771
+
1772
+ **Table syntax** — newlines are rows and `|` separates columns, so a table is
1773
+ typed into the same single text field as everything else rather than needing a
1774
+ bespoke editor. The first row is tinted as a header; short rows are padded so the
1775
+ grid stays rectangular, and empty cells are kept (clearing a value is editing the
1776
+ table, not asking for the column to vanish).
1777
+
1778
+ **A new table arrives already a grid** — four rows by two columns, with the
1779
+ syntax visible in the editor:
1191
1780
 
1192
- ```bash
1193
- npm run dev # Vite dev server with demo chart
1194
- npm run build # ESM + CJS via tsup → dist/
1195
- npm run test # Vitest unit tests
1196
- npm run typecheck # tsc --noEmit
1197
- npm run lint # ESLint
1198
1781
  ```
1782
+ Level | Price
1783
+ Entry |
1784
+ Stop |
1785
+ Target |
1786
+ ```
1787
+
1788
+ That is deliberate. An empty table rendered a single placeholder row and opened a
1789
+ blank editor, so nothing told you rows are newlines and columns are `|` — the
1790
+ tool looked as though it had no rows or columns at all. Overtyping a grid is also
1791
+ faster than building one from nothing.
1792
+
1793
+ **Pin anchors by its tip, not its centre.** A marker whose middle sits on the
1794
+ level is ambiguous about which price it means.
1795
+
1796
+ **Anchored Text vs Text** — plain `text` floats with no indication of what it
1797
+ refers to. Anchored Text draws its anchor, so a note about one specific candle
1798
+ still points at that candle after panning and zooming.
1799
+
1800
+ **Comment vs Callout** — `callout` is a square-cornered box with a straight
1801
+ pointer; `comment` is the softer rounded bubble. Both are kept because the
1802
+ difference is exactly what the user is choosing between.
1803
+
1804
+ Empty tools render a placeholder (`Text`, `Note`, `Event`…) rather than nothing,
1805
+ so a drawing placed but not yet typed into is still visible and selectable.
1806
+
1807
+ ### Native wrapper parity
1808
+
1809
+ All six are `DrawingToolType` strings, so `setDrawingTool('pin')` works on
1810
+ [charts-android](../charts-android) and [charts-ios](../charts-ios) with no
1811
+ wrapper change.
1199
1812
 
1200
1813
  ---
1201
1814
 
1202
- ## License
1815
+ ## Indicator Library
1203
1816
 
1204
- MIT
1817
+ **78 studies added**, taking the library from 30 to 108.
1818
+
1819
+ ```ts
1820
+ chart.addIndicatorByName('TRIX');
1821
+ chart.addIndicatorByName('Vortex');
1822
+ ```
1823
+
1824
+ They appear in the Indicators flyout alongside the originals, grouped by the
1825
+ same categories, and each is configurable through the settings dialog.
1826
+
1827
+ ### How they are registered
1828
+
1829
+ The original thirty are registered by hand in three places — a preset list, a
1830
+ param-schema list, and `indicators.json`. Repeating that seventy-eight times
1831
+ would be seventy-eight chances to register an indicator in two places and not
1832
+ the third, which fails *silently*: the tool appears in the menu and does
1833
+ nothing, or computes and never appears.
1834
+
1835
+ So each new indicator is declared once in `indicators/registry.ts` and the three
1836
+ views are derived:
1837
+
1838
+ ```ts
1839
+ {
1840
+ shortName: 'TRIX', name: 'TRIX', type: 'Momentum',
1841
+ fields: [periodField(18), colorField('#00BFA5'), sourceField()],
1842
+ factory: (p) => new SimpleOscillator('TRIX', p.color, …),
1843
+ }
1844
+ ```
1845
+
1846
+ ### Shared foundations
1847
+
1848
+ | Module | What it holds |
1849
+ | --- | --- |
1850
+ | `indicators/math.ts` | `sma`, `ema`, `rma`, `wma`, `hma`, `vwma`, `alma`, `dema`, `tema`, `mcginley`, `lsma`, `stdev`, `standardError`, `correlation`, `atr`, … |
1851
+ | `indicators/base.ts` | `LineIndicatorBase`, `BandIndicatorBase`, `HistogramIndicatorBase` |
1852
+
1853
+ All exported, so a host can compute the same series off-chart.
1854
+
1855
+ Two conventions the maths holds to throughout:
1856
+
1857
+ - **`null` means undefined and propagates.** An EMA of an RSI is null wherever
1858
+ the RSI is. Returning `0` instead would draw a line through a period where the
1859
+ indicator does not exist, which reads as data and is not.
1860
+ - **`stdev` is the population form**, because Bollinger Bands and everything
1861
+ derived from them are defined that way; using `n−1` shifts every band visibly
1862
+ on short periods.
1863
+
1864
+ ### The comparative studies
1865
+
1866
+ **Correlation Coefficient**, **Correlation – Log**, **Ratio**, **Spread** and
1867
+ **Advance/Decline** are undefined against a single series — they need a second
1868
+ instrument. `IIndicator.compute` gained an optional second argument for this:
1869
+
1870
+ ```ts
1871
+ compute(data: OHLCVBar[], context?: IndicatorComputeContext): IndicatorResult[]
1872
+ ```
1873
+
1874
+ `context.compares` carries the bars for each symbol added through the Compare
1875
+ feature. The parameter is optional, so every existing indicator is unaffected.
1876
+
1877
+ **With no compare symbol added, these draw nothing.** Substituting a stand-in
1878
+ series — correlating price against its own average, say — would produce a
1879
+ confident-looking line answering a different question than the indicator's name
1880
+ promises.
1881
+
1882
+ ### Two things worth knowing
1883
+
1884
+ **Volume Profile Visible Range** distributes each bar's real volume across the
1885
+ price levels that bar actually traded through, and marks the Point of Control.
1886
+ The existing `anchoredVP` *drawing tool* is a different thing: its bar heights
1887
+ come from a hardcoded bell curve, not from the feed.
1888
+
1889
+ **`maxSubPanes` caps concurrent sub-pane indicators.** Most of these 78 live in
1890
+ their own pane, so adding many at once silently stops at the cap. Raise
1891
+ `maxSubPanes` if you need more on screen together.
1892
+
1893
+ ### Native wrapper parity
1894
+
1895
+ All 78 are reachable through the existing `addIndicator` bridge command by short
1896
+ name — no wrapper change:
1897
+
1898
+ ```kotlin
1899
+ chartView.addIndicatorByName("TRIX")
1900
+ ```
1901
+
1902
+ ### What was added
1903
+
1904
+ | Group | Studies |
1905
+ | --- | --- |
1906
+ | Moving averages (14) | ALMA, DEMA, TEMA, LSMA, McGinley, SMMA, VWMA, Hamming, Adaptive (KAMA), MA Channel, MA Double, MA Triple, MA Multiple, Guppy |
1907
+ | Momentum (23) | Accelerator, ASI, Balance of Power, CMO, Connors RSI, Coppock, DPO, Fisher, KST, Majority Rule, Momentum, Price Oscillator, Rank Correlation, Relative Vigor, SMI Ergodic, TRIX, TSI, Ultimate, Correlation, Correlation Log, + crosses |
1908
+ | Volatility (16) | %B, BB Width, Historical, Close-to-Close, Zero Trend, O-H-L-C, Volatility Index, StdDev, StdError, StdError Bands, Choppiness, Chop Zone, Chaikin Volatility, Mass Index, RVI, Envelopes |
1909
+ | Trend (12) | Aroon, DMI, Vortex, Trend Strength, LinReg Slope, Price Channel, Chande Kroll, 52W H/L, Alligator, Fractal, Zig Zag, MA/EMA crosses |
1910
+ | Volume (9) | Ease of Movement, Elder's Force, Klinger, Volume Oscillator, Net Volume, PVT, Chaikin Oscillator, Advance/Decline, VPVR |
1911
+ | Price transforms (4) | Average Price, Median Price, Typical Price, Ratio, Spread |
1912
+
1913
+ ---
1914
+
1915
+ ## Shapes & Arrows
1916
+
1917
+ ### Already shipped: the line arrow
1918
+
1919
+ **`'arrowMarker'`** is TradingView's Arrow — a line from tail to tip with a
1920
+ filled arrowhead. It was only ever *labelled* "Arrow Marker", which hid it. The
1921
+ label now reads **Arrow**.
1922
+
1923
+ The `DrawingToolType` string is unchanged, and labels are i18n-overridable
1924
+ through `labels.drawingToolbar.tools`, so nothing breaks — but it is a
1925
+ user-visible string change worth knowing about.
1926
+
1927
+ ### Arrow Mark Left / Right — `'arrowMarkLeft'`, `'arrowMarkRight'`
1928
+
1929
+ Single-click marks that point *at* a price level from the side — the horizontal
1930
+ siblings of `arrowUp` / `arrowDown`. Where those call out a move's direction,
1931
+ these call out a level: the arm runs along the price, so the mark reads as "this
1932
+ price, from the left" rather than "up from here".
1933
+
1934
+ Fixed pixel geometry, not price-space — a marker is chrome and should stay the
1935
+ same size whatever the axis is doing. The hit box covers the whole glyph, stem
1936
+ and head, so you grab what you can see.
1937
+
1938
+ ### Curve — `'curve'`
1939
+
1940
+ Two endpoints and a handle that bends the line between them: a **quadratic
1941
+ Bézier**, not a circular arc.
1942
+
1943
+ The existing `'arc'` tool fits a circle through three points, and a circle's
1944
+ curvature is constant — it cannot leave one endpoint steeply and arrive at the
1945
+ other gently. A Bézier can, which is what you want for sketching a rounding top
1946
+ or a decelerating trend.
1947
+
1948
+ One handle is exactly what a quadratic takes, so every position you can drag to
1949
+ maps to a curve, and every curve the tool can draw is reachable by dragging. A
1950
+ cubic would need a second handle to be fully controllable, or would hide half its
1951
+ shape. The handle and its guides are drawn only while selected.
1952
+
1953
+ ### Double Curve — `'doubleCurve'`
1954
+
1955
+ An S, from the same three clicks as a single Curve. The chord is split at its
1956
+ midpoint and each half gets its own quadratic, bent by equal and **opposite**
1957
+ offsets — so one handle controls both bends, and dragging across the chord
1958
+ inverts the S.
1959
+
1960
+ Deriving the second bend from the first, rather than asking for a fourth click,
1961
+ is the point: an S whose halves are set independently is just two curves. The
1962
+ shape only reads as one gesture if the halves stay symmetric, and making that
1963
+ automatic is cheaper for the user than making it their job.
1964
+
1965
+ ### Curve maths
1966
+
1967
+ Exported, so a host can reproduce the same geometry:
1968
+
1969
+ ```ts
1970
+ import { quadraticAt, controlFromOffset, offsetFromHandle } from 'acttrader-charts';
1971
+ ```
1972
+
1973
+ `controlFromOffset` and `offsetFromHandle` are **true inverses**, both speaking
1974
+ in *apex* distance — how far the curve itself lands from the chord, not how far
1975
+ the control point does. A quadratic's apex sits halfway between chord and
1976
+ control, so the conversion doubles in one direction and halves in the other.
1977
+
1978
+ ### Native wrapper parity
1979
+
1980
+ All four are `DrawingToolType` strings, so `setDrawingTool('doubleCurve')` works
1981
+ on [charts-android](../charts-android) and [charts-ios](../charts-ios) with no
1982
+ wrapper change.
1983
+
1984
+ ---
1985
+
1986
+ ## Projection & Measurement
1987
+
1988
+ ### Already shipped: Long Position / Short Position
1989
+
1990
+ `'longPosition'` and `'shortPosition'` exist today and are complete risk/reward
1991
+ tools: three prices (entry, target, stop) drawn as a green profit zone and a red
1992
+ risk zone, with the money and quantity the account's risk budget implies. You
1993
+ place entry and target; the stop is materialised from the default reward:risk, so
1994
+ the common case is two clicks rather than three.
1995
+
1996
+ They are gated behind `features.enableForecasting` and need `account` for money
1997
+ and quantity, and `instrument` for pips:
1998
+
1999
+ ```ts
2000
+ new ChartEngine({
2001
+ container,
2002
+ features: { enableForecasting: true },
2003
+ account: { equity: 50_000, riskPercent: 1 },
2004
+ });
2005
+ ```
2006
+
2007
+ Deliberately **not** Trade-From-Chart — `setLevels` draws real broker orders and
2008
+ committing one sends it. These are drawings; nothing here reaches the broker.
2009
+
2010
+ ### Anchored VWAP — `'anchoredVwap'`
2011
+
2012
+ Volume-weighted average price accumulated from a bar you pick: the average price
2013
+ everyone who traded since the anchor actually paid, which is what turns a swing
2014
+ high or an earnings gap into support.
2015
+
2016
+ **This is not the existing `'anchoredVP'`.** That one is Anchored Volume
2017
+ *Profile* — a horizontal histogram of volume by price level, and its bar heights
2018
+ come from a hardcoded bell curve rather than from the feed. Anchored VWAP is a
2019
+ single line computed from real volume.
2020
+
2021
+ Placed with one click, re-accumulating as data streams in. The series is
2022
+ exported:
2023
+
2024
+ ```ts
2025
+ import { anchoredVwapSeries } from 'acttrader-charts';
2026
+
2027
+ const vwap = anchoredVwapSeries(bars, anchorIndex); // number[] | null
2028
+ ```
2029
+
2030
+ Two deliberate behaviours:
2031
+
2032
+ - It uses the **(H+L+C)/3 typical price**, the convention VWAP is defined on —
2033
+ not the close, which would make it a volume-weighted close.
2034
+ - It returns **`null` when the span carries no volume**, and the chart draws no
2035
+ line. A VWAP without volume silently degrades into a running mean of typical
2036
+ prices: it looks like a VWAP and is not one. A volume-less feed gets no line
2037
+ rather than a plausible wrong one. The anchor dot is still drawn, so the
2038
+ drawing stays selectable and deletable.
2039
+
2040
+ ### Forecast — `'forecast'`
2041
+
2042
+ Three points: p1→p2 is what happened, p2→p3 is what you expect next. The base is
2043
+ solid, the forecast dashed, and a shaded cone opens from zero at p2 to half the
2044
+ base move's size at p3 — because a projection is exact where it starts and vague
2045
+ where it ends, and a bare line implies a precision no forecast has. A readout
2046
+ gives the projected change in price, percent and bars.
2047
+
2048
+ That cone is what separates it from the existing `'projection'` tool, which
2049
+ extrapolates a trend line to the right edge with no second leg you control and no
2050
+ statement of confidence.
2051
+
2052
+ ### Bars Pattern — `'barsPattern'`
2053
+
2054
+ Three points: p1 and p2 bracket the bars to copy, p3 anchors the copy. It draws
2055
+ real candles from the source bars, re-based by price **offset** rather than ratio
2056
+ — the tool is for asking "the same move, from here", not "a proportional move".
2057
+
2058
+ The copy is drawn at reduced alpha inside a dashed bounding box. Without that it
2059
+ renders in the chart's own candle colours and becomes indistinguishable from real
2060
+ data, which is worse than useless.
2061
+
2062
+ ### Native wrapper parity
2063
+
2064
+ All three new tools are `DrawingToolType` strings, so `setDrawingTool('forecast')`
2065
+ works on [charts-android](../charts-android) and [charts-ios](../charts-ios) with
2066
+ no wrapper change. Long/Short Position need `enableForecasting` in the native
2067
+ `init` payload, which both wrappers already expose.
2068
+
2069
+ ---
2070
+
2071
+ ## Patterns
2072
+
2073
+ ### XABCD Pattern — `'xabcdPattern'`
2074
+
2075
+ The free-form harmonic, and the only one that shows its working.
2076
+
2077
+ Every named harmonic in the library — Gartley, Bat, Butterfly, Crab, Shark,
2078
+ Cypher — draws the identical X→A→B→C→D zigzag and dashed XD line, differing only
2079
+ in colour. None of them measures or validates anything. XABCD assumes nothing
2080
+ instead: you place five pivots and it reports the ratios those pivots actually
2081
+ produce, so you can decide which harmonic the structure matches.
2082
+
2083
+ That measurement is the whole point. Without it this would be an existing tool
2084
+ under a new name.
2085
+
2086
+ | Ratio | Measured against | Why it matters |
2087
+ | --- | --- | --- |
2088
+ | `AB/XA` | the initial leg | the first retracement |
2089
+ | `BC/AB` | the AB leg | the counter-move |
2090
+ | `CD/BC` | the BC leg | the final leg's extension |
2091
+ | `AD/XA` | the whole XA move | what separates a Gartley (0.786) from a Butterfly (1.27) |
2092
+
2093
+ It also shades the XAB and BCD triangles, which is what makes the shape readable
2094
+ at a glance — the zigzag alone is just four lines.
2095
+
2096
+ The arithmetic is exported, so a host can auto-classify a pattern with the same
2097
+ numbers the chart draws:
2098
+
2099
+ ```ts
2100
+ import { xabcdRatios } from 'acttrader-charts';
2101
+
2102
+ const chips = xabcdRatios(drawing.points);
2103
+ // → [{ from: 1, to: 2, text: 'AB/XA 0.600' }, …]
2104
+ ```
2105
+
2106
+ A leg of zero length has no defined ratio against it, so that entry is **omitted**
2107
+ rather than printed as `Infinity` or `NaN`, and ratios for pivots you have not
2108
+ placed yet simply do not appear.
2109
+
2110
+ ### Elliott Triple Combo (WXYXZ) — `'elliottTripleCombo'`
2111
+
2112
+ The triple three: three corrective structures joined by two X waves, six points
2113
+ from an origin.
2114
+
2115
+ There are now three neighbouring tools and the distinction is exact:
2116
+
2117
+ | Tool | Points | Labels |
2118
+ | --- | --- | --- |
2119
+ | `'elliottWxy'` | 4 | the **double** three — W, X, Y |
2120
+ | `'elliottCombination'` | 7 | W, X, Y, X2, Z, X3, end |
2121
+ | `'elliottTripleCombo'` | 6 | 0, W, X, Y, X, Z |
2122
+
2123
+ You asked whether the existing Combination tool already covers this. It partly
2124
+ does — but it takes **seven** points where a triple three has six, and numbers its
2125
+ connectors `X2`/`X3` where Elliott notation leaves both as `X`. A trader counting
2126
+ a triple three places five waves after the origin, and a tool demanding six
2127
+ leaves them with a pivot to park somewhere meaningless. This tool matches the
2128
+ count and the notation; the Combination tool is unchanged.
2129
+
2130
+ Wave labels sit above a peak and below a trough, so they never land on the line
2131
+ that produced them.
2132
+
2133
+ ### Native wrapper parity
2134
+
2135
+ Both are new `DrawingToolType` strings, so `setDrawingTool('xabcdPattern')` works
2136
+ on [charts-android](../charts-android) and [charts-ios](../charts-ios) with no
2137
+ wrapper change.
2138
+
2139
+ ---
2140
+
2141
+ ## Fibonacci & Gann
2142
+
2143
+ Five tools added for TradingView parity. Each exists because it answers a
2144
+ question an existing tool in the same group cannot.
2145
+
2146
+ | Tool | `DrawingToolType` | Points | vs. its neighbour |
2147
+ | --- | --- | --- | --- |
2148
+ | **Trend-Based Fib Time** | `'trendBasedFibTime'` | 3 | Fib Timezone measures from its own origin. This projects one leg's *duration* onto a different starting bar. |
2149
+ | **Fib Speed Resistance Arcs** | `'fibSpeedResistanceArcs'` | 2 | The Fan projects straight lines, so implied support stays proportional forever. Arcs curve, so it decays with distance. |
2150
+ | **Fib Wedge** | `'fibWedge'` | 3 | Fib Circles sweep a full turn from one centre. A wedge is bounded by two user-drawn rays. |
2151
+ | **Pitchfan** | `'pitchfan'` | 3 | A Pitchfork's tines run parallel — a fixed channel. A Pitchfan's radiate, so they spread with distance. |
2152
+ | **Gann Square Fixed** | `'gannSquareFixed'` | 2 | The plain Gann Square stretches to the drag box, so its diagonal is only 45° at one zoom. |
2153
+
2154
+ ```ts
2155
+ chart.setDrawingTool('fibWedge');
2156
+ ```
2157
+
2158
+ ### Details that matter
2159
+
2160
+ **Trend-Based Fib Time** — p1→p2 is the base leg and p3 is where projection
2161
+ starts, so the verticals answer *"if this leg took N bars, when do the Fibonacci
2162
+ multiples of N fall from here?"*. Lines outside the viewport are skipped rather
2163
+ than stroked and clipped. It stays inert until the third point lands and when the
2164
+ base leg has zero duration — there is nothing to project in either case.
2165
+
2166
+ **Fib Speed Resistance Arcs** — drawn as **ellipses**, not circles, with the x and
2167
+ y radii taken separately from the trend's run and rise. A pixel-space circle
2168
+ would change shape the moment the price axis was rescaled, which makes the tool
2169
+ meaningless on a chart the user has zoomed. Only the half facing the trend is
2170
+ drawn; the half behind the origin would imply resistance before the move began.
2171
+
2172
+ **Fib Wedge** — the sweep always takes the short way round, so a wedge never
2173
+ flips to the reflex angle when an edge crosses the ±π seam. Hit testing checks
2174
+ the angular span first, so a click at a matching radius but outside the wedge
2175
+ correctly misses.
2176
+
2177
+ **Pitchfan** — rays are extended *forward* past the base, since that is the only
2178
+ part anyone trades off. Handle and base are dashed: construction, not signal.
2179
+
2180
+ **Gann Square Fixed** — takes the **longer** side of the drag and uses it for
2181
+ both, so the 45° diagonal really is 45°. That is the premise of Gann's angles and
2182
+ worthless if the shape skews with the axes. The cost is that the box no longer
2183
+ matches the drag exactly — "fixed" means fixed *proportion*, not fixed size.
2184
+
2185
+ ### Native wrapper parity
2186
+
2187
+ All five are new `DrawingToolType` strings, so `setDrawingTool('pitchfan')` works
2188
+ on [charts-android](../charts-android) and [charts-ios](../charts-ios) with no
2189
+ wrapper change.
2190
+
2191
+ ---
2192
+
2193
+ ## Cursors & Line Tools
2194
+
2195
+ ### Extending lines
2196
+
2197
+ Four tools that differ from a Trend Line only in where they stop being drawn —
2198
+ which is exactly why they exist as separate tools rather than a style option.
2199
+
2200
+ | Tool | `DrawingToolType` | What it does |
2201
+ | --- | --- | --- |
2202
+ | **Ray** | `'ray'` | Two anchors; continues past the second. |
2203
+ | **Extended Line** | `'extendedLine'` | Two anchors; continues past both. |
2204
+ | **Horizontal Ray** | `'horizontalRay'` | One click; a level that runs **forward only**. |
2205
+ | **Info Line** | `'infoLine'` | A trend line that permanently reports what it spans. |
2206
+
2207
+ ```ts
2208
+ chart.setDrawingTool('ray');
2209
+ ```
2210
+
2211
+ The extension is recomputed against the canvas every frame, so panning and
2212
+ zooming re-extend the line instead of dragging a stale endpoint around. Hit
2213
+ testing uses the *extended* segment, so the infinite part is clickable too — the
2214
+ user can grab what they can see. Anchor dots are drawn only at the anchors,
2215
+ never at the extended ends, because a dot at the canvas edge reads as a handle
2216
+ and there is nothing there to grab.
2217
+
2218
+ **Horizontal Ray vs Horizontal Line** is the one worth calling out: a level drawn
2219
+ from the swing high that formed it should not be painted back across the history
2220
+ that preceded it, because that implies support which did not yet exist.
2221
+
2222
+ **Info Line vs Ruler**: the Ruler is a transient measurement — drawn, read,
2223
+ discarded. An Info Line is a drawing you keep, so its readout travels with it and
2224
+ updates as either end is dragged. It reports price delta, percent, bar count,
2225
+ and — when `instrument` and bar timestamps are available — pips and calendar
2226
+ duration. Each is omitted rather than shown as a zero when it cannot be computed.
2227
+
2228
+ ### Cursors
2229
+
2230
+ Pointer behaviour over the plot, **independent of the drawing tool**: switching
2231
+ mode never cancels a drawing in progress, and arming a tool never changes the
2232
+ mode.
2233
+
2234
+ | `CursorMode` | Behaviour |
2235
+ | --- | --- |
2236
+ | `'cross'` | The default crosshair with its axis readouts. |
2237
+ | `'dot'` | A dot follows the pointer instead of two lines cutting across the candles. |
2238
+ | `'arrow'` | A plain pointer, no crosshair. |
2239
+ | `'demonstration'` | A laser trail that fades behind the pointer, for screen-sharing. Draws nothing permanent and creates no drawing. |
2240
+ | `'eraser'` | A click deletes the drawing under it. |
2241
+
2242
+ ```ts
2243
+ const chart = new ChartEngine({
2244
+ container,
2245
+ cursorMode: 'cross', // initial mode
2246
+ features: { enableCursorModes: true }, // adds the Cursors group to the toolbar
2247
+ });
2248
+
2249
+ chart.setCursorMode('eraser');
2250
+ chart.on('cursorModeChange', ({ mode }) => persist(mode));
2251
+ ```
2252
+
2253
+ `features.enableCursorModes` is a gate because it adds a **category** to a
2254
+ toolbar that hosts have laid out around its current contents. With it off the
2255
+ group is absent and the toolbar is exactly what it was — and the modes are still
2256
+ reachable from `setCursorMode()`, so a host can drive them from its own chrome
2257
+ without taking the group.
2258
+
2259
+ Two details worth knowing:
2260
+
2261
+ - **A drawing tool owns the cursor while armed.** It needs crosshair precision
2262
+ whatever the mode says; clearing the tool hands the cursor back to the mode.
2263
+ - **The eraser consumes every click**, hit or miss. A miss must not fall through
2264
+ to selecting or panning — that would be a surprising thing to do with an eraser
2265
+ in hand. It deletes via select-then-delete, so it shares the undo history with
2266
+ every other delete.
2267
+
2268
+ ### Value tooltip on long press
2269
+
2270
+ ```ts
2271
+ const chart = new ChartEngine({ container, valueTooltip: true });
2272
+ ```
2273
+
2274
+ A floating OHLCV readout beside a long press, on top of the crosshair that
2275
+ gesture already arms. The OHLC strip at the top of the chart carries the same
2276
+ numbers, but on a phone it is at the opposite end of the screen from the finger —
2277
+ the user has to look away from the thing they are pointing at.
2278
+
2279
+ It flips to the other side of the touch rather than running off an edge, never
2280
+ takes pointer events (the drag is still in progress), and omits volume rather
2281
+ than printing a zero when the feed carries none. Default `false`.
2282
+
2283
+ ### Native wrapper parity
2284
+
2285
+ The four line tools are new `DrawingToolType` strings, so `setDrawingTool('ray')`
2286
+ works on [charts-android](../charts-android) and [charts-ios](../charts-ios)
2287
+ unchanged.
2288
+
2289
+ | JS | Android | iOS |
2290
+ | --- | --- | --- |
2291
+ | `setCursorMode(m)` | `setCursorMode(m)` | `setCursorMode(_:)` |
2292
+ | `cursorModeChange` | `BridgeEvent.CursorModeChange` | `.cursorModeChange` |
2293
+ | `cursorMode` at init | `Init(cursorMode = "…")` | `cursorMode:` argument |
2294
+ | `valueTooltip` | `Init(valueTooltip = true)` | `valueTooltip:` argument |
2295
+ | `features.enableCursorModes` | `Init(enableCursorModes = true)` | `enableCursorModes:` argument |
2296
+
2297
+ ---
2298
+
2299
+ ## Chart Types
2300
+
2301
+ Thirteen time-based types plus five added for TradingView parity. The five split
2302
+ into two kinds, and the difference matters more than the list suggests.
2303
+
2304
+ ### HLC bars — `'hlc'`
2305
+
2306
+ An ordinary per-bar series: the high-low range with a close tick and no open
2307
+ stub. Halves the ink of an OHLC bar, which is the point — on a dense chart the
2308
+ closes stay legible where full bars smear. Colour still comes from open vs close.
2309
+
2310
+ ### Price-transform types — `'renko'`, `'linebreak'`, `'kagi'`, `'pointfigure'`
2311
+
2312
+ These are **not drawn per time bar.** A brick, block, kagi segment or P&F column
2313
+ forms when *price* moves far enough, which may take fifty bars or none at all.
2314
+ 365 daily candles might be 24 Renko bricks or 15 P&F columns.
2315
+
2316
+ So they are not renderers — the bar array itself is rebuilt. Each transform turns
2317
+ raw OHLCV into **synthetic** bars, one per visual element, which the rest of the
2318
+ chart then treats as ordinary bars. That is what keeps the feature small:
2319
+ viewport, zoom, price range, crosshair, the time axis, indicators and drawings
2320
+ all keep working unchanged. It also means **an indicator on a Renko chart is
2321
+ computed over the bricks**, not the underlying candles — same as TradingView.
2322
+
2323
+ Three consequences worth knowing:
2324
+
2325
+ - **The time axis is non-linear.** Labels show when each element *completed*.
2326
+ Several elements completing on one bar get timestamps one millisecond apart so
2327
+ drawing anchors and viewport restore keep working.
2328
+ - **Switching in or out refits the view**, because the old viewport indexes a
2329
+ different number of elements.
2330
+ - **Market price still comes off the raw feed.** Trade levels and P&L price
2331
+ against the real last close, never a brick top.
2332
+
2333
+ ### Parameters
2334
+
2335
+ ```ts
2336
+ const chart = new ChartEngine({
2337
+ container,
2338
+ series: 'renko',
2339
+ seriesOptions: {
2340
+ renko: { boxSize: { kind: 'atr', length: 14 } }, // the default
2341
+ lineBreak: { lines: 3 },
2342
+ kagi: { reversal: { kind: 'percent', percent: 2 } },
2343
+ pointFigure: { boxSize: { kind: 'fixed', size: 0.5 }, reversal: 3 },
2344
+ },
2345
+ });
2346
+
2347
+ chart.setSeriesOptions({ renko: { boxSize: { kind: 'fixed', size: 5 } } });
2348
+ ```
2349
+
2350
+ Every box/reversal size defaults to **ATR(14)**, not a fixed price, because a
2351
+ fixed box is meaningless until you know the instrument: ten points is noise on an
2352
+ index and a lifetime on a forex pair. `setSeriesOptions` merges, so retuning
2353
+ Renko leaves Kagi and P&F alone.
2354
+
2355
+ | `BoxSizeMode` | Meaning |
2356
+ | --- | --- |
2357
+ | `{ kind: 'atr', length }` | Wilder ATR over the last `length` bars. Default `14`. |
2358
+ | `{ kind: 'fixed', size }` | A fixed price distance. |
2359
+ | `{ kind: 'percent', percent }` | A percentage of the latest close. |
2360
+
2361
+ When a box cannot be sized — fewer than `length + 1` bars for the ATR, or a
2362
+ non-positive size — the transform returns **no elements** rather than guessing. A
2363
+ wrong box size does not look wrong; it looks like a different market.
2364
+
2365
+ ### The rules each type implements
2366
+
2367
+ | Type | Rule |
2368
+ | --- | --- |
2369
+ | **Renko** | A brick prints when price closes a full box past the last brick's edge. Reversals need **two** boxes, not one — that two-box rule is what filters the noise. `source: 'highlow'` lets a bar's extremes print bricks instead of its close. |
2370
+ | **Line Break** | A block prints when the close clears the extreme of the last `lines` blocks (default 3). No box size at all — the reversal distance is whatever recent blocks span, so it widens automatically in volatile stretches. |
2371
+ | **Kagi** | **Direction** flips on a retrace of the reversal amount. **Thickness** flips on a break of the prior shoulder or waist. These are independent: a line can reverse repeatedly without ever changing thickness. |
2372
+ | **Point & Figure** | Columns of X's and O's on a box grid, built from each bar's **high and low** — high first in an X column, low first in an O column, so a bar that both extended and reversed is read in the order it happened. A new column needs `reversal` boxes (default 3). |
2373
+
2374
+ ### Using the transforms off-chart
2375
+
2376
+ They are exported as pure functions, so a backtest or a server-side render gets
2377
+ byte-identical elements:
2378
+
2379
+ ```ts
2380
+ import { toRenko, toKagi, atrValue } from 'acttrader-charts';
2381
+
2382
+ const { bars, meta } = toRenko(ohlcv, { boxSize: { kind: 'fixed', size: 5 } });
2383
+ ```
2384
+
2385
+ Each returns `{ bars, meta }`. `meta[i]` carries what cannot be read off the
2386
+ synthetic bar: Kagi's `thick`, P&F's `boxSize`, and `sourceBars` / `startTime`
2387
+ for every type.
2388
+
2389
+ ### Native wrapper parity
2390
+
2391
+ The five types are new values of the same `series` string, so `setSeries('renko')`
2392
+ works on [charts-android](../charts-android) and [charts-ios](../charts-ios)
2393
+ unchanged. Parameters travel as a JSON object:
2394
+
2395
+ | JS | Android | iOS |
2396
+ | --- | --- | --- |
2397
+ | `seriesOptions` at init | `Init(seriesOptionsJson = "…")` | `seriesOptionsJson:` init argument |
2398
+ | `setSeriesOptions(o)` | `setSeriesOptions(json)` | `setSeriesOptions(_:)` |
2399
+
2400
+ ---
2401
+
2402
+ ## Top-Toolbar Features
2403
+
2404
+ Four opt-in features that bring the header in line with TradingView's: **indicator
2405
+ templates**, **saved chart layouts**, **Quick Search**, and **chart-settings
2406
+ templates with "Apply to all charts"**. Compare and Snapshot already shipped — see
2407
+ [Multi-Pane Layouts](#multi-pane-layouts) and the Compare section.
2408
+
2409
+ Two rules apply to all of them:
2410
+
2411
+ - **Nothing moves.** Every gate defaults to `false`, and with them off the chart's
2412
+ DOM is unchanged. When enabled, each feature extends a flyout, popover or dialog
2413
+ that already exists — no feature adds a header button (Quick Search can, but only
2414
+ if you ask for one).
2415
+ - **The library persists nothing.** Saving emits an event carrying the complete
2416
+ object; your app stores it and seeds it back. This is the same contract
2417
+ `stateChange` follows, and it is what lets Android and iOS reuse the feature
2418
+ without reimplementing storage twice.
2419
+
2420
+ ### Indicator templates
2421
+
2422
+ Named, reusable indicator sets, listed in a **Templates** block at the foot of the
2423
+ indicators flyout.
2424
+
2425
+ ```ts
2426
+ const chart = new ChartEngine({
2427
+ container,
2428
+ enableIndicatorTemplates: true,
2429
+ indicatorTemplates: loadFromStorage(), // what you saved last session
2430
+ });
2431
+
2432
+ chart.on('indicatorTemplateSaved', ({ template }) => persist(template));
2433
+ chart.on('indicatorTemplateDeleted', ({ id }) => forget(id));
2434
+ ```
2435
+
2436
+ | API | Does |
2437
+ | --- | --- |
2438
+ | `captureIndicatorTemplate(name)` | Saves the active indicators; emits `indicatorTemplateSaved`. Returns the template or `null`. |
2439
+ | `applyIndicatorTemplate(idOrName)` | Replaces the active indicators with the template's. Returns `false` if nothing matched. |
2440
+ | `deleteIndicatorTemplate(idOrName)` | Removes it; emits `indicatorTemplateDeleted`. |
2441
+ | `setIndicatorTemplates(list)` | Replaces the list the flyout shows. |
2442
+ | `getIndicatorTemplates()` | Reads it back (copies). |
2443
+
2444
+ Saving twice under one name yields two templates — ids are de-duplicated
2445
+ (`my-set`, `my-set-2`), which is what users expect from "Save as".
2446
+
2447
+ Rendered by the default `TopBar` and by `AdvancedToolbar`. The compact per-pane
2448
+ strip and the mobile header have no full indicators flyout, so they skip it.
2449
+
2450
+ ### Saved chart layouts
2451
+
2452
+ A **saved layout** is a grid preset *plus* every pane's full `ChartState` — symbol,
2453
+ timeframe, series, indicators, drawings, viewport, compares. That is the difference
2454
+ from the preset grid already in the layout popover, which only picks a *shape*.
2455
+
2456
+ Requires `enableMultipleLayouts`, since the section renders inside that popover.
2457
+
2458
+ ```ts
2459
+ const chart = new ChartEngine({
2460
+ container,
2461
+ enableMultipleLayouts: true,
2462
+ enableSavedLayouts: true,
2463
+ savedLayouts: loadFromStorage(),
2464
+ });
2465
+
2466
+ chart.on('layoutSaved', ({ layout }) => persist(layout));
2467
+ chart.on('layoutApplied', ({ layout }) => mountPanes(layout)); // multi-pane hosts
2468
+ ```
2469
+
2470
+ | API | Does |
2471
+ | --- | --- |
2472
+ | `captureSavedLayout(name, paneId?)` | Saves the preset + this chart's state. Single-engine: one pane. |
2473
+ | `applySavedLayout(idOrName, paneId?)` | Applies the preset (emits `layoutChange`) then this pane's state. |
2474
+ | `deleteSavedLayout(idOrName)` | Removes it; emits `layoutDeleted`. |
2475
+ | `setSavedLayouts(list)` / `getSavedLayouts()` | Replace / read the list. |
2476
+
2477
+ For a real multi-pane grid use `ChartGroup`, which sees every pane:
2478
+
2479
+ ```ts
2480
+ const layout = group.captureLayout('My Desk', chart.getLayoutPreset());
2481
+ persist(layout);
2482
+ for (const [, engine] of group.entries()) engine.setSavedLayouts(allLayouts);
2483
+
2484
+ // restoring: mount the grid for layout.presetId yourself, then
2485
+ const { applied, missing } = group.applyLayout(layout);
2486
+ ```
2487
+
2488
+ `applyLayout` skips panes that aren't registered yet and returns them in `missing`,
2489
+ so a host that mounts lazily can create them and call again. Registered panes that
2490
+ the layout doesn't mention are left alone rather than cleared.
2491
+
2492
+ ### Quick Search
2493
+
2494
+ A command palette over everything the chart can do: series types, timeframes,
2495
+ durations, indicators, drawing tools, saved templates and layouts, and the header
2496
+ actions.
2497
+
2498
+ ```ts
2499
+ const chart = new ChartEngine({ container, enableQuickSearch: true });
2500
+ ```
2501
+
2502
+ Opened with **Ctrl/⌘+K**, with **`/`**, or by `chart.openQuickSearch()`. It is
2503
+ keyboard-first and **adds no header button** — pass
2504
+ `quickSearch: { showButton: true }` if you want one. A bare `/` is ignored while
2505
+ the user is typing in any input, textarea, select, or contenteditable.
2506
+
2507
+ Add your own commands beside the built-ins:
2508
+
2509
+ ```ts
2510
+ chart.registerCommand({
2511
+ id: 'myapp.openTicket',
2512
+ label: 'Open order ticket',
2513
+ group: 'My App',
2514
+ keywords: ['buy', 'sell', 'trade'],
2515
+ run: () => openTicket(),
2516
+ });
2517
+
2518
+ chart.on('quickSearchCommand', ({ id }) => track(id));
2519
+ ```
2520
+
2521
+ Namespace your ids so a future built-in can't collide. `matchCommands`,
2522
+ `scoreCommand` and `groupCommands` are exported if you want the same ranking in
2523
+ your own UI: exact label beats prefix beats word-start beats substring, with
2524
+ keyword and group hits last, and ties keep their original order so the list never
2525
+ reshuffles unpredictably as the user types.
2526
+
2527
+ ### Chart-settings templates + Apply to all charts
2528
+
2529
+ Named snapshots of everything the Chart Settings dialog edits, plus a switch to
2530
+ push the current settings to every other chart. Both render in the dialog's
2531
+ footer — no new button anywhere.
2532
+
2533
+ ```ts
2534
+ const chart = new ChartEngine({
2535
+ container,
2536
+ enableSettingsTemplates: true,
2537
+ settingsTemplates: loadFromStorage(),
2538
+ });
2539
+
2540
+ chart.on('settingsTemplateSaved', ({ template }) => persist(template));
2541
+
2542
+ chart.on('chartSettingsApplied', ({ settings, applyToAll }) => {
2543
+ // This chart already applied them. Only the fan-out is yours:
2544
+ if (applyToAll) group.applySettingsToAll(settings, thisPaneId);
2545
+ });
2546
+ ```
2547
+
2548
+ | API | Does |
2549
+ | --- | --- |
2550
+ | `getChartSettings()` / `applyChartSettings(s)` | Read / apply a settings snapshot. Every route — dialog, template, apply-to-all, bridge — goes through `applyChartSettings`. |
2551
+ | `captureSettingsTemplate(name)` | Saves the current settings; emits `settingsTemplateSaved`. |
2552
+ | `applySettingsTemplate(idOrName)` | Applies a saved one. |
2553
+ | `deleteSettingsTemplate(idOrName)` | Removes it. |
2554
+ | `setSettingsTemplates(list)` / `getSettingsTemplates()` | Replace / read the list. |
2555
+ | `ChartGroup.applySettingsToAll(settings, fromPaneId?)` | Applies to every other pane. Not gated on a `sync` toggle — it is an explicit one-shot action, not continuous mirroring. |
2556
+
2557
+ ### Native wrapper parity
2558
+
2559
+ All four features, plus snapshot capture, are exposed by
2560
+ [charts-android](../charts-android) and [charts-ios](../charts-ios). Templates and
2561
+ layouts cross the bridge as opaque JSON strings: the app stores what the chart
2562
+ handed it and sends the same string back, so neither Kotlin nor Swift has to mirror
2563
+ a `ChartState` that only the chart interprets.
2564
+
2565
+ | JS | Android | iOS |
2566
+ | --- | --- | --- |
2567
+ | `enableIndicatorTemplates` | `Init(enableIndicatorTemplates = true)` | `HeaderFeatures(enableIndicatorTemplates: true)` |
2568
+ | `captureIndicatorTemplate(name)` | `captureIndicatorTemplate(name)` | `captureIndicatorTemplate(_:)` |
2569
+ | `enableSavedLayouts` | `Init(enableSavedLayouts = true)` | `HeaderFeatures(enableSavedLayouts: true)` |
2570
+ | `enableQuickSearch` / `openQuickSearch()` | `openQuickSearch()` | `openQuickSearch()` |
2571
+ | `enableSettingsTemplates` | `Init(enableSettingsTemplates = true)` | `HeaderFeatures(enableSettingsTemplates: true)` |
2572
+ | `chartSettingsApplied` event | `BridgeEvent.ChartSettingsApplied` | `.chartSettingsApplied` |
2573
+ | `chart.toDataUrl()` | `requestSnapshot()` → `BridgeEvent.Snapshot` | `requestSnapshot()` → `.snapshot` |
2574
+
2575
+ On mobile there is no Ctrl/⌘+K, so Quick Search is opened with the
2576
+ `openQuickSearch` command from your own toolbar.
2577
+
2578
+ ---
2579
+
2580
+ ## Chart Settings
2581
+
2582
+ Six settings TradingView has and ActCharts did not, behind
2583
+ `features.enableChartSettings`. The gate adds three tabs — **Status Line**,
2584
+ **Scales**, **Canvas** — to the Chart Settings dialog and a bar-colouring choice
2585
+ to Appearance. Every one of them is also a `ChartConfig` option and a
2586
+ `ChartEngine` method, so a host can drive them from its own chrome and leave the
2587
+ dialog as it was.
2588
+
2589
+ ```ts
2590
+ const chart = new ChartEngine({
2591
+ container,
2592
+ features: { enableChartSettings: true },
2593
+ statusLine: { barChange: true },
2594
+ scales: { highLowLabels: true, pricePrecision: 4, timezone: 'Asia/Tokyo' },
2595
+ canvas: { gridVertical: false, watermarkVisible: true },
2596
+ barColorSource: 'previousClose',
2597
+ });
2598
+ ```
2599
+
2600
+ ### Status line
2601
+
2602
+ What the legend above the chart shows.
2603
+
2604
+ | Field | Default | Shows |
2605
+ | --- | --- | --- |
2606
+ | `symbol` | `true` | The instrument name and its stream dot |
2607
+ | `ohlc` | `true` | O / H / L / C of the hovered bar |
2608
+ | `barChange` | **`false`** | Absolute and percent change, e.g. `+1.68 (+0.96%)` |
2609
+ | `volume` | `true` | V, when the feed carries it |
2610
+
2611
+ `barChange` is the one default of `false`: it is a new readout, and turning it on
2612
+ by itself would change a legend hosts have laid out around. **Change is measured
2613
+ against the previous bar's close**, which is what "the change" means on every
2614
+ quote screen — against this bar's open it would only restate the candle's colour.
2615
+
2616
+ ### Scales and lines
2617
+
2618
+ ```ts
2619
+ chart.setScalesSettings({ lastPriceLabel: false, highLowLabels: true });
2620
+ ```
2621
+
2622
+ | Field | Default | Effect |
2623
+ | --- | --- | --- |
2624
+ | `lastPriceLabel` | `true` | The live price tag and its dashed line |
2625
+ | `bidLabel` / `askLabel` | follows config | The bid / ask tags |
2626
+ | `highLowLabels` | `false` | Tags at the extremes of the **visible** range |
2627
+ | `timeAxisCountdown` | follows `showCandleCountdown` | Countdown on the time axis |
2628
+ | `pricePrecision` | `null` | Decimal places; null infers from the feed |
2629
+ | `timezone` | `'UTC'` | IANA name for axis, crosshair and tooltips |
2630
+
2631
+ Bid and ask fall through to the `showBidLine` / `showAskLine` config they
2632
+ duplicate, so the dialog and the existing runtime setters stay **one switch**
2633
+ rather than two that can disagree.
2634
+
2635
+ High/low are measured over what is on screen, not the whole dataset: a tag for a
2636
+ high six months out of view marks a line the user cannot see and cannot scroll
2637
+ to without losing it.
2638
+
2639
+ ### Price precision
2640
+
2641
+ ```ts
2642
+ chart.setPricePrecision(4); // pin
2643
+ chart.setPricePrecision(null); // back to inferring from the feed
2644
+ ```
2645
+
2646
+ One accessor feeds all eleven places the chart writes a price — axis, legend,
2647
+ tooltips, crosshair, drawings, trade levels — so an override cannot apply to
2648
+ some and not others. A price axis reading `1.2345` beside a tooltip reading
2649
+ `1.23` is worse than either choice on its own.
2650
+
2651
+ **It deliberately does not move pip size.** A pip is a property of the contract;
2652
+ asking the axis for fewer decimals is a display choice, and the Ruler must keep
2653
+ saying what a move is actually worth. Pip size still comes from `InstrumentSpec`
2654
+ and, failing that, from the precision *inferred* from the data.
2655
+
2656
+ ### Timezone
2657
+
2658
+ `setTimezone(tz)` already existed; it is now in the dialog, carried in
2659
+ `ChartSettingsSnapshot`, and emits `timezoneChange`. `'local'` resolves to the
2660
+ device zone immediately, so `getTimezone()` always returns a real IANA name.
2661
+
2662
+ ### Canvas
2663
+
2664
+ ```ts
2665
+ chart.setCanvasOptions({ gridVertical: false, watermarkVisible: true, watermarkSize: 128 });
2666
+ ```
2667
+
2668
+ | Field | Default |
2669
+ | --- | --- |
2670
+ | `gridHorizontal` / `gridVertical` | `true` |
2671
+ | `watermarkVisible` | `false` |
2672
+ | `watermarkText` | `''` — empty uses the current symbol |
2673
+ | `watermarkSize` / `watermarkOpacity` | `72` / `0.06` |
2674
+ | `crosshairStyle` | `'dashed'` |
2675
+ | `crosshairWidth` | `1` |
2676
+
2677
+ Colours stay in `setCanvasColors`, which was already plumbed per theme;
2678
+ `gridVertical` and `watermark` are new entries in `CanvasColorSettings` and fall
2679
+ back to `grid` and `axisText`.
2680
+
2681
+ **The watermark draws above the grid and below everything else.** Painted after
2682
+ the series it would tint the candles, and the point of it is to sit behind them.
2683
+ Crosshair dash lengths scale with the width, or a 4px dash on a 4px line reads as
2684
+ a solid bar.
2685
+
2686
+ ### Colour bars based on previous close
2687
+
2688
+ ```ts
2689
+ chart.setBarColorSource('previousClose');
2690
+ ```
2691
+
2692
+ Whether a bar is "up" against its own open (the default) or against the previous
2693
+ bar's close. The two disagree constantly — a gap-up bar that sells off all
2694
+ session is up on one rule and down on the other — which is why it is a setting
2695
+ and not a fix.
2696
+
2697
+ Applies to candles, hollow candles, bars, HLC bars, columns **and the volume
2698
+ pane together**: they are one reading of the same market, and a volume pane
2699
+ disagreeing with the candles above it is a bug, not a setting. Heikin Ashi,
2700
+ Renko, Kagi and Point & Figure are unaffected — direction is intrinsic to what
2701
+ those transforms compute.
2702
+
2703
+ Eight series each carried their own `close >= open`; they now share
2704
+ `computeUpFlags()`, which the engine calls once per frame. It takes the bar
2705
+ *before* the visible slice, because the renderers only ever see what is on
2706
+ screen — without it the leftmost bar would have nothing to compare against and
2707
+ would flip colour as the user panned it into view. At the very start of the data,
2708
+ where no earlier bar exists, that one bar falls back to open-vs-close.
2709
+
2710
+ ### Persistence
2711
+
2712
+ All six ride in `ChartSettingsSnapshot`, so they are covered by settings
2713
+ templates and "Apply to all charts" for free. **Absent is meaningful**: a
2714
+ template saved before these fields existed applies as "change nothing", not as
2715
+ "reset everything to its default" — otherwise re-applying an old template would
2716
+ silently rearrange the chart.
2717
+
2718
+
2719
+ ## Bottom Bar & Price Scale
2720
+
2721
+ Five TradingView controls, behind `features.enableScaleControls`. The gate adds
2722
+ a cluster to the left of the duration buttons — **Go to date**, a **timezone**
2723
+ selector, and **%**, **log**, **auto** — and needs `showBottomBar: true`, since
2724
+ the duration bar is off by default. Each is also a `ChartEngine` method, so a
2725
+ host can drive them from its own chrome and leave the bar as it was.
2726
+
2727
+ ```
2728
+ ┌──────────────────────────────────────────────────────────────────────┐
2729
+ │ 📅 │ UTC ⌄ │ % log auto 1D 5D 1M 3M 6M 1Y 5Y All │
2730
+ └──────────────────────────────────────────────────────────────────────┘
2731
+ ```
2732
+
2733
+ All five are ordinary buttons styled like the duration buttons beside them, and
2734
+ the two that need input open a themed popover above the bar. **No native
2735
+ `<input type="date">` or `<select>`**: both take their colours from the
2736
+ operating system, so in a dark chart they rendered as pale boxes with a browser
2737
+ calendar glyph — the one part of the bar that could not be themed. The menus
2738
+ open *upward*, since the bar is the last row on screen.
2739
+
2740
+ ```ts
2741
+ const chart = new ChartEngine({
2742
+ container,
2743
+ showBottomBar: true,
2744
+ features: { enableScaleControls: true },
2745
+ priceScaleMode: 'log',
2746
+ autoScale: true,
2747
+ });
2748
+ ```
2749
+
2750
+ ### Go to a specific date
2751
+
2752
+ ```ts
2753
+ chart.goToDate('2024-03-01'); // ISO, a Date, or unix ms
2754
+ ```
2755
+
2756
+ The calendar button opens a date field and a **Go**; the method behind it
2757
+ centres the **nearest** bar and returns its index, or `null` when there is no
2758
+ data. Nearest rather than exact because the date a user types is rarely a bar —
2759
+ it falls on a weekend, a holiday, or between two intraday bars — and refusing to
2760
+ move is a worse answer than landing beside it. Binary search, so it costs
2761
+ nothing on a long history. Emits `goToDate` with the bar it settled on.
2762
+
2763
+ ### Timezone selector
2764
+
2765
+ The bottom-bar button shows the current zone's short name and opens a checked
2766
+ list. It writes through `setTimezone()`, the same path the Scales tab and the
2767
+ config option use, so all three stay in step. `'local'` resolves to
2768
+ the device zone immediately — `getTimezone()` always returns a real IANA name.
2769
+
2770
+ ### Price scale modes
2771
+
2772
+ ```ts
2773
+ chart.setPriceScaleMode('log'); // 'normal' | 'log' | 'percent'
2774
+ ```
2775
+
2776
+ **One choice, not three flags.** Log and percent are different answers to the
2777
+ same question, and a chart in both at once has no meaning. Clicking the active
2778
+ button returns to `'normal'`, so the pair works as a toggle rather than a trap.
2779
+
2780
+ #### Logarithmic
2781
+
2782
+ Equal ratios get equal height: a move from 10 to 20 occupies the same space as
2783
+ one from 100 to 200. On a series running 1 → 1000 the pixel gaps between the
2784
+ decade marks go from **49.8px and 497.3px** linear to **156.4px and 156.4px**
2785
+ log, and an exponential series renders as a straight line.
2786
+
2787
+ The mode is carried on the **`PriceRange`**, not on the `ScaleManager`:
2788
+
2789
+ ```ts
2790
+ interface PriceRange { min: number; max: number; log?: boolean }
2791
+ ```
2792
+
2793
+ One manager serves the price pane and every sub-pane, and an RSI drawn on a log
2794
+ axis would be nonsense. Every price→pixel call already passes a range, so putting
2795
+ the flag there made series, drawings, indicators, the crosshair and hit-testing
2796
+ all log-aware **without changing a single call site**.
2797
+
2798
+ **Log needs a positive range.** `isLogRange()` falls back to linear when `min <= 0`
2799
+ rather than refusing to draw, so an instrument that trades through zero quietly
2800
+ keeps working. A manual zoom-out that drags the displayed minimum below zero is
2801
+ clamped instead, because falling back there would make the chart snap between two
2802
+ mappings in the middle of a drag.
2803
+
2804
+ **Ticks are the 1/2/5 × 10ⁿ series per decade**, thinned by *pixel* distance
2805
+ rather than by value — a decade occupies the same height whether it runs 1→10 or
2806
+ 1000→10000. A range inside a single decade falls back to the linear generator,
2807
+ since over a span that narrow the two mappings are within a pixel of each other
2808
+ and linear ticks read better.
2809
+
2810
+ Label precision is computed **per tick** from its own neighbours. One precision
2811
+ taken from the first pair would render `500` as `500.0` and `0.2` as `0.2` in the
2812
+ same column.
2813
+
2814
+ #### Percent
2815
+
2816
+ Every price re-expressed as percent change from the first visible bar's close,
2817
+ with `+0.00%` emphasised on the axis. It reuses the transform compare mode
2818
+ already had, with no second series to combine against, so panning re-bases the
2819
+ way TradingView's percent scale does rather than pinning to the start of history.
2820
+
2821
+ ### Auto scale
2822
+
2823
+ ```ts
2824
+ chart.setAutoScale(false); // freeze the Y range
2825
+ ```
2826
+
2827
+ Switching it off freezes whatever is on screen *now*, so the chart does not jump
2828
+ at the moment the user asks it to stop moving. A manual axis drag still wins —
2829
+ turning auto off should not also take away the ability to move the axis by hand.
2830
+
2831
+ This is separate from the implicit manual mode a price-axis drag already
2832
+ produced: that one is entered by dragging and left by resetting, while this is a
2833
+ switch the user holds across pans and timeframe changes.
2834
+
2835
+
2836
+ ## Side Panels
2837
+
2838
+ A right-hand docked panel with two tabs, behind `features.enableSidePanels`.
2839
+
2840
+ ```
2841
+ ┌──────────────────────────┐
2842
+ │ Data Window │ Objects │✕ │
2843
+ ├──────────────────────────┤
2844
+ │ Date 12 Aug 2026│
2845
+ │ Open 149.73│
2846
+ │ Close 148.56│
2847
+ │ Change -1.17 (-0.78%) │
2848
+ │ MA(20) 150.56│
2849
+ │ MACD(12, 26, 9) │
2850
+ │ MACD 1.22│
2851
+ │ Signal 1.84│
2852
+ │ Histogram -0.62│
2853
+ └──────────────────────────┘
2854
+ ```
2855
+
2856
+ ```ts
2857
+ const chart = new ChartEngine({
2858
+ container,
2859
+ features: { enableSidePanels: true },
2860
+ });
2861
+
2862
+ chart.setSidePanelTab('objects');
2863
+ chart.setSidePanelVisible(false); // the ✕ does this too
2864
+ ```
2865
+
2866
+ The panel is **docked, not floating**: both tabs are read while looking at the
2867
+ chart, and a floating window would cover the candles the numbers describe.
2868
+
2869
+ **Closing it collapses it to an icon rail, it does not hide it.**
2870
+
2871
+ ```
2872
+ expanded (232px) collapsed (30px)
2873
+ ┌──────────────────┐ ┌──┐
2874
+ │ Data │ Objects │✕│ │ ▦ │ ← Data Window
2875
+ ├──────────────────┤ │ ◈ │ ← Objects
2876
+ │ … │ │ │
2877
+ └──────────────────┘ └──┘
2878
+ ```
2879
+
2880
+ A panel that vanished completely would leave nothing to click to get it back,
2881
+ stranding the feature behind a command palette. The rail keeps 30px and gives
2882
+ the chart the other 202px; the `ResizeObserver` already watching `canvasWrap`
2883
+ resizes the canvases for free. Each rail icon opens straight onto *its* tab
2884
+ rather than reopening whatever was last showing, and the last-opened one stays
2885
+ marked so reopening is a single click on the icon already highlighted.
2886
+
2887
+ `setSidePanelVisible(false)` is the same operation as the ✕ — expanded versus
2888
+ rail. `features.enableSidePanels` is what removes the panel entirely.
2889
+
2890
+ ### Data Window
2891
+
2892
+ The bar under the cursor — or the last bar when the cursor is off the plot —
2893
+ followed by one block per visible indicator, refreshed from the render pass so
2894
+ it coalesces with the animation frame instead of firing on every pointer event.
2895
+
2896
+ Values come from the engine's existing per-instance result cache, which is a
2897
+ full-length array indexed by bar, so nothing is recomputed to fill the panel.
2898
+ Only indicators that are actually being recomputed are listed: a hidden or
2899
+ timeframe-locked instance holds a stale cache and showing it would present old
2900
+ numbers as current.
2901
+
2902
+ **Indicator fields are named by what they are.** `IndicatorResult` has five
2903
+ fixed slots — `value`, `upper`, `lower`, `signal`, `histogram` — and indicators
2904
+ do not agree on what they mean. MACD puts its signal line in `upper` and its
2905
+ histogram in `lower`, where Bollinger puts bands in both, so labelling the slots
2906
+ generically would print `Upper 1.84` for a MACD signal. A small table names the
2907
+ ones that differ; everything else falls back.
2908
+
2909
+ A single-line indicator renders as one `MA(20): 150.56` row rather than a
2910
+ heading with one orphan beneath it. One still warming up shows a dash, because
2911
+ omitting the block would read as the indicator having been removed.
2912
+
2913
+ Rows use tabular figures so the value column does not jitter as digits change
2914
+ under a moving crosshair, and the panel **reconciles rather than rebuilds** —
2915
+ it keys on the row labels and, when they are unchanged, writes only the text.
2916
+
2917
+ ### Object Tree
2918
+
2919
+ Everything on the chart, grouped, with per-row show/hide, lock and remove.
2920
+ Clicking a drawing row selects it; clicking an indicator row opens its settings.
2921
+ Empty groups are omitted rather than shown as a zero.
2922
+
2923
+ Drawing names come from `labels.drawingToolbar.tools` — the toolbar's own label
2924
+ map, so the tree is localised by the same override a host already supplies. A
2925
+ text tool shows its first line beside the type name, clipped, since a Table or
2926
+ Note carries several and the rest would push every other row off the panel.
2927
+
2928
+ Indicators get **no lock control**: there is nothing to lock. The panel reads an
2929
+ absent `locked` as exactly that rather than needing a flag.
2930
+
2931
+ ### New per-object primitives
2932
+
2933
+ The manager only had bulk operations, so these are new:
2934
+
2935
+ ```ts
2936
+ chart.setDrawingVisible(id, false);
2937
+ chart.setDrawingLocked(id, true);
2938
+ chart.deleteDrawing(id); // not "select it, then delete"
2939
+ chart.selectDrawing(id); // null clears
2940
+ chart.toggleIndicatorVisibility(instanceId);
2941
+ ```
2942
+
2943
+ `deleteDrawing` is separate from `deleteSelected()` on purpose: selecting fires
2944
+ `onSelectionChange`, which opens the style popover on a drawing that is about to
2945
+ disappear. Hiding or locking the selected drawing deselects it, the way the bulk
2946
+ operations already did — a selection box floating over nothing, with a popover
2947
+ attached, is worse than losing the selection. All three take an undo snapshot.
2948
+
2949
+ ### Reopening
2950
+
2951
+ Click either rail icon. Three Quick Search commands do the same from the
2952
+ keyboard: **Open Data Window**, **Open Object Tree**, **Toggle side panel**.
2953
+
2954
+ ### Rendering the data yourself
2955
+
2956
+ `buildDataWindow()` and `buildObjectTree()` are exported as pure functions, and
2957
+ `SidePanel` takes their output. A host can render the same rows in its own
2958
+ chrome, or feed the panel from somewhere other than the chart.
2959
+
2960
+
2961
+ ## Custom Indicator
2962
+
2963
+ Implement `IIndicator` and pass it to `addIndicator()`:
2964
+
2965
+ ```ts
2966
+ import type { IIndicator, OHLCVBar, IndicatorResult } from 'acttrader-charts';
2967
+
2968
+ class MyIndicator implements IIndicator {
2969
+ name = 'MyInd';
2970
+ color = '#e91e63';
2971
+ pane = 'sub' as const; // 'main' = overlay, 'sub' = dedicated pane
2972
+ paneHeight = 80;
2973
+
2974
+ compute(data: OHLCVBar[]): IndicatorResult[] {
2975
+ return data.map((bar, i) => ({ index: i, value: bar.close }));
2976
+ }
2977
+
2978
+ render(ctx, results, scale, viewport, chartHeight) {
2979
+ // draw with ctx (Canvas 2D)
2980
+ }
2981
+ }
2982
+
2983
+ chart.addIndicator(new MyIndicator());
2984
+ ```
2985
+
2986
+ ---
2987
+
2988
+ ## Build & Dev
2989
+
2990
+ ```bash
2991
+ npm run dev # Vite dev server with demo chart
2992
+ npm run build # ESM + CJS via tsup → dist/
2993
+ npm run test # Vitest unit tests
2994
+ npm run typecheck # tsc --noEmit
2995
+ npm run lint # ESLint
2996
+ ```
2997
+
2998
+ ---
2999
+
3000
+ ## License
3001
+
3002
+ MIT
3003
+
3004
+ ## Bar Replay
3005
+
3006
+ Replay history bar by bar, as TradingView does. `enableReplay: true` adds a
3007
+ **Replay** button to the header (simple and advanced layouts); it opens a
3008
+ control strip under the chart:
3009
+
3010
+ ```
3011
+ ⇤ Select bar ▾ │ ▷ ▷| 1x 1D │ ▷▷| ✕
3012
+ ```
3013
+
3014
+ - **Select bar** — a cut line with a scissors badge follows the pointer; click
3015
+ a bar and everything from it onward is hidden. The ▾ menu also offers
3016
+ **Select date…**, **First available date** and **Random bar**.
3017
+ - **▷ / ▷|** — play at the chosen speed (`0.1x` – `10x` bars per second) or
3018
+ step one bar forward. Keyboard: `Shift+→` step, `Shift+↓` play/pause,
3019
+ `Esc` leaves select mode.
3020
+ - **▷▷|** — jump to real time: every hidden bar comes back, including live
3021
+ bars built while the replay ran. **✕** closes the strip.
3022
+
3023
+ Live ticks keep updating the hidden series during a replay, so nothing is
3024
+ lost; a `loadData()` during a replay (timeframe or symbol change) keeps the
3025
+ replay date. Default `false`; without it nothing changes.
3026
+
3027
+ ```ts
3028
+ const chart = new ChartEngine({ container, enableReplay: true });
3029
+
3030
+ // Drive it from code (works without the header button too):
3031
+ chart.openReplay(); // show the strip, arm "Select bar"
3032
+ chart.startReplay('2026-06-01'); // hide bars after this date (number | Date | string)
3033
+ chart.setReplaySpeed(3); // bars per second
3034
+ chart.playReplay(); chart.pauseReplay(); chart.replayStepForward();
3035
+ chart.exitReplay(); // back to real time, strip stays open
3036
+ chart.closeReplay(); // back to real time and close the strip
3037
+ chart.isReplayActive();
3038
+
3039
+ chart.on('replayStart', ({ time }) => { /* bars after `time` are hidden */ });
3040
+ chart.on('replayStep', ({ time }) => { /* one more bar revealed */ });
3041
+ chart.on('replayEnd', ({ time }) => { /* last hidden bar revealed */ });
3042
+ chart.on('replayExit', () => { /* live chart is back */ });
3043
+ ```
3044
+
3045
+ On Android and iOS the same controls are bridge commands — `openReplay`,
3046
+ `closeReplay`, `startReplay { time }`, `playReplay`, `pauseReplay`,
3047
+ `replayStepForward`, `setReplaySpeed { barsPerSecond }`, `exitReplay` — with
3048
+ `enableReplay` on `init`; the four events above arrive through the bridge and the
3049
+ mobile header gets its own Replay button. See the `charts-android` and
3050
+ `charts-ios` READMEs for the Kotlin / Swift calls.
3051
+
3052
+ ## Two-finger measure (mobile)
3053
+
3054
+ Hold two fingers on the chart and it shows what the TradingView app shows: a
3055
+ pill over the range with the **close and date under each finger** and, between
3056
+ them, the **change in price and percent**, coloured by direction; a vertical
3057
+ line and a dot on the close mark each finger and the range is tinted. Moving
3058
+ the fingers moves the measurement; lifting either finger ends it. Pinch still
3059
+ zooms — the measure only starts once both fingers have rested for ~0.3 s.
3060
+
3061
+ ```ts
3062
+ new ChartEngine({ container, enableTwoFingerMeasure: true });
3063
+
3064
+ chart.on('twoFingerMeasure', ({ phase, startTime, endTime, startClose, endClose, change, changePercent, bars }) => {
3065
+ // phase: 'start' | 'update' | 'end'
3066
+ });
3067
+ ```
3068
+
3069
+ Touch-only, so desktop is unaffected. Default `false`. On Android / iOS set
3070
+ `enableTwoFingerMeasure` on `init`; the event arrives through the bridge.