# 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
``` - A `ResizeObserver` watches the canvas's content box. When its CSS size changes, the backing store and the layout follow and the chart redraws. You never call a resize method. - When `devicePixelRatio` changes (browser zoom, moving the window to another screen), the backing store is resized too. - The backing store is at least 1 × 1 px. If the chart is in a hidden element when it is created, it draws as soon as the element gets a size. - `display: block` avoids the few pixels of space below an inline canvas. - Inside flex or grid layouts, give the canvas `min-height: 0` (or `min-width: 0`) so the container can shrink it. When the chart is created, the canvas also gets `tabindex="0"` (unless it has a `tabindex`) so it can receive keys, `touch-action: none` so touch gestures pan and zoom the chart instead of the page (`pan-y` with `touchScroll: 'page'`, which leaves vertical swipes to the page; see [Touch screens](https://ferrochart.com/docs/web#touch-screens)), and `outline: none`. The cursor style is set while the pointer is over the chart. ## Cleaning up ```ts import { FerroChart, FerroPlot } from '@ferrochart/core'; declare const chart: FerroChart; declare const plot: FerroPlot; chart.destroy(); plot.destroy(); // FerroPlot's equivalent ``` `destroy()`: - removes the DOM event listeners on the canvas and every callback added with `on`; - leaves the chart's sync group; - removes the attribution logo; - resolves a pending `playIntro` promise; - releases the GPU resources. The canvas element stays in the page; remove it yourself if you no longer need it. After `destroy()`, the chart object cannot be used, and calls on its `Series`, `Indicator` and other handles throw (`the FerroChart was destroyed`). Destroy charts you no longer show: each one holds GPU memory, and browsers limit the number of WebGL contexts a page may have. In React or Vue, create the chart when the component mounts and destroy it when it unmounts; see [React and Vue](https://ferrochart.com/docs/frameworks). --- Source: https://ferrochart.com/docs/indicators # Indicators FerroChart has 30 built-in technical indicators. An indicator reads a source series, computes one or more output series, and keeps them up to date as the source changes. The outputs are ordinary series: you style them, read their values and put markers on them like any other series. ## Adding an indicator ```ts const sma = chart.addIndicator(candles, 'sma', { n: 50 }); const boll = chart.addIndicator(candles, 'boll', { n: 20, k: 2 }); const macd = chart.addIndicator(candles, 'macd', { fast: 12, slow: 26, signal: 9 }); const rsi = chart.addIndicator(candles, 'rsi'); // all defaults ``` `chart.addIndicator(source, name, params?, placement?)` returns an `Indicator`. | Argument | Meaning | |---|---| | `source` | The series to compute from. Any series except volume and custom series. | | `name` | One of the names in the table below, e.g. `'sma'`, `'stochRsi'`. `snake_case` spellings (`'stoch_rsi'`, `'volume_ma'`) are accepted too. | | `params` | Parameters by name, in camelCase. Missing ones take their defaults. | | `placement` | Where the outputs go; default `'default'`. | The indicator is computed over all existing data at once, before `addIndicator` returns. ### Placement ```ts type Placement = 'default' | 'overlay' | 'newPane' | 'volume' | number; ``` | Value | Outputs go to | |---|---| | `'default'` | The indicator's usual place: `'overlay'` for moving averages and channels, `'newPane'` for oscillators, `'volume'` for Volume MA (see the table) | | `'overlay'` | The source's pane, on its price scale | | `'newPane'` | A new pane below the others, created for this indicator | | `'volume'` | The pane of the source's volume series, on the volume scale. Without a volume series for the source, a new pane | | a pane id | That pane (from `chart.panes()`, `chart.mainPane`, `chart.addPane()` or `series.pane`) | ```ts // Two oscillators in one pane. const rsi = chart.addIndicator(candles, 'rsi'); const pane = rsi.outputs()[0].pane; chart.addIndicator(candles, 'stochRsi', {}, pane); ``` A pane created by `'newPane'` (or by `'volume'` without a volume series) is removed with the indicator when nothing else is left on it. ### Source series An OHLC series (candlestick, OHLC bar, Heikin-Ashi) gives the indicator its open, high, low, close and volume. A single-value series (line, area, baseline, histogram, points) gives `open = high = low = close = value` and no volume. So you can compute an RSI of a line series, but not an OBV. Indicators that need volume (VWMA, Volume MA, VWAP, MFI, OBV, CMF) throw when the source is a single-value series, or an OHLC series whose data has no volume column. Bars where the source has no value, such as times that only another series has, are skipped: the outputs are `NaN` there and the bar does not count in the indicator's windows. ### Indicators of indicators The source can be an output of another indicator. For example, a 9-bar SMA of the RSI, in the RSI's pane: ```ts const rsiLine = chart.addIndicator(candles, 'rsi').outputs()[0]; const rsiAvg = chart.addIndicator(rsiLine, 'sma', { n: 9 }, rsiLine.pane); ``` Removing the RSI removes the SMA too. ## The built-in indicators `indicatorNames()` returns the 30 names in the order of this table. Outputs are listed in the order `outputs()` returns them. All outputs are lines unless marked (histogram) or (points). | Name | Indicator | Parameters (defaults) | Outputs | Default placement | |---|---|---|---|---| | `sma` | Simple moving average | `n` (20), `source` | sma | overlay | | `ema` | Exponential moving average | `n` (20), `source` | ema | overlay | | `wma` | Weighted moving average | `n` (20), `source` | wma | overlay | | `hma` | Hull moving average | `n` (20, at least 2), `source` | hma | overlay | | `vwma` | Volume-weighted moving average | `n` (20), `source` | vwma | overlay | | `dema` | Double EMA | `n` (20), `source` | dema | overlay | | `tema` | Triple EMA | `n` (20), `source` | tema | overlay | | `volumeMa` | Moving average of volume | `n` (20) | vma | volume | | `boll` | Bollinger bands | `n` (20), `k` (2), `source` | upper, mid, lower; band upper–lower | overlay | | `keltner` | Keltner channel | `n` (20), `m` (2), `atrN` (10) | upper, mid, lower; band upper–lower | overlay | | `donchian` | Donchian channel | `n` (20) | upper, mid, lower | overlay | | `ichimoku` | Ichimoku cloud | `tenkan` (9), `kijun` (26), `senkou` (52), `shift` (26) | tenkan, kijun, span A, span B, chikou; band span A–span B | overlay | | `sar` | Parabolic SAR | `afStart` (0.02), `afStep` (0.02), `afMax` (0.2) | sar (points) | overlay | | `supertrend` | SuperTrend | `atrN` (10), `m` (3) | long, short | overlay | | `vwap` | Volume-weighted average price | `anchor` (`'day'`), `utcOffsetMs` (0) | vwap | overlay | | `macd` | MACD | `fast` (12), `slow` (26), `signal` (9), `source` | macd, signal, hist (histogram) | new pane | | `rsi` | Relative strength index | `n` (14), `source` | rsi | new pane | | `stoch` | Stochastic oscillator | `k` (14), `smoothK` (3), `d` (3) | %K, %D | new pane | | `stochRsi` | Stochastic RSI | `rsiN` (14), `stochN` (14), `smoothK` (3), `d` (3), `source` | %K, %D | new pane | | `cci` | Commodity channel index | `n` (20) | cci | new pane | | `willr` | Williams %R | `n` (14) | %R | new pane | | `mfi` | Money flow index | `n` (14) | mfi | new pane | | `adx` | ADX with directional indicators | `n` (14) | adx, +DI, −DI | new pane | | `atr` | Average true range | `n` (14) | atr | new pane | | `obv` | On-balance volume | none | obv | new pane | | `cmf` | Chaikin money flow | `n` (20) | cmf | new pane | | `roc` | Rate of change (%) | `n` (10), `source` | roc | new pane | | `momentum` | Momentum | `n` (10), `source` | momentum | new pane | | `trix` | TRIX | `n` (15), `source` | trix | new pane | | `aroon` | Aroon | `n` (14) | up, down | new pane | ### Parameter values | Parameter | Values | |---|---| | Periods (`n`, `fast`, `slow`, `signal`, `k` of `stoch`, `smoothK`, `d`, `rsiN`, `stochN`, `atrN`, `tenkan`, `kijun`, `senkou`, `shift`) | Whole numbers, at least 1 (`hma`: `n` at least 2) | | Multipliers (`k` of `boll`, `m`) | Finite numbers greater than 0 | | `afStart`, `afStep`, `afMax` | Finite numbers greater than 0, `afStart` not above `afMax` | | `source` | `'close'` (default), `'open'`, `'high'`, `'low'`, `'hl2'` (H+L)/2, `'hlc3'` (H+L+C)/3, `'ohlc4'` (O+H+L+C)/4 | | `anchor` (`vwap`) | `'day'` (default), `'week'` (weeks start on Monday), `'month'`, or a time in UTC ms to accumulate from | | `utcOffsetMs` (`vwap`) | Whole milliseconds added to UTC before splitting days, weeks and months, e.g. `-5 * 3600_000` for New York standard time | ```ts chart.addIndicator(candles, 'ema', { n: 21, source: 'hlc3' }); chart.addIndicator(candles, 'vwap', { anchor: 'week' }); chart.addIndicator(candles, 'vwap', { anchor: Date.UTC(2024, 2, 1) }); // anchored VWAP chart.addIndicator(candles, 'vwap', { utcOffsetMs: 9 * 3600_000 }); // sessions in UTC+9 ``` Parameter names must be written exactly as in the table. A key the indicator does not use, including snake_case spellings such as `atr_n`, throws an error that lists the accepted keys: ```ts chart.addIndicator(candles, 'sma', { length: 20 }); // Error: unknown parameter 'length' for indicator 'sma' (expected: n, source) ``` `addTransformSeries` checks its parameters the same way. ### Formulas In brief; `P` is the chosen `source` price. "Warm-up" is the number of leading bars whose output is `NaN`. **Moving averages and channels** - **SMA**: mean of the last `n` values of `P`. Warm-up `n − 1`. - **EMA**: `e = e + α(P − e)`, `α = 2/(n + 1)`, seeded with the SMA of the first `n` values. Warm-up `n − 1`. - **WMA**: weights `n, n−1, …, 1` from the newest value. Warm-up `n − 1`. - **HMA**: `WMA(2·WMA(P, n/2) − WMA(P, n), √n)` (halves and roots rounded down). Warm-up `n + ⌊√n⌋ − 2`. - **VWMA**: `Σ(P·V) / ΣV` over `n` bars (`NaN` when the volume sum is 0). Warm-up `n − 1`. - **DEMA**: `2·e1 − e2`, where `e1 = EMA(P, n)` and `e2 = EMA(e1, n)`. Warm-up `2(n − 1)`. - **TEMA**: `3·e1 − 3·e2 + e3`, `e3 = EMA(e2, n)`. Warm-up `3(n − 1)`. - **Volume MA**: SMA of the volume. Warm-up `n − 1`. - **BOLL**: mid = `SMA(P, n)`, upper and lower = mid ± `k` × the population standard deviation over `n` bars. Warm-up `n − 1`. - **Keltner**: mid = `EMA(close, n)`, upper and lower = mid ± `m` × `ATR(atrN)`. Warm-up `max(n − 1, atrN)`. - **Donchian**: upper = highest high of `n` bars, lower = lowest low, mid = their average. Warm-up `n − 1`. - **Ichimoku**: tenkan and kijun are the midpoints of the high-low range over `tenkan` and `kijun` bars. Span A = (tenkan + kijun)/2 and span B = the midpoint over `senkou` bars, both drawn `shift` bars ahead (the last `shift` values appear right of the last bar). Chikou is the close drawn `shift` bars back. - **SAR**: Parabolic SAR with acceleration from `afStart` in steps of `afStep` up to `afMax`, computed as TA-Lib does. Warm-up 1. - **SuperTrend**: bands `HL2 ± m·ATR(atrN)` that only tighten while the trend lasts; the trend flips when the close crosses the active band. `long` (the lower band) has values in up trends, `short` (the upper band) in down trends, `NaN` otherwise. Warm-up `atrN`. - **VWAP**: `Σ(HLC3·V) / ΣV` from the anchor on, restarting at each day, week or month (in UTC plus `utcOffsetMs`), or from the given time on (`NaN` before it). Warm-up 0. **Oscillators** - **MACD**: macd = `EMA(P, fast) − EMA(P, slow)`, signal = `EMA(macd, signal)`, hist = macd − signal. Warm-up `slow − 1` for macd, `slow + signal − 2` for signal and hist. - **RSI**: Wilder's smoothing (`r = r + (x − r)/n`) of gains and losses; `100·gain/(gain + loss)`, 50 when both are 0. Warm-up `n`. - **Stoch**: raw = `100·(C − lowest low)/(highest high − lowest low)` over `k` bars (50 when the range is 0); %K = `SMA(raw, smoothK)`, %D = `SMA(%K, d)`. Warm-up `k + smoothK − 2` for %K, `d − 1` more for %D. - **StochRSI**: the stochastic formula applied to `RSI(P, rsiN)` over `stochN` bars, then smoothed like Stoch. Warm-up `rsiN + stochN + smoothK − 2` for %K, `d − 1` more for %D. - **CCI**: `(TP − SMA(TP, n)) / (0.015 · mean deviation)`, `TP` = HLC3; 0 when the deviation is 0. Warm-up `n − 1`. - **Williams %R**: `−100·(highest high − C)/(highest high − lowest low)` over `n` bars; −50 when the range is 0. Warm-up `n − 1`. - **MFI**: `100·positive flow/(positive + negative flow)` over `n` bars, where flow = HLC3 × volume and its sign follows the change of HLC3; 50 when both are 0. Warm-up `n`. - **ADX**: +DI and −DI from Wilder-smoothed directional movement and true range; adx = Wilder average of `100·|+DI − −DI|/(+DI + −DI)`. Warm-up `n` for the DIs, `2n − 1` for adx. - **ATR**: Wilder average of the true range. Warm-up `n`. - **OBV**: running total of volume, added on up closes and subtracted on down closes. Warm-up 0. - **CMF**: `Σ(MFM·V)/ΣV` over `n` bars, `MFM = ((C − L) − (H − C))/(H − L)`. Warm-up `n − 1`. - **ROC**: `100·(P / P[n bars ago] − 1)`. Warm-up `n`. - **Momentum**: `P − P[n bars ago]`. Warm-up `n`. - **TRIX**: percent change of `EMA(EMA(EMA(P, n), n), n)` from the previous bar. Warm-up `3(n − 1) + 1`. - **Aroon**: `100·(n − bars since the highest high)/n` (up) and the same for the lowest low (down), over the last `n + 1` bars. Warm-up `n`. ## Styling outputs `indicator.outputs()` returns the output series. Style them with `applyOptions`, as any series (see [Series](https://ferrochart.com/docs/series)): ```ts const [macdLine, signalLine, hist] = macd.outputs(); macdLine.applyOptions({ color: '#2962ff', lineWidth: 2 }); signalLine.applyOptions({ color: '#ff9800', lineStyle: 'dashed' }); hist.applyOptions({ color: '#787b86' }); const [upper, mid, lower] = boll.outputs(); mid.applyOptions({ lineStyle: 'dotted' }); ``` Outputs are created with a line width of 1 CSS px (points: 3, the dot diameter), a fixed color per output, `priceLineVisible: false` and the last value label shown. Each `outputs()` call returns new handles to the same series; compare them by `id`. An output cannot be removed on its own: `series.remove()` on it throws. Remove the indicator instead. ### Bands BOLL and Keltner fill the area between their upper and lower lines; Ichimoku fills the cloud between span A and span B (green where A is above B, red below). `indicator.bands()` returns the ids of these fills; change their colors with `chart.setBandOptions`: ```ts const [band] = boll.bands(); chart.setBandOptions(band, { fill: 'rgba(41, 98, 255, 0.08)' }); const ichimoku = chart.addIndicator(candles, 'ichimoku'); const [cloud] = ichimoku.bands(); chart.setBandOptions(cloud, { fill: 'rgba(38, 166, 154, 0.25)', fillCrossed: 'rgba(239, 83, 80, 0.25)' }); console.log(chart.bandOptions(cloud)); // { fill, fillCrossed } ``` | Band option | Meaning | |---|---| | `fill` | Where the upper output is at or above the lower one | | `fillCrossed` | Where it is below | `null` restores the default: for BOLL and Keltner, the upper line's color at 15% opacity (`fillCrossed`: as `fill`). Pass `'transparent'` to hide a fill. Other indicators have no bands; `bands()` returns an empty array. ## Removing ```ts macd.remove(); ``` `remove()` takes off the indicator, its output series, their price lines and markers, its bands, any indicators computed from its outputs, and the pane it created if that pane is now empty. Afterwards, `outputs()`, `bands()` and `remove()` on the object throw. Removing the source series removes its indicators. ## Changing parameters Parameters cannot be changed in place. Remove the indicator and add it again. To keep custom styles, read them first: ```ts import type { FerroChart, Indicator, Series, Placement } from '@ferrochart/core'; function replaceIndicator( chart: FerroChart, old: Indicator, source: Series, name: string, params: Record, placement?: Placement, ): Indicator { // `shift` is set by the indicator (Ichimoku), so it is not copied. const styles = old.outputs().map((s) => { const { shift, ...style } = s.options(); return style; }); old.remove(); const next = chart.addIndicator(source, name, params, placement); next.outputs().forEach((s, i) => { if (styles[i]) s.applyOptions(styles[i]); }); return next; } let sma = chart.addIndicator(candles, 'sma', { n: 20 }); sma = replaceIndicator(chart, sma, candles, 'sma', { n: 50 }); ``` Removing an oscillator also removes the pane it created (when nothing else is on it), so the replacement gets a new pane at the bottom. To keep an oscillator in a fixed place, create the pane yourself with `chart.addPane()` and pass its id as the placement: a pane you created is not removed with the indicator. ## Errors `addIndicator` throws an `Error` and changes nothing when: | Problem | Message (example) | |---|---| | Unknown name | `unknown indicator 'smaa'` | | A period that is not a whole number ≥ 0 | `'n' must be a non-negative integer` | | A period of 0 | `invalid argument: periods must be at least 1` | | `hma` with `n` below 2 | `invalid argument: the period is too short` | | A multiplier ≤ 0 or not finite | `invalid argument: multipliers must be finite and > 0` | | `afStart` above `afMax` | `invalid argument: af_start must not exceed af_max` | | A non-number where a number is expected | `'k' must be a finite number` | | Unknown `source` | `unknown source 'median'` | | Invalid VWAP `anchor` | `'anchor' must be 'day', 'week', 'month' or a time in ms` | | `utcOffsetMs` not a whole number | `'utcOffsetMs' must be an integer` | | Invalid `placement` | `placement must be 'default', 'overlay', 'newPane', 'volume' or a pane id` | | Unknown pane id | `unknown id` | | A volume series as source | `invalid argument: volume series have no data of their own; use the source series` | | A volume indicator on a source without volume | `invalid argument: the indicator needs volume` | ```ts try { chart.addIndicator(candles, 'rsi', { n: 0 }); } catch (e) { console.error((e as Error).message); // invalid argument: periods must be at least 1 } ``` ## Live updates Indicators follow their source by themselves: - `series.update(bar)` with the time of the last bar updates the last value of every output; with a later time it appends one. Only the new or changed bar is computed, not the whole series. - `series.setData(...)` recomputes the indicators over the new data. The results of incremental updates are the same as computing over the whole series again. The outputs change in the same frame as the source. ```ts const rsi = chart.addIndicator(candles, 'rsi').outputs()[0]; feed.onTick((bar) => { candles.update(bar); const last = chart.dataRange(); if (last) console.log('RSI', rsi.dataAt(last.to)?.value); }); ``` ## Listing the names ```ts import init, { indicatorNames } from '@ferrochart/core'; await init(); // not needed once a chart has been created console.log(indicatorNames()); // ['sma', 'ema', ..., 'aroon'] ``` --- Source: https://ferrochart.com/docs/drawings # Drawing tools Drawings are objects placed on the chart by the user or by code: trend lines, rectangles, Fibonacci tools, positions, patterns, text and more. Each drawing has anchors in data space (time and price), so it stays attached to the bars when the chart is panned, zoomed or resized. FerroChart handles creation, selection, dragging, deletion and undo/redo itself; your page only arms a tool and, if it wants, reacts to the drawing events. ## The Drawings object All drawing methods are on `chart.drawings`: ```ts const drawings = chart.drawings; drawings.startTool('trend_line'); // the next clicks draw a trend line const id = drawings.add({ // or add one from code kind: 'horizontal_line', anchors: [{ time: Date.UTC(2024, 0, 2), price: 101.5 }], }); drawings.setStyle(id, { line: '#ef5350', lineWidth: 2 }); drawings.undo(); ``` Drawings are identified by numeric ids. Ids are never reused within a chart; an undo that brings a drawing back restores its old id. | Method / property | What it does | |---|---| | `kinds()` | Kinds that `add` and `startTool` accept (the 29 built-in ones plus registered ones) | | `startTool(kind)` / `cancelTool()` / `activeTool` | Interactive creation | | `add(data, pane?)` | Adds a drawing; returns its id | | `get(id)` | The drawing's `DrawingData` (kind, anchors, style, params), `null` for an unknown id | | `ids()` | All ids, bottom to top | | `paneOf(id)` | The pane id of a drawing | | `setAnchors(id, anchors)` | Moves the anchors | | `setStyle(id, style)` | Changes some style keys | | `setParam(id, key, value)` | Sets a tool parameter (`text`, `levels`, `quantity`, `currency`) | | `select(id)` / `selected` | Selection | | `setVisible(id, visible)` / `isVisible(id)` | Show or hide | | `setLocked(id, locked)` / `isLocked(id)` | Lock against dragging | | `bringToFront(id)` / `sendToBack(id)` | Z order | | `remove(id)` | Removes a drawing | | `undo()` / `redo()` / `canUndo` / `canRedo` / `clearHistory()` | History | | `register(kind, tool)` | Adds a drawing tool written in JavaScript | Methods that take an id throw for an unknown id (except `get`, `paneOf`, `isVisible` and `isLocked`, which return `null` or `undefined`). Drawings are saved and restored with the chart state (see [Saving state](https://ferrochart.com/docs/state)). ## Built-in kinds Kind names are snake_case strings. **Lines** | Kind | Anchors | Notes | |---|---|---| | `trend_line` | 2 | Segment between the anchors | | `ray` | 2 | From the first anchor through the second to the plot edge | | `extended_line` | 2 | Through both anchors, to both plot edges | | `horizontal_line` | 1 | Across the plot at the anchor's price, with a price label at the right edge | | `horizontal_ray` | 1 | From the anchor to the right edge, with a price label | | `vertical_line` | 1 | Across the plot at the anchor's time | | `arrow` | 2 | Segment with an arrow head at the second anchor | **Shapes and text** | Kind | Anchors | Notes | |---|---|---| | `parallel_channel` | 3 | Line through the first two anchors and a parallel copy through the third; filled, with a dashed middle line | | `rectangle` | 2 | Opposite corners; filled | | `ellipse` | 2 | Inscribed in the rectangle of the two anchors; filled | | `text` | 1 | Text starting at the anchor. Parameter `text` (default `'Text'`). Drawn on a `fill`-colored background when the fill is not transparent | | `callout` | 2 | A text box at the second anchor with a leader line to the first. Parameter `text` (default `'Callout'`). The box is filled with the line color, the text is white | | `path` | 2 or more | Polyline; one click per point, finished with a double click or Enter | | `brush` | 2 or more | Freehand line: press, drag and release. No handles; it is moved as a whole | **Measurements and positions** | Kind | Anchors | Notes | |---|---|---| | `price_range` | 2 | Shaded range with the price change and percent change from the first anchor to the second | | `date_range` | 2 | Shaded range with the number of bars and the duration | | `long_position` | 3 (2 clicks) | Entry (first anchor), target (second) and stop (third). The stop mirrors the target around the entry when created. Profit and loss areas, labels with prices and percentages, and the reward/risk ratio. Parameters `quantity` and `currency` (see [Chart trading](https://ferrochart.com/docs/drawings#chart-trading)) | | `short_position` | 3 (2 clicks) | As `long_position`, with percentages for a short trade | **Fibonacci and Gann** | Kind | Anchors | Notes | |---|---|---| | `fib_retracement` | 2 | A level line at `p2 + (p1 − p2) · level` for each level, labelled `level (price)`, with alternating shaded bands. Parameter `levels` (default `[0, 0.236, 0.382, 0.5, 0.618, 0.786, 1]`) | | `fib_extension` | 3 | Levels at `p3 + (p2 − p1) · level`, drawn from the third anchor. Parameter `levels` (default `[0, 0.382, 0.618, 1, 1.272, 1.618, 2, 2.618]`) | | `fib_time_zones` | 2 | Vertical lines at bar `i1 + (i2 − i1) · F` for the Fibonacci numbers F = 0, 1, 2, 3, 5, 8, … | | `gann_fan` | 2 | Rays from the first anchor with slopes 1/8 … 8 times that of the line to the second anchor, labelled `1x8` … `8x1` | | `pitchfork` | 3 | Andrews' pitchfork: median line from the first anchor through the midpoint of the other two, with parallel tines through them; filled between the tines | | `schiff_pitchfork` | 3 | As `pitchfork`, with the origin moved halfway towards the second anchor in price | | `modified_schiff_pitchfork` | 3 | As `pitchfork`, with the origin at the midpoint of the first two anchors | **Patterns and waves** | Kind | Anchors | Notes | |---|---|---| | `xabcd_pattern` | 5 | Points X, A, B, C, D with the retracement ratios between the legs; the XAB and BCD triangles are filled | | `head_and_shoulders` | 7 | Labels for left shoulder, head and right shoulder, and the neckline through the third and fifth anchors; filled | | `elliott_impulse` | 6 | Waves labelled 0 to 5 | | `elliott_correction` | 4 | Waves labelled 0, A, B, C | `p1`, `p2`, `p3` are the anchors' prices in order. Labels of patterns and waves go above peaks and below troughs. ## Creating drawings interactively ```ts chart.drawings.startTool('rectangle'); ``` `startTool(kind)` arms a tool. The cursor becomes a crosshair over the plots, and the next press on any pane starts a drawing there. An unknown kind throws. Arming a tool cancels a drawing in progress. How the drawing is completed depends on the kind: - **Fixed number of anchors** (most kinds): the first press places the first anchor; the next anchor follows the pointer until you click again, and so on until the last anchor is placed. One-anchor kinds (`horizontal_line`, `horizontal_ray`, `vertical_line`, `text`) are finished by the first press. The first two anchors can also be placed by pressing, dragging and releasing. - **Open** (`path`): one click per anchor. A double click or Enter finishes it (the duplicate point of the double click is dropped). Finishing needs at least two anchors. - **Freehand** (`brush`): press, drag and release. An anchor is added every 3 CSS px of movement. A stroke with fewer than two anchors is dropped. While placing anchors, x snaps to the nearest bar (times past the last bar are extrapolated), and in magnet crosshair mode y snaps to the nearest open, high, low or close. Freehand anchors are not snapped. When a drawing is finished, it is selected, the `drawingCreated` event is sent, and **the tool is disarmed**: one `startTool` creates one drawing. To keep drawing the same kind, arm it again in the `drawingCreated` listener (see the toolbar example below). | Key | While creating | |---|---| | Escape | Cancels the drawing in progress (a `path` with at least two anchors is finished instead), or disarms an armed tool | | Enter | Finishes a `path` | `cancelTool()` disarms the tool and drops a drawing in progress, without an event. `activeTool` is the armed kind, or the kind of the drawing being created; it is `undefined` otherwise. No `click` events are sent while a drawing is being created. ## Selecting and editing Without an armed tool: - **Pressing a drawing** selects it (`drawingSelected`). Its handles appear: one per anchor for most kinds; positions have handles for the entry, target, stop and right edge; horizontal and vertical lines have one in the middle of the plot; brushes have none. - **Dragging** the drawing moves it: whole bars horizontally, following the pointer vertically. Dragging a handle moves that anchor. A finished drag sends `drawingModified`. Escape during a drag puts the drawing back. - **Pressing empty space** clears the selection. - The selected drawing's handles are hit first, then the selected drawing, then the other drawings from the top. - Hidden drawings cannot be hit. Rectangles, ellipses and channels are hit on their outline, or anywhere inside when their fill is not transparent. A press on a drawing is not a pan. A press on a locked drawing selects it and then pans the chart. ### Keyboard The canvas takes keyboard input when it has focus; it is focused when pressed. | Key | Effect | |---|---| | Delete | Removes the selected drawing (locked ones too) | | Escape | Cancels creation, disarms the tool, or undoes the current drag | | Enter | Finishes a `path` being created | | Ctrl+Z / ⌘+Z | Undo | | Ctrl+Shift+Z / ⌘+Shift+Z, Ctrl+Y / ⌘+Y | Redo | Backspace does nothing. To delete with another key, listen on the canvas yourself: ```ts canvas.addEventListener('keydown', (e) => { const id = chart.drawings.selected; if (e.key === 'Backspace' && id != null) chart.drawings.remove(id); }); ``` ## Adding drawings from code ```ts const id = chart.drawings.add({ kind: 'fib_retracement', anchors: [ { time: Date.UTC(2024, 0, 10), price: 120 }, { time: Date.UTC(2024, 1, 20), price: 95 }, ], style: { line: '#787b86', fill: 'rgba(120, 123, 134, 0.15)' }, params: { levels: [0, 0.382, 0.5, 0.618, 1] }, }); ``` ```ts interface DrawingData { kind: string; anchors: { time: number | bigint; price: number }[]; style?: DrawingStyle; params?: Record; } ``` - `time` is UTC milliseconds (an integer). It need not be the time of a bar. - `price` is in the units of the pane's first price series and must be finite. - The number of anchors must match the kind: exactly as in the table for most kinds; 2 or 3 for positions (with 2, the stop is added as the mirror of the target); 2 to 4096 for `path` and `brush`. - `pane` defaults to the main pane. Pass a pane id to draw on another pane. - Missing style keys take the defaults below; parameter keys a kind does not use are ignored. `add` throws, and adds nothing, for an unknown kind, too few or too many anchors, a non-finite price, an unknown pane, an invalid style or an invalid parameter. A drawing added from code is not selected. `get(id)` returns the saved form with every key: `kind`, `anchors`, the full `style`, and `params` with the kind's parameters (`text` for `text` and `callout`, `levels` for the Fibonacci retracement and extension, `quantity` and `currency` for positions that have them). Pass it to `add` to copy a drawing: ```ts const copy = chart.drawings.get(id); if (copy) chart.drawings.add(copy, chart.drawings.paneOf(id)); ``` `setAnchors(id, anchors)` moves a drawing. It needs the same number of anchors the drawing has (3 for a finished position). ## Style ```ts chart.drawings.setStyle(id, { line: '#26a69a', lineWidth: 2, lineDash: 'dashed' }); ``` | Key | Type | Default | Used for | |---|---|---|---| | `line` | `Color` | `#2962ff` | Lines and outlines; label backgrounds of ranges and positions; callout boxes | | `lineWidth` | `number` | `1` | CSS px, greater than 0 | | `lineDash` | `'solid' \| 'dashed' \| 'dotted'` | `'solid'` | Dash pattern of lines | | `fill` | `Color` | `#2962ff` at 16% opacity | Areas: channels, rectangles, ellipses, ranges, Fibonacci bands, pitchforks, pattern triangles, the text background | | `text` | `Color` | `#2962ff` | Text and labels without a background | | `fontSize` | `number` | `12` | CSS px, texts and labels | `setStyle` changes only the keys you pass. Colors cannot be `null`; use `'transparent'` for no fill. The profit and loss areas of positions have fixed green and red colors. ## Parameters ```ts chart.drawings.setParam(textId, 'text', 'Breakout'); chart.drawings.setParam(fibId, 'levels', [0, 0.5, 1, 1.618]); ``` | Parameter | Kinds | Value | |---|---|---| | `text` | `text`, `callout` | A string | | `levels` | `fib_retracement`, `fib_extension` | Up to 24 finite numbers | | `quantity` | `long_position`, `short_position` | A finite number above 0; not set by default | | `currency` | `long_position`, `short_position` | A string of at most 8 bytes (UTF-8), written before amounts; empty by default | A value of the wrong type throws and leaves the drawing unchanged. Style and parameter changes send `drawingModified` and can be undone. ## Visibility, locking and order ```ts chart.drawings.setVisible(id, false); // hidden drawings are not drawn or hit chart.drawings.setLocked(id, true); // can be selected and deleted, not dragged chart.drawings.bringToFront(id); chart.drawings.sendToBack(id); console.log(chart.drawings.isVisible(id), chart.drawings.isLocked(id), chart.drawings.ids()); ``` Hiding the selected drawing clears the selection. Locking does not prevent `setAnchors`, `setStyle` or `remove` from code. Visibility, locking and order send no events and are not part of the undo history; they are saved with the chart state. ## Selection ```ts chart.drawings.select(id); // selects it and shows its handles chart.drawings.select(null); // clears the selection const sel = chart.drawings.selected; // the selected id, or undefined ``` ## Removing ```ts chart.drawings.remove(id); for (const d of chart.drawings.ids()) chart.drawings.remove(d); // remove all ``` Removing a pane removes its drawings; if it had any, the undo history is cleared. ## Undo and redo These changes are recorded, whether made by the user or by code: adding, removing, moving (dragging, `setAnchors`), and changing the style or a parameter. Selection, visibility, locking and z order are not. ```ts chart.drawings.undo(); // false if there was nothing to undo chart.drawings.redo(); if (chart.drawings.canUndo) { /* enable the undo button */ } chart.drawings.clearHistory(); ``` The history keeps the last 256 changes. A new change clears the redo list. `undo` and `redo` cancel a drawing in progress. Loading a state (`loadState`) clears the history. Drawings received from a sync group are not recorded. ## Drawing events | Event | Payload | When | |---|---|---| | `drawingCreated` | `{ id }` | A drawing was finished by the user, added from code, restored by undo/redo or loaded | | `drawingModified` | `{ id }` | It was moved, restyled or had a parameter changed | | `drawingRemoved` | `{ id }` | It was removed | | `drawingSelected` | `{ id: number \| null }` | The selection changed | Events arrive after the frame in which the change happened, not inside the method call. See [Crosshair and events](https://ferrochart.com/docs/crosshair-events). ```ts chart.on('drawingCreated', (e: ChartEventMap['drawingCreated']) => { const d = chart.drawings.get(e.id); console.log('new', d?.kind, d?.anchors); }); ``` ## Example: a toolbar ```html
``` ```ts import { FerroChart, type ChartEventMap } from '@ferrochart/core'; const canvas = document.getElementById('chart') as HTMLCanvasElement; const chart = await FerroChart.create(canvas); const candles = chart.addCandlestickSeries(); candles.setData(bars); const d = chart.drawings; const toolbar = document.getElementById('toolbar') as HTMLDivElement; const sticky = document.getElementById('sticky') as HTMLInputElement; const button = (id: string) => document.getElementById(id) as HTMLButtonElement; let lastKind: string | null = null; function refresh() { const active = d.activeTool ?? null; toolbar.querySelectorAll('button[data-kind]').forEach((b) => { b.classList.toggle('active', b.dataset.kind === active); }); const sel = d.selected; button('delete').disabled = sel == null; button('lock').disabled = sel == null; button('lock').textContent = sel != null && d.isLocked(sel) ? 'Unlock' : 'Lock'; button('undo').disabled = !d.canUndo; button('redo').disabled = !d.canRedo; } toolbar.addEventListener('click', (e) => { const kind = (e.target as HTMLElement).closest('button[data-kind]')?.dataset.kind; if (!kind) return; if (d.activeTool === kind) { d.cancelTool(); lastKind = null; } else { d.startTool(kind); lastKind = kind; } canvas.focus(); // so that Escape and Enter reach the chart refresh(); }); button('delete').onclick = () => { const sel = d.selected; if (sel != null) d.remove(sel); }; button('lock').onclick = () => { const sel = d.selected; if (sel != null) d.setLocked(sel, !d.isLocked(sel)); refresh(); }; button('undo').onclick = () => d.undo(); button('redo').onclick = () => d.redo(); chart.on('drawingCreated', (_e: ChartEventMap['drawingCreated']) => { if (sticky.checked && lastKind && d.activeTool == null) d.startTool(lastKind); refresh(); }); chart.on('drawingModified', refresh); chart.on('drawingRemoved', refresh); chart.on('drawingSelected', refresh); // Escape disarms a tool without an event. canvas.addEventListener('keyup', refresh); refresh(); ``` Undo and redo triggered from the buttons send `drawingCreated`, `drawingModified` or `drawingRemoved` after the next frame, which refreshes the buttons. ## Chart trading Long and short positions can show a size, and the optional module `@ferrochart/core/trading` adds an order ticket, order lines, an order button, buy and sell buttons, ladder orders, trailing stops, liquidation prices and trade markers. The tools only report **intents**: what the user wants to do. They make no network requests and keep no accounts or credentials. Sending orders, signing them and checking risk belong to your application. ### Position size `long_position` and `short_position` take the parameters `quantity` and `currency`. With a quantity, the target and stop labels show the percentage and the profit or loss (price difference × quantity) instead of the price, and the entry label shows the side, the quantity and the reward/risk ratio. `currency` is the sign written before the amounts. ```ts const id = chart.drawings.add({ kind: 'long_position', anchors: [ { time: Date.UTC(2024, 0, 10), price: 100 }, // entry { time: Date.UTC(2024, 0, 20), price: 106 }, // target { time: Date.UTC(2024, 0, 20), price: 98 }, // stop ], params: { quantity: 250, currency: '$' }, }); chart.drawings.setParam(id, 'quantity', 100); ``` `riskQuantity` gives the quantity that loses `risk` between `entry` and `stop`, rounded down to a multiple of `step` (optional). It returns 0 when there is none: no distance, no risk, or less than one step. ```ts import { riskQuantity } from '@ferrochart/core/trading'; riskQuantity({ entry: 100, stop: 98, risk: 500, step: 0.1 }); // 250 ``` ### Order ticket `createTradeTicket(chart, series, options)` shows a card beside the selected position, with its side, quantity and risk and a Place order button. It is placed after the canvas, so the canvas' parent should be positioned (`position: relative`). On a canvas narrower than 480 CSS px the card is docked below the canvas if the parent has room there (about 96 px), and over the canvas' bottom otherwise. | Option | Meaning | |---|---| | `canvas` | The chart's canvas; required | | `onPlaceOrder(intent)` | Called by the button, which waits for the returned promise; the message of a rejection is shown. Required | | `risk` | Amount to lose at the stop; sizes positions that have no quantity | | `currency` | Sign written before amounts on the drawing, at most 8 bytes | | `priceStep` | Prices of intents are rounded to a multiple of this | | `quantityStep` | Quantities are multiples of this | | `text` | Texts of the card, to translate them: `long`, `short`, `quantity`, `risk`, `placeOrder`, `placing`, `failed` | A position sized by risk follows its entry and stop until the user types a quantity; typing a risk sizes it by risk again. The button is enabled when the position has a quantity and its target and stop are on the right sides of the entry. The intent has `side` (`'buy'` or `'sell'`), `entry`, `target`, `stop`, `quantity` and `drawing`, the id of the position drawing. ### Order lines `createTradingLines(chart, series, options?)` manages [price lines](https://ferrochart.com/docs/markers#price-lines) for orders, positions, take profits and stops. `set(line)` adds a line or replaces the one with the same `id`; `get(id)`, `ids()` and `remove(id)` read and remove them. | Line field | Meaning | |---|---| | `id` | Your own id, a string or a number | | `kind` | `'order'`, `'position'`, `'takeProfit'`, `'stopLoss'` or `'liquidation'` (solid orange) | | `price` | Price, must be finite | | `quantity` | Shown in the default title | | `title` | Text at the right end; by default the kind and quantity | | `color` | By default the color of the kind | | `draggable` | Default `true`, `false` for positions and liquidations | When the user drops a line, `onModify({ id, kind, from, price })` is called. The line cannot be dragged again until the returned promise settles. A rejection or `false` puts the line back to `from`; `onError(error, id)` receives a rejection. Lines that you `set` or remove in the meantime keep your state. Without `onModify`, lines cannot be dragged. `priceStep` rounds dragged prices. ### Order button `createOrderButton(chart, series, options)` shows a "+" at the crosshair's height, beside the price axis of the main pane. Tapping it, or right-clicking an empty part of the plot, opens a menu with the two orders that make sense at that price: below the last price a buy limit and a sell stop, above it a sell limit and a buy stop, at it a buy limit and a sell limit. A right click on a drawing, a price line or an axis is left to the page. On touch screens a long press shows the crosshair and the "+", which stay after the finger lifts. | Option | Meaning | |---|---| | `canvas` | The chart's canvas; its parent should be positioned. Required | | `lastPrice()` | The last traded price; nothing is offered while it is not positive. Required | | `onOrder(intent)` | Receives `{ side, type: 'limit' \| 'stop', price, quantity }`. The menu waits for the returned promise and shows the message of a rejection. Required | | `quantity` | A number, or a function that returns one (e.g. from your own field); items are disabled while it is not positive. Required | | `priceStep` | Prices are rounded to a multiple of this and shown with its decimals | | `formatPrice(price)` | Text of a price in the menu | | `text` | Translations: `buyLimit`, `sellLimit`, `buyStop`, `sellStop`, `add` (the accessible name of the "+"), `failed` | The menu has `role="menu"`: the arrow keys move, Enter chooses, and Escape, a click outside or panning the chart close it. `open(price)` opens it from your own control and `close()` closes it. ### Buy and sell buttons `createQuickTrade(chart, options)` puts a sell button (at the bid) and a buy button (at the ask) over the top left of the plot, with the spread and a quantity field between them. Each click sends a market order `{ side, type: 'market', quantity }` to `onOrder`. Prices come from your feed through `setQuote({ bid, ask })`; without a quote (`setQuote(null)`) or a quantity the buttons are disabled. By default the first click arms a button (it reads Confirm) and a second click within 3 seconds sends; Escape cancels. Pass `confirm: false` to send on the first click. | Option | Meaning | |---|---| | `canvas` | The chart's canvas; its parent should be positioned. Required | | `onOrder(intent)` | Sends the order; the buttons wait for the returned promise and show the message of a rejection. Required | | `quantity` | Initial quantity; the user can change it, and `quantity` reads or sets it | | `quantityStep` | Typed quantities are rounded down to a multiple of this | | `confirm` | Default `true` | | `priceStep` | Prices are shown with its decimals; by default with 6 significant digits | | `formatPrice(price)` | Text of the bid, the ask and the spread; overrides `priceStep` | | `text` | Translations: `buy`, `sell`, `confirm`, `quantity`, `spread`, `failed` | ```ts import { createOrderButton, createQuickTrade } from '@ferrochart/core/trading'; let last = 0; const quick = createQuickTrade(chart, { canvas, quantity: 1, quantityStep: 0.001, onOrder: (i) => send('/orders', i) }); const button = createOrderButton(chart, candles, { canvas, priceStep: 0.5, lastPrice: () => last, quantity: () => quick.quantity, onOrder: (i) => send('/orders', i), }); feed.onquote = ({ bid, ask, price }) => { last = price; quick.setQuote({ bid, ask }); }; ``` ### Line triggers The optional module `@ferrochart/core/trading-trigger` fires when the price reaches or crosses a drawn line: an order or an alert, depending on what your `onTrigger` does. `createLineTrigger(chart, drawingId, options)` watches a `trend_line` (between its anchors), `ray` (from the first anchor through the second), `extended_line`, `horizontal_line` or `horizontal_ray` (from its anchor on). Other kinds throw a `TypeError`. Call `update(time, price)` with each price, where `time` is usually the opening time of its bar; it returns whether the trigger fired. The line's price at a time follows the chart: straight between bars and beyond the data as drawn, and straight in log price on a logarithmic scale. `lineAt(time)` returns it, or `null` outside a segment or ray. | Option | Meaning | |---|---| | `mode` | `'touch'` (default): the price reaches or crosses the line. `'crossUp'`: from below to on or above it. `'crossDown'`: from above to on or below it. `'close'`: only updates with `closed` true (`update(time, price, true)`) count, and the close is on the other side than the last one | | `once` | Default `true`: the trigger stops after firing (`active` becomes `false`) | | `onTrigger(event)` | Receives `{ drawing, mode, time, price, line }`. Called synchronously; what it throws goes to the caller of `update`. Required | The first update only takes a base, and so does the first update after the price was outside the segment and the first one after the user moved the line: dragging a line over the price does not fire it. A removed drawing makes the trigger inactive. `destroy()` removes its listeners. ```ts import { createLineTrigger } from '@ferrochart/core/trading-trigger'; const breakout = createLineTrigger(chart, lineId, { mode: 'crossUp', onTrigger: ({ price }) => send('/orders', { side: 'buy', type: 'market', quantity: 1, price }), }); const alert = createLineTrigger(chart, supportId, { mode: 'close', once: false, onTrigger: ({ line }) => new Notification(`Closed through ${line.toFixed(2)}`), }); feed.ontick = ({ barTime, price }) => breakout.update(barTime, price); feed.onclose = (bar) => alert.update(bar.time, bar.close, true); ``` `logicalIndexOf(chart, time)`, from the same module, gives the logical index of any time by the same rules. ### Ladder orders `ladderOrders(options)` splits a quantity into `count` (1–1000) limit orders evenly spaced from `from`, the price nearest the market, to `to`. It returns intents `{ side, type: 'limit', price, quantity }` and sends nothing; preview them with order lines before sending. | Option | Meaning | |---|---| | `side` | `'buy'` or `'sell'` | | `from`, `to` | Prices of the first (nearest) and last (farthest) orders | | `count` | Number of orders, 1–1000 | | `total` | Quantity shared by the orders; their sum never exceeds it | | `distribution` | `'flat'` (default, equal), `'linear'` (1, 2, …, n) or `'geometric'` (`ratio` to the power k) | | `ratio` | Of `'geometric'`; default 1.5 | | `priceStep` | Prices are rounded to a multiple of this | | `quantityStep` | Quantities are rounded down to a multiple of this; the remainder goes to the farthest order | Orders that round to the same price are merged and orders with no quantity are dropped, so there may be fewer than `count`. For a grid, call it once below the market and once above. Re-placing filled grid orders is your application's. ```ts import { ladderOrders } from '@ferrochart/core/trading'; ladderOrders({ side: 'buy', from: 99, to: 95, count: 5, total: 1, distribution: 'linear', quantityStep: 0.01 }); // 99 × 0.06, 98 × 0.13, 97 × 0.2, 96 × 0.26, 95 × 0.35 ``` ### Trailing stop `trailingStop(options)` keeps a stop at `distance` (a price difference) or `percent` (1 = 1%) from the market. `update(price)` returns the new stop when it moved, else `null`; `stop` and `active` read the state. The stop only moves in the position's favour, below the price for a long (`side: 'buy'`) and above it for a short. With `activation` it starts to trail when the price reaches that level; `stop` is the initial stop; `priceStep` rounds stops away from the market. Prices that are not positive and finite are ignored. ```ts import { trailingStop } from '@ferrochart/core/trading'; // `send` and `lines` as in the example at the end of this chapter. const trail = trailingStop({ side: 'buy', distance: 2, activation: 105, stop: 95, priceStep: 0.5 }); socket.onmessage = async ({ data }) => { const stop = trail.update(JSON.parse(data).price); if (stop !== null) { await send('/orders/modify', { id: 'sl', price: stop }); lines.set({ id: 'sl', kind: 'stopLoss', price: stop }); } }; ``` ### Liquidation price `liquidationPrice({ side, entry, quantity, margin, maintenanceRate })` estimates where a linear contract with isolated margin is liquidated, with one maintenance margin rate and no fees: `(entry − margin / quantity) / (1 − maintenanceRate)` for a long, `(entry + margin / quantity) / (1 + maintenanceRate)` for a short. It returns `null` when the result is not positive. Exchanges differ (fees, margin tiers, cross margin), so prefer the price your exchange reports and use this for previews. ```ts import { liquidationPrice } from '@ferrochart/core/trading'; // 10× long: 1 BTC at 60,000 with 6,000 margin, 0.5% maintenance. const liq = liquidationPrice({ side: 'buy', entry: 60_000, quantity: 1, margin: 6_000, maintenanceRate: 0.005 }); if (liq !== null) lines.set({ id: 'liq', kind: 'liquidation', price: liq }); // ≈ 54,271 ``` ### Trade markers `tradeMarkers(fills, options?)` turns fills `{ id?, time, price, quantity, side }` into [markers](https://ferrochart.com/docs/markers) at their price: an arrow up for buys and down for sells. Fills of the same bar and side are merged at their average price, weighted by quantity, and each marker keeps its fills in `fills`, which `click` and `markerHover` hand back. An integer `id` of a marker's first fill becomes the marker's `id`. `setMarkers` replaces all markers of a series, so merge them with your own. | Option | Meaning | |---|---| | `times` | Opening times of the bars, ascending (e.g. your `time` column). Fills are moved to the bar they happened in, and fills before the first bar are dropped. Without it only fills at the same time are merged | | `buyColor`, `sellColor` | Default `'#26a69a'` and `'#ef5350'` | | `size` | Diameter in CSS px, 4–64 | | `text` | `(m) => string` with `side`, `price`, `quantity` and `fills`; default `'B 2'` or `'S 2'`; `false` for none | ```ts import { tradeMarkers } from '@ferrochart/core/trading'; candles.setMarkers([...myMarkers, ...tradeMarkers(fills, { times: bars.time })]); ``` ### Example: from position to order Call `destroy()` on the ticket, the lines, the triggers and the other tools before `chart.destroy()`. ```ts import { FerroChart } from '@ferrochart/core'; import { createTradeTicket, createTradingLines } from '@ferrochart/core/trading'; const canvas = document.getElementById('chart') as HTMLCanvasElement; const chart = await FerroChart.create(canvas); const candles = chart.addCandlestickSeries(); candles.setData(bars); // your OHLC columns // Your own code: your server checks, signs and sends the order. async function send(path: string, body: object): Promise { const r = await fetch(path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), }); if (!r.ok) throw new Error(`refused: ${r.status}`); } const lines = createTradingLines(chart, candles, { priceStep: 0.5, onModify: ({ id, price }) => send('/orders/modify', { id, price }), onError: (e, id) => console.warn(`${id} not changed`, e), }); const ticket = createTradeTicket(chart, candles, { canvas, risk: 500, currency: '$', priceStep: 0.5, quantityStep: 0.001, async onPlaceOrder(intent) { await send('/orders', intent); const { entry, target, stop, quantity, drawing } = intent; lines.set({ id: 'entry', kind: 'order', price: entry, quantity }); lines.set({ id: 'tp', kind: 'takeProfit', price: target, quantity }); lines.set({ id: 'sl', kind: 'stopLoss', price: stop, quantity }); chart.drawings.remove(drawing); }, }); chart.drawings.startTool('long_position'); // two clicks: entry, then target // When the page removes the chart: function dispose() { ticket.destroy(); lines.destroy(); chart.destroy(); } ``` ## Custom tools `chart.drawings.register(kind, tool)` adds a drawing tool written in JavaScript. The tool says how it is created (`anchorCount`: a number of clicks, `{ open: min }` or `'freehand'`) and returns drawing commands from `build(ctx)`; an optional `hitTest` decides what a press hits. The kind is available to this chart's `add`, `startTool` and `loadState`; built-in kinds cannot be replaced. See [Plugins](https://ferrochart.com/docs/plugins#drawing-tools). --- Source: https://ferrochart.com/docs/state # Saving and restoring `chart.saveState()` returns the parts of a chart the user changes by working with it: the zoom, the scroll position, pane heights, price scale settings, the crosshair mode and the drawings. `chart.loadState(state)` puts them back. The state is plain JSON-compatible data, so you can keep it in `localStorage`, a file or your server. ```ts import { FerroChart, type ChartState } from '@ferrochart/core'; declare const chart: FerroChart; const state: ChartState = chart.saveState(); localStorage.setItem('chart-layout', JSON.stringify(state)); ``` ## What a state contains | Field | Contents | |---|---| | `version` | Format version, currently `1` | | `barSpacing` | Bar spacing in CSS px (the zoom level) | | `rightOffset` | Empty space right of the last bar, in bars (the scroll position) | | `crosshairMode` | `'normal'`, `'magnet'` or `'hidden'` | | `panes` | One entry per pane, top to bottom (below) | | `drawings` | Every finished drawing, bottom to top (below) | Each `panes` entry: | Field | Contents | |---|---| | `stretch` | Height relative to the other panes | | `priceScale.mode` | `'normal'`, `'logarithmic'`, `'percentage'` or `'indexedTo100'` | | `priceScale.inverted` | Whether higher prices are drawn lower | | `priceScale.margins` | `{ top, bottom }`, fractions of the pane height | | `priceScale.range` | `{ low, high }` when auto-scaling is off (the user dragged the price axis, or you set a range); `null` while auto-scaling | Each `drawings` entry: | Field | Contents | |---|---| | `pane` | Index of the pane, top to bottom (0 is the main pane), not a pane id | | `visible` | Whether it is shown | | `locked` | Whether it is locked against editing | | `data` | `{ kind, anchors, style, params }`, the same as `chart.drawings.get(id)` | Anchors are stored as time (UTC ms) and price, so drawings stay on the right bars when the data changes or more history is loaded. ## What it does not contain The state describes how the user arranged the chart, not what the chart shows. These are **not** saved: - data, series and their options; - indicators, bands, markers and price lines; - layer plugins and registered drawing tools; - the theme, renderer and other `FerroChart.create` options; - sync group membership; - drawing ids, the selection, the armed tool, a drawing still being created, and the undo history. Your application creates all of these itself, then loads the state on top. Keep whatever you need to recreate them (the symbol, interval, indicator list and parameters) next to the state. ## Loading a state `loadState` needs a chart set up the same way as the one that was saved: in particular, **the same number of panes**. Panes are matched by position, so create the series and indicators that add panes (for example `'macd'` or `'rsi'` with their default placement, or `addPane()`) in the same order before loading. Load the data first as well; the restored drawings are placed by time. ```ts import { FerroChart, randomWalk, type ChartState } from '@ferrochart/core'; declare const canvas: HTMLCanvasElement; declare const saved: ChartState; const chart = await FerroChart.create(canvas); const candles = chart.addCandlestickSeries(); candles.setData(randomWalk(1, 2_000, Date.UTC(2024, 0, 1), 60_000)); chart.addVolumeSeries(candles); // same pane: no new pane chart.addIndicator(candles, 'macd'); // adds a pane, as before saving chart.loadState(saved); // two panes on both sides ``` What loading does: - Bar spacing, right offset and crosshair mode are set. - Each pane gets its stretch and price scale settings. A pane saved with a `range` keeps that range with auto-scaling off; a pane saved with `range: null` switches auto-scaling back on. - All current drawings are removed and the saved ones are added. They get new ids, and the chart sends `drawingRemoved` and `drawingCreated` events for them. - The undo history is cleared. ### Drawing tools written in JavaScript A drawing of a kind registered with `chart.drawings.register(kind, tool)` can only be loaded into a chart where that kind is registered. Register your tools before calling `loadState`. See [Drawings](https://ferrochart.com/docs/drawings) and [Plugins](https://ferrochart.com/docs/plugins). ## Errors `loadState` throws an `Error` and leaves the chart unchanged when the state does not fit. Nothing is applied partially. | Cause | Example message | |---|---| | Not an object | `state must be an object from saveState()` | | A required field is missing | `state: missing 'barSpacing'` | | Unknown names | `state: unknown crosshair mode 'x'`, `state: unknown price scale mode 'x'` | | A newer format version | `state version is newer than supported` | | A different number of panes | `state has a different number of panes` | | Bar spacing not finite or not positive, right offset not finite | `invalid bar spacing or right offset` | | Margins outside 0 to 1 (or adding up to 1 or more); a range that is not finite and increasing, or not positive on a logarithmic scale | `invalid price scale state` | | A drawing on a pane index that does not exist | `drawing on a missing pane` | | A drawing the chart cannot build (unknown kind, wrong number of anchors, invalid style or parameters) | depends on the drawing | A pane `stretch` that is not a positive number is replaced by 1 instead of being an error. When a saved state may be stale (for example after you changed the default indicators of your app), catch the error and fall back to the default layout: ```ts import { FerroChart, type ChartState } from '@ferrochart/core'; declare const chart: FerroChart; function restore(chart: FerroChart, json: string | null): boolean { if (json === null) return false; try { chart.loadState(JSON.parse(json) as ChartState); return true; } catch (e) { console.warn('saved layout ignored:', e); return false; } } restore(chart, localStorage.getItem('chart-layout')); ``` ## A complete example The page below keeps one layout per symbol in `localStorage`. The setup function creates everything that is not in the state (series, data, indicators, their colors), and the state restores the rest. The layout is saved whenever the user changes a drawing and when the page is hidden. ```ts import { FerroChart, randomWalk, type ChartState, type Series } from '@ferrochart/core'; declare const canvas: HTMLCanvasElement; /** What the app needs to rebuild a chart; kept next to the chart state. */ interface Layout { symbol: string; indicators: { name: string; params: Record }[]; state: ChartState; } const key = (symbol: string) => `layout:${symbol}`; function loadBars(symbol: string) { // Replace with your data source. const seed = [...symbol].reduce((s, c) => s + c.charCodeAt(0), 0); return randomWalk(seed, 5_000, Date.UTC(2024, 0, 1), 60_000); } async function openChart(symbol: string): Promise { const chart = await FerroChart.create(canvas, { theme: 'dark' }); // 1. Series and data (not part of the state). const candles: Series = chart.addCandlestickSeries(); candles.setData(loadBars(symbol)); chart.addVolumeSeries(candles); // 2. Indicators, in the order they were saved, so the panes match. const json = localStorage.getItem(key(symbol)); const saved: Layout | null = json ? (JSON.parse(json) as Layout) : null; const indicators = saved?.indicators ?? [{ name: 'sma', params: { n: 50 } }, { name: 'rsi', params: { n: 14 } }]; for (const { name, params } of indicators) { chart.addIndicator(candles, name, params); } // 3. The saved view, layout and drawings. if (saved) { try { chart.loadState(saved.state); } catch (e) { console.warn('saved layout ignored:', e); } } // Save after every drawing change and when the page is hidden. const save = () => { const layout: Layout = { symbol, indicators, state: chart.saveState() }; localStorage.setItem(key(symbol), JSON.stringify(layout)); }; for (const event of ['drawingCreated', 'drawingModified', 'drawingRemoved'] as const) { chart.on(event, save); } document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') save(); }); return chart; } await openChart('BTCUSD'); ``` Three details in this example matter in practice: - The indicator list is saved with the state. If the user adds or removes an indicator, the number of panes changes, and an old state would no longer load. - `drawingModified` is sent while the user drags a drawing, up to once per frame. Writing a small state to `localStorage` that often is fine; if you save to a server, debounce the call. - The zoom and scroll position change without any drawing event, which is why the example also saves when the page is hidden. Listen to `visibleRangeChanged` if you need to save them sooner. ## Saving drawings only To keep only the drawings (for example to copy them to another chart with a different pane layout), read them from the drawings API instead of the state: ```ts import { FerroChart, type DrawingData } from '@ferrochart/core'; declare const source: FerroChart; declare const target: FerroChart; const drawings: Required[] = source.drawings .ids() .filter((id) => source.drawings.paneOf(id) === source.mainPane) .map((id) => source.drawings.get(id)) .filter((d): d is Required => d !== null); for (const d of drawings) target.drawings.add(d); // to the main pane ``` To keep drawings in step between open charts instead, see [Synchronizing charts](https://ferrochart.com/docs/sync). --- Source: https://ferrochart.com/docs/sync # Synchronizing charts Charts that join the same `SyncGroup` follow each other: moving the crosshair over one shows it on the others, and panning or zooming one scrolls the others to the same time range. Optionally, drawings made on one appear on the others. ```ts import { FerroChart, SyncGroup } from '@ferrochart/core'; declare const left: HTMLCanvasElement; declare const right: HTMLCanvasElement; const a = await FerroChart.create(left); const b = await FerroChart.create(right); const group = new SyncGroup(); a.joinSync(group); b.joinSync(group); ``` `new SyncGroup()` needs the WebAssembly module. It is loaded by the first `FerroChart.create`; to create a group before any chart, call `await init()` first (`import init from '@ferrochart/core'`). ## Time, not bar numbers Every message between charts carries a **time** (UTC ms), never a logical index. Charts in a group may therefore show different symbols, different intervals, or data with gaps in different places: - A crosshair at 10:37 on a 1-minute chart is shown on a 1-hour chart on the 10:00 bar (the last bar at or before that time). Past either end of the data the time is extrapolated. - After a pan or zoom, the other charts show the same time span from the left edge to the right edge, as far as their bar spacing limits allow (the right edge is kept). A 1-hour chart following a 1-minute chart that shows two hours would need two bars across the whole plot; with the default maximum bar spacing of 50 px it shows more, ending at the same time. A chart without data ignores received ranges. ## Joining and leaving ### `chart.joinSync(group, options?)` Joins `group`, leaving the group the chart was in, if any. At its next frame, the chart takes over the group's current crosshair and visible range. `SyncOptions` choose what the chart shares. Each option works in both directions: a chart with `crosshair: false` neither shows other charts' crosshairs nor sends its own. | Option | Shares | Default | |---|---|---| | `crosshair` | The crosshair time | `true` | | `visibleRange` | The visible time range (pan and zoom) | `true` | | `drawings` | The drawings of the main pane | `false` | ```ts import { FerroChart, SyncGroup } from '@ferrochart/core'; declare const group: SyncGroup; declare const overview: FerroChart; declare const detail: FerroChart; // The overview shows the crosshair of the others but keeps its own zoom. overview.joinSync(group, { visibleRange: false }); detail.joinSync(group); ``` To change the options of a chart, call `joinSync` again with the same group. ### `chart.leaveSync()` Leaves the group. A crosshair this chart showed on the others is removed. `chart.destroy()` leaves the group as well. ### `chart.syncOptions()` What the chart shares, with every option filled in, or `null` when it is not in a group. ```ts import { FerroChart } from '@ferrochart/core'; declare const chart: FerroChart; const opts = chart.syncOptions(); if (opts === null) console.log('not synced'); else console.log(opts.crosshair, opts.visibleRange, opts.drawings); ``` ## What is sent, and when - **Crosshair.** When the pointer moves over a chart's plot, the chart sends the time under the crosshair; when the pointer leaves, it sends that the crosshair is gone. The other charts show a crosshair at that time. Their `crosshairMove` events then have a `point` with `price: NaN`, no `x`/`y`, and `pane` set to the main pane. - **Visible range.** When the view changes, by the user (drag, wheel, pinch, keys) or by your code (`setVisibleLogicalRange`, `setBarSpacing`, `fitContent` and so on), the chart sends the times at its left and right edges. If the chart changed its own view in the same frame, that change wins over a received range. - Applying a received message never sends it again, so messages cannot bounce between charts. A chart that sends a message schedules a frame of the other charts in the group; they apply it when they draw that frame. ## Synchronizing drawings With `drawings: true`, drawings on the **main pane** of a chart are copied to the main pane of the other charts that share drawings: adding, moving, restyling, showing, hiding, locking and removing. Use it for charts of the same symbol (for example several timeframes), since anchors are prices. ```ts import { FerroChart, SyncGroup } from '@ferrochart/core'; declare const group: SyncGroup; declare const m5: FerroChart; declare const h1: FerroChart; m5.joinSync(group, { drawings: true }); h1.joinSync(group, { drawings: true }); // Appears on h1 at its next frame. m5.drawings.add({ kind: 'horizontal_line', anchors: [{ time: Date.UTC(2024, 0, 2), price: 42_000 }], }); ``` Details: - A chart that joins with `drawings: true` first takes over the drawings the group already has, then shares its own. - Drawings on other panes are not shared (other panes may show different indicators on each chart). Received drawings always go to the main pane. - Received changes are not added to the receiving chart's undo history. Undo and redo on the chart where a change was made are sent like any other change, so all charts end up the same. - The selection and a drawing still being created are not shared. - Every chart must know the drawing kind. A drawing tool written in JavaScript (`chart.drawings.register`) is registered once for all charts of the page. ## Charts that do not share a group object A `SyncGroup` connects charts created by the same instance of the WebAssembly module on one page. Charts elsewhere, such as in another window, tab or iframe, or in a native application, cannot join it. For those, the chart reports what it sends, and you forward it with any transport you like (`postMessage`, `BroadcastChannel`, a WebSocket). The chart that sends must be in a group (a group of one is fine): only a chart in a group reports its messages. ### Crosshair and visible range The `sync` event delivers each message this chart sent to its group. On the other side, `chart.applySync(message)` applies it. ```ts import { FerroChart, SyncGroup, type SyncMessage } from '@ferrochart/core'; declare const chart: FerroChart; const channel = new BroadcastChannel('chart-sync'); const group = new SyncGroup(); chart.joinSync(group); // Out: what this chart sent. chart.on('sync', ({ message }: { message: SyncMessage }) => { channel.postMessage(message); }); // In: what a chart in another window sent. channel.onmessage = (e: MessageEvent) => { chart.applySync(e.data); }; ``` A `SyncMessage` is plain data: ```ts type SyncMessage = | { type: 'crosshair'; time: number | null } // null: the crosshair left | { type: 'visibleRange'; from: number; to: number }; // times at the plot edges, UTC ms ``` `applySync` affects only the chart it is called on; it is neither sent again nor passed to that chart's own group. On the receiving side, call it on every chart that should follow. `applySync({ type: 'visibleRange', from, to })` is also a convenient way to show a time range on a single chart. ### Drawings Drawing changes travel as `DrawingSyncOp` values. Each drawing has a `key` that identifies it across charts: ```ts type DrawingSyncOp = | { type: 'add'; key: number; data: DrawingData; visible: boolean; locked: boolean } | { type: 'update'; key: number; data: DrawingData } | { type: 'setVisible'; key: number; visible: boolean } | { type: 'setLocked'; key: number; locked: boolean } | { type: 'remove'; key: number }; ``` | Member | Description | |---|---| | `drawingSync` event | The chart has sent drawing operations. Sent once; the next one comes after you call `takeDrawingSyncOps()` | | `takeDrawingSyncOps()` | The operations sent and not yet taken, oldest first. At most 1024 are kept; older ones are dropped | | `applyDrawingSync(op)` | Applies one operation from another chart (main pane, not undoable, not sent again) | | `drawingSyncState()` | All synced drawings of this chart as `'add'` operations, for a chart that joins later | | `loadDrawingSyncState(ops)` | Makes the synced drawings match such a list: adds, updates, and removes synced drawings that are not in it | Keys are assigned by the group: the group's `origin` times 2³², plus a counter. When several pages forward drawings to each other, give each page's group its own origin with `new SyncGroup(origin)`, so keys from different pages do not collide. The origin is an integer from 0 (the default) to 2²¹ − 1; a larger one throws, which keeps keys exact as JavaScript numbers. ```ts import { FerroChart, SyncGroup, type DrawingSyncOp } from '@ferrochart/core'; declare const chart: FerroChart; declare const pageNumber: number; // different on every page, 0 to 2^21 - 1 type Msg = | { type: 'ops'; ops: DrawingSyncOp[] } | { type: 'hello' } | { type: 'state'; ops: DrawingSyncOp[] }; const channel = new BroadcastChannel('chart-drawings'); const group = new SyncGroup(pageNumber); chart.joinSync(group, { drawings: true }); const send = (m: Msg) => channel.postMessage(m); // Out: forward this chart's changes. chart.on('drawingSync', () => send({ type: 'ops', ops: chart.takeDrawingSyncOps() })); channel.onmessage = (e: MessageEvent) => { const m = e.data; if (m.type === 'ops') { for (const op of m.ops) { try { chart.applyDrawingSync(op); } catch (err) { console.warn('drawing op skipped:', err); } } } else if (m.type === 'hello') { // A page that just opened asks for the current drawings. send({ type: 'state', ops: chart.drawingSyncState() }); } else { chart.loadDrawingSyncState(m.ops); } }; send({ type: 'hello' }); ``` Errors: - `applyDrawingSync` throws for an `update`, `setVisible`, `setLocked` or `remove` of a key the chart does not have, and for a drawing it cannot build (an unregistered kind, wrong anchors or parameters). An `add` of a key the chart already has updates that drawing. - `loadDrawingSyncState` throws, leaving the chart unchanged, if an operation is not an `'add'`, a key appears twice, or a drawing cannot be built. ## Example: a multi-timeframe layout Four charts of one symbol at 1 minute, 5 minutes, 1 hour and 1 day. The three intraday charts share crosshair, zoom and drawings. The daily chart shows the crosshair of the others but keeps its own view, so it stays an overview. ```html
``` ```ts import { FerroChart, SyncGroup, randomWalk, type SyncOptions } from '@ferrochart/core'; const MIN = 60_000; const start = Date.UTC(2024, 0, 1); const layout: { id: string; interval: number; sync: SyncOptions }[] = [ { id: 'm1', interval: MIN, sync: { drawings: true } }, { id: 'm5', interval: 5 * MIN, sync: { drawings: true } }, { id: 'h1', interval: 60 * MIN, sync: { drawings: true } }, { id: 'd1', interval: 1_440 * MIN, sync: { visibleRange: false } }, ]; const group = new SyncGroup(); const charts: FerroChart[] = []; for (const { id, interval, sync } of layout) { const canvas = document.getElementById(id) as HTMLCanvasElement; const chart = await FerroChart.create(canvas, { theme: 'dark' }); const candles = chart.addCandlestickSeries(); // Replace with your data; all four cover the same period. const bars = Math.round((90 * 1_440 * MIN) / interval); candles.setData(randomWalk(7, bars, start, interval)); chart.addVolumeSeries(candles); chart.joinSync(group, sync); charts.push(chart); } // Show the last two days of the 1-minute chart; m5 and h1 follow it. const range = charts[0].dataRange(); if (range) charts[0].setVisibleLogicalRange(range.to - 2 * 1_440, range.to); charts[3].fitContent(); ``` The data in this example is random, so the four charts do not show the same prices; with real data from one symbol they line up. Notes on this layout: - `setVisibleLogicalRange` on `charts[0]` changes its view like a pan by the user would, so the change is sent to the group and `m5` and `h1` follow. (`applySync` would change only `charts[0]`: applied messages are not sent on.) - The daily chart joins with `visibleRange: false`: it neither follows nor moves the others, but still shows their crosshair. - A synced chart redraws when a message arrives or its own content changes; idle charts do not redraw. ## Rust In Rust the same features are `Chart::join_sync(&group, SyncOptions)`, `Chart::leave_sync`, `Chart::apply_sync`, `ChartEvent::Sync`, `Chart::take_drawing_sync_ops`, `Chart::apply_drawing_sync`, `Chart::drawing_sync_state` and `Chart::load_drawing_sync_state`, with `SyncGroup::new()` and `SyncGroup::with_origin(origin)`. --- Source: https://ferrochart.com/docs/orderflow # Order flow `ferrochart-orderflow` adds three series built from trades and order books. They are [custom series](https://ferrochart.com/docs/plugins#custom-series), so they share the chart's time axis, price axis, crosshair and panes with the candles. | Series | Shows | Input | |---|---|---| | **Footprint** | per candle, the volume sold and bought at each price level | trades | | **Heatmap** | order book depth (or traded volume) per time column and price level | order book snapshots or trades | | **TPO** (market profile) | per session, which periods traded at each price; point of control, value area, initial balance | candles | All three work with every renderer. With WebGPU and native GPUs, the heatmap aggregates its cells in a compute shader. On WebGL2 and the CPU renderer it uses its portable path, and the output is the same. ## Common rules - **Price levels.** Prices are rounded to a grid of `step = tickSize × rowSize`: level `round(price / step)`, with halves going up. A level covers `±step / 2` around its center price. - **Time columns** start at UTC multiples of their period (the footprint's timeframe, the heatmap's column length). - **Trades** are columns of equal length: time (UTC ms, non-decreasing), price, size (≥ 0; zero is ignored) and an optional side. A batch is checked first; if it is invalid, the chart does not change. Trades in the last column update it, and later trades open new columns. Trades earlier than the last column are rejected. - **Aggressor side.** Buy and sell are used as given. Unknown sides follow the tick rule: above the previous trade's price → buy, below → sell, equal → the previous trade's side (the first trade counts as a buy). ## Footprint ```js const chart = await FerroChart.create(canvas, { maxBarSpacing: 200 }); const candles = chart.addCandlestickSeries(); const footprint = chart.addFootprint({ tickSize: 0.25, timeframeMs: 60_000, // the candles' period rowSize: 4, // ticks per row mode: 'bidAsk', // 'bidAsk' | 'delta' | 'volume' }); footprint.appendTrades({ time: new Float64Array([...]), price: new Float64Array([...]), size: new Float64Array([...]), side: new Int8Array([...]), // 1 buy, -1 sell, 0 unknown; optional }); ``` What is drawn depends on the bar spacing: | Bar spacing (CSS px) | Drawn | |---|---| | < 12 | nothing (the candles stay visible) | | 12 – 60 | shaded cells | | ≥ 60 | cells and numbers | The default `maxBarSpacing` is 50, so create the chart with a larger one if you want to zoom in to the numbers. - **Modes.** `bidAsk`: sell volume in the left half, buy volume in the right. `delta`: buy − sell, colored by sign. `volume`: the total. Shading intensity is relative to the largest value in the same column. - **Imbalances** compare diagonally: buy at a level ≥ `imbalanceRatio` × sell one level below (a buy imbalance, bar on the right edge). Sell at a level ≥ ratio × buy one level above is a sell imbalance (bar on the left edge). The default ratio is 3; `null` turns imbalances off. - **POC.** With `showPoc` (the default), the level with the most volume in each column is outlined. - Colors default to the theme's up/down/line/text colors; override them with `colors: { buy, sell, volume, text, poc }`. ## Heatmap ```js const book = chart.addHeatmap({ source: 'depth', // or 'trades' (fed with appendTrades) tickSize: 0.25, columnMs: 1_000, // may be finer than the candles }); book.appendDepth({ time: Date.now(), prices: bookPrices, sizes: bookSizes }); ``` - Columns are placed by time between the candle slots, so 1-second columns can lie under 1-minute candles. They add no slots. - **Depth.** Within one snapshot, adjacent prices that fall on the same level are added. Within one column, each level keeps its largest size over the snapshots. - **Trades.** Sizes are added per column and level; the side is not used. - **Colors.** Five color stops from small to large values (`colors`, with alpha), on a `log` (default) or `linear` scale. The range is `{ percentile: 0.99 }` of the visible cells by default, quantized so colors do not flicker while panning, or fixed with `{ lo, hi }`. - The heatmap does not take part in auto scaling by default, because order books span far more than the candles; set `autoScale: true` to include it. - When more levels are visible than 8 per pixel row, nothing is drawn. Zoom in or use a larger `rowSize`. ## TPO ```js const chart = await FerroChart.create(canvas, { maxBarSpacing: 600 }); const tpo = chart.addTpo({ tickSize: 0.25, rowSize: 4, periodMs: 30 * 60_000, // one letter per period (default 30 min) sessionOffsetMs: 14.5 * 3_600_000, // New York cash session: 14:30 UTC… sessionMs: 6.5 * 3_600_000, // …for 6.5 hours }); tpo.appendBars(oneMinuteBars); // time, high and low are used ``` - **Sessions** start once per UTC day at `sessionOffsetMs` and last `sessionMs` (a period to a day; default: the UTC day). Each session is one slot of the time axis. Bars outside every session are skipped. - **Periods** are lettered A–Z, then a–z. A bar belongs to the period its open time falls in. Sending the live bar again widens its period's range. - **Statistics** per session: - **POC**: the level with the most TPOs. Ties go to the level nearest the session's middle, then to the lower level. - **Value area**: `valueArea` of the TPOs (default 70%), grown from the POC two levels at a time toward the side with more TPOs (ties go up). - **Initial balance**: the range of the first two periods. - **Drawing.** Letters when every visible session's widest row fits at a readable font size, histograms otherwise; one choice per frame. The initial balance is a bar on the left, and rows outside the value area are dimmed. ## Rust ```rust use ferrochart_core::chart::SeriesOptions; use ferrochart_orderflow::{Footprint, FootprintOptions, Side, TickColumns, append_trades}; let fp = Footprint::new(FootprintOptions::new(0.25, 60_000, &theme))?; let id = chart.add_custom_series(chart.main_pane(), Box::new(fp), SeriesOptions::default())?; append_trades(&mut chart, id, &TickColumns { time, price, size, side: Vec::new(), // all unknown: tick rule })?; ``` | Series | Options | Data | |---|---|---| | `Footprint` | `FootprintOptions::new(tick_size, timeframe_ms, &theme)` | `append_trades` | | `Heatmap` | `HeatmapOptions::new(tick_size, column_ms, HeatmapSource::Depth \| Trades)` | `append_depth(&DepthSnapshot)` / `append_trades` | | `Tpo` | `TpoOptions::new(tick_size, &theme)` | `append_bars(&OhlcColumns)` | Set `ChartOptions::max_bar_spacing` for footprint numbers and TPO letters. With `ferrochart-render-wgpu`, call `ferrochart_orderflow::register_gpu(&ctx, &mut renderer)` once (in `ChartApp::on_renderer` with `ferrochart-winit`). It returns whether the device supports the native heatmap. The default feature `gpu` provides it; without the feature, the crate does not depend on wgpu. Session statistics are available from `Tpo::profile(i)` (POC, value area, initial balance), and the raw cells from `Footprint::grid()` and `Heatmap::grid()`. ## Performance A one-minute footprint plus a one-second trade heatmap over 1,000,000 trades (Apple M4 Max, 1600×900 CSS px at 2×, native heatmap), per frame: | Scenario | p50 | p99 | |---|---|---| | Pan, footprint numbers | 0.47 ms | 1.6 ms | | Pan, footprint cells | 0.65 ms | 1.6 ms | | Zoom, footprint + heatmap | 0.78 ms | 3.3 ms | | Pan, everything visible | 3.9 ms | 6.8 ms | | Pan, TPO letters | 0.28 ms | 1.1 ms | Real-time trades at prices already in the last column, order book snapshots into the last column and live bars in the last TPO session allocate nothing. New price levels and new columns allocate, like appending candles. Reproduce with `cargo bench -p ferrochart-bench --bench orderflow`. --- Source: https://ferrochart.com/docs/plots # Plots (FerroPlot) `FerroChart` is built around bars in time. For everything else, such as a volatility smile, a returns histogram, a sector bar chart, a P&L waterfall or a correlation heatmap, use `FerroPlot`: a general x/y plot with numeric, logarithmic, category and date axes. It uses the same renderers as charts (WebGPU, then WebGL2), the same canvas handling and the same themes. ```ts import { FerroPlot } from '@ferrochart/core'; declare const canvas: HTMLCanvasElement; const plot = await FerroPlot.create(canvas, { theme: 'dark' }); const smile = plot.addMark('line', { pointSize: 5 }); smile.setData({ x: [80, 90, 100, 110, 120], // strikes y: [0.31, 0.26, 0.24, 0.25, 0.29], // implied volatility }); plot.axis('right').applyOptions({ format: { type: 'percent', decimals: 0 }, title: 'IV' }); plot.axis('x').applyOptions({ title: 'Strike' }); ``` A plot is made of: - **marks**: lines, areas, scatter, bars, waterfalls and cells, each with its own data and options; - three **axes**: `'x'` at the bottom, `'right'`, and `'left'` (hidden by default); - **rules**: horizontal or vertical lines, or shaded bands, at a value; - **labels**: texts or symbols at data coordinates. ## Creating a plot `FerroPlot.create(canvas, options?)` returns a promise, like `FerroChart.create`, and loads the WebAssembly module on first use. The canvas is sized by CSS; see [Themes and styling](https://ferrochart.com/docs/styling#sizing-the-canvas). | Option | Values | Default | |---|---|---| | `theme` | `'light'`, `'dark'` | `'light'` | | `renderer` | `'auto'`, `'webgpu'`, `'webgl2'` | `'auto'` | | `crosshair` | Crosshair lines through the hovered element | `false` | | `hoverHighlight` | Highlight the hovered element | `true` | | `attributionLogo` | The FerroChart logo at the bottom-left of the plot area | `true` | | `touchScroll` | `'chart'`, `'page'`: who gets a vertical swipe; see [Touch screens](https://ferrochart.com/docs/web#touch-screens) | `'chart'` | Other members of `FerroPlot`: | Member | Description | |---|---| | `addMark(kind, options?): Mark` | Adds a mark, drawn above the earlier ones | | `axis(name): Axis` | `'x'`, `'left'` or `'right'` | | `addRule(options): Rule` | A line or band at a value | | `addLabel(options): Label` | A text or symbol at a point | | `fit()` | Every axis back to its configured range; automatic axes follow the data again | | `on(event, callback)`, `off(event, callback)` | Events: `hover`, `click`, `viewChange` | | `playIntro(options?)`, `finishIntro()` | Intro animation, as for charts | | `setAttributionLogo(on)` | Shows or removes the logo | | `renderer` | `'webgpu'` or `'webgl2'` | | `destroy()` | Removes listeners and the logo, releases GPU resources (`dispose()` is the same method, under its earlier name) | The user can pan and zoom a plot: dragging pans, the wheel or a pinch zooms the x axis around the pointer (over a y axis, or with Alt, it zooms that axis), Shift+wheel and horizontal scrolling pan, dragging along an axis zooms it, and a double click fits. Category axes pan but do not zoom. On a touch screen one finger pans and two fingers zoom around their midpoint, each direction by the change of the fingers' distance along it (a direction in which the fingers are closer than 16 CSS px does not zoom). Pressing a finger on an element shows its hover, which stays after lifting unless the finger panned; a finger hits points 8 CSS px further away than the mouse. ## Marks `plot.addMark(kind, options?)` adds a mark of a `MarkKind` with `MarkOptions` and returns a `Mark` handle. | Kind | Draws | Data used | |---|---|---| | `'line'` | Points joined in data order | `x`, `y` | | `'area'` | The area between the line and `y0` (or `baseValue`) | `x`, `y`, `y0?` | | `'scatter'` | A symbol per point | `x`, `y`, `size?`, `value?`, `color?`, `label?` | | `'bars'` | Bars from `y0` (or `baseValue`) to `y` | `x`, `y`, `y0?`, `value?`, `color?`, `label?` | | `'waterfall'` | Running-total bars on a category axis | `x`, `y`, `step?` | | `'cells'` | Colored cells of a grid (heatmaps) | `x`, `y`, `value` | ### Data `mark.setData(data)` replaces the data. All columns have the same length; typed arrays are copied in one `memcpy` per column. | Column | Type | Meaning | |---|---|---| | `x` | `Float64Array \| number[]` | Numbers, UTC ms (date axes) or category numbers. For horizontal bars: the values | | `y` | `Float64Array \| number[]` | Values; `NaN` is a gap. For horizontal bars: the position on the y axis | | `y0` | `Float64Array \| number[]` | Lower edge of areas, start of bars | | `value` | `Float64Array \| number[]` | Values colored by the color scale (cells, bars, scatter) | | `size` | `Float32Array \| number[]` | Scatter diameters, CSS px | | `color` | `(string \| null)[] \| Uint32Array` | Per-point colors (`null`: the mark color), or `0xRRGGBBAA` | | `step` | `('delta' \| 'subtotal' \| 'total')[]` | Waterfall roles; default all `'delta'` | | `label` | `(string \| null)[]` | Per-point texts: scatter labels; replaces the value text of bars and cells | `setData` throws and keeps the old data when columns have different lengths, an `x` is not finite, or a value on a category axis is not a whole number from 0. Three ways to change data: | Method | Use it for | |---|---| | `setData(data)` | Replacing everything | | `append(data)` | Adding points at the end; `data` must have the same columns as the mark's data | | `update(point)` | Replacing the last point, e.g. a live value; O(1), no allocation | ```ts import { FerroPlot } from '@ferrochart/core'; declare const plot: FerroPlot; const pnl = plot.addMark('area', { color: '#26a69a', downColor: '#ef5350' }); plot.axis('x').applyOptions({ format: 'date' }); const t0 = Date.UTC(2024, 0, 2); pnl.setData({ x: [t0, t0 + 60_000, t0 + 120_000], y: [0, 120, 80] }); pnl.append({ x: [t0 + 180_000], y: [150] }); // a new point pnl.update({ x: t0 + 180_000, y: 165 }); // the last point changed ``` `update` takes a `MarkPoint` (`{ x, y, y0?, value?, size?, color? }`); fields for columns the mark does not have are ignored. It throws if the mark has no data or `x` is not finite. The color-scale domain and the automatic cell size keep the values computed by the last `setData` or `append`. ### Options Options are passed to `addMark` and changed with `mark.applyOptions(options)`; keys you leave out keep their value. `mark.options()` returns every option. A `null` color means the default: the next color of the plot's palette for `color` (the first mark gets the theme's line color), or the theme's color for the others. | Option | Applies to | Meaning | Default | |---|---|---|---| | `yAxis` | all | `'left'` or `'right'` | `'right'` | | `orientation` | bars, waterfall | `'vertical'` or `'horizontal'` | `'vertical'` | | `color` | all | Main color | palette | | `downColor` | area, waterfall | Areas below the base value; decreasing waterfall items | theme | | `totalColor` | waterfall | Subtotals and totals | theme | | `fillAlpha` | area | Opacity of the fill, 0 to 1 | `0.25` | | `lineWidth` | line, area | CSS px, > 0 | `2` | | `lineStyle` | line, area | `'solid'`, `'dashed'`, `'dotted'` | `'solid'` | | `stepLine` | line, area | Steps: horizontal to the next x, then vertical | `false` | | `pointSize` | line, scatter | Line: a symbol at each point (0: none). Scatter: the diameter when there is no `size` column | `0` | | `icon` | line, scatter | `'circle'`, `'square'`, `'arrowUp'`, `'arrowDown'` | `'circle'` | | `baseValue` | area, bars | Start of areas and bars without `y0` | `0` | | `group` | bars | Bars of the same group share a slot side by side; `null` for none | `null` | | `stack` | bars, area | Marks of the same stack add up (positive and negative values apart); `null` for none | `null` | | `band` | bars, cells | Fraction of the slot taken, 0 (exclusive) to 1; `null` for the default (0.8 for bars, 1 for cells) | `null` | | `colorScale` | cells, bars, scatter | How `value` maps to colors (below); `null` for the default sequential scale | `null` | | `showValues` | bars, waterfall, cells | Write the value on each element when it fits | `false` | | `valueFormat` | bars, waterfall, cells | Format of those values (see [Formats](https://ferrochart.com/docs/plots#formats)) | `'auto'` | | `cellSize` | cells | `[width, height]` in data units on numeric axes; `null`: the smallest gap between distinct x and between distinct y | `null` | | `hoverable` | all | Hit by hover and click | `true` | | `visible` | all | Drawn | `true` | Invalid values throw, for example `'fillAlpha' must be between 0 and 1` or `'icon' must be 'circle', 'square', 'arrowUp' or 'arrowDown'`. `mark.id` is unique in its plot, `mark.kind` is the kind, and `mark.remove()` removes the mark. ### Bars on a category axis ```ts import { FerroPlot } from '@ferrochart/core'; declare const plot: FerroPlot; const x = plot.axis('x'); x.applyOptions({ type: 'category' }); x.setCategories(['Tech', 'Energy', 'Banks', 'Health']); // Two series side by side in each slot. const q1 = plot.addMark('bars', { group: 1, showValues: true }); const q2 = plot.addMark('bars', { group: 1, showValues: true }); q1.setData({ x: [0, 1, 2, 3], y: [4.2, -1.3, 2.1, 0.8] }); q2.setData({ x: [0, 1, 2, 3], y: [3.1, 0.6, -0.4, 1.9] }); plot.axis('right').applyOptions({ format: { type: 'percent', decimals: 1 } }); plot.addRule({ value: 0, lineStyle: 'solid' }); ``` Category `k` covers the slot from `k` to `k + 1` and is labelled `labels[k]`. With `stack: 1` instead of `group: 1`, the bars would be stacked. For horizontal bars, set `orientation: 'horizontal'`, make the left or right axis the category axis and swap the meaning of the columns: `x` holds the values and `y` the category numbers. ### Waterfall ```ts import { FerroPlot } from '@ferrochart/core'; declare const plot: FerroPlot; const x = plot.axis('x'); x.applyOptions({ type: 'category' }); x.setCategories(['Revenue', 'COGS', 'Gross', 'Opex', 'Tax', 'Net']); const pnl = plot.addMark('waterfall', { color: '#26a69a', // increases downColor: '#ef5350', // decreases totalColor: '#5d6d7e', // subtotals and totals showValues: true, valueFormat: 'compact', }); pnl.setData({ x: [0, 1, 2, 3, 4, 5], y: [1_200_000, -450_000, 0, -380_000, -90_000, 0], step: ['delta', 'delta', 'subtotal', 'delta', 'delta', 'total'], }); ``` A `'delta'` adds its value to the running total. A `'subtotal'` or `'total'` draws a bar from 0 to the running total and leaves it unchanged; its `y` is not used. In hover and click events, `hit.y` of a subtotal or total is the running total. ### Scatter with sizes, colors and labels ```ts import { FerroPlot } from '@ferrochart/core'; declare const plot: FerroPlot; const assets = plot.addMark('scatter', { colorScale: 'diverging' }); assets.setData({ x: [12.1, 18.4, 25.0, 9.8], // volatility, % y: [6.2, 9.1, 14.7, 3.9], // return, % size: [10, 18, 24, 8], // diameter, CSS px value: [0.4, -0.2, 1.1, -0.6], // e.g. Sharpe ratio, colored label: ['Bonds', 'Gold', 'Tech', 'Cash'], }); plot.axis('x').applyOptions({ title: 'Volatility %' }); plot.axis('right').applyOptions({ title: 'Return %', includeZero: true }); ``` ### Cells (heatmaps) ```ts import { FerroPlot } from '@ferrochart/core'; declare const plot: FerroPlot; const names = ['SPX', 'NDX', 'GLD', 'TLT']; const corr = [ [1, 0.92, 0.05, -0.31], [0.92, 1, 0.02, -0.35], [0.05, 0.02, 1, 0.21], [-0.31, -0.35, 0.21, 1], ]; for (const name of ['x', 'right'] as const) { const a = plot.axis(name); a.applyOptions({ type: 'category' }); a.setCategories(names); } const x: number[] = [], y: number[] = [], value: number[] = []; corr.forEach((row, i) => row.forEach((v, j) => { x.push(j); y.push(i); value.push(v); })); const cells = plot.addMark('cells', { colorScale: { center: 0, domain: [-1, 1] }, showValues: true, valueFormat: { type: 'fixed', decimals: 2 }, }); cells.setData({ x, y, value }); ``` On numeric axes, cells are `cellSize` data units wide and high, or as large as the smallest gap between distinct `x` and between distinct `y` values. ## Axes `plot.axis(name)` returns the `'x'`, `'left'` or `'right'` axis. The left axis is hidden by default; a mark uses it with `yAxis: 'left'`. ```ts import { FerroPlot } from '@ferrochart/core'; declare const plot: FerroPlot; plot.axis('left').applyOptions({ visible: true, title: 'Volume', format: 'compact' }); plot.addMark('bars', { yAxis: 'left', color: 'rgba(120, 120, 120, 0.5)' }); plot.addMark('line', { yAxis: 'right' }); ``` ### `AxisOptions` `axis.applyOptions(options)` changes options; keys left out keep their value. `axis.options()` returns every option. | Option | Meaning | Default | |---|---|---| | `type` | `'linear'`, `'log'` or `'category'` | `'linear'` | | `range` | `'auto'`, following the data, or a fixed `[lo, hi]` | `'auto'` | | `includeZero` | Automatic range: keep 0 inside | `false` | | `margin` | Automatic range: fraction added at both ends, 0 to 1 | `0.05` (category: `0`) | | `format` | How tick labels are written (below) | `'auto'` | | `inverted` | Values decrease to the right (x) or upwards (y) | `false` | | `visible` | Ticks, labels and the axis line are drawn | `true` (left: `false`) | | `grid` | Grid lines at the ticks (category axes: at slot boundaries) | `true` (category: `false`) | | `title` | Text beside the axis; `null` removes it | `null` | | `locked` | Panning and zooming leave the axis alone | `false` | Changing `type` starts from that type's defaults for `grid`, `margin` and `range`; `visible`, `title`, `format`, `inverted` and `locked` are kept. The automatic range covers the visible data of the marks on that axis. For bars, areas and waterfalls, an end at zero gets no margin, so bars stand on the axis. A category axis spans all categories. Errors: a fixed range must be two finite, different numbers, and positive on a log axis. ### Log axes ```ts import { FerroPlot } from '@ferrochart/core'; declare const plot: FerroPlot; plot.axis('right').applyOptions({ type: 'log' }); ``` Values of 0 or less have no position on a log axis and are not drawn. ### Category axes A category axis has equal slots; category `k` covers `[k, k + 1)` and its center is `k + 0.5`. Data on it are whole numbers from 0. Name the categories with `axis.setCategories(labels)` (up to 1 000 000). ### Date axes A date axis is a linear axis whose values are UTC milliseconds, with the `'date'` format: ```ts import { FerroPlot } from '@ferrochart/core'; declare const plot: FerroPlot; plot.axis('x').applyOptions({ format: 'date' }); // UTC plot.axis('x').applyOptions({ format: { type: 'date', utcOffsetMinutes: 60 } }); // UTC+1 ``` ### Formats `PlotFormat` is used by `AxisOptions.format` and `MarkOptions.valueFormat`: | Format | Writes | |---|---| | `'auto'` | At least 2 decimals and 4 significant digits, with a subscript count of zeros for small values (like chart price labels) | | `'compact'` | K, M and B suffixes | | `{ type: 'fixed', decimals }` | Fixed decimals, 0 to 12 | | `{ type: 'percent', decimals }` | Fixed decimals and a `%` sign; values are already percent (`5` is written `5%`) | | `'date'` | Values are UTC ms, written as dates and times in UTC | | `{ type: 'date', utcOffsetMinutes }` | The same at an offset from UTC, −1440 to 1440 minutes | ### The visible range | Method | Description | |---|---| | `axis.view(): [number, number]` | The visible range as of the last frame | | `axis.setView(lo, hi)` | Shows `lo..hi` (category units on a category axis); the axis stops following the data until `plot.fit()`. Sends no `viewChange` event | | `plot.fit()` | Every axis back to its configured range | ## Rules A rule is a line across the plot at a value, or a shaded band between two values. ```ts import { FerroPlot } from '@ferrochart/core'; declare const plot: FerroPlot; const target = plot.addRule({ value: 100, label: 'target' }); // horizontal line on the right axis plot.addRule({ axis: 'x', value: Date.UTC(2024, 5, 1), label: 'FOMC' }); // vertical line plot.addRule({ value: 30, to: 70, color: 'rgba(120, 120, 255, 0.12)' }); // band target.applyOptions({ value: 105 }); target.remove(); ``` | Option | Meaning | Default | |---|---|---| | `axis` | The axis of `value`: `'x'` gives a vertical rule | `'right'` | | `value` | Position | `0` | | `to` | Other edge of a band; `null` for a line | `null` | | `color` | Color; `null` for the theme's crosshair color (bands at 12% opacity) | `null` | | `lineWidth` | CSS px | `1` | | `lineStyle` | `'solid'`, `'dashed'`, `'dotted'` | `'dashed'` | | `label` | Text on the axis at the value; `null` for none | `null` | | `labelBackground` | The label sits on a box of the rule color (otherwise it is written in the rule color) | `true` | ## Labels A label is a text, a symbol or both at a point in data coordinates. ```ts import { FerroPlot } from '@ferrochart/core'; declare const plot: FerroPlot; const peak = plot.addLabel({ x: 3, y: 14.7, text: 'peak', icon: 'arrowDown', align: 'center', offset: [0, -14] }); peak.remove(); ``` | Option | Meaning | Default | |---|---|---| | `x`, `y` | The point (required) | | | `yAxis` | `'left'` or `'right'` | `'right'` | | `text` | Text (may be empty with an icon) | `''` | | `icon` | `'circle'`, `'square'`, `'arrowUp'`, `'arrowDown'` or `null` | `null` | | `color` | `null` for the theme's text color | `null` | | `align` | Text alignment relative to the point: `'left'`, `'center'`, `'right'` | `'left'` | | `offset` | Offset of the text from the point, CSS px right and down | `[6, 0]` | Labels cannot be changed; remove one and add another. ## Color scales Cells always color their `value` column by a color scale. Bars and scatter marks do so when they have a `value` column; otherwise they use `color`. A point's own color in the `color` column takes precedence over its value. | `colorScale` | Meaning | |---|---| | `null` or `'sequential'` | Dark blue to yellow, low to high | | `'diverging'` | The theme's down color, a neutral middle and the up color, centered on 0 | | `{ stops?, center?, domain?, quantile? }` | Your own scale | The object form: | Key | Meaning | |---|---| | `stops` | `[position, color][]`, positions 0 to 1 in ascending order (at least one stop) | | `center` | Makes the scale diverging around this value: the middle of the scale is at `center`, and the side farther from it decides the extent of both sides | | `domain` | A fixed `[lo, hi]`; values outside it get the end colors | | `quantile` | Without `domain`: the scale covers the values from the `quantile` to the `1 − quantile` quantile, so outliers saturate. 0 to 0.5, default 0.01 | Without `stops`, a scale with `center` uses the diverging colors and one without uses the sequential colors. ```ts import { FerroPlot } from '@ferrochart/core'; declare const plot: FerroPlot; const heat = plot.addMark('cells', { colorScale: { stops: [[0, '#0d1b4c'], [0.5, '#219ebc'], [1, '#f4e04d']], quantile: 0.05 }, }); ``` The domain is computed from the data by `setData` and `append`; `update` keeps it. ## Hit testing and events The plot finds the element under the pointer: a point of a line or scatter, a bar or a cell. It highlights it (`hoverHighlight`), draws crosshair lines through it (`crosshair`), and reports it. ```ts interface PlotEventMap { hover: { hit: PlotHit | null }; // the hovered element changed click: { hit: PlotHit | null; x: number; y: number }; viewChange: {}; // an axis range changed by pan, zoom or fit() } interface PlotHit { mark: Mark; // compare with mark.id: it is a new handle each time index: number; // index of the point in the mark's data x: number; y: number; // waterfall subtotals and totals: the running total position: { x: number; y: number }; // where it is drawn, CSS px from the canvas' top-left } ``` In `click`, `x` and `y` are the axis values at the pointer (`y` on the right axis, or on the left axis if the right one is hidden). Marks with `hoverable: false` are never hit. ```ts import { FerroPlot, type PlotHit } from '@ferrochart/core'; declare const plot: FerroPlot; declare const tooltip: HTMLElement; const bars = plot.addMark('bars', { showValues: true }); bars.setData({ x: [0, 1, 2], y: [5, 6, 7] }); plot.on('hover', ({ hit }: { hit: PlotHit | null }) => { if (!hit || hit.mark.id !== bars.id) { tooltip.hidden = true; return; } tooltip.hidden = false; tooltip.textContent = `#${hit.index}: ${hit.y}`; tooltip.style.transform = `translate(${hit.position.x}px, ${hit.position.y}px)`; }); plot.on('click', ({ hit, x, y }: { hit: PlotHit | null; x: number; y: number }) => { console.log(hit ? `clicked point ${hit.index}` : `empty space at ${x}, ${y}`); }); ``` Events are delivered after the frame that produced them. ## Lining a plot up with a chart pane `chart.attachSidePlot(plot, pane?)` places a plot beside a chart pane so that a price is at the same height in both. Every frame, the chart sets the plot's right axis to the prices at the top and bottom of the plot area, as the pane maps them. The canvases' positions on the page are read each frame, so the plot may be anywhere beside the chart, and its plot area may be taller or shorter than the pane. - The plot's right axis is locked: the chart is its only source. If the pane's price scale is logarithmic when you attach, the right axis becomes a log axis. - The plot's attribution logo is removed; the chart's stands for both. - `chart.detachSidePlot(plot)` stops following; the right axis stays locked and keeps its last range. ### Example: a volume profile The profile shows how much volume traded at each price in the visible bars, as horizontal bars beside the candles. ```html
``` ```ts import { FerroChart, FerroPlot, randomWalk, type OhlcData } from '@ferrochart/core'; const chart = await FerroChart.create(document.getElementById('chart') as HTMLCanvasElement, { theme: 'dark' }); const candles = chart.addCandlestickSeries(); const bars: OhlcData = randomWalk(3, 3_000, Date.UTC(2024, 0, 1), 60_000); candles.setData(bars); chart.addVolumeSeries(candles); const profile = await FerroPlot.create(document.getElementById('profile') as HTMLCanvasElement, { theme: 'dark', hoverHighlight: false, }); profile.axis('x').applyOptions({ visible: false, grid: false }); profile.axis('right').applyOptions({ visible: false, grid: false }); // the chart shows the prices const rows = profile.addMark('bars', { orientation: 'horizontal', color: 'rgba(41, 98, 255, 0.5)', band: 0.9 }); chart.attachSidePlot(profile); /** Volume per price row of the bars `from..=to` (indices into `bars`). */ function volumeProfile(from: number, to: number, rowSize: number) { const byRow = new Map(); for (let i = from; i <= to; i++) { const row = Math.floor(bars.close[i] / rowSize); byRow.set(row, (byRow.get(row) ?? 0) + (bars.volume?.[i] ?? 0)); } const y: number[] = [], x: number[] = []; for (const [row, volume] of byRow) { y.push((row + 0.5) * rowSize); // price at the middle of the row x.push(volume); } return { x, y }; } const n = bars.close.length; const update = (from: number, to: number) => { const a = Math.max(0, Math.floor(from)); const b = Math.min(n - 1, Math.ceil(to)); if (a <= b) rows.setData(volumeProfile(a, b, 0.5)); }; update(n - 200, n - 1); chart.on('visibleRangeChanged', ({ from, to }: { from: number; to: number }) => update(from, to)); ``` Horizontal bars on a numeric axis are as thick as `band` times the smallest gap between their `y` values, so rows of equal size touch with `band: 1`. When the user scrolls or zooms the chart, `visibleRangeChanged` recomputes the profile for the visible bars, and the price range follows by itself. For order book depth beside the candles, use the same setup with bid and ask sizes as `x` and their prices as `y`, and `rows.update` for live changes of the last level. ## Cleaning up `plot.destroy()` removes the plot's listeners and logo and releases its GPU resources; a side plot also stops following its chart. The `Mark`, `Axis`, `Rule` and `Label` handles then throw (`the FerroPlot was destroyed`). The canvas element stays in the page. --- Source: https://ferrochart.com/docs/plugins # Plugins FerroChart has five ways to extend a chart. All of them write drawing commands into the frame, so they work with every renderer (WebGPU, WebGL2, Vulkan/Metal/DX12 and the CPU renderer) and show up in screenshots and golden images like built-in series. | Extension | Use it for | Rust | JavaScript | |---|---|---|---| | Layer plugin | Extra drawing on a pane or the whole chart: watermarks, trade marks, session shading | `LayerPlugin` | `chart.addLayer` | | Custom series | A series that owns its data and draws it: profiles, heatmaps, range boxes | `CustomSeries` | — | | Native GPU series | A GPU implementation of a custom series kind (compute shaders, large data) | `GpuSeries` | — | | Series transform | A new OHLC-like series computed from bars: Renko-style charts | `SeriesTransform` | — | | Drawing tool | A user-drawn object with anchors, handles and hit testing | `DrawingTool` | `chart.drawings.register` | The runnable Rust example is `examples/plugins` (`cargo run -p example-plugins --release`); it has a watermark, trade marks and a custom series updated by a simulated feed. The order flow crate (`ferrochart-orderflow`, see [Order flow](https://ferrochart.com/docs/orderflow)) is the largest plugin and uses every Rust extension point. ## Rules every plugin follows - **Draw every frame without allocating.** `build` is called for every frame, including while the user pans and zooms. Write into the `FrameBuilder` you are given (its pools keep their capacity) and keep your own scratch buffers in the plugin, cleared and reused. Only draw what is visible: you are given the visible range. - **No panics.** A plugin runs inside the chart's frame; return early instead. - **Coordinates are physical pixels** (`Px`, `PointPx`, `RectPx`) in Rust and CSS pixels in JavaScript. Convert sizes from CSS with `ctx.px(Css(…))` in Rust. - **Colors come from the style or your options.** Use `ctx.style()` (series colors resolved against the theme) or colors you take as options; then the plugin follows light and dark themes. - **Tell the chart about changes.** A layer whose content changes calls `invalidate_layer`; a custom series changes its data only through `update_custom`. ## Layer plugins A layer draws on one pane (its plot area) or on the whole chart, at one of four depths: | `LayerPosition` | Drawn | |---|---| | `Background` | above the grid, behind everything else | | `BelowSeries` | below the series | | `AboveSeries` | above series and markers, below drawings and labels | | `Overlay` | on the overlay layer, below the crosshair | ```rust use ferrochart_core::drawing::{FrameBuilder, Label}; use ferrochart_core::frame::TextAlign; use ferrochart_core::geom::{Css, PointPx, Rgba}; use ferrochart_core::plugin::{LayerCtx, LayerPlugin, LayerPosition}; struct Watermark(&'static str); impl LayerPlugin for Watermark { fn position(&self) -> LayerPosition { LayerPosition::Background } fn build(&self, ctx: &LayerCtx<'_>, out: &mut FrameBuilder<'_>) { let r = ctx.rect(); let center = PointPx { x: r.x + r.w / 2.0, y: r.y + r.h / 2.0 }; let label = Label { font: ctx.font(Css(48.0)), color: Rgba::hex(0x80_8080).with_alpha(0x40), align: TextAlign::Center, bg: None, }; out.text(center, self.0, label); } } // None: the whole chart; Some(pane): that pane's plot. let id = chart.add_layer(None, Box::new(Watermark("BTCUSD")))?; ``` On a pane, `ctx.coords()` gives the pane's time and price conversions (`x_of`, `y_of`, `time_at`, `price_at`, `px`, `plot`, price formatting). Find the visible part of your data with `time_at(plot.x)` and `time_at(plot.right())` and a binary search, as `TradeMarks` in the example does. When the layer's own data changes, call `chart.invalidate_layer(id)` so the next frame redraws it. `chart.remove_layer(id)` removes it. ### In JavaScript ```js const id = chart.addLayer({ pane: 0, // omit for the whole chart position: 'aboveSeries', // 'background' | 'belowSeries' | 'aboveSeries' | 'overlay' build(ctx) { const x = ctx.timeToX(entryTime); const y = ctx.priceToY(entryPrice); if (x === null || y === null) return []; return [ { type: 'line', x1: ctx.rect.x, y1: y, x2: x, y2: y, color: '#2962FF', dash: 'dashed' }, { type: 'text', x: x + 4, y, text: ctx.formatPrice(entryPrice), color: '#2962FF', align: 'left' }, ]; }, }); chart.invalidateLayer(id); // after the plugin's own data changed chart.removeLayer(id); ``` `build(ctx)` returns an array of commands in CSS pixels from the canvas' top-left corner: `rect`, `line`, `polyline`, `polygon`, `text` and `icon` (the `PluginCommand` type lists their fields). An `icon` takes the same extras as a marker: `image` (a name registered with `chart.registerIcon`), `label`, `border` and `borderWidth`, so a layer can draw avatars anywhere, not only at bars (see [Markers](https://ferrochart.com/docs/markers)). The `ctx` functions (`timeToX`, `priceToY`, `xToTime`, `yToPrice`, `textWidth`, `formatPrice`) work only during the call. A plugin that throws or returns an invalid command draws nothing for that frame (the commands before the bad one are kept); its first error is logged with `console.warn`. JavaScript layers are called once per frame across the wasm boundary, so keep the command count to what is visible (hundreds, not hundreds of thousands). For large data, write a custom series in Rust. ## Custom series A custom series owns its data. The chart asks it for its times and price extremes, places it on the time axis, scales the price axis to it and lets it draw the visible points. ```rust use ferrochart_core::chart::SeriesOptions; use ferrochart_core::data::{DataChange, Timestamp}; use ferrochart_core::drawing::FrameBuilder; use ferrochart_core::geom::RectPx; use ferrochart_core::plugin::{AxisMode, CustomSeries, MinMaxIndex, SeriesCtx}; /// A vertical bar from `lo` to `hi` per point. #[derive(Default)] struct Ranges { time: Vec, range: Vec<(f64, f64)>, index: MinMaxIndex, } impl Ranges { fn push(&mut self, t: Timestamp, lo: f64, hi: f64) -> DataChange { self.time.push(t); self.range.push((lo, hi)); let _ = self.index.push(lo, hi); DataChange::Append { count: 1 } } } impl CustomSeries for Ranges { fn kind(&self) -> &'static str { "example.ranges" } fn axis_mode(&self) -> AxisMode { AxisMode::Slots } fn times(&self) -> &[Timestamp] { &self.time } fn extremes(&self, from: usize, to: usize) -> Option<(f64, f64)> { self.index.query(from, to) } fn build(&self, ctx: &SeriesCtx<'_>, from: usize, to: usize, out: &mut FrameBuilder<'_>) { let w = (ctx.bar_spacing().0 * 0.6).max(1.0); for i in from..to { let (lo, hi) = self.range[i]; let (Some(x), Some(y0), Some(y1)) = (ctx.x_of_point(i), ctx.coords().y_of(hi), ctx.coords().y_of(lo)) else { continue; }; out.rect(RectPx { x: x - w / 2.0, y: y0, w, h: (y1 - y0).max(1.0) }, ctx.style().up); } } } let id = chart.add_custom_series(chart.main_pane(), Box::new(Ranges::default()), SeriesOptions::default())?; chart.update_custom(id, |r: &mut Ranges| r.push(60_000, 1.0, 2.0))?; let ranges: Option<&Ranges> = chart.custom_series::(id); ``` ### The contract | Method | Called | Must | |---|---|---| | `kind` | when added | return a unique name, e.g. `"myorg.profile"`; native GPU implementations match on it | | `axis_mode` | when added | return `Slots` or `Overlay` (below) | | `times` | after each change | return strictly increasing times (UTC ms); point `i` is `times()[i]` | | `extremes(from, to)` | every frame | return the price range of points `from..to` in O(log n): use `MinMaxIndex` | | `build(ctx, from, to, out)` | every frame | draw points `from..to` (the visible ones and one more on each side) without allocating | | `last_value` | every frame | the value of the last-value label (`None`: no label) | | `crosshair_value(i)` | when the crosshair moves | the value shown for point `i` | | `native_params` | every frame, native path only | write up to 8 parameters for the GPU implementation | **Axis modes.** `Slots`: each point is a slot of the time axis, like the bars of a built-in series (a footprint column per candle). `Overlay`: points are placed between the existing slots by their times and add no slots (one-second heatmap columns on a one-minute chart). **Changing data.** Change the plugin only through `chart.update_custom(id, |s: &mut MySeries| { …; change })`, returning what changed: | `DataChange` | Meaning | |---|---| | `UpdateLast` | the last point changed, its time did not (does not allocate: the real-time path) | | `Append { count }` | `count` points were added at the end (`count: 0`: nothing changed) | | `Prepend { count }` | `count` points were added at the beginning (history) | | `Replace` | anything else | A change that does not match the data (wrong count, the last time moved) is applied as `Replace`, so a wrong answer costs time but never corrupts the chart. Times that stop being strictly increasing return `TimeNotIncreasing`, and the series shows nothing until a valid change. **Extremes.** `MinMaxIndex` answers range min/max queries in O(log n), and `push` / `set_last` keep it current. Use one per series and update it in the same closure that changes the data. **Drawing.** `ctx.x_of_point(i)` is the center of point `i` (with `SeriesOptions::shift`). `ctx.coords()` converts prices and times, gives fonts and formats prices. `ctx.bar_spacing()` is the distance between slots, and `ctx.style()` holds the series colors. The `FrameBuilder` writes rectangles, lines, polylines, polygons, text and icons; rectangles snapped to whole pixels look sharp at any device pixel ratio. A custom series cannot share a chart with a transform series (both decide how the time axis is built). ## Native GPU series The portable `build` path works everywhere. When a series has too much data for it, e.g. a heatmap with a million cells, a native implementation can draw it on the GPU instead. The frame then holds one `DrawCmd::Custom` for the series instead of its primitives. ```rust use ferrochart_render_wgpu::{GpuSeries, GpuSeriesCtx}; use ferrochart_core::chart::ChartDataView; use ferrochart_core::frame::CustomDraw; struct MySeriesGpu { /* pipelines, per-series buffers */ } impl GpuSeries for MySeriesGpu { fn kind(&self) -> &'static str { "myorg.profile" // the CustomSeries::kind it draws } fn prepare(&mut self, ctx: &GpuSeriesCtx<'_>, draw: &CustomDraw, data: &ChartDataView<'_>) { // Upload what changed since the last frame: // data.changes_since(draw.series, synced_generation) // Read the plugin: data.custom(draw.series), downcast through &dyn Any. // Compute work may be submitted to ctx.queue here. } fn draw(&self, pass: &mut wgpu::RenderPass<'_>, draw: &CustomDraw) { // Set the pipeline and bind groups and draw; the scissor is already // the pane's plot. Do not change the scissor or viewport. } } renderer.register_series(Box::new(MySeriesGpu { /* … */ })); // Before each frame (the winit and web hosts do this for you): chart.set_native_kinds(renderer.native_kinds()); ``` With `ferrochart-winit`, register in `ChartApp::on_renderer`, which is called whenever the GPU renderer is created. Rules for native implementations: - **Same output as the portable path.** Compute layout, thresholds and color ranges in the plugin (core side) and pass them through `native_params` and `data.custom`. The shader only applies them. Test both paths against the same golden image. - **Check the device.** WebGL2 has no compute shaders or storage buffers. Register only when the device supports what you need. Unregistered kinds use the portable path automatically. - **Upload incrementally.** `CustomDraw::generation` and `data.changes_since` tell you what changed. Real-time updates usually touch only the last point. `ferrochart_orderflow::register_gpu` is a complete implementation: a compute shader aggregates heatmap cells per pixel and one quad colors them. ## Series transforms A transform turns the main series' bars into a new OHLC-like series, as the built-in Renko, Range Bars, Kagi and Point & Figure do. It is called once per input bar; `peek` shows what the still-forming last bar would produce. | Method | Must | |---|---| | `name` | return a name, e.g. `"renko"` | | `output_kind` | return `Candlestick`, `OhlcBar`, `Kagi` or `PointFigure` | | `push(bar, out)` | commit `bar` and write the elements it completes into `out` | | `peek(bar, out)` | without changing state, write what `bar` would complete plus the elements still forming | | `reset` | forget all input | | `box_size` | Point & Figure only: the price height of one box | ```rust let id = chart.add_transform_series(pane, Box::new(MyTransform::new()), SeriesOptions::default())?; chart.set_data(id, SeriesData::Ohlc(bars))?; // input bars chart.update_last(id, tick)?; // live input ``` A transform series' x axis is its own output, not time, so it cannot share a chart with other time-based series. ## Drawing tools A drawing tool is an object the user places with the mouse: it has anchors (time, price), handles for editing, hit testing, a style and a saved form for undo/redo and state files. ### In Rust Implement `DrawingTool` (`kind`, `anchors`, `anchors_mut`, `anchor_count`, `build`, `hit_test`, `handles`, `style`, `save`; optionally `move_handle`) and register a factory that rebuilds it from its saved form: ```rust fn my_tool(data: &DrawingData) -> ferrochart_core::Result> { Ok(Box::new(MyTool::from_data(data)?)) } chart.drawings().register("myorg.zone", my_tool); ``` `AnchorCount` decides how it is created: a fixed number of clicks, an open count finished with a double click or Enter, or freehand. Built-in tools are listed in `ferrochart_core::drawing::BUILTIN_KINDS` and are good references. ### In JavaScript ```js chart.drawings.register('myorg.zone', { anchorCount: 2, // or { open: 3 } or 'freehand' build(ctx) { const [a, b] = ctx.anchors; if (a.x === null || b.x === null) return []; return [{ type: 'rect', x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), width: Math.abs(b.x - a.x), height: Math.abs(b.y - a.y), color: ctx.style.fill ?? 'rgba(41, 98, 255, 0.2)', }]; }, // Optional; default: hit inside the drawn bounds. hitTest(ctx, point) { return false; // true: the drawing; a number: that anchor's handle }, }); chart.drawings.startTool('myorg.zone'); ``` A JavaScript kind is available on the chart whose `drawings.register` was called (for `add`, `startTool` and `loadState`); register it on each chart that needs it. Registering a kind again replaces its implementation on every chart of the page. Built-in kinds cannot be replaced. ## Testing a plugin - **Golden images.** Render a fixed scene with `ferrochart-render-cpu` (deterministic, no GPU) and compare it to a stored PNG. With a native implementation, render it with `ferrochart-render-wgpu` too and compare both paths to the same image. - **No allocations.** Warm up a few frames, then count allocations while panning, zooming and moving the crosshair (`build_frame`) and while updating the last point. The count should be zero. `ferrochart-orderflow/tests/zero_alloc.rs` shows the counting allocator. - **Headless frames.** `ferrochart_core::testing::MonoMeasurer` (feature `testing`) lets you call `chart.build_frame` in unit tests without fonts or a GPU. --- Source: https://ferrochart.com/docs/ai-assistants # AI assistants The FerroChart agent skill gives coding assistants platform-specific setup, API guidance and recipes, so they can build charts with FerroChart's actual API. Use it when adding a chart, connecting live data, styling a dashboard or migrating an existing chart. ## Install the skill In Claude Code, add the marketplace and open the plugin's installation panel: ```text /plugin marketplace add 0x0077/ferrochart /plugin install ferrochart@ferrochart ``` Choose **Install** in the panel. The plugin includes the `ferrochart` skill; its instructions and topic references live in `skills/ferrochart/`. See the skill README for installation details. To install manually, clone or download the repository, then run these commands from its root: ```bash mkdir -p ~/.claude/skills cp -R skills/ferrochart ~/.claude/skills/ ``` For other tools that support Agent Skills, copy the complete `skills/ferrochart` directory into the tool's skill directory. Keep `SKILL.md` and `references/` together. Installing the skill adds instructions for the assistant; install the FerroChart library separately in your application as described in the [Web](https://ferrochart.com/docs/web), [Python](https://ferrochart.com/docs/python), [Rust desktop](https://ferrochart.com/docs/desktop) or [C, C++ and C#](https://ferrochart.com/docs/native) guide. ## Give the assistant a concrete task Include the platform, data format and expected behavior. For example: > Use the FerroChart skill to add a React candlestick chart with volume and a > moving average. My feed sends UTC millisecond timestamps and full OHLC bars. > Update the chart as bars arrive, and release its resources on unmount. Have the assistant read only the platform and topic references it needs, check the installed package's types and version, and run the resulting example. FerroChart's native API and its lightweight-charts compatibility entry are different interfaces; use the [migration guide](https://ferrochart.com/docs/migrate) when adapting an existing integration. ## Read the documentation as text - [llms.txt](https://ferrochart.com/llms.txt) is the compact index. Give it to an assistant to locate the relevant guide chapters and API reference. - [llms-full.txt](https://ferrochart.com/llms-full.txt) contains the English guide and example catalog in one text document. Use it when the assistant needs broader context and can accept a larger input. - The [JavaScript API overview](https://ferrochart.com/docs/js-api) and [generated API reference](https://ferrochart.com/docs/api) help verify method names and options. The [cookbook](https://ferrochart.com/docs/cookbook) gives task-oriented examples. The text files are generated from the same sources as the website. Prefer the index and selected chapters for a focused task; check the installed library's version before using an option shown in the current documentation. --- Source: https://ferrochart.com/docs/cookbook # Cookbook Task-oriented recipes for applications using FerroChart. Each browser recipe is an independent TypeScript module for a browser bundler with `@ferrochart/core` installed; the React recipe also needs React. Pass a mounted, nonzero-width `HTMLElement` as `host`, for example `document.body`, and call the returned cleanup when the view is removed. The price-alert recipe instead returns `update` and `destroy` methods. See [Web setup](https://ferrochart.com/docs/web). The examples use synthetic data. Timestamps are UTC milliseconds, with bars in ascending time order. Network recipes describe the input contract for your own feed; no market-data service is bundled. Python recipes specify their packages and write PNG files into the current directory. ## Stream candles over WebSocket Connect a chart to your own WebSocket endpoint that sends one JSON OHLC bar per text message. ```ts import { FerroChart, type Bar } from '@ferrochart/core'; export async function mountLiveChart(host: HTMLElement, feedUrl: string) { const canvas = document.createElement('canvas'); canvas.style.cssText = 'display:block;width:100%;height:360px'; host.append(canvas); const chart = await FerroChart.create(canvas); const candles = chart.addCandlestickSeries(); const socket = new WebSocket(feedUrl); const receive = (event: MessageEvent) => { try { const bar = JSON.parse(event.data) as Bar; candles.update(bar); } catch (error) { console.error('Invalid or out-of-order bar', error); } }; socket.addEventListener('message', receive); socket.addEventListener('error', () => console.error('WebSocket error')); return () => { socket.removeEventListener('message', receive); socket.close(); chart.destroy(); canvas.remove(); }; } ``` - The feed must send `time` in UTC milliseconds and `open`, `high`, `low`, `close` (optionally `volume`); adapt your provider's payload before calling `update`. - The same opening time replaces the last candle; a later time appends one. Earlier times throw. Each update supplies the complete current candle, not a trade delta. - Call the returned cleanup when unmounting; connection recovery belongs to your feed adapter. See [Real-time updates](https://ferrochart.com/docs/data#real-time-updates). ## Load older history when scrolling left Load an earlier page without moving the current view; this standalone example uses an in-memory archive in place of a backend. ```ts import { FerroChart } from '@ferrochart/core'; export async function mountHistory(host: HTMLElement) { const canvas = document.createElement('canvas'); canvas.style.cssText = 'display:block;width:100%;height:360px'; host.append(canvas); const chart = await FerroChart.create(canvas); const archive = Array.from({ length: 120 }, (_, i) => ({ time: Date.UTC(2025, 0, 1) + i * 60_000, open: 100 + i, high: 102 + i, low: 99 + i, close: 101 + i, })); const initial = archive.slice(-40); const candles = chart.addCandlestickSeries(); let oldest = initial[0].time; let loading = false, exhausted = false, disposed = false; const button = document.createElement('button'); button.textContent = 'Load earlier / retry'; host.append(button); async function loadBefore(before: number) { return archive.filter(bar => bar.time < before).slice(-40); } async function loadOlder() { if (loading || exhausted || disposed) return; loading = true; button.disabled = true; try { const older = await loadBefore(oldest); if (disposed) return; if (!older.length) { exhausted = true; return; } candles.prepend(older); oldest = older[0].time; } catch (error) { console.error('History load failed; use the retry button', error); } finally { loading = false; button.disabled = exhausted; } } chart.on('needMoreHistory', loadOlder); button.onclick = () => { void loadOlder(); }; candles.setData(initial); chart.fitContent(); return () => { disposed = true; chart.destroy(); canvas.remove(); button.remove(); }; } ``` - Replace `loadBefore` with your backend request: return ascending, unique timestamps strictly before `before`. Keep volume columns consistent with the initial data. - `needMoreHistory` fires once per first bar. An empty response ends pagination; a failed request can be retried explicitly with the button. - `prepend` preserves existing logical indices and the view; do not call `fitContent` after each page. See [Loading older history](https://ferrochart.com/docs/data#loading-older-history). ## Put an indicator in its own pane Add an overlay moving average and an RSI pane to the same candle series. ```ts import { FerroChart } from '@ferrochart/core'; export async function mountIndicators(host: HTMLElement) { const canvas = document.createElement('canvas'); canvas.style.cssText = 'display:block;width:100%;height:360px'; host.append(canvas); const chart = await FerroChart.create(canvas); const bars = Array.from({ length: 60 }, (_, i) => ({ time: Date.UTC(2025, 0, 1) + i * 60_000, open: 100 + i, high: 102 + i, low: 99 + i, close: 101 + i, })); const candles = chart.addCandlestickSeries(); candles.setData(bars); chart.fitContent(); chart.addIndicator(candles, 'ema', { n: 20 }, 'overlay'); chart.addIndicator(candles, 'rsi', { n: 14 }, 'newPane'); return () => { chart.destroy(); canvas.remove(); }; } ``` - Placement is the fourth argument: `'overlay'`, `'newPane'`, or an existing pane id. Defaults depend on the indicator. - Indicators follow their source data; do not feed them separately. Supply enough history for the chosen period. See [Indicator placement](https://ferrochart.com/docs/indicators#placement). ## Attach buy and sell records to markers Return to your own trade object when a user clicks its marker. ```ts import { FerroChart, type Marker } from '@ferrochart/core'; type Trade = { id: number; time: number; side: 'buy' | 'sell'; quantity: number }; export async function mountTradeMarkers(host: HTMLElement) { const canvas = document.createElement('canvas'); canvas.style.cssText = 'display:block;width:100%;height:360px'; host.append(canvas); const chart = await FerroChart.create(canvas); const bars = Array.from({ length: 60 }, (_, i) => ({ time: Date.UTC(2025, 0, 1) + i * 60_000, open: 100 + i, high: 102 + i, low: 99 + i, close: 101 + i, })); const candles = chart.addCandlestickSeries(); candles.setData(bars); chart.fitContent(); const trades: Trade[] = [ { id: 1, time: bars[10].time, side: 'buy', quantity: 2 }, { id: 2, time: bars[30].time, side: 'sell', quantity: 1 }, ]; const markers: (Marker & { trade: Trade })[] = trades.map(trade => ({ id: trade.id, time: trade.time, trade, position: trade.side === 'buy' ? 'belowBar' : 'aboveBar', shape: trade.side === 'buy' ? 'arrowUp' : 'arrowDown', text: trade.side, })); candles.setMarkers(markers); const info = document.createElement('p'); info.textContent = 'Click a buy or sell marker'; host.append(info); chart.on('click', ({ target }) => { if (target?.type !== 'marker' || target.series.id !== candles.id) return; const marker = markers.find(candidate => candidate === target.marker); if (marker) info.textContent = `Trade ${target.id}: ${marker.trade.side} ${marker.trade.quantity}`; }); return () => { chart.destroy(); canvas.remove(); info.remove(); }; } ``` - `id` is your safe non-negative integer identifier; `target.marker` is the object passed to `setMarkers`, including its custom `trade` field. - The event's index refers to time-sorted markers, not the original array order. A folded badge has type `'markerOverflow'`; handle it separately if needed. - `setMarkers` replaces the marker list. See [Markers](https://ferrochart.com/docs/markers#markers) and [Click events](https://ferrochart.com/docs/crosshair-events#click). ## Draw a price alert line and detect crossings Show a threshold and notify your application when incoming candle closes cross it upward. ```ts import { FerroChart, type Bar } from '@ferrochart/core'; export async function mountPriceAlert(host: HTMLElement, notify: (price: number) => void) { const canvas = document.createElement('canvas'); canvas.style.cssText = 'display:block;width:100%;height:360px'; host.append(canvas); const chart = await FerroChart.create(canvas); const candles = chart.addCandlestickSeries(); const first = { time: Date.UTC(2025, 0, 1), open: 100, high: 102, low: 99, close: 101 }; candles.setData([first]); const threshold = 105; candles.createPriceLine({ price: threshold, title: 'Alert', color: '#ef5350', lineStyle: 'dashed' }); let previous = first.close; return { update(bar: Bar) { candles.update(bar); const crossed = previous < threshold && bar.close >= threshold; previous = bar.close; if (crossed) notify(bar.close); }, destroy() { chart.destroy(); canvas.remove(); }, }; } ``` - Send feed bars through the returned `update` method; the line itself does not monitor prices or deliver alerts. - This detects close-to-close crossings, including updates to the forming candle. It triggers again only after price goes below the threshold and crosses back up; it is not a background service. - Call `destroy` on unmount. See [Price lines](https://ferrochart.com/docs/markers#price-lines) and [Real-time updates](https://ferrochart.com/docs/data#real-time-updates). ## Synchronize two charts Share crosshair time and visible time range across two charts. ```ts import { FerroChart, SyncGroup } from '@ferrochart/core'; export async function mountSyncedCharts(host: HTMLElement) { const canvases = [document.createElement('canvas'), document.createElement('canvas')]; for (const canvas of canvases) { canvas.style.cssText = 'display:block;width:100%;height:260px'; host.append(canvas); } const first = await FerroChart.create(canvases[0]); let second: FerroChart; try { second = await FerroChart.create(canvases[1]); } catch (error) { first.destroy(); canvases.forEach(canvas => canvas.remove()); throw error; } const bars = Array.from({ length: 60 }, (_, i) => ({ time: Date.UTC(2025, 0, 1) + i * 60_000, open: 100 + i, high: 102 + i, low: 99 + i, close: 101 + i, })); first.addCandlestickSeries().setData(bars); second.addSeries('line').setData(bars.map(bar => ({ time: bar.time, value: bar.close }))); first.fitContent(); second.fitContent(); const group = new SyncGroup(); first.joinSync(group, { crosshair: true, visibleRange: true }); second.joinSync(group, { crosshair: true, visibleRange: true }); return () => { first.destroy(); second.destroy(); group.free(); canvases.forEach(canvas => canvas.remove()); }; } ``` - Synchronization uses time, not bar indices; each chart still needs its own data. Bar-spacing limits can constrain the range a chart displays. - Destroying a chart leaves its group. Release the group after its charts; drawing synchronization is separate and off by default. See [Synchronizing charts](https://ferrochart.com/docs/sync#time-not-bar-numbers). ## Save drawings and the viewport Persist the user's view and drawings in localStorage while reconstructing the chart's data yourself. ```ts import { FerroChart, type ChartState } from '@ferrochart/core'; export async function mountSavedChart(host: HTMLElement) { const canvas = document.createElement('canvas'); canvas.style.cssText = 'display:block;width:100%;height:360px'; host.append(canvas); const chart = await FerroChart.create(canvas); const bars = Array.from({ length: 60 }, (_, i) => ({ time: Date.UTC(2025, 0, 1) + i * 60_000, open: 100 + i, high: 102 + i, low: 99 + i, close: 101 + i, })); const candles = chart.addCandlestickSeries(); candles.setData(bars); chart.fitContent(); const key = 'ferrochart-cookbook-view'; const status = document.createElement('p'); const draw = document.createElement('button'); draw.textContent = 'Draw trend line'; draw.onclick = () => chart.drawings.startTool('trend_line'); const save = document.createElement('button'); save.textContent = 'Save view and drawings'; save.onclick = () => { try { localStorage.setItem(key, JSON.stringify(chart.saveState())); status.textContent = 'Saved'; } catch (error) { status.textContent = String(error); } }; host.append(draw, save, status); try { const stored = localStorage.getItem(key); if (stored) chart.loadState(JSON.parse(stored) as ChartState); } catch (error) { status.textContent = `Could not restore: ${String(error)}`; } return () => { chart.destroy(); canvas.remove(); draw.remove(); save.remove(); status.remove(); }; } ``` - Recreate data, series, indicators and the same pane layout before `loadState`; the state does not contain market data or series definitions. - Restoring replaces drawings and clears undo history. Use separate storage keys for incompatible layouts or instruments, and surface storage/restore errors. - Click Save before unmounting. See [State contents](https://ferrochart.com/docs/state#what-a-state-contains) and [Loading a state](https://ferrochart.com/docs/state#loading-a-state). ## Create and destroy a chart in React Keep GPU resources tied to a mounted canvas, including an unmount that happens while initialization is pending. ```tsx 'use client'; import { useEffect, useRef } from 'react'; import { FerroChart, type OhlcRow } from '@ferrochart/core'; const bars: OhlcRow[] = Array.from({ length: 60 }, (_, i) => ({ time: Date.UTC(2025, 0, 1) + i * 60_000, open: 100 + i, high: 102 + i, low: 99 + i, close: 101 + i, })); export function PriceChart() { const canvas = useRef(null); useEffect(() => { const element = canvas.current; if (!element) return; let disposed = false; let chart: FerroChart | undefined; void FerroChart.create(element).then(created => { if (disposed) { created.destroy(); return; } chart = created; created.addCandlestickSeries().setData(bars); created.fitContent(); }).catch(error => console.error('Chart initialization failed', error)); return () => { disposed = true; chart?.destroy(); }; }, []); return ; } ``` - Render `` in a client component. The effect runs in the browser; the disposed check also handles React's development setup/cleanup cycle. - For live data, retain the series in a ref and call `update`; do not recreate the chart on every tick. See [React](https://ferrochart.com/docs/frameworks#react). ## Switch between light and dark themes Rebuild the chart with a different theme while carrying its viewport and drawings across. ```ts import { FerroChart } from '@ferrochart/core'; export async function mountThemeSwitch(host: HTMLElement) { const canvas = document.createElement('canvas'); canvas.style.cssText = 'display:block;width:100%;height:360px'; host.append(canvas); const bars = Array.from({ length: 60 }, (_, i) => ({ time: Date.UTC(2025, 0, 1) + i * 60_000, open: 100 + i, high: 102 + i, low: 99 + i, close: 101 + i, })); let theme: 'light' | 'dark' = 'light'; const create = async () => { const result = await FerroChart.create(canvas, { theme }); result.addCandlestickSeries().setData(bars); return result; }; let chart: FerroChart | undefined = await create(); chart.fitContent(); let disposed = false; const button = document.createElement('button'); button.textContent = 'Switch theme'; host.append(button); button.onclick = async () => { if (!chart) return; button.disabled = true; const state = chart.saveState(); chart.destroy(); chart = undefined; theme = theme === 'light' ? 'dark' : 'light'; try { const next = await create(); if (disposed) { next.destroy(); return; } chart = next; chart.loadState(state); button.disabled = false; } catch (error) { console.error('Theme rebuild failed', error); } }; return () => { disposed = true; chart?.destroy(); canvas.remove(); button.remove(); }; } ``` - Theme is a creation option, not an `applyOptions` update. Recreate the same data, series and panes before restoring state; reattach your event subscriptions as well. - Unset series colors follow the new theme. This example disables switching while rebuilding; a rebuild failure is reported rather than retried automatically. See [Theme](https://ferrochart.com/docs/styling#theme) and [State exclusions](https://ferrochart.com/docs/state#what-it-does-not-contain). ## Build a DOM tooltip for the crosshair Display the hovered candle close in your own HTML overlay. ```ts import { FerroChart } from '@ferrochart/core'; export async function mountTooltip(host: HTMLElement) { const wrapper = document.createElement('div'); wrapper.style.position = 'relative'; const canvas = document.createElement('canvas'); canvas.style.cssText = 'display:block;width:100%;height:360px'; const tip = document.createElement('div'); tip.hidden = true; tip.style.cssText = 'position:absolute;pointer-events:none;background:#111;color:#fff;padding:6px'; wrapper.append(canvas, tip); host.append(wrapper); const chart = await FerroChart.create(canvas); const bars = Array.from({ length: 60 }, (_, i) => ({ time: Date.UTC(2025, 0, 1) + i * 60_000, open: 100 + i, high: 102 + i, low: 99 + i, close: 101 + i, })); const candles = chart.addCandlestickSeries(); candles.setData(bars); chart.fitContent(); chart.on('crosshairMove', ({ point }) => { if (!point?.bar || point.time === null || point.x === undefined || point.y === undefined) { tip.hidden = true; return; } tip.textContent = `${new Date(point.time).toISOString()} · ${point.bar.close.toFixed(2)}`; tip.style.left = `${point.x + 12}px`; tip.style.top = `${point.y + 12}px`; tip.hidden = false; }); return () => { chart.destroy(); wrapper.remove(); }; } ``` - Coordinates are CSS pixels relative to the canvas, so keep the overlay in the same positioned wrapper. Use `textContent` for feed-derived text. - Leaving the plot sends `point: null`; gaps can have no bar. A synchronized crosshair has no pointer coordinates and is hidden here. See [Crosshair events](https://ferrochart.com/docs/crosshair-events#crosshairmove). ## Export a pandas DataFrame to PNG Draw OHLCV data from a pandas DataFrame and save a chart image without opening a window. ```python import pandas as pd import ferrochart as fc df = pd.DataFrame({ "time": pd.to_datetime([ "2026-01-01T00:00:00Z", "2026-01-01T00:01:00Z", "2026-01-01T00:02:00Z" ]), "open": [100.0, 101.0, 100.5], "high": [102.0, 102.5, 103.0], "low": [99.0, 100.0, 100.0], "close": [101.0, 100.5, 102.0], "volume": [1200.0, 950.0, 1400.0], }) chart = fc.Chart(theme="dark", width=800, height=450) candles = chart.add_series("candlestick") candles.set_data(df) chart.add_volume_series(candles) chart.fit_content() chart.to_png("pandas-chart.png") ``` - Install `ferrochart` and `pandas`. Datetime columns are converted to UTC milliseconds; this example supplies explicit UTC timestamps. - Keep rows sorted by time and supply all OHLC columns. `to_png(path)` writes a PNG; `show()` is not needed. See [Python quick start](https://ferrochart.com/docs/python#quick-start). ## Render a PNG on a CPU-only server Create PNG bytes without a window or GPU adapter, ready for a file or your own HTTP response. ```python from pathlib import Path import ferrochart as fc chart = fc.Chart(width=800, height=450) chart.add_series("line", color="#2196f3").set_data({ "time": [1767225600000, 1767225660000, 1767225720000], "value": [100.0, 101.5, 100.8], }) chart.fit_content() png = chart.to_png(backend="cpu") Path("server-chart.png").write_bytes(png) ``` - Install `ferrochart`. `backend="cpu"` belongs to `to_png`, not the `Chart` constructor; this path does not create a GPU adapter. - Without a path, `to_png` returns bytes. Choose dimensions for your output rather than relying on a browser canvas. See [CPU offscreen rendering](https://ferrochart.com/docs/offscreen#on-the-cpu) and [Python](https://ferrochart.com/docs/python#quick-start). --- Source: https://ferrochart.com/docs/migrate # Migrating from lightweight-charts FerroChart has two ways in for code written for lightweight-charts: 1. **The compatibility entry** `@ferrochart/core/lightweight-charts`. It implements the commonly used part of the lightweight-charts v4 and v5 API on top of FerroChart, so an existing chart often runs after changing the import. Use it to try FerroChart on an existing page, or to migrate in steps. 2. **The native API** `@ferrochart/core`. It is what the rest of this guide describes, and gives access to everything: columnar data for large data sets, indicators, drawings, sync, order flow and plots. ## The compatibility entry ```ts // Before: // import { createChart, CandlestickSeries, LineSeries } from 'lightweight-charts'; import { createChart, CandlestickSeries, LineSeries, type UTCTimestamp } from '@ferrochart/core/lightweight-charts'; const container = document.getElementById('chart') as HTMLElement; const chart = createChart(container, { layout: { background: { color: '#131722' } } }); const candles = chart.addSeries(CandlestickSeries, { upColor: '#26a69a', downColor: '#ef5350' }); candles.setData([ { time: 1700000000 as UTCTimestamp, open: 10, high: 12, low: 9, close: 11 }, { time: 1700000060 as UTCTimestamp, open: 11, high: 13, low: 10, close: 12 }, ]); const sma = chart.addSeries(LineSeries, { color: '#2962ff', lineWidth: 2 }); sma.setData([{ time: 1700000060 as UTCTimestamp, value: 11.5 }]); chart.timeScale().fitContent(); ``` ### Supported | Area | Supported | |---|---| | Creating | `createChart(container, options)`, with an element or its id | | Series | `addSeries(definition, options?, paneIndex?)` with `CandlestickSeries`, `BarSeries`, `LineSeries`, `AreaSeries`, `BaselineSeries`, `HistogramSeries`; the v4 methods `addCandlestickSeries`, `addBarSeries`, `addLineSeries`, `addAreaSeries`, `addBaselineSeries`, `addHistogramSeries`; `removeSeries` | | Data | `setData`, `update`, `dataByIndex`; times as `UTCTimestamp` seconds, `'YYYY-MM-DD'` strings or `BusinessDay` objects; per-bar `color` of histogram data | | Series API | `applyOptions`, `options`, `seriesType`, `priceScale`, `createPriceLine`, `removePriceLine` | | Markers | v4 `series.setMarkers` / `series.markers`; v5 `createSeriesMarkers(series, markers)` with `setMarkers`, `markers`, `detach` | | Time scale | `fitContent`, `scrollToRealTime`, `scrollToPosition`, `scrollPosition`, `getVisibleLogicalRange`, `setVisibleLogicalRange`, `getVisibleRange`, `setVisibleRange`, `logicalToCoordinate`, `coordinateToLogical`, `timeToCoordinate`, `coordinateToTime`, the visible logical and time range subscriptions, `applyOptions` / `options` (`barSpacing`, `rightOffset`), `width` | | Price scale | `chart.priceScale('right', paneIndex)` and `series.priceScale()`: `applyOptions` / `options` with `scaleMargins`, `mode`, `invertScale`, `autoScale` | | Crosshair | `subscribeCrosshairMove` / `unsubscribeCrosshairMove`, with `time`, `logical`, `point`, `paneIndex` and `seriesData` | | Chart | `applyOptions` / `options` (`width`, `height`, `layout`, `grid`, `crosshair`, `rightPriceScale.visible`, `handleScroll`, `handleScale`, `timeScale.barSpacing`, `timeScale.rightOffset`, `timeScale.visible`), `resize`, `remove`, `timeScale`, `priceScale` | | Constants | `ColorType`, `CrosshairMode`, `LineStyle`, `LineType`, `PriceScaleMode`, `isUTCTimestamp`, `isBusinessDay` | TypeScript declarations are included (`ISeriesApi`, `IChartApi`, `Time`, `UTCTimestamp`, `SeriesMarker` and so on). ### Asynchronous start The GPU is set up asynchronously, but `createChart` returns at once, as in lightweight-charts. Calls made before the chart is ready are queued and run in order once it is. Two additions help where that matters: | Member | Description | |---|---| | `chart.whenReady(): Promise` | Resolves when the GPU is set up and the queued calls have run | | `chart.ferrochart: FerroChart \| null` | The underlying native chart, `null` until ready | Getters such as `getVisibleLogicalRange()`, `getVisibleRange()`, `coordinateToTime()` or `dataByIndex()` return `null` until the chart is ready (and `priceScale().options()` returns `{}`). Await `whenReady()` before reading them: ```ts import { createChart } from '@ferrochart/core/lightweight-charts'; declare const container: HTMLElement; const chart = createChart(container); // ... add series and data ... await chart.whenReady(); console.log(chart.timeScale().getVisibleLogicalRange()); ``` An error in a queued call is written to the console with `console.error` instead of being thrown, since the call that caused it has already returned. After the chart is ready, errors are thrown as usual. ### Differences **Rendering and size** - The chart draws into a `` that `createChart` appends to the container. Without `width`/`height` options the canvas fills the container (`100%` × `100%`) and follows its size, so give the container a height. `autoSize` is not needed and is ignored. - `width`, `height` and `resize(width, height)` set the canvas's CSS size. - `remove()` destroys the chart and removes its canvas. - WebGPU or WebGL2 is required; see [Themes and styling](https://ferrochart.com/docs/styling#renderer). **Theme and colors** - `layout.background.color` sets the background and picks the base theme: a dark color written as `#rrggbb` (or `#rrggbbaa`) gives the dark theme, anything else the light theme. `layout.textColor` and `layout.fontSize` set the text; a gradient background is drawn in its `topColor`; `fontFamily` is ignored. All of these can change with `applyOptions`. - `grid.vertLines` / `grid.horzLines`: `visible` hides each set of lines; there is one grid color (the horizontal lines' if both are given). - `rightPriceScale.visible` (or `priceScale('right').applyOptions({ visible })`) and `timeScale.visible` hide the axes; the price axis is hidden in every pane. - `handleScroll` and `handleScale`: `false`, or an object whose options are all `false`, switches panning or zooming off; any `true` sub-option leaves it on (FerroChart has one switch each). - `crosshair.mode`: `Normal`, `Magnet` and `Hidden` work; `MagnetOHLC` acts as `Magnet`. `vertLine.visible` and `horzLine.visible` hide each line; the labels are shown unless both lines' `labelVisible` are `false`. - `watermark`, `localization`, `kineticScroll` and other chart options without an equivalent are accepted and ignored. - Colors must be in a form FerroChart accepts: `#rgb`, `#rrggbb`, `#rrggbbaa`, `rgb()`, `rgba()` or `transparent`. Named colors such as `'red'` are an error. See [Colors](https://ferrochart.com/docs/styling#colors). **Series options.** Only these options are used; the others are accepted and ignored: | Series | Options used | |---|---| | Candlestick, Bar | `upColor`, `downColor` | | Line | `color` | | Area | `lineColor`, `topColor`, `bottomColor` | | Baseline | `topLineColor`, `bottomLineColor`, `topFillColor1`, `bottomFillColor1`, `baseValue: { type: 'price', price }` | | Histogram | `color`, `base` | | All | `lineWidth`, `lineStyle`, `lineType`, `lastValueVisible`, `priceLineVisible`, `priceFormat.precision` | So `wickUpColor`, `borderUpColor` and similar candle colors, `crosshairMarker*`, `priceFormat.minMove`, `priceFormat.type`, `title` and `visible` have no effect. `LineStyle.LargeDashed` draws dashed, `LineStyle.SparseDotted` dotted; `LineType.WithSteps` draws steps and `LineType.Curved` straight segments. **Price scales** - Each pane has one price scale, on the right. There are no left or overlay price scales: a series created with a `priceScaleId` other than `'right'` (including the common `''` for a volume overlay) gets a pane of its own, 30% as high as a default pane, and a warning is logged. For volume, the native `addVolumeSeries` (below) draws it in the bottom of the main pane instead. - `chart.priceScale(id)` with an id other than `'right'` logs a warning and returns the right scale. - `series.priceToCoordinate` and `series.coordinateToPrice` use the last frame and return `null` before the first one. As with the crosshair `point`, y is measured from the canvas' top edge, so in a pane below the first it includes the panes above. **Time** - Times are converted to UTC milliseconds. `'YYYY-MM-DD'` strings and `BusinessDay` objects are midnight UTC; other string formats throw. - The first time the chart sees (in `setData` or `update`) decides the format of times it returns: events, `getVisibleRange`, `coordinateToTime`, `dataByIndex` and the crosshair's `time` use seconds, strings or `BusinessDay` objects accordingly. - Logical indices are 0 at the first bar, as in lightweight-charts. **Data** - Whitespace items (`{ time }` only) are dropped from candlestick and bar data, and are gaps in line, area, baseline and histogram data. - OHLC data has no volume in this API. Use the native API for a volume series. **Markers** - `position: 'inBar'` is drawn above the bar, and an unknown `shape` as a circle. `size` is a multiple of the default size (1 is 10 CSS px, kept within 4–64 px); `id` is ignored. **Not supported yet** - `subscribeClick` is a no-op and logs a warning. Use the native `click` event through `chart.ferrochart` instead. - Custom series, series primitives and pane primitives. See [Plugins](https://ferrochart.com/docs/plugins) for FerroChart's own extensions. - `scrollToPosition(position, animated)` ignores `animated`. - `IPriceLine.options()` returns the options you passed, not every option. ### Using native features from the compatibility entry `chart.ferrochart` is the native `FerroChart`, so a page can keep the lightweight-charts calls it has and use native features alongside: ```ts import { createChart, CandlestickSeries } from '@ferrochart/core/lightweight-charts'; declare const container: HTMLElement; const chart = createChart(container); chart.addSeries(CandlestickSeries); await chart.whenReady(); const fc = chart.ferrochart; if (fc) { fc.drawings.startTool('trend_line'); fc.on('click', (e) => console.log('clicked at', e.time, e.price)); } ``` Series added through the native object are not known to the compatibility layer (they are not in `seriesData` of crosshair events, for example). ## Moving to the native API The native API differs from lightweight-charts in a few general ways: - **Creation is async.** `FerroChart.create(canvas, options)` returns a promise, and takes a `` element sized by CSS instead of a container. - **Times are UTC milliseconds**, as `number`, `bigint` or (in rows) `Date`. Multiply lightweight-charts' seconds by 1000. - **Data can be columns.** `setData` accepts arrays of rows, but columns of typed arrays are much faster for large data. - **Kinds are strings.** `chart.addSeries('candlestick', options, pane)`; panes are ids, not indices. - **Options are flat.** Series colors are `color`, `downColor`, `topFill` and `bottomFill`; the theme is `'light'` or `'dark'`. - **Events use `on`/`off`.** `chart.on('crosshairMove', ...)` instead of `subscribeCrosshairMove(...)`. ### Side by side lightweight-charts: ```js import { createChart, CandlestickSeries, HistogramSeries } from 'lightweight-charts'; const chart = createChart(document.getElementById('chart'), { layout: { background: { color: '#131722' }, textColor: '#d1d4dc' }, }); const candles = chart.addSeries(CandlestickSeries, { upColor: '#26a69a', downColor: '#ef5350' }); candles.setData(rows); // [{ time: 1700000000, open, high, low, close }] const volume = chart.addSeries(HistogramSeries, { priceScaleId: '' }); volume.priceScale().applyOptions({ scaleMargins: { top: 0.8, bottom: 0 } }); volume.setData(rows.map((r) => ({ time: r.time, value: r.volume }))); chart.subscribeCrosshairMove((param) => { const bar = param.seriesData.get(candles); if (bar) legend.textContent = `C ${bar.close}`; }); chart.timeScale().fitContent(); ``` FerroChart: ```ts import { FerroChart } from '@ferrochart/core'; declare const rows: { time: number; open: number; high: number; low: number; close: number; volume: number }[]; declare const legend: HTMLElement; const canvas = document.getElementById('chart') as HTMLCanvasElement; // style="width: 100%; height: 480px" const chart = await FerroChart.create(canvas, { theme: 'dark' }); const candles = chart.addCandlestickSeries({ color: '#26a69a', downColor: '#ef5350' }); candles.setData(rows.map((r) => ({ ...r, time: r.time * 1000 }))); // seconds to ms; volume included chart.addVolumeSeries(candles); // reads the volume column, bottom of the main pane chart.on('crosshairMove', ({ point }) => { if (point?.bar) legend.textContent = `C ${point.bar.close}`; }); chart.fitContent(); ``` ### Mapping of common calls | lightweight-charts | FerroChart | |---|---| | `createChart(container, options)` | `await FerroChart.create(canvas, { theme, renderer })` | | `chart.addSeries(CandlestickSeries, o)` / `addCandlestickSeries(o)` | `chart.addCandlestickSeries(o)` or `chart.addSeries('candlestick', o)` | | `BarSeries` / `addBarSeries` | `chart.addSeries('ohlc', o)` | | `LineSeries`, `AreaSeries`, `BaselineSeries`, `HistogramSeries` | `chart.addSeries('line' \| 'area' \| 'baseline' \| 'histogram', o)` | | `chart.addSeries(def, o, paneIndex)` | `chart.addSeries(kind, o, chart.panes()[paneIndex])`; new panes with `chart.addPane()` | | Volume histogram with `priceScaleId: ''` | `chart.addVolumeSeries(candles)` | | `chart.removeSeries(series)` | `series.remove()` | | `series.setData(items)` | `series.setData(rows)` (times in ms) or `series.setData({ time, open, high, low, close, volume })` columns | | `series.update(item)` | `series.update(bar)` (time in ms) | | `series.applyOptions({ upColor, downColor })` | `series.applyOptions({ color, downColor })` | | `series.applyOptions({ lineColor, topColor, bottomColor })` | `series.applyOptions({ color, topFill, bottomFill })` | | `series.applyOptions({ priceFormat: { precision } })` | `series.applyOptions({ pricePrecision })` | | `series.createPriceLine(o)` / `removePriceLine(line)` | `series.createPriceLine(o)` / `line.remove()` | | `series.setMarkers(m)` / `createSeriesMarkers(series, m)` | `series.setMarkers(m)` (time in ms) | | `series.dataByIndex(i)` | `series.dataAt(logicalIndex)` | | `chart.timeScale().fitContent()` | `chart.fitContent()` | | `chart.timeScale().scrollToRealTime()` | `chart.scrollToRealtime()` | | `timeScale().scrollToPosition(n)` / `scrollPosition()` | `chart.setRightOffset(n)` / `chart.rightOffset` | | `timeScale().getVisibleLogicalRange()` | `chart.visibleLogicalRange()` | | `timeScale().setVisibleLogicalRange({ from, to })` | `chart.setVisibleLogicalRange(from, to)` | | `timeScale().setVisibleRange({ from, to })` | `chart.applySync({ type: 'visibleRange', from, to })` (ms) | | `timeScale().applyOptions({ barSpacing, rightOffset })` | `chart.setBarSpacing(px)`, `chart.setRightOffset(bars)` | | `timeScale().logicalToCoordinate(i)` / `coordinateToLogical(x)` | `chart.logicalToCoordinate(i)` / `chart.coordinateToLogical(x)` | | `timeScale().timeToCoordinate(t)` | `chart.logicalToCoordinate(chart.indexOfTime(ms))` | | `timeScale().coordinateToTime(x)` | `chart.timeAtIndex(chart.coordinateToLogical(x))` | | `timeScale().subscribeVisibleLogicalRangeChange(h)` | `chart.on('visibleRangeChanged', h)` | | `chart.priceScale('right').applyOptions({ scaleMargins, mode, invertScale, autoScale })` | `chart.applyPriceScaleOptions({ margins, mode, inverted, autoScale }, pane)` | | `PriceScaleMode.Logarithmic` | `mode: 'logarithmic'` (also `'normal'`, `'percentage'`, `'indexedTo100'`) | | `chart.applyOptions({ crosshair: { mode: CrosshairMode.Magnet } })` | `chart.setCrosshairMode('magnet')` | | `chart.subscribeCrosshairMove(h)` | `chart.on('crosshairMove', h)` | | `chart.subscribeClick(h)` | `chart.on('click', h)` | | `chart.applyOptions({ width, height })` / `resize(w, h)` | Set the canvas's CSS size; the chart follows | | `chart.remove()` | `chart.destroy()` | Logical indices differ in one respect: in FerroChart a bar keeps its logical index when older data is prepended, so the first bar can have a negative index. `chart.dataRange()` returns the indices of the first and last bar. For the details of each native call, see [Series](https://ferrochart.com/docs/series), [Data](https://ferrochart.com/docs/data), [Time scale](https://ferrochart.com/docs/time-scale), [Price scale](https://ferrochart.com/docs/price-scale), [Crosshair and events](https://ferrochart.com/docs/crosshair-events) and [Markers](https://ferrochart.com/docs/markers). --- Source: https://ferrochart.com/docs/rendering # How rendering works ## The loop Every binding runs the same loop: ```rust,ignore if chart.needs_redraw() != Invalidation::None { chart.build_frame(now_ms, &renderer.measurer()); // &mut chart, ends here renderer.render(chart.frame(), &chart.data_view())?; // two shared borrows } ``` `needs_redraw` stays `None` while nothing changes, so an idle chart costs nothing. Building a frame takes about 20 µs, independent of the data size. ## Frames A `Frame` has three layers — background (grid), main (series, axes) and overlay (crosshair) — each a flat list of draw commands with a revision number. Series are not expanded into rectangles: the frame says *draw this series, visible range i..j, with this transform*, and the renderer reads the data columns directly. When only the crosshair moves, only the overlay's revision changes and the GPU renderer reuses a cached texture of the other two layers. ## Data on the GPU The wgpu renderer keeps series data in GPU buffers, in chunks of 4096 bars. It uploads a chunk the first time it is drawn and afterwards only the ranges that changed. Panning and zooming change a few numbers per chunk; nothing is re-uploaded. Prices are stored relative to a reference price per chunk, so 32-bit floats on the GPU keep full precision even for large prices with small ticks. ## Same pixels everywhere The coordinate math lives in `ferrochart_core::transform_helpers` and is mirrored operation by operation in the WGSL shaders, so the CPU and GPU renderers round identically. Golden-image tests compare both against the same reference images. (One subtlety: GPU compilers may fuse `a * b + c` into a single instruction with different rounding, so the transforms are written as `(a + b) * c`, which cannot be fused.) --- Source: https://ferrochart.com/docs/performance # Performance ## Targets | | Scenario | Target | |---|---|---| | P1 | `set_data`, 10 million bars, including the LOD pyramid | < 300 ms | | P2 | Memory per bar (OHLCV, steady state) | < 64 bytes | | P3 | Core CPU time of a pan/zoom frame | < 0.5 ms, independent of data size | | P4 | Pan/zoom frame, end to end | < 8 ms | | P5 | `update_last` | < 20 µs | | P6 | 16 charts × 1M bars, linked crosshair | steady 60 fps | | P7 | WebAssembly package (gzip) | ≤ 1.5 MB | ## Measured Apple M4 Max, release builds: | | Measured | |---|---| | P1 | 73 ms | | P2 | 58 bytes | | P3 | 19 µs (1M and 10M bars alike) | | P4 | p99 2.2 ms (pan), 2.9 ms (zoom), 3.2 ms (pan with all 10M bars visible) — 3200 × 1800 px, Metal | | P5 | 0.3 µs (17.1 µs with all 30 indicators) | | P6 | p50 1.49 ms, p95 2.76 ms per frame | | P7 | 1.4 MB | ## In the browser Same data, same page and same mouse input for FerroChart, lightweight-charts and Vela in Chrome (`examples/compare`). With 1M bars: | | Load → first paint | Pan with 100k bars visible (p95 frame interval / dropped) | |---|---:|---:| | FerroChart | 43 ms | 9.3 ms / 0 % | | lightweight-charts 5.3.0 | 1603 ms | 74.9 ms / 36 % | | Vela 0.10.13 | 77 ms | n/a — cannot zoom out that far | ## Reproducing ```bash cargo bench -p ferrochart-core # P1, P3, P5 cargo bench -p ferrochart-bench --bench memory # P2 cargo bench -p ferrochart-bench --bench frame_time # P4 (needs a GPU) cargo bench -p ferrochart-bench --bench sync # P6 (needs a GPU) cd examples/compare && npm install && node bench.mjs # browser comparison ``` --- Source: https://ferrochart.com/docs/js-api # JavaScript API overview Package `@ferrochart/core`. This page covers loading the module and the conventions every part of the API follows. The full reference, every class, method and type, is generated from the package's TypeScript declarations: [JavaScript API reference](https://ferrochart.com/docs/api). ## Loading ```ts import { FerroChart } from '@ferrochart/core'; const chart = await FerroChart.create(canvas, { theme: 'dark' }); ``` `FerroChart.create` and `FerroPlot.create` load the WebAssembly module the first time they are called; concurrent calls share one load. Call the default export `init` yourself when you need the module without creating a chart first (`randomWalk`, `new SyncGroup()`, `indicatorNames()`), or to load the `.wasm` file from another URL: ```ts import init, { SyncGroup } from '@ferrochart/core'; await init(); // next to the module (default) await init({ module_or_path: '/assets/ferrochart_wasm_bg.wasm' }); const group = new SyncGroup(); ``` `init` can be called any number of times; after the first load it returns at once. ### TypeScript Declarations are included. They use `Symbol.dispose`, so add `"ESNext.Disposable"` to `compilerOptions.lib`, or keep the common `skipLibCheck: true`. ### Bundlers and frameworks The package is an ES module that fetches its `.wasm` file relative to its own URL (`new URL('…_bg.wasm', import.meta.url)`), which Vite, webpack 5, Rollup and esbuild understand. Create charts in the browser only: in React use an effect, in Vue `onMounted`, and skip server rendering for the component (see [React and Vue](https://ferrochart.com/docs/frameworks)). ## Classes | Class | Created by | What it is | |---|---|---| | [`FerroChart`](https://ferrochart.com/docs/api/FerroChart) | `FerroChart.create(canvas, options?)` | A financial chart on a ``: panes, series, scales, crosshair, drawings | | [`Series`](https://ferrochart.com/docs/api/Series) | `chart.addSeries`, `addCandlestickSeries`, `addVolumeSeries`, `addTransformSeries`, order-flow `add*` | One data series | | [`Indicator`](https://ferrochart.com/docs/api/Indicator) | `chart.addIndicator` | An indicator and its output series | | [`PriceLine`](https://ferrochart.com/docs/api/PriceLine) | `series.createPriceLine` | A horizontal line at a price, draggable if you want | | [`Drawings`](https://ferrochart.com/docs/api/Drawings) | `chart.drawings` | The chart's drawings and drawing tools | | [`SyncGroup`](https://ferrochart.com/docs/api/SyncGroup) | `new SyncGroup()` | Links crosshair, visible range and drawings of several charts | | [`FerroPlot`](https://ferrochart.com/docs/api/FerroPlot) | `FerroPlot.create(canvas, options?)` | A general x/y plot (numbers, categories, dates) | | [`Mark`](https://ferrochart.com/docs/api/Mark), [`Axis`](https://ferrochart.com/docs/api/Axis), [`Rule`](https://ferrochart.com/docs/api/Rule), [`Label`](https://ferrochart.com/docs/api/Label) | methods of `FerroPlot` | The parts of a plot | ## Conventions ### Time Times are **UTC milliseconds**. Column data (`time` in `setData`) accepts `number[]`, `Float64Array` or `BigInt64Array`; everywhere else a single time (rows, `update`, markers, drawing anchors, `indexOfTime`) can be a `number`, a `bigint` or a `Date`. Times must be strictly increasing. Events and getters return times as `number` (or `null` beyond the data). The time axis labels are in UTC. ### Logical indices Bars are addressed by a **logical index**: the first bar of the initial data is 0, the next 1, and so on. Bars prepended later get negative indices, so an index never changes once given. Visible ranges, the crosshair and the conversion methods (`coordinateToLogical`, `timeAtIndex`, `indexOfTime`) use them. Fractional values are positions between bar centers. ### Coordinates Positions are **CSS pixels** from the canvas' top-left corner, as in DOM events. The canvas is sized by CSS; the chart sets its backing store to the CSS size × `devicePixelRatio` and follows size changes by itself. `series.priceToCoordinate(price)` and `series.coordinateToPrice(y)` convert between prices and y in the last frame; they return `null` before it, or for a price that has no place on the scale. ### Colors A `Color` is a CSS color string: `#rgb`, `#rrggbb`, `#rrggbbaa`, `rgb()`, `rgba()` or `'transparent'`. In options, `null` means the theme's default. ### Options objects Options are plain objects. `applyOptions` and similar methods change only the keys you pass; absent keys keep their value. Getters such as `series.options()` return every key (`Required<…>`). ### Errors Methods throw an `Error` with a message that names the problem (an unknown indicator name, an invalid parameter, columns of different lengths, a bar whose time is not increasing, an unknown id). The chart is left unchanged. `FerroChart.create` rejects when the requested GPU API is not available: there is no Canvas 2D fallback; `renderer: 'auto'` tries WebGPU, then WebGL2. ### Events `chart.on(name, callback)` subscribes, `chart.off(name, callback)` unsubscribes. The callback's parameter is typed from the event name. Events are delivered after the frame that produced them, not inside the input handler. An exception thrown by a callback is reported to the console (through `reportError`) and the other callbacks still run. See [Crosshair and events](https://ferrochart.com/docs/crosshair-events). ### Lifetime and memory A chart listens to its canvas and the window and redraws on its own. Keep a reference to it while it is on the page, and call `chart.destroy()` when you remove it: that removes the listeners and releases GPU memory. A chart that is dropped without `destroy` may be garbage-collected and stop responding. Every object of the API holds WebAssembly memory. Objects the chart returns (`Series`, `Indicator`, `PriceLine`) are freed with the chart; `free()`, or a `using` declaration, releases one earlier. Removing a series (`remove()`) is a different thing: it takes it off the chart. ### Input handled on the canvas Pointer (mouse, pen, touch), wheel, keyboard (the canvas gets `tabindex="0"`), double-click and trackpad pinch (Ctrl+wheel in Chrome and Firefox, gesture events in Safari), and two-finger touch, which the chart recognizes itself. The canvas style gets `touch-action: none`, or `pan-y` with `touchScroll: 'page'` (see [Touch screens](https://ferrochart.com/docs/web#touch-screens)). See [Gestures and keyboard](https://ferrochart.com/docs/interaction) for what each gesture does. ## Test data `randomWalk(seed, n, startMs, intervalMs)` returns deterministic OHLC columns, identical to the Rust generator `ferrochart_core::testing::random_walk`. The examples and demos use it. ```ts import init, { randomWalk } from '@ferrochart/core'; await init(); const bars = randomWalk(42, 10_000, Date.UTC(2024, 0, 1), 60_000); ``` --- Source: https://ferrochart.com/docs/rust-api # Rust API The API documentation is generated by rustdoc. Locally: ```bash cargo doc --workspace --exclude ferrochart-py --no-deps --open ``` Published on docs.rs: | Crate | Contents | |---|---| | `ferrochart-core` | `Chart`, data model, scales, input, `Frame`, `Renderer` trait, `transform_helpers` | | `ferrochart-render-wgpu` | `GpuContext`, `WgpuRenderer` (surface or offscreen) | | `ferrochart-render-cpu` | `CpuRenderer` (tiny-skia) | | `ferrochart-text` | `TextEngine`, the bundled font | | `ferrochart-winit` | `run`, `ChartApp`, `InputConverter` | | `ferrochart-indicators` | Incremental indicators | | `ferrochart-orderflow` | Footprint, heatmap and TPO series ([Order flow](https://ferrochart.com/docs/orderflow)) | Extending the chart (layers, custom series, native GPU series, transforms, drawing tools) is described in [Plugins](https://ferrochart.com/docs/plugins). ## Where to start - `ferrochart_core::Chart`: create it with `ChartOptions`, `resize`, add series, set data, feed `InputEvent`s with `handle_input`, `build_frame`, read events with `drain_events`. - `ferrochart_core::render::Renderer`: implemented by both renderers; you call `render(chart.frame(), &chart.data_view())`. ## Rules the API follows - **No panics.** Methods that can fail return `Result`; lookups by id return `Result` or `Option`. - **No allocations on the hot path.** Panning, zooming, moving the crosshair (`build_frame`) and `update_last` allocate nothing once warmed up; tests assert this with a counting allocator. - **Typed coordinates.** `Css` and `Px` (and the point, size and rect types built on them) keep CSS and device pixels apart; the device pixel ratio is passed to `Chart::resize`. `Chart::price_to_coordinate` and `coordinate_to_price` convert between a series' prices and `Css`. - **Core is pure.** `ferrochart-core` has no dependencies outside the standard library (`smallvec` is the only one allowed): no GPU, window, font, time or async libraries, and no `unsafe`. --- Source: https://ferrochart.com/docs/building # Building from source Requires Rust 1.93 or newer. For the web package: the `wasm32-unknown-unknown` target and wasm-pack. For the browser tests and the comparison page: Node.js 20+. ```bash git clone https://github.com/0x0077/ferrochart.git cd ferrochart scripts/check.sh # everything below, as run before each commit cargo test --workspace --exclude ferrochart-py cargo run -p example-desktop --release # Web package and demo rustup target add wasm32-unknown-unknown (cd crates/ferrochart-wasm && wasm-pack build --release --target web) python3 -m http.server 8000 # open http://localhost:8000/examples/web/ # Browser smoke test (Chrome, Firefox, WebKit) and TypeScript type check cd tests/web && npm install && npx playwright install firefox webkit node smoke.mjs && npx tsc -p . # This book mdbook serve docs/book ``` ## Python wheel and C library ```bash # Python: a virtualenv with maturin and twine in .venv, plus wasm-pack (for # the Jupyter front end); the wheel lands in target/wheels python3 -m venv .venv && .venv/bin/pip install maturin twine scripts/build-py-wheel.sh .venv/bin/pip install target/wheels/ferrochart-*.whl # C library and header (crates/ferrochart-ffi/include/ferrochart.h) cargo build -p ferrochart-ffi --release ``` ## Golden images Rendering changes are checked against reference PNGs in `crates/ferrochart-render-cpu/tests/golden/`; both the CPU and the GPU renderer must match them. If a change is meant to alter the output, regenerate them with `FERROCHART_UPDATE_GOLDEN=1 cargo test golden` and commit the new images on their own, explaining why. ## Project rules The working rules are in CONTRIBUTING.md. --- # Example catalog --- ## Price action - [Candlesticks + volume](https://ferrochart.com/charts/price/candles): The classic view. - [Real-time stream](https://ferrochart.com/charts/price/live): update replaces the last bar or appends a new one. - [Bar replay](https://ferrochart.com/charts/price/replay): History played back bar by bar with update, the way a live feed would arrive, with an EMA keeping pace incrementally. - [OHLC bars](https://ferrochart.com/charts/price/ohlc): Open and close ticks on a high–low bar: the denser alternative to candles, common for futures and FX. - [Heikin-Ashi](https://ferrochart.com/charts/price/heikin): Averaged candles that make trends easier to read. - [Hollow candles](https://ferrochart.com/charts/price/hollow): Rising bars (close above open) are hollow, falling ones filled; the color compares the close with the previous close. - [Volume-width candles](https://ferrochart.com/charts/price/volcandles): Each body's width is its volume against the busiest bar on screen, so heavy bars stand out from thin ones. - [HLC bars](https://ferrochart.com/charts/price/hlc): High–low bars with only a close tick, colored by the change from the previous close. - [Rounded candles](https://ferrochart.com/charts/price/roundcandles): Candles with rounded bodies and round-capped wicks, for dashboards and consumer apps. - [High–low range bars](https://ferrochart.com/charts/price/highlow): Each day as one bar from its low to its high, with both prices printed when zoomed in. - [Line](https://ferrochart.com/charts/price/line): Closing prices as a single line: the cleanest view of a trend. - [Line with points](https://ferrochart.com/charts/price/linemarkers): A line series with a points series on the same data, so each daily close is a visible dot. - [Step line](https://ferrochart.com/charts/price/step): A yield (in percent) held flat until the next print and then stepping to it, as rates and fixings are usually drawn. - [HLC area](https://ferrochart.com/charts/price/hlcarea): The close as a line, with the room up to the high filled green and down to the low filled red: the range of every bar without candle bodies. - [Columns](https://ferrochart.com/charts/price/columns): Closing prices as columns rising from the lowest low, each colored by whether it closed up or down. - [Returns histogram](https://ferrochart.com/charts/price/histogram): The close above and each bar's percent return below as a histogram around zero, colored by sign. - [Area](https://ferrochart.com/charts/price/area): Twenty thousand points, all on screen. - [Baseline](https://ferrochart.com/charts/price/baseline): Above and below a reference price in two colors: performance since the open, P&L against an entry. - [Compare (% change)](https://ferrochart.com/charts/price/compare): Three markets on one percentage scale, rebased to the first visible bar as you pan. - [Two markets as candles](https://ferrochart.com/charts/price/overlaycandles): Two markets' candles on one time axis, in their own colors. - [Higher-timeframe candles](https://ferrochart.com/charts/price/htfcandles): Fifteen-minute candles with the four-hour candle each belongs to drawn behind them: body as a tinted box, wicks dotted. - [Trading sessions](https://ferrochart.com/charts/price/extsession): Fifteen-minute bars of a currency pair with the Asia, London and New York sessions shaded and labelled. - [Drawing tools](https://ferrochart.com/charts/price/drawings): 29 built-in tools: lines, channels, Fibonacci, pitchforks, Gann, patterns and positions. - [Quote card](https://ferrochart.com/charts/price/quote-card): A phone-style quote: price and change over the chart, the range's line coloured above and below the price it started from (dashed), and 1D to All tabs. - [Watchlist](https://ferrochart.com/charts/price/watchlist): Thirty pairs with a 24-hour sparkline each and prices that refresh every 2 seconds. - [Period switch](https://ferrochart.com/charts/price/period-switch): One market in six periods: on a click, beginTransition makes the candles merge into the longer period or split into the shorter one by time instead of… - [Chart type switch](https://ferrochart.com/charts/price/type-switch): Candles, a line of the closes and Heikin-Ashi on the same bars. - [Symbol switch](https://ferrochart.com/charts/price/symbol-switch): Three markets on one chart: beginTransition({ kind: 'fade' }) before setData cross-fades the old candles and price scale into the new ones, since another… --- ## Bar types & transforms - [Renko](https://ferrochart.com/charts/transforms/renko): Bricks of a fixed (or ATR-based) size, built from your bars as they arrive. - [Range bars](https://ferrochart.com/charts/transforms/range): Every bar spans the same price range, so quiet periods shrink and busy ones expand. - [Kagi](https://ferrochart.com/charts/transforms/kagi): A line that changes direction on reversals and thickness when it breaks the previous shoulder or waist. - [Point & figure](https://ferrochart.com/charts/transforms/pnf): Columns of X and O boxes with a three-box reversal: supply and demand without the noise of time. - [Three-line break](https://ferrochart.com/charts/transforms/linebreak): A new block only when the close beats the previous block; a reversal has to break the extreme of the last three. - [Tick bars](https://ferrochart.com/charts/transforms/tickbars): Every bar holds the same number of trades, so the volume pane below shows how much each batch of 150 trades moved: large prints stand out. - [Volume bars](https://ferrochart.com/charts/transforms/volbars): A bar closes every 40 BTC of volume, so each carries the same weight. - [Dollar bars](https://ferrochart.com/charts/transforms/dollarbars): Bars of equal notional (price × size), which stay comparable when the price level moves a lot. - [Delta candles](https://ferrochart.com/charts/transforms/deltacandles): One-minute candles above; below, cumulative volume delta (buy minus sell volume, in BTC) drawn as a candle per minute: open where the last minute ended,… - [Ratio with bands](https://ferrochart.com/charts/transforms/spread): ETH priced in BTC: the ratio of two markets' closes, with its 100-bar mean and a two-standard-deviation band. - [Continuous futures](https://ferrochart.com/charts/transforms/rollover): A continuous futures contract as back-adjusted candles, with the unadjusted front-month close in amber. --- ## Technical analysis - [Bollinger · MACD · RSI](https://ferrochart.com/charts/indicators/macd-rsi): Each indicator keeps its own state and updates with the last bar in O(1). - [Oscillators](https://ferrochart.com/charts/indicators/oscillators): Stochastic, ADX and CCI in their own panes, sharing the time axis and the crosshair. - [Ichimoku cloud](https://ferrochart.com/charts/indicators/ichimoku): Five lines and the cloud between them, displaced forward in time. - [Supertrend · SAR](https://ferrochart.com/charts/indicators/trend): Trend-following stops on the price pane. - [Supertrend signals](https://ferrochart.com/charts/indicators/supertrend): The SuperTrend stop in green under longs and red over shorts, with a marker wherever it flips. - [Parabolic SAR + Keltner](https://ferrochart.com/charts/indicators/psar): A Keltner channel (EMA 20 ± 2 ATR) as the volatility envelope and Parabolic SAR dots as the trailing stop. - [Donchian breakouts](https://ferrochart.com/charts/indicators/donchian): The 20-bar Donchian channel (highest high, lowest low and their midpoint), with arrows where the close first breaks out of the previous channel: the classic… - [Zigzag & swing labels](https://ferrochart.com/charts/indicators/patterns): A 2.5% zigzag drawn as a line series through the swing pivots, each pivot labelled HH, LH, HL or LL against the previous one of its kind: the market… - [Daily pivot points](https://ferrochart.com/charts/indicators/pivots): Classic floor pivots (P, R1–R2, S1–S2) from each previous session, drawn as line series that start fresh every day. - [Gaps and gap fills](https://ferrochart.com/charts/indicators/gaps): Every opening gap of 4% or more as a box from the previous close to the open, running until a later bar trades back through it; open gaps run to the edge. - [Regime shading](https://ferrochart.com/charts/indicators/shaded): The background turns green while price closes above its 50-bar average and red while below, making trend regimes visible at a glance. - [Corporate events](https://ferrochart.com/charts/indicators/events): Earnings (with the EPS surprise, green for a beat), dividends and a stock split as markers on daily candles. - [Event timeline](https://ferrochart.com/charts/indicators/eventline): A year of daily closes with the events that moved them: rate decisions, inflation and jobs data, upgrades, outages and regulation. - [Annotated lesson](https://ferrochart.com/charts/indicators/teaching): A teaching chart: the last big swing traced with a trend line, Fibonacci levels on it, numbered markers and a callout, over candles and an EMA. - [Historical analog](https://ferrochart.com/charts/indicators/analog): Searches the history for the 60-bar window most correlated with the latest 60 and lays it, scaled, over the last bars as an amber line that runs on into the… - [Forecast band](https://ferrochart.com/charts/indicators/forecast): A median path extended 72 hours past the last candle, with the 25–75% range as a filled band and the 5% and 95% paths dotted. - [Fan chart](https://ferrochart.com/charts/indicators/fan): A fan of nested quantile bands, 5–95% outermost and 35–65% innermost, widening with the horizon. --- ## Order flow - [Footprint](https://ferrochart.com/charts/orderflow/footprint): Sell and buy volume at every price inside each candle (in $5 rows), with diagonal imbalances and the point of control. - [Delta footprint](https://ferrochart.com/charts/orderflow/delta): Net aggression per price level: buyers minus sellers, colored by sign. - [Depth heatmap](https://ferrochart.com/charts/orderflow/heatmap): Resting liquidity over time under one-minute candles; walls sit at fixed prices for a while. - [Market profile (TPO)](https://ferrochart.com/charts/orderflow/tpo): One profile per session: letters per 30-minute period, point of control, value area and initial balance. - [Volume heat candles](https://ferrochart.com/charts/orderflow/volheat): Each one-minute bar is split into $10 cells shaded by the volume traded there, with the busiest cell outlined; thin OHLC bars on top keep the direction. - [Session volume profile](https://ferrochart.com/charts/orderflow/svp): A horizontal volume profile behind every session of five-minute futures candles: the point of control in amber, the 70% value area brighter. - [Visible-range volume profile](https://ferrochart.com/charts/orderflow/profile): The volume profile of whatever is on screen, at the right edge, with the point of control and the value area high and low across the chart. - [Anchored & fixed-range profile](https://ferrochart.com/charts/orderflow/anchoredfixedran): Two volume profiles drawn inside their own time ranges: one over a fixed stretch of bars and one anchored at a swing high and running to the latest bar. - [Order-book imbalance](https://ferrochart.com/charts/orderflow/obi): Where the book leans: at each distance from the touch, the excess of bids over asks is painted green below the price and the excess of asks red above it, as… - [Liquidity heatmap with trades](https://ferrochart.com/charts/orderflow/bookmap): Eight minutes of a one-second order-book heatmap with the last price, buy and sell volume as bubbles every five seconds, and the current walls labelled at… - [Block trade bubbles](https://ferrochart.com/charts/orderflow/tape-bubbles): Every trade of $100k or more as a bubble on one-minute candles, sized by notional and colored by the aggressor side, with the five largest labelled. - [Icebergs & large fills](https://ferrochart.com/charts/orderflow/iceberg): Prices where aggressive trades took more than twice the size the order book displayed there, a sign of a hidden or refilled order. - [Pulled-order patterns](https://ferrochart.com/charts/orderflow/spoof): Large resting orders that appeared away from the price, sat for 10 to 40 seconds and vanished before trading, boxed on a one-second depth heatmap under the… - [Trade size distribution](https://ferrochart.com/charts/orderflow/tradesize): BTC volume per minute split into four notional tiers, from small orders at the bottom to block trades on top, under one-minute candles. - [Adds, cancels, fills & OFI](https://ferrochart.com/charts/orderflow/orderevents): Book activity per minute in BTC: size added by new orders above zero, cancelled and filled size stacked below it, and order flow imbalance (positive when… - [Bid/ask band & spread](https://ferrochart.com/charts/orderflow/bidask): The best ask (red) and bid (green) as step lines with the spread filled between them by addBand, and the spread itself in basis points below. - [Liquidity terrain candles](https://ferrochart.com/charts/orderflow/terrain): Candles over a terrain of the liquidity that rested near the price while each one formed: amber columns where the book was thinnest, blue where it was… - [Liquidity withdrawal shocks](https://ferrochart.com/charts/orderflow/pullshock): Moments when liquidity near the touch was pulled. - [Depth recovery](https://ferrochart.com/charts/orderflow/depthrecovery): Resting size near the touch in ten-second averages, against its median. - [Depth chart beside the candles](https://ferrochart.com/charts/orderflow/depth): The order book as a depth chart beside one-minute candles: cumulative bid size (green) below the mid and ask size (red) above, as horizontal bars in a… --- ## Execution & trade review - [Chart trading](https://ferrochart.com/charts/execution/chart-trading): Trade from the chart, as a paper simulation. - [Order from the price axis](https://ferrochart.com/charts/execution/order-button): Orders from the price axis, as a paper simulation on replayed bars. - [Trailing stop and liquidation](https://ferrochart.com/charts/execution/trailing-stop): A long position at 10x on replayed bars, as a paper simulation. - [Line triggers and alerts](https://ferrochart.com/charts/execution/line-trigger): Drawn lines that act, as a paper simulation on replayed bars. - [Parent order progress](https://ferrochart.com/charts/execution/parentprogress): A five-hour buy order of 750 BTC, three hours in: cumulative fills against a VWAP schedule built from yesterday's volume curve and a straight TWAP line,… - [Participation rate](https://ferrochart.com/charts/execution/participation): A volume-participation algorithm aiming at 10% of the market: its share of volume over a rolling 20 minutes, against a 7 to 13% tolerance band filled with… - [Queue position](https://ferrochart.com/charts/execution/queuepos): Where a resting bid stands in the queue at its price: the BTC ahead of it, worked out from one-second order-book snapshots and the trades at that price,… - [Slippage quantile band](https://ferrochart.com/charts/execution/slippageband): Every fill's slippage against the arrival mid in basis points, as red (cost) and green (improvement) points, with the rolling median and a 10th to 90th… - [Reference, quote & fill](https://ferrochart.com/charts/execution/fillvs): A taker algorithm's buy fills on five-second data: the mid as the reference price, the best ask it was quoted as a step line, and each fill as a point,… - [Price for your size](https://ferrochart.com/charts/execution/sizeband): What you would pay or receive for a market order of 25 or 250 BTC, worked out by sweeping each order-book snapshot from the touch: two nested bands around… - [Trades on the chart](https://ferrochart.com/charts/execution/tradeplot): The trades of a simple moving-average cross on 15-minute candles: buy and sell markers with each trade's result, and a layer plugin that shades every… - [Signal-to-fill latency](https://ferrochart.com/charts/execution/signallatency): Buy signals (violet arrows) and their fills (circles labelled with the slippage in bps) on one-second prices. - [Fee erosion](https://ferrochart.com/charts/execution/feeerosion): One year of a strategy indexed to 100, before and after trading fees of 6 bps per unit of turnover: addBand fills the widening gap in amber, and the pane… - [Cross-exchange spread](https://ferrochart.com/charts/execution/xexspread): One market quoted on three venues: the prices overlaid, and below them Exchange B and C against Exchange A in basis points, where a steady premium and a… --- ## Crypto derivatives - [Funding · open interest · liquidations](https://ferrochart.com/charts/perps/derivs): Three derived series under one-hour candles: funding per 8 h in percent, colored by sign, open interest, and liquidated longs (down) and shorts (up). - [Long/short ratio · CVD](https://ferrochart.com/charts/perps/positioning): Account positioning against the move: the long/short ratio around 1 as a baseline series, and cumulative volume delta. - [Implied volatility · basis](https://ferrochart.com/charts/perps/volatility): At-the-money implied volatility and the annualised futures basis, both in percent, under four-hour candles. - [Long/short ratio · liquidations](https://ferrochart.com/charts/perps/lsr): The ratio of long to short accounts as a baseline series around 1, and liquidated longs (down) and shorts (up) in $M as two histograms on one pane. - [Open interest × price quadrants](https://ferrochart.com/charts/perps/oiquad): The hourly change in open interest, colored by which of the four price/OI quadrants the bar falls in, with open interest itself below. - [Liquidation bubbles](https://ferrochart.com/charts/perps/liqtimeline): A layer plugin draws a bubble for every hour with over $10M liquidated, sized by the amount: longs under the candle (red) and shorts above it (green). - [Liquidation heatmap](https://ferrochart.com/charts/perps/liqheat): Estimated liquidation levels per hour as an addHeatmap fed with appendDepth: each hour's new open interest is spread over 10–100× leverage, and a level… - [Premium index](https://ferrochart.com/charts/perps/premium): The perpetual's premium over the index price in percent, as a baseline series: green when the perp trades rich (longs pay), red when it trades at a discount. - [Cumulative funding by venue](https://ferrochart.com/charts/perps/fundcum): What holding a long perpetual for a year cost on three venues: the per-8-hour funding rate summed into a running total in percent. - [Top traders vs all accounts](https://ferrochart.com/charts/perps/toptrader): The long/short ratio of the largest traders against that of all accounts. - [Futures weekend gaps](https://ferrochart.com/charts/perps/cmegap): A layer plugin shades each weekend and draws the gap between a futures market's Friday close and its Sunday reopen, both taken from round-the-clock spot… - [Volume share by venue](https://ferrochart.com/charts/perps/exshare): Each venue's share of perpetual volume, stacked to 100% with area series drawn from the top total down on a fixed 0–100 scale. - [Insurance fund · auto-deleveraging](https://ferrochart.com/charts/perps/insfund): The insurance fund balance in $B under four-hour candles. - [OI-weighted funding](https://ferrochart.com/charts/perps/oiweighted): One funding rate for the market: the venues' per-8-hour rates averaged with their open interest as weights, as a baseline series that turns red when shorts pay. - [Activity by hour and weekday](https://ferrochart.com/charts/perps/hourheat): When BTC trades: average hourly volume over twelve weeks by hour of day and weekday, as a heat map with a sequential colour scale whose range ignores the… --- ## On-chain - [MVRV · realised price](https://ferrochart.com/charts/onchain/mvrv): Price against the average cost of all holders on a log scale; MVRV above 1 means holders are in profit on average. - [Realised price bands](https://ferrochart.com/charts/onchain/mvrvband): Price on a log scale over bands at 0.75×, 1×, 1.25× and 1.5× the realised price, filled with addBand; below, MVRV (price over realised price). - [HODL waves](https://ferrochart.com/charts/onchain/hodlwaves): Weekly supply by time since the coins last moved, stacked to 100% under the price: young coins (warm) swell in rallies as old coins are spent. - [SOPR-colored price](https://ferrochart.com/charts/onchain/sopr): The price is drawn green while the 7-day SOPR is above 1 (coins being spent are sold at a profit) and red below, as two line series with NaN gaps. - [NUPL cycle zones](https://ferrochart.com/charts/onchain/nupl): NUPL, computed from MVRV as 1 − 1/MVRV, as a histogram colored by cycle zone, with dotted price lines at the zone edges and a legend drawn by a layer… - [Market cap vs realised cap](https://ferrochart.com/charts/onchain/realizedcap): Market cap against realised cap (every coin valued at the price it last moved) on a log scale. - [Long- and short-term holders](https://ferrochart.com/charts/onchain/lthsupply): Supply held by long-term holders (coins unmoved for 155+ days) and by short-term holders, each in its own pane: long-term holders sell into rallies, which… - [Coin-days destroyed · dormant supply](https://ferrochart.com/charts/onchain/cdd): Coin-days destroyed per day, with the top 5% of days highlighted by per-point color: old coins waking up. - [Supply by balance tier](https://ferrochart.com/charts/onchain/balbands): Five years of weekly data: the share of supply held by addresses in each balance tier, in percent. - [Issuance minus burn](https://ferrochart.com/charts/onchain/burnnet): New coins issued minus fees burned, per day, colored by sign; when activity spikes, the burn outruns issuance. - [Fee revenue by chain](https://ferrochart.com/charts/onchain/chainfees): Two years of weekly fee revenue on five chains, in $M on a log scale so the small chains stay readable next to the large ones. - [Supply in profit](https://ferrochart.com/charts/onchain/supplyprofit): The share of supply that last moved below today's price, from a small cost-basis model built from daily volume in the example, on a fixed percent scale… - [Miner balance · outflows](https://ferrochart.com/charts/onchain/minerflow): Coins held by miner addresses and what they send out each day: outflows jump on big moves as miners sell into strength or cover costs in drawdowns. - [Hash ribbons](https://ferrochart.com/charts/onchain/hashribbon): Hash rate (EH/s) with its 30- and 60-day averages; addBand fills red while the fast one is below (miner capitulation) and markers flag the recoveries on the… - [Puell multiple](https://ferrochart.com/charts/onchain/puell): Miner revenue against its own one-year average: low readings mark miner stress, high ones overheated markets. - [NVT signal](https://ferrochart.com/charts/onchain/nvt): The network's price-to-earnings: market cap over the 90-day average of value moved on chain, as a baseline around 70. - [Staking ratio · yield](https://ferrochart.com/charts/onchain/stakeyield): The share of supply staked keeps climbing while the annual staking yield drifts: two panes in percent under the price. - [Log regression rainbow](https://ferrochart.com/charts/onchain/rainbow): A power-law fit of price against time since the first block, with nine bands of ±2.2 standard deviations filled by addBand on a log scale. - [Exchange and bridge net flows](https://ferrochart.com/charts/onchain/exflow): Coins moved onto exchanges (red, potential selling) or off them (green), and the net value bridged into a chain, each a histogram with per-point colors in… - [Active addresses · transfer sizes](https://ferrochart.com/charts/onchain/activity): Three years of weekly data: active addresses, and the number of transfers stacked by size: three histograms drawn tallest first so each layer shows its own… - [Cost basis distribution](https://ferrochart.com/charts/onchain/costbasis): A layer plugin draws, to the right of the candles, how much supply last moved at each price ($1,000 rows), from a simple model built from daily volume:… --- ## DeFi & AMMs - [LP range on pool candles](https://ferrochart.com/charts/defi/lprange): One-hour pool candles with a liquidity position: two dashed lines from the entry bar with addBand between them mark the range, and markers show where the… - [LP risk canvas](https://ferrochart.com/charts/defi/lp-risk): One position with its risks on one chart. - [LP positions](https://ferrochart.com/charts/defi/lanes): Six liquidity positions of one pool over a month of one-hour candles. - [AMM liquidity history](https://ferrochart.com/charts/defi/ammheat): Where the liquidity of a pool sat over a month: a depth heatmap with one column per hour and one row per $10 level, under the candles. - [LP position replay](https://ferrochart.com/charts/defi/lpreplay): A month of a rebalancing LP strategy replayed on one-hour candles: the range is ±5% and moves to the price after eight hours outside it. - [Pool TVL · volume · fees](https://ferrochart.com/charts/defi/poolstats): A year of one pool: value locked in USD millions, daily swap volume, and the fee APR, a day’s fees annualised over the value locked. - [Yield by source](https://ferrochart.com/charts/defi/apybreak): A pool’s yield in percent a year, split by source: trading fees (blue) and token rewards (violet) stacked on top. - [TVL change: price vs flows](https://ferrochart.com/charts/defi/tvlbreak): Value locked in USD billions and where each day’s change came from: the price effect on the tokens already deposited (middle) and net deposits or… - [Revenue vs incentives](https://ferrochart.com/charts/defi/revincentive): Two years of a protocol’s weekly revenue (up) against the token incentives it paid out (down), in USD millions, and the net as a baseline series around… - [LP P&L: fees vs LVR](https://ferrochart.com/charts/defi/lvrdecomp): Two months of an LP position’s cumulative P&L in USD thousands: fees earned (green), loss-versus-rebalancing computed from hourly returns (red, negative)… - [Tokenised treasury fund](https://ferrochart.com/charts/defi/rwa): A year of a tokenised money-market fund: assets in USD millions, the yield it pays (a step line that follows the policy rate) and the token’s premium or… - [Lending rates](https://ferrochart.com/charts/defi/lendrates): Borrow (amber) and supply (green) APR of a stablecoin market in percent, with the spread filled by addBand. - [Bad debt vs reserve](https://ferrochart.com/charts/defi/baddebt): Two years of a lending protocol’s bad debt (red area) against the reserve set aside to cover it (green), in USD millions, with the collateral price below:… - [Liquidation auction](https://ferrochart.com/charts/defi/auctionpath): One collateral auction on 15-second data: the auction price (amber steps) starts above the market (blue) and falls 1% a minute until keepers buy, marked… - [Stablecoin depeg](https://ferrochart.com/charts/defi/depeg): Four months of a stablecoin’s price every four hours as basis points from $1, as a baseline series around the peg, with a −50 bp alert line. - [Mint & redeem flows](https://ferrochart.com/charts/defi/mintredeem): A stablecoin’s daily net issuance in USD millions, mints up and redemptions down, and the supply it adds up to in USD billions. - [Stablecoin supply by chain](https://ferrochart.com/charts/defi/stablesupply): Two years of one stablecoin’s supply in USD billions, stacked by chain: Chain A at the bottom, Chain E on top. - [Staking queues](https://ferrochart.com/charts/defi/unstakeq): A year of the staking queues in thousand ETH: waiting to exit (red) and to enter (green). - [LST · LRT discount](https://ferrochart.com/charts/defi/lstpeg): Market price of a liquid staking token (top) and a restaking token (bottom) against the ETH backing them, in percent, as baseline series around par. - [Oracle deviation](https://ferrochart.com/charts/defi/oraclelag): Twelve hours of one-minute prices: the market (blue) and an oracle (amber steps) that updates on a 0.5% move or an hourly heartbeat. - [Airdrop claims & selling](https://ferrochart.com/charts/defi/airdrop): The three months after a token airdrop: tokens claimed (green) and sold (red), cumulative in millions against the 200 M allocation, with the token’s daily… - [Cross-pool spreads](https://ferrochart.com/charts/defi/xpool): Six hours of one-minute ETH prices: the reference venue on top and, below, each pool’s deviation from it in basis points. - [Concentrated liquidity by price](https://ferrochart.com/charts/defi/liqdist): How an ETH pool's liquidity is spread over $10 price ticks, beside two weeks of hourly candles: a FerroPlot of horizontal bars attached with attachSidePlot,… --- ## Memecoins & wallets - [Market-cap chart with trade labels](https://ferrochart.com/charts/meme/meme): Fifteen-minute candles quoted in market cap ($M, price times supply). - [Trade bubbles](https://ferrochart.com/charts/meme/meme-bubbles): A layer plugin draws a bubble at the time and price of each of the 80 largest trades of the last two hours, sized by its notional and colored by the… - [KOL and smart-money wallets](https://ferrochart.com/charts/meme/meme-kol): One-minute candles with the largest trades of 16 tracked wallets as avatars: influencers (KOL) with a thin ring, smart money with a thick one, green for… - [Meme reality layer](https://ferrochart.com/charts/meme/meme-reality): What the feed shows against what traded. - [Market cap step line](https://ferrochart.com/charts/meme/meme-line): Market cap as a step line: the hourly close times the circulating supply, which changes in steps as tokens are burned or minted (second pane). - [Top-holder concentration](https://ferrochart.com/charts/meme/topholders): How much of the supply the ten largest wallets hold, stacked in percent under four-hour candles: concentration falls as the token rallies and spreads to new… - [Developer wallet timeline](https://ferrochart.com/charts/meme/devwallet): Every swap and transfer of the developer wallet as a marker on hourly candles, and the wallet's balance replayed from those events as a step area below. - [LP lock and burn](https://ferrochart.com/charts/meme/lplock): Liquidity-pool locks, unlocks and burns as markers, and the share of LP tokens that cannot be pulled, replayed from those events as stacked step areas on a… - [Social heat and price](https://ferrochart.com/charts/meme/social): Mentions per hour as a histogram colored by the mood of the posts, and average sentiment from −1 to 1 as a baseline series: hype peaks with the price. - [Suspected wash trading](https://ferrochart.com/charts/meme/washtrade): The share of each bar's volume flagged as likely wash trading, pink above a 30% threshold, with markers on single flagged trades and their notional. - [Arbitrage window lifetimes](https://ferrochart.com/charts/meme/arblifetime): The price gap between two pools every 5 seconds. - [Launch, graduation, listing](https://ferrochart.com/charts/meme/lifecycle): A token's first year on a log scale. - [Wallet group flows](https://ferrochart.com/charts/meme/groupflow): Net buying by labeled wallet groups: smart money's hourly flow as a signed histogram, and every group's running total since the start of the window as… - [Unlock schedule and supply](https://ferrochart.com/charts/meme/unlock): Monthly token unlocks over the last half year and the next one: the circulating supply steps up at each unlock (markers, future ones in amber) inside the… --- ## Equities & fundamentals - [Revenue · profit · free cash flow](https://ferrochart.com/charts/equities/financials): Six years of quarterly results on quarterly timestamps: revenue with net income drawn over it as two histogram series, free cash flow as a line, and both… - [EPS: actual vs estimate](https://ferrochart.com/charts/equities/surprise): Reported EPS as two points series (sized with lineWidth), beats and misses, against the consensus estimate (dashed), with the surprise in percent as a… - [Margin trends](https://ferrochart.com/charts/equities/margins): Gross, operating and net margin per quarter, each a line with points on the reported quarters, on one percent scale. - [Guidance vs actual](https://ferrochart.com/charts/equities/guidance): Quarterly revenue against the range guided a quarter earlier, filled with addBand. - [Earnings reaction replay](https://ferrochart.com/charts/equities/earnreplay): Daily candles played back with update, the way a host app drives a replay; each report marker (beat or miss, with the EPS surprise) appears when the replay… - [Estimate revisions](https://ferrochart.com/charts/equities/revisions): Weekly candles over the next-year EPS consensus as a step line, and the number of analysts raising (up) and cutting (down) their estimate each week. - [Valuation percentile bands](https://ferrochart.com/charts/equities/valband): Five years of weekly trailing P/E (price over trailing EPS) against its own history: addBand shades the most expensive and cheapest 20% of readings, with… - [Analyst price targets](https://ferrochart.com/charts/equities/targets): The history of the high, mean and low 12-month targets around daily candles, with the high–low range filled by addBand, and today's three targets as… - [52-week range position](https://ferrochart.com/charts/equities/range52): Rolling 52-week high and low as dotted step lines on daily candles, today's levels as price lines, and the close's position in the range (0–100%) as a… - [Short interest · borrow fee](https://ferrochart.com/charts/equities/shortint): A growth stock with short interest as a percent of free float and the annualised borrow fee in their own panes: both climb into sell-offs and ease in rallies. - [Dividends, buybacks & splits](https://ferrochart.com/charts/equities/dividendsbuyback): Corporate actions from three event feeds as markers on split-adjusted daily candles: quarterly dividends with the amount per share, buyback authorisations… - [Dividend history & coverage](https://ferrochart.com/charts/equities/dividend): Quarterly dividend per share as a histogram, and its earnings coverage below as a baseline series around 2x with a price line at the threshold. - [Buybacks & share count](https://ferrochart.com/charts/equities/buyback): Money spent on repurchases each quarter as a histogram and the shares outstanding as a step line: the share count shrinks as the buybacks retire stock. - [Insider trades](https://ferrochart.com/charts/equities/insider): Insider open-market buys (B) and sells (S) as markers on daily candles, labelled in USD millions, with the signed value of each trade as a histogram on the… - [Revenue by segment](https://ferrochart.com/charts/equities/segments): Quarterly revenue of four business lines as a stacked bar chart: the example sums the segments and draws each running total as a histogram, tallest first. - [Earnings quality](https://ferrochart.com/charts/equities/accrual): Net income against operating cash flow with addBand filling the gap, green where cash covers earnings and red (fillCrossed) where it does not, and the… - [Market breadth](https://ferrochart.com/charts/equities/breadth): Index futures over daily net advancing issues as a histogram and the advance–decline line, their running sum. - [Income statement waterfall](https://ferrochart.com/charts/equities/incomewf): One quarter of a company's income statement from revenue down to net income as a waterfall: costs step down in red, subtotals and the total are full bars… - [Seasonality by month](https://ferrochart.com/charts/equities/seasonality): A stock's return since the first trading day of January for each year, month by month: past years in grey, their average dashed and this year in blue. - [Monthly returns heat map](https://ferrochart.com/charts/equities/seasonheat): Every month's return of a stock over ten years, one row per year: a cells mark on two category axes with a diverging colour scale (green up, red down) and… - [Daily returns calendar](https://ferrochart.com/charts/equities/calendar): A year of BTC daily returns as a calendar: one cell per day, a column per week and a row per weekday, green for up days and red for down days. - [Relative rotation graph](https://ferrochart.com/charts/equities/rrg): Five markets against the equity index on a relative rotation graph: relative strength (x) against its momentum (y), each with a ten-week tail. --- ## China A-shares - [Intraday tick chart](https://ferrochart.com/charts/ashares/intraday): One session of one-minute closes as a baseline series around the previous close, the running average price and volume. - [Five-day tick chart](https://ferrochart.com/charts/ashares/intraday5): Five sessions of one-minute closes against the close before them, with the average price restarting each day. - [Opening call auction](https://ferrochart.com/charts/ashares/auction): The ten-minute opening call auction: the indicative match price as a step line, matched volume building up, and the unmatched buy or sell surplus. - [Chip distribution (CYQ)](https://ferrochart.com/charts/ashares/chips): Where the float last changed hands: a turnover-decay model in a few lines spreads each day's turnover over its range. - [Main-force money flow](https://ferrochart.com/charts/ashares/moneyflow): Daily net inflow of extra-large and large orders (the "main force") as a red/green histogram, and the cumulative net inflow of each order size below: big… - [Cross-border connect flows](https://ferrochart.com/charts/ashares/connect): Net buying of A-shares through the cross-border stock connect under the index: daily flows as a histogram and their running total as an area series. - [Margin financing balance](https://ferrochart.com/charts/ashares/margin): Two years of the market-wide margin financing balance (leveraged longs) and securities lending balance (shorts) on the index's time axis, each in its own… - [Block trades](https://ferrochart.com/charts/ashares/blocktrade): Off-exchange block trades from an event feed: markers name the buying branch, and the pane below gives each block's premium or discount to the day's close.… - [Limit-up statistics](https://ferrochart.com/charts/ashares/limitstats): Market-wide counts of stocks closing at the daily price limit, up and down, and the share of limit-ups that failed to hold into the close, a gauge of… - [Market sentiment gauge](https://ferrochart.com/charts/ashares/sentiment): A composite "money-making effect" score as a baseline series, built from advancing stocks (a histogram around half the market, using baseValue), the… - [IPO first-day returns](https://ferrochart.com/charts/ashares/ipo): Each new listing's first-day return as a point on its listing date, red for gains and green for breaks below the offer price, and the rolling break rate of… - [Lock-up expiry calendar](https://ferrochart.com/charts/ashares/alift): Lock-up expiries of restricted shares under the stock: past ones in grey, the schedule for the next six months in amber. - [Convertible bond premiums](https://ferrochart.com/charts/ashares/cbpremium): A convertible bond's premium over its conversion value and over its straight-bond floor, with addBand coloring which one dominates: bond-like when the stock… - [Convertible call countdown](https://ferrochart.com/charts/ashares/cbcall): The stock under a convertible bond with its conversion price and 130% call trigger as price lines, the count of qualifying days in the last 30 as a… - [A/H share premium](https://ferrochart.com/charts/ashares/ahpremium): The same company listed in two markets: the A share and the H share converted to CNY, and the premium of A over H as a baseline series around zero. - [Warehouse receipts](https://ferrochart.com/charts/ashares/warrantcn): A futures contract with its registered warehouse receipts, deliverable stock in exchange warehouses, and their daily change in red and green: receipts pile… --- ## Options & volatility - [Implied vs realised vol · IV rank](https://ferrochart.com/charts/options/ivrv): At-the-money implied volatility against 20-day realised volatility, with addBand shading the gap: violet while options price more movement than the stock… - [Expected move to expiry](https://ferrochart.com/charts/options/expmove): The move options price in by an expiry 21 trading days out: the stock price ± spot × IV × √t for one (filled with addBand) and two standard deviations… - [Risk reversal · butterfly](https://ferrochart.com/charts/options/rrfly): The 25-delta risk reversal (call minus put implied volatility) as a baseline series: red while puts trade over calls. - [Put/call ratio](https://ferrochart.com/charts/options/pcr): Daily put volume over call volume as a baseline series around 1, red when puts dominate, with its 10-day average in amber. - [Large option prints](https://ferrochart.com/charts/options/optflow): Large option trades on one-hour candles: a layer plugin draws a bubble per print at the stock price when it traded, its area proportional to the premium,… - [Earnings: implied vs actual move](https://ferrochart.com/charts/options/earnmove): One slot per earnings report: the actual one-day move as a histogram and the move options implied as violet points at ± that size. - [Open interest by strike](https://ferrochart.com/charts/options/oitime): Calls plus puts open at each strike, day by day, as an addHeatmap fed with one column per day: rows are strikes and brighter cells hold more contracts.… - [Dealer gamma exposure](https://ferrochart.com/charts/options/dex): Dealer gamma at every price, day by day, from open interest by strike and implied volatility: green where dealers are long gamma and damp moves, red where… - [Strategy P&L by price and date](https://ferrochart.com/charts/options/pnlheat): What an iron condor on BTC opened today is worth on each future day at each price, priced with Black–Scholes at today's implied volatility: green for… - [Delta hedge replay](https://ferrochart.com/charts/options/hedgereplay): Delta hedging a short call position, replayed: markers are the daily stock trades that keep it delta neutral, the middle pane the shares held (step line)… - [Gamma P&L attribution](https://ferrochart.com/charts/options/gammapnl): A delta-hedged long call position's daily P&L split by Greek: what gamma earns (green) against what theta costs (red) in one pane, vega (violet) in the… - [Volatility smile](https://ferrochart.com/charts/options/smile): Implied volatility across strikes for 30-day BTC options, built from at-the-money vol, the 25-delta risk reversal and the butterfly: today in violet, a… - [Option payoff · long straddle](https://ferrochart.com/charts/options/payoff): Profit and loss of a 30-day at-the-money BTC straddle against the price: at expiry as an area that is green above zero and red below (downColor under… - [Greeks across the price](https://ferrochart.com/charts/options/greeks): Delta, gamma and theta of a three-week BTC call against the underlying price. - [Volatility cone](https://ferrochart.com/charts/options/volcone): How volatile BTC has been over windows of 10 to 252 days: bands from the 5th to 95th and 25th to 75th percentiles of four years of history (areas with a… - [Implied price distribution](https://ferrochart.com/charts/options/impliedpdf): Where options say BTC will be in 30 days: the risk-neutral density from the smile (Breeden–Litzenberger), as horizontal bars in a FerroPlot beside the… - [Gamma exposure by strike](https://ferrochart.com/charts/options/gex): Dealer gamma exposure at each of nine BTC strikes: positive (green) where dealers are long gamma and damp moves, negative (red) where they chase them. - [Open interest by strike](https://ferrochart.com/charts/options/oichain): Call and put open interest at each BTC strike as grouped bars (marks with the same group sit side by side), with the max-pain strike, where option buyers… --- ## Rates, FX & macro - [Curve level · slope · curvature](https://ferrochart.com/charts/rates/curveshape): A yield curve in three numbers: the level (the 10-year yield, percent), the slope (10s minus 2s, bp) as a baseline series that turns red when the curve… - [Real yield · breakeven inflation](https://ferrochart.com/charts/rates/breakeven): The 10-year nominal yield (blue) and the real yield of inflation-linked bonds (violet). - [Swap spread](https://ferrochart.com/charts/rates/swapspread): The 10-year swap rate (amber) against the treasury yield (blue), and their difference in basis points as a baseline series. - [Credit spread percentiles](https://ferrochart.com/charts/rates/spreadpct): A high-yield credit spread over five years against its own distribution: the 10th–90th percentile range shaded with addBand, the median dotted, and today's… - [Maturity wall](https://ferrochart.com/charts/rates/maturitywall): Corporate bonds coming due per year, in USD bn: investment grade (blue) stacked on high yield (amber). - [Bond cash-flow ladder](https://ferrochart.com/charts/rates/cashflowladder): Ten years of cash flows from a five-bond portfolio, one slot per semi-annual payment date: coupons stacked by bond above, steps down as each bond matures,… - [Treasury auction results](https://ferrochart.com/charts/rates/tsyauction): Two years of monthly 10-year auctions on an axis of auction dates only: the stop-out yield, the bid-to-cover ratio against its average, and the tail in… - [Central bank balance sheets](https://ferrochart.com/charts/rates/cbbs): Total assets of four central banks in USD tn over ten years of month-end values, stacked: each area is a running sum, and the largest is drawn first so the… - [Macro data surprises](https://ferrochart.com/charts/rates/macroev): Each data release as a bar of its surprise, actual minus consensus in standard deviations, under daily EUR/USD candles. - [FX carry · drawdown](https://ferrochart.com/charts/rates/carry): Total return of an FX carry basket, long high-yielding currencies against low-yielding funders, and its drawdown from the running peak below: carry earns… - [Rate differential vs FX](https://ferrochart.com/charts/rates/ratediff): USD/JPY (blue) against the two-year yield gap between the two countries (amber), both rebased to 100 with indexedTo100 so a percent and an exchange rate… - [Real effective exchange rate](https://ferrochart.com/charts/rates/reer): EUR/USD (blue) against the euro's nominal (amber) and inflation-adjusted real (violet) effective exchange rates, trade-weighted against many currencies.… - [Purchasing power parity gap](https://ferrochart.com/charts/rates/ppp): EUR/USD against its purchasing-power-parity fair value. - [FX trading sessions](https://ferrochart.com/charts/rates/fxsessions): Fifteen-minute EUR/USD candles over the Asian, European and US sessions. - [Balance of payments](https://ferrochart.com/charts/rates/bop): Ten years of quarterly flows in USD bn: the current account (goods, services, income) above and the financial account (direct, portfolio, other investment)… - [Treasury yield curve](https://ferrochart.com/charts/rates/yield): The Treasury curve today and three months ago, fitted with Nelson–Siegel through the 2-, 5- and 10-year yields. - [Key rate durations](https://ferrochart.com/charts/rates/krd): How a bond portfolio's interest-rate risk is spread along the curve against its benchmark: the duration attributed to each key rate, as horizontal grouped… - [Policy rate projections (dot plot)](https://ferrochart.com/charts/rates/dotplot): A dot plot of nineteen policy makers' rate projections per year. --- ## Futures & commodities - [Futures basis](https://ferrochart.com/charts/commodities/basis): Daily crude oil candles over the basis, front-month futures minus spot in USD per barrel, as a baseline series: red while the market is in backwardation.… - [Positioning report](https://ferrochart.com/charts/commodities/cot): Weekly crude oil candles over the weekly positioning report: net positions of managed money (amber), swap dealers (blue) and other reportables (violet) in… - [Inventories vs price](https://ferrochart.com/charts/commodities/invprice): Weekly crude oil candles over commercial inventories in million barrels and the weekly change: builds in red, draws in green. - [3-2-1 crack spread](https://ferrochart.com/charts/commodities/crack): A refiner's margin from three futures: crude (white), gasoline (amber) and heating oil (blue) in USD per barrel above, and the 3-2-1 crack spread below as a… - [Soybean crush margin](https://ferrochart.com/charts/commodities/crush): The board crush, what a processor earns turning a bushel of soybeans into meal and oil, in USD per bushel as a baseline series around its average. - [Freight and origin spread](https://ferrochart.com/charts/commodities/freight): A dry bulk freight index (points), the export price spread between two soybean origins in USD per tonne as a baseline series, and soybean futures below, all… - [Residual load](https://ferrochart.com/charts/commodities/residualload): A year of grid demand (white) with solar (amber) and wind (blue) taken off it as addBand fills, leaving the residual load (red) that gas and coal plants… - [Carbon price · allowance balance](https://ferrochart.com/charts/commodities/carbon): Weekly carbon allowance candles over the market's balance: allowances issued minus verified emissions each week (red: a deficit), and the running surplus as… - [Heating and cooling degree days](https://ferrochart.com/charts/commodities/weatherdd): Natural gas candles over daily heating (blue) and cooling (amber) degree days, the gap between the mean temperature and 65 °F, with the seasonal normal… - [Futures term structure](https://ferrochart.com/charts/commodities/term): Crude oil futures by expiry month today (amber) and a month ago (dashed): downward sloping in backwardation, upward in contango. --- ## Funds & ETFs - [Premium / discount to NAV](https://ferrochart.com/charts/funds/premdisc): A listed fund's market price against its net asset value, and the premium or discount of the price to NAV as a baseline series around zero: positive in… - [Tracking difference & error](https://ferrochart.com/charts/funds/trackerr): An index fund against its index rebased to 100 (indexedTo100), the daily tracking difference in basis points and the rolling 60-day tracking error, computed… - [Fee drag](https://ferrochart.com/charts/funds/feedrag): Ten years of growth of 10,000 in a total-return index before fees, and after a 0.10% and a 1.50% annual fee. - [Dollar-cost averaging](https://ferrochart.com/charts/funds/dca): Five years of a monthly investment plan against investing the same total on day one: the plan's value as an area, the money paid in as a step line, and the… - [Returns by manager tenure](https://ferrochart.com/charts/funds/managertenure): Eight years of an active fund's NAV on a log scale. - [Top holdings over time](https://ferrochart.com/charts/funds/topholdings): Portfolio weights of a fund's five largest holdings from quarterly disclosures, stacked: each segment is one holding and the height of the bar is the top-5… - [Fund shares & net creations](https://ferrochart.com/charts/funds/fundshares): An index fund's shares outstanding and the daily net creations and redemptions under its index: investors redeem into rallies and buy the dips. - [Brinson attribution](https://ferrochart.com/charts/funds/brinson): Why a fund beat its benchmark last quarter: a waterfall from the benchmark return through each sector's Brinson–Fachler effect (allocation, selection and… --- ## Portfolio, risk & quant - [Equity curve · drawdown](https://ferrochart.com/charts/quant/equity): A strategy against its benchmark on a percentage price scale, so both read as return since the first visible day, with the drawdown from the running peak in… - [Underwater curve · worst drawdown](https://ferrochart.com/charts/quant/ddepth): The underwater curve, the percentage below the running peak, as a baseline series under the equity. - [Joint drawdowns](https://ferrochart.com/charts/quant/jointdd): Drawdowns of three strategies (trend, carry, value), one baseline pane each, and a histogram counting how many are more than 10% under water on the same… - [Walk-forward windows](https://ferrochart.com/charts/quant/walkfwd): A walk-forward test: the model is fitted on 250 days and traded on the next 60, then the window rolls on. - [In-sample vs out-of-sample](https://ferrochart.com/charts/quant/isos): One equity curve split into the period the strategy was designed on and the held-out period. - [Live vs backtest](https://ferrochart.com/charts/quant/livevsbt): The live equity of a strategy against its backtest (grey) since launch, both rebased to 1, with the tracking gap in percent as a baseline series below and a… - [Rebalancing counterfactuals](https://ferrochart.com/charts/quant/rebalcf): One portfolio rebalanced monthly (green), quarterly (blue) or never (grey), rebased to 1. - [Rolling return · volatility · Sharpe · beta](https://ferrochart.com/charts/quant/rolling): Half-year (126-day) rolling statistics of a strategy, computed in the example from its daily returns: annualised return and volatility in percent, the… - [Rolling correlation](https://ferrochart.com/charts/quant/corrtime): Soybeans (amber) and soybean meal (blue) on a percentage scale, and below, the 40-day correlation of their daily returns as a baseline around the 250-day… - [VaR backtest exceptions](https://ferrochart.com/charts/quant/varbt): Daily P&L in thousands as a histogram against a rolling 99% historical VaR (amber step line). - [Liquidity-adjusted VaR](https://ferrochart.com/charts/quant/lvar): One-day 99% VaR and liquidity-adjusted VaR in millions, with addBand filling the liquidity add-on between them. - [Cash stress test](https://ferrochart.com/charts/quant/cashstress): A fund's weekly cash in millions under a base and a stress scenario, against the cash it could be asked for in margin calls and redemptions (red). - [Currency hedge effect](https://ferrochart.com/charts/quant/fxhedge): Cumulative return in euros of US stocks, hedged (green) and unhedged (grey), aligned by date in the example. - [Allocation & drift](https://ferrochart.com/charts/quant/alloc): Weekly weights of four asset classes stacked to 100%: each boundary is a running sum, and addBand fills between neighbouring lines. - [Factor ranking (bump chart)](https://ferrochart.com/charts/quant/bump): The monthly rank of six equity factors by trailing score: one line and points series per factor, with the price scale inverted so rank 1 is on top. - [Quintile backtest](https://ferrochart.com/charts/quant/quantile): Cumulative return in percent of five portfolios sorted on a factor, from the bottom quintile (red) to the top (green). - [IC · Rank IC](https://ferrochart.com/charts/quant/ic): A factor's weekly information coefficient as a histogram colored by sign, the rank IC (blue) and its 26-week rolling mean (amber), with a zero price line. - [Factor turnover](https://ferrochart.com/charts/quant/factorturn): The share of a monthly-rebalanced factor portfolio traded at each rebalance, in percent, with the average as a dashed price line. - [Market regimes](https://ferrochart.com/charts/quant/regime): Daily candles over shaded market regimes: bull above a 50-day average, bear below it, and stress when 20-day volatility runs well above its median. - [Return distribution](https://ferrochart.com/charts/quant/distrib): Four years of BTC daily returns: a histogram, a kernel density estimate (white) and the normal distribution with the same mean and deviation (dashed). - [Risk vs return](https://ferrochart.com/charts/quant/riskret): Eleven markets by one-year return against annualised volatility, coloured by return per unit of risk on a diverging colour scale (red below zero, green… - [Efficient frontier](https://ferrochart.com/charts/quant/frontier): Random long-only mixes of stocks, gold, bitcoin and the euro, from three years of daily returns, coloured by Sharpe ratio, with the efficient frontier (the… - [Correlation matrix](https://ferrochart.com/charts/quant/correlation): Correlations of six months of daily returns between ten markets as a heat map: cells on two category axes with a diverging colour scale centred on zero… - [Factor exposures by month](https://ferrochart.com/charts/quant/factors): Six equity factor scores of a portfolio month by month as stacked bars (marks with the same stack add up, positives above zero and negatives below), with… --- ## Private markets & personal finance - [Private fund J-curve](https://ferrochart.com/charts/finance/jcurve): Net cash flow to investors per year in millions (calls red, distributions green) and the cumulative net cash flow in amber: the J. - [Capital calls & distributions](https://ferrochart.com/charts/finance/capitalcalls): Seven years of quarterly capital calls (down) and distributions (up) of one fund commitment in millions, and below, the cumulative net cash flow as a… - [DPI · TVPI](https://ferrochart.com/charts/finance/tvpi): A fund's quarterly multiples: total value to paid-in (TVPI) and distributed to paid-in (DPI). - [Platform AUM by business](https://ferrochart.com/charts/finance/aummix): Ten years of assets under management in billions by business line, stacked: each line is a running total and addBand fills between neighbours. - [Cash runway scenarios](https://ferrochart.com/charts/finance/cashrunway): A startup's cash in millions: 18 months of history, then three burn scenarios projected 30 months ahead from the last balance and burn. - [Funding rounds & valuation](https://ferrochart.com/charts/finance/rounds): A startup's post-money valuation in millions as a step area on a logarithmic scale, one step per funding round, with the amount raised per round below. - [Debt covenant headroom](https://ferrochart.com/charts/finance/covenantheadroom): A borrower's quarterly net debt to EBITDA against a 4.0x maintenance covenant (red price line), and below, the headroom in percent: how far EBITDA could… - [Cash conversion cycle](https://ferrochart.com/charts/finance/cashcycle): Days sales outstanding (DSO), days inventory outstanding (DIO) and days payables outstanding (DPO) by quarter, and below, the cash conversion cycle DSO +… - [Mortgage amortization](https://ferrochart.com/charts/finance/amortization): Each year's payments on a 30-year fixed mortgage, in thousands, split into interest (amber) and principal (blue) by drawing two histograms over each other,… - [Prepayment vs standard](https://ferrochart.com/charts/finance/prepay): Remaining balance in thousands of a 30-year mortgage paid as scheduled (grey) or with $500 extra a month (green), with addBand between them and the… - [Debt payoff: snowball vs avalanche](https://ferrochart.com/charts/finance/debtplan): Total debt left in thousands under two payoff plans with the same monthly budget: snowball (smallest balance first, amber) and avalanche (highest rate… - [Net worth breakdown](https://ferrochart.com/charts/finance/networth): Ten years of a household balance sheet in thousands: home (slate), investments (blue) and cash (amber) stacked up, mortgage (dark red) and other debt (red)… - [Retirement savings fan](https://ferrochart.com/charts/finance/retirement): Twenty years of weekly outcomes for a $650k portfolio: the median path and the 25–75% and 5–95% ranges filled with addBand, against a $2m goal. --- ## Prediction markets - [Probability with news](https://ferrochart.com/charts/prediction/probline): Two months of a binary market’s Yes price as a percent chance, on a fixed 0–100 scale, with the news that moved it marked by setMarkers. - [Multi-outcome market](https://ferrochart.com/charts/prediction/outcomes): Three months of a five-outcome market. - [Cross-market consistency](https://ferrochart.com/charts/prediction/marketconstraints): Yes prices of three markets on mutually exclusive outcomes (A amber, B blue, C violet) and, below, their sum against 100%. - [Resolution timeline](https://ferrochart.com/charts/prediction/resolutionpath): The last ten days of a market: trading, then a proposed outcome, a dispute, a 48-hour vote and the payout. - [Forecast revisions](https://ferrochart.com/charts/prediction/forecastrevision): Thirty weekly revisions of a published vote-share forecast (step line) with its uncertainty band, narrowing as the vote nears, and the final result as a… --- ## Custom series & plugins - [100% stacked area](https://ferrochart.com/charts/custom/stackedarea): Portfolio weights stacked to 100% over a year. - [Stacked columns](https://ferrochart.com/charts/custom/stackedbars): Daily spot volume by venue (USD billions) stacked into one column per day. - [Grouped columns](https://ferrochart.com/charts/custom/groupedbars): Weekly volume per venue as side-by-side columns in each week's slot. - [Buy vs sell volume](https://ferrochart.com/charts/custom/dualhist): Under one-minute candles: aggressive buy volume up, sell volume down (BTC) and their difference as an amber line, aggregated from the trade feed in a few… - [Rounded gradient columns](https://ferrochart.com/charts/custom/prettyhist): One venue's daily volume (USD billions) as rounded columns, each shaded from sky at the foot to violet at the top. - [Lollipop](https://ferrochart.com/charts/custom/lollipop): Daily returns as lollipops: a histogram stick from zero with a dot on its tip, colored by sign. - [Trade scatter](https://ferrochart.com/charts/custom/scatter): Four minutes of trades as points at their price, green for aggressive buys and red for sells, with bigger dots for bigger trades. - [Box & whisker](https://ferrochart.com/charts/custom/boxwhisker): The spread of each day's hourly closes: box from the first to the third quartile, amber median, whiskers to the extremes. - [Brushed range](https://ferrochart.com/charts/custom/brushable): Move the pointer to brush a range from there to the latest bar: the shaded region, the rise or fall and the percent change follow it. - [Streamgraph](https://ferrochart.com/charts/custom/streamgraph): Social mentions by topic stacked symmetrically around zero, so the stream swells and thins with the total. - [Session timeline](https://ferrochart.com/charts/custom/gantt): Thirty-minute BTC prices above a timeline of exchange sessions, one row per venue in UTC: Asia-Pacific in sky, Europe in violet, the US in amber. --- ## Labs & flagships - [Ten years, one series](https://ferrochart.com/charts/labs/deepzoom): A decade of hourly candles, about 87 600 bars, in one series on a log scale. - [Dense order book heatmap](https://ferrochart.com/charts/labs/bookmap4k): Ten minutes of the book at 250 ms and $2 resolution, 960 000 cells, aggregated per pixel on the GPU, with the last price and the larger trades as bubbles… - [Capacity terrain](https://ferrochart.com/charts/labs/capacityterrain): How much it would cost to trade, by order size (vertical, USD millions) and time: cool where liquidity is deep, hot where an order would move the price. - [Data trust rail](https://ferrochart.com/charts/labs/trustrail): A rail under the candles rates every bar: green normal, amber sparse, violet nearly empty (against the median trade count), red when the price strays more… - [Narrative timeline](https://ferrochart.com/charts/labs/narrative): Price with the story around it: on-chain events above the candles, macro news below, and social activity in the pane underneath, so a move can be read… - [Execution mirror](https://ferrochart.com/charts/labs/mirror): A replay mirror for a desk: our fills (sky) against the best price available within an hour either side (amber, with the gap in bps) and the fills of a… - [Look-ahead audit](https://ferrochart.com/charts/labs/asofaudit): For three datasets, when each record describes (grey dot) and when it became public (green tick). - [Liquidity resilience](https://ferrochart.com/charts/labs/resilience): How the market absorbs shocks: one-minute candles with the three largest moves marked, the quoted spread in bps (amber) and resting depth within 10 bps in… - [Two clocks](https://ferrochart.com/charts/labs/dualclock): One-second prices on two clocks: as the exchange stamped them (sky) and what we had actually received at that moment (amber steps). - [Leg risk](https://ferrochart.com/charts/labs/atomicitybreak): A two-leg trade that is meant to be flat but fills leg by leg: the lanes show each fill as it happens, and the step baseline below shows the net BTC… - [Gap impact lens](https://ferrochart.com/charts/labs/missingimpact): Holes in a feed (shaded), the linear patch over each one (amber) against the true price (dotted grey) and what was received (sky), with the worst error of… - [Price gravity](https://ferrochart.com/charts/labs/gravity): A sideways profile of where price has spent its volume, weighted toward recent bars, drawn against the right edge: long bands pull price, gaps let it…