@trdrs/quickcharts
v5.12.0
Published
Quick Charts: a datafeed-driven charting library with drawings, indicators, layouts and replay over host-supplied data and storage ports.
Maintainers
Readme
@trdrs/quickcharts
Quick Charts is a datafeed-driven charting library with drawings, indicators, layouts and replay.
It draws over the datafeed and the storage you supply: the chart consumes the ChartDatafeed
interface, so your feed drives it without a change to the chart.
Install
npm install @trdrs/quickchartsSupported npm versions automatically install the required renderer. You do not need to name
another package in the install command. Quick Charts ships ESM and TypeScript declarations.
From a CommonJS host, load it through dynamic import().
The renderer remains a required lightweight-charts 5 peer so compatible consumers share one
runtime. Use default peer resolution; do not suppress peer checks.
Quick Charts is licensed under the Apache License 2.0: see LICENSE and NOTICE. Because the
renderer is your dependency, its own Apache-2.0 NOTICE
obligations attach to your bundle: THIRD-PARTY-NOTICES.md in this package spells out exactly
what to carry and how. An application composes its own features on the chart through the extension
seam below.
Quickstart, the smallest working chart (see The widget for the full options). The stylesheet import is not optional: it carries the chart's layout as well as its look, and without it the chart has no size and paints nothing.
import '@trdrs/quickcharts/styles.css'
import { createChart, createUdfDatafeed } from '@trdrs/quickcharts'
const widget = createChart({
container,
datafeed: createUdfDatafeed({ baseUrl: 'https://feed.example.com/udf' }),
})
await widget.ready()The datafeed contract
Implement ChartDatafeed (see datafeed.ts). Required methods: search, resolve, history,
subscribeBars. Optional: serverTime (countdown skew correction) and config (a feed-level
capability declaration, described below). The datafeed serves
symbol metadata, bars and bar updates.
subscribePrices(symbol, { onPrices }), also optional, serves the prices one symbol stands at
(SymbolPrices: bid, ask, last, and previousClose or the change since it) and returns the
unsubscribe. A delivery may carry only what moved; a field it leaves out keeps its last value. The
chart subscribes only while a setting draws the prices: the bid and ask labels and lines, the
legend's change since the previous close, the previous close's label and line, and the percentage
under the last value. Without the port the bid and ask draw nothing, and the previous close is the
last regular-hours close of the trading day before the newest bar's, read off the bars.
import type { ChartDatafeed, SymbolPrices } from '@trdrs/quickcharts'
declare const feed: ChartDatafeed
declare function onBook(symbol: string, push: (prices: SymbolPrices) => void): () => void
const withPrices: ChartDatafeed = {
...feed,
subscribePrices: (symbol, { onPrices }) => onBook(symbol, onPrices),
}While the priceLabels.countdown setting is on, as it is by default, a live streaming time bar
replaces the native last-value label with one price-and-time label. The price uses the resolved symbol formatter. Replay, stale,
delayed or end-of-day data, tick bars, closed declared sessions and missing bars retain the native
price label. serverTime corrects clock skew when available; absence or failure uses the client
clock. Bar opens define fixed and calendar alignment, and declared session facts shorten only a
bar they actually close. Under priceLabels.symbolValueMode: 'priceAndPercent' the same label
writes the change since the previous session's close under the price, two decimals and its sign,
with the countdown beneath that; each line is 14px below the one before at the 12px text size.
resolve answers with SymbolInfo, the symbology contract (Symbology): the
symbol's identity (ticker, name, description), venue and type (exchange,
listedExchange, type), supportedResolutions (chart timeframe tokens; an empty list declares
no restriction), the exchange session triple (timezone, session, sessionHolidays),
dataStatus, currencyCode or unitId, volumePrecision, and the price-format facts in
format. Null means the symbol is unknown to your catalogs.
import type { SymbolInfo } from '@trdrs/quickcharts'
const treasury: SymbolInfo = {
ticker: 'ZBZ2026',
name: 'ZBZ2026',
description: '30-year T-bond Dec 2026',
exchange: 'CBOT',
listedExchange: 'CBOT',
type: 'futures',
supportedResolutions: [], // no restriction: any timeframe token
timezone: 'America/Chicago',
session: '1700-1600:23456',
dataStatus: 'streaming',
currencyCode: 'USD',
volumePrecision: 0,
format: { pricescale: 32, minmov: 1, fractional: true },
}
void treasuryimport type { ChartDatafeed, FeedBar } from '@trdrs/quickcharts'
export const myFeed: ChartDatafeed = {
async search(query, opts) {
const rows = await myBackend.search(query, opts?.cls, opts?.limit ?? 50, opts?.offset ?? 0)
return { hits: rows.hits, hasMore: rows.hasMore } // hasMore is EXACT, never a page-boundary guess
},
async resolve(symbol) {
return (await myBackend.symbolInfo(symbol)) ?? null // null = unknown symbol (a data answer)
},
async history(symbol, tf, range) {
const page = await myBackend.bars(symbol, tf, range?.from, range?.to, range?.countBack)
return { bars: page.bars, noData: page.endOfHistory } // noData ONLY on a countBack ask
},
subscribeBars(symbol, tf, handlers) {
const stream = myBackend.stream(symbol, tf)
stream.onSnapshot((bars: FeedBar[]) => handlers.onBars({ kind: 'snapshot', bars })) // on connect AND every reconnect
stream.onBar((bar: FeedBar) => handlers.onBars({ kind: 'bar', bar }))
return () => stream.close()
},
}The bar rules (the chart relies on them)
- Ascending, unique, inclusive. Bars are sorted by time, one bar per timestamp. A
historywindow is INCLUSIVE of both ends: a bar exactly atfromor attobelongs to the answer. The chart never re-requests a bar it holds: it pages withto = oldest − 1, so you never re-send one either. countBackoutranksfrom, and the count is an obligation. Whenhistoryis called withcountBack: N, return the last N bars at/beforetoeven if that reaches back pastfrom(a weekend or holiday week betweentoand the data is YOUR problem to reach across, not the chart's). The widget asks once per scroll approach and does not loop to compensate: a short answer is a visibly short chart. Fill outward in widening rounds until the count is met or history is exhausted.noDataends scroll-back. When acountBackrequest finds nothing, return{ bars: [], noData: true }. A plainfrom/torequest with an empty window must not setnoData(an empty window can be a mid-history gap, not the end of history).- Live updates mutate the last bar or append.
subscribeBarsemits{ kind: 'snapshot', bars }on connect and after every reconnect (the self-healing re-sync), then{ kind: 'bar', bar }per update. A bar'stis its bucket-open epoch-seconds time, never the update's wall-clock time. The chart opens the subscription alongside history. The first data frames the chart; history arriving later adds older bars and retains newer stream readings. Mark a preliminary history snapshot withbackfill: true: it fills missing timestamps without replacing bars already held. - Bar time is epoch SECONDS. Not milliseconds.
- No feed for a symbol is terminal. Throw
FeedUnavailableErrorfromhistorywhen no feed serves the symbol; the chart shows "market data unavailable" and stops. A transient fetch failure should throw a normal error (the chart retries). - Never synthesize prices. A bar carries what the market printed; a symbol with no data has no bars, never invented ones.
Coarser grains than the feed serves (withFoldedHistory, optional)
A venue that keeps 15-minute bars keeps every 45-minute bar too, just not under that name. Wrap a feed to answer those:
import { withFoldedHistory, type ChartDatafeed } from '@trdrs/quickcharts'
declare const venueFeed: ChartDatafeed // your feed from the section above
const feed = withFoldedHistory(venueFeed, { serves: ['1m', '15m', '1h', '1d', '1mo'] })serves names the grains the feed answers natively. Every other request is folded from the coarsest
of them that divides it, so a 45-minute ask fetches 15-minute bars three at a time: first open,
extremes across the run, last close, summed volume. Month multiples fold by calendar month, so a
quarter is a quarter rather than ninety days, and weeks start on Monday.
Folding only works downward. A finer bar cannot be recovered from a coarser one, because the path the price took inside it was never written down, so a request below everything the feed serves passes through untouched and the feed answers for itself. This is rule 7 in wrapper form.
Capability declaration (config, optional)
A feed with a fixed capability set may declare it; the widget reads the declaration once at mount and constrains itself. In particular, its opening timeframe must be servable: a sticky/default tf the feed did not declare falls to your first declared resolution instead of dead-ending the first paint on a refusal. The viewer's stored preference is not overwritten (capability is the feed's property, preference is the viewer's, so a later feed that serves the preferred tf gets it back).
import type { ChartDatafeed, DatafeedConfig } from '@trdrs/quickcharts'
declare const baseFeed: ChartDatafeed // your feed from the section above
export const feed: ChartDatafeed = {
...baseFeed,
async config(): Promise<DatafeedConfig> {
return { resolutions: ['1m', '5m', '1h', '1d'] }
},
}Declare only what is true. Absent method / absent field / empty list = unconstrained, so a feed that
serves any timeframe must not declare a finite resolutions list, because the widget then enforces
it. The UDF adapter declares automatically from the server's own /config (and only ever declares
timeframes it would actually serve).
The UDF on-ramp
Already serving bars over the UDF wire protocol? Skip implementing the interface and point the adapter at your server:
import { createUdfDatafeed } from '@trdrs/quickcharts'
const datafeed = createUdfDatafeed({ baseUrl: 'https://feed.example.com/udf' })UDF is REST and poll-based (no push): subscribeBars polls /history for the newest bar. For true
real-time, implement ChartDatafeed directly over your own stream. UDF is the low-effort on-ramp,
not the endpoint.
What the adapter honors of the protocol:
/configis fetched once and drives the rest.supported_resolutionsis validated against: asking for a resolution the server didn't declare isFeedUnavailableError, not a silent guess ('D'and'1D'are recognized as the same declaration). A server without/configgets the protocol's defaults (search on, no groups). The adapter also republishes the declaration through the seam'sconfig(), so the widget opens on a timeframe the server actually serves.- Group-catalog symbol search. When
/configdeclaressupports_group_request, search is served from the columnar/symbol_info?group=catalog instead of/search. no_data+nextTimeis a gap, not the end. The chart re-asks once atnextTime(a session gap hop); onlyno_datawithout the hint ends scroll-back.nextTimein ms or s both work.- The seam's inclusive
[from, to]is bridged to UDF's exclusivetoinside the adapter, so your server sees standard UDF ranges; implement nothing special.
Symbology
Symbology is the set of display facts that decide how a market's prices are written. Your datafeed
owns them (resolve answers with SymbolInfo), and one package formatter uses them everywhere a
price appears: the price scale, the crosshair and last-price labels, the legend, the context menu,
every drawing label, indicator scales, and the extension seam. Precision comes from the symbol,
never from the size of the price, so the same market reads at the same width on every surface. An
indicator that declares its own precision keeps it; every other value writes through the symbol
formatter.
PriceFormat expresses every supported form in five facts:
| Fact | What it says |
|---|---|
| pricescale | Price units per whole unit. 100 writes cents, 100000 writes FX pipettes, 32 writes thirty-seconds. |
| minmov | The smallest move, in those units. It declares the grid, not the column width. |
| minmove2 | The further division of one minmov step. 4 means quarters of a thirty-second. |
| fractional | Write the sub-unit part as a counted fraction rather than as decimals. |
| variableTickSize | An ordered ladder of tick sizes by price band, as a space-separated string. |
Build a formatter once per symbol and keep it:
import { createPriceFormatter, type PriceFormat } from '@trdrs/quickcharts'
const equity: PriceFormat = { pricescale: 100, minmov: 1 }
createPriceFormatter(equity).format(123.4) // '123.40'
const emini: PriceFormat = { pricescale: 100, minmov: 25 }
createPriceFormatter(emini).format(4500.25) // '4500.25'
const treasury: PriceFormat = { pricescale: 32, minmov: 1, fractional: true }
createPriceFormatter(treasury).format(110.5) // "110'16"
const bonds: PriceFormat = { pricescale: 128, minmov: 1, minmove2: 4, fractional: true }
createPriceFormatter(bonds).format(110.515625) // "110'16'2"format and parse are exact inverses, so a formatter reads back what it wrote:
import { createPriceFormatter } from '@trdrs/quickcharts'
const formatter = createPriceFormatter({ pricescale: 32, minmov: 1, fractional: true })
formatter.parse("110'16") // 110.5
formatter.parse('110.5') // null, because that symbol does not write decimals
formatter.precision() // 0, because a fractional format writes no decimal digitsA surface with no DOM at all, a native view or a server, imports the same formatter from
@trdrs/quickcharts/format. The entry carries the formatter and its types and nothing that names a
window, a document or a DOM type, so it loads anywhere JavaScript runs and writes a price exactly as
the chart's axis does:
import { createPriceFormatter, type PriceFormat } from '@trdrs/quickcharts/format'
const bonds: PriceFormat = { pricescale: 128, minmov: 1, minmove2: 4, fractional: true }
createPriceFormatter(bonds).format(110.515625) // "110'16'2"A ladder changes width by band, because the symbol declared those bands:
import { createPriceFormatter, parseTickBands, tickBandFor } from '@trdrs/quickcharts'
const laddered = createPriceFormatter({ pricescale: 10000, minmov: 1, variableTickSize: '0.0001 1 0.001 10 0.01' })
laddered.format(0.5432) // '0.5432'
laddered.format(54.32) // '54.32'
const bands = parseTickBands('0.0001 1 0.001 10 0.01')
tickBandFor(bands, 5)?.size // 0.001The formatter writes a . decimal sign and no thousands separator. Pass a locale to take that
locale's decimal sign, or set the punctuation yourself:
import { createPriceFormatter } from '@trdrs/quickcharts'
createPriceFormatter({ pricescale: 100, minmov: 1 }, { locale: 'de-DE' }).format(1234.5) // '1234,50'
createPriceFormatter({ pricescale: 100, minmov: 1 }, { numericPunctuation: { groupSign: ',' } }).format(1234.5) // '1,234.50'Naming
The same facts name the market on screen, through one rule with three faces. symbolNames reads a
resolved SymbolInfo, a search row, or the feed symbol alone before either has landed, and answers
the compact mark a label wears, the title a reading wears, and the description beside a mark. A
pair market reads in the codes it trades in, never a spelled-out currency; a market that is not a
pair keeps the feed's own words; the venue prefix never reaches the screen. The chart's pill, legend
and picker read these faces, so anything you name beside the chart reads the same:
import { symbolNames, type SymbolNames, type SymbolRow } from '@trdrs/quickcharts'
const row: SymbolRow = { symbol: 'HYPERLIQUID:ETH', name: 'Ethereum perpetual', exchange: 'Hyperliquid', type: 'crypto', currencyCode: 'USDC' }
const perp: SymbolNames = symbolNames(row)
perp.mark // 'ETHUSDC'
perp.title // 'ETH / USDC'
perp.description // 'ETH / USDC'
symbolNames({ symbol: 'NASDAQ:AAPL', name: 'Apple Inc', exchange: 'NASDAQ', type: 'stock', currencyCode: 'USD' }).mark // 'AAPL'
symbolNames({ symbol: 'NASDAQ:AAPL', name: 'Apple Inc', exchange: 'NASDAQ', type: 'stock', currencyCode: 'USD' }).description // 'Apple Inc'
symbolNames('HYPERLIQUID:ETH').mark // 'ETH', before the symbol resolves
symbolNames('KRAKEN:BTC/USD').title // 'BTC / USD': a slash pair states both sidesOne exchange prefix comes off a symbol on its own. Where your feed writes a symbol that says more,
give the row the ticker a viewer reads it by, as SymbolInfo.ticker states it for the charted
symbol; the row keeps its symbol as the market's identity:
import { symbolNames } from '@trdrs/quickcharts'
symbolNames({ symbol: 'EXCH:BOOK:NVDA', ticker: 'NVDA', name: 'NVIDIA Corp', exchange: 'EXCH', type: 'stock' }).mark // 'NVDA'A crypto or forex market whose ticker names it whole, as an exchange may write a perpetual or a pair
(SOL-PERP, SOL/USD), sets pair: false and reads as its ticker, written as the feed writes it,
beside its name. A row's kind is the tag its search row wears in place of its type:
import { symbolNames } from '@trdrs/quickcharts'
symbolNames({ symbol: 'EXCH:SOL_USDC_PERP', ticker: 'SOL-PERP', name: 'Solana', exchange: 'EXCH', type: 'crypto', currencyCode: 'USDC', pair: false, kind: 'perp' }).mark // 'SOL-PERP'
symbolNames({ symbol: 'EXCH:SOL_USDC', ticker: 'SOL/USD', name: 'Solana', exchange: 'EXCH', type: 'crypto', currencyCode: 'USDC', pair: false, kind: 'spot' }).description // 'Solana'@trdrs/quickcharts/symbols carries the same rule on its own, symbolNames and bareTicker, with
nothing that names a window, a document or a DOM type, so a view of your own with no DOM, a native
search list among them, names a market exactly as the chart does. bareTicker is the ticker inside
a feed symbol, its venue prefix shed:
import { bareTicker, symbolNames } from '@trdrs/quickcharts/symbols'
symbolNames({ symbol: 'HYPERLIQUID:BTC', name: 'Bitcoin perpetual', exchange: 'Hyperliquid', type: 'crypto', currencyCode: 'USDC' }).title // 'BTC / USDC'
bareTicker('CME:ES1!') // 'ES1!'
bareTicker('KRAKEN:BTC/USD') // 'BTC/USD'
bareTicker('NYSE:F/2') // 'NYSE:F/2': a ratio keeps its whole expressionSymbology is display truth: how the chart writes a market's prices. Execution facts, such as lot size and pip value, stay with your trading integration, and its execution grid can differ from the chart's display grid.
If your data comes from a UDF server, map its /symbols answer without collapsing the facts:
import { createPriceFormatter, udfPriceFormat, udfSymbolInfo } from '@trdrs/quickcharts'
const raw = { name: 'ZBZ2026', pricescale: 128, minmov: 1, minmove2: 4, fractional: true }
const info = udfSymbolInfo(raw, 'ZBZ2026')
createPriceFormatter(udfPriceFormat(raw)).format(110.515625) // "110'16'2"
info?.dataStatus // 'streaming'Save and load
Quick Charts persists two different kinds of thing, and the difference decides where each one lives.
Saved charts, layouts, drawing documents and templates are entities: a viewer names them, opens
them in two tabs, and can lose them. They have identity and versions, and they live on the
save/load adapter you supply. Viewer preferences (the last symbol and timeframe, the scale mode, the
replay speed) are flat settings: they need no identity, and they live on the small ChartStorage
port beside it.
The chart never writes on its own. It tells you when a save would be worth making, through the
saveNeeded event, and it runs a write only when a viewer asks for one through the built-in UI or
when you call a save method yourself.
What a saved entity carries
Every family works the same way. A read returns a ResourceRef: a stable id plus an opaque revision
token. A write quotes the revision it believes it is replacing. A write against a revision the store
has moved past returns a typed conflict carrying the current ref, which you resolve rather than
overwrite.
import { memorySaveLoadAdapter } from '@trdrs/quickcharts'
const adapter = memorySaveLoadAdapter()
const created = await adapter.charts.create({ name: 'Morning', symbol: 'ESZ2026', timeframe: '5m', content: '{}' })
if (created.kind === 'ok') {
const accepted = await adapter.charts.update(created.ref, { name: 'Morning', symbol: 'ESZ2026', timeframe: '15m', content: '{}' })
const stale = await adapter.charts.update(created.ref, { name: 'Morning', symbol: 'ESZ2026', timeframe: '1h', content: '{}' })
accepted.kind // 'ok', and it carries the revision the store now holds
stale.kind // 'conflict', and it carries the ref that won
}A chart's, a layout's and a template's content is opaque to your store: pass it through, and the
chart's formats stay the chart's own. A drawing document is the one structured body, because two
surfaces showing the same drawings have to merge rather than overwrite.
Treat the revision as opaque. Mint it however your backend prefers, as an ETag, a counter or a content hash, and compare it only for equality.
The built-in Save/Load UI
With the layouts feature on, the top bar carries the open layout's name, a marker for unsaved
changes, and a menu with Save, an Autosave switch, Make a copy, Rename, Download chart data, Create
new layout, the layouts used most recently, and Open layout: the Layouts dialog, with search, a sort
by name or by date modified, a star that keeps a layout at the top, and delete behind a
confirmation. The sort and the stars are the viewer's, kept in the widget's ChartStorage. Each
saved layout is listed by the market and timeframe its active chart showed when
it was saved, or by its age where the store kept neither.
Every row runs a command (widget.layout.save, rename, load, open, delete, create, autosave,
and chart.data.download for the export), so an access policy that refuses layout writes disables
the rows and refuses the same verb from every other door. Ctrl+S, and Cmd+S on a Mac keyboard, run
the save command from the chart's own root, under that same policy: an open layout saves, and a
never-saved one is asked for a name first. The period key opens the Layouts dialog through
widget.layout.open, under the same policy. Download chart data writes the active chart's loaded bars
as CSV with time, open, high, low, close and volume columns in UTC, and is unavailable on a chart
holding no bars. The menu hears what a verb did through the widget's layout event and
what it refused through saveConflict.
Save and Rename commands are unavailable while a layout load is pending. Hosts performing
background initialization should recheck commands.available('widget.layout.save') after any
awaited discovery, before creating an initial layout. Direct API calls retain caller-controlled
ordering; this command readiness is distinct from the unsafe-content notSaving() state.
Direct widget.layout.saveLoad calls publish the same events once at the committed binding,
so a host-created or reopened layout immediately updates the package toolbar. Cancelled loads
and stale write results publish no success. A rescue copy or partial load can update the name
without clearing notSaving() or the toolbar's existing dirty state. Removing an already absent
open row reports its removal and a saveConflict refusal; the absent binding is detached.
import { createChart, createUdfDatafeed, memorySaveLoadAdapter } from '@trdrs/quickcharts'
declare const uiContainer: HTMLElement
const uiWidget = createChart({
container: uiContainer,
datafeed: createUdfDatafeed({ baseUrl: 'https://feed.example.com/udf' }),
saveLoad: memorySaveLoadAdapter(),
})
uiWidget.on('saveNeeded', () => note('the viewer changed something a save would keep'))
uiWidget.on('layout', (event) => note(`${event.kind} ${event.name ?? ''}`))
uiWidget.commands.execute('widget.layout.save', { name: 'Desk', asNew: true })The transport-neutral adapter
ChartSaveLoadAdapter is four families over one contract. Each family is a ResourceStore with the
same five calls, and every call takes an AbortSignal so abandoned work stops cleanly:
import { emptyDrawingDocument, memorySaveLoadAdapter, type ResourceRef } from '@trdrs/quickcharts'
const adapter = memorySaveLoadAdapter()
const controller = new AbortController()
await adapter.layouts.list(controller.signal)
await adapter.templates('indicator').list()
const context = { version: 1, kind: 'symbol-global', symbol: 'ESZ2026' } as const
await adapter.drawings(context).create(emptyDrawingDocument(context))
const ghost: ResourceRef = { id: 'gone', revision: 'rev-1' }
const outcome = await adapter.charts.remove(ghost)
outcome.kind // 'not-found'An aborted call rejects with an error named AbortError and changes nothing.
memorySaveLoadAdapter keeps everything in memory for the life of the page. Use it for tests,
server rendering and an intentionally ephemeral embed, and implement the same contract over your
own backend for durable storage.
The REST adapter and its wire contract
If your saved resources live behind HTTP, @trdrs/quickcharts/adapters/rest implements the same contract
over a published wire contract, and you implement the service.
import { createRestSaveLoadAdapter } from '@trdrs/quickcharts/adapters/rest'
const restSaves = createRestSaveLoadAdapter({
baseUrl: 'https://api.example.com/chart-storage',
// Your transport. `fetch` fits as it is; wrap it to add what your product needs.
request: (url, init) => fetch(url, { ...init, credentials: 'include' }),
})
await restSaves.layouts.list()You supply two values. baseUrl is where you mounted the routes, and request is how a request is
made. Authorization, cookies, CORS, retries, timeouts and tenancy stay in your request function,
because their consequences are yours: the adapter builds each request from baseUrl and hands it to
your function, which adds the credentials and headers your service needs, and it makes a request
only when you call a verb.
Your service serves four collections under that base URL. Every path below is relative to it.
| Path | Verbs | Body |
| --- | --- | --- |
| /charts | GET lists, POST creates | { name, symbol, timeframe, content } |
| /charts/{id} | GET reads, PUT replaces, DELETE removes | the same |
| /layouts, /layouts/{id} | the same five | { name, symbol?, timeframe?, content } |
| /drawings?symbol=&context=, /drawings/{id} | the same five | { content } |
| /templates/{kind}, /templates/{kind}/{id} | the same five | { name, tool?, content } |
A layout's symbol and timeframe are listing text: the active chart's market as the chart writes it
(BTCUSDC) and its timeframe token, as they stood at the save. Keep them and return them in the
listing, or leave them out and the chart lists the layout by its age.
A listing answers { "items": [...] } of metadata. A read answers { "id", "revision", "body" }. A
create, update or delete answers { "id", "revision", "meta"? }. Every update and delete sends the
revision it is replacing in If-Match, and your service must compare it before it writes.
Three statuses carry meaning, and the adapter turns each into the same outcome the in-memory adapter gives you:
404isnot-foundfrom a write, andnullfrom a load.409isconflict, and its body states the ref that stands now:{ "error": "conflict", "current": { "id", "revision" } }. A create quotes no revision, so it can conflict only on identity: a drawings context that already holds a document, or a name a sibling already has.428states that a conditional route was reached with noIf-Match. The adapter always sends one, so a428means the request did not arrive as it was sent.
Any other status, and any body that is not the shape the route promises, raises a
RestSaveLoadError carrying the status, the method and the URL. Decide what it means: an outage is
not an empty listing, and answering one as an empty listing is a lie the next save acts on.
import { createRestSaveLoadAdapter, RestSaveLoadError } from '@trdrs/quickcharts/adapters/rest'
const saves = createRestSaveLoadAdapter({ baseUrl: 'https://api.example.com/chart-storage', request: fetch })
try {
const rows = await saves.layouts.list()
note(`${rows.length} saved layouts`)
} catch (e) {
if (e instanceof RestSaveLoadError) note(`${e.method} ${e.url} answered ${e.status}`)
else throw e
}The drawings collection is scoped by two query parameters: symbol, and an opaque context token
for the drawing-resource context. Store rows under the pair and return them under the pair; the
token is not for reading.
The full schema ships with the package as dist/rest-openapi.json, an OpenAPI document generated
from the same contract the adapter implements. Read it, lint it, or generate a server stub from it.
The adapter is a separate entrypoint, so a project that never imports it carries none of it.
Charts, layouts and their low-level APIs
The widget drives the charts family for you. createChart({ saveLoad }) takes your adapter, and
chart.saveLoad holds the open saved chart: save(name) updates it at the revision it was opened
at (or creates, when nothing is open or you pass asNew), load(id) applies a saved chart and
opens it, remove() deletes the open one at its held revision, detach() forgets the binding so
the next save creates, and current() reports the ref and name on screen. serialize() hands you
the same opaque content the save writes, and restore(content) applies one. A layout does the same
for itself through widget.layout.saveLoad over the layouts family.
A load is one transaction. The content is read and applied first, and the resource's id, name and
revision become the open resource only after that succeeds. A saved layout is read whole, its
version, arrangement, normalized custom pane geometry, sync flags, active tile and every chart
inside it included, before a single tile moves. The current layout reader accepts only this v2
shape. Divider drags preserve the selected arrangement's topology and save normalized geometry;
tile maximize is transient and preserves every chart instance. If a chart
callback synchronously detaches or starts another load while that content is applying, the later
operation owns the binding. The superseded load answers cancelled and cannot restore its id after
the callback returns.
The built-in layout setup control follows committed layout state, including direct API changes and restores. Its arrangement glyph, accessible name, selected tile, and five synchronization switches remain in step while the menu is open; transient tile maximize does not change the arrangement it names.
Growing a layout keeps every existing chart instance and initializes each new tile from pane 0's safe presentation: symbol, timeframe, style, indicators and comparisons. Mutable indicator configuration is copied per tile; replay, session state and saved-chart identity are not copied.
load answers rather than rejecting. Five kinds, told apart without reading a message:
| kind | What happened |
|---|---|
| ok | The content is on screen and the resource is open. Carries its ref and body. |
| not-found | The store answered, and holds no resource under that id. |
| invalid | The content could not be read, or could not be applied. |
| unavailable | The store could not be reached. Carries cause, the error it failed with. |
| cancelled | The load was abandoned: a later load took its place, your signal aborted, or the widget went down. |
Only ok binds. A refusal before application leaves the screen and its former binding untouched.
If a synchronous callback supersedes a load during application, the applied screen is left unbound
unless the newer operation has already committed its own binding, so it can never autosave through
the resource that was on screen before the load. An AbortSignal of your own ends the load as
cancelled too, so nothing in this family rejects for a load that was abandoned. A widget built
with no saveLoad adapter is the one case that is not an outcome: every verb of the family rejects,
because nothing was wired for them to reach.
import { createChart, createUdfDatafeed, memorySaveLoadAdapter } from '@trdrs/quickcharts'
declare const container: HTMLElement
const widget = createChart({
container,
datafeed: createUdfDatafeed({ baseUrl: 'https://feed.example.com/udf' }),
saveLoad: memorySaveLoadAdapter(),
})
widget.on('saveConflict', (info) => console.warn(info.message))
const saveLoad = widget.activeChart().saveLoad
const saved = await saveLoad.save('Morning')
if (saved.kind === 'conflict') console.warn(saved.message) // saved elsewhere since it was opened
saveLoad.current()?.name // 'Morning'
const opened = await saveLoad.load('chart-42')
switch (opened.kind) {
case 'ok':
break
case 'cancelled':
break // a later load is landing instead, so there is nothing to say
case 'unavailable':
console.warn(opened.message, opened.cause) // your store, not the content
break
case 'invalid':
case 'not-found':
console.warn(opened.message) // still bound to what you had
break
}A load that a later load supersedes is cancelled, with no signal of your own involved, and only
the later load binds. This includes a later load begun synchronously by a chart callback during
application. A widget disposed while the store is still answering answers the same way. That is
what keeps a slow answer for the chart a viewer has left from landing on the chart they are looking
at.
Where a body fails after part of it has been applied, the chart puts back the content it held. If
that fails too the chart is holding neither, and it stops saving: saveLoad.notSaving() reports it,
save answers not-saving and writes nothing, the built-in layouts menu says so on the toolbar and
stands its Save and its autosave down, and the sentence for the viewer arrives on saveConflict.
Saving starts again when a load lands, and only then: a whole content out of the store, applied in
full, under the resource it came from. save(name, { asNew: true }) stays available throughout, and
it is worth offering, because a copy creates a resource of its own and writes over nothing, so the
work on screen is kept and the last version that was whole is left standing. It is a rescue rather
than a repair: a store accepting a write says nothing about the content of what it took, so the
chart goes on saving nowhere else until a load puts a whole content back.
A layout also refuses writes while any child chart is not saving. A complete layout load recovers its children only after the whole content and layout binding commit, and detaches their previous standalone chart bindings. Partial content and copy saves do not establish recovery.
A saved chart carries its symbol, timeframe, style, scale, the chart settings a viewer chose,
comparisons, extension state, combined-mode drawings, and every indicator instance. Indicator definitions remain code in
your widget. The blob names each definition by manifest.id and carries the instance id, explicit
inputs, color, title, overrides and hidden state. Loading replaces the full instance list, so the
constructor's indicators are seeds only for a chart with no saved content. Definitions resolve
against the widget's built-ins and the host definitions that widget has carried. An unknown or
access-denied definition is left out with one counted notice while the remaining content lands. A
definition of your own survives a save only when its manifest declares an id.
The opaque version-5 reader validates the whole indicator list before changing a chart or layout.
Missing lists, duplicate instance ids and malformed inputs, titles, colors or overrides refuse the
body as invalid; values are not silently filtered or normalized. A load that omits a definition
because it is unavailable is partial and cannot clear an earlier notSaving() state.
Complete recovery requires a settings record whose every leaf holds a value its leaf can hold,
every color a concrete one the renderer paints, and, in combined mode, a drawings array.
Separate-mode chart content does not need that array. A version-4 blob reads its appearance
record into the settings sections its leaves now live in.
Hydration and rollback do not emit saveNeeded for their own storage writes. An event already
queued by a viewer's edit is preserved. A late save result does not replace a newer load's binding;
the built-in commands announce a saved layout only while that result is still current.
Drawings: combined or separate
Drawings have two storage modes, and you pick one when you construct the widget. Combined is the default: the drawings ride the chart's own saved content, so saving a chart or a layout saves the drawings on it. Separate keeps them out of that content entirely and stores them as their own documents in the adapter's drawings family, one document per drawing-resource context:
import { createChart, createUdfDatafeed, memorySaveLoadAdapter } from '@trdrs/quickcharts'
declare const separateContainer: HTMLElement
const separate = createChart({
container: separateContainer,
datafeed: createUdfDatafeed({ baseUrl: 'https://feed.example.com/udf' }),
saveLoad: memorySaveLoadAdapter(),
// chart-local: one document per chart, per symbol. `layout-shared` gives the layout's charts one
// document per symbol, and `symbol-global` gives every chart one.
drawingPersistence: { mode: 'separate', scope: 'chart-local', layoutId: 'desk-1' },
})
const documents = separate.activeChart().drawingResources
const read = await documents?.get()
if (read?.kind === 'ok') {
// The ref the read stood at rides the apply, so the chart's next write is an update at that
// revision rather than a create that learns the ref from the refusal it gets back.
const applied = documents?.apply(read.document, read.ref)
// 'ok' with the drawings it attached, and every one it would not: an entry whose source or pane
// is not on this chart is named rather than moved onto whatever is nearest.
applied?.kind
}
await documents?.reload()A document carries each drawing's stable id, the source and pane that own it, its type and its own
opaque state, plus ordered groups and deletion tombstones. The tombstones are why a drawing you
delete stays deleted: another chart showing the same document still holds it, and the merge that
follows a refused write drops it instead of taking it back. A refused write reaches you through the
widget's saveConflict event.
layoutId is yours to choose and must be stable across reloads; chart-local and layout-shared
require it, because a document keyed by an id the next page load mints again could never be read
back. There is no reader, fallback or mirrored write between the two modes.
A chart-local document is keyed by the chart's tile in the layout, which is what survives a
reload. It is a position, so it follows the position: changing the arrangement, or closing a chart
with charts after it, renumbers those tiles, and each of them then opens the document of the tile it
now occupies. Choose layout-shared when the drawings belong to the layout rather than to one
tile.
Templates
adapter.templates(kind) is a store per kind: 'indicator' for indicator settings, 'drawing' for
a drawing tool's look, 'chart' for the chart settings a viewer saves from the settings dialog's
Template menu, and 'palette', which the chart itself does not write. A drawing template carries the tool
it belongs to, because a trend-line template means nothing on a rectangle. Their content is opaque,
like a chart's.
Viewer settings
The widget keeps the viewer's flat preferences in a ChartStorage. Every key is an opaque string in
the quickcharts. namespace, and every value is an opaque string; a store routes or scopes them and
treats both as opaque. The default is an in-memory store that lasts the page; supply your own to
keep them per device or per viewer. A browser store is a few lines you write and own, so where
preferences live stays your decision:
import { memoryChartStorage, type ChartStorage } from '@trdrs/quickcharts'
const perDevice: ChartStorage = {
get: (key) => localStorage.getItem(key),
set: (key, value) => localStorage.setItem(key, value),
remove: (key) => localStorage.removeItem(key),
keys: () => Object.keys(localStorage),
}
void perDevice
void memoryChartStorage()Preferences need no identity or revision. Saved charts, layouts, drawings and templates do, and they live on the saved-resource adapter above, never here.
Conflicts
A conflict means someone else wrote the same entity after the copy on screen was read. The chart never resolves that by overwriting. It reports the case with a sentence from its own catalog and the ref that stands now, and leaves the decision to you: reload and lose the local edit, save a copy under a new name, or show the viewer both.
Reach the report in two places. A verb you called answers a typed conflict outcome. A write the
widget made for the viewer, through the built-in UI or its own drawing sync, arrives on the
saveConflict event with the family it came from.
Common issues
Nothing saves and no error appears. The widget has no adapter. createChart({ saveLoad }) is
what enables the family, and widget.capabilities().saveLoad reports which families it sees.
Every save creates another row. Something detached the open resource, or each save passes
asNew. current() reports what the next save will update.
A saved layout opens with the wrong drawings. In separate mode the document is keyed by
layoutId and the chart's tile. An id that changes between reloads, or a re-tile that moves a
chart, points the chart at another document.
A conflict on the first save of the day. Two tabs are open on the same entity. Both hold a revision, and the second write is refused; reload the newer one before saving it again.
A REST call raises instead of answering. The status is one the contract gives no meaning to.
Read error.status and error.url: a 401 is a session your request function has to renew, and a
5xx is your service.
Indicators
Indicators are definitions: a declarative manifest (typed inputs + declared plots/levels/fills, placement, volume needs) paired with a pure compute over the chart's bars. The package owns the whole rendering pipeline (overlay and per-indicator panes, lines/areas/histograms/markers, static levels, band fills, per-instance style overrides) and treats every definition alike, so a definition renders identically in this widget and in any richer host built on the same pipeline.
The built-in indicators
The package ships 23 built-in definitions as BUILT_IN_INDICATORS, in picker order: SMA, EMA,
HMA, VWMA, Bollinger Bands, Donchian Channels, Keltner Channels, Supertrend, Parabolic SAR, RSI,
MACD, Stochastic, Stochastic RSI, ADX, ATR, CCI, Williams %R, Rate of Change, Momentum, Volume,
VWAP, On-Balance Volume, and Money Flow Index. Each is a plain IndicatorDefinition with its
catalog identity beside it: id (the stable key you persist), tag (the short mark a legend chip
shows), category, and nameKey and descriptionKey, which resolve through the chart's own
language object in every built-in locale.
import { BUILT_IN_INDICATORS, createChart, createChartI18n, createUdfDatafeed } from '@trdrs/quickcharts'
const i18n = createChartI18n('en')
const rsi = BUILT_IN_INDICATORS.find((definition) => definition.id === 'rsi')!
const widget = createChart({
container,
datafeed: createUdfDatafeed({ baseUrl: 'https://feed.example.com/udf' }),
i18n,
indicators: [{ id: 'rsi-14', definition: rsi, title: i18n.t(rsi.nameKey), color: '#f5a623' }],
})
const picker = BUILT_IN_INDICATORS.map((definition) => ({
id: definition.id,
name: i18n.t(definition.nameKey),
description: i18n.t(definition.descriptionKey),
}))An instance's inputs override the manifest defaults by key ({ period: 21, source: 5 } for an
RSI over HLC3). A built-in's plotTitles and inputTitles are its manifest's titles by key.
Your own definitions
A host definition is the same shape. The math is yours; the manifest declares what to draw.
import type { IndicatorDefinition } from '@trdrs/quickcharts'
export const smaDefinition: IndicatorDefinition = {
manifest: {
name: 'SMA',
pane: 'overlay',
inputs: { period: { kind: 'int', default: 20, min: 1 } },
plots: { sma: { kind: 'line', lineWidth: 2 } },
},
compute(bars, inputs) {
const period = inputs.period ?? 20
const out: (number | null)[] = bars.map((_, i) => {
if (i + 1 < period) return null // warmup → whitespace, never a fake value
let sum = 0
for (let k = i + 1 - period; k <= i; k++) sum += bars[k]!.c
return sum / period
})
return { sma: out }
},
}How the settings dialog lays a definition out
The settings dialog reads everything it shows from the manifest, so a host definition lays out by the same rules as a built-in:
- Inputs lists every input in declaration order. A number is a field with steppers bounded by
min,maxandstep, anenumis a list of itsoptions, and abool(held as 1 or 0) is a checkbox row.titlelabels it, else its key read as words (fastLengthreads "Fast Length"). Inputs that name the samegroupin a run stand under one heading.enabledWhennames another input and the values under which this one applies, and it stands disabled under the others. - Style shows every plot, then every level, then every fill, each behind the checkbox that
shows it, labelled by its
title: a line with its color, thickness and style, a histogram drawnupanddownwith a row for each color, a level with its color, style and value, and a fill with its color. The precision and the values the price scale and the status line write follow. - Visibility holds the timeframes the instance draws on.
import type { IndicatorDefinition } from '@trdrs/quickcharts'
const manifest = {
id: 'trend-filter',
pane: 'pane',
inputs: {
length: { kind: 'int', default: 20, min: 1, title: 'Length' },
smoothing: { kind: 'enum', default: 0, options: ['None', 'SMA', 'EMA'], title: 'Type', group: 'Smoothing' },
smoothingLength: { kind: 'int', default: 9, min: 1, title: 'Length', group: 'Smoothing', enabledWhen: { input: 'smoothing', values: [1, 2] } },
showZero: { kind: 'bool', default: 1, title: 'Show zero line' },
},
plots: { trend: { kind: 'line', lineWidth: 2, title: 'Trend' } },
levels: { zero: { price: 0, lineStyle: 'dashed', title: 'Zero Line' } },
} satisfies IndicatorDefinition['manifest']Every edit previews on the chart, and Ok commits the session as one chart.indicators.update. Its
Defaults menu resets an instance to the definition's own settings, or keeps its inputs and look in
the chart's storage as the ones the definition's next instance opens with, when that instance is
added with no inputs and no overrides of its own. ui.indicatorSettings: false turns the dialog
off, and the legend's gear then opens the inputs-only editor, the dialog's Inputs page in a popover.
Wire instances through ChartWidgetOptions.indicators:
import { createChart, createUdfDatafeed } from '@trdrs/quickcharts'
const widget = createChart({
container,
datafeed: createUdfDatafeed({ baseUrl: 'https://feed.example.com/udf' }),
indicators: [{ id: 'sma-20', definition: smaDefinition, color: '#4c98fb' }],
})Rules the pipeline enforces:
- Channels align 1:1 to bars.
computereturns one value array per declared plot key; null/NaN entries become clean whitespace gaps (warmups break, never bridge). - Placement is the manifest's.
pane: 'pane'gives the instance its own bottom pane (created and swept automatically);'overlay'rides the main price scale. - A plot can ride the volume band.
scale: 'volume'on a plot pins it to the chart's volume histogram instead of the pane's price scale. - A fill can shade between levels. A fill whose
betweennames two levels rather than two plots shades between those limit lines wherever the bars are. needsVolumeis honest. On a feed whose bars carry no volume, the instance draws nothing and reports "No volume from this feed" instead of painting a flat lie.- Overrides layer, never fork. Per-instance styling (
IndicatorOverrides) folds into the manifest before the walk and gates visibility after, the same layering every host applies. - Instances save by definition id. Saved charts and layouts retain each instance's explicit
inputs, look and hidden state. Give a host definition a stable
manifest.idso the widget can resolve it when content loads.
The lower-level pieces are exported for hosts that orchestrate their own compute:
buildManifestPlots (the walker), attachIndicators (the renderer), overriddenManifest /
applyPlotOverrides (the override fold), and the fill/shade canvas painters.
The widget
createChart(options) mounts a complete datafeed-driven chart into a DOM element, with no framework
required. It answers a ChartWidget: one or many charts under one root, one theme, one language,
one command registry.
import { createChart, createUdfDatafeed } from '@trdrs/quickcharts'
const widget = createChart({
container: document.getElementById('chart')!,
datafeed: createUdfDatafeed({ baseUrl: 'https://feed.example.com/udf' }),
symbol: 'ES',
timeframe: '1m',
style: 'candles',
theme: { mode: 'dark' },
})
await widget.ready() // the first data has painted
widget.activeChart().setSymbol('NQ')
widget.dispose() // teardown; every handle and subscription is inert afterwardsThe widget paints the main series and volume, applies live updates by the bar rules above, pages
older history in as the viewer scrolls left and as a window set with setVisibleRange reaches back
past the loaded bars (stopping at the feed's noData), persists the viewer's
preferences through ChartStorage, runs configured indicator instances through the manifest
pipeline, and mounts the drawing layer, the legend and the context menu.
When older main or comparison history extends the renderer's shared timeline, the chart retains the latest fractional logical window, spacing and permitted off-data padding. Its compensating range write is not a viewer event and does not fan through layout date-range synchronization. The write owns the renderer's deferred reports only while the current symbol generation and navigation epoch still match. A coalesced mouse, touch or wheel pan/zoom remains observable and takes priority, including when a mouse drag continues outside the chart or renderer bounds retain the maintenance span or either endpoint. Public range methods and built-in navigation commands enter that same epoch, so every supported navigation door has the same precedence.
toolbarContainer optionally supplies a separate element for the top toolbar, such as a space
between a host's navigation and its other controls. The widget appends one package-owned, themed
child there; it never clears or styles the supplied element. The toolbar follows the widget's
theme, language and active chart, and its child is removed at disposal. The toolbar's menus and
dialogs open in the widget's layer on the document body, at viewport coordinates, so each menu
drops from its control wherever you place the toolbar and stands over your own elements. Supply a
fullscreen.target containing both elements to keep the
toolbar available in fullscreen. Without toolbarContainer, the toolbar sits above the chart as
part of the default composition. When horizontal space is limited, the toolbar scrolls without
dropping controls from the keyboard order.
drawingToolbarContainer supplies separate host space for a single drawing toolbar. The package
fills that space's height with its own themed child, follows the active chart when a layout
changes, and removes the child on disposal. An external drawing toolbar leaves the full chart width
for the canvas; without the option, each chart keeps its internal drawing toolbar and reserved
leading column. Drawing flyouts stay beside the external drawing toolbar within the widget's bounds
regardless of the active pane. Switching charts closes an open flyout before the drawing toolbar
targets the newly active chart.
Include this container in the custom fullscreen target alongside the chart and top toolbar.
Widget and chart
Two scopes, because two things are true at once: what the widget as a whole is doing, and what one
chart is doing. widget.charts() lists every chart; widget.activeChart() is the one the viewer
last pointed at; widget.chart(id) finds one by its stable id.
import { CHART_STYLES, type ChartHandle, type ChartWidget } from '@trdrs/quickcharts'
function drive(widget: ChartWidget): void {
const chart: ChartHandle = widget.activeChart()
chart.setTimeframe('5m')
chart.setStyle(CHART_STYLES[3]!) // 'line'
chart.setScaleMode('log')
chart.scroll(-50) // fifty bars back
chart.zoom(0.8) // show fewer bars
chart.reset() // fit the loaded data
chart.goLive() // back to the live edge, same span
chart.setVisibleRange({ from: 1_735_689_600, to: 1_738_368_000 }) // January 2025, paged in if older
chart.indicators.set([])
void chart.visibleRange()
void chart.rangePreset() // selected bottom-bar range, or null after other navigation
void chart.logicalRange()
}setVisibleRange({ from, to }) frames a window in the feed's unix seconds. A window inside the
loaded bars frames at once. A window that starts before the oldest loaded bar first pages older
history in through your feed's history, with the same to and countBack asks a scroll back
makes, each sized to the bars still missing, page after page until the bars reach from, the feed
answers noData or the chart holds 20,000 bars. It then frames the window over the bars it holds;
the view stays where it stands while the pages are away. A page that rejects ends the paging and
frames the window over the bars already loaded. A symbol or timeframe switch, any other navigation
or dispose() while a page is away leaves the window unframed. The chart.range.set command with
an explicit { from, to } window does the same.
The live edge and the plot
goLive() glides the view back to the live edge on an easing curve, moving it sideways only: the
zoom and the price scale stay as they are. From far back it steps in to a width and a half first, so
the return reads the same from any distance, and a touch, a drag, a wheel or any other navigation
stops it where it stands. Under a reduced-motion preference it goes in one step. Alt+Shift+Right
and the chart.view.goLive command run the same glide.
awayFromLiveEdge() says whether the view sits back from the live edge, and the liveEdge event
reports each change, so a control offering the way back shows exactly while there is somewhere to go
back from. A glide under way reads as returned from its first frame, and bar replay, which has its
own way back, reads as returned throughout. plotArea() and the plotArea event give the main
pane's plot in the pixels of the element you handed the widget, as the four distances an absolutely
positioned element takes, so a control floating over the bars stays beside the price scale as it
widens:
import { type ChartHandle } from '@trdrs/quickcharts'
function backToLive(chart: ChartHandle, button: HTMLButtonElement): () => void {
const place = (): void => {
const plot = chart.plotArea()
if (!plot) return
button.style.right = `${plot.right + 8}px`
button.style.bottom = `${plot.bottom + 8}px`
}
button.onclick = () => chart.goLive()
button.hidden = !chart.awayFromLiveEdge()
place()
const offEdge = chart.on('liveEdge', (away) => {
button.hidden = !away
})
const offPlot = chart.on('plotArea', place)
return () => {
offEdge()
offPlot()
}
}On a touch screen two fingers zoom proportionally: the bars spread exactly as far as the fingers do, and the point under the fingers stays under them as they travel. A finger held on the plot scrubs the crosshair while it stays down, and a flick coasts the chart calmly to rest.
With touch: { freePan: true } the chart is a canvas under the finger: a one-finger drag on the plot
releases the main price scale's framing, as a drag on the price scale does, so the price follows the
finger as freely as the time and nothing re-frames while the viewer pans, flicks or pinches. A pinch
zooms the time and leaves the price where it stands. A double-tap on the price scale, a new symbol or
timeframe, and goLive() frame the bars again; goLive() frames them from the tap, and the price
follows the window home as the time glides. It is off unless you turn it on.
With features: { navigation: false } the chart holds its view: no drag, flick, pinch or wheel moves
it, a scale takes no drag or double-tap, and the zoom and scroll commands and their keys are
unavailable, so the navigation cluster is not drawn whatever ui.navigation says. The view stays
where the chart frames it: on the live edge, at a range preset or at a window you set. goLive()
and reset() still frame it, and the crosshair still follows a pointer or a held finger. It is on
unless you turn it off.
Chart styles
candles, hollow, bars, line, area, baseline, stepline, listed as CHART_STYLES. A
style switch is presentation: nothing refetches, and the loaded bars, indicators, drawings,
comparisons, scale and visible range all survive it. Four of the seven are value-shaped
(valueShaped(style)), which is the one predicate a host branches on when it renders open, high and
low values of its own.
By default a chart offers all seven styles, and the style picker groups them by family. styles
names the styles you offer, in the order the picker lists them, and style must be one of them:
import { createChart, type ChartDatafeed } from '@trdrs/quickcharts'
declare const datafeed: ChartDatafeed
// Candles, line and area, in this order, opening on the line.
createChart({ container, datafeed, styles: ['candles', 'line', 'area'], style: 'line' })
// Every style and no picker: a control of your own runs the chart.style.<id> commands.
createChart({ container, datafeed, ui: { topBar: { styles: false } } })
// Candles and line, with no picker.
createChart({ container, datafeed, styles: ['candles', 'line'], ui: { topBar: { styles: false } } })A style you leave out has no chart.style.<id> command, so no menu, shortcut or host control
reaches it, and setStyle ignores it. With one style offered the picker is not shown, since there
is nothing to choose. ui.topBar.styles: false hides the picker on its own terms, so you can
restrict the set, hide the picker, do both, or do neither. A saved layout, saved chart or stored
preference that names a style you left out opens on the first style in styles, and the rest of it
restores. An empty list, an id outside CHART_STYLES, a repeated id and a style outside the list
are setup errors that createChart throws.
With transitions: { style: true } a change between a style drawn from whole bars (candles, hollow
candles, bars) and one drawn from closes (line, area, baseline, step line) morphs over half a second,
easing in and out: each bar's open, high and low slide into its close as the line comes in through
the closes, and back out of it as the line goes. A change within either family is made at once, and
so is every change under a reduced-motion preference. It is off unless you turn it on.
import { createChart, type ChartDatafeed, type TransitionOptions } from '@trdrs/quickcharts'
declare const datafeed: ChartDatafeed
const transitions: TransitionOptions = { style: true }
createChart({ container, datafeed, transitions })Offered timeframes
By default a chart offers the 26 presets (TIMEFRAME_PRESETS) and lets the viewer compose custom
timeframes. timeframes names the timeframe tokens you offer, presets or any other token the
grammar reads, and timeframe must be one of them. The order you give does not matter: the picker
lists each unit's group smallest first. customTimeframes: false keeps the presets and removes
custom timeframes:
import { createChart, type ChartDatafeed } from '@trdrs/quickcharts'
declare const datafeed: ChartDatafeed
// Four timeframes, one of them beyond the presets, opening on five minutes.
createChart({ container, datafeed, timeframes: ['2m', '5m', '1h', '1d'], timeframe: '5m' })
// Every preset and no custom timeframes.
createChart({ container, datafeed, customTimeframes: false })
// Two timeframes and no picker: a control of your own runs the chart.timeframe.<token> commands.
createChart({ container, datafeed, timeframes: ['1m', '5m'], ui: { topBar: { timeframes: false } } })A preset you leave out has no chart.timeframe.<token> command, and chart.timeframe.set and
setTimeframe ignore any token you leave out. The picker shows only what you list: a group with
no listed token is not drawn, a listed token beyond the presets sits in its unit's group without a
delete, and there is no custom-timeframe composer. The viewer's saved chips show where you list
them. When you list none of them, the chips are your five smallest timeframes, and the viewer's
stored chips stay stored for a chart that offers them. With one timeframe offered the picker is not
shown. ui.topBar.timeframes: false hides the picker on its own terms. A range preset whose
timeframe you leave out reads its span at your nearest coarser timeframe, or at your largest when
none is coarser. Within what you offer, the feed's resolutions and the symbol's
supportedResolutions still apply: a chip the feed or the symbol does not serve is disabled, and
the picker's list leaves its row out.
A saved layout, saved chart or stored preference that names a timeframe you left out opens on your
smallest timeframe, and the rest of it restores. With customTimeframes: false a stored custom
token opens on 1m. An empty list, a token the grammar cannot read, a repeated token, a
timeframe or layout.charts[].timeframe outside what you offer, and customTimeframes: true
beside a list are setup errors that createChart throws. customTimeframes is the switch, and
preferences.customTimeframes is the list of custom tokens a first-run viewer starts with.
Offered layouts
By default a chart offers all 55 arrangements (ARRANGEMENTS) and lets the viewer change every
sync switch. layouts names the arrangement codes you offer, and the layout opens on
layout.arrangement or else on the first code you list. layoutSync names the sync switches the
viewer may change:
import { createChart, type ChartDatafeed, type ChartSaveLoadAdapter } from '@trdrs/quickcharts'
declare const datafeed: ChartDatafeed
declare const saveLoad: ChartSaveLoadAdapter
// A single chart: no layout setup menu, and no re-tile from any door.
createChart({ container, datafeed, layouts: ['s'] })
// One chart, two side by side or a 2x2 grid, with the crosshair always synced and symbol sync the
// only switch the viewer changes.
createChart({ container, datafeed, layouts: ['s', '2h', '4'], layoutSync: ['symbol'], layout: { sync: { crosshair: true } } })
// Every arrangement, with the layout setup menu kept and the saved-layouts menu hidden.
createChart({ container, datafeed, saveLoad, ui: { topBar: { savedLayouts: false } } })The layout setup menu shows only the arrangements you list, in its own rows by chart count, and
leaves out a row with none of them. An arrangement you leave out has no tile, and
widget.layout.setArrangement and its command ignore it. With one arrangement offered there is
nothing to choose, so the menu is not shown, unless that arrangement holds several charts and a
sync switch is offered, in which case the menu holds the switches alone. A switch you leave out holds
the value layout.sync gives it, or off: the menu does not show it, widget.layout.setSync and its
command leave it as it is, and a saved layout cannot change it. An empty layoutSync fixes every
switch.
A saved layout whose arrangement you left out opens on the offered arrangement with the most charts not above the saved count, the first one listed winning a tie. When every offered arrangement holds more charts, it opens on the on
