# ORTEX Charts, complete reference > ORTEX Charts is a commercial JavaScript charting library for financial applications, built from the ground up with no third-party code or dependencies: 89.9 KB gzip for a full chart with a toolbar, indicators, drawings and order flow, 32.5 KB for a line chart, and a first paint in 33 ms at 100,000 bars. ## What ORTEX Charts is ORTEX Charts is a commercial JavaScript charting library for financial applications, made by ORTEX Technologies Ltd, the company behind the ORTEX trading and market-data platform. It draws candlesticks, bars, line, area, baseline, Heikin-Ashi, hollow candles, Renko, Kagi, Point and Figure and Line Break, with 51 built-in indicators, 32 drawing tools, order flow (footprint bars, volume profile, market profile, delta, cumulative delta, relative volume), bar replay, draggable price alerts, linked charts, a toolbar and shell, sparklines, treemaps, heatmaps and React bindings. It is Canvas 2D rather than WebGL. It is not the ORTEX subscription. ORTEX is a market-data and short-interest platform sold to investors at ortex.com, priced per user per month. ORTEX Charts is a library sold to developers at ortexcharts.com, priced per product. Buying one does not include the other, and using ORTEX Charts does not require an ORTEX data subscription. It is not built on TradingView, Lightweight Charts, Highcharts or ChartIQ. It is an independent rendering engine built from the ground up in TypeScript, with no third-party runtime dependencies and no code, icons or styles from any other library: every package installs with an empty dependency tree, and every line of it is ORTEX's own. ## What it costs ### Pro: $42 a month per product, paid annually as $499 One product, any number of developers, no mark. Or $59 month to month. - Commercial license for paid, private and internal applications. - Any number of developers. Nothing is counted per seat. - Every package, every release published during the term. - The private npm registry with type definitions, and the hosted kit. - Email support. ### Business: $125 a month for up to five products, paid annually as $1,499 Up to five products, priority support, invoicing, and an optional ORTEX data API trial. Or $179 month to month. - Everything in Pro, for up to five products. - Priority support: one business day. - Invoice and purchase order on request. - Optional: a trial of the ORTEX data API, if you want ORTEX data alongside your own. The library itself ships without data. ### OEM: By agreement annual contract Ship it inside a product you sell, with your own logo on the chart. - Ship the library inside your product to your own customers, including on-premises and desktop. - Priced by the number of deployments it reaches. - A read-only mirror of the source repository, a named engineer, a service-level agreement. - Optional: an ORTEX data licence alongside the library, under one contract. There is no free plan. Since library 1.1.0 a chart with no valid licence key draws a licence-required notice instead of its content on any host other than localhost; on localhost it draws with the ORTEX mark, so evaluation and tests need no key. Use of the library ends with the term on every plan: the key stops verifying on its expiry date and the chart stops drawing. Pro covers one product (one domain, plus localhost), Business up to five, OEM as agreed. Every paid plan shows no mark, and only OEM puts the customer's own logo on the chart. Sixty-day money-back guarantee; the price you buy at is held for as long as you stay. own and no license check phones home. ## How it compares, measured Payload, gzip, measured 2026-09-08 with one method for every library: - ORTEX Charts, a line chart: 32.5 KB in one file. engine, scales, crosshair, one series. - ORTEX Charts, candles and volume: 59.0 KB in one file. createFinancialChart, plus legend, price lines and crosshair readout. - ORTEX Charts, candles with indicators and drawings: 67.3 KB in one file. what a stock page loads. - ORTEX Charts, the full shell: 89.9 KB in one file. toolbar, menus, indicators, drawings, order flow. - ORTEX Charts, a sparkline: 3.3 KB in one file. the lite package. - TradingView Lightweight Charts 5.2.1: 60.7 KB in one file. standalone production build; series only. - Highcharts Stock 13, chart only: 132.6 KB in one file. highstock.js alone. - Highcharts Stock 13, with its stock tools: 215.6 KB across 9 files. highstock, indicators-all, stock-tools, annotations-advanced, drag-panes, price-indicator, full-screen, heikinashi, hollowcandlestick. - TradingView Advanced Charts: 4,757.5 KB across 154 files. the licensed drop, uncompressed on disk. - ChartIQ: 4.4 MB across 65 files. transferred by their public demo. Rendering, headless Chromium, the same chart in both libraries: ORTEX Charts first paints 100,000 bars in 33 ms against 448 ms for Lightweight Charts 5, and 10,000 bars in 40 ms against 83 ms. On a live tick, measured to the frame that paints it in both, the two are level at 10,000 bars and ORTEX Charts stays inside one frame at 33 ms against 68 ms at 100,000. TradingView Advanced Charts and ChartIQ have no installable build to drive, so only their load cost is comparable. Indicators: 51 built in, plus 78 more in @ortex-charts/indicators-extra, a package that costs about 11 KB gzip only when imported; 129 in all, more than Advanced Charts, and the host curates which of them end users see (include, exclude, featured, groups, labels). ### The grid One page, five libraries, four groups of rows: speed, payload, features and licensing. ORTEX Charts ships every feature row outright except one; the next best library ships about half. It is the smallest chart with a toolbar by a factor of two and a half, the fastest to first paint by more than ten times against the only competitor that can be driven from code, and the only one licensed for paid, private and internal applications at a published price with no third-party code behind it. The comparison grid: https://ortexcharts.com/compare ## What is below All 28 documentation pages, in the order the site presents them. Individual pages are served as Markdown at https://ortexcharts.com/docs/.md, and the index is at https://ortexcharts.com/llms.txt. The 20 live examples at https://ortexcharts.com/examples run in a browser and are not included below. --- # Quickstart > Install the package, draw a chart, add an indicator, in about five minutes. Section: Start here. Source: https://ortexcharts.com/docs/quickstart ## What You Will Have in Five Minutes A candlestick chart of your own bars, with a volume pane, a moving average, a crosshair readout and live updates, in about 30 lines of code. There are two paths through this page: one for an application with a bundler (Vite, webpack, Next.js, Rollup) and one for a plain HTML page with no build step at all. Both end at the same library. _Live example: [stock-chart](https://ortexcharts.com/examples/stock-chart)_ ## Path One: A Project With a Bundler ### Install the Package The packages are published to a private registry, so a one-line `.npmrc` has to come first. [Installation and delivery](https://ortexcharts.com/docs/install) explains where the token comes from and what the other delivery modes are. ```bash # .npmrc, next to package.json # @ortex-charts:registry=https://gitlab.com/api/v4/projects/86057283/packages/npm/ # //gitlab.com/api/v4/projects/86057283/packages/npm/:_authToken=${ORTEX_NPM_TOKEN} npm install @ortex-charts/financial ``` `@ortex-charts/financial` re-exports everything in `@ortex-charts/core`, so one dependency is enough for a price chart. Data types such as `Bar` and `Tick` come from `@ortex-charts/math`, which arrives as a transitive dependency. Add `@ortex-charts/ui` when you want the toolbar, `@ortex-charts/react` for components, `@ortex-charts/lite` for sparklines and `@ortex-charts/viz` for treemaps and heatmaps. ### Set the License Key Call `setLicenseKey` once, as early in the application as you can, before any chart is created. It returns a promise that resolves when the signature check finishes, but you do not have to await it: the check is asynchronous and the chart never blocks on it. ```ts import { setLicenseKey } from "@ortex-charts/financial"; void setLicenseKey(process.env.NEXT_PUBLIC_ORTEX_CHARTS_KEY!); ``` On `localhost` the library draws without a key: the ORTEX mark stays on the first pane, so this page can be followed before a licence is bought. The console stays quiet unless a chart asks to hide the mark, which without a white-label key writes one warning and leaves the mark on. On any other host a chart with no valid key paints a licence notice instead of its content. See [the ORTEX mark](https://ortexcharts.com/docs/branding) and [license keys](https://ortexcharts.com/docs/licensing). ### Draw the Chart The container needs a height. The chart follows its container with a `ResizeObserver`, so a `height` in CSS is enough and no resize handling is required. ```ts import { createFinancialChart } from "@ortex-charts/financial"; import type { Bar } from "@ortex-charts/math"; const bars: Bar[] = [ { time: 1735689600000, open: 219.4, high: 221.8, low: 218.9, close: 221.2, volume: 41200000 }, { time: 1735776000000, open: 221.3, high: 224.0, low: 220.6, close: 223.7, volume: 38900000 }, // … ]; const el = document.getElementById("chart") as HTMLDivElement; const chart = createFinancialChart(el, { theme: "dark", // "dark", "light", or your own token object timeZone: "America/New_York", resolution: "1D", // datafeed notation: 1, 5, 15, 60, 1D, 1W, 1M data: bars, }); ``` `time` is milliseconds since the Unix epoch, in UTC. Every timestamp in the library is. The time zone controls where bar boundaries fall and how axis labels read, not the timestamps themselves. Bars must be sorted ascending; duplicates and gaps are a question for your feed, not for the chart. `createFinancialChart` returns a small handle, not the engine itself. `chart.chart` is the core `Chart` and `chart.main` is the candlestick series, and everything the handle does not cover is reachable through them. ### Add an Indicator ```ts chart.addIndicator("ema", { length: 21 }); chart.addIndicator("sma", { length: 200 }); chart.addIndicator("rsi"); // lands in a pane of its own ``` There are 51 built-in indicators, listed in [Indicators](https://ortexcharts.com/docs/indicators). Registering your own takes about 20 lines and it then behaves like a built-in one, including in the toolbar menu and in saved layouts. ### Read Values Under the Crosshair ```ts chart.chart.subscribeCrosshairMove((e) => { if (e.index === null) return; // pointer left the chart const v = e.seriesValues.get(chart.main.id); if (v && "close" in v) { console.log(v.open, v.high, v.low, v.close, v.volume); } }); ``` `seriesValues` is a `Map` keyed by series id. Bar series give OHLCV, value series give `{ value }`. ### Push Live Updates The simplest form is a single call per update. An incoming bar whose `time` equals the last bar replaces it in place; a later `time` appends. ```ts chart.update({ time: 1735862400000, open: 223.7, high: 226.1, low: 223.0, close: 225.8, volume: 12400000 }); ``` For a stream of trades rather than bars, hand the chart a source and let it fold ticks into bars of the chart resolution: ```ts import { websocketSource, type LiveItem } from "@ortex-charts/financial"; const source = websocketSource({ url: "wss://feed.example.com/trades", onOpen: (send) => send(JSON.stringify({ subscribe: "ACME" })), parse: (raw) => { const m = JSON.parse(String(raw)) as { t: number; p: number; s: number }; return { time: m.t, price: m.p, size: m.s }; // a Tick }, }); const stop = chart.live(source); // call stop() to unsubscribe ``` The socket opens on the first subscriber, reconnects with backoff, and closes when the last subscriber leaves. [Your own data](https://ortexcharts.com/docs/data) covers datafeeds, adapters and every input shape. _Live example: [live-stream](https://ortexcharts.com/examples/live-stream)_ ### Clean Up ```ts chart.remove(); ``` In a component, call this in the teardown of the effect that created the chart. ## Path Two: A Plain HTML Page Customers on the hosted kit get a single script tag with their key already baked in. There is nothing to install and nothing to configure. ```html
``` The kit is an immediately-invoked bundle of `@ortex-charts/financial` and `@ortex-charts/ui` that puts everything on one global, `OrtexCharts`, and installs the license key for you. `OrtexCharts.createChartShell` is there too, so the whole toolbar is one more call: ```html ``` The CDN serves a kit only to the domains registered on it, so the same script tag on another site returns a 403. Evaluating without a kit works too: load the packages from your own build and leave the key unset. ## The Whole Thing, Once Everything above, together, as one module. This is the shape of nearly every integration. ```ts import { createFinancialChart, setLicenseKey } from "@ortex-charts/financial"; import type { Bar } from "@ortex-charts/math"; void setLicenseKey(import.meta.env.VITE_ORTEX_CHARTS_KEY); export function mountChart(el: HTMLDivElement, bars: Bar[], onHover: (text: string) => void) { const chart = createFinancialChart(el, { theme: "dark", timeZone: "America/New_York", resolution: "1D", watermark: { text: "ACME", visible: true, fontSize: 44 }, data: bars, }); chart.addIndicator("ema", { length: 21 }); chart.addIndicator("sma", { length: 200 }); chart.setMarkers([ { time: bars[120].time, position: "belowBar", shape: "arrowUp", text: "E", tooltip: "Earnings" }, ]); chart.chart.subscribeCrosshairMove((e) => { const v = e.index === null ? null : e.seriesValues.get(chart.main.id); onHover(v && "close" in v ? `O ${v.open} H ${v.high} L ${v.low} C ${v.close}` : ""); }); // Open on the last year rather than on the whole history. chart.chart.timeScale.setVisibleRange(bars.length - 260, bars.length - 1); return () => chart.remove(); } ``` ## Common First Problems - **Nothing is drawn and the container is zero pixels high.** The chart follows its container, so the container needs a height from CSS or from `options.height`. - **Every bar is at the wrong hour.** Timestamps are milliseconds, not seconds; multiply a Unix second timestamp by 1,000 before passing it in. - **Daily bars land on the wrong day.** Set `timeZone` to the exchange time zone rather than leaving it at the default of `UTC`; see [Time, sessions and resolutions](https://ortexcharts.com/docs/time). - **The ORTEX mark is on a licensed chart.** Only a license that grants the `whitelabel` feature (every paid plan) may hide it, and the console says which of the two cases applies. Replacing it with your own needs `brand`, which is an OEM agreement. - **The chart works in development and is blank after a server-side render.** The library is browser-only; create it inside an effect, never during a render on the server. ## Where to Go Next | If you want to | Read | |---|---| | Understand panes, scales, series and the render loop | [Concepts](https://ortexcharts.com/docs/concepts) | | Connect a real feed rather than a static array | [Your own data](https://ortexcharts.com/docs/data) | | Change every color, font and number format | [Colors, fonts and formatting](https://ortexcharts.com/docs/customization) | | Get the toolbar, symbol search and saved layouts | [The shell and layouts](https://ortexcharts.com/docs/shell) | | Write React instead of imperative calls | [React](https://ortexcharts.com/docs/react) | | Know what the library does not do | [Migrating](https://ortexcharts.com/docs/migration) and [Questions we are asked](https://ortexcharts.com/docs/faq) | --- # Installation and delivery > The hosted kit, the private npm registry and the source drop, and which one you want. Section: Start here. Source: https://ortexcharts.com/docs/install ## Three Ways to Get the Library ORTEX Charts is a commercial library, so the code does not come from public npm. There are three delivery modes. They share one license-key system and one set of builds; they differ only in what leaves ORTEX and how much of the plumbing you own. | Mode | What you do | What you get | Who it suits | |---|---|---|---| | Hosted kit | Put one ` ``` Everything exported by the two packages is on the `OrtexCharts` global. There is no module system involved, so `OrtexCharts.createFinancialChart`, `OrtexCharts.createChartShell`, `OrtexCharts.registerIndicator` and the rest are all reachable directly. Two properties are worth knowing about: - `window.__ORTEX_CHARTS_KIT__` carries the kit id, key id, plan, library version and build time, which is what you quote in a support request. - The CDN checks the request `Origin` or `Referer` against the domains registered on the kit before the bytes leave the edge, so a copied script tag on another host returns a 403 rather than a working chart. Kits auto-update within their major version. A new patch or minor release is picked up the next time the file is fetched; a major version is a new URL, so nothing breaks under you. ## The Private Registry Packages live in the GitLab package registry of the `ortex/ortex-charts` project. Two lines in `.npmrc` point the `@ortex-charts` scope at it and supply a token. ```bash # .npmrc — commit this file; the token comes from the environment @ortex-charts:registry=https://gitlab.com/api/v4/projects/86057283/packages/npm/ //gitlab.com/api/v4/projects/86057283/packages/npm/:_authToken=${ORTEX_NPM_TOKEN} ``` The token is issued with the license, is scoped to reading this one package registry, and expires with the license term. Never commit a real token. Export it in your shell for local work and set it as a masked variable in continuous integration: ```bash export ORTEX_NPM_TOKEN="the token from your license email" npm install @ortex-charts/financial @ortex-charts/ui ``` npm, pnpm and yarn all read `.npmrc` in this form. Yarn Berry users who have moved to `.yarnrc.yml` need the equivalent `npmScopes` entry pointing at the same URL. ### Which Packages to Install | Package | Install it when | Depends on | |---|---|---| | `@ortex-charts/math` | You want the scales, sessions, resolutions or rolling statistics without a chart | Nothing | | `@ortex-charts/core` | You are building a chart type of your own on the engine | `math` | | `@ortex-charts/financial` | You want a price chart; re-exports all of `core` | `core`, `math` | | `@ortex-charts/indicators-extra` | You want the 78 extra studies as well as the 51 built in, 129 in all | `financial` | | `@ortex-charts/ui` | You want the toolbar, drawing rail and layouts | `financial` | | `@ortex-charts/lite` | You want sparklines in a table | `math` only | | `@ortex-charts/viz` | You want treemaps, heatmaps, XY, pie or Sankey charts | `core`, `math` | | `@ortex-charts/migrate` | You are coming from TradingView or Highcharts | `ui`, `viz` | | `@ortex-charts/react` | You prefer components and hooks | All of the above | Installing `@ortex-charts/ui` pulls in `financial`, `core` and `math` transitively; you do not have to list them, though listing the ones you import from is good practice. Every package is published at the same version — see [Release notes](https://ortexcharts.com/docs/changelog) — ships ECMAScript modules with declaration files, is marked side-effect free, and has a single entry point. There are no CommonJS builds and no source maps outside the OEM mode. ## Source Access Under OEM An OEM or enterprise agreement includes read access to a mirror of the repository: the TypeScript source of every package, the unit and visual test suites, and the playground application. Building it is `pnpm install && pnpm build`, which writes `packages/*/dist`. The contract, not the code, is what makes this mode different, and it is the only mode in which the source and the tests leave ORTEX. ## Bundler Notes The packages are plain ECMAScript modules with `"sideEffects": false`, which is all a modern bundler needs. A few specifics: - **Tree shaking works, and it matters.** A chart built with `createFinancialChart` and no toolbar is about 56 KB gzipped; adding `@ortex-charts/ui` brings the full chart to about 89.9 KB gzipped. Importing `@ortex-charts/viz` when you only wanted a sparkline is the usual way to pay for something you are not using. - **Vite, Rollup, esbuild, webpack 5 and Next.js need no configuration.** There is no `require`, no Node built-in, and no import of CSS from a package other than `@ortex-charts/ui`, which injects its own stylesheet at runtime rather than shipping a `.css` file to import. - **Webpack 4 and other bundlers without ECMAScript module support will not work**, because no CommonJS build is published. - **There is nothing else to install.** No `@ortex-charts/*` package has a third-party runtime dependency, so an install adds the packages you asked for and nothing behind them. The maths that used to come from D3 is ours; where an algorithm was ported rather than rewritten, the file carries the ISC notice and the third-party notices list it. ## TypeScript Declarations ship with every package, so no `@types` package is needed. The library is written against `"module": "NodeNext"` semantics with explicit `.js` specifiers internally, which means your `tsconfig.json` should use a modern module resolution mode: ```json { "compilerOptions": { "target": "ES2020", "module": "ESNext", "moduleResolution": "Bundler", "lib": ["ES2020", "DOM", "DOM.Iterable"], "strict": true } } ``` `"moduleResolution": "Bundler"` (or `"NodeNext"`) is required; the legacy `"Node"` mode does not read the `exports` field and will not find the types. TypeScript 5.0 or later is expected. One import path is worth memorizing: **the data types live in `@ortex-charts/math`**. `Bar`, `Tick`, `BarSeries`, `ValueSeries`, `Resolution` and `Session` are exported from there, while everything about drawing a chart comes from `@ortex-charts/core` (re-exported by `@ortex-charts/financial`). Installing `financial` puts `math` in `node_modules` transitively, but listing it in `package.json` is worth it if you import the types. ```ts import { createFinancialChart } from "@ortex-charts/financial"; import type { Bar, Tick } from "@ortex-charts/math"; ``` Two further typing habits make the API pleasant. Options objects are `DeepPartial`, so you only write the keys you are changing. Series options are keyed by series type, so `chart.addSeries("candlestick", { … })` narrows to `CandlestickSeriesOptions` and `chart.addSeries("histogram", { colorMode: "sign" })` type-checks without a cast. ## Server-Side Rendering The library is browser-only. It creates canvases, reads `devicePixelRatio`, attaches pointer listeners and observes element sizes, none of which exist on a server. There is no server-side rendering mode and none is planned; chart images for emails and social cards are a separate problem, better solved by a rendering service. In practice this means one rule: **create the chart inside an effect, never during render.** ```tsx "use client"; import { useEffect, useRef } from "react"; import { createFinancialChart, type Bar } from "@ortex-charts/financial"; export function PriceChart({ bars }: { bars: Bar[] }) { const ref = useRef(null); useEffect(() => { if (!ref.current) return; const chart = createFinancialChart(ref.current, { data: bars, resolution: "1D" }); return () => chart.remove(); }, [bars]); return
; } ``` The components in [`@ortex-charts/react`](https://ortexcharts.com/docs/react) already do this: they create the chart in a layout effect guarded by a `typeof window` check, so they render an empty container on the server and fill it on hydration. In Next.js the file still needs the `"use client"` directive, because the effect only runs in a client component. ## Content Security Policy The library needs no `unsafe-eval` and makes no network requests of its own, with one opt-in exception: `setLicenseKey(key, { revocationList })` reads one JSON document from the URL you name, once, after the key verifies. Hosted kits set it to the ORTEX CDN. Three directives are worth checking: - `img-src data:` is needed if the ORTEX mark is shown, because the wordmark is drawn from an inline data URI. It is also needed for symbol logos supplied as data URIs. - `connect-src` must allow your own feed hosts when you use `websocketSource` or a datafeed; the library uses the browser `fetch` and `WebSocket` you would have used yourself. Hosted-kit users additionally need `script-src https://cdn.ortexcharts.com` and `connect-src https://cdn.ortexcharts.com` for the revocation list; a registry install that does not pass `revocationList` needs neither. ## Verifying the Installation The fastest check that everything resolved, the key is valid and the browser is happy: ```ts import { createFinancialChart, licenseStatus, setLicenseKey } from "@ortex-charts/financial"; await setLicenseKey(KEY); console.log(licenseStatus()); // { state: "valid", verified: true, message: "Licensed", payload: { customer, tier, features, domains, exp } } const chart = createFinancialChart(document.body.appendChild(document.createElement("div")), { height: 300, data: [{ time: Date.now(), open: 1, high: 2, low: 0.5, close: 1.5, volume: 10 }], }); ``` A `state` of `unlicensed`, `expired`, `domain` or `invalid` is explained in [license keys](https://ortexcharts.com/docs/licensing). On `localhost` none of them stop the chart from drawing; on any other host every one of them does, and the chart paints a licence notice instead. --- # Concepts > Charts, panes, series, scales, primitives and the render loop, in one page. Section: Start here. Source: https://ortexcharts.com/docs/concepts ## The Shape of the Library Seven packages sit in four layers, and dependencies only ever point downwards. ```text react components and hooks financial lite viz ui product packages core canvas engine: panes, scales, series, interaction math pure functions, no DOM ``` Nothing sits below `math`. There is no third-party runtime dependency anywhere in the library and no third-party code inside it: what you install is our code, written from the ground up, and your lockfile gains one entry per package you actually import. `@ortex-charts/math` has no access to the DOM and no canvas; it runs in Node, in a worker or on a server. `@ortex-charts/core` owns the canvas and the DOM. The product packages register series types, indicators, tools and chrome with the core. `@ortex-charts/react` wraps the product packages and has no logic of its own. The practical consequence is that you can drop a layer at any point. `createChartShell` gives you a whole application; `createFinancialChart` gives you a price chart without chrome; `createChart` gives you an engine with nothing on it. Each returns a handle that exposes the layer below it, so you never have to choose the top layer and then discover a wall. ## Chart, Pane, Price Scale, Series A **chart** is a vertical stack of **panes** that share one time axis. A pane has its own canvases, its own legend and any number of **price scales**. A **series** belongs to one pane and one price scale. ```ts const chart = createChart(el, { theme: "dark", timeZone: "America/New_York" }); const price = chart.addSeries("candlestick", { title: "AAPL" }); price.setData(bars); const rsiPane = chart.addPane({ heightRatio: 0.25 }); const rsi = chart.addSeries("line", { title: "RSI", pane: rsiPane.id, color: "#A78BFA" }); rsi.setData(rsiPoints); ``` Pane heights are relative weights, not pixels. The first pane has a weight of one, so a pane created with `heightRatio: 0.25` takes a fifth of the height. Users can drag the separator between panes, collapse a pane to a legend strip, or maximize one; the core methods for that are `setPaneCollapsed`, `maximizePane` and `restorePanes`. Price scales are addressed by id. `"right"` and `"left"` are drawn on the corresponding edge; any other id is an overlay scale that is not drawn at all, which is how a series gets its own autoscaling without taking up axis width. ```ts chart.addSeries("line", { title: "Volume ratio", priceScaleId: "left" }); chart.addSeries("line", { title: "Score", priceScaleId: "score-only" }); // invisible scale chart.priceScale("left").applyOptions({ mode: "percentage", scaleMargins: { top: 0.2, bottom: 0.05 } }); ``` Each scale carries its own mode: `normal`, `logarithmic`, `percentage` or `indexedTo100`. Autoscale considers only the visible index range and only the visible series on that scale, which is why zooming into a quiet stretch expands the price axis instead of leaving a flat line at the bottom. ## The Index-Based Time Axis The time axis is indexed by **bar position**, not by clock time. Bar 0 is the first bar of the main series, bar 1 the second, and the pixel position of a bar is a linear function of its index. Times in between are interpolated onto fractional indices. This is what makes nights, weekends and holidays disappear without special cases: they are simply absent from the index. It also means a chart can be scrolled past the last bar, since indices extrapolate beyond the data, and that panning cost does not depend on how much history is loaded. The consequences worth internalizing: - Ranges are expressed in indices for precision (`setVisibleRange(from, to)`) and in times for convenience (`setVisibleTimeRange(fromTime, toTime)`); the second converts to the first. - The **main series** owns the timeline. It is the first bar series added, or whatever `chart.setMainSeries(id)` names. - Every other series is **aligned** onto that timeline before it is drawn, which is the next concept. ```ts chart.timeScale.setVisibleRange(bars.length - 260, bars.length - 1); chart.timeScale.fitContent(); chart.timeScale.scrollToRealtime(); chart.timeScale.subscribeVisibleRangeChange((r) => console.log(r.fromTime, r.toTime, r.barSpacing)); ``` ## Alignment: Series That Do Not Share a Timeline Short interest arrives daily while the price chart shows five-minute bars. A benchmark trades on a different calendar. A signal fires on 30 dates in two years. All of these go on the same chart, and none of them share the main timeline. Every series therefore declares an `align` mode, and the engine produces one value per bar of the main timeline before drawing: | Mode | Behavior | Typical use | |---|---|---| | `exact` | A value appears only where the timestamps match exactly. | Indicators computed from the bars themselves. | | `forwardFill` | The last known value is carried forward until the next one. | Slower-moving fundamentals: short interest, cost to borrow, ratings. | | `nearest` | The closest value within `maxGapMs` is used. | Feeds whose timestamps are close but not identical. | | `bucket` | Values are collected into the bar that contains them. | Event counts and other things that are summed per bar. | `forwardFill` is the default for a new series, because it is what a host adding its own data almost always wants. Indicators set `exact` for themselves. Alignment is incremental. When a live tick extends the main timeline in place, only the tail is re-aligned, so an overlay costs work proportional to the new bars rather than to all of the history. _Live example: [short-interest](https://ortexcharts.com/examples/short-interest)_ ## Data Representation Series data is stored as a struct of arrays, not an array of objects. A bar series is `{ length, time, open, high, low, close, volume }` where every column is a `Float64Array`; a value series is `{ length, time, value }`. `NaN` marks a gap. You do not have to build those arrays. `setData` accepts whichever form you have: ```ts series.setData(barRows); // Bar[] series.setData([[time, value], [time, value]]); // [time, value] pairs series.setData([{ time, value }, { time, value }]); // point objects series.setData({ length, time, value }); // columns you already own ``` Passing columns you already own is the cheapest path and the one to prefer for large data sets, because nothing is copied. The trade-off is the invariant that goes with it: aligned columns handed to renderers are **views** into growable buffers, so never hold a reference to `series.columns` across a data change. Timestamps are always milliseconds since the Unix epoch, in UTC. ## The Render Loop Drawing is scheduled on an animation frame and split into layers, so the common interactions do not repaint everything. - Each pane has a **main canvas** (background, grid, series, primitives) and an **overlay canvas** (crosshair, active drawings, tooltips). Moving the crosshair repaints only the overlay canvases and the legend. - The time-axis label has a canvas of its own for the same reason. - Panning and zooming repaint the main canvases, but only for the visible index range, and dense lines are decimated to one minimum and one maximum per pixel column. - Legend DOM is rebuilt only when its content actually changes, so a 60 Hz pan does not churn the DOM. - Live updates append into a capacity-doubling backing store, so a tick does not copy the columns, and indicators recompute a window rather than the whole history. `chart.requestDraw()` schedules a frame, `chart.requestDraw("overlay")` schedules an overlay frame, and `chart.flush()` draws synchronously, which is what a test or a screenshot wants. ## Primitives: Anything That Is Not a Series A **primitive** is an object attached to a pane that can draw in three passes, take part in autoscale, be hit-tested, and consume pointer events before the chart does. Markers, drawings, events, footprints, volume profiles, alerts and indicator band fills are all primitives, and so is anything you write. ```ts import type { PanePrimitive, PaneView } from "@ortex-charts/core"; const sessionShading: PanePrimitive = { id: "session-shading", zIndex: -1, draw(ctx, view: PaneView, layer) { if (layer !== "belowSeries") return; ctx.fillStyle = "rgba(120, 140, 180, 0.08)"; for (let i = view.from; i <= view.to; i++) { if (!isPreMarket(view.indexToTime(i))) continue; ctx.fillRect(view.x(i) - view.timeScale.barSpacing / 2, view.plot.y, view.timeScale.barSpacing, view.plot.height); } }, }; chart.addPrimitive(sessionShading); ``` The `PaneView` a primitive receives carries everything needed to place pixels: `x(index)`, `y(value)`, `valueAt(px)`, `indexAt(px)`, the visible range, the master timeline, the theme, the device pixel ratio and the current hover position. ## Options, Themes and Events Options are deeply partial everywhere. `chart.applyOptions({ crosshair: { mode: "free" } })` changes one nested key and leaves the rest alone, and the same is true of `series.applyOptions`. A **theme** is a flat token object. Switching themes is a repaint, never a rebuild: series, indicators, drawings and the visible range all survive `chart.setTheme("light")`. See [Colors, fonts and formatting](https://ortexcharts.com/docs/customization) for the token list. Events are subscriptions that return their own unsubscribe function, which is the shape the whole library uses: ```ts const off = chart.subscribeCrosshairMove((e) => { /* … */ }); off(); ``` The subscriptions on the core chart are `subscribeCrosshairMove`, `subscribeClick`, `subscribeDblClick`, `subscribeDataChange`, `subscribePaneChange`, `subscribeLegendMenu` and `chart.timeScale.subscribeVisibleRangeChange`. ## State Belongs to the Host The chart never writes to storage and never talks to a server. It does not fetch bars, it does not save layouts, and it has no account system. What it does instead is hand you plain JSON at the boundary. A [layout](https://ortexcharts.com/docs/shell) is a serializable object you store per user. [Drawings](https://ortexcharts.com/docs/drawings) serialize to an array you store per symbol. [Alerts](https://ortexcharts.com/docs/replay) are a list you persist and re-apply. Where the data comes from is a [datafeed or an adapter](https://ortexcharts.com/docs/data) that you supply. This is a deliberate constraint. It keeps ORTEX out of your customers' data, it makes the library work identically behind a login and on a public page, and it means there is no ORTEX service that has to be up for your chart to work. ## Vocabulary | Term | Meaning | |---|---| | Bar | One OHLCV row: `{ time, open, high, low, close, volume }`, optionally with `buyVolume` and `sellVolume`. | | Tick | One trade: `{ time, price, size }`, optionally with an aggressor `side`. | | Resolution | A bar size in datafeed notation: `1`, `5`, `60`, `1D`, `1W`, `1M`. | | Session | Trading hours as `0930-1600`, possibly several segments, or `24x7`. | | Main series | The bar series that owns the timeline. | | Alignment | Placing another series' values onto the main timeline. | | Pane | A horizontal band with its own canvases and scales. | | Primitive | A drawable, hit-testable object on a pane that is not a series. | | Overlay | A host-defined data series the user can switch on from the toolbar. | | Layout | The user's chart configuration as JSON, stored by the host. | --- # Series types > Candlesticks, bars, line, area, baseline, histogram, Heikin-Ashi and your own. Section: Charts. Source: https://ortexcharts.com/docs/series ## The Six Built-In Types Every series is created through `chart.addSeries(type, options)` and returns a `SeriesModel`. Three of the types hold OHLCV bars and three hold single values; the difference matters, because a value series cannot be redrawn as candles. | Type | Kind | Data | Draws | |---|---|---|---| | `candlestick` | bars | `Bar[]` | Body between open and close, wicks to high and low. Hollow and Heikin-Ashi are options on this type, not separate types. | | `bar` | bars | `Bar[]` | A vertical high-low line with an open tick left and a close tick right. | | `line` | values | points | A polyline, optionally curved, optionally with point markers. | | `area` | values | points | A line with a vertical gradient fill beneath it. | | `baseline` | values | points | A line whose halves above and below a base value are colored and filled separately. | | `histogram` | values | points | Columns from a base value, colored fixed, by sign, or by the main series direction. | ```ts const price = chart.addSeries("candlestick", { title: "AAPL" }); price.setData(bars); const ma = chart.addSeries("line", { title: "EMA 21", color: "#F5A524", lineWidth: 1.5 }); ma.setData(emaPoints); ``` _Live example: [stock-chart](https://ortexcharts.com/examples/stock-chart)_ ## Options Every Series Has These come from `SeriesOptionsBase` and apply to all six types and to any type you register yourself. | Option | Type | Default | What it does | |---|---|---|---| | `id` | `string` | generated | Stable identity, useful when you restore a saved chart. | | `title` | `string` | `""` | Name in the legend and in the layout. Placement is keyed by it. | | `pane` | `string` | first pane | Which pane the series lives on. | | `priceScaleId` | `string` | `"right"` | `right`, `left`, or any other id for an undrawn overlay scale. | | `visible` | `boolean` | `true` | Hides the series without removing it; it keeps updating. | | `color` | `string` | next palette color | Line, area and histogram color. | | `lineWidth` | `number` | `2` | Stroke width in CSS pixels. | | `lineStyle` | `"solid" \| "dashed" \| "dotted"` | `"solid"` | Stroke pattern. | | `priceFormat` | `PriceFormat` | price, 2 decimals | Number formatting for the axis, legend and labels. | | `lastValueVisible` | `boolean` | `true` | Value label on the price axis. | | `priceLineVisible` | `boolean` | `false` | Dashed horizontal line at the last value. The `bar` and `candlestick` types default it to `true`. | | `align` | `AlignMode` | `"forwardFill"` | How timestamps map onto the main timeline. | | `zIndex` | `number` | `0` | Draw order within a pane. | | `legendVisible` | `boolean` | `true` | Whether the series appears in the legend. | | `crosshairMarkerVisible` | `boolean` | `true` | Dot on the series at the crosshair index. | `color` left unset takes the next color from the theme palette, so several overlays added in a row are distinguishable without any color management on your side. ## Candlesticks ```ts chart.addSeries("candlestick", { title: "AAPL", upColor: "#22C08A", downColor: "#EF4E5A", wickUpColor: "#22C08A", wickDownColor: "#EF4E5A", borderVisible: true, hollowUp: false, heikinAshi: false, bodyWidthRatio: 0.7, }); ``` `hollowUp` draws up candles with a transparent body, which is the classic hollow-candle style. `bodyWidthRatio` is the fraction of the bar spacing a body occupies; bodies never grow wider than the gap allows and never shrink below one pixel, so a chart at maximum zoom out still reads as candles rather than as mush. Colors left unset fall back to the theme `up`, `down`, `upWick` and `downWick` tokens, which is what makes a theme switch repaint candles correctly without touching the series. ### Heikin-Ashi Heikin-Ashi is an option rather than a type, so it can be toggled without recreating the series or losing the indicators computed from it. ```ts price.applyOptions({ heikinAshi: true }); ``` The transform runs over the raw bars whenever the data or the flag changes. Note the limitation: on a live chart the transform currently re-runs over all bars on every tick, which is measurable on very long intraday histories. Indicators still read the raw columns, so an EMA over Heikin-Ashi candles is an EMA of the real closes. ## OHLC Bars ```ts chart.addSeries("bar", { title: "AAPL", thin: false, openVisible: true }); ``` `thin` drops the open and close ticks and draws only the high-low line, which is what most people want below about four pixels of bar spacing. `openVisible: false` keeps the close tick and drops the open one. ## Line ```ts chart.addSeries("line", { title: "Cost to borrow", curve: "linear", // "linear" | "step" | "monotone" | "smooth" pointMarkers: false, pointRadius: 2.5, align: "forwardFill", }); ``` `curve: "step"` is the right choice for anything that holds a value until it changes, such as a rating, a threshold or a daily statistic drawn on an intraday chart. `monotone` is a shape-preserving spline; `smooth` is a basis spline that does not pass through its points, so avoid it where the exact values matter. Line series decimate when they are denser than the pixels available: one minimum and one maximum per pixel column. The visual result is identical and the cost stops growing with the data. ## Area ```ts chart.addSeries("area", { title: "Estimated Short Interest", color: "#7C5CE6", topColor: "rgba(124, 92, 230, 0.30)", bottomColor: "rgba(124, 92, 230, 0.02)", baseValue: 0, }); ``` `topColor` and `bottomColor` are the ends of a vertical gradient; unset, they come from the theme `areaTop` and `areaBottom` tokens. `baseValue` fills down to a value instead of to the bottom of the pane, which is what you want for a series that can go negative. ## Baseline ```ts chart.addSeries("baseline", { title: "Relative performance", baseValue: 0, // or "first" for the first visible value topLineColor: "#22C08A", bottomLineColor: "#EF4E5A", topFillColor: "rgba(34, 192, 138, 0.18)", bottomFillColor: "rgba(239, 78, 90, 0.18)", }); ``` `baseValue: "first"` re-bases on every pan, which turns the series into "performance since the left edge of the view" without any recomputation on your side. ## Histogram ```ts chart.addSeries("histogram", { title: "Volume", colorMode: "mainDirection", // "fixed" | "sign" | "mainDirection" base: 0, widthRatio: 0.7, upColor: "rgba(34, 192, 138, 0.45)", downColor: "rgba(239, 78, 90, 0.45)", priceFormat: { type: "volume", precision: 0, minMove: 1 }, }); ``` The three color modes cover the three things histograms are used for. `fixed` is one color for a count. `sign` colors above and below `base` differently, which is what a MACD histogram or a delta pane wants. `mainDirection` colors each column by whether the main series bar at the same index closed up or down, which is what a volume pane wants — and it is why `createFinancialChart` does not need you to precompute colored volume rows. ## Setting and Updating Data `setData` replaces everything. `update` handles one row and is the path live data takes. ```ts series.setData(rows); const appended = series.update({ time, open, high, low, close, volume }); // true when a new bar was appended, false when the last bar was replaced in place ``` The rules `update` follows are worth knowing, because the fast paths depend on them: - A `time` equal to the last bar replaces that bar in place. - A later `time` appends into a capacity-doubling backing store, so no column is copied. - An earlier `time` takes a slower rebuild path; feeds that emit out of order pay for it. `series.holdUpdates()` and `series.releaseUpdates()` queue updates and apply them in order later. [Bar replay](https://ortexcharts.com/docs/replay) uses this so a live feed can keep running while the user replays history. ## Switching Type Without Losing State ```ts price.setType("line", { lineWidth: 2 }); ``` `setType` keeps the data, the id, the pane, the scale, the title, the alignment and every base option, and swaps only the renderer and its type-specific defaults. Indicators, markers and drawings attached to the chart are untouched. This is what the toolbar's chart-type buttons call, and it is why switching from candles to a line does not flash. A value series cannot become a bar series, because it has no open, high or low. The call throws with a message that says exactly that. ## Reading Values ```ts series.valueAt(index); // { open, high, low, close, volume } or { value } or null series.primaryValue(index); // the number the axis label and price line use series.lastIndex(); // index of the last finite value, or -1 series.rawLength; // rows as given, before alignment series.raw; // the struct-of-arrays form, or null before setData series.columns; // aligned columns — a view, never hold it across a data change ``` ## Price Lines A price line is a horizontal line at a fixed value on the series' scale, with an axis label. It belongs to the series, so it moves with the scale and disappears with it. ```ts const id = chart.addPriceLine(series.id, { price: 182.5, title: "Entry", color: "#F5A524", lineStyle: "dashed", lineWidth: 1, axisLabelVisible: true, }); chart.removePriceLine(series.id, id); ``` For lines the user can drag, and for crossing notifications, use [alerts](https://ortexcharts.com/docs/replay) instead. ## Writing Your Own Series Type A series type is four functions and a defaults object. Register it once and `chart.addSeries("your-type", …)` works, including in saved layouts and the legend. ```ts import { registerSeriesType, pixelColumns, type SeriesOptionsBase, type SeriesTypeDef } from "@ortex-charts/core"; import { valueExtent } from "@ortex-charts/math"; interface DotOptions extends SeriesOptionsBase { radius: number; } const dotSeries: SeriesTypeDef = { kind: "values", defaults: { radius: 3 }, draw(ctx, view) { const { xs, ys } = pixelColumns(view, "value"); ctx.fillStyle = view.options.color; for (let i = 0; i < xs.length; i++) { if (ys[i] !== ys[i]) continue; // NaN is a gap ctx.beginPath(); ctx.arc(xs[i], ys[i], view.options.radius, 0, Math.PI * 2); ctx.fill(); } }, extent: (columns, from, to) => valueExtent(columns.value, from, to), valueAt: (columns, i) => (columns.value[i] === columns.value[i] ? { value: columns.value[i] } : null), primaryValue: (columns, i) => columns.value[i], }; registerSeriesType("dot", dotSeries); chart.addSeries("dot", { title: "Signals", color: "#F472B6", radius: 4 }).setData(points); ``` The `SeriesView` handed to `draw` carries aligned `columns`, the visible index bounds `from` and `to`, the mappings `x(index)` and `y(value)`, the bar spacing, the resolved theme, the device pixel ratio, the plot rectangle, the hovered index and the main series columns. Draw only between `from` and `to`; the engine has already clipped to the pane. Four rules keep a custom type well behaved: - Return `null` from `extent` when the series should not affect autoscale. - Return `null` from `valueAt` where there is no data, so the legend shows nothing rather than `NaN`. - Treat `NaN` as a gap in every column rather than as a zero. - Add an optional `colorAt` when the series is drawn in more than one color, so the last-value label matches what is on screen. ## What Is Not Here Renko, Kagi, Point and Figure, line break, step-line bars, scatter and HLC area are not built in. They are transforms plus a renderer on the same interfaces shown above, and they are on the roadmap, but today writing one is your work rather than a configuration flag. --- # Indicators > The built-in library, their inputs, and how to register your own in 20 lines. Section: Charts. Source: https://ortexcharts.com/docs/indicators ## Adding One ```ts const ema = chart.addIndicator("ema", { length: 21 }); const rsi = chart.addIndicator("rsi"); // its own pane const macd = chart.addIndicator("macd", { fast: 12, slow: 26, signal: 9 }); ``` An indicator declares its own inputs, outputs, colors and pane, so the second argument is optional and any input you leave out takes its default. Outputs become ordinary series, so everything on [Series types](https://ortexcharts.com/docs/series) applies to them: they appear in the legend, they autoscale, they can be moved to another scale or pane, and they are hidden and shown like any other series. The instance you get back is the handle for changing and removing it: ```ts ema.setInputs({ length: 50 }); // recomputes and relabels ema.setVisible(false); ema.remove(); ema.id; // instance id ema.def; // the definition: name, inputs, outputs, pane, levels ema.paneId; // where it was placed ema.series; // Map ema.inputs; // resolved inputs, defaults filled in ``` ## The Built-In Library There are 51 as of version 0.2.0: 18 that draw on the price pane and 33 that take a pane of their own. That is comparable to Highcharts Stock, which ships about 50, and short of TradingView Advanced Charts, which ships roughly 110, where the long tail is mostly further variations on what is here. Anything missing is a `registerIndicator` call, and the engine — inputs, multiple outputs, bands, levels, own panes, incremental recompute — has no privileged path for the built-ins. The tables below are generated from the registry. `listIndicators()` is the same list at runtime, and it is the one to read if you build your own menu. ### Overlays on the Price Pane | Id | Name | Inputs | Outputs | |---|---|---|---| | `sma` | Moving Average | `length` (20), `source` | `sma` | | `ema` | Exponential Moving Average | `length` (20), `source` | `ema` | | `wma` | Weighted Moving Average | `length` (20), `source` | `wma` | | `vwma` | Volume Weighted Moving Average | `length` (20), `source` | `vwma` | | `hma` | Hull Moving Average | `length` (9), `source` | `hma` | | `dema` | Double Exponential Moving Average | `length` (20), `source` | `dema` | | `tema` | Triple Exponential Moving Average | `length` (20), `source` | `tema` | | `bb` | Bollinger Bands | `length` (20), `mult` (2), `source` | `upper`, `basis`, `lower` | | `keltner` | Keltner Channels | `length` (20), `mult` (2), `atrLength` (10), `source` | `upper`, `basis`, `lower` | | `donchian` | Donchian Channels | `length` (20) | `upper`, `basis`, `lower` | | `envelope` | Envelope | `length` (20), `percent` (2.5), `source` | `upper`, `basis`, `lower` | | `atrbands` | ATR Bands | `length` (14), `mult` (2), `source` | `upper`, `lower` | | `linreg` | Linear Regression Channel | `length` (100), `mult` (2), `source` | `upper`, `basis`, `lower` | | `ichimoku` | Ichimoku Cloud | `conversion` (9), `base` (26), `spanB` (52), `displacement` (26) | `conversion`, `base`, `spanA`, `spanB`, `lagging` | | `psar` | Parabolic SAR | `step` (0.02), `max` (0.2) | `sar` | | `supertrend` | Supertrend | `length` (10), `mult` (3) | `supertrend` | | `pivots` | Pivot Points | `period` (`day`, `week`, `month`), `method` (`classic`, `fibonacci`) | `r3`, `r2`, `r1`, `p`, `s1`, `s2`, `s3` | | `vwap` | VWAP | `anchor` (`session`, `week`, `month`, `all`) | `vwap` | ### Indicators in Their Own Pane | Id | Name | Inputs | Outputs | Levels | |---|---|---|---|---| | `rsi` | Relative Strength Index | `length` (14), `source` | `rsi` | 30, 70 | | `stochrsi` | Stochastic RSI | `rsiLength` (14), `stochLength` (14), `k` (3), `d` (3), `source` | `k`, `d` | 20, 80 | | `macd` | MACD | `fast` (12), `slow` (26), `signal` (9), `source` | `hist`, `macd`, `signal` | 0 | | `ppo` | Percentage Price Oscillator | `fast` (12), `slow` (26), `signal` (9), `source` | `hist`, `ppo`, `signal` | 0 | | `stoch` | Stochastic | `k` (14), `smooth` (3), `d` (3) | `k`, `d` | 20, 80 | | `willr` | Williams %R | `length` (14) | `r` | −80, −20 | | `cci` | Commodity Channel Index | `length` (20) | `cci` | −100, 100 | | `cmo` | Chande Momentum Oscillator | `length` (9), `source` | `cmo` | −50, 50 | | `roc` | Rate of Change | `length` (9), `source` | `roc` | 0 | | `mom` | Momentum | `length` (10), `source` | `mom` | 0 | | `trix` | TRIX | `length` (15), `source` | `trix` | 0 | | `dpo` | Detrended Price Oscillator | `length` (21), `source` | `dpo` | 0 | | `ao` | Awesome Oscillator | `fast` (5), `slow` (34) | `ao` | 0 | | `uo` | Ultimate Oscillator | `fast` (7), `middle` (14), `slow` (28) | `uo` | 30, 70 | | `adx` | Average Directional Index | `length` (14), `smooth` (14) | `adx`, `plus`, `minus` | 25 | | `aroon` | Aroon | `length` (14) | `up`, `down` | 30, 70 | | `vortex` | Vortex Indicator | `length` (14) | `plus`, `minus` | 1 | | `volume` | Volume | `ma` (20) | `volume`, `ma` | — | | `rvol` | Relative Volume | `length` (50) | `rvol` | 1 | | `cumvol` | Cumulative Volume | `length` (20) | `sum` | — | | `obv` | On Balance Volume | — | `obv` | — | | `ad` | Accumulation/Distribution | — | `ad` | — | | `pvt` | Price Volume Trend | — | `pvt` | — | | `mfi` | Money Flow Index | `length` (14) | `mfi` | 20, 80 | | `cmf` | Chaikin Money Flow | `length` (20) | `cmf` | 0 | | `chaikinosc` | Chaikin Oscillator | `fast` (3), `slow` (10) | `osc` | 0 | | `eom` | Ease of Movement | `length` (14), `divisor` (10000) | `eom` | 0 | | `atr` | Average True Range | `length` (14) | `atr` | — | | `stdev` | Standard Deviation | `length` (20), `source` | `stdev` | — | | `hv` | Historical Volatility | `length` (10), `annual` (365) | `hv` | — | | `bbw` | Bollinger Bandwidth | `length` (20), `mult` (2), `source` | `bbw` | — | | `delta` | Volume Delta | `method` (`auto`, `aggressor`, `estimate`) | `delta` | 0 | | `cvd` | Cumulative Volume Delta | `method` (`auto`, `aggressor`, `estimate`) | `cvd` | — | `delta`, `cvd` and `rvol` are covered in detail on [Order flow](https://ortexcharts.com/docs/order-flow); they read the aggressor volumes on the bars when the feed supplies them and say so in the tooltip when they had to estimate instead. The `source` input accepts `close`, `open`, `high`, `low`, `hl2`, `hlc3` and `ohlc4`. Enumerate the registry at runtime rather than hard-coding the list: ```ts import { listIndicators, getIndicator } from "@ortex-charts/financial"; for (const def of listIndicators()) { console.log(def.id, def.name, def.pane, def.inputs.map((i) => i.key)); } getIndicator("rsi").levels; // [30, 70] ``` _Live example: [custom-indicator](https://ortexcharts.com/examples/custom-indicator)_ ## Placement and Color ```ts chart.addIndicator("rsi", { length: 14 }, { pane: "separate", // "overlay", "separate", or an existing pane id paneHeightRatio: 0.25, colors: { rsi: "#A78BFA" }, seriesOptions: { lineWidth: 1, lastValueVisible: false }, sourceSeriesId: comparisonSeries.id, }); ``` - `pane` overrides where the definition wanted to go. Passing an existing pane id puts two indicators in one pane, which is how RSI and Stochastic end up together. - `colors` overrides output colors by output key; unset, each output takes the color its definition derives from the theme, so a theme switch recolors it. - `seriesOptions` is applied to every output series. - `sourceSeriesId` computes the indicator from another bar series instead of the main one, which is how you put an RSI of a comparison symbol on the chart. ## How Live Recomputation Works Indicators recompute whenever the series they read from changes. On a live tick, a full pass over ten years of minute bars for every indicator would be the dominant cost, so an indicator may declare a `lookback`: the number of bars its last value depends on, to the precision that matters on screen. When `lookback` is set, a tick recomputes only the last `max(500, lookback)` bars and patches the final value. This is verified against a full recompute to within 1e-6 in the test suite. Indicators that carry state from the beginning of the data — `obv`, `cvd`, `vwap`, `cumvol` — leave `lookback` unset and recompute fully, which is correct and slower. The practical consequences: - A moving average, RSI or MACD on 100,000 bars costs the same per tick as on 1,000. - Cumulative indicators are the ones to watch on very long histories with a fast feed. - Changing an input forces a full recompute, which is what you want. ## Writing Your Own An indicator is one object. `compute` receives the aligned main-series columns and returns one `Float64Array` per output key, and everything else — the legend label, the settings dialog, the pane, the level lines, the band fill, the layout entry — follows from the declaration. ```ts import { registerIndicator, sourceColumn, type IndicatorDef } from "@ortex-charts/financial"; import { rollingMean, rollingStd } from "@ortex-charts/math"; const zscore: IndicatorDef = { id: "zscore", name: "Z-Score", short: "Z", pane: "separate", levels: [-2, 0, 2], lookback: (inputs) => 10 * Number(inputs.length), inputs: [ { key: "length", name: "Length", type: "number", default: 50, min: 2, max: 2000, step: 1 }, { key: "source", name: "Source", type: "select", default: "close", options: ["close", "open", "high", "low", "hl2", "hlc3", "ohlc4"] }, ], outputs: [{ key: "z", title: "Z", plot: "line", color: (theme) => theme.palette[2] }], compute({ columns, inputs }) { const src = sourceColumn(columns, inputs.source); const length = Number(inputs.length); const mean = rollingMean(src, length); const sd = rollingStd(src, length); const z = new Float64Array(src.length); for (let i = 0; i < src.length; i++) z[i] = sd[i] > 0 ? (src[i] - mean[i]) / sd[i] : NaN; return { z }; }, }; registerIndicator(zscore); chart.addIndicator("zscore", { length: 100 }); ``` Registering it also puts it in the toolbar's indicator menu and lets it survive in a saved [layout](https://ortexcharts.com/docs/shell), because both read the same registry. ### The Definition Fields | Field | Meaning | |---|---| | `id` | Registry key, and what a layout stores. | | `name` | Full name in the menu and the settings dialog. | | `short` | Legend label prefix, for example `EMA`. Inputs are appended automatically. | | `pane` | `"overlay"` for the price pane, `"separate"` for its own. | | `levels` | Constant value lines drawn in a separate pane, such as 30 and 70 for RSI. | | `lookback` | Bars the last value depends on, a number or a function of the inputs. Unset means full recompute. | | `priceFormat` | `{ type, precision }` for the axis and legend of the outputs. | | `inputs` | Declarations the settings dialog is generated from. | | `outputs` | One per returned column. | | `compute` | The calculation. | ### Input Declarations ```ts { key: "length", name: "Length", type: "number", default: 20, min: 1, max: 2000, step: 1 } { key: "source", name: "Source", type: "select", default: "close", options: ["close", "hl2"] } { key: "showBands", name: "Show bands", type: "boolean", default: true } ``` The four types are `number`, `select`, `boolean` and `source`. The shell builds the settings dialog from these declarations, so an indicator you register gets the same dialog the built-ins have. ### Output Declarations ```ts { key: "hist", title: "Histogram", plot: "histogram", signColors: true } { key: "upper", title: "Upper", plot: "band", bandWith: "lower", color: (t) => t.palette[5], lineWidth: 1 } { key: "vol", title: "Volume", plot: "histogram", mainDirectionColors: true } { key: "sum", title: "Sum", plot: "area", color: (t) => t.palette[4] } ``` `plot` is `line`, `histogram`, `area` or `band`. A `band` output pairs with another output named in `bandWith` and the space between them is filled, which is how Bollinger Bands and Donchian Channels get their shading from two ordinary line series. `signColors` colors a histogram by sign; `mainDirectionColors` colors it by the main series candle direction. `color` is a function of the theme rather than a string, so the indicator recolors itself when the theme changes rather than being repainted in a color that no longer fits. ### The Compute Context ```ts compute(ctx) { ctx.columns; // aligned main-series columns: time, open, high, low, close, volume, // plus buyVolume and sellVolume when the feed supplied them ctx.length; // number of bars ctx.inputs; // resolved inputs ctx.timeZone; // the chart time zone, for session-anchored calculations such as VWAP return { key: Float64Array }; } ``` Return arrays of `ctx.length`. Use `NaN` for bars where the indicator has no value, which is normally the warm-up period; the renderer treats `NaN` as a gap and the legend shows nothing rather than a number. `@ortex-charts/math` carries the primitives most indicators need: `rollingSum`, `rollingMean`, `rollingStd`, `rollingMin`, `rollingMax`, `ema`, `wilderSmooth`, `pctChange`, `logReturns`, `cumulativeReturn` and `diff`. They are all typed-array in, typed-array out. ## What Is Not Here - **There is no scripting language.** No Pine Script, no formula editor, no sandbox. Indicators are TypeScript or JavaScript, which is more capable and less safe: an indicator is code you ship, not code your users write. If letting end users author indicators matters to your product, this library does not solve it for you. - **The library is 51 indicators deep, not 110.** Ichimoku, Supertrend, ADX, Parabolic SAR, Keltner Channels, Money Flow Index, Williams %R, Aroon and TRIX all arrived in version 0.2.0, but the far end of the Advanced Charts list is not here, and some of it never will be. - **Indicators of indicators are not declarative.** Computing an RSI of a moving average means doing both calculations inside one `compute`. ## The Extras Package The long tail lives in `@ortex-charts/indicators-extra`, a package of its own so that the chart you ship only carries the studies your users open: 78 more, 30 overlays and 54 in their own pane, which with the built-in 51 is 129, more than TradingView Advanced Charts' catalog of roughly 110. A build that imports it pays about 11 KB gzip; one that does not pays nothing. ```ts import { registerExtraIndicators } from "@ortex-charts/indicators-extra"; registerExtraIndicators(); // once, before the first chart chart.addIndicator("kama", { length: 10 }); ``` **Overlays:** Arnaud Legoux MA, Kaufman adaptive MA, Tillson T3, zero-lag EMA, smoothed MA, least-squares MA, McGinley Dynamic, triangular MA, sine-weighted MA, VIDYA, FRAMA, moving-average cross, moving-average ribbon, Guppy multiple MA, Williams Alligator, Chandelier exit, Chande Kroll stop, standard error bands, zig zag, median price, typical price, weighted close, Camarilla, Woodie and Fibonacci pivot points, VWAP bands, anchored VWAP, rolling VWAP. **Own pane:** Connors RSI, Laguerre RSI, Fisher transform, Schaff trend cycle, Know Sure Thing, Special K, Coppock curve, relative vigor index, relative volatility index, inertia, balance of power, choppiness index, mass index, Elder Ray, force index, accelerator oscillator, gator oscillator, market facilitation index, true strength index, stochastic momentum index, absolute price oscillator, percentage volume oscillator, Klinger volume oscillator, volume oscillator, volume zone and price zone oscillators, negative and positive volume index, Aroon oscillator, Chaikin volatility, ulcer index, Bollinger %B, Qstick, Williams VIX Fix, Woodies CCI, squeeze momentum, linear regression slope, R-squared, standard error, Chande forecast oscillator, efficiency ratio, center of gravity, polarized fractal efficiency, random walk index, trend intensity index, pretty good oscillator, intraday intensity, volume rate of change, trade volume index, Donchian width, coefficient of variation, normalized ATR, true range, performance, Parkinson and Garman-Klass volatility. ## Choosing What Your Users See A catalog of 129 is for you, not necessarily for your users. Two controls decide what an end user is offered. `registerExtraIndicators` takes `only` or `except`, so only the studies you name exist at all; and the shell's `indicators` option curates the menu: which ids, pinned favorites, headed groups, and the labels your users know them by. ```ts registerExtraIndicators({ only: ["kama", "stc", "squeeze", "vwapbands"] }); createChartShell(el, { indicators: { featured: ["sma", "rsi", "squeeze"], groups: [ { title: "Trend", ids: ["sma", "ema", "kama", "supertrend"] }, { title: "Momentum", ids: ["rsi", "macd", "stc", "squeeze"] }, { title: "Volume", ids: ["volume", "vwapbands", "kvo"] }, ], otherTitle: "More", labels: { rsi: "Strength" }, }, }); ``` `include` and `exclude` narrow the list, an array of ids is a plain allowlist, and `false` removes the menu. The menu reads the registry when it opens, so a study registered after the shell was created is offered too. Search matches your labels as well as the standard names. --- # Drawing tools > Trend lines, Fibonacci levels, shapes and notes, with magnet, undo and JSON. Section: Charts. Source: https://ortexcharts.com/docs/drawings ## Attaching the Tools Drawing tools are a primitive on a pane. Create them once and the returned object is the whole API: starting a tool, adding drawings from code, selecting, deleting, undo, redo and serialization. ```ts import { createDrawingTools, createFinancialChart } from "@ortex-charts/financial"; const chart = createFinancialChart(el, { data: bars, resolution: "1D" }); const tools = createDrawingTools(chart.chart, { magnetPx: 8, onChange: (change) => { if (change.type !== "selected" && change.type !== "toolChanged") { saveDrawings(tools.getDrawings()); } }, }); ``` Using [the shell](https://ortexcharts.com/docs/shell) instead gives you the same primitive with a tool rail already wired to it, reachable as `shell.drawings`. ## The 32 Tools Every kind below is placed by clicking, moved by dragging, edited by its handles, hit-tested for tooltips and serialized to the same JSON shape. `POINTS_REQUIRED` is exported, so a custom tool rail can show progress while a drawing is being placed. ### Lines and Freehand | Tool | `kind` | Points | Notes | |---|---|---|---| | Trend line | `trendline` | 2 | Extends left, right, both or neither through `style.extend`. | | Ray | `ray` | 2 | A trend line that always extends right. | | Horizontal line | `horizontalLine` | 1 | Price line across the pane with a value label. | | Horizontal ray | `horizontalRay` | 1 | A price line from its anchor rightward. | | Vertical line | `verticalLine` | 1 | Time line across the pane. | | Arrow | `arrow` | 2 | A line with a head at the second point, labeled from `style.text`. | | Curved arrow | `curvedArrow` | 3 | The third point bends the curve. | | Polyline | `polyline` | Open ended | A click per vertex, ended by a double-click or Enter. | | Brush | `brush` | Open ended | Samples the pointer while the button is held, smoothed. | ### Shapes and Channels | Tool | `kind` | Points | Notes | |---|---|---|---| | Rectangle | `rectangle` | 2 | Filled at `style.fillOpacity`, optional label from `style.text`. | | Ellipse | `ellipse` | 2 | The two points are opposite corners of its bounding box. | | Triangle | `triangle` | 3 | Filled at `style.fillOpacity`. | | Parallel channel | `parallelChannel` | 3 | Two points define the base line, the third the width. | | Regression trend channel | `regressionChannel` | 2 | A least-squares fit between the two times, with a band at `style.deviation` standard deviations either side. | ### Fibonacci, Gann and Pitchfork | Tool | `kind` | Points | Default levels | |---|---|---|---| | Fibonacci retracement | `fibRetracement` | 2 | 0, 0.236, 0.382, 0.5, 0.618, 0.786, 1 | | Fibonacci extension | `fibExtension` | 3 | 0, 0.618, 1, 1.618, 2.618, 3.618, 4.236 | | Fibonacci fan | `fibFan` | 2 | 0.236, 0.382, 0.5, 0.618, 0.786 | | Fibonacci arcs | `fibArcs` | 2 | 0.382, 0.5, 0.618, 1 | | Fibonacci time zones | `fibTimeZone` | 2 | 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, counted in bars | | Fibonacci channel | `fibChannel` | 3 | 0, 0.236, 0.382, 0.5, 0.618, 1, 1.618 | | Gann fan | `gannFan` | 2 | 1/8, 1/4, 1/3, 1/2, 1, 2, 3, 4, 8, as price per bar | | Pitchfork | `pitchfork` | 3 | 1, the median line and its two tines; add 0.5 for the half lines | All eight read `style.levels`, so replacing the array changes which lines are drawn. `LEVELS_BY_KIND` holds the sets that differ from the retracement default, and `levelsFor` returns the one a kind starts with. ### Measurement and Position | Tool | `kind` | Points | Notes | |---|---|---|---| | Measure | `measure` | 2 | Price change, percent change and bar count between two points. | | Price range | `priceRange` | 2 | The vertical move alone, colored up or down. | | Date range | `dateRange` | 2 | The horizontal span alone, in bars and in elapsed time. | | Date and price range | `datePriceRange` | 2 | Both readouts in one box. | | Long position | `longPosition` | 3 | Entry, target and stop, shaded profit and loss, with the reward-to-risk ratio. | | Short position | `shortPosition` | 3 | The same, inverted. | ### Annotation | Tool | `kind` | Points | Notes | |---|---|---|---| | Text | `text` | 1 | A text note anchored to a bar and a price. | | Callout | `callout` | 2 | Text in a rounded box with a tail to the anchor. | | Note with a leader line | `note` | 2 | A dot at the anchor, an underlined note at the second point. | | Price label | `priceLabel` | 1 | The price at a bar as a filled tag, prefixed by `style.text`. | `TEXT_KINDS` names the three that ask the host for their text as they are placed, through `requestText`. ### What the Rail Shows The shell's tool rail shows nine of these by default, because 32 icons crowd a rail: trend line, ray, horizontal line, vertical line, rectangle, parallel channel, Fibonacci retracement, measure and text. Its `drawingTools` option names the set you want instead, in the order you want it. See [The toolbar](https://ortexcharts.com/docs/toolbar). TradingView ships roughly 90 drawing tools, counting the variations within each family. The 32 here are the ones a chart reaches for: the whole Fibonacci set, the channels, the ranges, the position tools and the annotations. Pattern tools, Elliott wave and XABCD among them, are the family that is not here. ## Drawing From the User Interface ```ts tools.startTool("trendline"); // next clicks place the points tools.startTool("fibRetracement", { color: "#F5A524", extend: "right" }); tools.cancelTool(); ``` While a tool is active, each click places a point and the drawing completes when it has the points it needs. Escape cancels. Once a drawing exists, clicking selects it, dragging moves it, and dragging a handle moves one point. Keyboard behavior on a focused chart: | Key | Effect | |---|---| | Escape | Cancel the active tool, or clear the selection. | | Delete or Backspace | Remove the selected drawing. | | Ctrl or Cmd + Z | Undo. | | Ctrl or Cmd + Shift + Z, Ctrl + Y | Redo. | ### Magnet `magnetPx` snaps a placed or dragged price to the nearest open, high, low or close of the bar under the cursor, when one is within that many pixels. It defaults to eight. Setting it to zero disables snapping entirely, which is what a chart of a continuous value rather than of bars wants. ## Drawing From Code ```ts tools.add({ kind: "trendline", points: [ { time: bars[120].time, price: bars[120].low }, { time: bars[300].time, price: bars[300].high }, ], style: { color: "#22C08A", extend: "right", text: "Support" }, meta: { source: "auto-detected", confidence: 0.8 }, }); ``` Only `kind` and `points` are required; the id, style, `locked` and `visible` are filled in. `meta` is carried through serialization untouched, which is where you keep the identifier that links a drawing back to whatever produced it. ```ts tools.updateDrawing(id, { style: { color: "#EF4E5A" }, locked: true }); tools.remove(id); tools.clear(); tools.select(id); // or null to clear the selection tools.selected; // a copy of the selected drawing, or null tools.undo(); tools.redo(); ``` A locked drawing is drawn and hit-tested but cannot be moved, which is the right state for levels your application computed rather than the user drew. ## The Drawing Shape Drawings are plain JSON. Points are anchored to data, not to pixels, so they survive zooming, panning, a resolution change and a window resize. ```ts interface Drawing { id: string; kind: DrawingKind; points: Array<{ time: number; price: number }>; style: DrawingStyle; locked: boolean; visible: boolean; meta?: unknown; } interface DrawingStyle { color: string; // empty string means the theme line color lineWidth: number; // 1.5 lineStyle: "solid" | "dashed" | "dotted"; fillOpacity: number; // 0.12 extend: "none" | "right" | "left" | "both"; text?: string; fontSize: number; // 12 levels?: number[]; // Fibonacci ratios deviation: number; // 2, the regression channel half-width in standard deviations showLabels: boolean; // true } ``` The Fibonacci defaults are `[0, 0.236, 0.382, 0.5, 0.618, 0.786, 1]`. Replace the array to change which levels are drawn, including adding extension levels above one: ```ts tools.add({ kind: "fibRetracement", points: [low, high], style: { levels: [0, 0.382, 0.5, 0.618, 1, 1.618, 2.618] }, }); ``` `DRAWING_STYLE_DEFAULTS` is exported if you want to start from the defaults and change one field. ## Saving and Restoring ```ts const json = JSON.stringify(tools.getDrawings()); tools.setDrawings(JSON.parse(json)); ``` That is the whole persistence story. The chart never writes to storage. Where drawings live is your decision, and the two common answers are different: - **Per symbol.** A trend line drawn on AAPL should be there on every chart of AAPL. This is the most-requested behavior in the category and it is a storage question, so [the shell](https://ortexcharts.com/docs/shell) takes a `drawingsStore` with `load(symbol)` and `save(symbol, drawings)` and does the rest. - **Per layout.** A drawing that belongs to one saved view. Pass `layoutIncludesDrawings: true` to the shell and drawings ride along inside the [layout](https://ortexcharts.com/docs/shell) JSON. Use one or the other, not both. ## Change Events ```ts createDrawingTools(chart.chart, { onChange: (c) => { switch (c.type) { case "created": console.log("added", c.drawing.kind); break; case "updated": console.log("moved", c.drawing.id); break; case "deleted": console.log("removed", c.id); break; case "selected": setSelected(c.id); break; case "toolChanged": setActiveTool(c.kind); break; } }, }); ``` `selected` and `toolChanged` fire for interface state and do not change the data, so persistence should ignore them, which is why the example at the top of this page filters them out. ## Other Hooks ```ts createDrawingTools(chart.chart, { paneId: rsiPane.id, // tools on a pane other than the first priceScaleId: "left", // anchor prices to another scale defaultStyle: { color: "#4C8DFF", lineWidth: 2 }, requestText: async () => window.prompt("Note") ?? null, onEdit: (drawing) => openMyStyleDialog(drawing), priceFormatter: (price) => `$${price.toFixed(2)}`, }); ``` - `requestText` is called when a text drawing is placed. It defaults to `window.prompt`; replace it with your own modal to keep the interface consistent. - `onEdit` fires on a double-click, which is where a style dialog belongs. - `priceFormatter` controls the labels on measures, Fibonacci levels and horizontal lines; it defaults to the main series price format. - One instance covers one pane. Drawing on two panes means two instances. ## Hit Testing and Tooltips Drawings take part in the chart hit test, so a hovered drawing reports through `chart.subscribeCrosshairMove` in the `hit` field of the event, and a click reports through `chart.subscribeClick`. ```ts chart.chart.subscribeClick((e) => { if (!e.hit) return; const payload = e.hit.data as { drawing: Drawing; handle: number } | undefined; if (payload) openDetailPanel(payload.drawing.id, payload.drawing.meta); }); ``` `hit.id` is the drawing id, `hit.data.drawing` is a copy of the drawing including your `meta`, and `hit.data.handle` is the index of the handle under the pointer or −1 for the body. That is enough to open your own context menu or detail panel. --- # Markers and events > Earnings, dividends, filings and news on the chart, as badges, lanes, callouts and ranges. Section: Charts. Source: https://ortexcharts.com/docs/markers ## Two Layers, Different Jobs There are two ways to put something on the chart at a point in time, and they are not interchangeable. - **Markers** (`setMarkers`) are trade-style marks anchored to a bar and a price: arrows, flags, circles, labels. They stack outward on a shared bar and collapse into a count when the zoom gets tight. This is the layer for entries, exits and signals. - **Events** (`setEvents`) are annotations anchored to time, in five presentation styles: lane badges above the time axis, badges next to the bar, callouts with a leader line, vertical lines and shaded ranges. This is the layer for earnings, dividends, filings, lock-ups and news. Both are primitives, both carry a tooltip and an arbitrary payload, and both surface through `chart.subscribeClick`. Use markers for things that belong to a price and events for things that belong to a moment. ## Markers ```ts chart.setMarkers([ { time: bars[120].time, position: "belowBar", shape: "arrowUp", color: "#22C08A", text: "B", tooltip: ["Bought 400 at 182.40", "Order 88213"], data: { orderId: 88213 }, }, { time: bars[164].time, position: "aboveBar", shape: "arrowDown", color: "#EF4E5A", text: "S" }, ]); ``` `setMarkers` replaces the whole list and returns the primitive, so calling it again with a new array is the normal way to update. The primitive is created on the first call and reused after that. | Field | Type | Notes | |---|---|---| | `id` | `string` | Generated when omitted. | | `time` | `number` | Milliseconds since the epoch; snapped to the nearest bar. | | `position` | `"aboveBar" \| "belowBar" \| "inBar" \| "top" \| "bottom"` | Relative to the bar, or pinned to the top or bottom of the pane. | | `shape` | `"arrowUp" \| "arrowDown" \| "circle" \| "square" \| "diamond" \| "flag" \| "label"` | `label` draws `text` in a rounded box. | | `color` | `string` | Falls back to the theme text color. | | `text` | `string` | One or two characters inside or beside the mark. | | `tooltip` | `string \| string[]` | Shown on hover; an array becomes lines. | | `size` | `number` | Overrides the size derived from the bar spacing. | | `data` | `unknown` | Returned with click and hover events. | Behavior worth knowing: - Markers on the same bar stack outward, so a bar with an entry and an exit shows both. - Markers that share a pixel column at low zoom collapse into a count badge, so a decade of trades does not become a solid stripe. - Markers past the last bar on the timeline are not drawn, so [bar replay](https://ortexcharts.com/docs/replay) does not leak the future. ```ts const markers = chart.setMarkers(list); markers.getMarkers(); // the normalized list, ids filled in ``` _Live example: [stock-chart](https://ortexcharts.com/examples/stock-chart)_ ## Events ```ts chart.setEvents([ { time: earnings, style: "lane", group: "Earnings", text: "E", tooltip: ["Q3 earnings", "EPS 2.18 vs 2.04 est"] }, { time: dividend, style: "lane", group: "Dividends", text: "D", tooltip: "Ex-dividend 0.25" }, { time: fomc, style: "line", text: "FOMC", lineStyle: "dashed", color: "#60A5FA" }, { time: newsAt, style: "callout", text: "Guidance raised", position: "aboveBar" }, { time: lockupStart, endTime: lockupEnd, style: "range", text: "Lock-up", color: "#A78BFA" }, ]); ``` ### The Five Styles | Style | Looks like | Used for | |---|---|---| | `lane` | A letter badge in a strip above the time axis, one row per `group`. | Earnings, dividends, splits — the convention traders already read. | | `badge` | A letter in a circle, square or pin next to the bar. | Signals, alerts, pinned news. | | `callout` | A text box on the chart with a leader line to the bar. | Analyst calls, headlines, trade notes. | | `line` | A vertical line across the pane with a label tag. | Macro events, index rebalances, product launches. | | `range` | A shaded band between `time` and `endTime` with a label. | Lock-ups, blackout periods, trading halts. | Lanes never overlap the price, which is why they are the right default for a recurring corporate-action feed. Badges and lane items collapse into a count at low zoom; callouts truncate and stack so they do not cover each other. ### The Event Shape | Field | Type | Notes | |---|---|---| | `id` | `string` | Generated when omitted. | | `time` | `number` | Anchor, in milliseconds. | | `endTime` | `number` | Range end; only for `range`. | | `style` | `EventStyle` | One of the five above. | | `text` | `string` | One or two letters for badges and lanes; the label for the rest. | | `tooltip` | `string \| string[]` | Hover text. | | `color` | `string` | Falls back to the theme. | | `position` | `"aboveBar" \| "belowBar" \| "top" \| "bottom"` | For badges and callouts. | | `price` | `number` | Callout anchor price; defaults to the bar high or low. | | `shape` | `"circle" \| "square" \| "pin"` | Badge shape. | | `group` | `string` | Lane row key; badges of one group share a row. | | `lineStyle` | `"solid" \| "dashed" \| "dotted"` | For `line` events. | | `data` | `unknown` | Returned with click and hover events. | ### Layout Options ```ts import { addEvents } from "@ortex-charts/financial"; const events = addEvents(chart.chart, chart.main, list, { laneHeight: 18, badgeSize: 16, rangeOpacity: 0.12, }); ``` `chart.setEvents(list)` is the same thing with the defaults. Use `addEvents` directly when you want the options or when the events belong to a series other than the main one. ## Reacting to Clicks and Hovers Both layers report through the chart hit test, so one subscription covers everything on the chart, including [drawings](https://ortexcharts.com/docs/drawings) and [alerts](https://ortexcharts.com/docs/replay). ```ts chart.chart.subscribeClick((e) => { if (!e.hit) return; const payload = e.hit.data as { orderId?: number } | undefined; if (payload?.orderId) openOrder(payload.orderId); }); chart.chart.subscribeCrosshairMove((e) => { setHovered(e.hit?.id ?? null); }); ``` The tooltip in `HitResult.tooltip` is rendered by the chart itself, so a marker or event with a `tooltip` needs no work from you. Subscribe only when you want behavior beyond the tooltip. ## A Worked Example: A Corporate-Action Feed The usual integration is a list of dated records from an API turned into lanes, one row per family, with the raw record kept for the detail panel. ```ts type Action = { date: string; kind: "earnings" | "dividend" | "split"; headline: string; detail: string }; const LETTER = { earnings: "E", dividend: "D", split: "S" } as const; const GROUP = { earnings: "Earnings", dividend: "Dividends", split: "Splits" } as const; chart.setEvents( actions.map((a) => ({ time: Date.parse(`${a.date}T00:00:00Z`), style: "lane" as const, group: GROUP[a.kind], text: LETTER[a.kind], tooltip: [a.headline, a.detail], data: a, })), ); chart.chart.subscribeClick((e) => { const action = e.hit?.data as Action | undefined; if (action?.date) showActionDetail(action); }); ``` Events do not need to be sorted; the primitive sorts and normalizes the list. Re-calling `setEvents` on a symbol change replaces everything, which is the intended pattern when the chart changes symbol. --- # Order flow > Footprint bars, volume profile, market profile, delta, cumulative delta and relative volume. Section: Charts. Source: https://ortexcharts.com/docs/order-flow ## The Position This Library Takes Most charting libraries estimate directional volume. They do not know which side was the aggressor, so they infer it from where the price moved inside the bar, which is the tick rule from the 1990s. The delta, cumulative delta and footprint numbers that come out of it disagree with the platforms that read exchange aggressor flags, and traders notice. ORTEX Charts takes the other route. **The host supplies the aggressor data and the library renders it exactly.** Where the data is missing it estimates, marks the result as estimated in the tooltip, and offers a strict mode that shows a gap rather than a guess. That is a real requirement, not a preference: footprint bars, exact volume profiles and true delta need per-price bid and ask volume from your feed. Without it you get the same estimates everyone else produces, honestly labeled. ## The Data Model Three optional shapes carry order-flow information into the library. ```ts // On a bar: volume that lifted the offer and volume that hit the bid. interface Bar { time: number; open: number; high: number; low: number; close: number; volume: number; buyVolume?: number; sellVolume?: number; } // Per bar, per price level: a footprint. interface FootprintBar { time: number; levels: Array<{ price: number; bid: number; ask: number }>; // ascending by price } // On a tick: the aggressor side when the feed reports it. interface Tick { time: number; price: number; size: number; side?: "buy" | "sell" } ``` `bid` is volume that traded at the bid, meaning aggressive sellers. `ask` is volume that lifted the offer, meaning aggressive buyers. `buyVolume` and `sellVolume` travel through every path in the engine: row conversion, bar aggregation, the realtime append buffers, `update`, and the aligned columns indicators read. Two consequences follow from how the columns are allocated: - A series created **without** aggressor volumes ignores them on later bars. History cannot be retro-fitted, so set the first `setData` with the columns you intend to use. - A series created **with** them writes `NaN` for a bar that lacks them, which is what `method: "aggressor"` shows as a gap. ## Footprint Bars ```ts const fp = chart.setFootprint(flow, { tickSize: 0.01, layout: "bidAsk", imbalanceRatio: 3, }); fp.updateBar(liveFootprintBar); // realtime ``` For every bar wider than `minBarWidth` the primitive draws one cell per price level: the bid half shaded in the down color and the ask half in the up color by share of the busiest level in that bar, the numbers when the cell is at least nine pixels high, diagonal imbalances outlined, the bar point of control boxed, and delta plus total volume under the bar. When bars are narrower than `minBarWidth` the cells are unreadable, so the primitive draws a thin per-bar delta strip along the bottom of the pane instead. The information stays visible at every zoom level rather than disappearing. Hovering a cell shows its bid, ask, delta and total. | Option | Default | What it does | |---|---|---| | `minBarWidth` | `28` | Below this bar width in pixels, the delta strip replaces the cells. | | `cluster` | `1` | Merge this many consecutive price levels into one cell. | | `tickSize` | `0` | Level height in price units; zero derives it from the smallest gap between levels. | | `layout` | `"bidAsk"` | `bidAsk` prints bid and ask per cell, `delta` prints ask − bid, `volume` prints the total. | | `imbalanceRatio` | `3` | Outline a level whose ask is at least this many times the bid one level below, and the mirror. Zero disables it. | | `heat` | `true` | Shade cells by volume relative to the busiest level of the bar. | | `showTotals` | `true` | Print delta and total under each bar. | | `showPoc` | `true` | Outline the bar point of control. | | `buyColor` | `null` | Overrides the theme up color. | | `sellColor` | `null` | Overrides the theme down color. | | `stripHeight` | `4` | Height of the fallback delta strip in pixels. | `setFootprint` does two extra things worth knowing. It gives the main bars their aggressor volumes if they arrived without them, so Delta and CVD become exact; and it feeds every volume profile added with `addVolumeProfile`, so those become exact too. _Live example: [footprint](https://ortexcharts.com/examples/footprint)_ ### Building Footprints From Ticks If your feed gives sided ticks rather than pre-aggregated levels: ```ts import { footprintFromTicks, mergeFootprint } from "@ortex-charts/financial"; import { parseResolution } from "@ortex-charts/math"; const flow = footprintFromTicks(ticks, parseResolution("1"), 0.01, "America/New_York"); const barsWithFlow = mergeFootprint(bars, flow); chart.setData(barsWithFlow); chart.setFootprint(flow, { tickSize: 0.01 }); ``` Ticks without a `side` fall back to the tick rule, which is the estimate every platform without aggressor data uses. Pass sided ticks for exact results. `footprintTotals(bar)` gives `{ buy, sell, total, delta, poc }` for one footprint bar, which is what a host-drawn summary row wants. ## Volume Profile and Market Profile ```ts const vp = chart.addVolumeProfile({ mode: "visible", tickSize: 0.01, splitDelta: true }); vp.setRange(fromTime, toTime); // switch to a fixed range vp.setOptions({ mode: "session" }); // one profile per trading day vp.setOptions({ kind: "tpo", tpoPeriodMs: 30 * 60_000 }); // market profile vp.profiles(); // the computed rows, POC and value area ``` ### Modes - `visible` recomputes for the bars currently on screen, cached per range and data version. - `fixed` uses `range`, which is what you set from a date-range drawing or a preset button. - `session` draws one profile per zoned trading day, anchored at the first bar of the day. ### Kinds - `volume` counts volume at price: a volume profile. - `tpo` counts one letter per `tpoPeriodMs` period per row: a market profile. Letters are drawn when rows are at least nine pixels high and a histogram replaces them below that. ### Accuracy With footprint levels attached, volume lands in the row that contains its price and the buy-and-sell split is real. The computed profile reports `exact: true`. Without them, each bar volume is spread evenly over the rows its range covers and split by where the close sits in that range. The profile reports `exact: false` and the tooltip says "estimated". This is the same approximation other libraries make; the difference is that it is labeled. ### Point of Control and Value Area The point of control is the row with the most volume, or the most letters for a market profile. The value area grows outward from it, taking the larger neighbor at each step, until it holds `valueArea` of the total, which defaults to 70 percent. ### Options | Option | Default | What it does | |---|---|---| | `kind` | `"volume"` | `volume` or `tpo`. | | `mode` | `"visible"` | `visible`, `fixed` or `session`. | | `range` | `null` | `[fromTime, toTime]` for `fixed`. | | `rows` | `24` | Number of price rows when `tickSize` is zero. | | `tickSize` | `0` | Row height in price units; capped at 400 rows. | | `width` | `0.3` | Widest bar as a fraction of the plot width, or of the session width. | | `position` | `"right"` | Which edge the profile grows from. | | `valueArea` | `0.7` | Share of volume inside the value area. | | `showPoc` | `true` | Draw the point-of-control line. | | `showValueArea` | `true` | Draw the value area more opaquely. | | `splitDelta` | `false` | Draw buy and sell volume as two stacked segments. | | `showLabels` | `true` | Print the row total when there is room. | | `color`, `buyColor`, `sellColor` | `null` | Override the theme. | | `opacity` | — | Fill opacity of the profile. | | `tpoPeriodMs` | — | Market profile period; one letter per period. | Profiles draw below the series, so they never cover the candles. Hovering a row shows its price range, volume, buy and sell split, and delta. _Live example: [volume-profile](https://ortexcharts.com/examples/volume-profile)_ ### Computing a Profile Without Drawing One `computeProfile` is the pure function behind the primitive and is what the tests cover. Use it when you want the numbers for a table, an export or a rule. It takes bar columns, an inclusive bar-index range, options, and an optional map of footprint bars keyed by bar time. ```ts import { computeProfile, type FootprintBar } from "@ortex-charts/financial"; const raw = chart.main.raw; if (!raw || !("high" in raw)) throw new Error("no bars yet"); const byTime = new Map(flow.map((f) => [f.time, f])); const profile = computeProfile( { time: raw.time, high: raw.high, low: raw.low, close: raw.close, volume: raw.volume }, 0, raw.length - 1, { rows: 40, valueArea: 0.7 }, byTime, ); console.log(profile.rows[profile.poc], profile.vaLow, profile.vaHigh, profile.exact); ``` The primitive already keeps its own computed results, so `vp.profiles()` is the cheaper route when a profile is on screen anyway. ## The Three Indicators | Id | Pane | What it shows | |---|---|---| | `delta` | Separate, histogram colored by sign, level line at zero | Per-bar buy minus sell volume. | | `cvd` | Separate, line | Cumulative delta. | | `rvol` | Separate, histogram, level line at one | Volume over the mean of the previous `length` bars, the current bar excluded. | `delta` and `cvd` share a `method` input: - `auto` uses the real aggressor columns when they exist and estimates otherwise. - `aggressor` uses only real data and writes `NaN` where it is missing, so a gap in the histogram is a gap in the feed rather than a zero. - `estimate` always uses the tick-rule estimate, which is useful when you want the number other platforms would show. ```ts chart.addIndicator("delta", { method: "aggressor" }); chart.addIndicator("cvd", { method: "auto" }); chart.addIndicator("rvol", { length: 50 }); ``` `indicators.barDelta(columns, method)` is exported for hosts that want the numbers without a pane. _Live example: [delta-cvd](https://ortexcharts.com/examples/delta-cvd)_ ## Putting It Together ```ts import { createFinancialChart, mergeFootprint } from "@ortex-charts/financial"; const chart = createFinancialChart(el, { timeZone: "America/New_York", resolution: "1", session: "0930-1600", data: mergeFootprint(bars, flow), seriesOptions: { priceFormat: { type: "price", precision: 2, minMove: 0.01 } }, }); chart.setFootprint(flow, { tickSize: 0.01, layout: "bidAsk", imbalanceRatio: 3 }); chart.addVolumeProfile({ mode: "session", tickSize: 0.01, splitDelta: true }); chart.addIndicator("delta", { method: "aggressor" }); chart.addIndicator("cvd"); ``` ## What Is Not Here - Footprint is a primitive drawn over whichever main series is shown, not a series type of its own, so there is no delta-colored candle style yet. - Composite profiles across several symbols are not supported. - Profiles do not animate as developing profiles during [bar replay](https://ortexcharts.com/docs/replay). - The toolbar has no built-in profile toggle. Adding one is a [`ToolbarAction`](https://ortexcharts.com/docs/toolbar) that calls `addVolumeProfile`. --- # Replay, linking and alerts > Bar replay with higher-timeframe followers, linked charts, and draggable price alerts. Section: Charts. Source: https://ortexcharts.com/docs/replay ## Three Features, One Principle Bar replay, linked charts and price alerts are the three most-requested additions to a charting library after indicators and drawings. All three are implemented the same way here: no server, no account, no ORTEX service. The host keeps whatever state survives a reload, and the library does the rest in the browser. ## Bar Replay Replay steps through history as if it were arriving live. The controller keeps the full data, shows a prefix of it, and appends each next bar **through the realtime path** rather than by redrawing a slice. That detail is what makes it useful: indicators take their incremental fast paths, the volume pane mirrors each bar, and drawings and alerts see exactly the sequence they would see on a live feed. ```ts const replay = chart.replay({ speed: 4 }); // created once, reused after that replay.start({ time: someTime }); // or start(barIndex) replay.step(1); replay.step(-1); replay.play(10); // 10 bars per second replay.pause(); replay.stop(); // put the full history back replay.subscribe((s) => { if (!s.active) return; setPosition(`${s.index + 1} / ${s.total}`, new Date(s.time), s.playing, s.speed); }); ``` `ReplayState` is `{ active, playing, index, total, time, speed }`. `index` is the position in the full history and is −1 while replay is inactive. | Method | What it does | |---|---| | `start(at)` | Begin at a bar index, or at `{ time }`. Defaults to the beginning. | | `step(count)` | Move forward or backward by whole bars. | | `seek(index)` | Jump to a bar. | | `play(speed?)` | Advance automatically at `speed` bars per second. | | `pause()` | Stop advancing, stay in replay. | | `stop()` | Leave replay and restore the full history. | | `link(target, resolution?)` | Make another chart follow the clock. | | `history()` | The full bar array the controller snapshotted. | | `subscribe(cb)` | State changes; returns an unsubscribe function. | Options are `speed` (bars per second, default two) and `follow` (keep the current bar in view while stepping, default true). ### Live Data During Replay A datafeed or WebSocket can keep running while the user replays. Updates that arrive are **held on the series** and applied in order when replay stops, so nothing is lost and nothing jumps into the middle of the replayed sequence. Under the hood this is `SeriesModel.holdUpdates()` and `releaseUpdates()`, which you can use directly for any other reason you might want to freeze a series. Markers and events past the last replayed bar are not drawn, so the future stays hidden rather than spoiling what the replay is for. ### Backward Steps Forward steps append one bar. Backward steps and seeks reset the prefix, which is a rebuild rather than an append. That asymmetry is deliberate: stepping forward is the common case and is cheap, and stepping backward is rare and costs a full recompute. _Live example: [replay](https://ortexcharts.com/examples/replay)_ ### Multi-Timeframe Replay ```ts const unlink = replay.link(fiveMinuteChart); // a FinancialChart, or { chart, main } ``` A linked chart follows the clock. It shows its own bars that closed before the current period, plus the current period **aggregated from the master bars so far**, so a five-minute candle forms in front of the viewer as the one-minute replay advances. This is the behavior traders mean by multi-timeframe replay, and it is the reason the higher timeframe cannot simply be a second replay. Link charts at the master resolution or coarser; linking a finer chart has nothing to aggregate from. Pair it with `linkCharts` when you also want a shared crosshair. ### In the Shell The toolbar's Replay button is off by default because most charts do not want it. ```ts createChartShell(el, { symbol: "AAPL", datafeed, toolbar: { replay: true } }); ``` Clicking it asks for a start bar: the next click on the chart begins the replay there, and a control strip appears under the toolbar with step back, play and pause, step forward, a speed selector from 1× to 30×, the position and an exit button. From code, `shell.replay()` returns the same `ReplayController`, and `shell.startReplay(index?)` and `shell.stopReplay()` drive it without the click. ## Linked Charts ```ts import { linkCharts } from "@ortex-charts/financial"; const unlink = linkCharts([daily.chart, hourly.chart, minute.chart], { timeRange: true, crosshair: true, }); ``` Panning or zooming any chart sets the same **time** span on the others, and the crosshair mirrors by time. Because the link is by time rather than by bar index, it works across resolutions: a daily chart and a one-minute chart stay on the same window and the bar spacing adapts on each. Echoes are suppressed, so there are no feedback loops. Both options default to true; set either to `false` to link only the other. The returned function unlinks everything. There is no grid container in the library, so a two-by-two layout is your own CSS. The link works with any arrangement of containers. ## Price Alerts Alerts are draggable horizontal lines that report crossings to the host. Nothing here talks to a server, sends an email or schedules anything: the library detects the crossing and tells you, and what happens next is your product's decision. ```ts const alerts = chart.alerts({ draggable: true }); alerts.add({ price: 182.5, label: "Breakout", color: "#22C08A" }); alerts.add({ price: 178, label: "Support", repeat: true }); alerts.subscribe((e) => { switch (e.type) { case "triggered": notify(`${e.alert.label} crossed ${e.direction} at ${e.price}`); break; case "added": case "removed": case "moved": saveAlerts(alerts.list()); break; } }); alerts.set(savedAlerts); // on load ``` ### Behavior - The line is dashed with a labeled tag on the right, drawn on the main series scale. - Dragging it moves the price and re-arms the alert, and emits a `moved` event carrying the previous price in `from`. - Every data update — live, replayed or set in bulk — is checked for a crossing of the main series last value, in either direction. - An alert is one-shot by default: it fires once, `triggered` is set, and it does not fire again until it is moved or patched. `repeat: true` fires on every crossing. - `hideTriggered: true` hides the line after a one-shot alert fires. ### The Alert Shape and the API ```ts interface Alert { id: string; price: number; label?: string; color?: string; repeat?: boolean; triggered?: boolean; data?: unknown; // anything you want back with the events } ``` | Method | What it does | |---|---| | `add(alert)` | Add one; `price` is required, the id is generated. | | `remove(id)` | Remove one. | | `patch(id, patch)` | Change price, label, color, repeat or triggered. | | `list()` | Plain JSON for your store. | | `set(list)` | Replace everything, for example after loading. | | `subscribe(cb)` | Alert events; returns an unsubscribe function. | `list()` and `set()` are the whole persistence contract. Store the array against a user and a symbol, restore it when the chart loads, and re-save on `added`, `removed` and `moved`. Alerts have no toolbar chrome in the shell. `shell.chart.alerts()` is the API and the host decides how to present adding one — a button, a context menu, a right-click on the price scale. _Live example: [alerts](https://ortexcharts.com/examples/alerts)_ ## Putting the Three Together A common arrangement: a master chart the user replays, a higher-timeframe chart following the clock, both linked for the crosshair, and alerts that fire during the replay so a strategy can be checked against them. ```ts import { createFinancialChart, linkCharts } from "@ortex-charts/financial"; const minute = createFinancialChart(topEl, { resolution: "1", timeZone: "America/New_York", data: minuteBars }); const fiveMin = createFinancialChart(bottomEl, { resolution: "5", timeZone: "America/New_York", data: fiveMinuteBars }); const unlinkCharts = linkCharts([minute.chart, fiveMin.chart], { crosshair: true, timeRange: false }); const replay = minute.replay({ speed: 8 }); const unlinkReplay = replay.link(fiveMin); const alerts = minute.alerts(); alerts.set(savedAlerts); alerts.subscribe((e) => e.type === "triggered" && toast(`${e.alert.label ?? "Alert"} at ${e.price}`)); replay.start({ time: sessionOpen }); replay.play(); ``` Note that `timeRange` is switched off in this arrangement: the follower chart is driven by the replay clock, so a second synchronization of the visible range would fight it. Keep the crosshair link, drop the range link. --- # Time, sessions and resolutions > Time zones, trading sessions, session-anchored intraday bars and aggregation. Section: Data. Source: https://ortexcharts.com/docs/time ## Timestamps Are Milliseconds, UTC Every timestamp in the library — bars, ticks, events, drawings, alerts, ranges — is milliseconds since the Unix epoch in UTC. There is no other convention anywhere and no per-series exception. A time zone never changes a timestamp. It decides two things: where bar boundaries fall when the library builds or aggregates bars itself, and how the axis, crosshair and legend labels read. ```ts const chart = createFinancialChart(el, { timeZone: "America/New_York", // an IANA zone name locale: "en-GB", // formatting locale for dates and numbers resolution: "1D", }); ``` Zone handling goes through `Intl`, so any IANA zone the browser knows works, daylight saving transitions are handled by the platform rather than by an offset table, and there is no time zone database in the bundle. If your feed sends seconds, multiply by 1,000 before handing the rows over. If it sends `YYYY-MM-DD` for daily bars, the [adapter layer](https://ortexcharts.com/docs/data) has a `date` time unit that parses it as midnight in a named zone, which is almost always what you want for daily data. ## Resolutions A resolution is written in datafeed notation: a number of minutes, or a number with a `D`, `W` or `M` suffix. | Text | Meaning | |---|---| | `1`, `5`, `15`, `30` | Minutes. | | `60`, `240` | Minutes that happen to be whole hours; parsed as hours. | | `1H`, `4H` | Hours, normalized to the minute form. | | `1D`, `3D` | Days. | | `1W` | Weeks. | | `1M`, `3M` | Months. | ```ts import { parseResolution, floorTimeToBar, nextBarTime, sameBar } from "@ortex-charts/math"; const res = parseResolution("15"); // { text: "15", unit: "minute", multiple: 15, isIntraday: true, durationMs: 900000 } floorTimeToBar(Date.now(), res, "America/New_York"); // start of the current bar nextBarTime(Date.now(), res, "America/New_York"); // start of the next one sameBar(a, b, res, "America/New_York"); // do two times share a bar ``` `durationMs` is nominal: calendar units use one day, seven days and 30 days respectively, because a month is not a fixed length. Bar boundaries themselves are computed with calendar arithmetic in the chart time zone, not by dividing by `durationMs`. The chart resolution matters in three places: it is what live ticks are folded into, it is what the axis labels are chosen for, and it is what a datafeed binding requests. Set it in options, or let the [datafeed binding](https://ortexcharts.com/docs/data) set it when the user changes it. ## Sessions A session string describes trading hours as local wall-clock minutes, with commas between segments and an optional day list after a colon. ```text 0930-1600 regular US equity hours 0400-0930,0930-1600,1600-2000 with pre-market and after-hours 24x7 continuous, for crypto 0930-1600:12345 Monday to Friday only (the default anyway) 1700-1600 an overnight session that wraps midnight ``` ```ts import { parseSession, isInSession, sessionBoundsForDay, sessionMinuteAt } from "@ortex-charts/math"; const session = parseSession("0400-0930,0930-1600,1600-2000"); isInSession(Date.now(), session, "America/New_York"); // boolean sessionBoundsForDay(Date.now(), session, "America/New_York"); // [[start, end], …] in ms sessionMinuteAt(Date.now(), session, "America/New_York"); // minutes elapsed in the session, NaN when closed ``` Days are 0 for Sunday through 6 for Saturday, and the default is Monday to Friday. Adjacent segments are merged when parsed, so `0930-1200,1200-1600` becomes one segment. The chart takes the session as an option, and the [datafeed binding](https://ortexcharts.com/docs/data) sets it for you from `SymbolInfo.session` when a symbol resolves. ```ts createFinancialChart(el, { timeZone: "America/New_York", resolution: "60", session: "0930-1600" }); ``` ## Shading Extended Hours An intraday chart of a stock with pre-market and after-hours data draws 04:00 exactly like 10:00, and a reader cannot tell thin extended-hours prints from the real session. Two options fix that, and both are off by default: ```ts createFinancialChart(el, { timeZone: "America/New_York", resolution: "60", session: "0400-0930,0930-1600,1600-2000", sessions: { shadeExtendedHours: true, dayBreaks: true, // Regular hours. Without this the first segment is used, which for the // session above is the pre-market, so a symbol with extended hours wants // it stated. regular: "0930-1600", }, data: bars, }); ``` | Option | Effect | |---|---| | `sessions.shadeExtendedHours` | Fills the columns outside `regular` with the theme's `sessionShade` | | `sessions.dayBreaks` | Draws a line at the first column of each trading day, in the theme's `sessionBreak` | | `sessions.regular` | Regular hours, as a session string. Defaults to the first segment of `session` | The day boundary is the **exchange's**, not the reader's: two bars an hour apart across UTC midnight are one New York day and two London days, and the break is drawn where the exchange says the day turned. Both colours are theme tokens, so a custom theme sets them like any other. Neither option costs anything on a chart that does not use it: a daily chart, or a market with no extended hours, produces no bands. ## Session-Anchored Intraday Bars This is the part that is different from most libraries, and it fixes a long-standing complaint about hourly candles. If hourly bars are floored to the hour, a US equity session produces a first candle covering only 09:30 to 10:00 and then a run of clean hours. The half-hour stub is an artifact of the arithmetic, not of the market. When the chart knows the session, intraday resolutions are **phased from the session open** instead. With `0930-1600`, 60-minute bars run 09:30–10:30, 10:30–11:30 and so on, and pre-market bars keep the same phase going backwards, so 08:30–09:30 lines up with the rest. ```ts import { anchoredResolution, parseResolution } from "@ortex-charts/math"; const res = anchoredResolution(parseResolution("60"), "0930-1600"); // { …, anchorMinute: 570 } // 09:30 expressed in minutes from midnight ``` Four things worth being precise about: - The anchor applies to **everything the library builds or aggregates itself**: ticks folded into bars by `streamTo`, `aggregateBars`, and the higher-timeframe followers in [bar replay](https://ortexcharts.com/docs/replay). - Bars delivered ready-made by a feed are shown exactly as given. The library does not re-cut somebody else's candles. - Daily and longer resolutions, and `24x7` sessions, are unaffected. - With several segments, the regular session is the one that starts latest before noon, so `0400-0930,0930-1600,1600-2000` anchors at 09:30 rather than at 04:00. _Live example: [intraday-session](https://ortexcharts.com/examples/intraday-session)_ ## The Time Axis The axis is indexed by bar position, so closed periods do not exist on it. There is no gap to hide, no `breaks` configuration and no special case for holidays: a day the market did not trade simply has no bars. Tick labels are chosen by weight rather than by a fixed interval, so a year label beats a month label, a month beats a day and a day beats an hour. When there is not room for everything, the more significant labels survive, which is why a two-year daily chart reads as years and months rather than as a row of collided dates. ```ts chart.applyOptions({ timeScale: { barSpacing: 8, // pixels per bar minBarSpacing: 0.5, maxBarSpacing: 60, rightOffsetPx: 60, // empty space right of the last bar fixLeftEdge: false, // stop scrolling past the first bar fixRightEdge: false, followRealtime: true, // follow new bars while the view is at the right edge borderVisible: true, visible: true, }, timeLabelGap: 72, // minimum pixels between time labels }); ``` `followRealtime` is what makes a live chart scroll with new bars only while the user is already at the right edge. Scrolling back into history stops the follow until `scrollToRealtime()` is called or the user pans back. ## Working With Ranges ```ts chart.timeScale.setVisibleRange(fromIndex, toIndex); chart.timeScale.setVisibleTimeRange(fromTime, toTime); chart.timeScale.fitContent(); chart.timeScale.scrollToRealtime(); chart.timeScale.setBarSpacing(12); chart.timeScale.timeToCoordinate(time); chart.timeScale.coordinateToTime(px); chart.timeScale.timeToIndex(time); chart.timeScale.indexToTime(index); const off = chart.timeScale.subscribeVisibleRangeChange((r) => { console.log(r.fromIndex, r.toIndex, r.fromTime, r.toTime, r.barSpacing); }); ``` Index ranges are exact and time ranges are converted to them, so `setVisibleRange` is the right call when you know how many bars you want on screen and `setVisibleTimeRange` is the right call when you are synchronizing with something that thinks in dates. Range presets — 1D, 5D, 1M, 3M, 6M, YTD, 1Y, 5Y, All — are not built into the toolbar. They are a few lines on top of `setVisibleTimeRange`, and adding them as [toolbar actions](https://ortexcharts.com/docs/toolbar) is the usual approach: ```ts const RANGES = { "1M": 30, "3M": 91, "6M": 182, "1Y": 365, "5Y": 1826 }; function applyRange(days: number) { const to = chart.main.rawTimes[chart.main.rawLength - 1]; chart.chart.timeScale.setVisibleTimeRange(to - days * 86_400_000, to); } ``` ## Aggregating Bars Yourself When you have fine bars and want coarse ones without another request: ```ts import { aggregateBars, anchoredResolution, barSeriesFromRows, barSeriesToRows, parseResolution } from "@ortex-charts/math"; const minute = barSeriesFromRows(minuteBars); const hourly = aggregateBars(minute, anchoredResolution(parseResolution("60"), "0930-1600"), "America/New_York"); chart.setData(barSeriesToRows(hourly)); ``` Aggregation carries `buyVolume` and `sellVolume` through when the source has them, so an [order-flow](https://ortexcharts.com/docs/order-flow) chart keeps exact delta after aggregation. ## Formatting Time Yourself ```ts import { formatBarTime, formatClock, formatDate } from "@ortex-charts/math"; formatBarTime(time, { timeZone: "America/New_York", resolution: parseResolution("15"), locale: "en-US" }); formatClock(time, { timeZone: "America/New_York" }); formatDate(time, { timeZone: "America/New_York" }); ``` `formatBarTime` picks the shape from the resolution, which is what the crosshair label uses: a date for daily bars, a date and a time for intraday ones. All three go through `Intl`, so `locale` controls the ordering and the month names. There is no string table for the rest of the interface. The toolbar, menus and dialogs in `@ortex-charts/ui` are English only today; dates and numbers localize, labels do not. --- # Your own data > Static arrays, a datafeed, a WebSocket, or an adapter that maps your existing JSON. Section: Data. Source: https://ortexcharts.com/docs/data ## The Library Never Fetches ORTEX Charts consumes data; it does not go and get it. There is no built-in HTTP client, no symbol database, no cache service and no ORTEX endpoint your chart depends on. You supply rows, or you supply an object that knows how to produce rows, and the chart draws them. That leaves four ways in, in increasing order of how much the library does for you: 1. **A static array.** You already have the bars. Call `setData`. 2. **A datafeed.** An object with `getBars` and optionally `subscribeBars`; the chart handles the initial load, lazy history when the user scrolls left, symbol switching and the realtime subscription. 3. **A live source.** Anything that pushes items over time — a WebSocket, a poller, a handle you push into — folded into bars at the chart resolution. 4. **An adapter spec.** A small JSON description of where history, live data and symbol metadata live in *your* messages, from which the library builds the datafeed and the sources for you. No code per feed. They compose. The common production shape is an adapter spec for the price feed and host-supplied series for everything else. ### If You Do Not Have the Data ORTEX is a market-data company before it is a charting one. The short interest, options flow, fundamentals, analyst estimates and corporate events behind app.ortex.com are published through the ORTEX API, documented at [docs.ortex.com](https://docs.ortex.com), and they arrive in shapes this library draws directly. An OEM agreement can carry a data licence alongside the library, so one contract covers the chart and the numbers on it: [talk to us](https://ortexcharts.com/contact?kind=oem). ## Static Bars ```ts import { createFinancialChart } from "@ortex-charts/financial"; import type { Bar } from "@ortex-charts/math"; const bars: Bar[] = rows.map((r) => ({ time: r.t * 1000, // milliseconds, UTC open: r.o, high: r.h, low: r.l, close: r.c, volume: r.v, })); const chart = createFinancialChart(el, { timeZone: "America/New_York", resolution: "1D", data: bars }); chart.setData(nextBars); // replaces everything ``` Bars must be sorted ascending by time. `volume` is required by the type; use zero when your instrument has none. ### Every Accepted Input Shape `setData` takes whichever of these you already have, so there is normally no conversion step. | Shape | Example | Use for | |---|---|---| | `Bar[]` | `[{ time, open, high, low, close, volume }]` | OHLCV series. | | `BarSeries` | `{ length, time, open, high, low, close, volume }` with `Float64Array` columns | Large OHLCV data you already hold columnar. | | `[time, value][]` | `[[1735689600000, 12.4], …]` | The shape most value endpoints return. | | `{ time, value }[]` | `[{ time: 1735689600000, value: 12.4 }]` | Readable value series. | | `ValueSeries` | `{ length, time, value }` with `Float64Array` columns | Large value data held columnar. | Columnar input is the cheapest, because nothing is copied. Helpers convert between the forms when you need them: ```ts import { barSeriesFromRows, barSeriesToRows, valueSeriesFromPoints, valueSeriesFromColumns } from "@ortex-charts/math"; const series = barSeriesFromRows(bars); const rows = barSeriesToRows(series); const values = valueSeriesFromPoints([[t1, v1], [t2, v2]]); const columns = valueSeriesFromColumns(timeArray, valueArray); ``` ### Optional Aggressor Volumes A bar may carry `buyVolume` and `sellVolume`: the volume that lifted the offer and the volume that hit the bid. They make delta, cumulative delta and split volume profiles exact rather than estimated. See [Order flow](https://ortexcharts.com/docs/order-flow). The one rule to remember is that a series created **without** those columns ignores them on later bars, because history cannot be retro-fitted into an already-allocated column. Decide at the first `setData`. ## A Datafeed A datafeed is one object with one required method. Give it to the chart with `bind` and the chart handles the initial load, paging older history when the user scrolls near the left edge, realtime subscription, and the teardown and reload on a symbol or resolution change. ```ts import type { Datafeed } from "@ortex-charts/financial"; const datafeed: Datafeed = { async resolveSymbol(symbol) { const info = await fetch(`/api/symbols/${symbol}`).then((r) => r.json()); return { symbol, name: info.name, exchange: info.exchange, timeZone: info.tz, // applied to the chart session: info.hours, // applied to the chart, anchors intraday bars currency: info.ccy, priceFormat: { precision: info.decimals, minMove: 10 ** -info.decimals }, logo: info.logoUrl, // shown in the toolbar and the legend }; }, async getBars({ symbol, resolution, from, to, countBack, firstRequest }) { const url = `/api/bars?s=${symbol}&res=${resolution}&from=${from}&to=${to}`; const rows: Array<[number, number, number, number, number, number]> = await fetch(url).then((r) => r.json()); return { bars: rows.map(([t, o, h, l, c, v]) => ({ time: t, open: o, high: h, low: l, close: c, volume: v })), noMoreData: rows.length === 0, }; }, subscribeBars(symbol, resolution, onBar) { const socket = openMyFeed(symbol, resolution, onBar); return () => socket.close(); }, async searchSymbols(query) { return fetch(`/api/search?q=${encodeURIComponent(query)}`).then((r) => r.json()); }, }; const binding = chart.bind(datafeed, { symbol: "AAPL", resolution: "1D" }); ``` ### The Interface ```ts interface Datafeed { resolveSymbol?(symbol: string): Promise; getBars(request: BarsRequest): Promise; subscribeBars?(symbol: string, resolution: string, onBar: (bar: Bar) => void): () => void; searchSymbols?(query: string): Promise; } interface BarsRequest { symbol: string; resolution: string; from: number; // inclusive start, milliseconds to: number; // exclusive end, milliseconds countBack: number; // the caller wants at least this many bars before `to` firstRequest: boolean; } interface BarsResponse { bars: Bar[]; noMoreData?: boolean; // set when the feed knows there is nothing earlier } interface SymbolInfo { symbol: string; name?: string; exchange?: string; timeZone?: string; session?: string; // "0930-1600" priceFormat?: Partial; currency?: string; logo?: string; // URL or data URI } ``` Returning a bare `Bar[]` from `getBars` is allowed; it is treated as `{ bars }` with no `noMoreData`. ### What the Binding Does For You - Resolves the symbol, applies `timeZone`, `session` and `priceFormat` to the chart and the series, and reports the info through `onSymbolInfo`. - Requests an initial window sized from `initialBars` (500 by default) and the resolution, sorts the rows, sets them and scrolls to the right edge. - Watches the visible range and requests older history when fewer than `loadMoreThresholdBars` (60 by default) remain to the left of the view, stopping when the feed returns `noMoreData` or nothing. - Subscribes to realtime bars and applies them through `series.update`, so a bar with the same time replaces the current one and a later time appends. - Cancels in-flight work on a symbol or resolution change with a generation counter, so a slow response for the old symbol cannot land on the new chart. ```ts const binding = chart.bind(datafeed, { symbol: "AAPL", resolution: "1D", initialBars: 800, loadMoreThresholdBars: 100, onSymbolInfo: (info) => setHeader(info.name, info.currency), onLoading: (loading) => setSpinner(loading), onError: (e) => reportError(e), }); await binding.setSymbol("MSFT"); await binding.setResolution("60"); await binding.reload(); binding.dispose(); ``` ## Loading History in Windows A datafeed's `getBars` is asked for more as the reader pans, because the binding knows where the view is. A series you fill yourself has no such help: the obvious code fetches the whole history up front, which for twenty years of daily rows is a slow first paint and a lot of bytes nobody looked at. `attachWindowedData` gives that series the same behavior as the main one. It fetches the visible span plus a margin, and goes back for more only when the view moves past what it already holds. ```ts import { attachWindowedData } from "@ortex-charts/financial"; const series = chart.addSeries("line", { title: "Short interest", priceScaleId: "left" }); const loader = attachWindowedData( chart, series, (from, to) => api.shortInterest(symbol, from, to), // epoch ms, [from, to) { margin: 0.5, // the screen plus half a screen either side earliest: Date.UTC(2005, 0, 1), // never ask for anything older maxSpan: 5 * 365 * 86_400_000, // split a wider gap into steps, nearest the view first initialSpan: 90 * 86_400_000, // the first request when there is no view yet debounce: 150, // quiet time after the view settles onError: (e) => console.warn(e), }, ); ``` Your function is handed a half-open range in epoch milliseconds and returns rows in any order — points or bars. The loader merges them, keeps one copy of each timestamp, and redraws. | Option | Default | What it does | | ----------------- | ------- | --------------------------------------------------------------- | | `margin` | `0.5` | Fraction of the visible span fetched beyond each edge | | `maxSpan` | none | Longest span one request may cover; wider gaps go in steps | | `earliest` | none | Nothing older is ever requested | | `latest` | now | Nothing newer is requested; a function is read on every check | | `debounce` | `150` | Milliseconds of quiet after the view settles | | `initialSpan` | 90 days | The first request when the chart has no visible range yet | | `minGap` | 60 s | A gap narrower than this is not worth a request | | `retryEmptyAfter` | 5 min | How long an edge that answered with nothing is left alone | The last two exist because of what a real feed does at the right-hand edge. Today's row does not exist until it exists, so a naive loader asks for the same missing minutes on every frame. An empty answer is remembered: the left edge is treated as the start of the history and never asked again, and the right edge is left alone for `retryEmptyAfter` before another try. The handle lets you stop or start over: ```ts loader.loading(); // true while a request is out loader.loadedRange(); // { from, to } fetched so far, or null await loader.refresh(); // forget everything and fetch the current window again loader.dispose(); // stop following the view; the series keeps what it has ``` In the [shell](https://ortexcharts.com/docs/shell#overlays-that-load-as-the-reader-scrolls), an overlay gets the same thing as `ctx.windowed(series, fetch)`, with the defaults set once in `overlayLoading`. ## Live Sources A live source is anything with a `subscribe(listener)` that returns an unsubscribe function. `chart.live(source)` folds whatever it emits into the main series. ```ts type LiveItem = | Tick // { time, price, size, side? } — folded into bars | Bar // replaces or appends, finer bars fold into coarser | { time: number; value: number } // for a value series | readonly [number, number]; // [time, value] ``` ### WebSocket ```ts import { websocketSource, type LiveItem } from "@ortex-charts/financial"; const source = websocketSource({ url: "wss://feed.example.com/stream", protocols: ["v2"], onOpen: (send) => send(JSON.stringify({ action: "subscribe", symbols: ["AAPL"] })), parse: (raw) => { const m = JSON.parse(String(raw)) as { ev: string; t: number; p: number; s: number }; return m.ev === "T" ? { time: m.t, price: m.p, size: m.s } : null; // null ignores the message }, onStatus: (s) => setConnectionState(s), // "connecting" | "open" | "closed" | "reconnecting" onError: (e) => console.warn(e), reconnect: true, minReconnectDelayMs: 500, maxReconnectDelayMs: 15000, heartbeat: JSON.stringify({ action: "ping" }), heartbeatMs: 15000, }); const stop = chart.live(source, { resolution: "1", onUpdate: (item, appended) => countTicks(appended) }); ``` The socket opens on the first subscriber and closes when the last one leaves, so subscribing the chart is enough to manage the connection. Reconnection is exponential with jitter. `parse` may return one item, an array of items, or `null` to ignore the message. `chart.connect(options)` is the same thing in one call when the chart is the only consumer; it returns a function that both unsubscribes and closes the socket. ### Polling and Manual Sources ```ts import { pollingSource, ManualSource, type LiveItem } from "@ortex-charts/financial"; const polled = pollingSource(async () => { const q = await fetch("/api/quote/AAPL").then((r) => r.json()); return { time: q.t, price: q.last, size: q.size }; }, 2000); const manual = new ManualSource(); chart.live(manual); manual.push({ time: Date.now(), price: 182.4, size: 100 }); ``` `ManualSource` is the escape hatch for transports the library does not know about: server-sent events, a shared worker, a message bus, a test fixture. _Live example: [live-stream](https://ortexcharts.com/examples/live-stream)_ ### How Folding Works `streamTo` — which is what `chart.live` calls — decides what to do from the shape of the item and the kind of the series: - A **tick** on a bar series extends the current bar or starts a new one at the chart resolution, in the chart time zone, honoring the [session anchor](https://ortexcharts.com/docs/time). - A **bar** on a bar series merges into the current bar of the chart resolution: the open stays, high and low extend, the close follows, and volume accumulates when the incoming bar is a new sub-bar rather than a restatement of the same one. This is what makes one-minute candles from a feed drive a 15-minute chart correctly. - A **value point** on a value series replaces or appends. - A **tick or bar** on a value series contributes its price or close. ## Adapter Specs Writing the datafeed above is 40 lines of glue for every feed. An **adapter spec** replaces it with data: a description of where history, live updates and symbol metadata live in your messages. `createAdapter` turns it into a `Datafeed` and live sources. Because a spec is plain data, it can live in a JSON file, be validated, be versioned, and be tested against a captured sample without running a chart. ```ts import { createAdapter, createFinancialChart } from "@ortex-charts/financial"; const spec = { name: "my-feed", variables: { token: process.env.FEED_TOKEN! }, symbol: { static: { timeZone: "America/New_York", session: "0930-1600", precision: 2, minMove: 0.01 } }, history: { url: "https://api.example.com/v1/{symbol}/bars?res={resolution}&from={from}&to={to}&key={token}", dates: { unit: "date" }, resolutions: { "1D": "daily", "1": "1min", "60": "hourly" }, records: { path: "bars", kind: "bar", time: { path: "d", unit: "date" }, fields: { open: "o", high: "h", low: "l", close: "c", volume: "vol" }, }, }, live: { url: "wss://stream.example.com?key={token}", subscribe: { action: "subscribe", symbols: ["{symbol}"] }, messages: [ { match: [{ path: "ev", equals: "T" }], records: { kind: "tick", time: { path: "t", unit: "ms" }, fields: { price: "p", size: "s" }, filter: [{ path: "sym", equals: "{symbol}" }], }, }, ], }, } as const; const adapter = createAdapter(spec); const chart = createFinancialChart(el, { timeZone: "America/New_York" }); chart.bind(adapter.datafeed, { symbol: "ACME", resolution: "1D" }); chart.live(adapter.live("ACME")); ``` ### The Vocabulary | Concept | What it is | |---|---| | Field path | `a.b[0].c` for objects, a column index such as `3` for array rows, `$` for the record itself. | | Field reference | A path plus `scale`, `offset`, `default` and `map`, for pence-to-pounds conversions and code lookups. | | Time unit | `ms`, `s`, `us`, `ns`, `iso`, `date`, `datetime`, `epochDays`, with a `timeZone` for the date units and an optional `floor` to a bar boundary. | | Records | An array at `path`, a single object, or parallel column arrays with `layout: "columns"`. | | Filter | Conditions applied to each record; `{symbol}` placeholders split a multiplexed feed. | | Message spec | Conditions on a whole message plus a records spec; a feed lists one per message type. | | Templates | `{symbol}`, `{exchange}`, `{ticker}`, `{resolution}`, `{from}`, `{to}`, `{countBack}`, your `variables`, and `{info.}` from symbol resolution. | Records come in three kinds: `bar` (needs `close`), `tick` (needs `price`) and `value` (needs `value`). A `value` record is how a non-price series arrives through the same machinery. ### Field References ```ts // A plain path { close: "c" } // A column index, for array rows like [t, o, h, l, c, v] { time: { path: 0, unit: "ms" }, open: 1, high: 2, low: 3, close: 4, volume: 5 } // Scaling: a feed that quotes UK stocks in pence { close: { path: "px", scale: 0.01 } } // A default when the field is missing { volume: { path: "v", default: 0 } } // A lookup table { value: { path: "rating", map: { BUY: 1, HOLD: 0, SELL: -1 } } } ``` ### Time Fields ```ts { time: { path: "t", unit: "ms" } } { time: { path: "d", unit: "date", timeZone: "America/New_York" } } { time: { path: "ts", unit: "iso" } } { time: { path: "t", unit: "s", floor: "1" } } // candles stamped with the trade time ``` `floor` is the fix for feeds that stamp a one-minute candle with the time of the last trade in it rather than with the start of the bar. ### Columnar Responses ```ts records: { layout: "columns", kind: "bar", time: { path: "t", unit: "s" }, fields: { open: "o", high: "h", low: "l", close: "c", volume: "v" }, } ``` A response of `{ t: [...], o: [...], h: [...], … }` needs nothing more than `layout`. ### Testing a Spec Without a Chart ```ts import { validateAdapterSpec, createAdapter, explainMapping } from "@ortex-charts/financial"; const problems = validateAdapterSpec(spec); // string[] with actionable messages if (problems.length) throw new Error(problems.join("; ")); const adapter = createAdapter(spec); console.log(adapter.explainHistory(capturedResponse)); // the records the chart would see console.log(adapter.explainLive(capturedMessage, "ACME")); // the same for a live message ``` `createAdapter` validates and throws an `AdapterError` listing every problem, so a broken spec fails at construction rather than as an empty chart. When a sample produces nothing, `explainMapping` says why. ### What the Adapter Handles - A reconnecting WebSocket with backoff and heartbeat, one socket per symbol, or one shared socket for a multiplexed feed, opened on the first subscriber and closed on the last. - History paging: more is requested when the user scrolls near the left edge, and the requests stop when the feed says there is nothing earlier. - Folding: ticks become bars at the chart resolution, finer bars fold into coarser ones, and candles stamped with trade times are floored. - Sorting and de-duplication of history rows. ### The Escape Hatches Some feeds need logic no declaration can express. When the spec is authored in TypeScript rather than JSON, `url`, `subscribe`, `unsubscribe` and `body` may be functions of the request context, `symbol.transform` may post-process the resolved info, and any field reference may carry a `transform`. A JSON spec cannot express these; that is the trade-off for the spec being data. ```ts const spec: AdapterSpec = { name: "venue-aware", live: { url: "wss://stream.example.com", subscribe: (ctx) => (ctx.exchange === "LSE" ? [{ sub: `${ctx.isin}GBP` }, { sub: `${ctx.isin}GBX` }] : { sub: ctx.ticker }), messages: [/* … */], }, }; ``` ### The ORTEX Preset `ortexAdapterSpec({ apiBase, wsBase })` returns a spec for ORTEX's own API, so the library is a drop-in on app.ortex.com. It is also the largest worked example of a spec, covering symbol resolution, daily history over HTTP, a live WebSocket with a per-venue subscribe handshake, and symbol search. ```ts import { createAdapter, ortexAdapterSpec } from "@ortex-charts/financial"; const adapter = createAdapter(ortexAdapterSpec({ apiBase: "https://app.ortex.com", wsBase: "wss://ws.ortex.com" })); ``` ## Your Own Series on Their Own Panes This is the case that sells the library, and it needs no adapter at all. A host series is just points, a pane and a scale. ```ts const chart = createFinancialChart(el, { timeZone: "America/New_York", resolution: "1D", volume: false, data: bars }); // Estimated short interest, on a pane of its own, as a percentage. const siPane = chart.chart.addPane({ heightRatio: 0.22 }); chart.chart .addSeries("area", { pane: siPane.id, title: "Estimated Short Interest, % of free float", color: "#7C5CE6", priceFormat: { type: "percent", precision: 2, minMove: 0.01 }, align: "forwardFill", }) .setData(siPoints); // Days to cover, another pane. const dtcPane = chart.chart.addPane({ heightRatio: 0.18 }); chart.chart .addSeries("line", { pane: dtcPane.id, title: "Days to Cover", color: "#F5A524", lineWidth: 1.5 }) .setData(dtcPoints); ``` _Live example: [short-interest](https://ortexcharts.com/examples/short-interest)_ Three details make this work with data that does not share the price timeline: - **`align: "forwardFill"`** carries the last known value forward, which is what a daily statistic on an intraday chart needs. `exact`, `nearest` and `bucket` are the other modes; see [Concepts](https://ortexcharts.com/docs/concepts). - **`priceFormat`** is per series, so a percentage pane and a price pane format independently. - **`priceScaleId`** puts a series on the left scale, or on an id of its own that is never drawn, which gives it independent autoscaling without spending axis width. To overlay rather than separate, drop the pane and choose a scale: ```ts chart.chart.addSeries("line", { title: "Utilization", priceScaleId: "left", color: "#34D399", }).setData(utilizationPoints); chart.chart.priceScale("left").applyOptions({ visible: true, mode: "normal" }); ``` ### Registering Them in the Toolbar When you are using [the shell](https://ortexcharts.com/docs/shell), wrap each of these in an `OverlayDef` and the user gets them in the Data menu, with the checked state and the layout handled for you: ```ts const overlays: OverlayDef[] = [ { id: "si", label: "Short interest", group: "Securities lending", defaultOn: true, add: async ({ chart, symbol }) => { const rows = await api.shortInterest(symbol); const s = chart.addSeries("line", { title: "Short interest", priceScaleId: "left", align: "forwardFill" }); s.setData(rows); return () => chart.removeSeries(s.id); }, }, ]; ``` `add` may be async, receives the symbol to fetch for, and returns the function that removes the overlay again. It is called again after every symbol or resolution change, with the previous disposer run first, so the host never has to watch the chart itself. ## Choosing an Approach | Your situation | Use | |---|---| | The data is already in the page. | `setData`. | | One symbol, no history paging, a push feed. | `setData` plus `chart.live(source)`. | | Symbol switching, resolution switching, lazy history. | A `Datafeed` and `chart.bind`. | | The same as above, but you would rather write JSON than glue. | An adapter spec. | | Non-price series alongside the price. | Host series on their own panes, or `OverlayDef` in the shell. | | A transport the library does not know. | `ManualSource` and push into it. | --- # Colors, fonts and formatting > Theme tokens, per-series colors, number and date formatting, and localization. Section: Customization. Source: https://ortexcharts.com/docs/customization ## Three Levels of Color Colors are resolved in one direction, from general to specific, and knowing the order saves a lot of guessing. 1. **The theme** is a flat token object. Every color the engine paints, when nothing more specific is set, comes from here. 2. **Series options** override the theme for one series: `color`, `upColor`, `topColor` and so on. 3. **Per-value coloring** overrides both, where the type supports it: a histogram in `colorMode: "sign"`, candles in up and down colors, a baseline series above and below its base. The rule to internalize is that **a series left with unset colors follows the theme**. That is what makes `chart.setTheme("light")` repaint an entire chart, indicators included, without touching a single series. Setting explicit colors opts that series out. _Live example: [theme-tokens](https://ortexcharts.com/examples/theme-tokens)_ Throughout this page `chart` is the core `Chart` — `setTheme`, `applyOptions`, `priceScale` and `theme` live there. If you started from `createFinancialChart` or `createChartShell`, reach it as `fc.chart` or `shell.chart.chart`. ## Theme Tokens `darkTheme` and `lightTheme` are exported objects, and a theme is just such an object. Every token is required, so start from one of the built-ins rather than from an empty object. | Token | Type | What it colors | |---|---|---| | `name` | `string` | An identifier for your own bookkeeping. | | `background` | color | The plot area of every pane. | | `axisBackground` | color | The price and time axis strips. | | `axisBorder` | color | The line between the axes and the plot. | | `grid` | color | Grid lines. | | `paneSeparator` | color | The divider between panes. | | `paneSeparatorHover` | color | The same divider while it is being hovered or dragged. | | `text` | color | Axis labels and general text. | | `textMuted` | color | Secondary text. | | `fontFamily` | CSS font stack | Every string the canvas draws. | | `fontSize` | number | Base size in pixels; labels derive from it. | | `crosshair` | color | The crosshair lines. | | `crosshairLabelBackground` | color | The axis tags at the crosshair. | | `crosshairLabelText` | color | Text inside those tags. | | `up` | color | Rising candle bodies and bars. | | `down` | color | Falling candle bodies and bars. | | `upWick` | color | Rising candle wicks. | | `downWick` | color | Falling candle wicks. | | `volumeUp` | color | Volume columns on a rising bar. | | `volumeDown` | color | Volume columns on a falling bar. | | `line` | color | A line or area series with no color of its own. | | `areaTop` | color | Top of the area gradient. | | `areaBottom` | color | Bottom of the area gradient. | | `palette` | `string[]` | Handed to successive overlays and indicator outputs in order. | | `watermark` | color | The watermark text. | | `lastValueText` | color | Text inside the last-value axis label. | | `legendBackground` | color | Behind the legend; transparent in both built-in themes. | | `legendText` | color | Legend text. | | `selection` | color | Selected drawings and selection rectangles. | | `tooltipBackground` | color | Hover tooltips. | | `tooltipText` | color | Tooltip text. | | `tooltipBorder` | color | Tooltip border. | Colors accept `#rgb`, `#rrggbb`, `#rrggbbaa`, `rgb()` and `rgba()`. ### The Palette `palette` is the one token that is not a single color, and it does more work than it looks. Every series added without an explicit `color` takes the next entry, cycling when it runs out. So does every indicator output whose definition asks for `theme.palette[n]`. Setting a brand palette therefore recolors indicators and host overlays at once: ```ts import { darkTheme } from "@ortex-charts/financial"; chart.setTheme({ ...darkTheme, name: "brand-dark", palette: ["#FF7A00", "#7C5CE6", "#00B8D9", "#36B37E", "#FFAB00", "#FF5630"], }); ``` ### Colour-Blind Safe Themes About one man in twelve cannot separate the red and green a candle chart has used since the 1980s. Two themes ship for that, and the toolbar has a switch: ```ts import { createFinancialChart } from "@ortex-charts/financial"; createFinancialChart(el, { theme: "dark-colorblind", data: bars }); ``` | Theme | Up | Down | |---|---|---| | `dark-colorblind` | `#56B4E9` | `#D55E00` | | `light-colorblind` | `#0072B2` | `#E69F00` | Both pairs come from the Okabe-Ito palette, which is chosen to stay apart under deuteranopia, protanopia and tritanopia, and both differ in **luminance** as well as hue, so direction survives a greyscale print, a monochrome display and total colour blindness. Overlay series use the rest of that palette, exported as `OKABE_ITO`. Only the colours that carry meaning change: direction, volume, the overlay palette and the single-series line. The background, grid and text keep the theme they came from, so a colour-blind chart still looks like the rest of your application. Your own theme can have the same treatment: ```ts import { colorBlindSafe } from "@ortex-charts/core"; const acmeSafe = colorBlindSafe(acmeTheme); // name becomes "acme-colorblind" ``` In [the shell](https://ortexcharts.com/docs/shell), the `colorBlind` toolbar item is a switch beside the light and dark one, and the two are independent: turning the palette on keeps you in dark, and switching to light keeps the palette. ### A Complete Custom Theme ```ts import { darkTheme, type Theme } from "@ortex-charts/financial"; export const brandDark: Theme = { ...darkTheme, name: "brand-dark", background: "#0B0E14", axisBackground: "#0B0E14", axisBorder: "#1E2531", grid: "#141A23", text: "#8A96A6", textMuted: "#5A6675", fontFamily: '"Inter", -apple-system, "Segoe UI", Roboto, sans-serif', fontSize: 11, up: "#00C08B", down: "#FF4D5E", upWick: "#00C08B", downWick: "#FF4D5E", volumeUp: "rgba(0, 192, 139, 0.4)", volumeDown: "rgba(255, 77, 94, 0.4)", line: "#4C8DFF", areaTop: "rgba(76, 141, 255, 0.28)", areaBottom: "rgba(76, 141, 255, 0.02)", palette: ["#FFAB00", "#A78BFA", "#F472B6", "#34D399", "#FB923C", "#60A5FA"], }; createFinancialChart(el, { theme: brandDark, data: bars }); ``` ### Switching at Runtime ```ts chart.setTheme("light"); chart.setTheme(brandDark); chart.theme(); // the resolved Theme object ``` A theme change is a repaint, never a rebuild. Series, indicators, drawings, primitives, the visible range and the crosshair position all survive it. Indicator colors are functions of the theme, so they follow too. ### Color Helpers ```ts import { parseColor, withAlpha, contrastText } from "@ortex-charts/financial"; parseColor("#22C08A"); // [34, 192, 138, 1] withAlpha(theme.up, 0.15); // "rgba(34, 192, 138, 0.15)" contrastText("#22C08A"); // "#111418" or "#FFFFFF", whichever reads ``` `contrastText` is what the engine uses for text on colored badges, and it is the right tool for a host drawing its own labels on a theme color. ## Chart Chrome Everything below is a chart option, applied at creation or with `applyOptions`, which is deeply partial so you write only the keys you are changing. ### Grid, Crosshair and Watermark ```ts chart.applyOptions({ grid: { vertical: true, horizontal: true }, crosshair: { mode: "magnet", // "magnet" | "free" | "hidden" vertLine: { visible: true, width: 1, style: "dashed", labelVisible: true, color: "#6F7D91" }, horzLine: { visible: true, width: 1, style: "dashed", labelVisible: true }, }, watermark: { text: "AAPL", visible: true, fontSize: 44 }, }); ``` `magnet` snaps the crosshair to the nearest bar value; `free` follows the pointer exactly; `hidden` removes it while leaving hover events intact. The watermark draws your own artwork instead of the text when you give it one, centred behind the series in the first pane: ```ts chart.applyOptions({ watermark: { visible: true, logo: "https://cdn.example.com/mark.svg", // or "ortex" for the ORTEX wordmark logoScale: 0.25, // height as a fraction of the pane, default 0.25 logoHeight: 120, // exact height in pixels, wins over logoScale opacity: 0.08, // default 0.08 }, }); ``` Keep the opacity low enough that a candle wick still reads over it; the width is capped at 80% of the plot so a wide mark cannot run under the price scale. This is your mark on your chart and is unrelated to the [ORTEX mark](https://ortexcharts.com/docs/branding), which a license removes. ### The Legend ```ts chart.applyOptions({ legend: { visible: true, showValues: true, // OHLC or value at the crosshair, not just titles logo: "https://logos.example.com/aapl.png", symbol: "NASDAQ:AAPL", // printed before the first series title paneControls: true, // the collapse toggle on pane legends collapsed: false, // show only the first row of every pane legend collapsible: true, // the reader's own toggle on that first row }, }); ``` `logo` is drawn before the first series title and is set automatically by the [datafeed binding](https://ortexcharts.com/docs/data) from `SymbolInfo.logo`. A missing image falls back to the color dot silently. `symbol` sits between the logo and the title, which is where an exchange and ticker belong; the [shell](https://ortexcharts.com/docs/shell) fills it in from the current symbol unless you turn that off. A chart carrying a dozen overlays has a legend to match, and a reader who knows what is on it wants the chart back. `collapsed` shows the first row only, and `collapsible` puts a toggle on that row so the reader decides. Both the toggle and the option go through the same three methods, so a host can drive it from its own button and store the answer: ```ts chart.setLegendCollapsed(true); chart.isLegendCollapsed(); // → true const off = chart.onLegendCollapse((e) => save(e.collapsed)); // fires on either route ``` The shell has the button already: add `"legend"` to its `toolbar` items, and the state travels in the layout as `legendCollapsed`. ### Price Scales Each scale is configured independently, per pane. ```ts chart.priceScale("right").applyOptions({ mode: "logarithmic", // "normal" | "logarithmic" | "percentage" | "indexedTo100" autoScale: true, visible: true, scaleMargins: { top: 0.1, bottom: 0.1 }, borderVisible: true, ticksVisible: true, minimumWidth: 64, invert: false, }); chart.priceScale("right", volumePane.id).applyOptions({ scaleMargins: { top: 0.8, bottom: 0 } }); ``` `scaleMargins` are fractions of the pane height left empty above and below the data, which is how a volume pane keeps its columns in the lower fifth. `invert` flips the axis, which is occasionally right for a yield or a rate. ### The Time Scale Covered on [Time, sessions and resolutions](https://ortexcharts.com/docs/time); the options are `barSpacing`, `minBarSpacing`, `maxBarSpacing`, `rightOffsetPx`, `fixLeftEdge`, `fixRightEdge`, `followRealtime`, `borderVisible` and `visible`. ### Interaction and Layout ```ts chart.applyOptions({ handleScroll: true, handleScale: true, kineticScroll: true, // momentum after a fast drag or flick autoSize: true, // follow the container with a ResizeObserver width: 900, // only when autoSize is false height: 480, timeAxisHeight: 26, priceLabelGap: 36, // minimum pixels between price labels timeLabelGap: 72, // minimum pixels between time labels }); ``` Raising `priceLabelGap` and `timeLabelGap` thins the labels, which is the fix for a small chart whose axes look crowded. Lowering them packs more in. ## Number Formatting Formatting is per series, through `priceFormat`. ```ts series.applyOptions({ priceFormat: { type: "price", precision: 2, minMove: 0.01 } }); series.applyOptions({ priceFormat: { type: "volume", precision: 0, minMove: 1 } }); series.applyOptions({ priceFormat: { type: "percent", precision: 2, minMove: 0.01 } }); series.applyOptions({ priceFormat: { type: "custom", precision: 2, minMove: 0.01, formatter: (v) => `${v >= 0 ? "+" : ""}${v.toFixed(2)} bp`, }, }); ``` | `type` | Renders | Used for | |---|---|---| | `price` | `1,234.56` with `precision` decimals | Prices and most values. | | `volume` | `1.23M`, `4.56B` | Volume and share counts. | | `percent` | `12.34%` | Ratios already expressed in percent. | | `custom` | Whatever `formatter` returns | Anything else: basis points, currencies, ratings. | `minMove` is the smallest increment the instrument trades in. It matters because the axis adds decimals when the visible range is narrow, and `minMove` is the floor it will not go below. A `minMove` of `0.01` on a stock and `0.0001` on a currency pair is the usual pairing with `precision` 2 and 4. `formatter` wins over everything else, and it is used for the axis labels, the crosshair tags, the last-value label and the legend, so one function covers them all. The formatting helpers are exported for host-drawn labels: ```ts import { formatPrice, formatPercent, formatCompact, formatVolume, precisionFromMinMove } from "@ortex-charts/math"; import { formatValue } from "@ortex-charts/financial"; formatPrice(1234.5678, { precision: 2 }); // "1,234.57" formatPercent(0.1234, { precision: 2 }); // percent formatting formatCompact(1234567, { precision: 2 }); // "1.23M" formatVolume(1234567); // volume shorthand precisionFromMinMove(0.0001); // 4 formatValue(1234.5, series.options.priceFormat); // exactly what the chart would print ``` ## Dates, Locales and Language Dates and numbers go through `Intl`, so the chart's `locale` option controls month names, date ordering and grouping separators. ```ts createFinancialChart(el, { locale: "de-DE", timeZone: "Europe/Berlin" }); ``` There is a limit worth stating plainly: **the interface strings are English only.** The toolbar labels, menu entries, dialog titles and tooltips in `@ortex-charts/ui` are not translated and there is no string table to supply. Dates and numbers localize; words do not. A host that needs another language today replaces the chrome with its own controls and drives the chart through the shell methods, which are all public. ## Per-Series Overrides at a Glance | Series type | The options that override the theme | |---|---| | `candlestick` | `upColor`, `downColor`, `wickUpColor`, `wickDownColor`, `borderVisible`, `hollowUp`, `bodyWidthRatio` | | `bar` | `upColor`, `downColor`, `thin`, `openVisible` | | `line` | `color`, `lineWidth`, `lineStyle`, `curve`, `pointMarkers`, `pointRadius` | | `area` | `color`, `topColor`, `bottomColor`, `baseValue`, `curve` | | `baseline` | `baseValue`, `topLineColor`, `bottomLineColor`, `topFillColor`, `bottomFillColor` | | `histogram` | `color`, `upColor`, `downColor`, `colorMode`, `base`, `widthRatio` | See [Series types](https://ortexcharts.com/docs/series) for what each one does. ## Styling the Chrome The toolbar and drawing rail in `@ortex-charts/ui` are ordinary DOM. They are styled with CSS custom properties derived from the chart theme, injected once per document, so a theme switch restyles them along with the canvas. ```ts import { applyThemeVars, UI_CSS, ensureStyles } from "@ortex-charts/ui"; ``` `ensureStyles(document)` injects the stylesheet if it is not already there, and `applyThemeVars(element, theme)` writes the custom properties onto an element. The shell does both for you; the exports exist so a host can style its own controls to match, or override the properties in its own stylesheet. Class names are prefixed `oc-ui-`, which makes them stable targets for a host stylesheet without fighting a CSS-in-JS runtime. ## A Practical Recipe: Two Themes and a Toggle ```ts import { createFinancialChart, darkTheme, lightTheme, type Theme } from "@ortex-charts/financial"; const brand = (base: Theme, name: string): Theme => ({ ...base, name, fontFamily: '"Inter", system-ui, sans-serif', palette: ["#FF7A00", "#7C5CE6", "#00B8D9", "#36B37E", "#FFAB00", "#FF5630"], }); const themes = { dark: brand(darkTheme, "brand-dark"), light: brand(lightTheme, "brand-light") }; const chart = createFinancialChart(el, { theme: themes.dark, data: bars }); matchMedia("(prefers-color-scheme: light)").addEventListener("change", (e) => { chart.chart.setTheme(e.matches ? themes.light : themes.dark); }); ``` Deriving both themes from one function keeps the pair consistent, and the switch is a repaint, so it can be wired to a media query without any care about timing. --- # Tooltips and the hover readout > The value beside the cursor: three modes, and a template you write for what it says. Section: Customization. Source: https://ortexcharts.com/docs/tooltips ## The Value Beside the Cursor A chart with a dozen lines on it already has a legend, and the legend carries every series and its value at the crosshair. What it cannot do is answer the question a reader asks by pointing: *what is this one, here?* The tooltip is that answer, and nothing else — it follows the pointer, and by default it says one line rather than all of them. ```ts const chart = createFinancialChart(el, { data: bars, tooltip: { mode: "hovered", template: "{name} {value} 1d {value % value[-1]} 1w {value % value[-7]}", }, }); ``` Hovering the short-interest line then reads: ```text 29 AUG ■ Short interest 12.50 1d +1.20% 1w -3.40% ``` The box carries three things: the hovered bar's date, formatted exactly as the time axis labels it, then a row per series with that series' colour beside it, and under each row whatever the template put after a newline. Set `title: false` to drop the date. ## Three Modes | `mode` | What shows | When to use it | |---|---|---| | `"none"` | Nothing. The default. | A chart that has not asked for a tooltip does not grow one. | | `"hovered"` | One row, for the series under the pointer | A page with many series, where the reader is pointing at one of them | | `"all"` | One row per series on the hovered pane | Two or three series that are read together, such as a spread | `hitRadius` decides how close the pointer has to be, in pixels, for a series to count as hovered. It defaults to 24, which is a comfortable target on a touch screen; lower it if your series sit on top of each other and the wrong one keeps winning. ## The Template The text is a template you write, not a format we picked. It is deliberately small: it reads a value, reads a value from earlier bars, compares two of them, and formats the result. Anything past that is what `formatter` is for. A placeholder is `{ term (operator term)? (|format)? }`. ### Fields | Field | What it reads | |---|---| | `name` | The series title | | `value` | The series' value at the hovered bar; the close, on a candlestick series | | `open`, `high`, `low`, `close` | The bar's own fields | | `volume` | The bar's volume | | `index` | The bar's index in the data, which is occasionally useful while debugging | | `time` | The hovered bar's timestamp | A field can read backwards: `value[-1]` is the bar before the hovered one, `value[-7]` seven bars before it. On a daily chart that is yesterday and last week; on a five-minute chart it is five and thirty-five minutes ago. The offset counts bars, not days, because that is what the chart has. ### Averages `avg(field, n)` is the mean of `n` bars ending at the term's offset, which is how a chart says "against the week behind it". ```ts tooltip: { mode: "hovered", template: "{name} {value|compact} vs 1w average {value % avg(value[-1],7)}" } ``` `avg(value[-1],7)` is the seven bars *before* the hovered one, so today is compared with the week it followed rather than with a week it is part of. A window that runs off the start of the data has no mean, and the row says so with an em dash rather than averaging whatever happens to be there: on the third bar of a chart, a week-average comparison is a question the data cannot answer. Volume carries this by default, so a volume bar reads as busy or quiet rather than as a number on its own. ### Operators | Operator | Meaning | Example | |---|---|---| | `%` | Percent change from the right value to the left, which is what a reader means by "change" | `{value % value[-7]}` → `+4.10%` | | `-` | Difference | `{value - value[-1]}` → `1.20` | | `/` | Ratio | `{high / low\|num}` → `1.03` | ### Formats A format follows a pipe: `{value|compact}`. | Format | Output | |---|---| | `price` | The series' own price format, with its precision. The default for a value. | | `pct` | `+4.10%`. The default when the operator is `%`. | | `num` | `1.03`, rounded to two decimals | | `compact` | `1.25M`, `3.40B` | | `raw` | The number as JavaScript prints it | | `date`, `time` | For `{time}`: `2026-09-07`, or `14:30` | Two rules keep a template honest at the edges. A value the data does not have prints an em dash rather than `NaN`, so a week-change placeholder on the eighth bar of the history says so instead of lying. A placeholder that cannot be parsed is left on the page exactly as it was written, which is how you find a typo without opening the console. ## Two Lines, and a Template per Series A newline in the template starts a quieter line under the value. That is where a change belongs: the value is what the reader came for, and the comparison is context. ```ts template: "{name} {value} 1d {value % value[-1]} 1w {value % value[-7]}" ``` A series can also carry its own text, which overrides the chart's template for that row. A volume histogram wants a different sentence from a price line, and the chart cannot guess which. ```ts chart.addSeries("histogram", { title: "Volume", tooltipTemplate: "{name} {value|compact} vs 1w average {value % avg(value[-1],7)}", }); ``` ## When the Template Is Not Enough `formatter` receives the same row the template would have rendered and returns a string, or `null` to fall back to the template. ```ts tooltip: { mode: "hovered", formatter: (row) => row.name === "Short interest" ? `${row.name} ${row.values.value?.toFixed(2)}% of free float` : null, } ``` The row carries `name`, `time`, `index`, the series' `values` at the hovered bar, its `priceFormat`, and `at(field, offset)` — the same reader the template's offsets use. ## Where It Sits `offset` moves the box relative to the pointer, `{ x: 14, y: 14 }` by default. The box flips to the other side of the cursor by itself when it would leave the chart, so a series at the right edge is still readable. The tooltip is styled from the theme tokens, so it follows a theme change without a second configuration. See [Colors, fonts and formatting](https://ortexcharts.com/docs/customization). ## On the Shell The shell passes the option straight through, so a full chart application configures it in the same place as everything else. ```ts const shell = createChartShell(el, { symbol: "AAPL", datafeed, tooltip: { mode: "hovered", template: "{name} {value} {value % value[-1]}" }, }); ``` Markers keep their own tooltips. A badge or a lane you hover still shows what it was given in `tooltip`, whether or not series tooltips are on, because those two answer different questions. --- # The toolbar and your buttons > Hide what you do not want, add your own buttons and menus, and keep it accessible. Section: Customization. Source: https://ortexcharts.com/docs/toolbar ## The Toolbar Is a Set of Switches `createChartShell` draws a toolbar above the chart and a drawing rail beside it. Every item is independently switchable, and everything an item does is also a method on the returned shell, so a host can hide the whole toolbar and still drive the chart from its own controls. ```ts import { createChartShell } from "@ortex-charts/ui"; const shell = createChartShell(el, { symbol: "AAPL", datafeed, toolbar: { theme: false, screenshot: false, download: true }, resolutions: ["5", "15", "60", "1D", "1W"], indicators: ["sma", "ema", "rsi", "macd", "bb"], drawingTools: ["trendline", "ray", "horizontalLine", "rectangle", "fibRetracement"], }); ``` _Live example: [custom-toolbar](https://ortexcharts.com/examples/custom-toolbar)_ ## The Built-In Items `ToolbarItem` is the union of the switch names. Everything is on by default except `download`. | Item | What it is | Shell method | |---|---|---| | `symbol` | Symbol button opening a search popover; Enter loads typed text | `setSymbol` | | `resolution` | Segmented buttons labeled `1m 5m 15m 1h D W M` | `setResolution` | | `ranges` | Period buttons: `1D 1W 1M 1Q 1Y 5Y 10Y` by default | `setRange` | | `seriesType` | Candles, bars, line, area, baseline, plus Heikin-Ashi and hollow toggles | `setSeriesType` | | `indicators` | Searchable list of the registry, plus the active list with settings, hide and remove | `addIndicator`, `indicators` | | `overlays` | Host data overlays, as a menu or the "Add data to chart" modal | `setOverlay`, `overlays`, `openDataPicker` | | `scale` | Auto, logarithmic and percent scale modes | `setScaleMode` | | `fit` | Fit the whole history into view | — | | `realtime` | Scroll to the latest bar | — | | `replay` | Bar replay; **off by default** | `replay`, `startReplay`, `stopReplay` | | `screenshot` | PNG download, or `onScreenshot` | — | | `download` | CSV of the visible series; **off by default** | `exportCsv` | | `theme` | Light and dark toggle | `setTheme` | | `colorBlind` | Colour-blind safe palette, independent of light and dark | `setTheme` | | `fullscreen` | Full screen and back | `toggleFullscreen` | ```ts toolbar: { replay: true, download: true, theme: false } ``` Switching everything off leaves a bare chart that is still fully driven by the shell methods, which is the supported way to build a completely custom interface without giving up symbol binding, layouts and overlays. `drawings: false` removes the drawing rail entirely. `indicators: false` removes the indicator menu. `indicators: ["sma", "ema"]` limits which ones the menu offers without affecting what `addIndicator` can do from code. ## Configuration as Data Every switch is plain JSON, so a company's chart configuration can live in a checked-in file with only the callbacks attached in code. ```json { "resolutions": ["5", "15", "60", "1D", "1W"], "toolbar": { "theme": true, "colorBlind": true, "screenshot": false, "download": true }, "indicators": ["sma", "ema", "rsi", "macd", "bb"], "drawingTools": ["trendline", "ray", "horizontalLine", "rectangle", "fibRetracement"], "dataPicker": "modal", "compare": true } ``` ```ts import config from "./chart-config.json"; createChartShell(el, { ...config, datafeed, overlays, onLayoutChange: (layout) => api.saveChartLayout("stock-page", layout), }); ``` ## Period Buttons A price chart is read in periods — the last month, the last year — so the toolbar carries them beside the resolutions. The two are different questions: a resolution is how coarse each bar is, a period is how much of the timeline is on screen. ```ts createChartShell(el, { datafeed, ranges: [ { label: "1D", ms: 86_400_000, resolution: "5", title: "The last day, in five-minute bars" }, { label: "1W", ms: 7 * 86_400_000, resolution: "60" }, { label: "1M", ms: 30 * 86_400_000 }, { label: "1Q", ms: 91 * 86_400_000 }, { label: "1Y", ms: 365 * 86_400_000 }, { label: "5Y", ms: 5 * 365 * 86_400_000, resolution: "1W" }, { label: "10Y", ms: 10 * 365 * 86_400_000, resolution: "1W" }, ], rangeDisplay: "auto", }); ``` `ranges` defaults to a day, a week, a month, a quarter, a year, five years and ten years, with no resolution attached. `DEFAULT_RANGES` is exported if you want to extend that list rather than replace it. Pass `false`, or `toolbar: { ranges: false }`, to leave the buttons out. Seven periods are seven clicks saved on a trading screen and seven buttons of clutter in a sidebar, and the same chart is often both. `rangeDisplay` decides which it is: | Value | What you get | |---|---| | `"auto"` (default) | Spelled out when the chart is wide enough, folded into one button when it is not, changing as the chart is resized | | `"buttons"` | Always spelled out | | `"menu"` | Always one button naming the current period | Folded, the button says which period is showing, or `Period` when the reader has moved to a view that is not one of them. | Field | What it does | |---|---| | `label` | What the button says | | `ms` | How much time it shows, ending at the last bar | | `resolution` | Switch resolution with it, for spans where the two only make sense together | | `title` | Tooltip and accessible name | Two details worth knowing. Each period ends at the **last bar rather than at the clock**, so a market that closed on Friday still shows its last month rather than a month of empty axis. And the button matching the view is lit only while it matches: pan or zoom away and it stops claiming to be what you are looking at. A period shorter than the chart can zoom to settles wider than asked, because bar spacing is capped — a week is seven daily bars, and seven bars do not stretch across a wide pane. That is what the `resolution` field is for. `shell.setRange(ms, resolution?)` does the same thing from your own control. ## One Row, Not Two A toolbar that carries every control wraps onto a second row on anything narrower than a wide desktop. That row costs the chart about forty pixels of height, and it costs them from the part of the screen a reader is actually looking at. So by default it does not wrap: it gives things up instead, in order of how little they are missed. | Step | What goes | What is left | |---|---|---| | 1 | The words on buttons that read as icons | Candles, Indicators, Data and Drawing tools as icons, with the words as tooltips | | 2 | The period buttons | One button naming the period showing | | 3 | The view and export controls | One **More** button holding them as a palette | | 4 | The middle resolutions | The shortest, the longest and the selected one, with a chevron holding the rest | Each step is applied only if the one before it was not enough, and the whole thing runs again whenever the chart is resized, so a chart that grows takes it all back. Everything given up stays one click away. ```ts createChartShell(el, { symbol: "AAPL", datafeed, toolbarFit: "auto", // the default; "wrap" takes a second row instead extrasCollapsed: true, // start with the tail folded, at any width drawingRailCollapsed: true, // the drawing tools folded to a thumb }); ``` `toolbarFit` is about what fits. `extrasCollapsed` and `drawingRailCollapsed` are about what you want to start with, and they hold at every width. The two are kept apart on purpose: folding because a chart is narrow is not the same as a reader choosing to fold, so a reader who opens the tail keeps it open at every width that can hold it. `extrasCollapsed` folds the right-hand end of the toolbar: the scale modes, fit, the legend and drawing-rail toggles, realtime, replay, download, screenshot, theme, colour-blind and full screen, behind a single **More** button. Opening it shows the same buttons as a small palette, with an item that puts them back in the toolbar for good. `drawingRailCollapsed` does the same for the drawing tools down the left edge, leaving a thumb that opens them. Both are starting positions, not locks. The reader's own choice is recorded in the layout and outranks the option on every later visit, and a layout that has never carried the field, which is every layout saved before you turned the option on, counts as no choice rather than as a vote for the old behaviour. ```ts shell.setExtrasCollapsed(false); // and shell.isExtrasCollapsed() shell.setDrawingRailCollapsed(true); ``` ## Your Own Buttons `ToolbarAction` adds a button or a dropdown. It is data plus callbacks, so it fits the same configuration-file pattern. ```ts interface ToolbarAction { id: string; label?: string; // icon-only when omitted icon?: IconName | string; // a built-in name, or your own markup title?: string; // tooltip and accessible name; defaults to label placement?: "start" | "middle" | "end"; onClick?: (shell: ChartShell, event: MouseEvent) => void; menu?: Array<{ label: string; icon?: IconName; hint?: string; onSelect: (shell: ChartShell) => void }>; active?: boolean; // render as pressed disabled?: boolean; } ``` ```ts createChartShell(el, { symbol: "AAPL", datafeed, actions: [ { id: "api", label: "Download with API", icon: "api", placement: "end", onClick: (shell) => openApiDialog(shell.symbol(), shell.resolution()), }, { id: "share", icon: "share", title: "Share", menu: [ { label: "Copy link", onSelect: (s) => navigator.clipboard.writeText(linkFor(s.getLayout())) }, { label: "Post to Slack", icon: "camera", onSelect: (s) => slack(s.chart.chart.takeScreenshot()) }, ], }, ], }); ``` `placement` decides where the button lands: `start` puts it with the symbol and resolutions, `middle` with the chart-type menus, and `end` at the right, which is the default. At runtime, `shell.addAction(action)` adds one and returns a function that removes it again, which is how a button appears only in a particular application state. ```ts const removeAlertButton = shell.addAction({ id: "add-alert", icon: "plus", title: "Add alert at the last close", onClick: (s) => { const last = s.chart.main.lastIndex(); const v = s.chart.main.valueAt(last); if (v && "close" in v) s.chart.alerts().add({ price: v.close, label: "New alert" }); }, }); removeAlertButton(); ``` ### A Button That Carries State `active` is read when the toolbar is built, so a button whose meaning changes — an adjusted-prices toggle, a "follow the last price" switch — is updated with `setAction` rather than by handing the shell a new definition. Rebuilding the options array, which is what a React host does on every render, changes nothing: the shell is created once. ```ts let adjusted = false; createChartShell(el, { datafeed, actions: [ { id: "adj", label: "ADJ", title: "Adjust prices for dividends", active: adjusted, onClick: (shell) => { adjusted = !adjusted; shell.setAction("adj", { active: adjusted, title: adjusted ? "Showing dividend-adjusted prices" : "Adjust prices for dividends", }); void shell.binding?.reload(); // the feed reads the flag itself }, }, ], }); ``` `setAction(id, patch)` takes any of `active`, `disabled`, `label` and `title`, changes only what the patch names, and does nothing for an id the toolbar does not have. `active` also sets `aria-pressed`, so the state is announced rather than only drawn. `binding.reload()` is the other half of that pattern: the same symbol fetched again because something the feed reads for itself changed. It does not resolve the symbol a second time, and it puts the reader back where they were looking instead of jumping to the right edge. ## Icons `ICONS` is a record of 52 inline SVG path fragments and `icon(name)` builds an `` element from one. They are 20-by-20, single stroke, and use `currentColor`, so they inherit the button color and follow the theme. ```ts import { ICONS, icon } from "@ortex-charts/ui"; Object.keys(ICONS); // every available IconName const el = icon("magnet"); ``` The names, grouped by what they are for: - **Series types:** `candles`, `bars`, `line`, `area`, `baseline`, `heikinAshi`, `hollow`. - **Tools:** `cursor`, `crosshair`, `trendline`, `ray`, `horizontalLine`, `verticalLine`, `rectangle`, `parallelChannel`, `fibRetracement`, `measure`, `text`, `magnet`. - **Editing:** `undo`, `redo`, `trash`, `clear`, `eye`, `eyeOff`, `settings`, `lock`, `plus`, `minus`, `check`, `close`, `chevron`. - **Navigation and scale:** `fit`, `realtime`, `log`, `percent`, `auto`, `search`. - **Replay:** `replay`, `play`, `pause`, `stepForward`, `stepBack`, `stop`. - **Actions:** `camera`, `download`, `share`, `link`, `api`, `indicator`, `sun`, `moon`. Passing your own markup instead of a name works and is the right answer for a brand icon: ```ts { id: "brand", icon: '' } ``` Use a 20-by-20 or 24-by-24 coordinate space and `currentColor` strokes so the icon matches the built-ins at every size and in both themes. ## Menus and Dialogs The same primitives the built-in toolbar uses are exported, so a host action can open a menu or a form that looks exactly like the rest of the chrome rather than like a bolted-on `window.prompt`. ```ts import { openMenu, openDialog, openSymbolSearch } from "@ortex-charts/ui"; openMenu(shell.root, anchorButton, (menu) => { menu.head("Export"); menu.item({ label: "CSV", icon: "download", onSelect: () => save(shell.exportCsv()) }); menu.item({ label: "PNG", icon: "camera", onSelect: () => savePng(shell.chart.chart.takeScreenshot()) }); menu.sep(); menu.item({ label: "Include hidden series", checked: includeHidden, onSelect: () => { includeHidden = !includeHidden; return false; } }); }); ``` Returning `false` from `onSelect` keeps the menu open, which is what a toggle wants. ```ts openDialog(shell.root, { title: "Alert settings", fields: [ { key: "price", label: "Price", type: "number", value: 182.5, step: 0.01 }, { key: "repeat", label: "Repeat", type: "boolean", value: false }, { key: "channel", label: "Notify by", type: "select", value: "email", options: ["email", "push", "none"] }, ], submitLabel: "Create", onSubmit: (values) => createAlert(values), }); ``` `openDialog` returns a function that closes it. Fields are `number`, `select` or `boolean`; this is the same generator the indicator settings dialog uses, which is why an indicator you [register yourself](https://ortexcharts.com/docs/indicators) gets a proper form without writing one. ## Keyboard and Accessibility What is implemented: - **The chart is focusable.** Arrow keys scroll, with Shift for a larger step; `+` and `-` zoom about the center; Home resets the time scale. - **Drawings respond to keys** on a focused chart: Escape cancels a tool or clears the selection, Delete and Backspace remove the selected drawing, and Ctrl or Cmd with Z and Y undo and redo. See [Drawing tools](https://ortexcharts.com/docs/drawings). - **Toolbar buttons carry `aria-pressed`** so a screen reader announces the active chart type, scale mode and tool. - **Menus are `role="menu"`** with `aria-haspopup` and `aria-expanded` on the button that opens them, arrow-key navigation between items, `aria-checked` on toggles, Escape to close, and focus returned to the anchor. - **Dialogs are `role="dialog"` with `aria-modal`**, an accessible name from the title, a focus trap, Enter to submit and Escape to cancel. - **Icon-only buttons carry a `title` and an accessible name**, which is why `ToolbarAction` falls back from `title` to `label`. - **Reduced motion** is respected in the chrome CSS. What is not implemented, stated plainly: - **There is no screen-reader description of the data.** The canvas is not annotated, and there is no textual summary of the series, the visible range or the values at the crosshair. - **There is no focusable data table** as an alternative representation, which is the approach the Highcharts accessibility module takes. - **There is no high-contrast theme** shipped, though one is a [theme object](https://ortexcharts.com/docs/customization) away. - **Keyboard support does not extend to creating or editing drawings**, only to canceling and deleting them. If accessibility conformance is a procurement requirement for you, these are the gaps to weigh, and the CSV export plus your own table is the honest interim answer. ## Mobile Below 640 pixels the toolbar drops its labels, the resolution strip scrolls horizontally, and the drawing rail becomes a horizontal bar under the chart. Coarse pointers get 32-pixel targets. Pinch zoom, drag panning and long-press crosshair are in the engine rather than in the chrome, so they work on a bare `createFinancialChart` too. Full screen uses the Fullscreen API on the shell root, and falls back to a fixed-position layer where the API is missing, which is the case on iOS Safari. Escape leaves either. ## Driving the Chart Without the Toolbar Every method behind the buttons is public, so switching the toolbar off is not a loss of functionality. ```ts const BARE = { symbol: false, resolution: false, seriesType: false, indicators: false, overlays: false, scale: false, fit: false, realtime: false, screenshot: false, theme: false, fullscreen: false, } as const; const shell = createChartShell(el, { symbol: "AAPL", datafeed, toolbar: BARE, drawings: false }); await shell.setSymbol("MSFT"); await shell.setResolution("60"); shell.setSeriesType("line"); shell.setScaleMode("logarithmic"); shell.addIndicator("rsi", { length: 21 }); await shell.setOverlay("si", true); shell.setTheme("light"); await shell.toggleFullscreen(); const csv = shell.exportCsv(); const layout = shell.getLayout(); ``` See [the shell and layouts](https://ortexcharts.com/docs/shell) for the full surface, including overlays, layouts and per-series placement. --- # The shell and layouts > The complete chart application: symbol search, panes, layouts and stored drawings. Section: Customization. Source: https://ortexcharts.com/docs/shell ## One Call for the Whole Application `createChartShell` wraps a financial chart in the chrome a user expects: a toolbar, a drawing rail, symbol search, an indicator menu, a data picker, scale controls, screenshot, theme and full screen. It is plain DOM with no framework dependency, styled through CSS custom properties derived from the chart theme. ```ts import { createChartShell } from "@ortex-charts/ui"; const shell = createChartShell(container, { symbol: "AAPL", datafeed, // any Datafeed; search comes from searchSymbols overlays: myOverlays, // host-defined data series layout: savedLayout, // what the user chose last time, or null onLayoutChange: (layout) => api.saveChartLayout("stock-page", layout), drawingsStore: myDrawingsStore, // drawings that follow the symbol }); ``` In React it is `` from [`@ortex-charts/react`](https://ortexcharts.com/docs/react). _Live example: [chart-shell](https://ortexcharts.com/examples/chart-shell)_ `ChartShellOptions` extends `FinancialChartOptions`, so every chart option — theme, time zone, resolution, session, watermark, crosshair, branding, `data` — is accepted in the same object. ## The Shell Handle ```ts interface ChartShell { readonly root: HTMLElement; readonly chart: FinancialChart; // .chart.chart is the core Chart readonly drawings: DrawingsPrimitive | null; readonly binding: DatafeedBinding | null; symbol(): string; setSymbol(symbol: string): Promise; resolution(): string; setResolution(resolution: string): Promise; setSeriesType(type: MainSeriesType): void; setScaleMode(mode: ScaleMode): void; addIndicator(id: string, inputs?: Record): IndicatorInstance; indicators(): readonly IndicatorInstance[]; overlays(): Array<{ id: string; symbol: string; key: string; label: string; on: boolean }>; setOverlay(id: string, on: boolean, symbol?: string): Promise; openDataPicker(): void; placeSeries(seriesId: string, placement: Partial): void; placementOf(seriesId: string): SeriesPlacement | null; addAction(action: ToolbarAction): () => void; exportCsv(): string; getLayout(): ChartLayout; setLayout(layout: ChartLayout | null): Promise; setTheme(theme: Theme | "dark" | "light"): void; toggleFullscreen(): Promise; isFullscreen(): boolean; replay(): ReplayController; startReplay(index?: number): void; stopReplay(): void; remove(): void; } ``` Nothing is hidden behind the toolbar. `shell.chart` is the `FinancialChart`, `shell.chart.chart` is the core `Chart`, and `shell.drawings` is the drawing primitive, so anything on [Series types](https://ortexcharts.com/docs/series), [Indicators](https://ortexcharts.com/docs/indicators), [Drawing tools](https://ortexcharts.com/docs/drawings) or [Order flow](https://ortexcharts.com/docs/order-flow) applies unchanged. ## Layouts: The Chart Never Persists, the Host Does A **layout** is the user's choice of *how* the chart looks, independent of *which* symbol is shown. It is plain JSON with a version. ```ts interface ChartLayout { version: 1; seriesType: "candlestick" | "bar" | "line" | "area" | "baseline"; scaleMode: "normal" | "logarithmic" | "percentage" | "indexedTo100"; resolution?: string; indicators: Array<{ id: string; inputs?: Record; visible?: boolean }>; overlays: string[]; // ids that are on; `id@SYMBOL` for a compared symbol scales?: Record; colors?: Record; // chosen from the legend menu legendCollapsed?: boolean; // with the "legend" toolbar item drawings?: Drawing[]; // only with layoutIncludesDrawings } ``` ```ts const layout = shell.getLayout(); await shell.setLayout(layout); // null resets to the shell defaults, including defaultOn overlays ``` `onLayoutChange` fires at most once per frame after any user action that changes the layout: chart type, scale mode, resolution, indicator added, removed, reconfigured or hidden, overlay toggled, series moved to another scale or pane, and drawings when they are included. The shell never touches storage. Where the layout lives — per user, per page kind, per symbol — is a host decision. The usual arrangement is one row per user and page kind: ```ts const saved = await api.get(`/chart-layout/stock/`); const shell = createChartShell(el, { symbol, datafeed, overlays, layout: saved, onLayoutChange: (l) => api.put(`/chart-layout/stock/`, l), }); ``` Unknown overlay and indicator ids in a stored layout are ignored rather than throwing, so renaming or retiring an overlay does not break every saved layout in your database. ## Colors the Reader Chooses Every legend row has a menu, and in it a row of swatches. One click repaints that series; a candlestick or bar series gets two rows, up and down, because a reader who wants green and red will want to say which green and which red. The choice is keyed by the series **title**, not by its id, so it survives a symbol change and a reload: "Price" stays the color the reader picked, whatever is being priced. When a second series of the same title arrives — the same overlay for a compared symbol, say — it takes a contrasting color instead, so the two can be told apart: ```ts import { contrastingColor } from "@ortex-charts/ui"; shell.setSeriesColor(series.id, "#7FA3F0"); // a line shell.setSeriesColor(series.id, { up: "#22C08A", down: "#EF4E5A" }); // candles or bars shell.seriesColorOf(series.id); // → what it is now, or null contrastingColor(["#7FA3F0", "#22C08A"], palette); // the furthest hue left ``` The colors travel in the layout as `colors`, so storing the layout stores them, and `setLayout(null)` puts every series back on the theme. ## Overlays Are Host-Defined An overlay is a named thing your application knows how to put on the chart. The shell shows the label and group in the Data menu, keeps the check marks in sync, stores only the id in the layout, and calls your disposer when it is switched off. ```ts import type { OverlayDef } from "@ortex-charts/ui"; const overlays: OverlayDef[] = [ { id: "si", label: "Short interest", group: "Securities lending", description: "Estimated short interest as a percentage of free float", defaultOn: true, add: async ({ chart, symbol, resolution }) => { const rows = await api.shortInterest(symbol, resolution); const s = chart.addSeries("line", { title: "Short interest", priceScaleId: "left", align: "forwardFill", priceFormat: { type: "percent", precision: 2, minMove: 0.01 }, }); s.setData(rows); return () => chart.removeSeries(s.id); }, }, ]; ``` `add` receives `{ chart, fc, shell, symbol, isCurrentSymbol, resolution }`, may be asynchronous, and returns the function that removes the overlay again. It is called again after **every symbol or resolution change**, with the previous disposer run first, so the host fetches for `ctx.symbol` inside `add` and never has to watch the chart itself. `otherSymbolOnly: true` marks an overlay that only makes sense for a compared symbol and hides it for the chart's own. ### Overlays That Load as the Reader Scrolls An overlay with twenty years of daily history behind it does not have to fetch twenty years to draw the last six months. `ctx.windowed` gives the series the visible span plus a margin, and fetches more only when the view moves past what it holds: ```ts add: async (ctx) => { const s = ctx.chart.addSeries("line", { title: "Short interest", priceScaleId: "left" }); const loader = ctx.windowed(s, (from, to) => api.shortInterest(symbol, from, to)); return () => { loader.dispose(); ctx.chart.removeSeries(s.id); }; }, ``` `overlayLoading` on the shell sets the defaults for every overlay that asks for one, and the third argument overrides them per overlay. The options are the loader's own, described under [loading history in windows](https://ortexcharts.com/docs/data#loading-history-in-windows). ```ts createChartShell(el, { overlayLoading: { margin: 0.5, earliest: Date.UTC(2005, 0, 1) }, }); ``` ## Comparing Symbols When a datafeed is bound, the shell adds a built-in **Price** overlay for other symbols: the closes of another instrument as a line, with the scale switched to percent so the two are comparable. Comparing AAPL with MSFT therefore needs no host code beyond `searchSymbols`. Overlays for another symbol are stored as `id@SYMBOL` in the layout, and `overlayKey` and `parseOverlayKey` are exported for hosts that need to read or build those keys. ```ts await shell.setOverlay("price", true, "MSFT"); shell.overlays(); // [{ id, symbol, key, label, on }, …] including compared symbols ``` Set `compare: false` to remove the feature. ## The "Add Data to Chart" Modal With more than eight overlays, or whenever symbol search is available, the Data button opens a modal instead of a dropdown. `dataPicker: "menu" | "modal" | "auto"` overrides the decision. The modal has a series search, a category list with counts on the left, grouped rows that toggle on click, and a symbol search that points the picker at another instrument so its series can be compared. `shell.openDataPicker()` opens it from your own control, and `openDataPicker` is exported from `@ortex-charts/ui` for hosts that want the same component somewhere else. ## Moving a Series to Another Scale or Pane Every legend row carries a `⋯` button. For an overlay or an indicator output it offers **Right scale**, **Left scale**, **Own scale** (a hidden scale, so the series autoscales alone), **Main pane**, **New pane**, **Hide** and **Remove**, plus **Collapse pane**, **Expand pane**, **Maximise pane** and **Restore panes** for the pane the series sits on. The choice is stored in `layout.scales`, keyed by series title, so it survives an overlay being re-added after a symbol change and comes back with the user's saved layout. ```ts shell.placeSeries(series.id, { scale: "own", pane: "separate" }); shell.placementOf(series.id); // { scale, pane, visible } or null ``` The underlying core methods are `chart.setPaneCollapsed`, `chart.isPaneCollapsed`, `chart.maximizePane`, `chart.restorePanes`, `chart.maximizedPane` and `chart.subscribePaneChange`, and `chart.subscribeLegendMenu` is the hook a host uses to build its own menu on that button. A collapsed pane is a 24-pixel legend strip. Its series stay attached and keep updating, so collapsing is a display state rather than a teardown. ## Drawings That Follow the Symbol The most-requested behavior in this category — a trend line drawn on AAPL being there on every chart of AAPL — is a storage question, and the host owns storage. Give the shell a `drawingsStore` and it does the rest. ```ts import { localStorageDrawingsStore } from "@ortex-charts/ui"; createChartShell(el, { symbol: "AAPL", datafeed, drawingsStore: localStorageDrawingsStore() }); // or your own, server-backed: createChartShell(el, { symbol: "AAPL", datafeed, drawingsStore: { load: (symbol) => api.get(`/drawings/${symbol}`), save: (symbol, drawings) => api.put(`/drawings/${symbol}`, drawings), }, }); ``` Both methods may be asynchronous. Drawings are saved whenever they change and on every symbol switch, and loaded for the new symbol. With a store in use, leave `layoutIncludesDrawings` off: a layout then describes the chart and drawings describe the symbol, which is the separation users expect. Turn `layoutIncludesDrawings` on instead only when the page is inherently single-symbol and you want one blob rather than two. ## Symbol Logos `SymbolInfo.logo` — a URL or a data URI — is shown in the symbol button and before the main series in the legend. A missing or failing image falls back to the color dot silently. The [datafeed](https://ortexcharts.com/docs/data) supplies it from `resolveSymbol` or `searchSymbols`, and an [adapter spec](https://ortexcharts.com/docs/data) maps it with `symbol.logo`, which accepts a template such as `https://logos.example.com/{symbol}.png` or `{info.logo_url}`. ## CSV Export The `download` toolbar item is off by default. Turning it on exports every visible series on the main timeline as CSV. ```ts createChartShell(el, { symbol: "AAPL", datafeed, toolbar: { download: true }, download: { fileName: "aapl-daily.csv", onDownload: (csv, shell) => api.saveExport(shell.symbol(), csv), // intercept it }, }); const csv = shell.exportCsv(); // the same text, on demand ``` With `onDownload` set, the browser does not save a file; the text goes to you instead. ## Screenshots ```ts createChartShell(el, { screenshotFileName: "chart.png", onScreenshot: (canvas) => canvas.toBlob((blob) => uploadToSlack(blob!)), }); const canvas = shell.chart.chart.takeScreenshot(); // from code, at any time ``` `takeScreenshot` composes every pane canvas into one and is on the core chart, so it works without the shell. ## Full Screen `toggleFullscreen()` uses the Fullscreen API on the shell root and falls back to a fixed-position layer where the API is unavailable, which is the case on iOS Safari. Escape leaves either. `isFullscreen()` reports the current state, and the toolbar button reflects it. ## Events ```ts createChartShell(el, { onLayoutChange: (layout) => save(layout), onSymbolChange: (symbol, info) => setPageTitle(symbol, info?.name), onResolutionChange: (resolution) => track("resolution", resolution), onThemeChange: (theme) => persistThemePreference(theme), onScreenshot: (canvas) => upload(canvas), onError: (error) => report(error), }); ``` `onError` catches datafeed and overlay failures that would otherwise be silent; wiring it to your error reporter is worth the two lines. ## What the Host Has to Provide The chart side is finished; the persistence side is yours. For a complete integration you need four things, none of which the library can decide for you: - **A per-user layout store keyed by page kind**, one JSON body per user and page, read on mount and written from `onLayoutChange`. - **An overlay registry**, one `OverlayDef[]` per page kind, wrapping your own series endpoints. - **A drawings store per symbol**, if you want drawings to follow the symbol. - **Defaults for anonymous users**, which is simply a layout object in your bundle. Nothing in the chart depends on those existing. Without any of them the shell still works; it just forgets everything on reload. --- # The ORTEX mark > What the mark is, when it shows, and how a white-label license removes it. Section: Commercial. Source: https://ortexcharts.com/docs/branding ## What the Mark Is Every chart drawn by ORTEX Charts carries a small mark on the first pane: the caption "Charts provided by" above the ORTEX wordmark, in the theme text color at 60 percent opacity, twelve pixels high, in the bottom-left corner by default. Clicking it opens ortexcharts.com in a new tab, which is the page that answers the question somebody asks by clicking a mark on a chart. The mark is the visible half of the commercial enforcement in the code. The other half is the gate: since 1.1.0 a chart with no valid key draws only on a development host, and paints a licence notice instead of its content anywhere else. See [license keys](https://ortexcharts.com/docs/licensing). _Live example: [branding](https://ortexcharts.com/examples/branding)_ ## What the Mark Is Not Stating this plainly matters more than describing the mark, because the assumption in this category is usually the opposite. - **The mark is not the enforcement; the gate is.** Since 1.1.0 a chart with no valid key draws only on a development host. On any other host it paints a licence notice instead of its content, in every state but `valid`: missing key, invalid key, expired key, wrong domain, revoked key. Keys carry a 14-day grace period past their term so a late renewal does not close the gate. See [license keys](https://ortexcharts.com/docs/licensing). - **A licensed chart never nags.** With a key in place there is no overlay, no modal, no banner, no watermark across the plot, and no repeated warning. Nothing is written to the user's screen beyond the mark itself, and a paid key removes that too. - **The mark does not say "Unlicensed".** On localhost, where an unlicensed chart still draws, the mark reads "Charts provided by ORTEX" and nothing more; a visitor cannot tell from the mark whether the page has paid. Off localhost the question does not arise, because the chart is not drawn. - **The chart never phones home.** No request is made to any ORTEX host. The key is verified locally, by the library's own Ed25519 code. See [Questions we are asked](https://ortexcharts.com/docs/faq) for the complete telemetry answer. ## When the Mark Shows There are three states, and only one of them removes the mark. | State | Mark | Console | |---|---|---| | No key, or an invalid, expired or wrong-domain key, on localhost | Shown, with the caption | None, unless the chart asked to hide the mark: then one warning naming the reason | | The same, on any other host | The chart is not drawn: a licence notice naming the reason takes its place | None | | A valid key **without** the `whitelabel` feature | Shown, exactly the same mark | One warning if you asked to hide it | | A valid key **with** the `whitelabel` feature | Hidden when `branding.visible` is `false` | Nothing | | A valid key **with** the `brand` feature | Hidden, or replaced with your own logo, text, caption and link | Nothing | Every paid plan, Pro and Business, grants `whitelabel`: the mark may be hidden. OEM agreements grant `*`, which includes `brand`: the mark may be yours. There is no free plan; without a key the mark shows on localhost and the chart does not draw anywhere else. So the mark is a ladder with two rungs. Paid shows none, and only OEM shows the customer's own. See [/pricing](https://ortexcharts.com/pricing) for the plans and the numbers. ## Removing It ```ts import { setLicenseKey, createFinancialChart } from "@ortex-charts/financial"; await setLicenseKey(WHITELABEL_KEY); const chart = createFinancialChart(el, { branding: { visible: false }, data: bars, }); ``` `branding.visible = false` is a request, not a command. It is honored only when the current license grants `whitelabel`. Setting it without that feature does exactly one thing beyond being ignored: it writes one line to the console. ```text [ORTEX Charts] This license does not include white-labeling; the ORTEX mark stays on. ``` With no key at all, the message is different and names the underlying problem: ```text [ORTEX Charts] No license key set. The ORTEX mark stays on until a valid key is set with setLicenseKey(). ``` Check what you have before assuming a key is the problem: ```ts import { hasFeature, licenseStatus } from "@ortex-charts/financial"; licenseStatus(); // { state, payload, message, verified } hasFeature("whitelabel"); // true only on a valid license that grants it ``` The signature is checked before `setLicenseKey` returns, by the library's own Ed25519 implementation, so a feature is granted from the moment the key is valid and never on an unchecked payload. ## Replacing It With Your Own A `brand` license, which is an OEM agreement, may keep a mark and make it yours, which is what a product shipped under your name usually wants rather than a bare corner. A Pro or Business key hides the mark; it does not replace it. ```ts createFinancialChart(el, { branding: { visible: true, logo: "https://cdn.example.com/brand/mark.svg", // a URL, a data URI, or "text" caption: "", // empty removes the caption line position: "bottomRight", height: 14, opacity: 0.5, href: "https://example.com", }, }); ``` Setting `logo: "text"` draws the `text` option in a bold face at `height` pixels instead of an image, which avoids an extra request for a wordmark that is just letters. Keeping the ORTEX mark on a licensed chart is also fine, and some customers do; the option simply stays at its default. ## Every Branding Option | Option | Type | Default | What it does | |---|---|---|---| | `visible` | `boolean` | `true` | Show the mark. Setting it to `false` requires the `whitelabel` feature. | | `position` | `"bottomLeft" \| "bottomRight" \| "topLeft" \| "topRight"` | `"bottomLeft"` | Corner of the first pane. | | `height` | `number` | `12` | Logo height in CSS pixels. | | `opacity` | `number` | `0.6` | Opacity of the whole mark. | | `logo` | `"ortex" \| "text" \| string` | `"ortex"` | The ORTEX wordmark, the `text` option, or an image URL or data URI. | | `text` | `string` | `"ORTEX"` | Drawn when `logo` is `"text"`. | | `caption` | `string` | `"Charts provided by"` | Small line above the mark; an empty string removes it. | | `href` | `string` | `"https://ortexcharts.com"` | Opened in a new tab when the mark is clicked. | `position`, `height` and `opacity` are honored regardless of the license, because they only move the mark about. `logo`, `text`, `caption` and `href` are honored only when the key carries the `brand` feature; without it the mark, when shown, is the ORTEX wordmark with its caption and its link whatever the options say, so replacing the mark with yours is an OEM agreement rather than an option. `whitelabel` alone (every paid plan) honors `visible: false` and nothing else. As of 1.0.26; between 0.6.1 and 1.0.25, `whitelabel` covered both. `BRANDING_DEFAULTS` is exported if you want to start from the defaults and change one field. ## Why It Works This Way Anything that runs in a browser ships to the browser. Minified JavaScript is source code with the comments removed, and a determined person can read it, copy it and patch out a check in an afternoon. That is true of every library in this category and every one of them is a functioning business, so the interesting question is not how to prevent copying but what makes the legitimate path the easier one. ORTEX's answer, in order: - **A contract with terms a company can be held to.** The customers who can afford a chart library do not risk a breach-of-contract suit to save a subscription. - **Updates and support**, which stop when the subscription does. - **Distribution through a per-customer channel** — a hosted kit locked to your domains, or a registry token — rather than through public npm. - **A signed, domain-bound key with one visible consequence**, so the unlicensed state is obvious in a screenshot but harmless to the end user. - **No obfuscation**, because it costs performance and debuggability and buys about a day of a copier's time. Removing the check by editing the bundle is possible. It is also a deliberate act, named as a breach in the agreement, with the evidence sitting in the customer's own deployment, and the key id in a leaked build identifies which customer it came from. That is the honest description of the protection, and it is the same one every vendor in the category could give. ## Related - [License keys](https://ortexcharts.com/docs/licensing) — issuing, domains, expiry and the states. - [Questions we are asked](https://ortexcharts.com/docs/faq) — telemetry, expiry, support. - [/pricing](https://ortexcharts.com/pricing) — which plan grants `whitelabel`, and which grants `brand`. --- # Sparklines > The 3.3 KB build for tables and cards: line, area, column and win-loss. Section: Packages. Source: https://ortexcharts.com/docs/sparklines ## The 5.4 KB Build `@ortex-charts/lite` is a separate package with one job: a tiny canvas chart for a table cell or a card. It is 3.3 KB gzipped, depends only on `@ortex-charts/math`, and has no axes, no crosshair, no legend and no interaction. A table with 300 sparklines schedules one animation frame, not 300. ```bash npm install @ortex-charts/lite ``` ```ts import { createSparkline } from "@ortex-charts/lite"; const spark = createSparkline(cell, { kind: "area", colorByTrend: true, width: 120, height: 28 }); spark.setData(closes); ``` _Live example: [sparkline-table](https://ortexcharts.com/examples/sparkline-table)_ ## Four Kinds | Kind | Draws | Used for | |---|---|---| | `line` | A polyline, optionally curved, with an endpoint dot. | Price and value history. | | `area` | The same line with a fill beneath it. | The same, with more weight in a dense table. | | `column` | One column per value, colored by sign around `baseline`. | Returns, flows, changes. | | `winloss` | Equal-height marks up or down by sign. | Win and loss streaks, hit rates. | ```ts createSparkline(el, { kind: "line" }); createSparkline(el, { kind: "column", baseline: 0 }); createSparkline(el, { kind: "winloss", baseline: 0 }); ``` ## Data ```ts spark.setData([12.4, 12.9, 12.1, 13.4]); // numbers spark.setData([{ value: 12.4 }, { value: 12.9 }]); // rows spark.setData([[t1, 12.4], [t2, 12.9]]); // [time, value] pairs ``` Time is accepted but not used for spacing: points are evenly spaced. A sparkline is a shape, not a chart, and a gap in the dates does not become a gap in the line. ```ts spark.push(13.1); // append one value spark.push(13.1, 60); // append, keeping at most 60 points ``` `push` is the live path. It is cheap enough to call on every tick of a streaming table. ## Options | Option | Default | What it does | |---|---|---| | `kind` | `"line"` | One of the four above. | | `width`, `height` | container size, else 100 by 28 | Canvas size in CSS pixels. | | `color` | `"#4C8DFF"` | Line or column color. | | `positiveColor` | `"#22C08A"` | Used by `colorByTrend` and by sign coloring. | | `negativeColor` | `"#EF4E5A"` | The same, downward. | | `colorByTrend` | `false` | Color the whole sparkline by whether the last value is above the first. | | `lineWidth` | `1.5` | Stroke width. | | `curve` | `"linear"` | `linear`, `step`, `monotone` or `smooth`. | | `fillOpacity` | `0.18` | Area fill opacity. | | `endpoint` | `true` | Dot at the last point. | | `endpointRadius` | `2` | Its radius. | | `baseline` | `null` | Draw a faint line at this value and color columns by sign around it. | | `baselineColor` | a faint gray | Color of that line. | | `min`, `max` | data extent | Fixed value range, for comparability across rows. | | `padding` | `2` | Inset in CSS pixels. | | `extremes` | `false` | Highlight the minimum and maximum points. | | `background` | `"transparent"` | Canvas background. | `SPARKLINE_DEFAULTS` is exported if you want to derive from the defaults. The two options that matter most in a table are `colorByTrend` and `min`/`max`. `colorByTrend` is what makes a column of sparklines readable at a glance without a legend. Fixing `min` and `max` makes rows comparable to each other; leaving them unset makes each row use its full height, which reads better per row and worse down the column. Choose deliberately. ## The Handle ```ts const spark = createSparkline(el, options); spark.canvas; // the element, appended to the container spark.setData(values); spark.push(value, maxPoints?); spark.applyOptions({ kind: "column", color: "#F5A524" }); spark.resize(160, 32); spark.invalidate(); // schedule a redraw spark.flush(); // draw now, synchronously spark.remove(); // detach and stop ``` Every mutator returns `this`, so calls chain. `flush()` is the one to call before taking a screenshot or asserting in a test, because drawing is otherwise deferred to the next frame. ## The Shared Render Loop Every sparkline on the page schedules its redraw on one `RenderScheduler`, exported as `renderScheduler`. A table that updates 300 cells in a loop produces one animation frame with 300 draws, not 300 frames. This is the reason the package exists separately from `@ortex-charts/core`, and it is why the cost of a sparkline table is proportional to the data rather than to the number of cells. You do not have to do anything to get this. It applies automatically. ## In a Table ```ts import { createSparkline, type Sparkline } from "@ortex-charts/lite"; const sparks = new Map(); for (const row of rows) { const cell = document.querySelector(`#spark-${row.id}`)!; const spark = createSparkline(cell, { kind: "area", colorByTrend: true, width: 120, height: 26, endpoint: true, }); spark.setData(row.closes); sparks.set(row.id, spark); } // Live: one push per row, one frame for all of them. feed.subscribe((tick) => sparks.get(tick.id)?.push(tick.price, 120)); // Teardown, when the table unmounts. for (const s of sparks.values()) s.remove(); ``` ## Beside a Line of Text A sparkline sized to the type next to it is the densest useful form, and it needs no chrome at all. ```ts createSparkline(span, { kind: "line", width: 56, height: 14, lineWidth: 1, endpoint: false, padding: 1, colorByTrend: true, }); ``` Keep the container `display: inline-block` with `line-height: 0` so the canvas sits on the text baseline instead of adding a descender's worth of space. _Live example: [spark-cells](https://ortexcharts.com/examples/spark-cells)_ ## In React ```tsx import { Sparkline } from "@ortex-charts/react"; ``` The component creates the sparkline on mount, applies data and option changes in place, and removes it on unmount. The instance is available through `ref` when you want `push`. See [React](https://ortexcharts.com/docs/react). ## When to Use the Full Chart Instead `@ortex-charts/lite` is deliberately small, and the things it does not do are the reason it is small. - **No axes, no ticks, no labels.** If you need a scale, use `@ortex-charts/financial` or `@ortex-charts/viz`. - **No crosshair, no tooltip, no hit testing.** Hovering does nothing. A tooltip on a sparkline is a `title` attribute or your own overlay on the container. - **No time axis.** Points are evenly spaced regardless of their timestamps. - **No theme object.** Colors are options on the sparkline, not tokens, because pulling in the theme would pull in the engine. - **No multiple series.** One array of numbers per sparkline. The crossover point in practice is a tooltip. As soon as a small chart needs to tell the user what a point is worth, it wants [`createFinancialChart`](https://ortexcharts.com/docs/quickstart) with most of the chrome switched off, which is about 56 KB gzipped instead of 3.3 KB. --- # Treemaps and heatmaps > The general-purpose charts in the family, on the same engine. Section: Packages. Source: https://ortexcharts.com/docs/viz ## What Is in the Package `@ortex-charts/viz` holds the general-purpose charts a financial data product needs alongside its price charts: a category chart for bars and columns, an XY chart over a numeric axis, a treemap, a heatmap, a pie or donut, a Sankey diagram, and export helpers for PNG and CSV. They run on the same canvas layer, follow the same [theme tokens](https://ortexcharts.com/docs/customization) and share one animation frame with everything else on the page. ```bash npm install @ortex-charts/viz ``` Each component follows its container, is device-pixel-ratio aware, has an optional built-in tooltip, and is created and disposed the same way: ```ts import { createTreemap, createHeatmap, createCategoryChart, createXYChart, createPieChart, createSankeyChart } from "@ortex-charts/viz"; const chart = createTreemap(el, { theme: "dark", data }); chart.applyOptions({ colorMode: "change" }); chart.setTheme("light"); chart.resize(900, 500); chart.flush(); // draw synchronously chart.remove(); ``` _Live example: [viz-treemap](https://ortexcharts.com/examples/viz-treemap)_ ## Treemap A treemap sizes rectangles by value and colors them by change, which is the standard way to show a universe of instruments at once. ```ts import { createTreemap, type TreemapNode } from "@ortex-charts/viz"; const data: TreemapNode = { name: "S&P 500", children: [ { name: "Technology", children: [ { name: "AAPL", value: 3_100_000, change: 1.42 }, { name: "MSFT", value: 2_900_000, change: -0.63 }, ], }, { name: "Financials", children: [{ name: "JPM", value: 620_000, change: 0.28 }], }, ], }; const treemap = createTreemap(el, { theme: "dark", data, colorMode: "change", changeDomain: "auto", valueFormat: { type: "compact", precision: 1 }, changeFormat: { type: "percent", precision: 2 }, headers: true, breadcrumb: true, drillDown: true, onClick: (hit) => openInstrument(hit.data.name), }); ``` A node has `name`, an optional `value` for leaves, an optional `change` that drives the diverging color scale, an optional explicit `color` inherited by descendants, an optional `logo` URL drawn in tiles with room for one, and `children`. Parents are sized by the sum of their leaves, so only the leaves need values. | Option | Default | What it does | |---|---|---| | `colorMode` | `"auto"` | `auto` uses an explicit color, else the change scale, else the group palette color. `explicit`, `change` and `group` force one of them. | | `changeDomain` | `"auto"` | Domain of the diverging scale. `auto` is symmetric about zero and reaches the ninetieth percentile of the moves on the map, not the largest of them, so one extreme cannot flatten every ordinary move into the neutral colour; anything beyond clamps to the ends. Pass `[-3, 3]` to fix it. | | `changeColors` | theme | `[low, neutral, high]`; defaults to `theme.down`, `theme.grid`, `theme.up`. | | `valueFormat`, `changeFormat` | — | Number formatting for the labels and the tooltip. | | `paddingInner`, `paddingOuter` | — | Gaps between and around rectangles. | | `headers`, `headerHeight` | `true` | Header strips above groups. | | `headerDepth` | `1` | How deep those strips go. A map nested sector to industry to ticker draws three bands of small text above every block at `3`; `1` names the top-level groups and lets the rest be tiles. | | `minHeaderWidth` | `56` | A group narrower than this gets no strip, because the name would be an ellipsis. | | `logoMinSize` | `44` | A tile at least this many pixels on its short side draws its `logo`. | | `breadcrumb` | `true` | Path strip above the map while zoomed in. | | `labels`, `minFontSize`, `maxFontSize` | `true` | Names and values inside leaves when they fit. | | `drillDown` | `true` | Click a group to zoom in; click the breadcrumb to zoom out. | ```ts treemap.setData(nextRoot); treemap.zoomTo(node); treemap.zoomOut(1); treemap.currentRoot(); treemap.getPath(); // TreemapNode[] from the full root to the current one treemap.getLayout(); // the laid-out tree in CSS pixels ``` `layoutTreemap`, `treemapLeaves` and `findPath` are exported for hosts that want the layout without the canvas — for a server-rendered image, a test, or an accessible table alternative. ## Heatmap A grid of rows by columns with a sequential or diverging color scale, which is what a returns calendar, a correlation matrix or a factor exposure grid wants. ```ts import { createHeatmap } from "@ortex-charts/viz"; const heatmap = createHeatmap(el, { theme: "light", rows: ["2021", "2022", "2023", "2024", "2025"], columns: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"], values: [ [1.2, -0.4, 2.8, 0.1, -1.9, 3.2], [-2.1, 0.8, 1.1, NaN, 0.4, -0.7], // … ], scale: { type: "diverging", domain: "auto", center: 0 }, format: { type: "percent", precision: 1 }, cellLabels: true, legend: true, onClick: (hit) => drillInto(hit.rowLabel, hit.columnLabel), }); ``` `values` is row-major: `values[row][column]`. `NaN` is an empty cell and is drawn in `emptyColor` rather than at the bottom of the scale, which matters for a calendar with missing months. | Option | Default | What it does | |---|---|---| | `scale.type` | `"diverging"` | `sequential` or `diverging`. | | `scale.domain` | `"auto"` | `[min, max]`, or derived from the finite values; symmetric about `center` when diverging. | | `scale.center` | `0` | Center of a diverging scale. | | `scale.colors` | theme | Two colors for sequential, three for diverging. | | `format` | percent, 1 decimal | Cell and tooltip formatting. | | `cellLabels` | `true` | Print the value in the cell when it fits. | | `cellGap` | `1` | Pixels between cells. | | `rowLabels`, `columnLabels` | `true` | Axis labels. | | `columnLabelPosition` | `"top"` | `top` or `bottom`. | | `maxLabelWidth` | `140` | Cap on a label footprint in pixels. | | `legend` | `true` | Color bar under the grid. | | `emptyColor` | a faint tint | Fill for `NaN` cells. | ```ts heatmap.setData({ rows, columns, values }); heatmap.colorFor(1.4); // the color a value would get, for a host-drawn legend ``` `resolveHeatmapDomain` and `createColorScale` are exported for the same reason: a host that wants to color a table cell to match the heatmap can use exactly the same scale. ## Category Chart Bars and columns over a categorical axis, stacked or grouped, horizontal or vertical. ```ts import { createCategoryChart } from "@ortex-charts/viz"; const chart = createCategoryChart(el, { theme: "dark", orientation: "horizontal", categories: ["Energy", "Financials", "Healthcare", "Technology", "Utilities"], series: [ { key: "long", title: "Long", color: "#22C08A", data: [12, 34, 21, 55, 8] }, { key: "short", title: "Short", color: "#EF4E5A", data: [-4, -12, -6, -19, -2] }, ], stacked: true, baseline: 0, colorBySign: false, valueLabels: true, legend: true, sortBy: "desc", valueAxis: { position: "bottom", format: { type: "compact", precision: 1 }, gridlines: true, visible: true }, onClick: (hit) => filterBy(hit.category), }); chart.setData({ categories, series }); ``` `orientation: "vertical"` draws columns and `"horizontal"` draws bars. `colorBySign` colors each bar by which side of `baseline` it falls on, using the theme up and down colors, which is the fastest way to a readable contribution chart. `sortBy` orders categories by their total across series without changing the underlying arrays, and `CategoryHit.categoryIndex` is the index into your original `categories`, not into the displayed order. ## XY Chart A chart over a **numeric** x axis rather than a timeline or a category list: an option strike ladder, a payoff diagram, a distribution, one measure against another. Lines, areas, columns, scatter and bubbles share the plot, with a second value axis when a series asks for it. ```ts import { createXYChart } from "@ortex-charts/viz"; const chart = createXYChart(el, { theme: "dark", series: [ { key: "gex", title: "Gamma", kind: "column", data: [[90, 10], [100, -4], [110, 7]], colorBySign: true }, { key: "oi", title: "Open interest", kind: "line", data: [[90, 100], [100, 250]], axis: "right", markers: true }, { key: "zone", title: "Profit zone", kind: "area", data: payoff, color: "#22C08A", fillOpacity: 0.16, lineWidth: 0 }, ], referenceLines: [ { value: 100, axis: "x", label: "Spot", lineStyle: "dashed" }, { value: 0, axis: "left", lineStyle: "solid" }, ], referenceBands: [{ from: 95, to: 105, axis: "x", color: "rgba(56,189,248,0.10)", label: "Expected move" }], xAxis: { format: { type: "price", precision: 0 }, title: "Strike" }, yAxis: { title: "Profit ($)", gridlines: true }, tooltipExtra: (x) => [{ label: "Δ", value: deltaAt(x).toFixed(3) }], }); ``` Points are `[x, y]`, `[x, y, size]` or `{ x, y, size?, color?, label? }`. A reference line is a marker on either axis with an optional label; a reference band is a shaded range, which is how a probability cone or an expected-move zone is drawn. Labels along the top of the plot are laid out so two markers close together do not print over each other. `lineWidth: 0` on an area is shading with no outline, which is what a zone under another series wants. A color that already carries transparency keeps it: `fillOpacity` scales the alpha rather than replacing it, so `rgba(…, 0.2)` with a fill opacity of 1 stays at 0.2. The pointer snaps to the nearest x within `snapDistance` and reports every series at that x, so one tooltip covers the whole ladder. ## Pie and Donut ```ts import { createPieChart } from "@ortex-charts/viz"; createPieChart(el, { slices: [{ label: "Cash", value: 42 }, { label: "Equity", value: 58, color: "#7FA3F0" }], innerRadius: 0.6, // 0 is a pie, 0.6 a donut labels: "percent", // "none" | "percent" | "value" | "label" labelPlacement: "auto", // inside where it fits, outside on a leader line where it does not minLabelAngle: 8, // thinner slices carry no label inside minOutsideFraction: 0.015, // and nothing under this share is named outside either centerText: "$1.2bn", centerSubtext: "Assets", sortBy: "desc", startAngle: 0, }); ``` ### Where the Labels Go A pie is usually one large slice and a tail of small ones, and that tail is where most pies fail: text written inside a sliver either overflows it or is dropped. `labelPlacement: "auto"` writes a label inside its slice only when it fits there, in a colour picked for contrast against the fill, and otherwise outside on a leader line. The outside labels are stacked down each side and pushed apart so none overlaps, long names wrap onto a second line, and each side keeps as many as its height can hold, largest slices first. `"inside"` and `"outside"` force the choice; under `"inside"`, a label with no room is left off rather than printed over its neighbours. A newline in a slice's label starts a second, quieter line, which is how a sector name and its move sit together: ```ts slices: sectors.map((s) => ({ label: `${s.name} ${s.move.toFixed(2)}%`, value: s.marketCap, color: s.move >= 0 ? up : down })) ``` ## Sankey Flow from one set of nodes to another: revenue into costs and profit, holders into positions, order flow into venues. ```ts import { createSankeyChart } from "@ortex-charts/viz"; createSankeyChart(el, { nodes: [{ id: "revenue" }, { id: "gross", label: "Gross profit" }, { id: "cogs", label: "Cost of sales", color: "#EF4E5A" }], links: [ { from: "revenue", to: "gross", value: 43_000 }, { from: "revenue", to: "cogs", value: 71_000 }, ], linkColor: "gradient", // "source" | "target" | "gradient" linkOpacity: 0.45, nodeWidth: 14, nodePadding: 12, curve: 0.4, // how far the ribbon control points sit from the ends format: { type: "compact", precision: 1 }, labelFormat: (node, value) => [node.label ?? node.id, fmt(value)], }); ``` A node's column is its longest path from a source unless you pin it with `column`. Links of zero or negative value are not drawn, so a statement with a missing line still renders. `sankeyLayout` is exported for hosts that want the geometry without the chart. ## Export ```ts import { canvasToPNG, downloadPNG, downloadCSV, rowsToCSV, composeCanvases } from "@ortex-charts/viz"; await downloadPNG(chartCanvas, "sectors.png", { scale: 2, background: "#0E1218" }); const csv = rowsToCSV(rows, ["symbol", { key: "change", label: "1D %" }]); downloadCSV(rows, "universe.csv", ["symbol", "value", "change"]); const combined = composeCanvases([topCanvas, bottomCanvas], "#0E1218"); ``` `canvasToPNG` returns a `Blob` for hosts that want to upload rather than download, and `composeCanvases` stacks several canvases into one image, which is how a multi-pane screenshot is assembled. These helpers are in `viz` rather than in `core` because they are DOM download plumbing rather than chart engine. A financial chart's own screenshot is `chart.takeScreenshot()`, which returns a canvas you can pass straight to `canvasToPNG`. ## Shared Options and Methods Every component takes `theme`, `width`, `height`, `tooltip` and `padding`, and exposes: ```ts component.root; // the container div it created component.getTheme(); component.getOptions(); // readonly component.setTheme(theme); // "dark", "light", or a Theme object component.applyOptions(patch); // deeply partial component.resize(width, height); component.invalidate(); // schedule a redraw component.flush(); // draw now component.remove(); ``` Leaving `width` and `height` unset makes the component follow its container, which is the usual choice; setting them fixes the size, which is what an export path wants. ## What Is Not Here `@ortex-charts/viz` is a handful of chart types, not a general charting library. There is no radar, no gauge, no geographic map and no 3D. Apache ECharts has 20 or more chart types and is a reasonable thing to use alongside this package if you need them. What `viz` is for is the small set of general charts that have to look like the price chart, share its theme, and cost nothing extra in the bundle because the engine is already there. --- # React > Declarative components and hooks over the same imperative API. Section: Packages. Source: https://ortexcharts.com/docs/react ## What the Package Is `@ortex-charts/react` is a thin binding layer with no logic of its own. Every component creates the corresponding imperative object in a layout effect, applies prop changes with `applyOptions` or `setData`, and disposes it on unmount. The underlying handle is always available through `ref`, so nothing is lost by using the components. It is tested against React 17, 18 and 19, and declares them as peer dependencies with `>=17`. ```bash npm install @ortex-charts/react ``` _Live example: [react-chart](https://ortexcharts.com/examples/react-chart)_ ## The Components | Component | Wraps | Handle through `ref` | |---|---|---| | `` | `createChart` | `Chart` | | `` | `chart.addPane` | — (provides its id through context) | | `` | `chart.addSeries` | `SeriesModel` | | `` | `createFinancialChart` | `FinancialChart` | | `` | `createChartShell` | `ChartShell` | | `` | `createSparkline` | `Sparkline` | ## The Financial Chart The common case is one component with data, indicators and markers as props. ```tsx import { FinancialChart, type IndicatorSpec } from "@ortex-charts/react"; import type { Bar, SeriesMarker } from "@ortex-charts/react"; import { useMemo, useState } from "react"; const OPTIONS = { theme: "dark", timeZone: "America/New_York", resolution: "1D" } as const; export function PriceChart({ bars, earnings }: { bars: Bar[]; earnings: SeriesMarker[] }) { const [hover, setHover] = useState(""); const indicators = useMemo( () => [ { id: "ema", inputs: { length: 21 } }, { id: "sma", inputs: { length: 200 } }, { id: "rsi" }, ], [], ); return ( <> setHover(e.time ? new Date(e.time).toDateString() : "")} />

{hover}

); } ``` `indicators` is diffed by identity: new entries are added, missing ones removed, and the rest are left alone rather than being torn down and recreated. The identity of an entry is the JSON of `{ id, inputs, options }`, or an explicit `key` when you supply one, so two moving averages with different lengths are two distinct entries and an unchanged array causes no work at all. `data` and `markers` are applied whenever the **array identity** changes, so a new array on every render means `setData` on every render. Memoize them or hold them in state. `options` is compared shallowly at the top level and the changed keys go to `applyOptions`. Two keys — `seriesType` and `volume` — take effect only at creation, because they decide what the chart is made of. ## The Core Chart With Children For anything that is not a standard price chart, compose it. ```tsx import { Chart, Pane, Series } from "@ortex-charts/react"; ``` `` renders nothing into the DOM; it manages a series on the chart from context. `` provides its id to nested series, and `options.pane` on a series overrides the enclosing pane if you need to place one explicitly. Changing `type` on a `` recreates it. Changing `heightRatio` or `minHeight` on a `` applies live. ## The Full Shell ```tsx import { ChartShell } from "@ortex-charts/react"; router.push(`/chart/${s}`), }} style={{ height: 640 }} /> ``` `symbol`, `resolution` and `theme` are controlled props: the shell follows them when they change, so the chart and your application state stay in step in either direction. `layout` is re-applied whenever its identity changes, which is what you want after loading a user's saved layout asynchronously. `options` is read at creation. Callbacks inside it are always invoked through their latest value, so inline arrow functions are fine and do not need memoizing. Structural options — `datafeed`, `overlays`, `toolbar` — need a remount to change, and the idiomatic way to force one is a `key`: ```tsx ``` ## Hooks ### `useChart` and `usePaneId` Inside a `` or ``, `useChart()` returns the core `Chart` or `null` until it exists after the first commit. `usePaneId()` returns the id of the enclosing ``. Both are how you write your own child components. ```tsx import { useChart, usePaneId } from "@ortex-charts/react"; import { useEffect } from "react"; function SessionShading() { const chart = useChart(); const paneId = usePaneId(); useEffect(() => { if (!chart) return; const primitive = makeSessionShading(); chart.addPrimitive(primitive, paneId); return () => chart.removePrimitive(primitive.id); }, [chart, paneId]); return null; } ``` ### `useChartEvents` The four event props — `onCrosshairMove`, `onClick`, `onDblClick`, `onVisibleRangeChange` — are accepted directly by `` and ``. The hook behind them is exported for a chart you hold yourself: ```tsx useChartEvents(chart, { onCrosshairMove: setHover, onVisibleRangeChange: setRange }); ``` Subscriptions are made once per chart instance and always call the latest handler, so handlers never need memoizing. ### `useLiveSource` A `LiveSource` must survive re-renders and be closed exactly once. `useMemo` does not guarantee either. `useLiveSource` does: it keeps the value for the lifetime of its dependencies, closes the previous one when they change, and closes the last one on unmount. ```tsx import { FinancialChart, useLiveSource } from "@ortex-charts/react"; import { websocketSource, type LiveItem } from "@ortex-charts/financial"; function LiveChart({ symbol, bars }: { symbol: string; bars: Bar[] }) { const source = useLiveSource( () => websocketSource({ url: `wss://feed.example.com/${symbol}`, parse: (raw) => JSON.parse(String(raw)) as LiveItem, onOpen: (send) => send(JSON.stringify({ subscribe: symbol })), }), [symbol], ); return ; } ``` Anything with a `close()` method is closed, so the hook works for your own sources too. ## Sparklines ```tsx import { Sparkline } from "@ortex-charts/react"; ``` The container is an inline-block `span` with zero line height, so it sits on the text baseline. Hold a `ref` to call `push` for live values. See [Sparklines](https://ortexcharts.com/docs/sparklines). ## Referential Stability This is the one thing to get right, and it applies to every component in the package. `options` and `data` props are compared by identity, not by value. A new object literal on every render is a new identity, so the effect runs every render. ```tsx // Wrong: a new object every render, so applyOptions runs every render. // Right: stable identities. const OPTIONS = { theme: "dark", resolution: "1D" } as const; // module constant const data = useMemo(() => rows.map(toBar), [rows]); // memoized ``` Callbacks are the exception. Every event prop and every shell callback is routed through a ref, so inline functions are correct and cost nothing. ## Getting the Imperative Handle ```tsx import { useRef } from "react"; import { FinancialChart, type FinancialChartHandle } from "@ortex-charts/react"; const ref = useRef(null); c.chart.timeScale.fitContent()} />; // Later: ref.current?.chart.timeScale.setVisibleTimeRange(from, to); ref.current?.alerts().add({ price: 182.5, label: "Breakout" }); ``` `onReady` fires once with the handle after creation, which is the right place for anything that has to happen before the user sees the first frame. The `ref` is the right place for anything that happens later. For realtime updates, prefer the handle over the `data` prop: `ref.current?.update(bar)` is one row, while a new `data` array is a full `setData`. ## Server-Side Rendering The components check for `window` before creating anything, so they render an empty container on the server and fill it on hydration. In Next.js the file still needs `"use client"`, because the effect only runs in a client component. There is no server-rendered chart image; see [Installation and delivery](https://ortexcharts.com/docs/install). ## Re-Exported Types To avoid importing from four packages, the React package re-exports the types callers usually need alongside the components: ```ts import type { ChartHandle, ChartOptions, DeepPartial, SeriesModel, SeriesDataInput, SeriesOptionsBase, SeriesTypeMap, CrosshairEvent, VisibleRangeEvent, FinancialChartHandle, FinancialChartOptions, SeriesMarker, LiveSource, LiveItem, StreamOptions, AddIndicatorOptions, IndicatorInstance, SparklineHandle, SparklineOptions, SparklineData, ChartShellHandle, ChartShellOptions, ChartLayout, OverlayDef, Bar, } from "@ortex-charts/react"; ``` ## What the Package Does Not Do - **There is no React renderer for the canvas.** Children of `` are effects that call the imperative API; they do not reconcile drawing operations. - **There are no components for drawings, events, order flow, replay or alerts.** Those are primitives on the chart, reached through the handle. Wrapping one in a component of your own is about ten lines, as in the `SessionShading` example above. - **`` does not manage realtime updates.** Use the `SeriesModel` from `ref` and call `update`, or hand the chart a `live` source. --- # Performance > What the numbers are, how they are measured, and how to keep them. Section: Packages. Source: https://ortexcharts.com/docs/performance ## The Numbers Measured on 5 September 2026 by `scripts/bench/bundle-size.mjs` in the library repository. Our entry points are bundled with esbuild and gzipped; the other vendors' own published production files are gzipped by the same code, file by file. Sizes are per entry point rather than per library, because tree-shaking makes "the library is N kilobytes" meaningless: a page that draws a line pays for a line. ### Payload | What a page imports | gzip | Files | |---|---|---| | ORTEX Charts, a line chart (`core`) | **32.5 KB** | 1 | | ORTEX Charts, candles and volume (`createFinancialChart`) | **59.0 KB** | 1 | | ORTEX Charts, candles with indicators and drawings | **67.3 KB** | 1 | | ORTEX Charts, the full shell (`financial` + `ui`) | **89.9 KB** | 1 | | ORTEX Charts, a sparkline (`lite`) | **3.3 KB** | 1 | | TradingView Lightweight Charts 5, standalone production build | 60.7 KB | 1 | | Highcharts Stock 13, `highstock.js` alone | 132.6 KB | 1 | | Highcharts Stock 13, with the stock tools and indicators its own demo loads | 215.6 KB | 9 | | TradingView Advanced Charts, the licensed drop | 4,757.5 KB uncompressed | 154 | | ChartIQ, its public demo | 4.4 MB transferred | 65 | Three comparisons are worth drawing out. - **Like for like, ORTEX Charts is smaller than Lightweight Charts.** A chart with one series costs 32.5 KB here against 60.7 KB there, a little over half for the same job, and none of the difference is features it has and we do not. Adding candles, a volume pane, a legend, price lines and a crosshair readout takes ORTEX Charts to 59.0 KB, which is still under the 60.7 KB of a renderer that draws a series and stops. The 45 KB figure quoted in most comparisons is the vendor's own claim rather than a measurement of the file they publish. - **Against a chart with a financial toolbar, the gap is wide.** Highcharts Stock does have one, and loading it the way their own Stock Tools demo does costs 215.6 KB across nine files. The ORTEX equivalent is 89.9 KB in one. - **Against the licensed drops it is not close.** Advanced Charts is 154 files and 4.8 MB on disk; ChartIQ transfers 4.4 MB across 65 files before a chart appears. ### Rendering Measured on 2026-09-08 in headless Chromium at 1400 by 900, driven by Playwright inside the same Linux image the tests run in, with the same chart in every library: candles, a volume pane and two overlay lines. Three repeats, every repeat on a fresh page, and the cell is the median. `scripts/bench/bench-linux.sh` reruns it, which is how these numbers stay comparable between releases rather than between machines. **Create to first paint**, timed from before the create call to the frame that paints the data. | Bars | ORTEX Charts 1.0.21 | Lightweight Charts 5.2.1 | Highcharts Stock 13.0.2 | |---|---|---|---| | 10,000 | **40 ms** | 83 ms | 50 ms | | 100,000 | **33 ms** | 448 ms | 202 ms | Highcharts Stock runs with its own data grouping left on, which is what it ships with: at 100,000 bars it is drawing far fewer than 100,000 candles, and that is the number its users get. **A live tick, to the frame that paints it.** Call the library's update, then wait for the frame that carries the change to the compositor. Both libraries coalesce drawing onto their own animation frame, so both are measured through that path: 60 ticks, one per frame, one in ten opening a new bar and the rest refining the forming one, as a feed does. | Bars | ORTEX Charts | Lightweight Charts 5 | Highcharts Stock 13 | |---|---|---|---| | 10,000 | **33 ms** | 33 ms | 33 ms | | 100,000 | **33 ms** | 68 ms, and 112 ms at the 95th percentile | 36 ms | 33 ms is the floor of this measurement: two frames of the 60 Hz cadence headless Chromium paces rendering at. A library sitting on the floor absorbed the tick inside one frame budget and dropped nothing. At 10,000 bars both do, and there is no difference a user could see. At 100,000 bars ORTEX Charts is still on the floor, Highcharts Stock is a fraction of a frame over it, and Lightweight Charts is two to five frames late. An earlier version of this page compared an ORTEX redraw against a Lightweight Charts update call that only schedules one. That is unlike work: it flattered us at 100,000 bars and flattered them at 10,000, and it has been withdrawn. Where the same call exists on both sides, the processor cost is a tie: an update at 100,000 bars is 3.4 ms here and 3.1 ms there. ORTEX Charts and Lightweight Charts both pan and zoom at the display's 60 Hz with 100,000 bars. Highcharts Stock holds about 41 Hz. Advanced Charts and ChartIQ cannot be driven from code in this harness — there is no installable build — so only their load cost is compared. _Live example: [benchmark](https://ortexcharts.com/examples/benchmark)_ The example above runs the same measurement in your browser: it creates a chart, sets 100,000 bars, waits for the first paint and prints the number your machine produced. Expect it to be slower than the headless figure on a laptop on battery, and faster than you expect on a desktop. ### Why 100,000 Bars Starts Faster Than 10,000 The 33 ms at 100,000 bars against 40 ms at 10,000 is not a typographical error, and it is worth understanding because it explains the engine's design. Start-up cost is dominated by the work proportional to the **visible** range, not to the data. With 100,000 bars the initial view is a smaller share of the data, so fewer bars are drawn on the first frame, and the per-bar setup is a typed-array copy rather than object allocation. The remaining variance between the two runs is measurement noise on a small absolute number. ## How the Numbers Are Produced Everything above is reproducible rather than asserted. - **Payload** is measured from a production build of the packages with `bundle-size`, which bundles the public entry points and gzips the result. The competitor figures are the transferred bytes their own demo pages fetch, read from the network panel. - **Rendering** is a Playwright script against the benchmark page in the repository, headless Chromium, fixed viewport, the same generated bars given to both libraries, timed around chart creation, `setData` and the first paint. It is opt-in, so it does not run in every continuous-integration job. Both are in the repository and are re-run when the numbers change. ## What Makes It Fast - **Typed-array columns.** Series are a struct of arrays, so a data set is a handful of allocations rather than one object per bar, and slicing a visible window is free. - **Visible-range work only.** Renderers receive `from` and `to` and draw between them. Autoscale considers only the visible range. Nothing iterates the whole history on a frame. - **Decimation.** A line denser than the pixels available is reduced to one minimum and one maximum per pixel column, so drawing cost stops growing with the data. - **Layered canvases.** Each pane has a main canvas and an overlay canvas, and the time-axis label has its own. Moving the crosshair repaints the overlays only, so a pointer move never redraws a series. - **Legend DOM only on change.** The legend is rebuilt when its content key changes, so a 60 Hz pan does not churn the DOM. - **Amortized appends.** Series keep a capacity-doubling backing store and hand out subarray views, so a live tick does not copy the columns. - **Incremental alignment.** When the main timeline grows in place, overlays re-align only their tail: O(tail) per tick rather than O(n). - **Windowed indicator recompute.** An indicator that declares its `lookback` has only that window recomputed on a tick, verified equal to a full recompute to within 1e-6. - **Candles batched by color.** Up candles and down candles are two fill passes, not one per bar. The single largest improvement in the library's history came from the realtime path: the processor cost of a live tick on 100,000 bars with two overlays, an EMA and an RSI fell by roughly four fifths when alignment and indicator recompute became incremental. ## Practical Guidance ### Hand Over Columns, Not Objects ```ts // Fine for a few thousand rows. series.setData(rows.map((r) => ({ time: r.t * 1000, value: r.v }))); // Better for a large set: build the columns once and hand them over. const time = new Float64Array(n); const value = new Float64Array(n); for (let i = 0; i < n; i++) { time[i] = rows[i].t * 1000; value[i] = rows[i].v; } series.setData({ length: n, time, value }); ``` Columnar input is not copied. For 100,000 rows this is the difference between one allocation and 100,000. ### Use `update` for Live Data, Never `setData` ```ts series.update(bar); // O(1) amortized, keeps every fast path series.setData(allBars); // full rebuild, full re-align, full indicator recompute ``` Calling `setData` on every tick is the single most common performance mistake, and it undoes every incremental path in the engine at once. The rules `update` relies on: - A time equal to the last bar replaces it in place. - A later time appends into the backing store. - An **earlier** time takes the slow rebuild path, so a feed that emits out of order pays for it on every tick. Buffer and sort before handing rows over. ### Do Not Hold On to `columns` Aligned columns are views into growable buffers. They are valid until the next data change and not after it. Read what you need and let go. ### Declare `lookback` on Custom Indicators An indicator without a `lookback` recomputes over all history on every tick. That is correct and, on a long history with a fast feed, the dominant cost. Declaring the window it actually depends on turns it into a constant. ```ts lookback: (inputs) => 10 * Number(inputs.length) ``` Leave it unset only for genuinely cumulative indicators, where the last value depends on the first bar. ### Watch the Cumulative Indicators `obv`, `cvd`, `vwap` and `cumvol` recompute fully on every tick by construction. On 100,000 bars with several of them and a tick every 200 ms, they are what will show up in a profile. ### Heikin-Ashi Is Not Incremental Yet The Heikin-Ashi transform re-runs over all bars whenever the data changes, including on every live tick. On a long intraday history with a live feed this is measurable. It is a known gap rather than a design decision. ### Prefer One Chart With Panes Over Several Charts Panes share one time scale, one interaction layer and one animation frame. Three linked charts are three of everything. ### Give the Container a Size Before Creating the Chart A chart created into a zero-height container does its layout work twice: once at zero and once when the `ResizeObserver` fires. Setting the height in CSS avoids the second pass and the visible reflow. ## Where the Ceiling Is Rendering is **Canvas 2D, not WebGL**. That is a real limit and it is worth being precise about where it bites. - A few hundred thousand visible points hold 60 Hz with decimation. A decade of daily bars is 2,500 rows; a decade of minute bars is about a million rows, of which only the visible window is drawn. - What Canvas 2D does not do is millions of points **all on screen at once** at 60 Hz with no decimation — the case SciChart's WebGL renderer is built for. If your product plots raw tick data for a whole session with every point visible, this library is the wrong choice today. - A WebGL path for line and candle series behind the same API is on the roadmap. It is not implemented. The other honest limits: there is no worker offload, so computation happens on the main thread; and there is no progressive rendering, so a very large `setData` is one synchronous block rather than a series of frames. ## Measuring Your Own Chart ```ts performance.mark("start"); const chart = createFinancialChart(el, { data: bars }); chart.chart.flush(); // force a synchronous draw performance.mark("painted"); performance.measure("first-paint", "start", "painted"); console.log(performance.getEntriesByName("first-paint")[0].duration); ``` `flush()` is the important call: drawing is otherwise deferred to the next animation frame, so a naive measurement times the setup and misses the paint. For the realtime path, measure a tick the same way around `series.update` followed by `chart.flush()`, and compare it against your tick rate. Anything under about 4 ms leaves headroom at 60 Hz. --- # License keys > Issuing keys, domain binding, expiry, and what happens when a key is missing. Section: Commercial. Source: https://ortexcharts.com/docs/licensing ## What a Key Is A license key is a string in three dot-separated parts: ```text OC1.. ``` The payload is JSON. The signature is Ed25519 over the payload string, made with ORTEX's private signing key, whose public half is embedded in `@ortex-charts/core`. Keys cannot be forged without that private key, which never leaves ORTEX's secret store. ```ts interface LicensePayload { id: string; // unique key id, for support and revocation customer: string; product: string; // always "ortex-charts" tier: string; // informational: "community", "pro", "business", "oem" features: string[]; // "whitelabel", "brand", "financial", "viz", "drawings", or "*" domains: string[]; // hostnames; "*.example.com" matches subdomains; "*" matches anything iat: number; // issued at, Unix seconds exp: number; // expiry, Unix seconds } ``` ## Installing One Call `setLicenseKey` once, as early as you can, before any chart is created. Every check, the signature included, runs before the call returns, so the state is settled by the next line; the promise it returns is for the optional revocation list, and awaiting it is never required. The signature is verified by the library's own Ed25519 implementation rather than by the browser's WebCrypto, so nothing a page can replace or remove takes part in the check. ```ts import { setLicenseKey } from "@ortex-charts/financial"; const status = await setLicenseKey(process.env.NEXT_PUBLIC_ORTEX_CHARTS_KEY!); console.log(status.state, status.verified, status.message); ``` On the [hosted kit](https://ortexcharts.com/docs/install) this is already done: the kit file ends with a `setLicenseKey` call carrying your key, so nothing in your page has to know about it. ### Where to Put the Key The key is a public artifact. It ships to the browser, it is bound to your domains, and anyone can read it out of your bundle. Treat it like a publishable API key rather than a secret: an environment variable at build time is convenient and correct, and a secret store is unnecessary. ```ts void setLicenseKey(import.meta.env.VITE_ORTEX_CHARTS_KEY); // Vite void setLicenseKey(process.env.NEXT_PUBLIC_ORTEX_CHARTS_KEY!); // Next.js ``` What is secret is the **registry token** in your `.npmrc`, which grants access to the package downloads. That one belongs in continuous-integration secrets and never in a commit. ## The States ```ts import { licenseStatus, onLicenseChange, hasFeature, clearLicense } from "@ortex-charts/financial"; licenseStatus(); // { state, payload, message, verified } hasFeature("whitelabel"); // true only on a valid license granting it onLicenseChange((s) => console.log(s.state)); clearLicense(); // mostly for tests ``` | `state` | Meaning | Effect | |---|---|---| | `unlicensed` | No key has been set. | Gated: on localhost the chart draws with the [ORTEX mark](https://ortexcharts.com/docs/branding); on any other host it draws the licence notice instead of its content. | | `pending` | Reserved; no longer occurs, since the signature is checked before `setLicenseKey` returns. | Treated as not valid. | | `valid` | Everything checked out, signature included. | Features per the payload. | | `invalid` | Malformed, wrong product, or a signature that failed. | Gated, as `unlicensed`. | | `expired` | `exp` is in the past. | Gated, as `unlicensed`. | | `domain` | The current hostname is not covered. | Gated, as `unlicensed`. | | `revoked` | The key id is on a revocation list. | Gated, as `unlicensed`. | `verified` reports that the Ed25519 signature was checked and passed. Since the check is the library's own and runs on every platform, `valid` and `verified: true` now always go together; there is no browser on which a payload is trusted unchecked. ### The Gate Since 1.1.0 the licence is a gate. `licenseGate()` answers `{ blocked, reason }` for the current state and hostname, and every chart asks it before it paints a frame: - **On a development host** (`localhost`, `127.0.0.1`, `::1`, any `*.localhost`, or no hostname at all as in tests and server-side rendering) the gate is never closed. An unlicensed chart draws in full with the ORTEX mark on, so evaluation, unit tests and continuous integration need no key. The console stays quiet unless a chart asks to hide the mark, which writes one warning. - **On any other host** a chart in any state but `valid` paints a notice on its own background, "ORTEX Charts. A licence key is required to display this chart", with the reason the check gave and the address of [/pricing](https://ortexcharts.com/pricing), and nothing else: no series, axes, legends, crosshair or tooltips. The moment a key verifies, every chart on the page repaints itself in full. The gate decides from the key's payload, not from a remembered answer: on every frame it checks the expiry against the clock and the domains against the hostname of the moment, and it requires the signature to have been verified. A key that expires while the page is open closes the gate at that second, and a key installed on one host does not carry to another. ```ts import { licenseGate } from "@ortex-charts/financial"; licenseGate(); // { blocked: false, reason: "" } on localhost licenseGate("app.example.com"); // { blocked: true, reason: "No licence key set" } with no key ``` Treemaps, heatmaps and the other `@ortex-charts/viz` components paint the same notice. Sparklines in `@ortex-charts/lite` are not gated. ## Domains `domains` is a list of hostnames the key covers. - An exact hostname matches itself: `app.example.com`. - A wildcard matches the base and every subdomain: `*.example.com` covers `example.com`, `app.example.com` and `a.b.example.com`. - `*` matches anything, and is what an OEM key usually carries. - **`localhost` is always allowed**, along with `127.0.0.1`, `::1` and any `*.localhost` host, on every key. Development never fails a domain check. ```ts import { domainAllowed } from "@ortex-charts/financial"; domainAllowed("app.example.com", ["*.example.com"]); // true domainAllowed("example.net", ["*.example.com"]); // false ``` The check runs against `location.hostname`, at install and again on every frame, and there is no way to tell the library it is somewhere else. Preview deployments are the case that catches people out. A branch preview on `pr-482.vercel.app` is not covered by `*.example.com`, so add the preview host as a wildcard domain when the key is issued, or accept the licence notice on previews. ### Two Layers of Domain Enforcement Hosted-kit customers are checked twice. The CloudFront function in front of the CDN compares the request `Origin` or `Referer` against the domains registered on the kit and refuses to serve the file to an unlisted host, and the key inside the file checks the hostname again in the browser. Registry customers get the second check only. ## Expiry and Renewal Keys are issued for the subscription term with a **14-day grace period** added on top, so a renewal that is a few days late never flips a customer's chart to the mark. A renewal re-signs onto the **same key id and the same kit id**, so your script tag and your key id do not change from year to year — only the key string does, and hosted-kit customers do not even see that. When a key does expire, the state becomes `expired`, the gate closes and the chart paints the licence notice instead of its content, naming the reason. There is no countdown and no degradation before that date. The right to use the library ends with the term on every plan; renewing issues a fresh key with no change to your code. ## Features | Feature | What it grants | |---|---| | `whitelabel` | `branding.visible = false` is honored: the mark may be hidden. Every paid plan. | | `brand` | The mark may be replaced with your own logo, text, caption and link. OEM agreements. | | `financial` | Informational; the financial package is not gated. | | `viz` | Informational; the viz package is not gated. | | `drawings` | Informational; drawing tools are not gated. | | `*` | Everything, including `whitelabel` and `brand`. | Being precise about this: **only `whitelabel` and `brand` change behavior today.** The others are recorded on the key so that the plan a customer is on is visible in the payload, and so that a future gate has a name to use, but no feature check in the library disables a package. A Pro key and an OEM key run the same code with the same capabilities; the mark is the difference. What a key of any plan does is open the gate. ## Getting a Key - **Pro and Business** keys are issued automatically. A purchase on ortexcharts.com signs a key, builds a hosted kit, registers your domains, issues a registry token and emails all of it within seconds of payment. There is no free key: evaluate on localhost and in the [playground](https://ortexcharts.com/playground), then buy with the sixty-day guarantee. - **OEM and enterprise** keys are issued by hand from the same signer after a conversation. Changing the domains on a key means re-issuing it, which happens automatically when the domains on the subscription change; the kit is rebuilt at the same URL. ## Revocation Every payload carries an `id`, and ORTEX can revoke a key before its expiry. What happens to a running implementation depends on how the library reached it: - **A hosted kit** stops being served within seconds: the kit's domains are removed from the edge store, so the next page load gets a 403 rather than the script. A page that already has the script loaded keeps its chart until reload; on reload there is no chart. - **A registry install that passes `revocationList`** reads a small JSON document from the ORTEX CDN once after the key verifies. A revoked id found there drops the licence to `revoked`: the gate closes and the chart paints the licence notice instead of its content. The document is cached for a few minutes, so that is the delay. - **A registry install that does not** keeps working until the key expires or the id ships in the library's built-in `REVOKED_KEY_IDS` in a later release, because the licence check makes no network call unless asked to. ```ts setLicenseKey(key, { revocationList: "https://cdn.ortexcharts.com/v1/revoked.json" }); ``` The list can only revoke, never grant, so an unreachable or malformed list changes nothing; a chart never goes dark because ORTEX was unreachable. Hosted kits set the option themselves. Whichever route, revocation and cancellation also revoke the registry token, so `npm install` stops as well, and the licence itself ends at that moment: Section 7 of the [licence](https://ortexcharts.com/legal/licence) applies. ## Testing Without a Key On a development host the gate never closes, so evaluation on `localhost`, unit tests in jsdom and continuous integration need no key: the chart draws in full with the ORTEX mark on. `localhost` is always allowed, so local development with a real key never fails a domain check either. The first real hostname is where a key is needed. For tests that need a specific license state, install your real key and read the status back; `clearLicense` returns the page to `unlicensed`: ```ts import { clearLicense, setLicenseKey, licenseStatus } from "@ortex-charts/financial"; beforeEach(() => clearLicense()); it("hides the mark under a white-label key", async () => { await setLicenseKey(KEY); expect(licenseStatus().state).toBe("valid"); }); ``` `setLicenseKey` takes no `publicKey`, `hostname` or `now` overrides. Earlier versions accepted them for tests, and the first of them let a page trust a signing key of its own, so they were withdrawn in 1.2.0. A key is verified against ORTEX's embedded signing key, on the hostname the page is served from, at the time it is installed and again on every frame. ## Related - [The ORTEX mark](https://ortexcharts.com/docs/branding) — what showing and hiding it actually means. - [Installation and delivery](https://ortexcharts.com/docs/install) — kits, registry tokens and source access. - [Questions we are asked](https://ortexcharts.com/docs/faq) — expiry, telemetry and support. --- # Moving from TradingView or Highcharts > Six ways products embed a chart today, and what the move costs from each one. Section: Commercial. Source: https://ortexcharts.com/docs/moving-in ## Find Your Integration, Not Your API Almost every product that draws financial charts has arrived at one of six shapes. The API mapping is on the [migration page](https://ortexcharts.com/docs/migration); this page is about the shape you are in, because that is what decides how long the move takes and what is easy to miss. Find the row that describes you. | Your shape | Typical signs | Effort | |---|---|---| | [A widget in a trading terminal](#a-widget-in-a-trading-terminal) | TradingView Advanced Charts in an iframe, one chart, saved layouts per user | A week | | [A chart on every instrument page](#a-chart-on-every-instrument-page) | One chart per symbol, server-rendered pages, no drawings | A day or two | | [A research or screening product](#a-research-or-screening-product) | Highcharts Stock, many small charts, comparisons, exports | Two to four days | | [A portfolio tracker](#a-portfolio-tracker) | Performance lines, allocation pies, risk matrices | Two to four days | | [A white-label platform you resell](#a-white-label-platform-you-resell) | One codebase, many brokers or prop firms, your customers' branding | A week, plus a licensing conversation | | [Charts in a dashboard](#charts-in-a-dashboard) | Highcharts for everything, finance is one section | A day per chart family | Everything below assumes one fact that catches everybody once: **timestamps are milliseconds since the Unix epoch, in UTC.** Not seconds, not business-day objects, not local dates. ## A Widget in a Trading Terminal You embed TradingView Advanced Charts, users draw on it, and you save their layouts, studies and drawings against their account so a chart follows them between devices. **What carries over as it is.** Your datafeed. The `resolveSymbol`, `getBars`, `subscribeBars` and `searchSymbols` shapes are deliberately close, and `tradingViewDatafeed` wraps an existing one so you can run it unchanged on day one. ```ts import { tradingViewWidget } from "@ortex-charts/migrate"; // Your existing widget options and your existing datafeed. const shell = tradingViewWidget({ container: "chart", symbol: "BTCUSD", interval: "60", datafeed: myTradingViewDatafeed, disabled_features: ["header_symbol_search"], }); ``` **What you have to decide.** Where saved state lives. Advanced Charts offers a save/load server contract and a chart storage service; ORTEX Charts has neither, on purpose. `shell.getLayout()` returns JSON and `shell.setLayout(json)` puts it back, so the store is the one you already have: a column on the user row, a document, a key in your own service. ```ts const shell = createChartShell(el, { symbol, datafeed, layout: await api.loadChartLayout(userId), onLayoutChange: (layout) => void api.saveChartLayout(userId, layout), drawingsStore: { load: (sym) => api.loadDrawings(userId, sym), save: (sym, drawings) => api.saveDrawings(userId, sym, drawings), }, }); ``` Drawings are stored per symbol rather than inside the layout, because a trend line on one instrument means nothing on another. **What will bite.** Three things, in the order people hit them. - **Callbacks became promises.** `getBars` returns `{ bars, noMoreData }` instead of calling `onHistoryCallback`. - **There is no iframe.** The chart is in your DOM, which is mostly a gift: your fonts, your CSS variables, your dev tools. It also means your CSS resets now apply to it. If your app sets `* { box-sizing: content-box }` or a global `canvas` rule, you will see it. - **Feature flags became options.** The `disabled_features` string list maps onto typed switches. `fromTVWidgetOptions` translates the common ones and lists the rest, flag by flag, in `ignored`. [Moving from TradingView](https://ortexcharts.com/docs/from-tradingview) ports one real widget end to end. **What you gain that matters here.** No attribution requirement on a licensed build, and no restriction to services offered free of charge. The free Advanced Charts agreement requires the TradingView mark to stay visible **and** the service to be free to the public, which a subscription terminal is not. ## A Chart on Every Instrument Page One chart per token, ticker or fund. Users read it; few of them draw on it. The page is often server-rendered and the chart is the only interactive thing on it. This is the fastest migration of the six, and the one where payload matters most: the chart is on the critical path of a page a search engine sends people to. ```ts import { createFinancialChart } from "@ortex-charts/financial"; const chart = createFinancialChart(el, { data: bars, // straight from your API seriesType: "candlestick", volume: true, theme: "dark", tooltip: { mode: "hovered", template: "{name} {value}\n1d {value % value[-1]}" }, }); ``` **Drop the shell if you do not need it.** `createFinancialChart` is the chart without the toolbar; a page with its own period buttons and its own symbol header does not need a second set. That is [59.0 KB rather than 89.9](https://ortexcharts.com/docs/performance). **Server rendering.** There is no server renderer, here or in the alternatives. Render the page, mount the chart on the client, and give the container a fixed height so the page does not jump when it appears. **Instrument pages are where the free plan usually stops applying.** If the page carries advertising or sits behind any kind of subscription, it is a commercial use. ## A Research or Screening Product Highcharts Stock behind a screener: many charts, often small, frequently compared against each other, and usually exportable. **Start with the translator.** It takes the options object you already have. ```ts import { fromHighcharts } from "@ortex-charts/migrate"; const { chart, series, indicators, markers, unsupported } = fromHighcharts(el, myHighchartsOptions); console.warn("did not carry over:", unsupported); // read this list once, then delete the line ``` The candles, the volume pane, the indicator series, the flags and the plot lines come through in that one call; `unsupported` names what has no equivalent rather than dropping it silently, so the port is a checklist. [Moving from Highcharts](https://ortexcharts.com/docs/from-highcharts) ports one real Highcharts Stock chart end to end, including the range selector and the theme. **Three things to plan for.** - **Comparisons.** A Highcharts compare axis becomes a second series plus a percentage or indexed scale: `rightPriceScale: { mode: "percentage" }`, or `"indexedTo100"`. - **Exporting.** There is no exporting server. `downloadPNG(canvas)` and `rowsToCSV` cover image and data export from the browser; a PDF report is your renderer's job. - **Many small charts.** If a chart is a cell in a results table, it should not be a chart at all: `@ortex-charts/lite` draws a [sparkline in 3.3 KB](https://ortexcharts.com/docs/sparklines) with no engine behind it. ## A Portfolio Tracker Performance lines, allocation by sector or asset, contribution and risk matrices. Only some of what you draw is a price chart. The financial chart covers the performance line. The rest is `@ortex-charts/viz`, which shares the engine, the theme and the maths: | What you draw now | What draws it here | |---|---| | Highcharts line or area with a percentage axis | `createFinancialChart` with `rightPriceScale: { mode: "percentage" }` | | Pie or donut of allocation | `createPieChart` | | Heatmap of returns by month or sector | `createHeatmap` | | Treemap of holdings | `createTreemap` | | Bar chart of contribution | `createCategoryChart` | | Scatter of risk against return | `createXYChart` with `kind: "scatter"` | | Sankey of flows in and out | `createSankeyChart` | `translateHighchartsCategory` and `translateHighchartsPie` take the category and pie options directly, so the non-price charts move with the same checklist as the price ones. **Watch the benchmark line.** A tracker almost always draws the portfolio against an index. Two series on a percentage scale, both anchored at the same first bar, is the correct shape; `align: "exact"` keeps a benchmark with different trading days on the portfolio's timeline rather than inventing bars for it. ## A White-Label Platform You Resell You build one trading platform and sell it to brokers or prop firms, each with their own branding. The chart inside it is TradingView, and every one of your customers inherits that relationship. This is the shape where the licence, not the API, is the reason to move. - **The mark is removable.** Every paid licence removes the ORTEX mark; an OEM agreement puts yours in its place. Your customers see your platform, not ours. - **One licence, many deployments.** If you ship the same product to fifty brokers, that is an [OEM](https://ortexcharts.com/oem) conversation rather than fifty licences: redistribution rights, a source drop, and a price that reflects the deployment rather than the seat count. - **Your customers do not need their own agreement.** Under OEM the chart is part of your product. Technically it is the terminal migration above, with one addition: whatever your branding system already does per customer, the chart follows. ```ts createChartShell(el, { symbol, datafeed, theme: brokerTheme, // your customer's palette, as tokens branding: { visible: false }, // with a white-label or OEM key toolbar: { symbol: false }, // their header already names the instrument }); ``` Set the licence key once at start-up with `setLicenseKey`, not per chart. ## Charts in a Dashboard Highcharts draws everything you have, and the financial charts are one section among many. You are not replacing Highcharts everywhere; you are replacing it where it is weakest. Move the price and time-series charts, keep the rest, and let the two coexist. Nothing here registers globals or touches the DOM outside its own container. When the financial section is done, the rest of `@ortex-charts/viz` is there if you want it, and the two libraries can run on one page for as long as you like. The one thing worth doing on day one is the theme: pull your palette into [theme tokens](https://ortexcharts.com/docs/customization) so the new charts match the old ones while both are on screen. ## What Every Migration Should Check Before It Ships - **Timestamps in milliseconds, UTC.** Every conversion bug traces back here. - **The first paint on your slowest page.** That is the number that justified the move. - **A symbol with a short history.** Week-over-week comparisons and indicators need enough bars; make sure they degrade rather than throw. - **A symbol with gaps.** Halts, holidays and thin instruments. - **Your saved layouts.** Load an old one, change something, save it, reload. - **The licence key on the deployed origin**, not just on localhost. - **The mark**, if you expect it to be gone. It goes when the key says it can, and not before. --- # Moving from Highcharts > One real Highcharts Stock chart ported end to end: what the translator does and what is left by hand. Section: Commercial. Source: https://ortexcharts.com/docs/from-highcharts ## The Chart Every Research Product Has This page ports one real Highcharts Stock chart, the one nearly every screener and research product has: candles, volume on a second y-axis, two moving averages as indicator series, earnings flags, a target line, a range selector, a navigator and the exporting module, with a page-wide theme from `Highcharts.setOptions` and live ticks through `addPoint`. The options object below is the one the port starts from; the [API mapping](https://ortexcharts.com/docs/migration) is the concept-by-concept table to keep open beside it. ```ts const options: Highcharts.Options = { chart: { height: 520 }, title: { text: "IBM · NYSE" }, rangeSelector: { selected: 4, buttons: [{ type: "month", count: 1, text: "1m" }, { type: "year", count: 1, text: "1y" }, { type: "all", text: "All" }] }, navigator: { enabled: true }, exporting: { enabled: true }, yAxis: [ { title: { text: "Price" }, height: "65%", opposite: true, plotLines: [{ value: 250, color: "#ff9800", dashStyle: "ShortDash", label: { text: "Target 250" } }] }, { title: { text: "Volume" }, top: "70%", height: "30%", offset: 0, opposite: true }, ], plotOptions: { candlestick: { color: "#ef5350", upColor: "#26a69a" } }, series: [ { type: "candlestick", id: "ibm", name: "IBM", data: ohlc }, // [x, o, h, l, c] { type: "column", id: "vol", name: "Volume", data: volume, yAxis: 1 }, // [x, v] { type: "sma", linkedTo: "ibm", name: "SMA 20", params: { period: 20 }, color: "#ffb74d" }, { type: "ema", linkedTo: "ibm", name: "EMA 50", params: { period: 50 }, color: "#4fc3f7" }, { type: "flags", onSeries: "ibm", name: "Earnings", shape: "circlepin", data: flags }, // { x, title, text } ], }; Highcharts.stockChart("chart", options); ``` Timestamps need no conversion: Highcharts and ORTEX Charts both use milliseconds since the Unix epoch. ## Step One: The Translator ```bash npm install @ortex-charts/migrate ``` ```ts import { fromHighcharts } from "@ortex-charts/migrate"; const { chart, series, indicators, markers, unsupported } = fromHighcharts(el, options, { theme: "dark" }); console.info("no counterpart:", unsupported); ``` `options` is the typed `Highcharts.Options` from above, passed as it is; the translator's input types accept it without a cast. One call produces: | In the options | On the chart | |---|---| | `candlestick` with `[x, o, h, l, c]` rows | The main series, on the right scale of the first pane. | | `yAxis[1]` with `top: "70%"` and `height: "30%"` | A second pane, 30/65 the height of the first. | | The `column` on `yAxis: 1` | The volume, in that pane, colored by the candle's direction and formatted as volume. | | `sma` and `ema` with `params.period` | `addIndicator("sma", { length: 20 })` and `addIndicator("ema", { length: 50 })`, in the series' colors. | | `flags` with `{ x, title, text }` | Markers above the bar: the title as the text, the text as the tooltip, `circlepin` as a circle. | | `plotLines` on `yAxis[0]` | One price line at 250, dashed, labelled, on the main series. | | `title.text` | The watermark. | | `chart.height` | The chart height. | And `unsupported` reads: ```text exporting (the shell offers the equivalent) navigator (the shell offers the equivalent) rangeSelector (the shell offers the equivalent) ``` Nothing else is lost, and nothing is emitted for what was: a series the translator cannot draw leaves no empty legend row behind. `translateHighcharts(options)` returns the same translation without creating anything: `chart`, `panes`, `series`, `indicators`, `markers` and `unsupported`, for a test or for a port that builds the chart itself, as the next step does. ## Step Two: What Is Left by Hand Three items in `unsupported`, and two that never appear in a Highcharts options object. **The range selector and the navigator.** These are the shell's period buttons. `createChartShell` takes everything `createFinancialChart` takes, so the translation can be poured into it. The buttons default to a day, a week, a month, a quarter, a year, five years and ten years; `ranges` sets your own. See [the toolbar](https://ortexcharts.com/docs/toolbar#period-buttons). **Exporting.** There is no export server. The shell's screenshot button and CSV download cover the two things the module was used for; `downloadPNG` and `rowsToCSV` in `@ortex-charts/viz` are the same from code. A PDF report is your renderer's job. **The theme.** `Highcharts.setOptions({ colors, chart: { backgroundColor } })` configured the page. Here every chart carries a theme object: start from `darkTheme`, set `background`, `grid`, `text`, `fontFamily` and `palette`, and pass it as `theme`. Indicators take the palette in order, which is what the `colors` array did. See [colors, fonts and formatting](https://ortexcharts.com/docs/customization). **Live ticks.** `series.addPoint(point, false)` on the candle, again on the volume, then `chart.redraw()` becomes one call: `fc.update(bar)`. A bar whose time equals the last bar replaces it; a later time appends. The chart schedules its own frame. **"All" is not `fitContent`.** Highcharts drew ten years in one view by grouping the data into weekly points. `timeScale.fitContent()` stops at `minBarSpacing`, half a pixel per bar by default, so 2,500 daily bars do not fit in 1,100 pixels and the view opens on the most recent bars that do. Lower `timeScale.minBarSpacing`, or open on the last year with `setVisibleRange`, which is what most readers wanted from "All" anyway. ## Step Three: The Finished Port The translation plus the shell, in about 30 lines. This is the code the research-product row of [moving in](https://ortexcharts.com/docs/moving-in) is budgeting for. ```ts import { createChartShell } from "@ortex-charts/ui"; import { darkTheme } from "@ortex-charts/financial"; import { translateHighcharts } from "@ortex-charts/migrate"; import type { Bar } from "@ortex-charts/math"; const t = translateHighcharts(options); const candle = t.series.find((s) => s.type === "candlestick")!; const bars = candle.data as Bar[]; // The volume came through as its own series; the financial chart draws volume from Bar.volume. const volume = t.series.find((s) => s.volume); if (volume) { const byTime = new Map((volume.data as Array<{ time: number; value: number }>).map((p) => [p.time, p.value])); for (const b of bars) b.volume = byTime.get(b.time) ?? 0; } const shell = createChartShell(el, { ...t.chart, // height, legend, watermark theme: { ...darkTheme, name: "brand", background: "#131722", grid: "#1f2535", palette: ["#4fc3f7", "#ffb74d", "#ba68c8"] }, timeZone: "America/New_York", resolution: "1D", symbol: "IBM", data: bars, volume: { heightRatio: t.panes[0]?.heightRatio ?? 0.3 }, toolbar: { symbol: false, resolution: false }, // the page has its own header extrasCollapsed: true, }); const fc = shell.chart; for (const l of candle.priceLines) fc.chart.addPriceLine(fc.main.id, { ...l, lineWidth: 1, axisLabelVisible: true, title: l.title ?? "" }); for (const ind of t.indicators) fc.addIndicator(ind.id, ind.inputs, ind.color ? { colors: { [ind.id]: ind.color } } : {}); fc.setMarkers(t.markers); feed.onBar((bar) => fc.update(bar)); // was addPoint + redraw ``` `fromHighcharts` is this without the shell: the same panes, indicators, markers and price lines on a core chart, for a page that has its own period buttons and export. ## Column and Pie Charts The other Highcharts charts on the page move in one call each, with nothing left by hand. ```ts import { fromHighchartsCategory, fromHighchartsPie } from "@ortex-charts/migrate"; const { chart: column, unsupported } = fromHighchartsCategory(el, columnOptions); // xAxis.categories, stacking: "normal" const pie = fromHighchartsPie(el, pieOptions); // innerSize: "60%" is a donut ``` Percent stacking is the one thing reported: normalise the data first. See [treemaps and heatmaps](https://ortexcharts.com/docs/viz) for what the category and pie charts can do that Highcharts' cannot. ## Before You Ship - **Check `unsupported` once**, then delete the log line. - **A comparison axis** becomes a second series on a percentage or indexed scale: `rightPriceScale: { mode: "percentage" }`, or `"indexedTo100"`. - **A Highcharts indicator with no counterpart** (Ichimoku, VWAP and the rest of the long tail) is reported by type. Look in `@ortex-charts/indicators-extra` first, then [register your own](https://ortexcharts.com/docs/indicators#writing-your-own). - **Indicator defaults differ.** A period Highcharts left unset takes the ORTEX Charts default, which is 20 for a moving average where Highcharts used 14. Set it explicitly if the number matters. - **Many small charts** in a results table should be [sparklines](https://ortexcharts.com/docs/sparklines), not charts. - **The licence key on the deployed origin**, not just on localhost. --- # Moving from TradingView > One real Charting Library widget ported end to end: the drop-in, what it ignores, and what onChartReady becomes. Section: Commercial. Source: https://ortexcharts.com/docs/from-tradingview ## The Widget Every Terminal Has This page ports one real TradingView Charting Library integration: a `new TradingView.widget` call with a theme, feature flags, overrides and a save/load service, a JS-API datafeed with callbacks and timescale marks, and an `onChartReady` block that adds two studies and a shape. The [API mapping](https://ortexcharts.com/docs/migration#from-tradingview-advanced-charts) is the table to keep open beside it; this page is the port itself. ```ts const widget = new TradingView.widget({ container: "chart", library_path: "/charting_library/", symbol: "IBM", interval: "D", datafeed, // onReady, searchSymbols, resolveSymbol, getBars, subscribeBars, getTimescaleMarks locale: "en", theme: "Dark", timezone: "America/New_York", autosize: true, disabled_features: ["header_symbol_search", "header_compare", "use_localstorage_for_settings", "header_saveload"], enabled_features: ["study_templates", "hide_left_toolbar_by_default"], overrides: { "mainSeriesProperties.candleStyle.upColor": "#26a69a", "mainSeriesProperties.candleStyle.downColor": "#ef5350", "paneProperties.background": "#131722" }, studies_overrides: { "volume.volume.color.0": "#ef5350", "volume.volume.color.1": "#26a69a" }, charts_storage_url: "https://saveload.example.com", charts_storage_api_version: "1.1", client_id: "terminal", user_id: userId, }); widget.onChartReady(() => { const chart = widget.activeChart(); chart.createStudy("Moving Average Exponential", false, false, [21]); chart.createStudy("Relative Strength Index", false, false, [14]); chart.createShape({ time: t, price: 250 }, { shape: "horizontal_line", text: "Target 250", lock: true }); }); ``` ## Step One: The Drop-In ```bash npm install @ortex-charts/migrate ``` ```ts import { tradingViewWidget } from "@ortex-charts/migrate"; const shell = tradingViewWidget(widgetOptions); console.info("no counterpart:", shell.ignored); ``` `widgetOptions` is the typed `ChartingLibraryWidgetOptions` from above, and `datafeed` the typed `IBasicDataFeed` inside it, passed as they are; the translator's input types accept both without a cast. The datafeed runs unchanged: `onReady` is awaited once, `resolveSymbol` once per symbol, `getBars` is asked in seconds and answered in milliseconds as before, and `subscribeBars` streams into the chart. The chart is on screen with history, live bars, the dark theme, the New York time zone and no symbol box. `shell.ignored` reads: ```text studies_overrides charts_storage_url charts_storage_api_version client_id user_id disabled_features: use_localstorage_for_settings disabled_features: header_saveload enabled_features: study_templates ``` Everything not in that list was mapped: `symbol` and `interval`, `theme`, `timezone`, `locale`, `header_symbol_search` to `toolbar.symbol: false`, `header_compare` to `compare: false`, `hide_left_toolbar_by_default` to `drawingRailCollapsed: true`, and the three overrides to the `up`, `down` and `background` theme tokens. `library_path` is neither, because there is no bundle to load. `fromTVWidgetOptions(widgetOptions)` returns the same shell options and the same `ignored` list without creating anything. ## Step Two: What Is Left by Hand Everything in `ignored`, plus what lived in `onChartReady` and in the datafeed's optional methods. **The `onChartReady` block.** The shell is ready when `tradingViewWidget` returns, so the block becomes the lines after it. `createStudy` is `shell.addIndicator`; `createShape` is `shell.drawings.add`. ```ts shell.addIndicator("ema", { length: 21 }); shell.addIndicator("rsi", { length: 14 }); shell.drawings?.add({ kind: "horizontalLine", points: [{ time: t, price: 250 }], style: { text: "Target 250" }, locked: true }); ``` Study names become indicator ids: `Moving Average Exponential` is `ema`, `Relative Strength Index` is `rsi`, `Bollinger Bands` is `bb`, `MACD` is `macd`. The [indicators](https://ortexcharts.com/docs/indicators) page lists all 51, and `listIndicators()` is the same list at runtime. **Timescale marks.** `getTimescaleMarks` has no wrapper; the earnings badges it drew are [events](https://ortexcharts.com/docs/markers#events) with `style: "lane"`: ```ts shell.chart.setEvents(earnings.map((time) => ({ time, style: "lane", group: "Earnings", text: "E", tooltip: "Earnings" }))); ``` **The save/load service.** `charts_storage_url`, `client_id` and `user_id` pointed at TradingView's storage contract. There is none here, on purpose: `shell.getLayout()` is JSON and `onLayoutChange` fires when it changes, so the store is the one you already have. `onLayoutChange` is a creation option, so it goes in the second argument: ```ts const shell = tradingViewWidget(widgetOptions, { layout: await api.loadChartLayout(userId), onLayoutChange: (layout) => void api.saveChartLayout(userId, layout), drawingsStore: { load: (s) => api.loadDrawings(userId, s), save: (s, d) => api.saveDrawings(userId, s, d) }, }); ``` Drawings are stored per symbol rather than inside the layout; see [the shell and layouts](https://ortexcharts.com/docs/shell). **`studies_overrides`.** Indicator colors are per call: `shell.addIndicator("ema", { length: 21 }, { colors: { ema: "#4fc3f7" } })`. The volume pane's colors are the `volumeUp` and `volumeDown` theme tokens. **Resolutions.** The widget read `supported_resolutions` from the datafeed and offered only those. `tradingViewWidget` is synchronous, as the widget constructor was, and the feed's list is not, so it offers the shell's default resolutions: a daily-only feed would show minute buttons. `tradingViewWidgetAsync` waits for the list first: ```ts const shell = await tradingViewWidgetAsync(widgetOptions); // resolutions: what the symbol, else onReady, declared ``` **Feature flags with no counterpart.** `use_localstorage_for_settings` and `header_saveload` describe TradingView's own storage, which does not exist here. `study_templates` is a [layout](https://ortexcharts.com/docs/shell#layouts-the-chart-never-persists-the-host-does) you store. ## Step Three: The Finished Port ```ts import { tradingViewWidgetAsync } from "@ortex-charts/migrate"; const shell = await tradingViewWidgetAsync(widgetOptions, { layout: await api.loadChartLayout(userId), onLayoutChange: (layout) => void api.saveChartLayout(userId, layout), }); shell.addIndicator("ema", { length: 21 }); shell.addIndicator("rsi", { length: 14 }); shell.drawings?.add({ kind: "horizontalLine", points: [{ time: t, price: 250 }], style: { text: "Target 250" }, locked: true }); shell.chart.setEvents(earnings.map((time) => ({ time, style: "lane", group: "Earnings", text: "E" }))); ``` The datafeed object is the one from the widget, untouched. Delete the `library_path` directory from `public/`: that was 6 MB. ## Keeping Your Own Shell A product that already has its own toolbar wants the datafeed and nothing else. `tradingViewDatafeed` wraps it, and `supportedResolutions` asks it what it serves: ```ts import { tradingViewDatafeed } from "@ortex-charts/migrate"; import { createChartShell } from "@ortex-charts/ui"; const feed = tradingViewDatafeed(datafeed); const shell = createChartShell(el, { datafeed: feed, symbol: "IBM", resolution: "1D", resolutions: await feed.supportedResolutions("IBM"), toolbar: { symbol: false, resolution: false }, }); ``` ## From Lightweight Charts There is no translator for Lightweight Charts and none is needed: the mental models are the same and the [mapping table](https://ortexcharts.com/docs/migration#from-tradingview-lightweight-charts) is exact. The one idiom to know is the overlay volume, a histogram on `priceScaleId: ""` with `scaleMargins`, which is `createFinancialChart` with `volume: true`; and times, which were seconds there and are milliseconds here. ```ts const fc = createFinancialChart(el, { theme: "dark", timeZone: "America/New_York", resolution: "1D", data: bars, volume: true }); fc.addIndicator("sma", { length: 20 }); // was addSeries(LineSeries) + your own SMA fc.chart.addPriceLine(fc.main.id, { price: 250, lineStyle: "dashed", title: "Target" }); // was series.createPriceLine fc.setMarkers(markers); // was createSeriesMarkers fc.chart.timeScale.fitContent(); // a property, not a method fc.chart.subscribeCrosshairMove((e) => e.seriesValues.get(fc.main.id)); // was param.seriesData.get(series) ``` ## Before You Ship - **Read `shell.ignored` once**, then delete the log line. - **Studies with no counterpart.** Advanced Charts ships about 110 studies against 51 built in and 78 more in `@ortex-charts/indicators-extra`; the long tail is mostly variations. Budget for the ones you have to [register](https://ortexcharts.com/docs/indicators#writing-your-own). - **Your CSS resets now apply.** There is no iframe. A global `canvas` rule or `* { box-sizing: content-box }` will show. - **Load an old layout, change something, save it, reload.** - **A symbol with a short history**, so the indicators degrade rather than throw. - **The licence key on the deployed origin**, not just on localhost. --- # API mapping > Concept by concept, from Lightweight Charts, Highcharts Stock, Advanced Charts or ChartIQ. Section: Commercial. Source: https://ortexcharts.com/docs/migration ## How to Read This Page If you have not decided yet, start with [moving from TradingView or Highcharts](https://ortexcharts.com/docs/moving-in): it is organised by how products actually embed a chart, and it says what the move costs from each shape. This page is the concept-by-concept mapping you want open while you do it. Four libraries, four honest comparisons. Each section maps the concepts that line up, then states plainly what that library does which ORTEX Charts does not. The second half is the part that matters when you are deciding, so it is not buried. Competitor APIs change between major versions. The mappings below are written against Lightweight Charts 5, Highcharts Stock 13, TradingView Advanced Charts 20-era and ChartIQ 8; check the exact names against the version you are on. One thing is common to all four migrations: **timestamps in ORTEX Charts are milliseconds since the Unix epoch, in UTC, everywhere.** Not seconds, not business-day objects, not local dates. That single conversion is most of the work in a mechanical port. ## The Translators Do the Mechanical Half For the two libraries most people arrive from, you do not have to do the mapping by hand. `@ortex-charts/migrate` takes what you already have — a TradingView datafeed and widget options, or a Highcharts options object — and returns a working chart plus a list of what did not carry over, so the port is a checklist rather than a guess. ```bash npm install @ortex-charts/migrate ``` ```ts import { tradingViewWidget, tradingViewDatafeed, fromHighcharts } from "@ortex-charts/migrate"; // Drop-in for `new TradingView.widget({...})` const shell = tradingViewWidget({ container_id: "chart", datafeed, symbol: "NASDAQ:AAPL", interval: "D", theme: "Dark" }); // Or keep your own shell and wrap only the datafeed createChartShell(el, { datafeed: tradingViewDatafeed(myDatafeed), symbol: "NASDAQ:AAPL", resolution: "1D" }); // Highcharts and Highcharts Stock, options object and all const { chart, series, indicators, markers, unsupported } = fromHighcharts(el, highchartsOptions); if (unsupported.length) console.info("Look at:", unsupported); ``` The inputs are typed to accept the vendors' own objects as they are: a `ChartingLibraryWidgetOptions` with its `IBasicDataFeed`, or a `Highcharts.Options`, without a cast. Two pages port one real chart each, end to end: [moving from Highcharts](https://ortexcharts.com/docs/from-highcharts) and [moving from TradingView](https://ortexcharts.com/docs/from-tradingview). The TradingView wrapper turns the callback interface into the promise one: `onReady` is awaited once, `resolveSymbol` is resolved once per symbol and cached, `getBars` is converted from seconds to milliseconds, `subscribeBars` returns an unsubscribe function, and resolutions map both ways (`D` ↔ `1D`). `pricescale` and `minmov` become `priceFormat`, and the first entry of `logo_urls` becomes the legend logo. `supportedResolutions()` on the wrapped feed answers with what the symbol, else `onReady`, declared, and `tradingViewWidgetAsync` waits for it so the toolbar offers only those. The Highcharts translator reads the series types (`line`, `spline`, `area`, `areaspline`, `column`, `bar`, `candlestick`, `ohlc`, `scatter`), every point shape Highcharts accepts, y-axes placed with `top` and `height` as panes, the column on the second axis under a candlestick as the volume, `sma`, `ema`, `wma`, `rsi`, `atr`, `bb`, `macd` and `stochastic` series as indicators with their periods, `flags` as markers, `plotLines` as price lines (once per axis), a left axis, and `dashStyle`, `lineWidth`, `fillOpacity` and `visible`. `fromHighchartsCategory` and `fromHighchartsPie` do the same for column, bar and pie charts. Anything without a counterpart is reported rather than silently dropped, and nothing is emitted for it: the Highcharts translator lists series types, `yAxis.min`/`max`, percent stacking and the modules the shell replaces (`navigator`, `rangeSelector`, `scrollbar`, `exporting`, `annotations`, `stockTools`) in `unsupported`; the TradingView translator lists every widget key, `disabled_features` or `enabled_features` flag and `overrides` path it did not read in `ignored`, on the shell it returns. `translateHighcharts`, `translateHighchartsCategory`, `translateHighchartsPie` and `fromTVWidgetOptions` return the translation without creating anything, which is what you want in a test or a gradual move. The rest of this page is the conceptual mapping, which you still want to read: the translators get a chart on the screen, not a finished port. ## From TradingView Lightweight Charts This is the easiest migration of the four. The mental models are close: one chart, series you add to it, data you set and update, a time scale you drive. ### API Mapping | Lightweight Charts | ORTEX Charts | |---|---| | `createChart(el, options)` | `createChart(el, options)`, or `createFinancialChart(el, options)` for a chart with a volume pane | | `chart.addSeries(CandlestickSeries, o)` | `chart.addSeries("candlestick", o)` | | `chart.addSeries(LineSeries, o)` | `chart.addSeries("line", o)` | | `chart.addSeries(AreaSeries, o)` | `chart.addSeries("area", o)` | | `chart.addSeries(BaselineSeries, o)` | `chart.addSeries("baseline", o)` | | `chart.addSeries(HistogramSeries, o)` | `chart.addSeries("histogram", o)` | | `chart.addSeries(BarSeries, o)` | `chart.addSeries("bar", o)` | | `series.setData(data)` | `series.setData(data)` | | `series.update(bar)` | `series.update(bar)` | | `series.applyOptions(o)` | `series.applyOptions(o)` | | `chart.removeSeries(series)` | `chart.removeSeries(series.id)` | | `chart.applyOptions(o)` | `chart.applyOptions(o)` | | `chart.timeScale().fitContent()` | `chart.timeScale.fitContent()` | | `chart.timeScale().setVisibleLogicalRange({from, to})` | `chart.timeScale.setVisibleRange(from, to)` | | `chart.timeScale().scrollToRealTime()` | `chart.timeScale.scrollToRealtime()` | | `chart.subscribeCrosshairMove(cb)` | `chart.subscribeCrosshairMove(cb)` | | `chart.subscribeClick(cb)` | `chart.subscribeClick(cb)` | | `chart.addPane()` | `chart.addPane({ heightRatio })` | | `createSeriesMarkers(series, markers)` | `addSeriesMarkers(chart, series, markers)`, or `fc.setMarkers(markers)` | | `series.createPriceLine(o)` | `chart.addPriceLine(series.id, o)` | | `chart.remove()` | `chart.remove()` | | Custom series plugin | `registerSeriesType(name, def)` | | Pane primitive plugin | `chart.addPrimitive(primitive, paneId)` | ### The Differences That Bite - **`timeScale` is a property, not a method.** `chart.timeScale.fitContent()`. - **Times are milliseconds.** Lightweight Charts takes Unix **seconds** or a business-day object. Multiply by 1,000; convert `{ year, month, day }` to a UTC midnight timestamp. - **Series are removed by id**, not by reference: `chart.removeSeries(series.id)`. - **Series types are strings**, not imported constructors. - **Colors default from the theme.** Where you set `upColor` and `downColor` on every series, you can set them once in the theme instead. - **A series declares how it aligns** to the main timeline. Lightweight Charts requires every series to share a time axis; here a daily series on an intraday chart is `align: "forwardFill"` rather than a data-preparation problem. ### What Lightweight Charts Has That ORTEX Charts Does Not - **It is open source, Apache 2.0.** No license key, no mark, no contract, no cost. If that is the deciding factor, it decides. - It is about 5 KB smaller for the subset it covers. - It has a longer public track record and a larger body of community examples. ### What You Gain A toolbar, symbol search, 32 drawing tools, 51 indicators, event markers, order flow, bar replay, alerts, host-managed layouts, an adapter layer, and a faster first paint at large data sizes — for about 5 KB more. ## From Highcharts Stock The mental model is further away. Highcharts is declarative: you describe a whole chart as one options object and call `update` to change it. ORTEX Charts is imperative: you create objects and call methods on them. ### API Mapping | Highcharts Stock | ORTEX Charts | |---|---| | `Highcharts.stockChart(el, options)` | `createFinancialChart(el, options)` | | `series: [{ type: "candlestick", data }]` | `chart.addSeries("candlestick").setData(data)` | | `data: [[x, o, h, l, c]]` | `[{ time, open, high, low, close, volume }]` | | `series: [{ type: "line", data: [[x, y]] }]` | `chart.addSeries("line").setData([[time, value]])` | | `yAxis: [{ …}, { … }]` with `height` and `top` | `chart.addPane({ heightRatio })` plus `priceScaleId` | | `yAxis.type: "logarithmic"` | `chart.priceScale("right").applyOptions({ mode: "logarithmic" })` | | `series[i].addPoint(point, redraw, shift)` | `series.update(point)` | | `series[i].setData(data)` | `series.setData(data)` | | `chart.update(options)` | `chart.applyOptions(options)` | | `series[i].update({ color })` | `series.applyOptions({ color })` | | `series: [{ type: "sma", linkedTo: "main", params: { period } }]` | `chart.addIndicator("sma", { length })` | | `series: [{ type: "flags", data }]` | `chart.setEvents(events)` or `chart.setMarkers(markers)` | | `chart.setSize(w, h)` | `chart.resize(w, h)`, or leave `autoSize` on | | `Highcharts.setOptions({ colors })` | `chart.setTheme({ ...darkTheme, palette })` | | `chart.destroy()` | `chart.remove()` | | `exporting` module | `chart.takeScreenshot()`, `shell.exportCsv()`, `downloadPNG`, `downloadCSV` | ### The Differences That Bite - **There is no global options object.** Nothing is configured for the page; every chart carries its own options and its own theme. - **Panes are not y-axes with pixel offsets.** A pane is a real container with a relative height weight, and a scale lives inside it. - **Indicators are not linked series.** They are a separate concept with their own registration, inputs and outputs. - **Rendering is Canvas, not SVG.** There is no DOM node per point to style with CSS or select with a query, and no SVG export. Styling is options and theme tokens. - **Redrawing is automatic.** There is no `redraw` flag on mutators; the chart schedules a frame. - **Times are milliseconds** here as well, which Highcharts also uses, so this is the one migration where timestamps need no conversion. ### What Highcharts Stock Has That ORTEX Charts Does Not - **A navigator strip and range-selector buttons** (1m, 3m, YTD, 1y, All) as built-in components. Range presets are the shell's period buttons, or a few lines on `setVisibleTimeRange`; a navigator mini-chart is not built in. The "All" button is not `timeScale.fitContent()` on a long history: Highcharts groups daily bars into weekly points to fit ten years in one view, while `fitContent` stops at `minBarSpacing`, half a pixel per bar by default, so 2,500 daily bars do not fit in 1,100 pixels and the view opens on the most recent bars that do. Lower `timeScale.minBarSpacing`, or open on a year. - **An accessibility module**: screen-reader descriptions of the data, a focusable data table, and keyboard navigation of points. See [The toolbar](https://ortexcharts.com/docs/toolbar) for what is and is not implemented here. - **A server-side export server** producing PNG, PDF and SVG from a running service. - **SVG rendering**, if per-point DOM matters to you for styling or testing. - **A boost module** for very large point counts. ### What You Gain About a fifth of the payload, a financial toolbar and drawing tools that Highcharts Stock does not include, an index-based time axis that removes closed periods without configuration, order flow, bar replay, and per-product rather than per-developer licensing. ## From TradingView Advanced Charts This is the migration with the largest gap in both directions, because Advanced Charts is a complete application delivered as a widget rather than a library you compose. ### API Mapping | Advanced Charts | ORTEX Charts | |---|---| | `new TradingView.widget({ … })` | `createChartShell(el, { … })` | | `datafeed` with `onReady`, `resolveSymbol`, `getBars`, `subscribeBars`, `searchSymbols` | `Datafeed` with `resolveSymbol`, `getBars`, `subscribeBars`, `searchSymbols`; no `onReady` | | `LibrarySymbolInfo` | `SymbolInfo` | | `resolution` as `"1"`, `"60"`, `"1D"` | The same notation | | `widget.setSymbol(symbol, interval, cb)` | `shell.setSymbol(s)` and `shell.setResolution(r)` | | `widget.activeChart().createStudy(name, …)` | `shell.addIndicator(id, inputs)` | | `widget.activeChart().createShape(point, o)` | `tools.add({ kind, points, style })` | | `widget.activeChart().createMultipointShape(points, o)` | The same | | `widget.activeChart().setChartType(n)` | `shell.setSeriesType("candlestick")` | | `widget.activeChart().setVisibleRange({from, to})` | `chart.timeScale.setVisibleTimeRange(from, to)` | | `widget.save(cb)` and `widget.load(state)` | `shell.getLayout()` and `shell.setLayout(layout)` | | `disabled_features` and `enabled_features` | `toolbar`, `drawings`, `indicators`, `drawingTools` switches | | `overrides` | Theme tokens and series options | | `widget.onChartReady(cb)` | The shell is ready when `createChartShell` returns | | Timescale marks | `chart.setEvents(events)` with `style: "lane"` | | Compare study | The built-in `price` overlay for another symbol | Datafeed shapes are deliberately close, so a port is usually mechanical: drop `onReady`, return `{ bars, noMoreData }` instead of calling `onHistoryCallback`, and return bars with millisecond `time` rather than second `time`. ### The Differences That Bite - **Callbacks become promises.** `getBars` returns a promise instead of calling `onHistoryCallback` and `onErrorCallback`. - **Times are milliseconds**, not seconds. - **There is no iframe.** The chart is in your DOM, so your CSS, your fonts and your developer tools all apply — and so do your layout bugs. - **State is yours.** There is no `save`/`load` server contract and no chart storage service; `getLayout` gives you JSON and you decide where it lives. - **Feature flags become option switches.** The `disabled_features` string list is replaced by typed options on the shell. ### What Advanced Charts Has That ORTEX Charts Does Not - **Around 110 built-in studies** against 51. The long tail there is mostly variations on what is here. - **The TradingView platform behind it**: the interface users already recognize, and the Pine Script ecosystem that comes with the platform rather than with the library. Custom studies in Advanced Charts itself are JavaScript, as they are here. - **Around 90 drawing tools** against 32. - **Multi-chart layouts** (two-by-two and the rest) as a built-in container, with symbol and interval synchronization. `linkCharts` synchronizes time and crosshair here, but the grid container is your CSS. - **Around 30 interface languages.** The chrome here is English only. - **A broker and order-management integration** — order tickets, positions, depth of market, an account panel — in the Trading Platform edition. - **The brand recognition.** Users know the interface. ### What You Gain 89.9 KB in one file instead of 4.8 MB across 154. A chart you can style, extend and debug. No attribution requirement on a licensed build, and no restriction to services offered free of charge: the free Advanced Charts agreement requires the TradingView mark **and** a service the public can use without paying, which rules out a subscription product and an internal desk tool outright. ## From ChartIQ ChartIQ is the closest competitor on feature depth and the furthest away on API style. It is also the most expensive of the four, sold as an annual enterprise contract. ### API Mapping | ChartIQ | ORTEX Charts | |---|---| | `new CIQ.ChartEngine({ container })` | `createFinancialChart(el, options)` | | `stxx.loadChart(symbol, { periodicity, masterData })` | `chart.bind(datafeed, { symbol, resolution })` | | `quotefeed` with `fetchInitialData`, `fetchPaginationData`, `fetchUpdateData` | `Datafeed` with `getBars` and `subscribeBars` | | `stxx.setPeriodicity({ period, interval })` | `binding.setResolution("15")` | | `stxx.setChartType("candle")` | `fc.setSeriesType("candlestick")` | | `stxx.setChartScale("log")` | `chart.priceScale("right").applyOptions({ mode: "logarithmic" })` | | `CIQ.Studies.addStudy(stxx, "rsi", inputs, outputs)` | `fc.addIndicator("rsi", inputs, options)` | | `stxx.addSeries(symbol, params)` | `chart.addSeries(type, options).setData(data)` | | `stxx.createDrawing(kind, params)` | `tools.add({ kind, points, style })` | | `stxx.exportDrawings()` and `importDrawings()` | `tools.getDrawings()` and `setDrawings()` | | `stxx.append`/`updateChartData` | `series.update(bar)` | | Themes as CSS | Theme tokens on the chart | | `stxx.destroy()` | `chart.remove()` | ### The Differences That Bite - **Styling is options, not CSS.** ChartIQ is styled with stylesheets over its own class names; here every color is a theme token or a series option. - **There is no periodicity object.** A resolution is a string. - **There is no `masterData` concept**; series own their own data and alignment. ### What ChartIQ Has That ORTEX Charts Does Not - **A much deeper indicator and study library**, with study editing, comparison studies and a study browser. - **Term structure, options chains, cross-section and time-span event charts** as first-class chart types. - **A trading and order-management integration**, and a market-depth component. - **Multi-chart layouts and workspace management** as products in their own right. - **A managed data service and a signature integration ecosystem.** - **An accessibility story**, including screen-reader support. ### What You Gain The demo transfers 4.4 MB and reaches DOMContentLoaded at 3.4 seconds. The full ORTEX chart is 89.9 KB in one file. Order flow — footprint bars, exact volume and market profiles, real delta from aggressor data — is included rather than a platform tier. And the price is public. ## A Migration Checklist Whichever library you are coming from: 1. **Convert timestamps to milliseconds, UTC.** Multiply seconds by 1,000, convert business-day objects to a UTC midnight, and drop local-date parsing. 2. **Set `timeZone` to the exchange zone**, not to the browser zone, or daily bars will land on the wrong day for a third of your users. 3. **Set `session`** if you draw intraday bars, so hourly candles start at the open. See [Time, sessions and resolutions](https://ortexcharts.com/docs/time). 4. **Move colors into a theme** rather than onto every series, so the theme switch works. 5. **Replace per-series time alignment work with `align`.** Data that does not share the price timeline is a series option here, not a pre-processing step. 6. **Replace `setData`-per-tick with `update`.** This is the single biggest performance difference between a good port and a bad one. 7. **Decide where layouts and drawings live**, because the library will not decide for you. See [The shell and layouts](https://ortexcharts.com/docs/shell). 8. **Audit your indicator list against the 51 built-ins** and budget for the ones you have to write. This is the most common source of unplanned work in a migration. ## The Honest Summary | If you need | Choose | |---|---| | Open source with no license at all | Lightweight Charts | | 110 studies, 90 drawing tools, 30 interface languages | TradingView Advanced Charts | | A navigator, an accessibility module, a server-side export service, SVG | Highcharts Stock | | The deepest study library, term structure, order management, an enterprise contract | ChartIQ | | Millions of points on screen at 60 Hz | SciChart | | A small, fast, extensible financial chart with a toolbar, drawings, order flow and replay, that you can white-label, priced per product | ORTEX Charts | --- # API reference > Every export of every package, grouped by what it is for. Section: Packages. Source: https://ortexcharts.com/docs/api ## How This Page Is Organized Every runtime export of every package, at version 1.2.0, grouped by package and then by purpose. Type-only exports are listed where they matter and omitted where they are only the options object of the function above them. `@ortex-charts/financial` re-exports all of `@ortex-charts/core`, so anything in the core tables is importable from `financial` too. Nothing re-exports `@ortex-charts/math`: data types such as `Bar` and `Tick` are imported from there directly. ## The Entry Points The five functions that create something. Everything else configures or extends what they return. ```ts function createChart(container: HTMLElement, options?: DeepPartial): Chart; function createFinancialChart(container: HTMLElement, options?: FinancialChartOptions): FinancialChart; function createChartShell(container: HTMLElement, options?: ChartShellOptions): ChartShell; function createSparkline(container: HTMLElement, options?: Partial): Sparkline; function createAdapter(spec: AdapterSpec, deps?: AdapterDeps): Adapter; ``` Plus the six in `@ortex-charts/viz`: `createTreemap`, `createHeatmap`, `createCategoryChart`, `createXYChart`, `createPieChart` and `createSankeyChart`, each `(container, options) => Component`. And, for a port, [`@ortex-charts/migrate`](https://ortexcharts.com/docs/migration#the-translators-do-the-mechanical-half): `tradingViewWidget`, `tradingViewWidgetAsync`, `tradingViewDatafeed`, `fromHighcharts`, `fromHighchartsCategory` and `fromHighchartsPie`, with `translateHighcharts`, `translateHighchartsCategory`, `translateHighchartsPie`, `fromTVWidgetOptions`, `fromTVSymbolInfo`, `fromTVResolution`, `toTVResolution` and `fromHCData` for the translation on its own. ## `@ortex-charts/math` Pure functions and small classes. No DOM, no canvas. Runs in Node and in a worker. ### Data Types and Conversion | Export | Description | |---|---| | `Bar` | One OHLCV row, with optional `buyVolume` and `sellVolume`. | | `Tick` | One trade: `time`, `price`, `size`, optional aggressor `side`. | | `BarSeries` | OHLCV in struct-of-arrays form with `Float64Array` columns. | | `ValueSeries` | Single-value series in the same form. | | `TimeValuePoint` | A `[time, value]` pair. | | `Range` | A numeric `[from, to]` pair. | | `barSeriesFromRows(rows)` | Rows to columns; allocates the aggressor columns only when a row carries them. | | `barSeriesToRows(series)` | Columns back to rows. | | `valueSeriesFromPoints(points)` | `[time, value]` pairs to columns. | | `valueSeriesFromColumns(time, value)` | Two arrays to a `ValueSeries`; throws when the lengths differ. | | `EMPTY_BARS` | A shareable empty `BarSeries`. | | `clamp(v, lo, hi)` | Clamp a number into a range. | ### Scales | Export | Description | |---|---| | `PriceScale` | Value-to-pixel mapping for one price axis, with autoscale and margins. | | `PriceScaleMode` | `"normal" \| "logarithmic" \| "percentage" \| "indexedTo100"`. | | `PriceScaleOptions` | Options for `PriceScale` (distinct from the chart's own price-scale options). | | `TimeIndexScale` | The index-based time axis: bar index to pixel, time to fractional index, zoom and scroll, extrapolation past the data. | | `TimeIndexScaleOptions`, `LogicalRange` | Its options and visible-range type. | | `symLog10(v)` | Symmetric base-10 log, linear near zero and defined for negatives. | | `symPow10(t)` | Its inverse. | ### Ticks | Export | Description | |---|---| | `priceTicks(...)` | Nice tick values for a price scale given pixel height and a minimum label gap. | | `PriceTick`, `PriceTickOptions` | Its result and options. | | `timeTicks(...)` | Ticks for the index axis with weighted labels so labels never collide. | | `TimeTick`, `TimeTickOptions` | Its result and options. | | `TickWeight` | The label significance ladder: year beats month beats day beats hour. | | `minimumWeight(barSpacing, minLabelGap, resolution)` | The finest weight worth labeling at a given zoom. | | `labelFor(parts, weight, locale)` | Label text for a tick: the coarsest unit that changed. | ### Formatting | Export | Description | |---|---| | `formatPrice(v, options?)` | Grouped fixed-precision number with an ASCII minus. | | `formatPercent(v, options?)` | Percentage formatting. | | `formatCompact(v, options?)` | `1.23M`, `4.56B`. | | `formatVolume(v)` | Volume shorthand. | | `precisionFromMinMove(minMove)` | Decimals implied by a minimum move. | | `precisionForRange(lo, hi, tickCount, minPrecision?)` | Decimals needed so neighboring tick labels differ. | | `NumberFormatOptions` | `precision`, `grouping`, `sign`. | | `formatBarTime(time, options)` | Bar label appropriate to the resolution. | | `formatClock(time, options)` | Time of day in a zone. | | `formatDate(time, options)` | Date in a zone. | | `TimeFormatOptions` | `timeZone`, `resolution`, `locale`. | ### Time Zones | Export | Description | |---|---| | `zonedParts(time, zone)` | Wall-clock parts of a timestamp in a zone. | | `ZonedParts` | Their shape. | | `tzOffsetMinutes(time, zone)` | Offset from UTC at that instant. | | `zonedTimeToUtc(parts, zone)` | Wall-clock parts back to a timestamp. | | `localWallToUtc(localMs, zone)` | A local wall-clock millisecond value back to UTC. | | `startOfZonedDay(time, zone)` | Midnight of that day in the zone. | | `minuteOfZonedDay(time, zone)` | Minutes since midnight in the zone. | ### Resolutions | Export | Description | |---|---| | `parseResolution(text)` | `"1"`, `"15"`, `"1D"`, `"1W"`, `"1M"` to a `Resolution`; throws on nonsense. | | `Resolution`, `ResolutionUnit` | The parsed form and its unit. | | `floorTimeToBar(time, res, zone?)` | Start of the bar containing a time, honoring `anchorMinute`. | | `nextBarTime(time, res, zone?)` | Start of the following bar. | | `sameBar(a, b, res, zone?)` | Whether two times share a bar. | | `anchoredResolution(res, session)` | A resolution phased from the session open. | | `intervalForUnit(unit)` | The `UtcInterval` a resolution's unit steps by. | ### Sessions | Export | Description | |---|---| | `parseSession(text)` | `"0930-1600"`, `"0400-0930,0930-1600"`, `"24x7"`, with an optional `:days` suffix. | | `Session`, `SessionSegment` | The parsed form. | | `mergeSegments(segments)` | Sort and merge touching or overlapping segments. | | `sessionMinutes(session)` | Total minutes in a session. | | `isInSession(time, session, zone)` | Membership, including overnight wraps. | | `sessionBoundsForDay(time, session, zone)` | `[start, end]` pairs for that day. | | `sessionMinuteAt(time, session, zone)` | Minutes elapsed in the session, `NaN` when closed. | ### Bars and Alignment | Export | Description | |---|---| | `ticksToBars(ticks, res, zone?)` | Trades to bars. | | `applyTick(last, tick, res, zone?)` | Fold one tick into the current bar; returns the bar and whether it appended. | | `aggregateBars(series, res, zone?)` | Coarser bars from finer ones, carrying aggressor volumes through. | | `heikinAshi(series)` | The Heikin-Ashi transform. | | `finiteRange(bars)` | Bar-index range whose close is finite. | | `priceExtent(bars, from, to)` | Min low and max high over an inclusive index range. | | `valueExtent(values, from, to)` | Min and max of a value column over an inclusive index range. | | `BarBuffer` | Growable OHLCV storage with amortized appends and zero-copy views. | | `alignToTimeline(masterTimes, series, options?)` | One value per master time, `NaN` where the rules give nothing. | | `alignTail(masterTimes, from, series, options?)` | The same for the tail only, which is the live path. | | `timesToIndices(masterTimes, times, barDurationMs)` | Fractional master indices for arbitrary times. | | `unionTimes(...columns)` | One sorted, de-duplicated timeline from several. | | `AlignMode`, `AlignOptions` | `"exact" \| "forwardFill" \| "nearest" \| "bucket"`, and `maxGapMs`. | ### Statistics and Search | Export | Description | |---|---| | `rollingSum`, `rollingMean`, `rollingStd`, `rollingMin`, `rollingMax` | Windowed statistics over a `Float64Array`. | | `ema(values, length)` | Exponential moving average. | | `wilderSmooth(values, length)` | Wilder's smoothing, for RSI and ATR. | | `pctChange`, `logReturns`, `cumulativeReturn`, `diff` | Return series. | | `lowerBound`, `upperBound` | Bisect on a sorted array. | | `nearestIndex(sorted, t)` | Closest index; ties go earlier. | | `indexRange(sorted, t0, t1)` | Inclusive index range within a value range. | ### Geometry | Export | Description | |---|---| | `traceLine(ctx, xs, ys, options?)` | Trace a polyline; `NaN` breaks the line into gaps. | | `traceArea(...)` | Trace a closed area between a series and a baseline. | | `crisp(px, lineWidth?, dpr?)` | Snap a coordinate so a one-pixel line is not blurred. | | `PathContext`, `CurveKind`, `PathOptions` | The minimal canvas path surface, `"linear" \| "step" \| "monotone" \| "smooth"`, and options. | ## `@ortex-charts/core` The canvas engine. ### Chart | Export | Description | |---|---| | `createChart(el, options?)` | Create a chart. | | `Chart` | The engine class; see the method groups below. | | `TimeScaleApi` | `chart.timeScale`: ranges, conversions and the range subscription. | | `CHART_DEFAULTS` | The full default `ChartOptions`. | | `ChartOptions` and the option interfaces | `PriceScaleOptions`, `TimeScaleOptions`, `CrosshairOptions`, `CrosshairLineOptions`, `CrosshairMode`, `GridOptions`, `LegendOptions`, `WatermarkOptions`. | `Chart` methods, grouped: - **Options and theme:** `options`, `applyOptions`, `theme`, `setTheme`, `resolution`. - **Panes:** `addPane`, `removePane`, `pane`, `panesList`, `resizePanes`, `setPaneCollapsed`, `isPaneCollapsed`, `maximizePane`, `restorePanes`, `maximizedPane`, `subscribePaneChange`. - **Scales:** `priceScale`, `zoomPriceScale`, `panPriceScale`, `resetPriceScale`, `valueAtPixel`. - **Series:** `addSeries`, `removeSeries`, `series`, `getSeries`, `mainSeries`, `setMainSeries`, `times`, `nextPaletteColor`, `subscribeDataChange`. - **Price lines:** `addPriceLine`, `removePriceLine`. - **Primitives:** `addPrimitive`, `removePrimitive`, `primitive`, `paneView`. - **Interaction and events:** `subscribeCrosshairMove`, `subscribeClick`, `subscribeDblClick`, `subscribeLegendMenu`, `setCrosshairPosition`, `clearCrosshairPosition`, `crosshairState`, `setCursor`. - **Geometry:** `paneRect`, `plotRect`, `zoneAt`. - **Lifecycle:** `resize`, `size`, `requestDraw`, `flush`, `takeScreenshot`, `remove`. `TimeScaleApi` methods: `fitContent`, `scrollToRealtime`, `scrollByPixels`, `zoom`, `setVisibleRange`, `setVisibleTimeRange`, `visibleRange`, `setBarSpacing`, `barSpacing`, `timeToCoordinate`, `coordinateToTime`, `indexToCoordinate`, `coordinateToIndex`, `timeToIndex`, `indexToTime`, `subscribeVisibleRangeChange`. ### Panes and Scales | Export | Description | |---|---| | `PaneModel` | A pane: canvases, legend element, scales and primitives. | | `PaneOptions` | `heightRatio`, `minHeight`, `collapsed`. | | `PriceScaleState` | One price scale in a pane; `applyOptions`, `zoomAt`, `panBy`, `resetAutoScale`, `currentPlotDomain`. | | `PRICE_SCALE_DEFAULTS` | Default price-scale options. | ### Series | Export | Description | |---|---| | `SeriesModel` | A series: data, options, alignment, price lines. | | `SeriesHost` | The interface a chart satisfies for a series. | | `registerSeriesType(name, def)` | Register a renderer so `addSeries(name, …)` works. | | `getSeriesType(name)` | Look one up; throws with the registered names. | | `SeriesTypeDef`, `SeriesView`, `SeriesKind` | The renderer contract. | | `SeriesTypeMap`, `BuiltInSeriesType` | Type-level map from a built-in name to its options. | | `SeriesOptionsBase`, `SeriesDataInput`, `SeriesValue` | Common options, accepted inputs, and the crosshair value shape. | | `LineSeriesOptions`, `AreaSeriesOptions`, `BaselineSeriesOptions`, `HistogramSeriesOptions`, `CandlestickSeriesOptions`, `BarSeriesOptions` | Per-type options. | | `pixelColumns(view, key)` | Pixel columns for the visible range, with one extra bar each side. | | `drawDecimated(...)` | Draw a dense line as one minimum and one maximum per pixel column. | | `bodyWidth(barSpacing, ratio)` | Candle body width that never exceeds the gap. | | `ohlcValueAt(columns, index)` | OHLCV at an index, or null. | `SeriesModel` methods: `setData`, `update`, `updateNow`, `applyOptions`, `setType`, `valueAt`, `primaryValue`, `lastIndex`, `holdUpdates`, `releaseUpdates`; properties `id`, `type`, `kind`, `options`, `columns`, `raw`, `rawTimes`, `rawLength`, `holding`, `priceLines`, `optionsChanged`. ### Primitives, Drawing and Layout | Export | Description | |---|---| | `PanePrimitive`, `PaneView`, `PrimitiveLayer`, `PrimitivePointerEvent` | The primitive contract. | | `PriceLineOptions` | A horizontal line at a value with an axis label. | | `CanvasLayer` | A device-pixel-ratio aware canvas. | | `FrameScheduler` | Coalesces draw requests onto one animation frame. | | `applyLineStyle`, `hline`, `vline`, `roundRect`, `measureText`, `drawLabel`, `drawText` | Canvas helpers a primitive can reuse. | | `LabelStyle` | Options for `drawLabel`. | | `inRect(rect, x, y)`, `Point`, `Rect` | Geometry helpers. | ### Theme and Formatting | Export | Description | |---|---| | `darkTheme`, `lightTheme` | The two built-in token sets. | | `Theme` | The token interface. | | `resolveTheme(theme)` | `"dark"`, `"light"` or an object to an object. | | `parseColor(color)` | Any accepted color string to `[r, g, b, a]`. | | `withAlpha(color, alpha)` | The same color at `alpha`, relative to the transparency it already carries. | | `isTransparent(color)` | True for `transparent` and any color with zero alpha. | | `surfaceOf(theme)` | The opaque color under the chart: `surface`, else `background`, else the mode's ground. | | `contrastText(background)` | Black or white, whichever reads. | | `formatValue(value, priceFormat)` | Exactly what the chart would print for a series value. | | `formatAxisValue(value, format, lo, hi, tickCount)` | The same for an axis tick, adding decimals on a narrow range. | | `PriceFormat` | `type`, `precision`, `minMove`, optional `formatter`. | ### Events, Utilities and Licensing | Export | Description | |---|---| | `Emitter` | The minimal event emitter the library uses. | | `Listener`, `DeepPartial` | Its listener type, and the recursive partial used by every options argument. | | `merge(base, patch)` | Deep merge used by `applyOptions`. | | `uid(prefix)` | Unique id generator. | | `CrosshairEvent`, `VisibleRangeEvent`, `LegendMenuEvent`, `HitResult` | Event payloads. | | `LineStyle`, `PriceScalePosition` | `"solid" \| "dashed" \| "dotted"`, `"left" \| "right" \| "overlay"`. | | `setLicenseKey(key, options?)` | Install a license key; every check, the signature included, runs before it returns. `options.revocationList` names a JSON document of revoked ids to read once afterwards, and `options.fetch` replaces the global `fetch` for that read. Since 1.2.0 there are no `publicKey`, `hostname` or `now` options. | | `licenseGate(hostname?)` | `{ blocked, reason }` for the current state on the given host, or on `location.hostname`. | | `isDevelopmentHost(hostname)` | The rule under which the gate never closes: `localhost`, loopback, `*.localhost`, no hostname. | | `revokeKeyIds(...ids)`, `revokedKeyIds()` | Add key ids to the runtime revocation set, and read it. | | `paintLicenseGate(ctx, rect, theme, reason)`, `LICENSE_GATE_URL` | The notice a gated chart paints, and the address it names. | | `licenseStatus()` | The current `LicenseStatus`. | | `hasFeature(name)` | Whether the current license grants a feature. | | `onLicenseChange(cb)` | Subscribe to status changes. | | `clearLicense()` | Reset to unlicensed, mostly for tests. | | `domainAllowed(hostname, domains)` | The domain-matching rule, including the localhost exemption. | | `ORTEX_CHARTS_PUBLIC_KEY`, `ORTEX_CHARTS_PUBLIC_KEYS`, `REVOKED_KEY_IDS` | The embedded Ed25519 verification key, the frozen list of trusted keys by id, and the key ids revoked in the build. | | `LicenseState`, `LicensePayload`, `LicenseStatus`, `SetLicenseOptions`, `LicenseGate` | Licensing types. | | `Branding`, `BRANDING_DEFAULTS`, `BrandingOptions`, `BrandingPosition` | The mark and its options. | | `ortexLogoSvg`, `ortexLogoDataUri`, `ORTEX_LOGO_ASPECT` | The wordmark as markup, as a data URI, and its aspect ratio. | ## `@ortex-charts/financial` Everything in `core`, plus the following. ### The Financial Chart ```ts function createFinancialChart(container: HTMLElement, options?: FinancialChartOptions): FinancialChart; ``` | Member | Description | |---|---| | `chart`, `main`, `volume` | The core chart, the main series, and the volume series or null. | | `setData(bars)`, `update(bar)` | Data in. | | `setSeriesType(type, options?)`, `seriesType()` | Switch the main series style without losing state. | | `addIndicator(id, inputs?, options?)` | Add an indicator. | | `setMarkers(markers)` | Trade-style marks; returns the primitive. | | `setEvents(events)` | Time-anchored annotations; returns the primitive. | | `setFootprint(flow, options?)` | Order-flow cells, and exact aggressor volumes on the bars. | | `addVolumeProfile(options?)` | A volume or market profile on the main pane. | | `replay(options?)` | The bar-replay controller, created on first use. | | `alerts(options?)` | The price-alerts primitive, created on first use. | | `live(source, options?)` | Stream a live source into the main series. | | `connect(wsOptions, streamOptions?)` | Open a WebSocket and stream it in. | | `bind(feed, options)` | Bind a datafeed. | | `remove()` | Dispose. | `MainSeriesType` is `"candlestick" \| "bar" \| "line" \| "area" \| "baseline"`. ### Data | Export | Description | |---|---| | `bindDatafeed(chart, series, feed, options)` | Initial load, lazy history, realtime subscription, symbol and resolution switching. | | `Datafeed`, `BarsRequest`, `BarsResponse`, `SymbolInfo`, `BindOptions`, `DatafeedBinding` | The datafeed contract. | | `WebSocketSource`, `websocketSource(options)` | A reconnecting WebSocket that parses messages into items. | | `ManualSource` | A source you push into. | | `pollingSource(fetchNext, intervalMs)` | Poll an async function. | | `attachWindowedData(chart, series, fetch, options?)`, `WindowedData`, `WindowedLoadOptions`, `WindowedFetch`, `WindowedPoint`, `WINDOWED_DEFAULTS` | History fetched a window at a time as the view moves. | | `LiveSource`, `SocketStatus`, `WebSocketSourceOptions` | Source types. | | `streamTo(series, source, options?)` | Fold live items into a series; what `live` calls. | | `StreamOptions`, `LiveItem` | Its options and the accepted item shapes. | ### Adapters | Export | Description | |---|---| | `createAdapter(spec, deps?)` | Build a datafeed and live sources from a spec; throws on an invalid one. | | `validateAdapterSpec(spec)` | Structural checks with actionable messages. | | `Adapter`, `AdapterDeps` | The result and its injectable dependencies. | | `AdapterError` | Thrown with the list of problems. | | `ortexAdapterSpec(options)`, `OrtexAdapterOptions` | The preset for the ORTEX API. | | `AdapterSpec`, `HistorySpec`, `LiveSpec`, `SymbolSpec`, `SearchSpec`, `MessageSpec`, `RecordSpec`, `RecordsSpec`, `RecordKind`, `FieldSpec`, `FieldRef`, `TimeFieldSpec`, `TimeUnit`, `Condition`, `JsonTemplate`, `DateParamSpec` | The spec vocabulary. | | `getPath`, `readField`, `readNumber`, `parseTime`, `formatTimeParam` | Field and time readers, exported so a host can reuse them. | | `fillTemplate`, `fillJsonTemplate`, `matches` | Template filling and condition matching. | | `mapRecord`, `mapRecords`, `explainMapping` | Mapping, and why a sample produced nothing. | | `MappedRecord`, `TemplateContext` | Their types. | ### Indicators | Export | Description | |---|---| | `addIndicator(chart, id, inputs?, options?)` | Add an indicator to any chart. | | `registerIndicator(def)` | Register your own. | | `getIndicator(id)` | Look one up; throws with the registered ids. | | `listIndicators()` | Every registered definition. | | `indicators` | The built-in library namespace, including `BUILT_IN_INDICATORS` and `barDelta`. | | `sourceColumn(columns, source)` | Resolve `close`, `hl2`, `hlc3`, `ohlc4` and the rest. | | `IndicatorDef`, `IndicatorInput`, `IndicatorOutput`, `IndicatorContext`, `IndicatorInputType`, `AddIndicatorOptions`, `IndicatorInstance` | The indicator contract. | ### Markers, Events, Drawings | Export | Description | |---|---| | `addSeriesMarkers(chart, series, markers)`, `SeriesMarkersPrimitive` | Trade-style marks. | | `SeriesMarker`, `MarkerShape`, `MarkerPosition` | Their types. | | `addEvents(chart, series, events, options?)`, `EventsPrimitive` | Lanes, badges, callouts, lines and ranges. | | `ChartEvent`, `EventStyle`, `EventsOptions` | Their types. | | `createDrawingTools(chart, options?)`, `DrawingsPrimitive` | Drawing tools on a pane. | | `Drawing`, `DrawingKind`, `DrawingPoint`, `DrawingStyle`, `DrawingChange`, `DrawingToolsOptions` | Their types. | | `DRAWING_STYLE_DEFAULTS`, `POINTS_REQUIRED` | Default style, and points needed per tool. | ### Order Flow | Export | Description | |---|---| | `addFootprint(chart, series, flow?, options?)`, `FootprintPrimitive` | Footprint cells and the fallback delta strip. | | `footprintFromTicks(ticks, res, tickSize, zone?)` | Build footprints from sided ticks. | | `mergeFootprint(bars, flow)` | Copy aggressor totals onto bars. | | `footprintTotals(bar)` | Buy, sell, total, delta and the bar point of control. | | `footprintIndex(times, bar)` | The bar index a footprint belongs to. | | `addVolumeProfile(chart, series, options?)`, `VolumeProfilePrimitive` | Volume and market profiles. | | `computeProfile(cols, from, to, options?, flow?)` | The pure function behind them. | | `FootprintBar`, `FootprintLevel`, `FootprintTotals`, `FootprintOptions` | Footprint types. | | `Profile`, `ProfileRow`, `ProfileKind`, `ProfileMode`, `ProfileColumns`, `VolumeProfileOptions` | Profile types. | ### Replay, Linking, Alerts | Export | Description | |---|---| | `createReplay(target, options?)`, `ReplayController` | Bar replay with higher-timeframe followers. | | `ReplayState`, `ReplayOptions`, `ReplayTarget` | Its types. | | `linkCharts(charts, options?)`, `LinkOptions` | Synchronize time range and crosshair across charts. | | `addAlerts(chart, series, options?)`, `AlertsPrimitive` | Draggable price alerts with crossing events. | | `Alert`, `AlertEvent`, `AlertsOptions` | Their types. | ## `@ortex-charts/lite` | Export | Description | |---|---| | `createSparkline(el, options?)`, `Sparkline` | The 3.3 KB table-cell chart. | | `SPARKLINE_DEFAULTS` | Default options. | | `SparklineOptions`, `SparklineKind`, `SparklineData` | Its types. | | `renderScheduler` | The animation frame shared by every sparkline on the page. | ## `@ortex-charts/ui` | Export | Description | |---|---| | `createChartShell(el, options?)` | Toolbar, drawing rail and chart in one call. | | `ChartShell`, `ChartShellOptions` | The handle and its options. | | `ChartLayout`, `LayoutIndicator`, `SeriesPlacement`, `ScaleMode` | The layout JSON a host stores. | | `OverlayDef`, `OverlayContext` | Host-defined data overlays. | | `overlayKey(id, symbol, current)`, `parseOverlayKey(key, current)` | The `id@SYMBOL` convention for compared symbols. | | `ToolbarItem`, `ToolbarAction` | The switches, and host buttons and menus. | | `RangePreset`, `DEFAULT_RANGES` | Period buttons: label, span in milliseconds, and an optional resolution. | | `SeriesColor` | A line color, or `{ up, down }` for candles and bars. | | `contrastingColor(used, palette)` | The palette hue furthest from everything already on the chart. | | `DEFAULT_RESOLUTIONS` | `["1", "5", "15", "60", "1D", "1W", "1M"]`. | | `resolutionLabel(res)` | `"60"` to `"1h"`, `"1D"` to `"D"`. | | `DrawingsStore`, `localStorageDrawingsStore(prefix?)` | Drawings that follow the symbol. | | `openDataPicker(options)`, `DataPickerOptions`, `PickerItem` | The "Add data to chart" modal. | | `openMenu(root, anchor, build, onClose?)`, `Menu`, `MenuItemSpec` | Keyboard-navigable dropdowns. | | `openDialog(root, options)`, `DialogOptions`, `FieldSpec`, `FieldValue` | Modal forms with a focus trap. | | `openSymbolSearch(options)`, `SymbolSearchOptions` | The debounced symbol search popover. | | `ICONS`, `icon(name)`, `IconName` | 52 inline SVG icons using `currentColor`. | | `UI_CSS`, `ensureStyles(doc)`, `applyThemeVars(el, theme)` | The chrome stylesheet and its theme variables. | | `h(doc, tag, attrs?)`, `button(spec)`, `ButtonSpec` | DOM helpers used by the toolbar. | | `downloadCanvas(canvas, name)`, `downloadText(text, name)` | Browser download helpers. | ## `@ortex-charts/viz` | Export | Description | |---|---| | `createTreemap(el, options?)`, `Treemap`, `TREEMAP_DEFAULTS` | Sized-and-colored rectangles with drill-down. | | `TreemapNode`, `TreemapLayoutNode`, `TreemapLayoutOptions`, `TreemapOptions`, `TreemapHit` | Its types. | | `layoutTreemap(...)`, `treemapLeaves(node)`, `findPath(root, node)` | The layout without the canvas. | | `createHeatmap(el, options?)`, `Heatmap`, `HEATMAP_DEFAULTS` | A row-by-column grid with a color scale. | | `HeatmapOptions`, `HeatmapScaleOptions`, `HeatmapHit` | Its types. | | `resolveHeatmapDomain(...)`, `createColorScale(...)` | The scale, for host-drawn legends and table cells. | | `createCategoryChart(el, options?)`, `CategoryChart`, `CATEGORY_CHART_DEFAULTS` | Bars and columns, stacked or grouped. | | `createXYChart(el, options?)`, `XYChart`, `XY_CHART_DEFAULTS` | Lines, areas, columns, scatter and bubbles over a numeric x axis. | | `XYChartOptions`, `XYSeries`, `XYSeriesKind`, `XYPoint`, `XYDatum`, `XYAxisOptions`, `XYReferenceLine`, `XYReferenceBand`, `XYHit` | Its types. | | `createPieChart(el, options?)`, `PieChart`, `PIE_CHART_DEFAULTS`, `PieChartOptions`, `PieSlice`, `PieHit`, `pieArcs(...)` | Pie and donut. | | `createSankeyChart(el, options?)`, `SankeyChart`, `SANKEY_CHART_DEFAULTS`, `SankeyChartOptions`, `SankeyNode`, `SankeyLink`, `SankeyHit`, `sankeyLayout(...)` | Flow between nodes, and its layout without the canvas. | | `CategoryChartOptions`, `CategorySeries`, `CategoryValueAxisOptions`, `CategoryAxisOptions`, `CategoryHit` | Its types. | | `sortedCategoryOrder(...)`, `categoryExtent(...)` | Ordering and extent helpers. | | `VizComponent`, `VizBaseOptions`, `ThemeInput` | The shared component base. | | `Tooltip`, `TooltipContent`, `TooltipRow` | The DOM tooltip the components use. | | `formatValue(value, format)`, `ValueFormat` | Viz number formatting. | | `niceTicks(...)`, `niceDomain(...)`, `thinLabels(...)`, `thinnedIndices(...)`, `fitText(...)`, `LabelThinning` | Axis and label helpers. | | `blend(a, b, t)` | Color interpolation. | | `canvasToPNG(canvas, options?)`, `downloadPNG(...)`, `downloadBlob(...)` | Image export. | | `rowsToCSV(rows, columns?, options?)`, `downloadCSV(...)`, `CSVColumn`, `CSVOptions` | CSV export. | | `composeCanvases(canvases, background?, options?)`, `ComposeOptions` | Stack canvases into one image. | | `renderScheduler` | The shared animation frame. | | `VIZ_VERSION` | The package version string. | ## `@ortex-charts/react` | Export | Description | |---|---| | `Chart`, `ChartProps` | The core chart in a div; children attach to it. | | `Pane`, `PaneProps` | An extra pane; provides its id to nested series. | | `Series`, `SeriesProps`, `SeriesOptionsFor` | A series on the enclosing chart and pane. | | `FinancialChart`, `FinancialChartProps`, `IndicatorSpec` | The financial chart with data, indicators, markers and a live source as props. | | `ChartShell`, `ChartShellProps` | The full shell, with controlled symbol, resolution, theme and layout. | | `Sparkline`, `SparklineProps` | A sparkline in an inline-block span. | | `useChart()`, `usePaneId()` | Context accessors for your own children. | | `ChartContext`, `PaneContext` | The contexts themselves. | | `useChartEvents(chart, props)`, `ChartEventProps` | Subscribe a chart to the four event props. | | `useLiveSource(factory, deps)` | A `LiveSource` that survives re-renders and is closed once. | The package also re-exports the types callers need alongside the components: `ChartHandle`, `ChartOptions`, `DeepPartial`, `SeriesModel`, `SeriesDataInput`, `SeriesOptionsBase`, `SeriesTypeMap`, `CrosshairEvent`, `VisibleRangeEvent`, `FinancialChartHandle`, `FinancialChartOptions`, `SeriesMarker`, `LiveSource`, `LiveItem`, `StreamOptions`, `AddIndicatorOptions`, `IndicatorInstance`, `SparklineHandle`, `SparklineOptions`, `SparklineData`, `ChartShellHandle`, `ChartShellOptions`, `ChartLayout`, `OverlayDef` and `Bar`. ## Registries You Can Extend Three registries decide what the library can draw, and all three are open. ```ts registerSeriesType(name, def); // core — a new series renderer registerIndicator(def); // financial — a new indicator chart.addPrimitive(primitive); // core — anything else drawn on a pane ``` Everything built in goes through these same three, so a series type, indicator or primitive you register is not a second-class citizen: it appears in the legend, the toolbar menus and saved layouts exactly as the built-ins do. See [Series types](https://ortexcharts.com/docs/series), [Indicators](https://ortexcharts.com/docs/indicators) and [Concepts](https://ortexcharts.com/docs/concepts). --- # Questions we are asked > Support, browsers, mobile, accessibility, data licensing and the awkward ones. Section: Commercial. Source: https://ortexcharts.com/docs/faq ## What This Is ### Is ORTEX Charts the Same Thing as ORTEX? No. ORTEX is a market-data and short-interest platform sold to investors at ortex.com, priced per user per month. ORTEX Charts is a JavaScript charting library sold to developers at ortexcharts.com, priced per product. The same company makes both. They are separate products with separate prices, separate licenses and separate customers: buying one does not include the other, and using ORTEX Charts does not require an ORTEX data subscription. ### Is It Built on TradingView, Lightweight Charts or Highcharts? No. ORTEX Charts is an independent rendering engine built from the ground up in TypeScript. It has no third-party runtime dependencies, and no line of it is copied, ported or adapted from any other library: no code, no icons, no styles. The algorithms it implements come from the published literature and are cited where they are used. It shares nothing with TradingView Lightweight Charts, TradingView Advanced Charts, Highcharts or ChartIQ, and is compared with all four on this site because those are the products a buyer is choosing between, not because it is built on any of them. ## Browsers and Platforms ### Which Browsers Are Supported? Current versions of Chrome, Edge, Safari and Firefox, on desktop and mobile. The requirements are Canvas 2D, `ResizeObserver`, Pointer Events, `Intl` and ECMAScript 2020 syntax, all of which have been available in every major browser since 2020. There is no Internet Explorer support and none is possible without a compilation step you would have to add yourself. All three engines are in the automated suite: Chromium (Chrome and Edge), WebKit (Safari on macOS and iOS) and Firefox, each against its own pixel baselines, on desktop and, for Chromium and WebKit, phone emulation. If you find a rendering difference in any of them, report it; it is a bug rather than a limitation. ### Does It Work on Mobile and With Touch? Yes, and touch handling is in the engine rather than in the chrome, so it works on a bare `createFinancialChart` as well as in the shell. Drag pans, pinch zooms, a long press raises the crosshair, and a fast flick has momentum. The shell adapts below 640 pixels: the toolbar drops its labels, the resolution strip scrolls horizontally, the drawing rail becomes a horizontal bar under the chart, and coarse pointers get 32-pixel targets. Full screen uses the Fullscreen API where it exists and a fixed-position layer where it does not, which is the case on iOS Safari. ### Is There a React Native or Native Mobile SDK? No, and there is not going to be one. The honest answer for a mobile application is the web build inside a WebView — Capacitor, React Native WebView or the platform equivalent — which is the same code, the same license key and the same behavior. ### Does It Work in Vue, Svelte or Angular? Yes. The engine has no framework dependency at all; it takes an element and returns an object. The only framework-specific package is `@ortex-charts/react`, and it exists because ORTEX needed it, not because the core requires anything. A binding in any framework is the same three steps: create the chart in a mount effect, call `applyOptions` or `setData` when props change, and call `remove` on unmount. Reading [the React source](https://ortexcharts.com/docs/react) is a reasonable template. ## Rendering and Size ### How Big Is It? 89.9 KB gzipped for the full chart with the toolbar, drawings, indicators and order flow; 59 KB for candles and volume, 32.5 KB for a line chart, and 3.3 KB for the sparkline build. All in one file each, with no chunk loading at runtime. See [Performance](https://ortexcharts.com/docs/performance) for how those are measured and how they compare. ### Is It Canvas or WebGL? Canvas 2D. That is a deliberate choice and it has a real ceiling. Canvas 2D with typed-array columns, visible-range-only work and decimation holds 60 Hz to a few hundred thousand visible points, which covers every normal financial size: a decade of daily bars is 2,500 rows, and a decade of minute bars is about a million rows of which only the visible window is drawn. What it does not do is millions of points **all on screen at once** without decimation. If that is your product, SciChart's WebGL renderer is the right tool today. A WebGL path behind the same API is on the roadmap and is not implemented. ### Why Is My Chart Blank? Almost always one of three things: the container has no height, the timestamps are in seconds rather than milliseconds, or the chart was created during a server-side render. See the common problems in [Quickstart](https://ortexcharts.com/docs/quickstart). ## Data and Privacy ### Is Any Data Sent Anywhere? No. There is no analytics call, no usage beacon, no license check over the network and no hidden call-home in the library. The license key is verified locally, by the library's own Ed25519 implementation, against a public key embedded in the bundle. Your bars, your symbols, your users and your layouts never leave the browser through anything the library does. Two things are disclosed rather than hidden, and both are in the contract: - **The hosted kit's CDN logs.** If you load the library from `cdn.ortexcharts.com`, that CDN sees the requests, which means which domain loaded which kit and when. It is a standard web server log with no user data in it. Registry customers who bundle the packages themselves do not touch ORTEX infrastructure at all. - **An optional license check-in.** The agreement describes a documented check-in carrying `{ keyId, hostname, version }` once per session, which enterprise customers may switch off. It is disclosed because a hidden one would be blocked by ad blockers and content security policies, would be a privacy liability, and would be the first thing a copier deleted. Nothing about it is covert. There is no third position. If a privacy review asks "does this library phone home", the answer is no, and the two items above are the complete disclosure. ### Do I Need a Data Subscription From ORTEX? No. The library consumes data; it does not supply it. There is no bundled feed and no requirement to buy one. The [ORTEX adapter preset](https://ortexcharts.com/docs/data) exists because ORTEX is a customer of its own library, not because you have to be. ### Can It Fetch Data Itself? Only through what you give it. A [datafeed](https://ortexcharts.com/docs/data) is your code. An [adapter spec](https://ortexcharts.com/docs/data) tells the library which URLs to call and how to read the responses, using the browser `fetch` and `WebSocket` you would have used yourself. Nothing is requested that your spec did not name. ### Where Are Layouts and Drawings Stored? Wherever you put them. `getLayout()` returns JSON, `getDrawings()` returns an array, and `list()` on the alerts primitive returns a list. There is no ORTEX storage service and no save-and-load server contract. See [The shell and layouts](https://ortexcharts.com/docs/shell). ## Licensing ### What Happens When a License Expires? The gate closes: the chart paints a licence notice naming the reason instead of its content. Nothing is written to the console. Keys carry a 14-day grace period beyond the subscription period end so a late renewal never closes it, and a renewal re-signs onto the same key id and the same kit URL, so nothing in your deployment changes from year to year. Renew before the grace period ends and nothing is ever seen. ### Does the Chart Ever Stop Working? Yes, on a deployment host without a valid key. Since 1.1.0 there is one state in which the library draws its content: a key that is `valid`. In every other state, no key, invalid key, expired key, wrong domain or revoked key, it paints a licence notice on its own background and nothing else. On `localhost` and its aliases the gate never closes, so development, tests and continuous integration are unaffected. See [license keys](https://ortexcharts.com/docs/licensing). ### Is the License Key a Secret? No. It ships to the browser, it is bound to your domains, and anyone can read it out of your bundle. Treat it like a publishable API key. What **is** secret is the npm registry token in your `.npmrc`, which grants package downloads and belongs in your continuous-integration secrets. ### Do I Need a License to Evaluate It? Not on your own machine. On `localhost` the library draws without a key, with the ORTEX mark on, so local development, unit tests and continuous integration need nothing. The [playground](https://ortexcharts.com/playground) and every example on this site run the real library too. On any other host a chart with no valid key paints a licence notice instead of its content, so the first deployment is where a key is needed; every purchase carries a sixty-day money-back guarantee, which is the trial. There is no free plan. ### Can I Remove the ORTEX Mark? Only with a license that grants the `whitelabel` feature, which is every paid plan: Pro, Business and OEM. Setting `branding.visible = false` without it is ignored and logs one line. Replacing the mark with your own needs the `brand` feature, which is an OEM agreement. See [The ORTEX mark](https://ortexcharts.com/docs/branding) and [/pricing](https://ortexcharts.com/pricing). ### Is It Open Source? No. It is a commercial library. Source access exists under OEM and enterprise agreements; see [Installation and delivery](https://ortexcharts.com/docs/install). It has no third-party runtime dependencies and contains no third-party code: every package installs with an empty dependency tree, and the source drop is entirely ORTEX's own. ### Can I Redistribute It Inside My Own Product? Embedding it in an application you sell is what the Pro and Business plans are for. Redistributing the library itself — shipping it as a component your customers then build with — is an OEM matter, because it changes who the licensee is. Ask. ## Features and Limitations ### How Many Indicators Are There? 51 built in, plus 78 more in `@ortex-charts/indicators-extra`, a package you only pay for when you import it: 129 in all, more than TradingView Advanced Charts. roughly 110, and you choose which of them your users see. The built-in 51 alone is comparable to Highcharts Stock, which ships about 50, and short of TradingView Advanced Charts, which ships about 110 — the long tail there is mostly variations on what is here. Registering your own is about 20 lines and it then behaves exactly like a built-in one. See [Indicators](https://ortexcharts.com/docs/indicators). ### Is There Pine Script or Another Indicator Language? No, and there is no plan for one. A scripting language is a decade of work and a permanent support burden. Indicators here are TypeScript, which is strictly more capable — and strictly less safe for end-user authoring, which is the trade-off. If letting your users write their own indicators is a product requirement, this library does not solve it. ### How Many Drawing Tools Are There? 32, as of version 0.2.0: trend lines and rays, arrows, a polyline and a freehand brush, rectangles, ellipses and triangles, parallel and regression channels, six Fibonacci tools, a Gann fan, a pitchfork, measure and range tools, long and short position tools with a reward-to-risk readout, and four annotation tools. Every one of them has magnet snapping, handle editing, undo, redo and JSON serialization. The shell's tool rail shows nine of them until you ask for more, because the full set crowds a rail, and `drawingTools` names the ones you want. See [Drawing tools](https://ortexcharts.com/docs/drawings). ### Can I Show Several Charts in a Grid? Yes, but the grid is your CSS. `linkCharts` synchronizes the visible time range and the crosshair across any number of charts, across resolutions, and a bar replay can drive higher-timeframe followers. There is no built-in two-by-two layout container. See [Replay, linking and alerts](https://ortexcharts.com/docs/replay). ### Is There a Navigator Strip or Range Buttons? No. Range presets are a few lines on `setVisibleTimeRange` and fit naturally as [toolbar actions](https://ortexcharts.com/docs/toolbar); there is an example on [Time, sessions and resolutions](https://ortexcharts.com/docs/time). A navigator mini-chart is not built in. ### Can the Chart Be Rendered on a Server? No. The library is browser-only: it creates canvases, reads `devicePixelRatio` and observes element sizes. There is no headless rendering mode. Chart images for emails and social cards are better solved by a separate rendering service. In React this means creating the chart inside an effect, which the components already do; the file still needs `"use client"` in Next.js. See [Installation and delivery](https://ortexcharts.com/docs/install). ### Is It Accessible? Partially, and the gaps are worth knowing before you commit. Implemented: the chart is focusable and responds to arrow keys, `+`, `-` and Home; toolbar buttons carry `aria-pressed`; menus are `role="menu"` with arrow-key navigation, `aria-checked` on toggles and focus return; dialogs are `role="dialog"` with `aria-modal` and a focus trap; icon-only buttons have accessible names; reduced motion is respected. Not implemented: there is no screen-reader description of the chart data, no focusable data table as an alternative representation, and no high-contrast theme shipped. If conformance is a procurement requirement, weigh those; Highcharts Stock ships an accessibility module and this library does not. The CSV export plus a table of your own is the honest interim answer. ### Is the Interface Available in Other Languages? Dates and numbers localize through `Intl` and follow the chart's `locale` option. The interface strings — toolbar labels, menu entries, dialog titles — are English only, and there is no string table to supply. A host that needs another language today switches the toolbar off and drives the chart from its own controls, which are all public methods. ### Does It Do Order Entry, Positions or Depth of Market? No. Price lines and [draggable alerts](https://ortexcharts.com/docs/replay) are as close as it gets. Order and position lines with drag handles are a small primitive on a documented interface and would be built if a customer needed them; a broker integration is deliberately out of scope. ## Support and Process ### How Does Support Work? By email, at [charts@ortex.com](mailto:charts@ortex.com). Pro includes email support; Business includes priority support; OEM agreements name an engineer and carry a service-level agreement. Commercial questions go to [sales@ortex.com](mailto:sales@ortex.com). When reporting a rendering problem, `window.__ORTEX_CHARTS_KIT__` on a hosted kit carries the kit id, key id, plan and library version, which is the fastest thing to quote. ### How Often Is It Released? Within a major version, hosted kits pick up new releases automatically the next time the file is fetched; registry customers upgrade on their own schedule. A subscription buys the versions released while it runs, and the right to use them ends with it: the key stops verifying on its expiry date and the ORTEX mark returns with a warning naming the reason. ### Can I Get the Source? Under an OEM or enterprise agreement, yes: read access to a repository mirror with the TypeScript source, the tests and the playground. Outside that, published packages are minified with no source maps. ### Something Is Missing That I Need. What Now? Ask. The extension points — series types, indicators, primitives — are the same ones the built-ins use, so a lot of what looks missing is a day of work rather than an architectural change. Where the answer is genuinely no — Pine Script, native mobile, a broker integration — this documentation says so rather than implying a date. --- # Release notes > Every release, newest first, with the one upgrade note there has been so far. Section: Commercial. Source: https://ortexcharts.com/docs/changelog ## How Versions Work Every release of ORTEX Charts is listed below, newest first. Versions are published together: all ten packages share one number, so `@ortex-charts/ui@1.0.24` always works with `@ortex-charts/core@1.0.24` and you never have to reason about a matrix. The version comes from a signed tag in the library repository, which is also what triggers the publish, so the registry and the history cannot disagree. Anything that would change the behavior of code you have already written is called out under **Upgrading**. There have been six such changes so far, in 0.3.2, 1.0.16, 1.0.22, 1.0.26, 1.1.0 and 1.2.0. ## 1.3.0 — 10 September 2026 **The translators finish the chart.** A real port of a Highcharts Stock page and a TradingView Charting Library widget through `@ortex-charts/migrate` found what they left behind, and the new pages [moving from Highcharts](https://ortexcharts.com/docs/from-highcharts) and [moving from TradingView](https://ortexcharts.com/docs/from-tradingview) walk both ports end to end. `fromHighcharts` now turns y-axes placed with `top` and `height` into panes, the column on the second axis into the volume, `sma`, `ema`, `wma`, `rsi`, `atr`, `bb`, `macd` and `stochastic` series into indicators with their periods, and `flags` into markers; a plot line is drawn once per axis rather than once per series, and a series with no counterpart is reported without an empty series being left behind. `tradingViewWidget` returns the shell with `ignored`: every widget key, feature flag and override it did not read. It maps `locale`, `header_compare`, `hide_left_toolbar_by_default` and the candle colour and background overrides, and the wrapped datafeed answers `supportedResolutions()`, which `tradingViewWidgetAsync` passes to the toolbar so a daily-only feed does not offer minute buttons. The input types accept TradingView's `ChartingLibraryWidgetOptions` and `IBasicDataFeed` and a typed `Highcharts.Options` without a cast. `drawings.add` takes a partial `style`, as the [drawing tools](https://ortexcharts.com/docs/drawings) page always said. **Upgrading.** `translateHighcharts` no longer emits a series for a type it reports as unsupported, so a port that counted on those placeholder series will find fewer entries in `series`; the same information is in `indicators`, `markers` and `unsupported`. ## 1.2.0 — 10 September 2026 **The licence check is the library's own.** The Ed25519 signature on a key is now verified by code inside `@ortex-charts/core`, written from RFC 8032 and FIPS 180-4, rather than by the browser's WebCrypto. Nothing a page can replace, remove or stall takes part in the check, it runs on every platform, and it is synchronous: a key is `valid` or it is not before `setLicenseKey` returns, and the `pending` state no longer occurs. There is no longer any browser on which a payload is accepted unverified. **The gate decides from the payload.** On every frame the gate re-checks expiry against the clock and the domains against the hostname of the moment, and requires the signature to have verified. A key that expires while a page is open closes the gate at that second. The list of trusted signing keys is frozen, verification reads a private copy of it, and the series renderer asks a second, independent check before it draws. **Upgrading.** `setLicenseKey` no longer accepts `publicKey`, `hostname` or `now`. They were test conveniences, and the first of them let a page trust a signing key of its own. A test that used them installs a real key instead and reads `licenseStatus()` back; a test that needs an unlicensed chart runs on localhost, where the gate never closes. Nothing else changes for a chart with a valid key. ## 1.1.0 — 10 September 2026 **The licence is a gate.** On any host other than `localhost` and its aliases, a chart with no valid or pending key paints a notice on its own background, "A licence key is required to display this chart", with the reason the check gave and the address of the pricing page, and nothing of its content: no series, axes, legends, crosshair or tooltips. The moment a key verifies, every chart on the page repaints itself in full. On a development host an unlicensed chart draws as before, with the ORTEX mark on and one console warning, so evaluation, unit tests and continuous integration need no key. `licenseGate()` answers `{ blocked, reason }` for the current state, and `isDevelopmentHost()` is the rule it uses. Treemaps, heatmaps and the other `@ortex-charts/viz` components paint the same notice; sparklines in `@ortex-charts/lite` are not gated. See [license keys](https://ortexcharts.com/docs/licensing). **Upgrading.** Before 1.1.0 the chart drew in every licence state and the mark was the only consequence. If a deployment relied on that, on a host its key does not cover, a preview host for instance, it now shows the notice; add the host to the key's domains or accept the notice on previews. A key that has expired past its 14-day grace period now stops the chart rather than restoring the mark. Nothing changes for a chart with a valid key. **The free Community plan is withdrawn.** No new Community keys are issued. Keys already issued keep verifying until they expire, under the terms they were issued with. ## 1.0.30 — 10 September 2026 **No report until a stored layout is fully applied.** Applying a stored layout whose toolbar extras were folded reported the layout to the host part-way through, before the stored overlays had been switched on, so that first report had no overlays in it. A host that stores what `onLayoutChange` hands it and passes it back could then apply that empty layout, and the chart came up without its lines. The shell now reports once, when the layout is applied, and `` ignores every layout it has itself reported, not only the newest. No API change. ## 1.0.29 — 10 September 2026 **A removed shell stays silent.** A host that keys `` on the symbol tears a shell down on every change of instrument, often while the overlays of its first layout are still loading. Until now that shell carried on: the loads finished on a chart that no longer existed, and the report that closed them reached `onLayoutChange` with an empty overlay list, because the shell had already let its overlays go. A host that stores what it is told then handed that layout to the shell that replaced it, and the next chart arrived without its lines. After `remove()`, a shell now reports nothing, applies nothing, and an overlay that finishes loading late is disposed rather than attached; `` stops forwarding callbacks once it is unmounted. No API change. ## 1.0.28 — 10 September 2026 **A stored layout is no longer applied back into the chart.** Keeping a chart's arrangement means storing what `onLayoutChange` reports and handing it back as the layout on the next visit, which is what [the shell guide](https://ortexcharts.com/docs/shell) recommends. In React, a host that handed back the layout it had just been given made the chart apply it, which made the chart report it, which is a loop: overlays were removed and re-added several times a second, and every overlay that fetches fetched again each time. `` now ignores a layout it reported itself; the chart is already in it. **An overlay is on from the moment you switch it on.** `getLayout()` counted an overlay as on only once its `add` had resolved, so a layout read while the chart was still loading came back without it: a chart saved during loading lost its lines, and applying such a layout switched them off. The data menu's check marks follow the same rule. ## 1.0.27 — 10 September 2026 **A legend menu stays anchored.** The button that opens a series' legend menu was replaced whenever the legend was rebuilt, so a host popup anchored to it was left pointing at an element no longer in the document, and drifted or vanished on the next update. The same button now survives a rebuild. ## 1.0.26 — 9 September 2026 **The mark is a ladder.** A key with `whitelabel`, which every paid plan now carries, may hide the ORTEX mark. A key with the new `brand` feature, which OEM agreements carry, may replace it with your own logo, text, caption and link. Between 0.6.1 and 1.0.25 `whitelabel` did both; a Pro or Business key that sets a custom logo now draws no mark rather than yours. See [the ORTEX mark](https://ortexcharts.com/docs/branding). **Upgrading.** If you hold a White-label key from before 9 September 2026, nothing changes: it grants `*`, which includes `brand`. The plans changed the same day, to one price per product with any number of developers; see [pricing](https://ortexcharts.com/pricing). ## 1.0.25 — 9 September 2026 **What a full read of the engine turned up.** A keyboard event reached every drawing with the hovered pane's scale rather than its own, which mattered to a drawing on a second pane. A sparkline kept the backing store it was born with when the window moved to a screen with another device pixel ratio, and drew clipped until something resized it. Both fixed. **Faster on every tick.** The timeline was copied in full on every live bar, undoing the amortised append underneath it; it is now kept by reference. `withAlpha` no longer runs a regex per drawing per frame, the legend no longer rewrites its container styles on frames that change nothing, and bar replay no longer builds a date formatter per step. ## 1.0.24 — 8 September 2026 **Asking for a control is not the same as having room for it.** Unfolding the view and export controls on a chart too narrow to hold them drew the buttons over each other. A reader's choice now outranks the width: the bar still drops labels, folds the periods and moves resolutions into the chevron, but it will not fold the tail away again behind them. When every concession is spent it takes a second row, which is worse than one row and much better than overlapping, and the fold button stays visible there as the way back. ## 1.0.23 — 8 September 2026 **The toolbar keeps to one row.** Rather than wrapping, it gives things up in order of how little they are missed: the words on buttons that read as icons, then the periods into their own button, then the view and export controls behind More, then the middle resolutions into a chevron that keeps the shortest, the longest and the selected one. Each step applies only if the one before it was not enough, and a chart that grows takes it all back. `toolbarFit: "wrap"` keeps the old behaviour. See [one row, not two](https://ortexcharts.com/docs/toolbar#one-row-not-two). ## 1.0.22 — 8 September 2026 **A toolbar one row deep.** `extrasCollapsed` folds the scale modes, fit, the legend and drawing-rail toggles, realtime, replay, download, screenshot, theme and full screen behind a single More button, so a toolbar that used to wrap onto a second row gives that height back to the chart. Opening it shows the same buttons as a palette, and an item puts them back for good. See [one row, not two](https://ortexcharts.com/docs/toolbar#one-row-not-two). **Upgrading.** If your host stores chart layouts, note that `getLayout()` now records `drawingRailCollapsed` and `extrasCollapsed` whether they are true or false. Absent has to keep meaning "this reader never said": stored only when true, a reader who opened the rail looked exactly like one who had never touched it, and a host turning either option on would have had it overridden for everybody with a saved layout. Existing layouts are unaffected and take the host's default until the reader changes it. ## 1.0.21 — 7 September 2026 **The readout is a box.** It carries the hovered bar's date, formatted as the time axis labels it, then a row per series with that series' colour beside it. A newline in the [template](https://ortexcharts.com/docs/tooltips#two-lines-and-a-template-per-series) starts a quieter line underneath, which is where a change belongs, and a long line now wraps inside the box rather than out of it. **`avg(field, n)` in a template.** The mean of a window of bars, so a chart can say "today against the week behind it". A window that runs off the start of the data prints an em dash rather than an average of whatever is there. A series can also carry its own `tooltipTemplate`, and the volume bar uses one by default. **Pie labels go where they fit.** Inside the slice when the text fits there, in a colour chosen against the fill; otherwise outside on a leader line, wrapped, stacked down each side and limited to what the height can hold. Slices take a second hairline just darker than their fill, which is the edge a pale slice on a white card did not have. See [where the labels go](https://ortexcharts.com/docs/viz#where-the-labels-go). **A treemap that is not grey mud.** The automatic colour range now reaches the ninetieth percentile of the moves rather than the largest of them, so one stock down forty percent no longer leaves every ordinary move a shade of neutral. `headerDepth` stops the bands of small text above deeply nested groups, and a leaf can carry a `logo`. ## 1.0.17 to 1.0.20 — 7 September 2026 **A value beside the cursor.** A chart can put a readout next to the pointer for the line the pointer is on, and what it says is a [template you write](https://ortexcharts.com/docs/tooltips): the series name, its value, the same value some bars back, and a comparison between two of them. Three modes decide how much shows — nothing, the hovered line, or every line on the pane. **Periods above the chart.** The toolbar carries `1D 1W 1M 1Q 1Y 5Y 10Y` by default, anchored to the last bar rather than to the clock, each one able to change the resolution with the span. On a narrow chart they fold into a single button rather than wrapping, and `rangeDisplay` decides that explicitly when you would rather it did not depend on the width. See [the toolbar](https://ortexcharts.com/docs/toolbar#period-buttons). **The drawing rail can start out of the way.** `drawingRailCollapsed` folds the tools to a thumb on the edge, which is what a chart in a dense page usually wants; the reader opens it when they need it, and the layout remembers. **A toolbar button reflects what it does.** `shell.setAction(id, patch)` updates a button after the toolbar is built, so a host toggle can light up. Before this, a button's `active` flag was read once and a React host that rebuilt its options changed nothing on screen. **Reloading keeps your place.** `binding.reload()` no longer re-resolves the symbol or jumps to the latest bar: it restores the view by bar index, or by time when the bar count changed. Switching a data option, such as adjusted prices, no longer throws the reader back to the right edge. **A scale change redraws immediately.** Switching to logarithmic or percent used to wait for the next pan or zoom before the chart showed it. **The mark links to this site.** Clicking "Charts provided by ORTEX" opens ortexcharts.com, which answers the question a reader is asking by clicking it. A white-label license still sets its own link. ## 1.0.11 to 1.0.16 — 6 September 2026 **A chart cannot hold its page open.** The chart root is capped at the width of its host and the shell contains its own inline size, so a toolbar's natural width can no longer widen the grid column it sits in and push a page sideways. The chart also checks its container on every frame, and re-measures when the tab becomes visible again, which is what makes a window resize or a returning background tab redraw at the right size. **Loading history in windows stops asking for what is not there.** A feed has nothing for today until it has something, and the loader used to ask again on every frame. An empty answer at an edge is now remembered: `minGap` ignores a gap too narrow to be worth a request, and `retryEmptyAfter` leaves that edge alone for five minutes. **Reading a chart over its own shading.** `withAlpha` scales a color's existing transparency instead of replacing it, an area series takes `lineWidth: 0` for shading with no outline, and labels along the top of an [XY chart](https://ortexcharts.com/docs/viz#xy-chart) stack onto free lines rather than printing over each other. Event lanes take a faint tint rather than a filled band, and `watermark.logoScale` sets the mark's height as a fraction of the pane. **Upgrading.** If you passed a color that already carried an alpha *and* asked for a fill opacity of 1 to get it back at full strength, that fill now stays translucent. Pass the opaque color and let `fillOpacity` do the fading, which is what the option was for. ## 1.0.0 to 1.0.9 — 5 September 2026 **Chunked history for series you fill yourself.** [`attachWindowedData`](https://ortexcharts.com/docs/data#loading-history-in-windows) gives any series the visible span plus a margin and fetches more as the reader scrolls, with `maxSpan`, `earliest`, `latest` and a debounce. In the shell it is `ctx.windowed(series, fetch)`, with defaults set once in `overlayLoading`. **A legend the reader controls.** `legend.collapsed` and `legend.collapsible` show the first row only and offer a toggle, with `setLegendCollapsed`, `isLegendCollapsed` and `onLegendCollapse` behind them, a `"legend"` toolbar item, and `legendCollapsed` in the layout. `legend.symbol` prints the exchange and ticker before the first series title, beside the logo. **Colors chosen from the chart.** Every legend menu carries swatches; a candlestick series gets an up and a down row. The choice is keyed by series title, travels in the layout as `colors`, and a second series of the same title takes a contrasting hue, which `contrastingColor` also exports for hosts that want the same rule elsewhere. **Your mark behind the chart.** `watermark.logo` draws the ORTEX wordmark or your own image, sized with `logoHeight` or `logoScale` and faded with `opacity`. **[`@ortex-charts/migrate`](https://ortexcharts.com/docs/migration#the-translators-do-the-mechanical-half).** A new package that wraps a TradingView datafeed or widget, and translates a Highcharts or Highcharts Stock options object, returning a working chart and a list of what did not carry over. **More in `viz`.** An [XY chart](https://ortexcharts.com/docs/viz#xy-chart) over a numeric axis with reference lines and shaded bands, a [pie or donut](https://ortexcharts.com/docs/viz#pie-and-donut), and a [Sankey diagram](https://ortexcharts.com/docs/viz#sankey), all with React bindings. **Transparent backgrounds.** `Theme.surface` names the opaque color under a chart whose `background` is transparent, so blends, glows and screenshots have something to composite against. `surfaceOf(theme)` returns it. ## 0.7.0 — 5 September 2026 **129 indicators, and a menu you curate.** The extras package grows to 78 studies, which with the built-in 51 passes the roughly 110 in TradingView Advanced Charts: further adaptive averages, three pivot systems, VWAP bands and anchored VWAP, regression statistics, the Bill Williams family, squeeze momentum, Laguerre RSI, and volatility estimators among them. `registerExtraIndicators({ only, except })` registers a subset, and the shell's `indicators` option takes a curated menu: `include`, `exclude`, `featured`, headed `groups` and `labels`, read from the registry when the menu opens. See [Indicators](https://ortexcharts.com/docs/indicators). ## 0.6.1 — 5 September 2026 **The mark is ORTEX's without a white-label key**, whatever the branding options say: `logo`, `text`, `caption` and `href` fall back to their defaults; `position`, `height` and `opacity` stay yours. See [The ORTEX mark](https://ortexcharts.com/docs/branding). ## 0.6.0 — 5 September 2026 **`@ortex-charts/indicators-extra`.** 38 more studies in a package of their own, so a chart only carries what its users open: 13 overlays and 25 in their own pane, 5.7 KB gzip when imported and nothing otherwise. One `registerExtraIndicators()` call and each appears in the menu, the legend and the saved layout like a built-in. See [Indicators](https://ortexcharts.com/docs/indicators). **Licence 1.2.** Use of the library ends with the term on every plan; the perpetual fallback is withdrawn. Every plan except OEM covers one domain, plus localhost. **0.5.2** carried the licence 1.1 text and README corrections only. ## 0.5.1 — 5 September 2026 **No third-party code of any kind.** 0.5.0 removed the last dependency but three files were still ports of D3 code under the ISC license. They are now independent implementations written from the published algorithms — Heckbert's nice numbers for axis ticks, Steffen's monotone interpolation and the uniform cubic B-spline for the curves, and Bruls, Huizing and van Wijk's squarified treemap — held to exactly the output the ports produced. Nothing in any package is copied, ported or adapted from another library. They are also faster. Filling an area through 100,000 points takes a quarter to a third less time across all four curves, the monotone line a fifth less, and the treemap layout no longer allocates per row. ## 0.5.0 — 5 September 2026 **No third-party runtime dependencies.** Every package now installs with an empty dependency tree. The D3 modules the library was built on were replaced by local ones: the tick algorithm and binary search that came from `d3-array`, the four curve interpolators from `d3-shape`, the UTC intervals from `d3-time`, the squarified treemap from `d3-hierarchy` and the color ramp from `d3-scale`. Each replacement was checked against the module it replaced while both were installed, and D3's own output is kept in the repository as a golden fixture, so the parity is asserted on every test run. The browser snapshot suite moved zero pixels. | Build | 0.4.0 | 0.5.0 | |---|---|---| | Line chart | 31.3 KB | **29.5 KB** | | Basic, the free build | 31.8 KB | **30.0 KB** | | Candles and volume | 58.2 KB | **55.8 KB** | | Full shell | 85.7 KB | **83.2 KB** | | Treemap and heatmap | 18.5 KB | **10.0 KB** | Drawing got faster as well. The D3 line and area generators wanted an array to iterate and an accessor function per column, so every redraw of every line built an index array and made two calls per point; the local curves read the typed arrays directly. Tracing 100,000 points takes 0.83 ms rather than 1.35 ms for a line, and 1.94 ms rather than 2.80 ms for an area. ## 0.4.0 — 5 September 2026 **Extended-hours shading and day breaks.** An intraday chart can now shade the columns outside regular trading hours and draw a line where each trading day begins, both off by default and both taking the exchange's day rather than the reader's. See [Time, sessions and resolutions](https://ortexcharts.com/docs/time). Number and date formatting moved onto the platform's own `Intl`, which removed another dependency and made locale-aware formatting the default rather than an option. ## 0.3.2 — 4 September 2026 **The price transforms register on demand.** Renko, Kagi, Point and Figure and Line Break used to register themselves when `@ortex-charts/core` was imported, which meant every build carried all four renderers whether or not anything drew them. They now register when `@ortex-charts/financial` is imported, which takes about 4 KB gzip off any build that does not use them, and keeps four paid renderers out of the free build. **Upgrading.** If you import only `@ortex-charts/core` and call `addSeries("renko")`, call `registerPriceTransforms()` first: ```ts import { registerPriceTransforms } from "@ortex-charts/core"; registerPriceTransforms(); ``` Nothing else changes. `@ortex-charts/financial`, `@ortex-charts/ui` and `@ortex-charts/react` do it for you, which covers almost every application. ## 0.3.1 — 4 September 2026 Publishes `@ortex-charts/basic`, which 0.3.0 built and did not send to the registry. ## 0.3.0 — 4 September 2026 **`@ortex-charts/basic`, the free build.** A candlestick chart with a volume pane, a legend and a crosshair, with no license key and a larger ORTEX mark. See [the ORTEX mark](https://ortexcharts.com/docs/branding). **Color-blind safe themes.** A dark and a light theme built on the Okabe-Ito palette, where up and down are told apart by hue and luminance rather than by red against green, plus a toolbar switch that turns them on. See [Colors, fonts and formatting](https://ortexcharts.com/docs/customization). **License key revocation and signing-key rotation.** Keys carry the identifier of the key that signed them, the runtime holds a revocation list, and a signing key can be retired without invalidating every key ever issued. See [License keys](https://ortexcharts.com/docs/licensing). ## 0.2.0 — 4 September 2026 **51 built-in indicators and 32 drawing tools**, up from 22 and nine, and the four price transforms: Renko, Kagi, Point and Figure and Line Break. See [Indicators](https://ortexcharts.com/docs/indicators) and [Drawing tools](https://ortexcharts.com/docs/drawings). ## 0.1.0 The founding release: the engine, the financial chart, the shell, the sparkline build, the general-purpose charts and the React components.