# FerroChart — complete guide
Version: 0.7.0. License: Apache-2.0.
Index: https://ferrochart.com/llms.txt
---
Source: https://ferrochart.com/docs
# Introduction
FerroChart is an open-source financial charting engine written in Rust. One
core drives every platform: the browser through WebAssembly (WebGPU or
WebGL2), native applications through wgpu (Metal, Vulkan, DirectX 12), Python
and C, and headless rendering on servers.
What it is built for:
- **Large data.** Ten million bars load in tens of milliseconds and pan as smoothly
as two hundred: the per-frame work depends on the screen, not on the data size.
- **Real-time updates.** Updating the last bar costs well under a microsecond in
the core and redraws only what changed.
- **One look everywhere.** All backends draw from the same frame description and
are checked against the same golden images.
## Architecture in one picture
```text
your app ──► Chart (ferrochart-core) ──► Frame ──► renderer ──► pixels
data, scales, layout, plain wgpu (GPU) / tiny-skia (CPU)
interaction, LOD draw list
```
- `ferrochart-core` holds the data and all chart logic: scales, ticks, layout,
input handling. It has no GPU, window, font or async dependencies and runs
anywhere, including `wasm32-unknown-unknown`.
- Each frame it produces a `Frame`: a flat list of draw commands. Series data
is not copied into it; renderers read the columns directly and upload only
what changed.
- Renderers turn frames into pixels. `ferrochart-render-wgpu` is the primary
one; `ferrochart-render-cpu` draws the same frames on the CPU.
- Bindings wrap it all for a platform: `ferrochart-wasm` (npm),
`ferrochart-winit` (desktop), `ferrochart-py` (PyPI) and `ferrochart-ffi`
(the C library).
## Where to start
| You use | Read |
|---|---|
| JavaScript or TypeScript in a web page | [Web](https://ferrochart.com/docs/web) |
| React, Vue or another framework | [React and Vue](https://ferrochart.com/docs/frameworks) |
| Rust on the desktop | [Desktop](https://ferrochart.com/docs/desktop) |
| Python, Jupyter or pandas | [Python](https://ferrochart.com/docs/python) |
| C, C++, C# or another native language | [C, C++ and C#](https://ferrochart.com/docs/native) |
| Images on a server | [Offscreen](https://ferrochart.com/docs/offscreen) |
---
Source: https://ferrochart.com/docs/web
# Web (JavaScript / TypeScript)
The npm package `@ferrochart/core` contains the WebAssembly build and TypeScript
types. It renders with WebGPU where available and falls back to WebGL2.
```bash
npm install @ferrochart/core
```
## A chart in a page
```html
```
The canvas is sized by CSS. FerroChart watches its size and the device pixel
ratio and keeps the backing store sharp; you never set `canvas.width` yourself.
Typed arrays are copied into the engine with one `memcpy` per column, so
`setData` with a million bars takes a few tens of milliseconds.
## Real-time updates
```js
// Same time as the last bar: replaces it. Later time: appends a new bar.
candles.update({ time: Date.now(), open: 101.2, high: 101.9, low: 100.8, close: 101.5, volume: 1234 });
```
Calling `update` a hundred times per second is fine: each call is cheap, and
the chart redraws at most once per animation frame.
## Events
```js
chart.on('crosshairMove', ({ point }) => {
if (point?.bar) console.log(point.time, point.bar.close);
});
chart.on('visibleRangeChanged', ({ from, to }) => { /* logical indices */ });
chart.on('needMoreHistory', ({ barsBeforeStart }) => { /* load older bars */ });
```
Events are delivered after the frame that produced them.
## Touch screens
On phones and tablets the chart pans with one finger, zooms with two and shows
the crosshair after a 500 ms long press (the full list is in
[Gestures and keyboard](https://ferrochart.com/docs/interaction#touch)). The `touchScroll` option says
who gets a vertical swipe:
```js
const chart = await FerroChart.create(canvas, { touchScroll: 'page' });
chart.setTouchScroll('chart'); // change it later
```
| `touchScroll` | Canvas `touch-action` | Vertical swipe | Use it for |
|---|---|---|---|
| `'chart'` (default) | `none` | Pans the chart | Full-screen charts, app-like pages |
| `'page'` | `pan-y` | Scrolls the page | Charts inside articles, docs and scrolling panels |
With `'page'`, horizontal swipes, two fingers and the long press still go to
the chart, and once the long-press crosshair is showing, moving the finger up
or down moves the crosshair, not the page. The cost: with the price axis'
auto-scale off, one finger cannot pan prices; use two fingers.
`FerroPlot` takes the same option.
## Cleaning up
```js
chart.destroy(); // removes listeners and releases GPU resources
```
## Browser support
WebGPU or WebGL2 is required; there is no Canvas2D fallback. Tested in Chrome,
Firefox and WebKit (Safari's engine) with both renderers. See
`examples/web` for a complete demo and the [JavaScript API](https://ferrochart.com/docs/js-api) for
every method.
---
Source: https://ferrochart.com/docs/frameworks
# React and Vue
`@ferrochart/core` works in any framework: create the chart when the canvas
is mounted and destroy it when it is removed. There are no wrapper packages
to install. Size the canvas with CSS; the chart follows its size and the
device pixel ratio.
## React
```tsx
import { useEffect, useRef } from 'react';
import { FerroChart, type OhlcRow } from '@ferrochart/core';
export function PriceChart({ bars }: { bars: OhlcRow[] }) {
const canvas = useRef(null);
useEffect(() => {
let chart: FerroChart | undefined;
let gone = false;
FerroChart.create(canvas.current!, { theme: 'dark' }).then((c) => {
if (gone) return c.destroy(); // unmounted while it was starting
chart = c;
chart.addCandlestickSeries().setData(bars);
});
return () => { gone = true; chart?.destroy(); };
}, [bars]);
return ;
}
```
For live data, keep the series in a ref and call `series.update(bar)` instead
of recreating the chart.
## Vue
```vue
```
## Server-side rendering
The chart needs a browser (WebGPU or WebGL2). In Next.js, Nuxt and similar
frameworks, create it only on the client: in `useEffect` / `onMounted` as
above, which never run on the server.
---
Source: https://ferrochart.com/docs/desktop
# Desktop (Rust + winit)
`ferrochart-winit` opens a window, renders with wgpu and handles mouse,
trackpad and keyboard input. You give it a `Chart` and, optionally, callbacks.
```toml
[dependencies]
ferrochart-core = "0.7"
ferrochart-winit = "0.7"
```
## A window with data
```rust,ignore
use ferrochart_core::data::OhlcColumns;
use ferrochart_core::{Chart, ChartOptions};
use ferrochart_indicators::named::ChartExt; // add_indicator_by_name
fn main() -> Result<(), Box> {
let mut chart = Chart::new(ChartOptions::default());
let candles = chart.add_candlestick()?;
chart.add_volume(candles)?;
chart.set_data(candles, OhlcColumns {
time: vec![/* UTC ms */],
open: vec![], high: vec![], low: vec![], close: vec![],
volume: Some(vec![]),
})?;
chart.add_indicator_by_name(candles, "ema", &[("n", 20.into())])?;
ferrochart_winit::show(chart)?;
Ok(())
}
```
`show` opens a window with the default title and size and returns when it is
closed. For a title, a size or callbacks (live data, events), use
`run(WindowOptions, chart, app)` with a `ChartApp`, below. `run` returns when
the window is closed. The chart redraws only when something
changed (input, new data, kinetic scrolling), so an idle chart uses no CPU.
The bundled font covers Latin letters, digits and common symbols. For Chinese,
Japanese, Korean or other scripts in marker texts, labels and titles, give
fallback fonts, searched in order (no system fonts are scanned; a character
that no font has is drawn as `□`):
```rust,ignore
let options = WindowOptions {
fonts: vec![std::fs::read("/System/Library/Fonts/Hiragino Sans GB.ttc")?],
..WindowOptions::default()
};
ferrochart_winit::run(options, chart, app)?;
```
With your own event loop, add them to the renderer:
`renderer.text_engine_mut().add_fallback_font(data)`.
## Live data
Implement `ChartApp::update`. It is called on every event-loop iteration; return
when you want to be called next, on the same millisecond clock it receives:
```rust,ignore
use ferrochart_core::Chart;
use ferrochart_core::data::{BarUpdate, SeriesId};
use ferrochart_winit::ChartApp;
struct Feed { series: SeriesId, bar: BarUpdate, next: f64 }
impl ChartApp for Feed {
fn update(&mut self, chart: &mut Chart, now_ms: f64) -> Option {
if now_ms >= self.next {
self.bar.close += 0.01;
self.bar.high = self.bar.high.max(self.bar.close);
let _ = chart.update_last(self.series, self.bar);
self.next = now_ms + 10.0; // 100 updates per second
}
Some(self.next)
}
}
```
`ChartApp::on_event` receives crosshair, visible-range and history events;
`ChartApp::on_frame` receives the CPU time of each rendered frame.
## The demo
```bash
cargo run -p example-desktop --release
```
Ten million one-minute bars with a simulated feed of 100 ticks per second.
Drag to pan (flick for kinetic scrolling), wheel or pinch to zoom, drag an axis
to scale it, double-click an axis to reset it, arrow keys and Home/End to
navigate. On a touch screen the [touch gestures](https://ferrochart.com/docs/interaction#touch) work
too: winit's touch events become touch pointers.
## Your own event loop
If your app already owns the window (egui, a game engine), use
`ferrochart_winit::InputConverter` to turn winit events into chart input, and
drive `Chart::build_frame` and `WgpuRenderer::render` yourself — see
[How rendering works](https://ferrochart.com/docs/rendering).
---
Source: https://ferrochart.com/docs/python
# Python
The `ferrochart` package draws charts from Python in a native window, in
Jupyter or to PNG, on the GPU (Metal, Vulkan, DirectX 12) with a CPU
fallback. It takes pandas or polars DataFrames, or dicts of NumPy arrays.
```bash
pip install ferrochart # windows and PNG
pip install "ferrochart[jupyter]" # also the Jupyter widget
```
One wheel per platform serves Python 3.10 and later.
## Quick start
```python
import ferrochart as fc
chart = fc.Chart(theme="dark", width=1200, height=700)
candles = chart.add_series("candlestick")
candles.set_data(df) # columns time, open, high, low, close[, volume]
chart.add_volume_series(candles)
chart.add_indicator(candles, "ema", n=20)
chart.add_indicator(candles, "macd") # in a new pane
chart.show() # a window; returns when it is closed
chart.to_png("chart.png") # offscreen, GPU or CPU
chart # in Jupyter: an interactive chart
```
`time` is a `datetime64` column (naive times are UTC) or integer
milliseconds; a pandas `DatetimeIndex` is used when there is no `time` column.
Line, area, baseline, histogram and points series take `time` and `value`,
and optionally `color` per point.
## Real-time data
```python
candles.update_last(t, open=o, high=h, low=l, close=c, volume=v) # same time: update, later: new bar
candles.append(new_bars)
```
Indicators follow the data. Changes made while the chart is shown are drawn at
once, including changes from other threads.
## Options, indicators and drawings
Options and parameters are keyword arguments; unknown names raise
`ValueError`.
```python
line = chart.add_series("line", color="#ff9800", line_width=2)
candles.apply_options(down_color="#e91e63")
candles.create_price_line(101.5, title="target", line_style="dashed")
stop = candles.create_price_line(98.5, title="stop", draggable=True, price_step=0.25)
y = candles.price_to_coordinate(98.5) # CSS px from the top; None before the first frame
price = candles.coordinate_to_price(200) # and back
candles.set_markers([{"time": t, "position": "below_bar", "shape": "arrow_up", "text": "buy"}])
whale = chart.add_icon(avatar) # a (height, width, 4) uint8 array; RGB works too
candles.set_markers([{"time": t, "icon": whale, "size": 24, "border": "#2fbf71"},
{"time": t, "label": "DB", "position": "below_bar"}])
candles.apply_options(marker_stack_limit=4, marker_cluster=28)
candles.set_markers([{"id": 101, "time": t, "position": "at_price", "price": 101.5, "text": "fill"}])
candles.set_bar_flags([t], filled=[True], clipped=[False])
candles.apply_options(filled_bar_color="#78909c")
chart.apply_price_scale_options(mode="logarithmic")
chart.apply_price_scale_options(smoothing=150) # auto-scaling eases over ~150 ms
chart.begin_transition() # animate the next set_data (period, type or symbol switch)
rsi = chart.add_indicator(candles, "rsi", n=14)
boll = chart.add_indicator(candles, "boll", n=20, k=2)
bricks = fc.Chart() # a transform series is the only series of its chart
renko = bricks.add_transform_series("renko", box_size=2.0)
renko.set_data(df) # OHLC bars in, Renko bricks drawn
d = chart.drawings
trend = d.add("trend_line", [(t0, 100.0), (t1, 120.0)], style={"line": "#e91e63", "line_width": 2})
d.add("fib_retracement", [(t0, 90.0), (t1, 130.0)], params={"levels": [0, 0.382, 0.618, 1]})
d.add("long_position", [(t0, 100.0), (t1, 106.0), (t1, 98.0)], params={"quantity": 250, "currency": "$"})
d.start_tool("rectangle") # the next clicks in the window draw one
d.undo()
import json
saved = json.dumps(chart.save_state()) # view, panes, price scales, drawings
chart.load_state(json.loads(saved)) # on a chart set up the same way
```
Markers accept an integer `id` (0 means none). `"at_price"` requires a
finite `price` and is neither stacked nor clustered. `marker_cluster` is a
positive CSS-pixel distance, or `None` to disable; `marker_stack_limit`
still handles single-bar folding. `set_bar_flags` replaces quality flags
using UTC-millisecond times and matching boolean arrays: `filled` draws a
hollow bar, `clipped` marks the wick ends. Keep original prices yourself
for tooltips. See [Marker placement](https://ferrochart.com/docs/markers#placement-and-snapping),
[Clustering](https://ferrochart.com/docs/markers#clustering-across-bars) and
[Bar quality flags](https://ferrochart.com/docs/data#bar-quality-flags).
## Events
```python
@chart.on("click")
def clicked(e):
print(e["time"], e["price"], e["target"])
chart.on("crosshair_move", lambda e: print(e["point"]))
```
Events: `click`, `crosshair_move`, `visible_range_changed`,
`need_more_history`, `drawing_created`, `drawing_modified`, `drawing_removed`,
`drawing_selected`, `warning`, `marker_hover` (a dict with `series`, `index`,
`id`, `overflow`, `bars`, `x`, `y`, `size`, or `None` when the pointer leaves the marker),
`price_line_drag` (a dict with `line`, `id`, `phase`, `from`, `price`; see
[Price lines](https://ferrochart.com/docs/markers#price-lines)). Callbacks run on the main thread while the
chart is shown.
A click on a draggable price line has a target of type `price_line` with the
line's `id`. A marker click target includes `id`; a `marker_overflow` target also has
`bars`, the inclusive logical bar range (a `(from, to)` tuple in native
window events). For a badge, `id` identifies the first hidden marker. Native Python events do not
return the original marker dictionary; keep your application objects in a
mapping keyed by `id`.
## Chinese, Japanese and Korean text
The bundled font covers Latin letters, digits and common symbols. For other
scripts, pass font files (paths or bytes), searched in order; characters that
no font has are drawn as `□`:
```python
chart = fc.Chart(fonts=["/System/Library/Fonts/Hiragino Sans GB.ttc"]) # macOS
chart = fc.Chart(fonts=["NotoSansSC-Regular.otf"]) # any system
```
The fonts are used by `show()` and `to_png()`. In Jupyter, the browser draws
with its own fonts and `fonts` is not needed. See [Markers](https://ferrochart.com/docs/markers).
## Windows
`chart.show()` blocks until the window is closed and can be called again. It
must run on the main thread. On Linux and Windows, `chart.show(block=False)`
opens the window from a background thread and returns at once; event callbacks
then run on the main thread between Python statements, or when you call
`ferrochart.process_events()`. The first `show` of a process fixes the mode.
In the window: drag to pan, wheel or pinch to zoom, drag an axis to scale it,
double-click an axis to reset it. With a tool started, click to place anchors;
Esc cancels, Delete removes the selected drawing, Ctrl/⌘+Z undoes.
## Jupyter
A chart that is the last expression of a cell is shown as an interactive
widget (with `ferrochart[jupyter]`; a PNG otherwise). Later changes, such as
new bars, reach every view of it. `chart.widget()` returns the widget, for
example to put it in an ipywidgets layout.
## Plots
`ferrochart.Plot` draws lines, areas, scatter, bars, waterfalls and heatmaps
on numeric, category or date axes. It is shown the same three ways as a chart:
`plot.show()`, the last expression of a notebook cell, or `plot.to_png()`.
```python
import ferrochart as fc
plot = fc.Plot(width=640, height=400)
plot.axis("x").apply_options(type="category")
plot.axis("x").set_categories(["north", "south", "east"])
plot.add_mark("bars", [4, 6, 5], color="#2196f3")
plot.add_mark("line", {"x": [0, 1, 2], "y": [3, 5.5, 4.5]}, line_width=2)
plot.add_rule(5, label="target", line_style="dashed")
plot.add_label(1, 6, "best", icon="arrow_down")
@plot.on("click")
def clicked(e):
if e["hit"]:
print(e["hit"]["mark"], e["hit"]["index"], e["hit"]["y"])
plot.to_png("plot.png")
```
`set_data` takes a DataFrame or dict with columns `x`, `y` and optional `y0`,
`value` (colored by the mark's color scale), `size`, `color`, `step`
(waterfalls) and `label`; a pandas Series (x from its index); a list or array
of y values; or keywords: `mark.set_data(x=xs, y=ys)`. Datetimes in `x` work
with `plot.axis("x").apply_options(format="date")`. Events: `hover`, `click`,
`view_change`.
---
Source: https://ferrochart.com/docs/native
# C, C++ and C#
`ferrochart-ffi` is a C library with one header, `ferrochart.h`. Use it from C
and C++ directly, and from C#, Swift, Go, Qt, Flutter or any language that can
call C. The library draws into a native window you own, or into an RGBA buffer.
```bash
cargo build -p ferrochart-ffi --release
# target/release/libferrochart.{so,dylib} or ferrochart.dll, plus a static
# library; the header is crates/ferrochart-ffi/include/ferrochart.h
```
## Conventions
- Functions return `FERROCHART_OK` (0) or a negative `FERROCHART_ERR_*` code.
`ferrochart_last_error()` describes the last failure on the calling thread.
- Structs start with a `size` field: set it to `sizeof` the struct before
passing it in either direction. This lets a newer library read an older
struct.
- Ids are `uint64_t`, times are UTC milliseconds, sizes are CSS pixels and
colors are `0xRRGGBBAA`.
- A chart is not thread-safe: use it from one thread (on macOS, the main
thread when it draws into a window).
- Strings the library returns are freed with `ferrochart_free_string`.
## A chart
```c
#include "ferrochart.h"
FerroChartOptions o = { .size = sizeof o };
ferrochart_options_default(&o);
o.theme = FERROCHART_THEME_DARK;
o.width = 1200; o.height = 700; o.dpr = 2;
FerroChart *chart;
if (ferrochart_create(&o, &chart) != FERROCHART_OK) {
fprintf(stderr, "%s\n", ferrochart_last_error());
return 1;
}
uint64_t candles, volume, ema;
ferrochart_add_series(chart, FERROCHART_MAIN_PANE, "candlestick", NULL, &candles);
ferrochart_add_volume_series(chart, FERROCHART_MAIN_PANE, candles, &volume);
ferrochart_set_data_ohlc(chart, candles, time, open, high, low, close, vol, n);
ferrochart_add_indicator(chart, candles, "ema", "{\"n\": 20}", FERROCHART_PLACEMENT_DEFAULT, &ema);
```
Indicator names and parameters are those of the other languages
(`ferrochart_indicator_names()` lists them); parameters are a JSON object, or
`NULL` for the defaults.
## Drawing
Into a buffer, for example to save an image or to show it in a UI toolkit:
```c
uint32_t w, h;
ferrochart_pixel_size(chart, &w, &h); // device pixels
uint8_t *pixels = malloc((size_t)w * h * 4);
ferrochart_render_rgba(chart, now_ms, pixels, (size_t)w * 4, (size_t)w * h * 4);
```
Into a window: pass its native handle to `ferrochart_attach_window`
(`FERROCHART_PLATFORM_WIN32` with the `HWND` and `HINSTANCE`, or
`FERROCHART_PLATFORM_APPKIT` with an `NSView*`), call `ferrochart_resize` when
the window is resized, and call `ferrochart_render` whenever
`ferrochart_needs_redraw` returns 1.
Animations (kinetic scrolling, [transitions](https://ferrochart.com/docs/transitions#c), price scale
[smoothing](https://ferrochart.com/docs/price-scale#smoothing)) advance with the `now_ms` you pass to
either render function; keep rendering while `ferrochart_needs_redraw`
returns 1.
## Markers, images and fonts
Markers can show an image clipped to their shape, or a short label such as
`"DB"`. Add the image once (straight RGBA8, up to 256 × 256; the chart keeps
a copy) and use its id in any number of markers:
```c
uint64_t avatar;
ferrochart_add_icon(chart, rgba, 64, 64, 64 * 4, &avatar);
FerroChartMarker m[2] = {0}; // zero fields are defaults
m[0].size = sizeof m[0];
m[0].time = t;
m[0].icon = avatar;
m[0].marker_size = 24; // CSS px, 4–64
m[0].border = 0x2fbf71ff;
m[1] = m[0];
m[1].icon = 0;
m[1].label = "DB"; // an image or a label, not both
m[1].position = FERROCHART_MARKER_BELOW_BAR;
ferrochart_set_markers(chart, candles, m, 2); // replaces the series' markers
```
With many markers on one bar, set `marker_stack_limit` in the series options:
beyond it a "+k" badge stands for the rest. `FERROCHART_EVENT_MARKER_HOVER`
reports the marker or badge under the pointer (`target_type`, `target_index`,
its center in `x`/`y`), for example to show a tooltip; a click on a badge has
`target_type` `FERROCHART_TARGET_MARKER_OVERFLOW` and `count`.
`FerroChartMarker.id` is your `uint64_t` identifier (0 means none); marker
click and hover events return it as `marker_id`. Keep a host-side lookup for
your own objects. To place a marker at a price, set `position` to
`FERROCHART_MARKER_AT_PRICE` and `price` to a finite value in series units;
it is not stacked or clustered. Other positions ignore the C `price` field.
`FerroChartSeriesOptions.marker_cluster` sets the cross-bar clustering
distance in CSS px; 0 disables it. Badge events include `bars_from` and
`bars_to`, the inclusive logical bar range; `marker_id` is the first hidden
marker's id. See [Clustering](https://ferrochart.com/docs/markers#clustering-across-bars).
For quality flags, call `ferrochart_set_bar_flags` with timestamp and flag
arrays, using `FERROCHART_BAR_FILLED` and `FERROCHART_BAR_CLIPPED` bits.
`FerroChartSeriesOptions.filled_bar_color` sets the hollow filled-bar color
as `0xRRGGBBAA` (0 uses the main color at 40% opacity). See
[Bar quality flags](https://ferrochart.com/docs/data#bar-quality-flags).
The bundled font covers ASCII and common symbols. For Chinese, Japanese,
Korean or other scripts, add a font file; characters are looked up in the
added fonts in order, and drawn as `□` when none has them:
```c
// font_data: the bytes of a .ttf, .otf or .ttc file, e.g. Noto Sans SC or
// /System/Library/Fonts/Hiragino Sans GB.ttc on macOS (copied by the call).
ferrochart_add_font(chart, font_data, font_len);
```
Color emoji fonts are not supported natively; an outline emoji font draws in
the text color.
## Input and events
Forward mouse, touch, wheel and key input with `ferrochart_handle_input`
(`FERROCHART_INPUT_*` events in CSS pixels); the chart pans, zooms, moves the
crosshair and draws with the active tool. For touch, set `pointer_kind` to
`FERROCHART_POINTER_TOUCH`, give each finger its own `pointer_id`, and send
`FERROCHART_INPUT_POINTER_CANCEL` when the system takes a touch over; the
chart then applies the [touch gestures](https://ferrochart.com/docs/interaction#touch). A
`FerroChartInput` from an older header (a smaller `size`) is a mouse. Then
read what happened:
```c
FerroChartEvent ev = { .size = sizeof ev };
while (ferrochart_poll_event(chart, &ev) == 1) {
if (ev.type == FERROCHART_EVENT_CLICK) printf("click at %f\n", ev.price);
}
```
Destroy the chart with `ferrochart_destroy(chart)`.
## C#
`examples/csharp` in the repository has the P/Invoke declarations of the whole
header (`Native.cs`), a small wrapper that turns status codes into exceptions
(`Chart.cs`) and a demo with indicators, drawings, events and a live feed:
```bash
cargo build -p ferrochart-ffi --release
dotnet run --project examples/csharp -- out/
```
---
Source: https://ferrochart.com/docs/offscreen
# Offscreen and server-side rendering
Both renderers can draw without a window, for PNG export, reports or tests.
## On the GPU
```rust,ignore
use ferrochart_core::chart::{SeriesData, SeriesOptions};
use ferrochart_core::frame::SeriesKind;
use ferrochart_core::geom::SizeCss;
use ferrochart_core::render::Renderer;
use ferrochart_core::testing::random_walk; // feature "testing"
use ferrochart_core::{Chart, ChartOptions};
use ferrochart_render_wgpu::{GpuContext, WgpuRenderer};
let ctx = GpuContext::headless()?;
let mut renderer = WgpuRenderer::offscreen(&ctx);
let mut chart = Chart::new(ChartOptions::default());
chart.resize(SizeCss { w: 800.0, h: 450.0 }, 1.0);
let id = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
chart.set_data(id, SeriesData::Ohlc(random_walk(1, 1000, 0, 60_000)?))?;
chart.build_frame(0.0, &renderer.measurer());
renderer.render(chart.frame(), &chart.data_view())?;
let rgba: Vec = renderer.read_pixels()?; // 800 × 450 × 4 bytes
```
A software adapter (lavapipe on Linux, WARP on Windows) works where there is
no GPU.
## On the CPU
`ferrochart-render-cpu` draws the same frames with tiny-skia and needs nothing
but the CPU. It produces the same pixels as the GPU backend (both are checked
against the same golden images).
```rust,ignore
use ferrochart_render_cpu::CpuRenderer;
let mut renderer = CpuRenderer::new();
chart.build_frame(0.0, &renderer.measurer());
renderer.render(chart.frame(), &chart.data_view())?;
let pixmap = renderer.pixmap(); // tiny_skia::Pixmap; encode it as PNG
```
The CPU renderer has no performance targets; use it where a GPU is not
available.
## Pixel size
`resize` takes the size in CSS pixels plus the device pixel ratio. The image is
`size × dpr` pixels: `resize(SizeCss { w: 800.0, h: 450.0 }, 2.0)` renders
1600 × 900 with text and lines scaled to match.
---
Source: https://ferrochart.com/docs/series
# Series types
A series is one set of data drawn one way: candles, a line, a histogram and
so on. A chart can hold any number of series on any number of panes. All
series of a chart share one time axis (see [Data](https://ferrochart.com/docs/data)).
## Adding a series
```ts
import { FerroChart } from '@ferrochart/core';
const chart = await FerroChart.create(canvas);
const candles = chart.addSeries('candlestick'); // main pane
const sma = chart.addSeries('line', { color: '#2962ff' }); // with options
const pane = chart.addPane(0.3);
const osc = chart.addSeries('histogram', {}, pane); // on another pane
```
`addSeries(kind, options?, pane?)` returns a `Series` handle. Leaving out
`pane` puts the series on the main (top) pane. `addCandlestickSeries(options?,
pane?)` is a shorthand for `addSeries('candlestick', ...)`. An unknown kind or
pane id throws.
A `Series` has three read-only properties:
| Property | Meaning |
|---|---|
| `id` | Number, unique within the chart. Handles of the same series (for example one from a `click` event) have the same id. |
| `kind` | The kind passed to `addSeries`; `'volume'` for volume series, `'kagi'` / `'pointFigure'` for those transforms (Renko and range bars report `'candlestick'` or `'ohlc'`), `'custom'` for plugin series. |
| `pane` | Id of the pane the series is on. |
## Kinds
| Kind | Data | Draws |
|---|---|---|
| `'candlestick'` | OHLC | Candles: body from open to close, wick from low to high |
| `'ohlc'` | OHLC | Bars with an open tick on the left and a close tick on the right |
| `'heikinAshi'` | OHLC | Heikin-Ashi candles computed from the bars you pass |
| `'line'` | value | A line through the values |
| `'area'` | value | A line with a gradient fill down to the bottom of the pane |
| `'baseline'` | value | A line and fills above and below `baseValue`, in different colors |
| `'histogram'` | value | Bars from `baseValue` to each value, optionally colored per point |
| `'points'` | value | A dot at each value |
Volume histograms are added with `addVolumeSeries` (see [Volume](https://ferrochart.com/docs/series#volume)),
and Renko, range bars, Kagi and Point & Figure with `addTransformSeries` (see
[Bar transforms](https://ferrochart.com/docs/series#bar-transforms)).
OHLC series take `{ time, open, high, low, close, volume? }`; value series
take `{ time, value, color? }`. [Data](https://ferrochart.com/docs/data) describes both formats, row
arrays, validation and real-time updates.
### Candlestick
```ts
const candles = chart.addCandlestickSeries({
color: '#26a69a', // up candles (close >= open)
downColor: '#ef5350', // down candles
});
candles.setData(randomWalk(1, 500, Date.UTC(2024, 0, 1), 60_000));
```
With neither `color` nor `downColor` set, wicks use the theme's wick colors.
As soon as one of them is set, wicks have the same color as the body.
### OHLC bars
`'ohlc'` takes the same data and options as `'candlestick'` and draws
traditional bars.
### Heikin-Ashi
`'heikinAshi'` takes ordinary OHLC bars; the chart computes the Heikin-Ashi
values from them, also for real-time updates. Colors work as for candlesticks.
### Line
```ts
const line = chart.addSeries('line', { color: '#2962ff', lineWidth: 1, lineStyle: 'dashed' });
line.setData({ time: [0, 60_000, 120_000, 180_000], value: [10, 11, NaN, 12] });
```
A `NaN` value is a gap: no line is drawn through it.
### Area
An area is a line with a vertical gradient below it. `topFill` is the color at
the line, `bottomFill` the color at the bottom of the pane.
```ts
chart.addSeries('area', {
color: '#2962ff',
topFill: 'rgba(41, 98, 255, 0.4)',
bottomFill: 'rgba(41, 98, 255, 0)',
});
```
By default both fills are `color` with an opacity of 40 % at the top and 2 %
at the bottom.
### Baseline
A baseline series splits at `baseValue`: above it the line has `color` and
the fill `topFill`; below it the line has `downColor` and the fill
`bottomFill`.
```ts
chart.addSeries('baseline', {
baseValue: 100,
color: '#26a69a',
downColor: '#ef5350',
});
```
By default the fills are the two line colors at 20 % opacity.
### Histogram
Bars go from `baseValue` (default 0) to each value. The auto-scaled range
always includes `baseValue`.
Each point can have its own color: pass a `color` column next to `value`. Its
entries are CSS colors, `null` for the series color, or a `Uint32Array` of
`0xRRGGBBAA` values where `0` means the series color.
```ts
const hist = chart.addSeries('histogram', { color: '#26a69a' }, pane);
hist.setData({
time: [0, 60_000, 120_000],
value: [1.5, -0.7, 0.4],
color: [null, '#ef5350', null],
});
// The same colors as packed integers.
hist.setData({
time: [0, 60_000, 120_000],
value: [1.5, -0.7, 0.4],
color: new Uint32Array([0, 0xef5350ff, 0]),
});
```
Per-point colors are drawn only at full detail. When you zoom out so far that
several bars share a pixel and are merged, the series color is used. Other
kinds accept a `color` column but ignore it. `update` cannot set a color; an
appended point has the series color.
### Points
`'points'` draws a dot at each value; `lineWidth` is the dot's diameter in CSS
px. Gaps (`NaN`) have no dot.
```ts
const dots = chart.addSeries('points', { color: '#ff9800', lineWidth: 4 });
```
### Volume
A volume series draws the `volume` column of an OHLC series. It has no data of
its own: `setData` and `update` on the source series update it.
```ts
const candles = chart.addCandlestickSeries();
const volume = chart.addVolumeSeries(candles); // main pane
// or: chart.addVolumeSeries(candles, chart.addPane(0.25));
```
The source must be an OHLC series (candlestick, OHLC bars, Heikin-Ashi) or a
transform series. Bars are colored by whether the source bar is up or down,
in the theme's volume colors. On a pane that also shows prices, the volume
has its own scale in the bottom quarter of the pane; on a pane of its own it
fills the pane. See [Price scale and panes](https://ferrochart.com/docs/price-scale#volume-placement).
Removing the source series also removes its volume series.
## Series options
Options are passed to `addSeries` and changed later with `applyOptions`; keys
you leave out keep their value. `options()` returns every key.
```ts
const s = chart.addSeries('line', { color: '#2962ff' });
s.applyOptions({ lineWidth: 3 }); // color stays '#2962ff'
console.log(s.options().lineWidth); // 3
s.applyOptions({ color: null }); // back to the theme color
```
| Option | Type | Default | Used by | Meaning |
|---|---|---|---|---|
| `color` | `Color \| null` | theme | all | Line color (line, area, points); up candles and bars; histogram bars; baseline line above the base; Kagi yang lines and Point & Figure X columns |
| `downColor` | `Color \| null` | theme | candlestick, ohlc, heikinAshi, baseline, transforms | Down candles and bars; baseline line below the base; Kagi yin lines and Point & Figure O columns |
| `topFill` | `Color \| null` | see [Area](https://ferrochart.com/docs/series#area), [Baseline](https://ferrochart.com/docs/series#baseline) | area, baseline | Area fill at the line; baseline fill above the base |
| `bottomFill` | `Color \| null` | see [Area](https://ferrochart.com/docs/series#area), [Baseline](https://ferrochart.com/docs/series#baseline) | area, baseline | Area fill at the bottom; baseline fill below the base |
| `lineWidth` | `number` | `2` | line, area, baseline, points, Kagi, Point & Figure | Line width in CSS px; for points, the dot diameter. Must be positive. |
| `lineStyle` | `'solid' \| 'dashed' \| 'dotted'` | `'solid'` | line, area, baseline | Dash pattern of the line |
| `step` | `boolean` | `false` | line, area, baseline | Step line, see [Step lines](https://ferrochart.com/docs/series#step-lines) |
| `baseValue` | `number` | `0` | baseline, histogram | Where the baseline fills split; where histogram bars start. Must be finite. |
| `lastValueVisible` | `boolean` | `true` | all but volume | Label with the last value on the price axis |
| `priceLineVisible` | `boolean` | `true` | all but volume | Dotted horizontal line at the last value |
| `shift` | `number` | `0` | all | Display shift in bars, see [Shift](https://ferrochart.com/docs/series#shift) |
| `pricePrecision` | `number \| null` | `null` | all | Decimals of price labels, see [Price precision](https://ferrochart.com/docs/series#price-precision) |
| `markerStackLimit` | `number \| null` | `null` | series with markers | Integer 1–65535: places per bar side, including the "+k" badge; `null` means no limit. See [Folding](https://ferrochart.com/docs/markers#folding-crowded-bars). |
| `markerCluster` | `number \| null` | `null` | series with markers | Positive, finite CSS-pixel distance for cross-bar clustering; `null` disables it. Excludes `atPrice`. See [Clustering](https://ferrochart.com/docs/markers#clustering-across-bars). |
| `filledBarColor` | `Color \| null` | `null` | candlestick, ohlc, heikinAshi | Color of bars flagged `filled`, drawn hollow; `null` uses the main color at 40% opacity. See [Bar quality flags](https://ferrochart.com/docs/data#bar-quality-flags). |
Invalid values (an unknown line style, a malformed color, a negative width)
throw, and the series keeps its old options.
Volume series always use the theme's volume colors.
### Colors
Colors are CSS strings: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`,
`rgb(r, g, b)`, `rgba(r, g, b, a)` (alpha from 0 to 1) or `'transparent'`.
Color names such as `'red'` are not accepted. `null` means the theme default.
`options()` returns colors as `#rrggbb`, or `rgba(...)` when they are
translucent, and `null` for theme colors.
### Step lines
With `step: true` the line runs horizontally to the next point's time, then
vertically to its value. Use it for values that hold until they change, such
as an interest rate or a position size.
```ts
const rate = chart.addSeries('line', { step: true, color: '#7e57c2' }, pane);
rate.setData({
time: [Date.UTC(2024, 0, 1), Date.UTC(2024, 2, 20), Date.UTC(2024, 6, 31)],
value: [5.5, 5.25, 5.0],
});
```
### Shift
`shift` draws the point at logical index `j` at `j + shift`: positive values
move the series to the right (into the future), negative values to the left.
It must be an integer. Auto-scaling, the crosshair and `dataAt` follow the
drawn positions. Ichimoku's leading spans and lagging line use it.
```ts
// A moving average drawn 10 bars ahead (a "displaced" moving average).
const dma = chart.addSeries('line', { shift: 10 });
```
### Price precision
`pricePrecision` sets the number of decimals of the price axis labels, the
last-value label and the crosshair label, from 0 to 12. `null` (the default)
is automatic: at least 2 decimals and 4 significant digits of the visible
prices. Very small prices are written with a subscript count of zeros:
`0.0₄1234` is 0.00001234.
The labels of a pane use the precision of its first price series. In the
`'percentage'` and `'indexedTo100'` price scale modes the axis always uses 2
decimals. Any other value than an integer from 0 to 12 or `null` throws.
```ts
candles.applyOptions({ pricePrecision: 5 }); // FX quotes
candles.applyOptions({ pricePrecision: null }); // automatic again
```
## Bar transforms
A transform series takes ordinary bars (or ticks) and draws what a charting
method makes of them: Renko bricks, range bars, Kagi lines or Point & Figure
columns. These methods ignore time; each element gets its own slot on the time
axis.
```ts
const renko = chart.addTransformSeries('renko', { boxSize: 0.5 });
renko.setData(randomWalk(1, 5_000, Date.UTC(2024, 0, 1), 60_000));
chart.addVolumeSeries(renko); // optional
chart.fitContent();
```
`addTransformSeries(name, params, options?, pane?)` returns a `Series`. Feed
it with `setData` and `update` exactly like a candlestick series. A tick is a
bar with four equal prices:
```ts
renko.update({ time: tick.time, open: tick.price, high: tick.price, low: tick.price, close: tick.price, volume: tick.size });
```
### Parameters
Prices are in the units of the data.
| Transform | Parameters | Drawn as |
|---|---|---|
| `'renko'` | `boxSize` (price) **or** `atr` (ATR period, whole number); `kind?` | Candlesticks (default) or OHLC bars |
| `'rangeBars'` | `range` (price); `kind?` | Candlesticks (default) or OHLC bars |
| `'kagi'` | `reversal` (price) **or** `reversalPercent` | Kagi lines |
| `'pointFigure'` | `boxSize` (price); `reversal?` (boxes, whole number, default 3) | X and O columns |
`kind` is `'candlestick'` (default) or `'ohlc'`. Numbers must be finite and
positive. Giving both alternatives (`boxSize` and `atr`, or `reversal` and
`reversalPercent`), neither, or an unknown name throws.
```ts
chart.addTransformSeries('renko', { atr: 14, kind: 'ohlc' });
chart.addTransformSeries('rangeBars', { range: 1 });
chart.addTransformSeries('kagi', { reversalPercent: 2 });
chart.addTransformSeries('pointFigure', { boxSize: 1, reversal: 3 });
```
(Each of these lines needs a chart of its own, see
[Constraints](https://ferrochart.com/docs/series#constraints).)
### Renko
Renko uses closing prices only. A brick is added each time the close moves a
full `boxSize` beyond the last brick: continuing in the same direction takes
one box, reversing takes two. The first brick is anchored at the first close.
With `atr: n` the box size is the average true range of the first `n` bars,
fixed from then on; nothing is drawn before that.
Renko has no forming brick: a brick appears only once it is complete.
### Range bars
Every bar spans exactly `range` from low to high. Within an input bar the
price is assumed to move open → low → high → close for an up bar and open →
high → low → close for a down bar. When the price leaves the current bar's
range, that bar is completed and the next one opens at its edge. The last bar
is forming and changes with updates.
### Kagi
A Kagi line follows the close in its direction and turns when the close
reverses by at least `reversal` (or `reversalPercent` percent of the line's
end price). A line becomes thick (yang, drawn with `color`) when it rises above
the previous shoulder and thin (yin, `downColor`) when it falls below the
previous waist. The last line is forming.
### Point & Figure
Prices are divided into boxes of `boxSize`. A column of X rises while the close
fills new boxes upward; a reversal of `reversal` boxes starts a column of O,
and the other way round. X columns use `color`, O columns `downColor`. The
last column is forming.
### Constraints
- A chart has at most one transform series, and no other series next to it
except volume. Adding a second transform or any other series throws, and so
does adding a transform to a chart that already has series. Use a separate
chart to show the original bars, and keep the two in step with
[sync](https://ferrochart.com/docs/sync) if needed.
- Each element's time is the time of the input bar that completed it (one
millisecond later than the previous element if that would not be
increasing). `timeAtIndex` and the time axis show these times.
- The input volume of each bar is added to the element forming after it.
Without input volume, the volume is empty.
- A single input bar can produce at most 65536 elements. If the box or range
is so small compared with the price moves that a bar exceeds this, the call
throws and the series is cleared.
- Bars that are gaps (all prices `NaN`) are skipped.
## Bands between two series
`addBand(upper, lower, options?)` fills the area between two single-value
series (line, area, baseline, histogram or points) of the same pane. `fill` is
used where `upper` is at or above `lower`, `fillCrossed` where it is below.
Bands are drawn behind the series of the pane (above the volume).
```ts
const upper = chart.addSeries('line', { color: '#26a69a' });
const lower = chart.addSeries('line', { color: '#ef5350' });
upper.setData({ time, value: highs });
lower.setData({ time, value: lows });
const band = chart.addBand(upper, lower, {
fill: 'rgba(38, 166, 154, 0.15)',
fillCrossed: 'rgba(239, 83, 80, 0.15)',
});
chart.setBandOptions(band, { fillCrossed: null }); // keys left out keep their value
console.log(chart.bandOptions(band)); // { fill: 'rgba(...)', fillCrossed: null }
chart.removeBand(band);
```
`addBand` returns a band id. A `null` (or missing) `fill` is the upper series'
color at 15 % opacity; a `null` `fillCrossed` is the same as `fill`.
`bandOptions` returns `null` for an unknown id. The band is removed
automatically with either series. Two OHLC series, series on different panes,
or the same series twice throw.
Indicators with bands (Bollinger, Keltner, Ichimoku) create them for you; see
[Indicators](https://ferrochart.com/docs/indicators).
## Removing a series
```ts
line.remove();
```
`remove()` deletes the series, its data, markers and price lines, and the
bands that use it. Removing an OHLC series also removes its volume series.
After that, every method of the handle throws (`'the series was removed'`).
Removing the last series with data resets the time axis.
Indicator outputs cannot be removed one by one: `remove()` on one throws;
remove the indicator instead (`indicator.remove()`).
To remove a whole pane with all its series, use `chart.removePane(id)` (see
[Price scale and panes](https://ferrochart.com/docs/price-scale)).
---
Source: https://ferrochart.com/docs/data
# Data
This chapter covers getting bars and values into a series: the data formats,
the validation rules, real-time updates, loading older history and reading
data back.
## Columns and rows
`setData` replaces all data of a series. It accepts two shapes: an object of
columns (one array per field) or an array of row objects.
### Columns
OHLC series (candlestick, OHLC bars, Heikin-Ashi and transforms) take
`OhlcData`:
| Column | Type | Notes |
|---|---|---|
| `time` | `BigInt64Array`, `Float64Array` or `number[]` | Bar open time, UTC milliseconds, strictly increasing |
| `open`, `high`, `low`, `close` | `Float64Array` or `number[]` | |
| `volume` | `Float64Array` or `number[]` | Optional |
Value series (line, area, baseline, histogram, points) take `ValueData`:
| Column | Type | Notes |
|---|---|---|
| `time` | `BigInt64Array`, `Float64Array` or `number[]` | UTC milliseconds, strictly increasing |
| `value` | `Float64Array` or `number[]` | `NaN` is a gap |
| `color` | `(string \| null)[]` or `Uint32Array` | Optional per-point colors, drawn by histograms only (see [Series types](https://ferrochart.com/docs/series#histogram)) |
All columns must have the same length.
```ts
candles.setData({
time: new BigInt64Array([1704067200000n, 1704067260000n, 1704067320000n]),
open: new Float64Array([100.0, 100.4, 100.1]),
high: new Float64Array([100.6, 100.5, 100.9]),
low: new Float64Array([99.8, 99.9, 100.0]),
close: new Float64Array([100.4, 100.1, 100.8]),
volume: new Float64Array([1200, 900, 1500]),
});
line.setData({ time: [1704067200000, 1704067260000], value: [100.4, 100.1] });
```
### Rows
An array of objects is also accepted: `OhlcRow` (`{ time, open, high, low,
close, volume? }`) for OHLC series and `ValueRow` (`{ time, value?, color? }`)
for value series. In rows, `time` can also be a `Date`.
```ts
candles.setData([
{ time: new Date('2024-01-01T00:00:00Z'), open: 100.0, high: 100.6, low: 99.8, close: 100.4 },
{ time: new Date('2024-01-01T00:01:00Z'), open: 100.4, high: 100.5, low: 99.9, close: 100.1 },
]);
line.setData([
{ time: 1704067200000, value: 100.4 },
{ time: 1704067260000 }, // no value: a gap
{ time: 1704067320000, value: 100.8 },
]);
```
A row without `value` (or with `NaN`) is a gap. A missing OHLC field throws an
error that names it (`data[3] has no 'open'`). If some rows have `volume` and
others not, the missing volumes are 0.
### Which to use
Rows are converted to columns before anything else happens, so both give the
same result. Use rows when your data already comes as objects (a JSON API, a
few hundred bars) and the code is simpler that way. Use columns for large data:
typed arrays are copied into the engine with one `memcpy` per column, with no
per-bar object to read, so `setData` with a million bars takes a few tens of
milliseconds. If you receive binary data (for example from a WebSocket or a
file), build typed arrays directly and skip objects altogether.
### Times
Times are UTC milliseconds since the Unix epoch, as whole numbers.
- `BigInt64Array` times are used as they are.
- `Float64Array` and `number[]` times are converted to integers; a value that is
not finite, has a fractional part, or is beyond ±9·10¹⁵ throws
(`time[5] is not an integer millisecond timestamp`).
- In rows and in `update`, `time` can be a number, a bigint or a `Date`.
If your source uses seconds, multiply by 1000.
The chart shows times in UTC.
## Validation
`setData` and `update` check the data first. If anything is wrong they throw,
and the series keeps its previous data.
| Rule | Error message |
|---|---|
| Times strictly increasing (no duplicates) | `time is not strictly increasing at index 7` |
| All columns as long as `time` | ``column `open` has a different length than `time` `` |
| Prices and volume finite, except gap bars | `invalid OHLC values in bar 12` |
| `high` ≥ max(`open`, `close`) and `low` ≤ min(`open`, `close`) | `invalid OHLC values in bar 12` |
| Columns are arrays of numbers / typed arrays | `column 'high' must be a Float64Array or an array of numbers` |
The index in the message is the position in the data you passed.
A bar whose four prices are all `NaN` is a gap bar (see [Gaps](https://ferrochart.com/docs/data#gaps)); it is
valid, and its volume is set to 0.
## Gaps
- In a value series, a `NaN` value (or a row without `value`) is a gap. Lines,
areas and baselines are interrupted there; histograms and points draw
nothing for it.
- In an OHLC series, a bar with `NaN` for open, high, low and close is a gap
and draws nothing.
`dataAt` returns `null` for a gap.
### Several series on one time axis
All series of a chart share one time axis: logical index 42 is the same time
in every series. When series have different times, the axis is the union of
their times. A series has no point at a time only the others have: OHLC
series, histograms and points show nothing there; lines, areas and baselines
connect the neighboring points. If new times fall between existing bars of the
axis, the axis is rebuilt and the chart sends a `warning` event.
## Bar quality flags
Use `setBarFlags` on candlestick, OHLC bar or Heikin-Ashi series to describe
data your application has filled in or clipped. Flags do not change the
prices; pass the prepared OHLC data first:
```ts
const start = Date.UTC(2024, 0, 1);
candles.setData([
{ time: start, open: 100, high: 102, low: 99, close: 101 },
{ time: start + 60_000, open: 101, high: 101, low: 101, close: 101 },
{ time: start + 120_000, open: 101, high: 104, low: 100, close: 103 },
]);
candles.applyOptions({ filledBarColor: '#78909c' });
candles.setBarFlags([
{ time: start + 60_000, filled: true },
{ time: start + 120_000, clipped: true },
]);
// Clear all quality flags when they are no longer needed:
// candles.setBarFlags([]);
```
- `filled` marks a bar your source synthesized without real trades. It is
drawn hollow in `filledBarColor` (by default the series' main color at
40% opacity). A truly missing bar can instead be a [gap](https://ferrochart.com/docs/data#gaps); this flag
does not fill missing data for you.
- `clipped` marks a bar whose outlier wick you clipped. A tick appears at
each end of its wick. Keep the raw high/low values in your application,
keyed by time, and show them in your tooltip; the chart only has the
clipped values you supplied. Both flags can be set on one bar.
- Each call replaces all flags; `[]` clears them. Times are UTC milliseconds
(or `Date`/`bigint`, as for data); for duplicate times the last entry wins.
When zooming out merges bars, the merged bar is filled only if all its
bars are filled, and clipped if any is clipped.
Python uses `candles.set_bar_flags(times, filled=..., clipped=...)`, with
boolean arrays of the same length as `times`, and
`candles.apply_options(filled_bar_color="#78909c")`. See
[Python](https://ferrochart.com/docs/python#options-indicators-and-drawings) and
[Series options](https://ferrochart.com/docs/series#series-options).
## Real-time updates
`update` changes the last bar or adds a new one:
- Same time as the last bar: replaces it (the forming bar).
- Later time: appends a new bar.
- Earlier time: throws.
```ts
// OHLC series
candles.update({ time: 1704067380000, open: 100.8, high: 101.2, low: 100.7, close: 101.0, volume: 300 });
// Value series
line.update({ time: 1704067380000, value: 101.0 });
```
The bar is validated like `setData` data. Replacing the last bar does not
allocate memory, and the chart redraws at most once per animation frame, so
calling `update` on every trade is fine. Indicators on the series are updated
incrementally. A volume series follows its source; it has no `update` of its
own.
For a transform series (Renko, Kagi and so on), each `update` is an input bar
or tick and the drawn elements change accordingly; see
[Bar transforms](https://ferrochart.com/docs/series#bar-transforms).
### Appending a batch
To add several bars at the end (a batch from your feed after a reconnect,
say), call `append` with columns or rows, in any form `setData` takes. Times
must come after the last bar, and the volume column must be present exactly
when the series has one; otherwise it throws and the data stays as it was.
```ts
candles.append([
{ time: 1704067440000, open: 101.0, high: 101.4, low: 100.9, close: 101.3, volume: 250 },
{ time: 1704067500000, open: 101.3, high: 101.5, low: 101.1, close: 101.2, volume: 180 },
]);
```
Use `update` for the forming bar, `append` for finished bars that arrive
together.
## Loading older history
`prepend` inserts older bars before the first one, in any form `setData`
takes. The bars already there keep their logical indices; the new ones get
negative indices (the bar before index 0 is -1). The view does not move, and
indicators on the series are recomputed. Times must come before the first bar;
the volume rule is the same as for `append`.
The chart tells you when to load: the `needMoreHistory` event is sent when
fewer bars than one screen width are left before the left edge of the view.
`barsBeforeStart` is the number of bars left (negative when empty space before
the data is already visible). It is sent once per first bar: after a
`prepend` the first bar is a new one, so the event comes again when the user
scrolls close to it.
### Worked example
```ts
import { FerroChart, type OhlcRow } from '@ferrochart/core';
// Your backend: up to `count` bars that end before `beforeMs`, oldest first.
declare function fetchBars(symbol: string, beforeMs: number, count: number): Promise;
const chart = await FerroChart.create(canvas);
const candles = chart.addCandlestickSeries();
chart.addVolumeSeries(candles);
const latest = await fetchBars('BTCUSD', Date.now(), 1000);
candles.setData(latest);
let first = Number(latest[0]?.time ?? Date.now());
let loading = false;
let exhausted = false;
chart.on('needMoreHistory', async () => {
if (loading || exhausted) return;
loading = true;
try {
// Only bars before the first one: an overlapping bar would make prepend throw.
const older = (await fetchBars('BTCUSD', first, 1000)).filter((b) => Number(b.time) < first);
if (older.length === 0) {
exhausted = true; // the backend has nothing older
return;
}
candles.prepend(older);
first = Number(older[0].time);
} finally {
loading = false;
}
});
```
The `loading` flag guards against overlapping requests from your own code
(the event itself does not repeat for the same first bar). Live bars keep
going through `update` meanwhile: `prepend` and `update` work on opposite
ends.
## Reading data back
| Method | Returns |
|---|---|
| `series.dataAt(index)` | `{ open, high, low, close, volume }` for OHLC series (`volume` is `null` without a volume column), `{ value }` for value series; `null` for a gap or outside the data |
| `chart.timeAtIndex(index)` | Time (UTC ms) of the bar at a logical index, `null` outside the data |
| `chart.indexOfTime(time)` | Logical index of the bar with exactly that time, `null` if there is none |
| `chart.dataRange()` | `{ from, to }`: logical indices of the first and last bar; `null` without data |
Fractional indices are rounded to the nearest bar.
```ts
const range = chart.dataRange();
if (range) {
const last = candles.dataAt(range.to); // the forming bar
const t = chart.timeAtIndex(range.to); // its time
console.log(t, last);
}
const i = chart.indexOfTime(Date.UTC(2024, 0, 2, 9, 30));
if (i !== null) console.log(candles.dataAt(i));
```
For a series with a `shift`, `dataAt(index)` returns the point drawn at
`index`.
## Logical indices
Every bar has a logical index. Visible ranges, crosshair positions and clicks
are reported in these indices, and they are what `setVisibleLogicalRange` and
`logicalToCoordinate` take; see [Time scale and viewport](https://ferrochart.com/docs/time-scale). All
series share the time axis, so index `i` is the same time in every series.
The first bar has index 0 after `setData`. Indices are fractional where
positions between bars matter (the edges of the view, the pointer): bar `i`
covers `i - 0.5` to `i + 0.5`.
## Level of detail
Bars are stored as columns: one array of times, one of opens, and so on. This
is what keeps loading fast and memory small: about 58 bytes per bar including
the time index and the level-of-detail pyramid.
When you zoom out until several bars share a pixel, FerroChart draws aggregated
bars from a precomputed pyramid (each level halves the count, keeping the true
high and low). The number of things drawn per frame is therefore bounded by
the screen width — about four per physical pixel — whatever the data size.
All data changes are incremental internally: the renderer is told which range
changed and uploads only that.
## Volume
A volume series reads the volume column of an OHLC series:
`chart.addVolumeSeries(candles)`. It has no data of its own; pass `volume` to
the candles' `setData` and `update`. See [Series types](https://ferrochart.com/docs/series#volume).
## Example: a simulated live feed
A chart with 500 bars of history and a new price every 250 ms. A new
one-minute bar starts whenever the clock passes a minute boundary.
```ts
import { FerroChart, randomWalk, type Bar } from '@ferrochart/core';
const chart = await FerroChart.create(canvas, { theme: 'dark' });
const candles = chart.addCandlestickSeries();
chart.addVolumeSeries(candles);
const interval = 60_000;
const now = Date.now();
const start = Math.floor(now / interval) * interval - 500 * interval;
const history = randomWalk(42, 500, start, interval); // deterministic demo data
candles.setData(history);
const n = history.close.length;
let bar: Bar = {
time: Number(history.time[n - 1]),
open: history.open[n - 1],
high: history.high[n - 1],
low: history.low[n - 1],
close: history.close[n - 1],
volume: history.volume?.[n - 1] ?? 0,
};
const timer = setInterval(() => {
const t = Math.floor(Date.now() / interval) * interval;
const price = bar.close * (1 + (Math.random() - 0.5) * 0.002);
const size = Math.round(Math.random() * 10);
if (t > Number(bar.time)) {
// A new minute: open a new bar at the last close.
bar = { time: t, open: bar.close, high: Math.max(bar.close, price), low: Math.min(bar.close, price), close: price, volume: size };
} else {
bar = { ...bar, high: Math.max(bar.high, price), low: Math.min(bar.low, price), close: price, volume: (bar.volume ?? 0) + size };
}
candles.update(bar); // same time: replaces, later time: appends
}, 250);
// When the chart goes away:
// clearInterval(timer); chart.destroy();
```
The view keeps its distance from the latest bar (the right offset), so each
appended bar scrolls the content one bar to the left, whether the user is
looking at the latest data or has scrolled back. `chart.scrollToRealtime()`
brings the latest bar back into view (see
[Time scale and viewport](https://ferrochart.com/docs/time-scale#right-offset)).
---
Source: https://ferrochart.com/docs/transitions
# Transitions
When you replace a chart's data (another period, another chart type, another
symbol) the new picture normally appears at once. A transition turns that
switch into a short animation from the picture on screen to the new one. This
chapter covers what moves during a transition, how to start one, and its
limits.
## What moves
A transition is started with `kind: 'morph'` (the default) or `kind: 'fade'`.
**Switching periods (morph).** Each old bar is matched with every new bar
whose time interval it overlaps:
- Several old bars merge into one new bar (1m to 5m).
- One old bar splits into several new bars (5m to 1m).
- An old bar that crosses a boundary of the new period flows into both new
bars. This is why any two periods work, also ones that don't divide each
other evenly, such as 45m and 1h.
The bar spacing stays the same and the time at the right edge of the view
stays where it is. Going to a longer period therefore shows a longer stretch
of time, and the camera zooms out; going to a shorter one zooms in. The price
scale moves to the new range at the same time.
**Switching chart types (morph).** Candles shrink to their closes and become a
line, and a line grows into candles. Candles, Heikin-Ashi and OHLC bars morph
into each other.
**Switching symbols (fade).** The prices of two symbols have nothing in
common, so nothing is matched. The price scale changes to the new symbol's
range at once, and the old picture fades out over the new one.
Whatever the kind, the last frame of a transition is exactly the picture you
would get by switching without one. Markers, drawings, price lines and axis
labels follow the moving view.
## Starting a transition
Call `chart.beginTransition(options?)`, then change the data before the next
frame is drawn: `setData`, `addSeries` (and the other `add*Series` methods),
`series.remove()` and `addIndicator`. Everything changed until the next frame
belongs to the transition.
| Option | Type | Default | Meaning |
|---|---|---|---|
| `duration` | `number` | `350` | Length in milliseconds; 0 switches at once |
| `kind` | `'morph' \| 'fade'` | `'morph'` | `'morph'` for periods and chart types, `'fade'` for symbols |
An invalid duration (negative, not finite) or an unknown kind throws.
| Method | Does |
|---|---|
| `beginTransition(options?)` | Starts a transition for the changes made before the next frame |
| `finishTransition()` | Ends the transition now and shows the new picture |
| `transitionProgress()` | Progress of the running transition, from 0 to 1, linear in time (before easing); `null` when none runs |
### Example: switching periods
Here the page keeps one-minute bars and aggregates them into the chosen
period. Loading the bars of the new period from your backend works the same
way: call `beginTransition` right before `setData`.
```ts
import { FerroChart, type OhlcRow } from '@ferrochart/core';
declare const minuteBars: OhlcRow[]; // oldest first, time in UTC ms
function aggregate(bars: OhlcRow[], periodMs: number): OhlcRow[] {
const out: OhlcRow[] = [];
for (const b of bars) {
const t = Math.floor(Number(b.time) / periodMs) * periodMs;
const last = out[out.length - 1];
if (last && last.time === t) {
last.high = Math.max(last.high, b.high);
last.low = Math.min(last.low, b.low);
last.close = b.close;
last.volume = (last.volume ?? 0) + (b.volume ?? 0);
} else {
out.push({ time: t, open: b.open, high: b.high, low: b.low, close: b.close, volume: b.volume ?? 0 });
}
}
return out;
}
const chart = await FerroChart.create(canvas);
const candles = chart.addCandlestickSeries();
chart.addVolumeSeries(candles);
candles.setData(aggregate(minuteBars, 60 * 60_000)); // 1h
function setPeriod(periodMs: number) {
chart.beginTransition(); // 350 ms morph
candles.setData(aggregate(minuteBars, periodMs));
}
setPeriod(45 * 60_000); // 1h -> 45m
```
With bars from a server, fetch first and start the transition when the data
has arrived, so the animation does not wait for the network:
```ts
async function loadPeriod(period: string) {
const bars = await fetchBars('BTCUSD', period); // your backend
chart.beginTransition({ duration: 400 });
candles.setData(bars);
}
```
### Example: switching chart types
To go from candles to a line of closes, remove the candle series and add a
line series with the same times:
```ts
let candles: Series | null = chart.addCandlestickSeries();
candles.setData(bars);
let line: Series | null = null;
function showLine() {
if (!candles) return;
chart.beginTransition();
candles.remove();
candles = null;
line = chart.addSeries('line', { color: '#2962ff' });
line.setData({ time: bars.map((b) => b.time), value: bars.map((b) => b.close) });
}
function showCandles() {
if (!line) return;
chart.beginTransition();
line.remove();
line = null;
candles = chart.addCandlestickSeries();
candles.setData(bars);
}
```
Candles, Heikin-Ashi and OHLC bars are switched the same way.
### Example: switching symbols
```ts
async function loadSymbol(symbol: string) {
const bars = await fetchBars(symbol, '1h');
chart.beginTransition({ kind: 'fade' });
candles.setData(bars);
}
```
### Indicator series your page computes
Indicators added with `addIndicator` follow their source series. If instead
your page computes its own series from the bars (a moving average drawn as a
line series, say), replace or clear them in the same transition, before
`setData` of the main series:
```ts
chart.beginTransition();
sma.setData(computeSma(newBars, 20)); // or sma.remove()
candles.setData(newBars);
```
All series share one time axis. A series still holding values at the old
bars' times keeps those times on the axis, and the new bars would not get the
spacing you expect.
## Interrupting
- Gestures end a running transition at once, at its new picture: a press,
the wheel, a pinch, a key, a double-click. Moving the pointer does not; the
crosshair is hidden while the transition runs and comes back at its end.
- `finishTransition()` ends it from your code.
- Calling `beginTransition` again during a period switch (the user clicks
through several periods quickly) starts the next one from the picture on
screen at that moment, so the motion has no jump. A running type switch or
fade first jumps to its end.
## Reduced motion
While the system asks for reduced motion (`prefers-reduced-motion: reduce`),
`beginTransition` switches at once. To animate anyway, pass
`respectReducedMotion: false` when creating the chart:
```ts
const chart = await FerroChart.create(canvas, { respectReducedMotion: false });
```
## Limits
- Area and baseline series (and points and step lines) are not morphed from
one type into another. They are drawn as usual during the transition, at
their new data.
- When very many bars are visible (several per pixel of the chart's width),
the bars switch at once and only the camera and the price scale animate.
To make the price scale also ease after the transition, during live updates
and while panning, see [Smoothing](https://ferrochart.com/docs/price-scale#smoothing).
## Python
```python
chart.begin_transition() # duration=350, kind="morph"
candles.set_data(df_45m)
chart.begin_transition(duration=500, kind="fade")
candles.set_data(other_symbol)
chart.finish_transition()
p = chart.transition_progress() # 0.0 to 1.0, None when none runs
```
A duration of 0 or less switches at once. `to_png` and `render_png` finish a
running transition first: an image has no clock, so it shows the new picture.
## Rust
```rust
use ferrochart_core::chart::{Transition, TransitionKind};
chart.begin_transition(Transition { duration_ms: 350.0, kind: TransitionKind::Morph });
// or: chart.begin_transition(Transition::default());
chart.set_data(series, SeriesData::Ohlc(bars_5m))?;
// In your render loop: each frame advances it.
chart.build_frame(now_ms, &text);
if chart.is_animating() {
// request another frame
}
chart.finish_transition();
let p: Option = chart.transition_progress();
```
The transition advances with the `now_ms` you pass to `build_frame`, and
`is_animating()` is true while it runs. A duration of 0, negative or `NaN`
switches at once.
## C
```c
ferrochart_begin_transition(chart, 350.0f, FERROCHART_TRANSITION_MORPH);
ferrochart_set_data_ohlc(chart, candles, time, open, high, low, close, vol, n);
/* FERROCHART_TRANSITION_FADE for a symbol switch */
ferrochart_finish_transition(chart);
float p;
ferrochart_transition_progress(chart, &p); /* 0 to 1; -1 when none */
```
The transition advances with the `now_ms` you pass to `ferrochart_render` or
`ferrochart_render_rgba`; `ferrochart_needs_redraw` returns 1 while it runs.
---
Source: https://ferrochart.com/docs/price-scale
# Price scale and panes
A chart is a stack of panes that share the time axis. Each pane has its own
price scale on the right. This chapter covers creating and sizing panes,
placing series on them, and the price scale options.
## Panes
A new chart has one pane, the main pane. `chart.mainPane` is the id of the top
pane, the default for every method that takes an optional pane.
```ts
const main = chart.mainPane;
const volumePane = chart.addPane(0.25); // below the others, a quarter of the main pane's height
const oscPane = chart.addPane(0.3);
console.log(chart.panes()); // [main, volumePane, oscPane], top to bottom
```
| Method | Does |
|---|---|
| `addPane(stretch?)` | Adds a pane below the others and returns its id. `stretch` is its height relative to the other panes (default 1); it must be a finite number above 0, or `addPane` throws. |
| `removePane(pane)` | Removes a pane with its series, drawings and layer plugins. The last pane cannot be removed. |
| `panes()` | Pane ids, top to bottom. |
| `mainPane` | Id of the top pane. |
| `setPaneStretch(pane, stretch)` | Changes a pane's relative height. `stretch` must be finite and positive. |
| `paneStretch(pane)` | A pane's relative height, `undefined` for an unknown id. |
Heights are proportional to the stretch factors: with factors 1, 0.25 and 0.3
the panes get 1/1.55, 0.25/1.55 and 0.3/1.55 of the height available. Users
can drag the separator between two panes, which changes the factors of those
two panes.
Pane ids are not reused after a pane is removed. If you remove the top pane,
the next one becomes the main pane. Apart from `paneStretch`, methods given an
unknown pane id throw.
```ts
chart.setPaneStretch(oscPane, 0.5);
console.log(chart.paneStretch(oscPane)); // 0.5
chart.removePane(oscPane); // its series go with it
```
Pane layout (the number of panes, their stretch factors and price scale
settings) is part of the saved state; see [Saving state](https://ferrochart.com/docs/state).
## Putting series on panes
Every method that adds a series takes the pane as its last argument; without
it the series goes on the main pane. `series.pane` tells where a series is.
```ts
const candles = chart.addCandlestickSeries(); // main pane
const sma = chart.addSeries('line', { color: '#2962ff' });
const pane = chart.addPane(0.3);
const rsi = chart.addSeries('line', { color: '#7e57c2' }, pane);
rsi.setData(rsiValues);
console.log(rsi.pane === pane); // true
```
A series stays on its pane; to move it, remove it and add it again on the
other pane. Indicators choose their pane through a placement argument; see
[Indicators](https://ferrochart.com/docs/indicators).
All series of a pane share its price scale and are auto-scaled together.
### Volume placement
`addVolumeSeries(source, pane?)` behaves differently depending on what else is
on the pane:
- **On a pane with price series** (the default: the main pane, next to the
candles), the volume has a separate scale of its own and occupies the bottom
quarter of the pane. It does not affect the price range, and the price axis
keeps showing prices.
- **On a pane of its own**, the volume uses the pane's price scale and fills
the pane: the bars stand on the bottom edge (bottom margin 0), and the axis
labels use K, M and B suffixes (`1.25M`).
```ts
// Volume under the candles, in the same pane.
chart.addVolumeSeries(candles);
// Or in a pane of its own below.
const volPane = chart.addPane(0.25);
chart.addVolumeSeries(candles, volPane);
```
## The price scale
`applyPriceScaleOptions(options, pane?)` changes the price scale of a pane
(default: the main pane); keys you leave out keep their value. It is all or
nothing: if one value is invalid it throws and the scale keeps every option it
had. `priceScale(pane?)` returns all of them.
```ts
chart.applyPriceScaleOptions({ mode: 'logarithmic' });
chart.applyPriceScaleOptions({ margins: { top: 0.2, bottom: 0.1 } }, pane);
const s = chart.priceScale();
// { mode: 'logarithmic', autoScale: true, inverted: false,
// margins: { top: 0.1, bottom: 0.1 }, range: { low: 98.2, high: 112.7 },
// smoothing: 0 }
```
| Option | Type | Default | Meaning |
|---|---|---|---|
| `mode` | `'normal' \| 'logarithmic' \| 'percentage' \| 'indexedTo100'` | `'normal'` | How prices map to heights, see [Modes](https://ferrochart.com/docs/price-scale#modes) |
| `autoScale` | `boolean` | `true` | Whether the range follows the visible data |
| `inverted` | `boolean` | `false` | Higher prices drawn lower |
| `margins` | `{ top, bottom }` | `{ top: 0.1, bottom: 0.1 }` | Empty space above and below the data, as fractions of the pane height |
| `range` | `{ low, high }` | follows the data | The price range shown (without margins). Setting it turns auto-scaling off. |
| `smoothing` | `number` | `0` | Time constant in ms with which auto-scaling eases to a new range, see [Smoothing](https://ferrochart.com/docs/price-scale#smoothing) |
`priceScale().range` is always the range currently shown, also while
auto-scaling.
The options are applied in the order `mode`, `margins`, `inverted`, `range`,
`autoScale`, `smoothing`. An invalid value throws and leaves the scale as it
was: either all the options are applied or none.
### Modes
| Mode | Axis shows |
|---|---|
| `'normal'` | Prices on a linear scale |
| `'logarithmic'` | Prices on a logarithmic scale: equal distances are equal ratios. Useful for long histories with large price changes. |
| `'percentage'` | Percent change from the first visible value: (p − base) / \|base\| × 100, labelled with 2 decimals and `%` |
| `'indexedTo100'` | Prices indexed to 100 at the first visible value: p / \|base\| × 100, labelled with 2 decimals |
In `'percentage'` and `'indexedTo100'` mode every series of the pane is
normalized to its own first visible value: the close of the first visible bar,
or the first visible value of a value series. Series with very different price
levels can then be compared on one scale. As the user pans, the base moves
with the first visible bar. The range, axis labels and crosshair price are in
percent or index points.
Switching between a price mode (`'normal'`, `'logarithmic'`) and a relative mode
(`'percentage'`, `'indexedTo100'`) turns auto-scaling on, because the old range
is in other units.
### Auto-scale and fixed ranges
By default the range follows the high and low of the visible data of all
series on the pane (plus the margins), and updates as you pan, zoom or receive
new data. Setting `range` fixes it:
```ts
chart.applyPriceScaleOptions({ range: { low: 90, high: 110 } }); // autoScale is now false
chart.applyPriceScaleOptions({ autoScale: true }); // follow the data again
```
`low` must be below `high`, both finite; in logarithmic mode `low` must be
above 0. In the relative modes the range is in percent or index points.
`range` turns auto-scaling off, so `{ range, autoScale: true }` contradicts
itself and throws; `{ range, autoScale: false }` is fine.
Users can also change the range: dragging the price axis or the wheel over
it (or Alt + wheel in the plot) scales prices, and turns auto-scaling off.
Double-clicking the price axis turns it back on. See
[Gestures and keyboard](https://ferrochart.com/docs/interaction#gestures).
### Margins
`margins` keep the data away from the top and bottom edges of the pane. Both
values must be from 0 up to (not including) 1, and their sum must be below 1.
Both keys are required.
```ts
// Leave the top 30 % free for a legend.
chart.applyPriceScaleOptions({ margins: { top: 0.3, bottom: 0.05 } });
```
### Inverted
`inverted: true` flips the scale: higher prices are drawn lower. This is
sometimes used for bond yields against prices, or for an inverse pair.
```ts
chart.applyPriceScaleOptions({ inverted: true });
```
### Smoothing
By default an auto-scaled range jumps to the new high and low as soon as the
visible data needs it. `smoothing` makes it ease there instead: it is a time
constant in milliseconds (default 0, off). With smoothing on, the range glides
when live updates push the price past the edge, while panning and zooming, and
after a [transition](https://ferrochart.com/docs/transitions).
```ts
chart.applyPriceScaleOptions({ smoothing: 150 });
console.log(chart.priceScale().smoothing); // 150
```
Only automatic changes are smoothed. Dragging the price axis, resetting it
with a double-click and turning `autoScale` on change the range at once.
`smoothing` must be a finite number of 0 or more, or it throws.
In the other languages:
| Language | Call |
|---|---|
| Python | `chart.apply_price_scale_options(smoothing=150)` |
| Rust | `chart.price_scale(pane, ScaleSide::Right)` then `.set_smoothing_ms(150.0)?` |
| C | `ferrochart_set_price_smoothing(chart, FERROCHART_MAIN_PANE, FERROCHART_SCALE_RIGHT, 150.0f)` |
## Example: comparing two symbols
Two line series on one pane in percentage mode show relative performance from
the left edge of the view.
```ts
const a = chart.addSeries('line', { color: '#2962ff' });
const b = chart.addSeries('line', { color: '#ff6d00' });
a.setData({ time, value: closesA }); // around 180
b.setData({ time, value: closesB }); // around 0.95
chart.applyPriceScaleOptions({ mode: 'percentage' });
```
## Example: a three-pane layout
Candles with a moving average on the main pane, volume below, an oscillator at
the bottom.
```ts
const candles = chart.addCandlestickSeries();
candles.setData(bars);
const volPane = chart.addPane(0.2);
chart.addVolumeSeries(candles, volPane);
const oscPane = chart.addPane(0.25);
const osc = chart.addSeries('histogram', { color: '#26a69a' }, oscPane);
osc.setData({ time: bars.time, value: oscillator });
// Fixed range for the oscillator, a little room at the top of the main pane.
chart.applyPriceScaleOptions({ range: { low: -1, high: 1 } }, oscPane);
chart.applyPriceScaleOptions({ margins: { top: 0.15, bottom: 0.1 } });
```
---
Source: https://ferrochart.com/docs/time-scale
# Time scale and viewport
The time scale decides which bars are visible and how wide they are. It is
shared by all panes. This chapter covers bar spacing, the right offset, the
visible range, converting between pixels, logical indices and times, and the
events that report view changes.
## Logical indices
The time scale works in logical indices, not times. After `setData` the first
bar has index 0, the next 1, and so on; bar `i` is centered on `i` and covers
`i − 0.5` to `i + 0.5`. Positions between bars and beyond the data have
fractional or out-of-range indices. Use `timeAtIndex` and `indexOfTime` to
convert to and from times (see [Data](https://ferrochart.com/docs/data#reading-data-back)).
Indices count bars, not time: a weekend or a trading halt with no bars takes
no space.
## Bar spacing
The bar spacing is the distance between the centers of two neighboring bars,
in CSS pixels. Zooming changes it.
```ts
console.log(chart.barSpacing); // 6 on a new chart
chart.setBarSpacing(12); // zoom in
```
| | Value |
|---|---|
| Default | 6 CSS px |
| Smallest | 0.5 CSS px, or less when needed to show all data at once (90 % of the plot width divided by the number of bars) |
| Largest | `maxBarSpacing`, default 50 CSS px |
`setBarSpacing` clamps the value to this range. Values that are not finite and
positive are ignored. The bar at the right edge stays in place.
The largest spacing is set when the chart is created:
```ts
const chart = await FerroChart.create(canvas, { maxBarSpacing: 200 });
```
`maxBarSpacing` must be a number of at least 1, or `create` rejects. Raise it
when single bars need room: footprint numbers need more than 60 px, TPO
letters several hundred (see [Order flow](https://ferrochart.com/docs/orderflow)).
## Right offset
The right offset is the empty space between the last bar and the right edge
of the plot, in bars. It can be fractional and negative (the last bar is then
beyond the right edge, which is how a view of older data is described).
```ts
console.log(chart.rightOffset); // 3 on a new chart
chart.setRightOffset(10); // more room for the forming bar
chart.scrollToRealtime(); // back to the latest bar, with the default offset of 3
```
`setRightOffset` keeps at least one bar on screen; values outside that are
clamped, and values that are not finite are ignored.
The view is anchored to the latest bar by the right offset. When `update` or
`setData` adds bars at the end, the right offset stays the same, so the content
moves left by one bar per new bar. While the user looks at the latest data,
new bars scroll into view; when they have scrolled back, the bars they look at
move left too. `scrollToRealtime()` brings the latest bar back.
## The visible range
`visibleLogicalRange()` returns the logical indices at the left and right edges
of the plot, as fractional numbers:
```ts
const { from, to } = chart.visibleLogicalRange();
const visibleBars = to - from;
```
`setVisibleLogicalRange(from, to)` shows exactly that range across the plot,
as far as the spacing limits allow (if they don't, the right edge is kept):
```ts
// The last 100 bars.
const data = chart.dataRange();
if (data) chart.setVisibleLogicalRange(data.to - 99.5, data.to + 0.5);
```
`from` must be below `to`, both finite; otherwise it throws and the view is
unchanged. You can call it right after `create`, before the first frame:
the range is applied as soon as the plot width is known. Panning or zooming
before that cancels it.
`fitContent()` shows all bars, from the left edge to the right edge, with no
right offset. With few bars, the largest bar spacing may leave space on the
left. Like `setVisibleLogicalRange`, it waits for the plot width.
`dataRange()` returns the indices of the first and last bar (`null` without
data), for computing ranges relative to the data:
```ts
const data = chart.dataRange();
if (data) {
// The first 200 bars.
chart.setVisibleLogicalRange(data.from - 0.5, data.from + 199.5);
}
```
### A range by time
Convert times to indices with `indexOfTime`. It needs a bar with exactly that
time; to find the nearest bar for an arbitrary time, search your own copy of
the times.
```ts
function showTimes(fromMs: number, toMs: number) {
const a = chart.indexOfTime(fromMs);
const b = chart.indexOfTime(toMs);
if (a !== null && b !== null && a < b) chart.setVisibleLogicalRange(a - 0.5, b + 0.5);
}
```
## Pixels, indices and times
| Method | Converts |
|---|---|
| `logicalToCoordinate(index)` | Logical index → x of the bar's center, CSS px from the canvas' left edge |
| `coordinateToLogical(x)` | x (CSS px from the canvas' left edge) → logical index, fractional |
| `timeAtIndex(index)` | Logical index → time (UTC ms) of that bar, `null` outside the data; rounds to the nearest bar |
| `indexOfTime(time)` | Time → logical index of the bar with exactly that time, `null` if there is none |
The coordinates refer to the layout of the last frame, so use them after the
first frame (for example in an event handler). x coordinates are the same in
every pane.
```ts
// The bar under a point of the canvas.
canvas.addEventListener('dblclick', (e) => {
const rect = canvas.getBoundingClientRect();
const index = Math.round(chart.coordinateToLogical(e.clientX - rect.left));
const time = chart.timeAtIndex(index);
if (time !== null) console.log(new Date(time).toISOString(), candles.dataAt(index));
});
// Position an HTML element over a bar.
function placeOverBar(el: HTMLElement, time: number) {
const index = chart.indexOfTime(time);
if (index === null) return;
el.style.left = `${chart.logicalToCoordinate(index)}px`;
}
```
For the crosshair and clicks, the events already carry the logical index,
time and price; see [Crosshair and events](https://ferrochart.com/docs/crosshair-events).
## The visibleRangeChanged event
`visibleRangeChanged` is sent whenever the visible logical range changes: by a
gesture, by one of the methods above, by a resize, or by data that moves the
view.
```ts
chart.on('visibleRangeChanged', ({ from, to }) => {
const a = chart.timeAtIndex(Math.ceil(from));
const b = chart.timeAtIndex(Math.floor(to));
label.textContent = a !== null && b !== null
? `${new Date(a).toISOString()} – ${new Date(b).toISOString()}`
: '';
});
```
Events are delivered after the frame that produced them, at most once per
frame: during a fast pan you get the latest range, not every intermediate one.
Nothing is sent while the chart has no data. Remove a listener with
`chart.off('visibleRangeChanged', callback)`.
The same frame may also send `needMoreHistory` when the view comes within one
screen of the first bar; see [Loading older history](https://ferrochart.com/docs/data#loading-older-history).
### Keeping the view across a reload
Loading older bars with `prepend` keeps every logical index and the view.
`setData` numbers the bars from 0 again, so logical indices change; times do
not. To restore a view after replacing the data (another symbol with the same
timestamps, say), save it as times:
```ts
function saveView() {
const { from, to } = chart.visibleLogicalRange();
return { from: chart.timeAtIndex(from), to: chart.timeAtIndex(to) };
}
function restoreView(view: { from: number | null; to: number | null }) {
if (view.from === null || view.to === null) return chart.fitContent();
const a = chart.indexOfTime(view.from);
const b = chart.indexOfTime(view.to);
if (a !== null && b !== null && a < b) chart.setVisibleLogicalRange(a, b);
}
```
To save the bar spacing and right offset together with drawings and pane
layout, use `saveState` (see [Saving state](https://ferrochart.com/docs/state)). To keep several charts
on the same range, see [Syncing charts](https://ferrochart.com/docs/sync).
## User gestures
These inputs change the time scale (see [Gestures and keyboard](https://ferrochart.com/docs/interaction)
for the full table):
| Input | Effect |
|---|---|
| Drag in the plot | Pan (release while moving: kinetic scrolling) |
| Wheel / trackpad scroll | Zoom time around the pointer |
| Horizontal scroll or Shift + wheel | Pan |
| Pinch (trackpad, two fingers) | Zoom |
| Drag the time axis | Change the bar spacing |
| Double-click the time axis | Reset the bar spacing |
| ← → | Pan by 10 % |
| ↑ ↓ | Zoom |
| Home / End | Jump to the first / latest bar |
Zooming keeps the bar under the pointer in place. Every change sends
`visibleRangeChanged`.
---
Source: https://ferrochart.com/docs/crosshair-events
# Crosshair and events
The chart reports what happens on it through events: the crosshair moving, a
click, the visible range changing, drawings being created or edited, and a few
more. This chapter lists every event, its payload and when it fires, and shows
two common uses: a legend that follows the crosshair and reacting to clicks on
markers and series.
## Crosshair modes
The crosshair follows the pointer over a plot. Its vertical line crosses every
pane; the horizontal line and the price label belong to the pane under the
pointer. The time label is on the time axis.
| Mode | Behaviour |
|---|---|
| `'normal'` (default) | x snaps to the nearest bar center, y follows the pointer |
| `'magnet'` | As `'normal'`, and y snaps to the nearest of the bar's open, high, low and close (of the first price series in the pane) |
| `'hidden'` | No crosshair is drawn, and `crosshairMove` reports `null` |
```ts
chart.setCrosshairMode('magnet');
console.log(chart.crosshairMode); // 'magnet'
```
An unknown mode throws. The mode is part of the saved state
(`saveState().crosshairMode`, see [Saving state](https://ferrochart.com/docs/state)).
The magnet mode also applies while placing drawings: anchors snap to the
nearest open, high, low or close (see [Drawing tools](https://ferrochart.com/docs/drawings)).
## Subscribing
```ts
import type { ChartEventMap } from '@ferrochart/core';
const onMove = (e: ChartEventMap['crosshairMove']) => {
console.log(e.point?.time);
};
chart.on('crosshairMove', onMove);
// later
chart.off('crosshairMove', onMove);
```
- `on(name, callback)` adds a listener. An unknown event name throws.
- `off(name, callback)` removes it. Pass the same function object you passed
to `on`.
- Adding the same function twice calls it twice; `off` removes both.
- Callbacks may call any chart method, including `on` and `off`.
- An exception thrown inside a callback is reported like an uncaught error
(`reportError`: it appears in the console and reaches `window.onerror`).
The other callbacks still run.
The callback parameter is typed from the event name, so
`chart.on('crosshairMove', (e) => e.point?.time)` needs no annotation.
`ChartEventMap[name]` (exported by the package) names a payload type when you
declare the callback separately, as above.
## Delivery timing
The chart draws in `requestAnimationFrame`. Each frame, it first applies the
input and API calls made since the last frame, builds and renders the frame,
and then delivers the events that frame produced. Consequences:
- Events are never delivered inside the DOM input handler or inside the method
call that caused them. `chart.drawings.add(...)` returns the id at once; the
`drawingCreated` event for it arrives after the next frame.
- At most one frame's worth of events is delivered at a time. If the
crosshair moved several times since the last frame, you get one
`crosshairMove` with the latest position, not one per pointer event. The
same holds for `visibleRangeChanged` and `sync`.
- Browsers pause `requestAnimationFrame` in background tabs, so events are
delayed until the tab is visible again.
## Lifetime
The chart keeps itself running through listeners on its canvas and the
window, which hold only weak references to it. Keep a reference to the
`FerroChart` object for as long as it is on the page. If the object is
garbage-collected, the chart stops drawing and stops sending events. When you
are done with a chart, call `destroy()`: it removes all event listeners (yours
and the DOM ones) and releases the GPU resources. The object cannot be used
afterwards.
```ts
chart.destroy();
```
## Event reference
| Event | Payload | Fires when |
|---|---|---|
| `click` | `ClickEvent` | A press and release in a plot that moved at most 3 CSS px |
| `crosshairMove` | `{ point: CrosshairPoint \| null }` | The crosshair moved to another bar, pane or price, or left the plot |
| `visibleRangeChanged` | `{ from, to }` | The visible logical range changed |
| `needMoreHistory` | `{ barsBeforeStart }` | The left edge of the view came within one screen of the first bar |
| `drawingCreated` | `{ id }` | A drawing was created |
| `drawingModified` | `{ id }` | A drawing was moved, restyled or had a parameter changed |
| `drawingRemoved` | `{ id }` | A drawing was removed |
| `drawingSelected` | `{ id: number \| null }` | The selected drawing changed |
| `sync` | `{ message: SyncMessage }` | The chart posted a message to its sync group |
| `drawingSync` | `{}` | The chart has drawing sync operations waiting to be taken |
| `warning` | `ChartWarning` | The chart adjusted something on its own |
| `markerHover` | `MarkerHoverEvent \| null` | The pointer moved onto a marker or a "+k" badge, or off it |
| `priceLineDrag` | `PriceLineDragEvent` | The user drags a draggable price line |
### click
```ts
interface ClickEvent {
x: number; // CSS px from the canvas' top-left corner
y: number;
pane: number; // pane id
logicalIndex: number; // fractional logical index at x
time: number | null; // UTC ms of the nearest bar, null beyond the data
price: number; // price at y on the pane's price scale
target: ClickTarget | null;
}
type ClickTarget =
| { type: 'priceLine'; id: number }
| { type: 'drawing'; id: number }
| { type: 'marker'; series: Series; index: number; id: number; marker: Marker }
| { type: 'markerOverflow'; series: Series; first: number; count: number; id: number; bars: { from: number; to: number }; marker: Marker }
| { type: 'series'; series: Series };
```
A click is a press and release (mouse, pen or touch) within a plot during
which the pointer moved at most 3 CSS px; a longer movement is a pan. No click is
sent while a drawing is being created.
`target` is what was under the pointer, checked in this order:
1. **A draggable price line**: `{ type: 'priceLine', id }`, where `id` is the
`PriceLine`'s. Only a drawing's handle comes before it. Lines that cannot
be dragged are not targets.
2. **A drawing** (its body or one of its handles): `{ type: 'drawing', id }`.
Pressing a drawing also selects it.
3. **A marker**: `{ type: 'marker', series, index, id, marker }`, where
`index` is the position in the time-sorted `series.markers()`, `id` is
your marker id (0 if absent), and `marker` is the original object passed
to `setMarkers`, including your custom fields. A "+k" badge from folding
or clustering has `{ type: 'markerOverflow', series, first, count, id,
bars, marker }`: `first` is the first hidden marker's sorted index,
`count` is the number hidden on that side, `id`/`marker` refer to the
first one, and `bars: { from, to }` is the inclusive logical bar range.
Hidden markers need not be contiguous in the sorted list. Prefer
`id`/`marker` for your own data; see [Marker data](https://ferrochart.com/docs/markers#your-own-data-on-a-marker)
and [Clustering](https://ferrochart.com/docs/markers#clustering-across-bars).
4. **A series**: `{ type: 'series', series }` when the pointer is on a
candle's body or wick, within 4 CSS px of a line, inside a histogram bar or
on a dot. With overlapping series, the one added last wins.
5. `null` for empty space.
The `Series` objects in a target are new handles to existing series. Compare
them by `id`, not with `===`:
```ts
chart.on('click', (e: ChartEventMap['click']) => {
if (e.target?.type === 'series' && e.target.series.id === candles.id) {
console.log('clicked the candles at', e.time);
}
});
```
Indicator outputs are ordinary series, so clicking an indicator line gives a
`series` target whose `id` matches one of `indicator.outputs()`.
### crosshairMove
```ts
interface CrosshairPoint {
logicalIndex: number; // the bar the crosshair is on (whole number)
time: number | null; // UTC ms, null beyond the data
pane: number; // pane under the pointer
price: number; // price at the crosshair; NaN for a synced crosshair
bar: BarValues | null; // OHLCV of the first OHLC series with a bar here
x?: number; // pointer position, CSS px; absent for a synced crosshair
y?: number;
}
interface BarValues {
open: number; high: number; low: number; close: number;
volume: number | null;
}
```
`point` is `null` when the pointer leaves the plot or the crosshair is hidden.
The event is sent only when something in the point changes; moving the pointer
within one bar and price does not repeat it.
In magnet mode, `price` is the snapped price. `bar` is `null` when no OHLC
series has a bar at that index (for example a chart with only line series, or
a gap). To read other series at the crosshair, use `series.dataAt(point.logicalIndex)`.
A chart in a [sync group](https://ferrochart.com/docs/sync) also reports the crosshair of the other
charts. Such a point has `price: NaN`, `pane` set to the main pane and no `x`
or `y`.
### visibleRangeChanged
`{ from: number, to: number }` are the logical indices at the left and right
edges of the plot, fractional. Panning, zooming, resizing and the methods that
change the view (`setVisibleLogicalRange`, `fitContent`, `scrollToRealtime`,
`setBarSpacing`, `setRightOffset`) all cause it. The same values are available
at any time from `chart.visibleLogicalRange()`.
### needMoreHistory
`{ barsBeforeStart: number }` is the number of bars between the first bar and
the left edge of the view. It is negative when the view already shows empty
space before the data. The event is sent once per first bar: after you add
older data, it can fire again when the user scrolls to the new beginning.
```ts
let loading = false;
chart.on('needMoreHistory', async (e: ChartEventMap['needMoreHistory']) => {
if (loading) return;
loading = true;
try {
await loadOlderBars(e.barsBeforeStart); // your code: fetch older bars, then series.prepend(them)
} finally {
loading = false;
}
});
```
See [Data](https://ferrochart.com/docs/data) for loading data.
### Drawing events
`drawingCreated`, `drawingModified` and `drawingRemoved` carry the drawing
`id`; `drawingSelected` carries the selected id or `null`.
| Event | Caused by |
|---|---|
| `drawingCreated` | The user finishing a drawing, `drawings.add`, an undo or redo that brings a drawing back (with its old id), `loadState` (one per loaded drawing), a drawing received from a sync group |
| `drawingModified` | Dragging a drawing or a handle, `setAnchors`, `setStyle`, `setParam`, an undo or redo of such a change, a synced change |
| `drawingRemoved` | Delete key, `drawings.remove`, an undo of a creation, `loadState` (for the drawings it replaces), removing a pane, a synced removal |
| `drawingSelected` | Pressing a drawing or empty space, finishing a new drawing (it becomes selected), `drawings.select`, hiding or removing the selected drawing |
Showing, hiding, locking and changing the z order of a drawing send no event.
See [Drawing tools](https://ferrochart.com/docs/drawings).
### sync
`{ message: SyncMessage }` is sent when the chart posted a crosshair or
visible-range message to its [sync group](https://ferrochart.com/docs/sync):
```ts
type SyncMessage =
| { type: 'crosshair'; time: number | null }
| { type: 'visibleRange'; from: number; to: number };
```
Charts in the same `SyncGroup` on one page need nothing from you. The event is
for forwarding messages to charts elsewhere, such as in a worker, which apply
them with `applySync(message)`. A chart outside a group, or one whose group
does not share that kind of message, sends no `sync` events.
### drawingSync
`{}`. Sent when the chart, sharing drawings in a sync group, has drawing
operations that the page has not taken yet. It is sent once; it is sent again
only after you call `chart.takeDrawingSyncOps()`. See [Synchronizing
charts](https://ferrochart.com/docs/sync).
### warning
The chart fixed something on its own and the call that caused it succeeded.
```ts
type ChartWarning =
| { kind: 'timeAxisMerged'; series: Series; count: number }
| { kind: 'ohlcRepaired'; series: Series; count: number }
| { kind: 'dataDropped'; series: Series }
| { kind: 'other' };
```
| `kind` | Meaning |
|---|---|
| `'timeAxisMerged'` | The times of `series` fell between the bars of the time axis. The axis was rebuilt as the union of all series' times, and the logical indices after the first inserted bar moved. `count` bars were inserted. |
| `'ohlcRepaired'` | `count` bars of `series` had a high below or a low above their other prices and were widened. (The JavaScript API rejects such bars instead, so a chart driven from JavaScript does not send it.) |
| `'dataDropped'` | The data of `series` could not be moved onto a rebuilt time axis (out of memory) and was cleared. |
| `'other'` | A kind added in a later version. |
```ts
chart.on('warning', (w) => {
if (w.kind === 'timeAxisMerged') console.warn(`time axis rebuilt: ${w.count} bars inserted by series ${w.series.id}`);
});
```
### markerHover
```ts
interface MarkerHoverEvent {
series: Series;
index: number; // position in series.markers(); for a badge, the first marker not drawn
id: number; // your marker id, 0 if absent
marker: Marker; // original object; for a badge, the first hidden marker
bars: { from: number; to: number }; // inclusive logical bar range
overflow: number; // k for a "+k" badge, 0 for a marker
x: number; // center, CSS px from the canvas' top-left corner
y: number;
size: number; // diameter, CSS px
}
```
The payload is `null` when the pointer leaves the marker. Moving from one
marker straight onto another sends only the new one. The marker under the
pointer is found when a frame is drawn, so the event comes at most once per
frame; drawings are not considered, and while the intro animation plays no
marker counts as hovered. Use it for tooltips over avatars or badges (see
[Markers](https://ferrochart.com/docs/markers)).
### priceLineDrag
```ts
interface PriceLineDragEvent {
id: number; // PriceLine.id
phase: 'moving' | 'dropped' | 'cancelled';
from: number; // the price before the drag
price: number; // the price now
}
```
Sent while the user drags a price line created with `draggable: true`.
`'moving'` comes at most once per frame, and the line's options do not change
yet. `'dropped'` means the line was released and its options hold the new price;
to refuse it, set `from` again with `applyOptions`. `'cancelled'` (Escape, a
cancelled pointer, or released at the old price) leaves the old price, and
`price` equals `from`. A press that does not move the line sends a `click`
instead. See [Price lines](https://ferrochart.com/docs/markers#price-lines).
## Example: a legend that follows the crosshair
A DOM element over the chart shows the bar under the crosshair, and the
latest bar when the pointer is elsewhere.
```html
```
```ts
import { FerroChart, type ChartEventMap } from '@ferrochart/core';
const canvas = document.getElementById('chart');
const legend = document.getElementById('legend');
if (!(canvas instanceof HTMLCanvasElement) || !(legend instanceof HTMLDivElement)) {
throw new Error('Expected #chart canvas and #legend div');
}
const chart = await FerroChart.create(canvas);
const candles = chart.addCandlestickSeries();
candles.setData(bars); // your OHLC columns
const sma = chart.addIndicator(candles, 'sma', { n: 20 }).outputs()[0];
const fmt = (v: number | undefined) => (v === undefined || Number.isNaN(v) ? '–' : v.toFixed(2));
const show = (index: number) => {
const bar = candles.dataAt(index);
const avg = sma.dataAt(index);
if (!bar || !('open' in bar)) {
legend.textContent = '';
return;
}
const time = chart.timeAtIndex(index);
const date = time === null ? '' : new Date(time).toISOString().slice(0, 16).replace('T', ' ');
legend.textContent =
`${date} O ${fmt(bar.open)} H ${fmt(bar.high)} L ${fmt(bar.low)} C ${fmt(bar.close)}` +
` SMA 20 ${fmt(avg && 'value' in avg ? avg.value : undefined)}`;
};
function showLatest() {
const range = chart.dataRange();
if (range) show(range.to);
}
chart.on('crosshairMove', (e: ChartEventMap['crosshairMove']) => {
if (e.point) show(e.point.logicalIndex);
else showLatest();
});
showLatest();
```
`dataAt` returns `{ open, high, low, close, volume }` for OHLC series,
`{ value }` for the others, and `null` for no data or a gap. After checking
for `null`, use `'open' in bar` or `'value' in avg` to narrow the result
before reading its fields. Indicator outputs are `NaN` during their warm-up
bars. When live updates change the latest bar,
call `showLatest()` after `update` if the pointer is not over the chart.
## Example: clicking markers and series
```ts
import { FerroChart, type ChartEventMap } from '@ferrochart/core';
const chart = await FerroChart.create(canvas);
const candles = chart.addCandlestickSeries();
candles.setData(bars);
candles.setMarkers([
{ time: bars.time[120], position: 'belowBar', shape: 'arrowUp', color: '#26a69a', text: 'Buy' },
{ time: bars.time[180], position: 'aboveBar', shape: 'arrowDown', color: '#ef5350', text: 'Sell' },
]);
chart.on('click', (e: ChartEventMap['click']) => {
const t = e.target;
if (!t) {
console.log(`empty space at ${e.price.toFixed(2)}`);
return;
}
switch (t.type) {
case 'marker': {
const marker = t.marker;
console.log(`marker "${marker.text}" at`, new Date(Number(marker.time)));
break;
}
case 'series':
if (t.series.id === candles.id) {
const bar = candles.dataAt(Math.round(e.logicalIndex));
console.log('candle', bar);
}
break;
case 'drawing':
console.log('drawing', t.id, chart.drawings.get(t.id)?.kind);
break;
}
});
```
Marker indices refer to the time-sorted list that `series.markers()` returns,
not to the order you passed to `setMarkers`. Keep your own data keyed by time
if you need to find it again. See [Markers and price lines](https://ferrochart.com/docs/markers).
---
Source: https://ferrochart.com/docs/interaction
# Gestures and keyboard
The chart handles input itself; bindings only translate platform events into
`InputEvent`s (`ferrochart-winit` and `ferrochart-wasm` do this for you).
## Gestures
| Input | Effect |
|---|---|
| Drag in the plot | Pan (release while moving: kinetic scrolling) |
| Wheel / trackpad scroll | Zoom time around the pointer; horizontal scroll or Shift+wheel pans |
| Wheel over the price axis, or Alt+wheel | Zoom prices |
| Pinch (trackpad, two fingers) | Zoom |
| Drag the price axis | Scale prices (turns auto-scale off) |
| Drag the time axis | Change the bar spacing |
| Double-click an axis | Reset it (auto-scale, default spacing) |
| ← → / ↑ ↓ | Pan by 10 % / zoom |
| Home / End | Jump to the first / latest bar |
The crosshair follows the pointer, with price and time labels on the axes. Its
mode is `Normal`, `Magnet` (snaps to the nearest of the bar's open, high,
low and close) or `Hidden`.
## Touch
On a touch screen (phones, tablets, touch laptops) a finger has no hover, so
the gestures differ from the mouse. A pen behaves like a mouse.
| Touch | Effect |
|---|---|
| Drag one finger | Pan (lift while moving: kinetic scrolling) |
| Two fingers | Zoom time around their midpoint by the change of their distance, and pan with the midpoint; lifting one finger keeps panning with the other |
| Hold one finger still for 500 ms | Show the crosshair; it follows the finger without panning and stays after lifting |
| Tap | A click; also hides a crosshair left by a long press |
| Double tap an axis | Reset it, like a double click |
- A finger has to move 8 CSS px before a press becomes a drag (a mouse: 3 px),
so a tap with a little wobble is still a click.
- Fingers hit from further away: 10 CSS px from a line, 12 px from a drawing's
handle, 8 px beyond a marker.
- While a drawing is being drawn or dragged, a second finger is ignored.
- With the crosshair mode `Hidden`, holding a finger still does nothing
special: moving it pans.
- When the system takes a touch over (the page starts scrolling, a call comes
in), the gesture ends without a click or kinetic scrolling.
In the browser, whether a vertical swipe pans the chart or scrolls the page
is the `touchScroll` option; see [Touch screens](https://ferrochart.com/docs/web#touch-screens).
## Events
What the chart reports back (crosshair moves, clicks, visible range changes,
history requests, drawing changes) is described in
[Crosshair and events](https://ferrochart.com/docs/crosshair-events). In Rust, pull the same events
with `Chart::drain_events`; if you don't drain them for a while, newer
crosshair and range events replace older ones instead of piling up.
## Time
Input events carry a timestamp (`time_ms`) and `build_frame` takes the current
time (`now_ms`); both must come from the same clock. Kinetic scrolling uses
them, and so does the long press: a finger held still turns into a crosshair
when the event time or the frame time reaches 500 ms after the press. The
bindings use `performance.now()` (web) or a monotonic clock started with the
window (desktop).
---
Source: https://ferrochart.com/docs/markers
# Markers and price lines
Markers are small shapes with optional text attached to bars, such as buy and
sell signals or news. A marker can also show an image (a wallet or account
avatar) or a short badge such as `DB`, and crowded bars can fold their markers
into a "+k" badge. Price lines are horizontal lines at a fixed price, such
as an order, a stop or a target. Both belong to a series. Each series also has
a last-value label and a last-value line, which are switched on and off with
series options.
## Markers
### Setting markers
```ts
candles.setMarkers([
{ time: Date.UTC(2024, 0, 15), position: 'belowBar', shape: 'arrowUp', color: '#26a69a', text: 'Buy' },
{ time: Date.UTC(2024, 1, 2), position: 'aboveBar', shape: 'arrowDown', color: '#ef5350', text: 'Sell' },
{ time: Date.UTC(2024, 1, 20), shape: 'circle', text: 'Earnings' },
]);
```
`setMarkers` replaces all markers of the series. To add one, read the current
list, append, and set it again; to clear them, pass an empty array:
```ts
candles.setMarkers([...candles.markers(), { time: Date.UTC(2024, 2, 1), text: 'Split' }]);
candles.setMarkers([]);
```
### Marker fields
| Field | Type | Default | Meaning |
|---|---|---|---|
| `time` | `number \| bigint \| Date` | required | UTC milliseconds (an integer) or a `Date`; `markers()` returns numbers |
| `id` | `number` | `0` | Your identifier: an integer from 0 to 2^53−1; 0 means none. Reported by click and hover events. |
| `position` | `'aboveBar' \| 'belowBar' \| 'atPrice'` | `'aboveBar'` | Above the high, below the low, or centered on `price`. For single-value series, above or below the value. |
| `price` | `number` | absent | Required and finite for `'atPrice'`; not allowed for other positions. In the series' price units. |
| `shape` | `'circle' \| 'square' \| 'arrowUp' \| 'arrowDown'` | `'circle'` | Filled icon |
| `color` | `Color \| null` | `null` | Icon and text color; `null` uses the series' main color (the up color for candles and bars) |
| `text` | `string` | `''` | Text next to the icon, on the side away from the bar; empty for none |
| `size` | `number \| null` | `null` | Diameter (side of a square), 4–64 CSS px; `null` for 10 |
| `icon` | `string \| null` | `null` | Name of an image added with `chart.registerIcon`, drawn inside a circle or square |
| `label` | `string` | `''` | Up to 8 characters drawn inside a circle or square, such as `'DB'`; not with `icon` |
| `border` | `Color \| null` | `null` | Ring inside the shape's edge; `null` for none |
| `borderWidth` | `number` | `2` | Ring width, CSS px |
An unknown `position` or `shape`, a missing or non-integer `time`, an
invalid color, a `size` outside 4–64, a `label` longer than 8 characters, or
an `icon` or `label` on an arrow or both on one marker throws, and the markers
are left as they were. An `id` outside the safe non-negative integer range,
a missing or non-finite `price` for `atPrice`, or a `price` on another
position also throws.
### Reading markers
`series.markers()` returns the markers sorted by time, with every field filled
in (`color` is `null` where the default is used). The sort is stable: markers
with the same time keep the order you gave them.
The index of a marker in this list is what a `click` event reports as
`target.index` (see [Crosshair and events](https://ferrochart.com/docs/crosshair-events)). Because the
list is sorted, the index can differ from the position in the array you passed
to `setMarkers`.
### Your own data on a marker
Give each marker your own `id` and attach application data to the same
object. JavaScript `click` and `markerHover` events return that original
object as `marker`, including custom fields:
```ts
import type { Marker } from '@ferrochart/core';
const trades: (Marker & { trade: { wallet: string; quantity: number } })[] = [
{ id: 101, time: Date.UTC(2024, 0, 15), position: 'belowBar', text: 'Buy',
trade: { wallet: 'wallet-a', quantity: 2 } },
];
candles.setMarkers(trades);
chart.on('click', ({ target }) => {
if (target?.type !== 'marker' || target.series.id !== candles.id) return;
const marker = target.marker as (typeof trades)[number];
console.log(target.id, marker.trade.wallet, marker.trade.quantity);
});
chart.on('markerHover', (e) => {
if (!e || e.series.id !== candles.id || e.overflow > 0) return;
const marker = e.marker as (typeof trades)[number];
console.log(e.id, marker.trade.wallet);
});
```
The assertions above describe the custom fields on this series' markers.
`index` is the position after sorting by time, not an application identifier;
prefer `id` or the original `marker` to reconnect an event to your data.
For a "+k" badge, `id` and `marker` refer to the first hidden marker, not a
separate badge object. `markers()` returns normalized marker fields, not
these original objects. Keep your own list if you need to preserve custom
fields when replacing markers with `setMarkers`.
### Placement and snapping
- A marker is drawn at the bar whose time equals `time`. A time between two
bars snaps to the **next** bar; a time after the last bar snaps to the last
bar. A time before the first bar snaps to the first bar.
- If the series has no value at that bar (a gap), the marker is not drawn.
- Markers follow the series' `shift` option.
- The icon is `size` CSS px across (10 by default). Above/below markers
sit 4 CSS px away from the bar.
- Several above/below markers on the same bar and side stack away from the bar, in the
order of `markers()`. A marker with text takes the icon plus one line of
text.
- The text is centered on the bar, above the icon for `aboveBar` and below it
for `belowBar`, in the marker's color.
- An `'atPrice'` marker is centered on its finite `price`, with text to the
right. It still snaps in time, but is neither stacked nor clustered;
several markers at the same time and price can overlap.
- Markers are clipped to the plot area.
```ts
// Two signals on the same bar: the first sits next to the low, the second below it.
candles.setMarkers([
{ time: t, position: 'belowBar', shape: 'arrowUp', text: 'Entry' },
{ time: t, position: 'belowBar', shape: 'circle', text: 'Alert' },
]);
```
For an event at an exact price:
```ts
candles.setMarkers([
{ id: 102, time: t, position: 'atPrice', price: 101.25, shape: 'circle', text: 'Fill' },
]);
```
### Images, badges and borders
Register an image once under a name, then use the name in any number of
markers. The source can be a URL (fetched; an image from another origin needs
CORS headers), an `HTMLImageElement`, `ImageBitmap`, `ImageData` or a canvas.
The chart keeps a copy scaled to fit 64 × 64 pixels:
```ts
await chart.registerIcon('whale', '/avatars/whale.png');
await chart.registerIcon('dev', document.querySelector('img#dev') as HTMLImageElement);
candles.setMarkers([
{ time: t1, icon: 'whale', size: 24, border: '#2fbf71' }, // a buy
{ time: t2, icon: 'whale', size: 24, border: '#ef5350' }, // a sell
{ time: t2, position: 'belowBar', label: 'DB', color: '#2962ff', size: 20 },
{ time: t3, position: 'belowBar', label: '狙', color: '#ff9800', size: 20 },
]);
```
- The image fills a circle (clipped round) or a square, over the marker's
color, so a transparent image shows the color behind it. Arrows cannot have
an image or a label.
- `registerIcon` returns a promise; wait for it before using the name.
`setMarkers` with a name that is not registered throws. The promise
rejects when the image cannot be loaded or read (a failed fetch, an image
from another origin without CORS headers): fall back to a `label` or a
plain shape for that marker.
- Registering a name again replaces the image in every marker using it.
`chart.unregisterIcon(name)` removes it (it returns whether there was one);
markers that used it then draw the shape alone, and `markers()` reports
their `icon` as `null`. A chart holds at most 1024 images.
- A `label` is drawn centered in a color that contrasts with the marker's,
sized to fit: about 0.45 of the diameter for Latin letters and 0.6 for
Chinese, Japanese or Korean characters, smaller when the text is wider.
- The `border` ring is drawn inside the edge, so it does not change the
marker's size, for example a green ring for buys and a red one for sells.
### Folding crowded bars
When many markers land on one bar, such as a dozen traders buying in the same
minute, set `markerStackLimit` on the series. At most that many places are
used on each side of a bar; the last one shows "+k" for the k markers not
drawn:
```ts
candles.applyOptions({ markerStackLimit: 4 }); // 3 markers, then "+k"
candles.applyOptions({ markerStackLimit: null }); // no limit (the default)
```
The badge is a circle in the series' main color, as large as the marker it
replaces. Clicking it sends a `click` whose target is
`{ type: 'markerOverflow', series, first, count, id, marker, bars }`.
`first` is the sorted index of the first hidden marker, `count` is the number
hidden on that side, and `id`/`marker` identify the first one. `bars` gives
the first and last logical bar index; for a single-bar fold they are equal.
The markers may be interleaved with markers on another side in the sorted
list, so `count` does not define a contiguous slice of that list.
### Clustering across bars
Set `markerCluster` to a positive, finite distance in CSS pixels to group
markers across nearby bars. `null` (the default) disables clustering:
```ts
candles.applyOptions({ markerCluster: 28, markerStackLimit: 4 });
// Later, keep per-bar folding but turn off cross-bar clustering:
candles.applyOptions({ markerCluster: null });
```
Buckets contain `ceil(markerCluster / bar spacing)` logical indices (at
least one). They align to logical indices, so panning does not regroup
markers; zooming can change the bucket size. On each side of a bucket with
markers on two or more bars, only the first marker and a "+k" badge are
shown, on the bar with the most markers on that side. `atPrice` markers do
not participate.
Clustering takes precedence over `markerStackLimit` for such a group.
Otherwise, `markerStackLimit` still controls folding on a single bar.
A badge click has a `markerOverflow` target; hover has `overflow > 0`.
Their `bars: { from, to }` contains the inclusive first and last logical
indices represented by the badge. Use the range, the side of `marker`, and
your own marker data to build a details list; `first`/`index` and the count
alone are not a contiguous list of members. See
[Logical indices](https://ferrochart.com/docs/data#logical-indices) and [Click events](https://ferrochart.com/docs/crosshair-events#click).
### Hovering markers
The `markerHover` event fires when the pointer moves onto a marker or a "+k"
badge, and with `null` when it leaves. It carries the marker's index, its
center and diameter in CSS px, which is what a tooltip needs:
```ts
chart.on('markerHover', (e) => {
if (!e) return hideTooltip();
if (e.overflow > 0) {
showTooltip(e.x, e.y - e.size / 2, `${e.overflow} more · bars ${e.bars.from}–${e.bars.to}`);
} else {
showTooltip(e.x, e.y - e.size / 2, e.marker.text ?? '');
}
});
```
`index` is the position in `series.markers()`; for a badge it is the first
marker not drawn and `overflow` is k (0 for a marker). `id` and `marker`
identify that marker; `bars` is the inclusive logical range represented by
the marker or badge. The hovered marker is
found when a frame is drawn, so the event comes at most once per frame. While
the intro animation plays, no marker counts as hovered. See
[Crosshair and events](https://ferrochart.com/docs/crosshair-events).
### Chinese, Japanese, Korean and emoji
Marker text and labels can use any script. The bundled font only covers
Latin letters, digits and common symbols; other characters come from:
- **Web**: the browser's own fonts (the system's CJK fonts and color
emoji), with nothing to configure and nothing added to the package.
- **Desktop, Python and C**: fonts you add, searched in order:
`WindowOptions { fonts, .. }` with winit, `fc.Chart(fonts=[...])` in
Python, `ferrochart_add_font` in C. No system fonts are scanned. Fonts that
are usually present: `/System/Library/Fonts/Hiragino Sans GB.ttc` (macOS),
`C:/Windows/Fonts/msyh.ttc` (Windows),
`/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc` (Linux, with the
Noto CJK package); or ship Noto Sans SC/JP/KR with your application.
A character that no font has is drawn as `□`. Natively, color emoji fonts are
not supported: an outline emoji font (Noto Emoji) draws in the text color.
Text is laid out by grapheme cluster: on the web, an emoji with a skin tone,
a family or other ZWJ sequence, a flag, or a letter with a combining accent is
measured and drawn by the browser as one glyph. Natively, such sequences are
drawn character by character (the fonts are not shaped). There is no shaping
or right-to-left layout, so Arabic and Hebrew do not come out right.
### Python, C and Rust
The bindings use their own naming conventions:
```python
red = chart.add_icon(avatar) # a (height, width, 4) or (height, width, 3) uint8 array
candles.set_markers([
{"time": t, "icon": red, "size": 24, "border": "#2fbf71"},
{"time": t, "position": "below_bar", "label": "DB", "color": "#2962ff"},
])
candles.apply_options(marker_stack_limit=4, marker_cluster=28)
chart.on("marker_hover", lambda e: print(e)) # None when the pointer leaves
```
In Python, marker dictionaries accept `id` and `position="at_price"` with
`price`; events report `id` and badge `bars`. Original-object `marker`
round-tripping is a JavaScript feature; in native Python, keep a mapping
from ids to your own objects. In Rust use `Marker::id`, `Marker::price` and
`MarkerPosition::AtPrice`; `SeriesOptions::marker_cluster` controls
clustering. In C use `FerroChartMarker.id`, `.price` and
`FERROCHART_MARKER_AT_PRICE`; series options use `marker_cluster`.
In Python, `add_icon` returns an integer id and `remove_icon(id)` removes the
image. In C, `ferrochart_add_icon` and `ferrochart_set_markers` take the same
fields (see [C, C++ and C#](https://ferrochart.com/docs/native)). In Rust, `Chart::add_icon` takes an
`IconImage` (straight RGBA, up to 256 × 256) and returns an `IconId` for
`Marker::icon`; `ChartEvent::MarkerHover` and `ClickTarget::MarkerOverflow`
are the event and click target.
### Which series can have markers
Every series kind except volume series. `setMarkers` on a volume series
throws. Markers can be put on an indicator output too (an `Indicator`'s
`outputs()` are ordinary series):
```ts
const rsi = chart.addIndicator(candles, 'rsi').outputs()[0];
rsi.setMarkers([{ time: t, position: 'aboveBar', shape: 'square', text: 'OB' }]);
```
### Example: markers from signals
```ts
import type { Marker, OhlcData } from '@ferrochart/core';
// Mark crossings of the close over a 20-bar SMA.
function crossMarkers(bars: OhlcData, sma: number[]): Marker[] {
const out: Marker[] = [];
const close = bars.close;
for (let i = 1; i < close.length; i++) {
const was = close[i - 1] - sma[i - 1];
const now = close[i] - sma[i];
if (Number.isNaN(was) || Number.isNaN(now)) continue;
if (was <= 0 && now > 0) {
out.push({ time: bars.time[i], position: 'belowBar', shape: 'arrowUp', color: '#26a69a', text: 'Buy' });
} else if (was >= 0 && now < 0) {
out.push({ time: bars.time[i], position: 'aboveBar', shape: 'arrowDown', color: '#ef5350', text: 'Sell' });
}
}
return out;
}
candles.setMarkers(crossMarkers(bars, smaValues));
```
## Price lines
### Creating a price line
```ts
const entry = candles.createPriceLine({
price: 101.25,
color: '#2962ff',
lineWidth: 1,
lineStyle: 'solid',
title: 'Entry',
});
const stop = candles.createPriceLine({ price: 98.5, color: '#ef5350', title: 'Stop' });
```
`createPriceLine` returns a `PriceLine`. The price is in the series' units, so
on a percentage or indexed price scale the line moves with the series (see
[Price scale](https://ferrochart.com/docs/price-scale)).
### Options
| Option | Type | Default | Meaning |
|---|---|---|---|
| `price` | `number` | `0` | Price, in the series' units; must be finite |
| `color` | `Color \| null` | `null` | Line, title and axis label color; `null` uses the series' main color |
| `lineWidth` | `number` | `1` | CSS px, greater than 0 |
| `lineStyle` | `'solid' \| 'dashed' \| 'dotted'` | `'dashed'` | Dash pattern |
| `axisLabelVisible` | `boolean` | `true` | Label with the price on the price axis |
| `title` | `string` | `''` | Text above the line at the right edge of the plot; empty for none |
| `draggable` | `boolean` | `false` | The user can drag the line up and down (`priceLineDrag` event) |
| `priceStep` | `number \| null` | `null` | Dragged prices are rounded to a multiple of this (greater than 0); `null` does not round |
The axis label uses the series' price format (its `pricePrecision`). Labels on
the price axis are moved apart when they would overlap. A price line that is
outside the visible price range is not drawn.
### Changing and removing
```ts
entry.applyOptions({ price: 101.5 }); // only the keys you pass change
console.log(entry.options()); // every option: { price, color, lineWidth, ... }
stop.applyOptions({ title: 'Stop (moved)', lineStyle: 'dotted' });
stop.remove();
```
After `remove()`, calling `options`, `applyOptions` or `remove` on that
object throws. Removing the series removes its price lines.
`createPriceLine` throws for a volume series, a non-finite price, an options
argument that is not an object, or an invalid option value.
### Example: a draggable order line
With `draggable: true` the user can drag the line up and down. The
`priceLineDrag` event reports the line's `id`, the price before the drag
(`from`), the `price` now and the `phase`:
| `phase` | Meaning |
|---|---|
| `'moving'` | The line follows the pointer; its options do not change yet |
| `'dropped'` | Released: the options hold the new price. To refuse it, set `from` again |
| `'cancelled'` | Escape, a cancelled pointer, or released at the old price; the old price stays |
```ts
const order = candles.createPriceLine({
price: 101.25,
title: 'Sell limit',
draggable: true,
priceStep: 0.25,
});
const minPrice = 100; // your own rule
chart.on('priceLineDrag', (e: ChartEventMap['priceLineDrag']) => {
if (e.id !== order.id || e.phase !== 'dropped') return;
if (e.price < minPrice) order.applyOptions({ price: e.from }); // refused: put it back
else console.log('order moved to', e.price);
});
```
When the answer comes later, for example from a server, use
`createTradingLines`: it blocks further drags until then (see [Chart
trading](https://ferrochart.com/docs/drawings#chart-trading)).
In Rust, set `draggable` and `price_step` in `PriceLineOptions`. The event is
`ChartEvent::PriceLineDrag { id, phase, from, price }` with a
`PriceLineDragPhase` (`Moving`, `Dropped`, `Cancelled`); refuse a drop with
`Chart::update_price_line`. In Python, the options are `draggable` and
`price_step` and the event is `price_line_drag`, whose `line` is the
`PriceLine`:
```python
order = candles.create_price_line(101.25, title="Sell limit", draggable=True, price_step=0.25)
@chart.on("price_line_drag")
def dragged(e):
if e["phase"] == "dropped" and e["price"] < 100:
e["line"].apply_options(price=e["from"]) # refused: put it back
```
## Last value label and line
Each series shows its latest value as a label on the price axis and as a
dotted horizontal line across the plot. Both use the up color when the last
bar closed at or above its open (for baseline series: at or above the base
value) and the down color otherwise; line, area, histogram and points series
use their main color.
| Series option | Default | Meaning |
|---|---|---|
| `lastValueVisible` | `true` | Label with the last value on the price axis |
| `priceLineVisible` | `true` | Dotted line at the last value |
| `pricePrecision` | `null` | Decimals of the label; `null` is automatic |
```ts
const line = chart.addSeries('line', { lastValueVisible: true, priceLineVisible: false });
candles.applyOptions({ priceLineVisible: false });
```
Volume series draw neither. Indicator outputs are created with
`priceLineVisible: false`; their last-value labels are shown. Turn them off
per output:
```ts
for (const s of chart.addIndicator(candles, 'boll').outputs()) {
s.applyOptions({ lastValueVisible: false });
}
```
Series options are described in [Series](https://ferrochart.com/docs/series).
---
Source: https://ferrochart.com/docs/styling
# Themes and styling
This chapter covers how a chart looks and how it fits into a page: the theme,
colors, axes and padding, interaction, the crosshair, many small charts,
images, the attribution logo, the intro animation, the GPU renderer, sizing
and cleanup. Everything here applies to `FerroPlot` as well unless noted.
## Theme
The theme is chosen when the chart is created:
```ts
import { FerroChart } from '@ferrochart/core';
declare const canvas: HTMLCanvasElement;
const chart = await FerroChart.create(canvas, { theme: 'dark' }); // 'light' (default) or 'dark'
```
The theme sets the background, grid, text, axis and crosshair colors, the
default up and down colors of candles, and the default colors of series,
indicators and drawings.
A theme can also be an object: colors on top of a `base` theme (`'light'` by
default), as CSS colors. Keys you leave out come from the base. Change the
theme of an existing chart with `applyOptions`; the view and data are kept.
```ts
import { FerroChart } from '@ferrochart/core';
declare const canvas: HTMLCanvasElement;
const chart = await FerroChart.create(canvas, {
theme: { base: 'dark', background: '#0b0d12', up: '#30a0f0', down: '#f09030', fontSize: 13 },
});
chart.applyOptions({ theme: 'light' });
```
The keys are `background`, `text`, `grid`, `axisLine`, `up`, `down`,
`upWick`, `downWick`, `volumeUp`, `volumeDown`, `crosshair`,
`crosshairLabelBg`, `crosshairLabelText`, `line`, `fontSize` and
`axisPadding`; an unknown key is an error. `chart.options().theme` reads the
current theme back.
Any color you leave unset, or set to `null`, follows the theme. Set colors
explicitly only where you need them; the rest then stays consistent in both
themes.
## Series colors
Series take their colors from `SeriesOptions`, at creation or later with
`series.applyOptions`:
```ts
import { FerroChart } from '@ferrochart/core';
declare const chart: FerroChart;
const candles = chart.addCandlestickSeries({ color: '#26a69a', downColor: '#ef5350' });
const line = chart.addSeries('line', { color: '#2962ff', lineWidth: 2, lineStyle: 'dashed' });
const area = chart.addSeries('area', {
color: '#2962ff',
topFill: 'rgba(41, 98, 255, 0.4)',
bottomFill: 'rgba(41, 98, 255, 0)',
});
line.applyOptions({ color: null }); // back to the theme's color
```
| Option | Used for |
|---|---|
| `color` | Line color of line, area and baseline (above the base) series; up candles and bars; histogram bars |
| `downColor` | Down candles and bars; the baseline series' line below the base |
| `topFill` | Area fill at the top; baseline fill above the base |
| `bottomFill` | Area fill at the bottom; baseline fill below the base |
| `lineWidth` | Line width in CSS px |
| `lineStyle` | `'solid'`, `'dashed'` or `'dotted'` |
Area fills are a gradient from `topFill` to `bottomFill`. Histogram series also
accept a color per bar (the `color` column of `setData`). All series options,
and what each series kind draws, are in [Series](https://ferrochart.com/docs/series).
Other objects have their own color options: price lines
(`createPriceLine({ color })`), markers (`color` per marker), bands between
two series (`addBand(upper, lower, { fill, fillCrossed })`) and drawings
(`style: { line, fill, text }`). See [Series](https://ferrochart.com/docs/series),
[Markers](https://ferrochart.com/docs/markers), [Indicators](https://ferrochart.com/docs/indicators) and
[Drawings](https://ferrochart.com/docs/drawings).
## Colors
Colors are CSS color strings in one of these forms (type `Color`):
| Form | Example |
|---|---|
| `#rgb`, `#rgba` | `'#f80'`, `'#f808'` |
| `#rrggbb`, `#rrggbbaa` | `'#ff8800'`, `'#ff880080'` |
| `rgb(r, g, b)` | `'rgb(255, 136, 0)'` |
| `rgba(r, g, b, a)` | `'rgba(255, 136, 0, 0.5)'`, alpha from 0 to 1 |
| `transparent` | `'transparent'` |
Channels are 0 to 255; commas, spaces or a `/` separate them. Named colors
(`'red'`), `hsl()` and percentages are **not** accepted: the call throws, for
example `'color': invalid color 'red'`.
Colors read back from `options()` are written as `#rrggbb`, or
`rgba(r, g, b, a)` when they are not opaque; a color that follows the theme
reads back as `null`.
Per-point color columns (histogram data, plot marks) also accept a
`Uint32Array` of `0xRRGGBBAA` values, which avoids creating strings for large
data.
## Axes, grid and padding
Charts in apps and tables often have no axes at all. `priceAxis` and
`timeAxis` show or hide the axes, `grid` the grid lines (`true`, `false` or
`{ horizontal, vertical }`), and `padding` leaves space around the plot (CSS
px, a number or `{ top, right, bottom, left }`). Hidden axes give their space
to the plot.
```ts
import { FerroChart } from '@ferrochart/core';
declare const canvas: HTMLCanvasElement;
const chart = await FerroChart.create(canvas, {
priceAxis: false,
grid: { vertical: false },
padding: { top: 72, bottom: 40 },
});
chart.applyOptions({ timeAxis: false });
```
All of these, and the options of the next two sections, work in `create` and
in `applyOptions`, and `chart.options()` reads them back. In Python they are
keyword arguments with snake_case names (`Chart(preset="sparkline")`,
`chart.apply_options(price_axis=False)`); in C they are the
`FerroChartAppearance`, `FerroChartInteraction`, `FerroChartCrosshairStyle`
and `FerroChartTheme` structs.
## Interaction
`interaction` switches panning, zooming and the crosshair on and off:
`{ pan, zoom, crosshair }`, or `false` for all three. Input a switch turns
off is not used by the chart, so on a touch screen the page scrolls and
zooms as usual. Clicks are still reported.
```ts
import { FerroChart } from '@ferrochart/core';
declare const canvas: HTMLCanvasElement;
const chart = await FerroChart.create(canvas, { interaction: { pan: false, zoom: false } });
```
## Crosshair style
`crosshairStyle` sets which parts of the crosshair are drawn: `vertical` and
`horizontal` lines, axis `labels`, and a `dot` on the first series' value
(`{ radius, color }`, `null` for none; the color defaults to the series').
A vertical line with a dot is the usual crosshair of a quote card.
```ts
import { FerroChart } from '@ferrochart/core';
declare const canvas: HTMLCanvasElement;
const chart = await FerroChart.create(canvas, {
crosshairStyle: { horizontal: false, labels: false, dot: { radius: 5 } },
});
```
## Many small charts
`preset: 'sparkline'` is a chart for a table cell: no axes, no grid, padding
2, no interaction, and a crosshair of a vertical line with a dot. Options
given next to it apply on top.
A browser keeps only about 16 WebGL contexts per page, and every chart has
its own GPU device. For a page of many small charts, create them from a
pool: they share one device (and on WebGL2, one context). Charts outside the
viewport are not drawn until they scroll back in.
```ts
import { FerroChart } from '@ferrochart/core';
declare const canvases: HTMLCanvasElement[];
const pool = await FerroChart.createPool();
const charts = await Promise.all(canvases.map((c) => pool.create(c, { preset: 'sparkline' })));
// …
pool.destroy(); // destroys every chart of the pool
```
On WebGL2 a pooled chart draws its canvas with a 2D context, so the canvas
must not have another context yet.
## Images
`chart.toBlob(type?, quality?)` draws a frame and returns it as a PNG (the
default), WebP or JPEG `Blob`; `chart.toImageBitmap()` returns an
`ImageBitmap`. The image has the canvas' pixel size and does not include the
attribution logo, which is not part of the canvas. `FerroPlot` has the same
methods.
```ts
import { FerroChart } from '@ferrochart/core';
declare const chart: FerroChart;
const png = await chart.toBlob();
const jpeg = await chart.toBlob('image/jpeg', 0.9);
```
## Attribution logo
By default a small FerroChart logo is shown at the bottom-left corner of the
lowest pane, just above the time axis. It links to ferrochart.com and shows
the name when the pointer is over it.
The logo is a courtesy, not a license requirement: you may turn it off.
When you do not set `attributionLogo`, it is shown only on canvases of at
least 320 × 160 CSS px, and appears or goes as the canvas is resized across
that size; `true` or `false` (or `setAttributionLogo`) fixes it.
```ts
import { FerroChart } from '@ferrochart/core';
declare const canvas: HTMLCanvasElement;
const chart = await FerroChart.create(canvas, { attributionLogo: false });
chart.setAttributionLogo(true); // show it
chart.setAttributionLogo(false); // remove it
```
How it is placed:
- It is an `` element inserted right after the canvas, positioned
absolutely next to it; it is not drawn into the canvas, so it does not
appear in screenshots or images rendered by the engine.
- Its position is updated when the layout changes. It is positioned relative
to the canvas's offset parent, like the canvas itself.
- If the canvas has no parent element when the logo would be added, it is
not added.
A `FerroPlot` has the same option and method; its logo sits at the
bottom-left of the plot area. A plot attached to a chart with
`attachSidePlot` loses its logo, since the chart's stands for both (see
[Plots](https://ferrochart.com/docs/plots)).
## Intro animation
`playIntro` shows the chart empty (grid and axes) and then draws the data from
left to right. Use it when a chart first appears, for example on a landing
page or when the user opens a symbol.
```ts
import { FerroChart, randomWalk } from '@ferrochart/core';
declare const canvas: HTMLCanvasElement;
const chart = await FerroChart.create(canvas, { theme: 'dark' });
chart.addCandlestickSeries().setData(randomWalk(1, 300, Date.UTC(2024, 0, 1), 3_600_000));
await chart.playIntro({ duration: 1200, delay: 200, pen: '#4cc9f0' });
// The animation has ended (or was ended early).
```
`IntroOptions`:
| Option | Meaning | Default |
|---|---|---|
| `duration` | Time to draw the data from left to right, ms | `900` |
| `delay` | Time the empty chart is shown first, ms | `0` |
| `pen` | Color of a glowing line at the drawing edge; `null` for none | `null` |
Behavior:
- The chart is shown empty at once, before the next frame, so call
`playIntro` right after `setData` to avoid a flash of the full chart.
- Price lines, value labels and the crosshair appear at the end.
- A press, wheel, pinch, double-click or key on the canvas ends it early.
Moving the pointer over the chart does not.
- `chart.finishIntro()` ends it at once.
- Calling `playIntro` again ends the running animation first.
- The returned promise resolves when the animation ends, however it ends
(also when the chart is destroyed). It never rejects; invalid options
(a negative or non-finite `duration` or `delay`, an invalid `pen` color)
throw from the call itself.
For a `FerroPlot`, `playIntro` draws the marks from left to right; rule labels
and the hover highlight appear at the end.
## Renderer
FerroChart draws with the GPU: WebGPU where the browser supports it, WebGL2
otherwise. There is no Canvas 2D fallback.
| `renderer` option | Behavior |
|---|---|
| `'auto'` (default) | WebGPU, then WebGL2 |
| `'webgpu'` | WebGPU only |
| `'webgl2'` | WebGL2 only |
`create` rejects when no requested API is available (`'WebGPU is not
available'`, `'WebGL2 is not available'`, or both joined by `;`), or for an
unknown option value. The `renderer` property tells which API is in use:
```ts
import { FerroChart } from '@ferrochart/core';
declare const canvas: HTMLCanvasElement;
try {
const chart = await FerroChart.create(canvas);
console.log(chart.renderer); // 'webgpu' or 'webgl2'
} catch (e) {
canvas.replaceWith(Object.assign(document.createElement('p'), {
textContent: 'This chart needs WebGPU or WebGL2.',
}));
}
```
Forcing `'webgl2'` is a simple way to test the fallback on a browser that
has WebGPU.
## Sizing the canvas
The canvas is sized with CSS. FerroChart sets the canvas's backing store
(`canvas.width` and `canvas.height`) itself, to the CSS size times
`devicePixelRatio`, so the chart is sharp on high-density screens. Do not set
`width` and `height` on the canvas yourself.
```html