VibeFox JS Trading — Help
Overview
VibeFox JS Trading is a library of financial charts for web applications: candlesticks and 13 other series types, 50 technical indicators, 48 drawing tools, real-time data from your datafeed, alerts, trading from the chart through your broker, backtests of JavaScript strategies and a ready-made terminal UI. It is plain JavaScript with no dependencies and works with or without a framework.
You create a chart with one call, createTradingChart(target, options), and control it through the same methods as every VibeFox JS library: setData, setOptions, on, getState, setState, setTheme, destroy. createTradingLayout(target, options) puts several synchronized charts on one screen.
Key features
- Series types: candlestick, OHLC, line, area, baseline, histogram, Heikin Ashi, hollow candles, volume candles, and the types built from the bars: Renko, Kagi, Point & Figure, line break, range bars.
- Timeframes from 1 minute to 1 month, resampled from your bars; live ticks and bars; markers; bar replay; volume profile.
- 50 built-in indicators (moving averages, trend, oscillators, volatility, volume, pivots and patterns) computed incrementally, and your own indicators.
- 48 drawing tools: lines, shapes, channels, pitchforks, Gann and Fibonacci tools, text and notes, measures, long / short positions; magnet, undo / redo, copy / paste, a properties panel.
- Datafeed API with lazy history paging, cache, retries and live updates; symbol comparison in percent.
- Navigator, period buttons, time zones and trading sessions with pre / post market, a watchlist, symbol search, several charts in a synchronized layout.
- Alerts on the price, volume, indicators and drawings with sounds, browser notifications and a hook for your webhook.
- Trading from the chart: order and position lines you drag, an order ticket, a depth-of-market ladder; your broker adapter executes the orders.
- Backtests of JavaScript strategies with a report, live signals and a parameter grid search in Web Workers.
- A ready-made terminal UI (toolbar, drawing toolbar, indicator and settings dialogs), four ready-made styles, every color and size as a CSS variable, WebGL drawing of large views, touch gestures, keyboard access and screen reader texts.
Requirements
- A current web browser.
- No runtime dependencies. The library makes no network requests of its own: bars come from your
dataor from your datafeed adapter, orders go to your broker adapter, alert payloads go to your own hook. - Node.js is not needed in the browser. The ES module can be imported in Node (no DOM is touched at import):
backtest,exportBacktest,paramGrid, the indicator registry and the helperssma,ema,resampleBars,buildChartType,generateBarsrun on a server. - Bars, symbols and exchange schedules are yours: the library ships no market data (the session presets are examples).
Installation
Files of the library
VibeFox JS Trading is a separate product with its own files. The whole JavaScript of the library is one file and the styles are one CSS file: a page needs exactly these two. The other files are optional.
| File | What it is |
|---|---|
vibefox-js-trading.global.js | The library for a classic <script> tag; defines one global variable, VibeFoxJSTrading. Minified: vibefox-js-trading.global.min.js. |
vibefox-js-trading.esm.js | The same code as an ES module. Minified: vibefox-js-trading.esm.min.js. |
vibefox-js-trading.css | All styles of the library, inside @layer vfjs; includes the themes light, dark and high-contrast. Minified: vibefox-js-trading.min.css. |
vibefox-js-themes.css | Optional theme pack: 18 ready-made themes (see Theming and styling). Minified: vibefox-js-themes.min.css. |
locales/vibefox-js-trading.<lang>.js | Optional language files, one for each language except English (see Localization and RTL). The same language as an ES module: .esm.js; as plain strings: .json. |
vibefox-js-trading.d.ts | TypeScript declarations (also vibefox-js-trading.esm.d.ts). |
*.js.map | Source maps. |
vibefox-js-trading-react.js, vibefox-js-trading-vue.js, vibefox-js-trading-svelte.js, vibefox-js-trading-jquery.js | Optional framework wrappers (each with its .d.ts). |
vibefox-js-trading-angular | Optional Angular package (Angular Package Format). |
vibefox-js-trading-wc.js | Optional Web Components wrapper (custom elements). |
Script tag
Link the CSS file and the script. The global variable VibeFoxJSTrading holds every export of the library. This also works from a file opened from disk (file://).
<link rel="stylesheet" href="vibefox-js-trading.css">
<script src="vibefox-js-trading.global.js"></script>
<script>
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars });
</script>
ES module
Import the ES module file and link the CSS file. Browsers load modules only over http(s), not from file://.
<link rel="stylesheet" href="vibefox-js-trading.css">
<script type="module">
import { createTradingChart } from './vibefox-js-trading.esm.js';
const chart = createTradingChart('#app', { data: bars });
</script>
npm
The library is also prepared as an npm package named @vibefox/js-trading. Install it from the package folder (or its packed .tgz file) that you received, then import it by name. Bundlers take the CSS through the @vibefox/js-trading/css export.
npm install ./vibefox-js-trading
import { createTradingChart } from '@vibefox/js-trading';
import '@vibefox/js-trading/css';
Exports of the package: @vibefox/js-trading (ES module), @vibefox/js-trading/min, @vibefox/js-trading/global, @vibefox/js-trading/global.min, @vibefox/js-trading/css, @vibefox/js-trading/min.css, @vibefox/js-trading/themes, @vibefox/js-trading/themes.min.css, @vibefox/js-trading/locales/<lang>, @vibefox/js-trading/locales/<lang>.json. TypeScript finds the declarations by itself.
Framework wrappers
The wrappers are small separate files; the library works without them. Each wrapper needs only VibeFox JS Trading and its framework (a peer dependency). The wrappers do not load CSS: link vibefox-js-trading.css yourself.
| Framework | File | npm package | Supported versions |
|---|---|---|---|
| React | vibefox-js-trading-react.js | @vibefox/js-trading-react | React 16.8 and newer |
| Vue 3 | vibefox-js-trading-vue.js | @vibefox/js-trading-vue | Vue 3.3 and newer |
| Angular | vibefox-js-trading-angular | @vibefox/js-trading-angular | Angular 17 and newer |
| Svelte | vibefox-js-trading-svelte.js | @vibefox/js-trading-svelte | Svelte 3, 4 and 5 |
| jQuery | vibefox-js-trading-jquery.js | @vibefox/js-trading-jquery | jQuery 1.12 to 4.x |
| Web Components | vibefox-js-trading-wc.js | @vibefox/js-trading-wc | no framework |
The ES module wrappers import the library as @vibefox/js-trading. Without npm, map that name to vibefox-js-trading.esm.js in your bundler settings or in an import map. The jQuery wrapper takes the library from the global VibeFoxJSTrading.
Common rules of all wrappers: props / inputs are the options of the library (changed ones go to setData or one setOptions call); events are framework events with the same payload object as on(); the instance is available for every method; on the server (SSR) an empty container is rendered and the instance is created in the browser only. The option style (ready-made look) is the prop variant in React, Vue, Svelte and Angular, because style and className / class belong to the host element.
Web Components
Load vibefox-js-trading-wc.js after the library file. It defines the elements <vfjs-trading-chart> and <vfjs-trading-layout> from the global VibeFoxJSTrading. Attributes are options in kebab-case (JSON for objects and arrays), properties are options, the methods of the component are methods of the element, events are CustomEvents named vfjstradingchart:<event> (layout: vfjstradinglayout:<event>) with the payload in detail. The element uses the light DOM, so the CSS of the library and your page CSS apply as usual.
<link rel="stylesheet" href="vibefox-js-trading.css">
<script src="vibefox-js-trading.global.js"></script>
<script type="module" src="vibefox-js-trading-wc.js"></script>
<vfjs-trading-chart id="g" style="height: 400px" symbol="BTCUSD" timeframe="5m"></vfjs-trading-chart>
<script>
const el = document.getElementById('g');
el.data = VibeFoxJSTrading.generateBars({ count: 500 });
el.addEventListener('vfjstradingchart:barClose', (e) => console.log(e.detail.bar));
</script>
With a bundler: import * as lib from '@vibefox/js-trading'; import { define } from '@vibefox/js-trading-wc'; define(lib);
Quick start
Plain HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="vibefox-js-trading.css">
<script src="vibefox-js-trading.global.js"></script>
</head>
<body>
<div id="app" style="height: 480px"></div>
<script>
// bars: { time (ms of the bar start), open, high, low, close, volume }
const bars = VibeFoxJSTrading.generateBars({ count: 1000, interval: 60000, startPrice: 100 });
const chart = VibeFoxJSTrading.createTradingChart('#app', {
data: bars,
symbol: 'DEMO',
timeframe: '5m',
toolbar: true,
drawingToolbar: true,
on: { barClose: (e) => console.log('closed', e.bar) },
});
chart.addIndicator('ema', { period: 21 });
chart.addIndicator('rsi');
// a live tick extends the last bar or opens a new one
let price = bars[bars.length - 1].close;
setInterval(() => {
price += (Math.random() - 0.5) * 0.15;
chart.addTick({ price, volume: 10 });
}, 1000);
</script>
</body>
</html>
The chart fills its element: give the element a height (without one, the chart is 400 px high: the variable --vfjs-trading-min-height). generateBars makes demo bars that look like a market; use your own bars or a datafeed (see Datafeed).
React
import { useRef } from 'react';
import { VibeFoxJSTradingChartReact } from '@vibefox/js-trading-react';
import '@vibefox/js-trading/css';
export function Prices({ bars }) {
const chart = useRef(null); // the VibeFoxJSTradingChart instance
return (
<div style={{ height: 480 }}>
<button onClick={() => chart.current.addIndicator('macd')}>MACD</button>
<VibeFoxJSTradingChartReact ref={chart} data={bars} symbol="DEMO" timeframe="15m" toolbar
onCrosshairMove={(e) => console.log(e.bar)} />
</div>
);
}
The layout wrapper is VibeFoxJSTradingLayoutReact.
Vue 3
<script setup>
import { ref } from 'vue';
import { VibeFoxJSTradingChartVue } from '@vibefox/js-trading-vue';
import '@vibefox/js-trading/css';
const props = defineProps({ bars: Array });
const timeframe = ref('15m');
</script>
<template>
<VibeFoxJSTradingChartVue :data="props.bars" v-model:timeframe="timeframe" symbol="DEMO" style="height: 480px"
@bar-close="(e) => console.log(e.bar)" />
</template>
v-model:timeframe, v-model:seriesType, v-model:symbol, v-model:timezone and v-model:sessions follow changes made in the chart.
Angular
import { Component } from '@angular/core';
import { VibeFoxJSTradingChartComponent } from '@vibefox/js-trading-angular';
@Component({
selector: 'app-root',
standalone: true,
imports: [VibeFoxJSTradingChartComponent],
template: `
<vfjs-trading-chart-ng #chart [data]="bars" symbol="DEMO" timeframe="15m" style="display: block; height: 480px"
(barClose)="closed($event)"></vfjs-trading-chart-ng>
<button (click)="chart.instance?.addIndicator('bollinger')">Bollinger</button>`,
})
export class AppComponent {
bars = [{ time: Date.UTC(2026, 0, 2), open: 10, high: 12, low: 9, close: 11, volume: 500 }];
closed(e: unknown) { console.log(e); }
}
Link vibefox-js-trading.css in angular.json (styles) or in index.html. For NgModule applications import VibeFoxJSTradingModule.
Svelte
<script>
import { vfjsTradingChart } from '@vibefox/js-trading-svelte';
export let bars;
</script>
<div style="height: 480px" use:vfjsTradingChart={{ data: bars, symbol: 'DEMO', timeframe: '15m' }}
on:vfjstradingchart:barClose={(e) => console.log(e.detail.bar)}></div>
jQuery
<script src="jquery.min.js"></script>
<link rel="stylesheet" href="vibefox-js-trading.css">
<script src="vibefox-js-trading.global.js"></script>
<script src="vibefox-js-trading-jquery.js"></script>
<script>
$('#chart').vfjsTradingChart({ data: VibeFoxJSTrading.generateBars({ count: 500 }), symbol: 'DEMO' })
.on('vfjstradingchart:barClose', (e, payload) => console.log(payload.bar));
$('#chart').vfjsTradingChart('addIndicator', 'rsi');
</script>
Core concepts
Bars
The data is an array of bars { time, open, high, low, close, volume }; time is the start of the bar in milliseconds (UTC epoch), volume is optional. The bars are sorted for you. They are the base resolution: the option timeframe shows them resampled into larger bars ('1m', '5m', '15m', '30m', '1h', '4h', '1D', '1W', '1M'; TIMEFRAMES gives their length in ms). Without timeframe (default null) the chart shows the timeframe of the bars themselves: hourly bars are '1h', daily bars '1D'; bars shorter than a minute are merged into '1m'; when no timeframe fits (for example 2-hour bars) the bars are shown as they are and no timeframe is shown (getTimeframe() returns null). The timeframe is detected again on every setData() (event timeframeChange when it changes) until you set one with setTimeframe() or the option; setOptions({ timeframe: null }) returns to the detection. With a datafeed the default is '1m'. Instead of data, a datafeed adapter can load the bars page by page (see Datafeed).
Creating and destroying
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'BTCUSD', timeframe: '1h' });
chart.setData(bars.slice(-500)); // replace the bars
chart.setTimeframe('15m'); // resample
chart.setSeriesType('heikinAshi');
chart.setOptions({ volume: { visible: false }, watermark: { text: 'BTC / USD' } });
chart.setOption('legend.visible', false);
chart.destroy();
new VibeFoxJSTradingChart(target, options) is the same as createTradingChart. getData() returns the base bars.
Events
Every event handler receives one payload object. Subscribe in the options (on: { barClose: fn }) or later with on, once and off; on('*', (event, payload) => …) receives every event.
chart.on('crosshairMove', (e) => console.log(e.time, e.bar?.close, e.price));
chart.on('visibleRangeChange', (e) => console.log(e.timeFrom, e.timeTo));
chart.on('timeframeChange', (e) => console.log(e.timeframe));
Every VibeFox JS component emits ready, dataChange, optionsChange, themeChange and destroy. The trading requests (orderPlace and others) can be answered or cancelled by a listener (see Trading from the chart). The full list is in API reference.
State snapshots
getState() returns a JSON-safe snapshot: symbol, timeframe, series type, price scale mode, visible range (as bar indexes and as times), indicators with their parameters, drawings, alerts, compared symbols, style, chart type parameters, favorites, colors, time zone, sessions, period, recent symbols and the watchlist. setState(state) restores it. A snapshot replaces the indicators, drawings and alerts as a whole, so restore full snapshots. Strategies are functions and are not part of the state.
localStorage.setItem('my-chart', JSON.stringify(chart.getState()));
chart.setState(JSON.parse(localStorage.getItem('my-chart')));
Data and real time
Live updates
addTick({ price, volume, time }) extends the current bar or opens a new one (time defaults to now); updateBar(bar) replaces or appends a whole bar of the current timeframe. Events: barUpdate ({ bar, isNew }, every tick) and barClose (a tick opened a new bar). Indicators recompute only the last bar.
chart.addTick({ price: 101.25, volume: 3 });
const last = chart.getData().at(-1);
chart.updateBar({ ...last, close: last.close + 0.5, high: Math.max(last.high, last.close + 0.5) });
chart.on('barClose', (e) => console.log('bar closed at', e.bar.close));
Helpers
resampleBars(bars, timeframe) aggregates bars into a timeframe; mergeTick(bars, tick, timeframe) merges a tick into an array; detectInterval(bars) finds the bar length; toHeikinAshi(bars) converts bars; generateBars({ count, startPrice, interval, end, volatility, seed, trend, clusters, decimals }) makes demo and test bars that look like a market: trends of different strength follow each other, calm phases alternate with bursts of volatility, candles have normal bodies and wicks. trend (default 1; 0 = a plain random walk) sets the strength of the trends, clusters (default 1; 0 = even volatility) the calm and busy phases, decimals the rounding of the prices (by default by the price level, as on the markets: 5 decimals below 10, as for a currency pair, 3 from 10 to 200, 2 from 200; a given decimals always wins). The same options and seed always give the same bars.
const hourly = VibeFoxJSTrading.resampleBars(bars, '1h');
const ha = VibeFoxJSTrading.toHeikinAshi(hourly);
console.log(hourly.length, ha[0], VibeFoxJSTrading.detectInterval(bars));
Markers
markers (option) or setMarkers(list) put arrows or circles at bars: { time, shape: 'arrowUp' | 'arrowDown' | 'circle', position: 'above' | 'below', text, color }. A click emits markerClick.
chart.setMarkers([
{ time: bars[bars.length - 40].time, shape: 'arrowUp', position: 'below', text: 'Buy' },
{ time: bars[bars.length - 10].time, shape: 'arrowDown', position: 'above', text: 'Sell', color: '#dc2626' },
]);
chart.on('markerClick', (e) => console.log(e.marker.text));
Replay
Replay plays the history bar by bar: startReplay({ at, time, intervalMs, autoplay }), pauseReplay(), resumeReplay(), stepReplay(n), stopReplay(). Events: replayStart, replayStep, replayFinish, replayStop.
chart.startReplay({ at: bars.length - 100, intervalMs: 200, autoplay: false });
chart.stepReplay(5);
chart.stopReplay();
Series and chart types
Series types
The option seriesType (or setSeriesType(), event seriesTypeChange): 'candlestick' (default), 'ohlc', 'line', 'area', 'baseline' (above / below baseline.value, default the middle of the scale), 'histogram', 'heikinAshi', 'hollowCandles' (hollow when the close is above the open, colored by the previous close), 'volumeCandles' (body width by volume), and the types built from the bars: 'renko', 'kagi', 'pointFigure', 'lineBreak', 'rangeBars'. SERIES_TYPES lists them.
Built chart types
For the built types the x axis is the sequence of their bars (bricks, lines, columns), not time; getData() still returns the time bars. Their parameters are in the option chartTypes (defaults CHART_TYPE_DEFAULTS); a size is 'atr' (the ATR of atrPeriod bars, measured on a full build) or a price amount.
chart.setOptions({ seriesType: 'renko', chartTypes: { renko: { boxSize: 0.5, source: 'close', wicks: true } } });
chart.setChartTypeParams('renko', { boxSize: 'atr', atrPeriod: 10 });
console.log(chart.getChartTypeInfo()); // { type: 'renko', size, percent, params }
const csv = chart.getBarsCSV(); // the displayed bars with direction / boxes
| Option | Type | Default | Description |
|---|---|---|---|
renko | object | { boxSize: 'atr', atrPeriod: 14, source: 'close', wicks: true } | Box size; bricks from the close or from the high / low path ('hl'); wicks. |
kagi | object | { reversal: 'atr', atrPeriod: 14 } | Reversal: 'atr', an amount or a percent string such as '2%'. |
pointFigure | object | { boxSize: 'atr', atrPeriod: 14, reversal: 3, source: 'hl' } | Box size, reversal in boxes, high / low or close. |
lineBreak | object | { lines: 3 } | Number of lines. |
rangeBars | object | { range: 'atr', atrPeriod: 14 } | Range of every bar. |
indicators | string | 'auto' | Bars the indicators use: 'built', 'source' (each built bar shows the value of its time bar) or 'auto' (built bars for the built types, time bars for Heikin Ashi). |
buildChartType(type, bars, params) builds a type without a chart; BUILT_TYPES lists the built types. exportCSV(filename, { source }) downloads the displayed bars (source: true: the time bars).
Indicators
Adding indicators
addIndicator(name, params) returns the id of the instance (null for an unknown name). Overlays are drawn on the price pane, the others get their own pane under it (panes are resized by dragging their borders; event paneResize).
const ma = chart.addIndicator('sma', { period: 50 });
const bb = chart.addIndicator('bollinger', { period: 20, mult: 2 });
const macd = chart.addIndicator('macd');
chart.updateIndicator(ma, { period: 100 }); // keeps its pane
chart.setIndicatorVisible(bb, false);
console.log(chart.getIndicators(), chart.getIndicatorValues(macd)); // { macd, signal, hist } at the last bar
chart.removeIndicator(macd);
Invalid parameter values keep the default. The pane legends show the values at the crosshair (or the last bar) and the price axis shows a badge with the last value of every line (option indicatorLabels: { values, axis }). Events: indicatorAdd, indicatorChange, indicatorRemove.
Built-in indicators
| Group | Indicators (name and default parameters) |
|---|---|
| Moving averages | sma (20), ema (20), wma (20), smma (7), dema (9), tema (9), hma (9), vwma (20), kama (10, fast 2, slow 30), alma (9, offset 0.85, sigma 6) |
| Trend | supertrend (10, factor 3), psar (0.02 / 0.02 / 0.2), ichimoku (9 / 26 / 52 / 26), dmi (14 / 14), adx (14 / 14), aroon (14), vortex (14), trix (18, signal 9) |
| Oscillators | rsi (14), macd (12 / 26 / 9), stochastic (14 / 3 / 3), stochRsi (14 / 14 / 3 / 3), cci (20, 0.015), williamsR (14), roc (9), momentum (10), awesome (5 / 34), ultimate (7 / 14 / 28), cmo (9), ppo (12 / 26 / 9), tsi (25 / 13 / 13) |
| Volatility | bollinger (20, 2), atr (14), keltner (20, 2, ATR 10), donchian (20), envelopes (20, 10 %), stddev (20), bbWidth (20, 2), bbPercentB (20, 2) |
| Volume | volumeMa (20, on the volume pane), obv, adl, mfi (14), cmf (20), chaikinOsc (3 / 10), force (13), vwap |
| Levels and patterns | pivots (type: 'classic', 'fibonacci', 'woodie', 'camarilla'; period: 'auto', '1D', '1W', '1M', '1Y'), zigzag (deviation 5 %), fractals (2) |
The exact parameter names are in indicators[name].params (for example macd: fast, slow, signal); INDICATOR_GROUPS holds the groups above. RSI, ATR, DMI / ADX and SMMA use Wilder smoothing; VWAP and pivots follow the trading days of the sessions when sessions are set. sma, ema, wma and stdev are also exported as functions of an array.
Your own indicators
registerIndicator(definition) adds an indicator to the registry of the page (a definition with the name of a built-in replaces it). compute(bars, params) returns plots: arrays of values aligned with the bars (null for warm-up gaps).
VibeFoxJSTrading.registerIndicator({
name: 'midline',
label: 'Mid line',
pane: 'overlay', // 'overlay' | 'separate' | 'volume'
params: { period: 10 },
compute(bars, p) {
const mid = bars.map((b) => (b.high + b.low) / 2);
return { plots: [{ key: 'mid', values: VibeFoxJSTrading.sma(mid, p.period), color: '#9333ea' }] };
},
});
chart.addIndicator('midline', { period: 30 });
Definition fields: name, label or labelKey, pane, params, levels (dashed guide lines), range (fixed scale), choices (allowed strings of a parameter), compact (K / M / B labels), axisLabels, autoscale, compute or create. A plot has key, values, type ('line', 'histogram', 'step', 'dots', 'marker'), color or colorKey, paletteIndex, tones, offset, connect, width, dashed, label, legend, visible, autoscale; fills ({ from, to, colorKey, downColorKey }) fill between two plots. With create(params) you return an incremental engine { plots, fills, step(bars, i) } that computes bar i from the state after bar i - 1, so live ticks recompute only the last bar.
Drawing tools
Tools
setTool(name) starts a tool (null: the cursor); the user clicks the anchors (or drags), Escape cancels. 48 tools in 9 groups (TOOLS, TOOL_GROUPS):
| Group | Tools |
|---|---|
| Lines | trendline, ray, extendedLine, infoLine, trendAngle, hline, horizontalRay, vline, crossLine |
| Shapes | rect, rotatedRect, ellipse, circle, triangle, polyline, arc, curve, brush, arrow |
| Channels | parallelChannel, regressionChannel, donchianChannel |
| Pitchforks | pitchfork, schiffPitchfork, modSchiffPitchfork, insidePitchfork |
| Gann | gannFan, gannSquare, gannGrid |
| Fibonacci | fib, fibExtension, fibChannel, fibTimeZones, fibFan, fibArcs, fibCircles, fibSpiral |
| Text | text, callout, note, priceLabel, flag, iconMarker |
| Measure | priceRange, dateRange, priceDateRange |
| Positions | longPosition, shortPosition |
A polyline gets a click per anchor (a double click or Enter finishes it, a click on the first anchor closes it); the brush is drawn by dragging; positions take two clicks (entry, then the end time and the target; the stop is mirrored). Text, callout and note open an editor in place (Enter: new line, Ctrl+Enter, Tab or a click outside: save, Escape: cancel). Events: toolChange, drawingComplete.
Drawings from code
A drawing is { id, tool, points: [{ time, price }], … }; anchors are time and price, so drawings survive timeframe changes, zoom and scale modes. Missing properties use the tool default and the CSS variables.
const t0 = bars[bars.length - 120].time, t1 = bars[bars.length - 20].time;
const id = chart.addDrawing({ tool: 'trendline', points: [{ time: t0, price: bars[bars.length - 120].low }, { time: t1, price: bars[bars.length - 20].low }],
color: '#2563eb', lineWidth: 2, extendRight: true });
chart.addDrawing({ tool: 'fib', points: [{ time: t0, price: 95 }, { time: t1, price: 105 }], showLabels: true });
chart.addDrawing({ tool: 'text', points: [{ time: t1, price: 104 }], text: 'Breakout', fontSize: 14, bold: true });
chart.updateDrawing(id, { lineStyle: 'dashed', locked: true });
console.log(chart.getDrawings().length);
chart.undo();
Properties: color, lineWidth, lineStyle ('solid' | 'dashed' | 'dotted'), fill, fillColor, fillOpacity, text, showLabels, levels ([{ value, visible, color }] of Fibonacci, pitchfork and Gann tools), extendLeft, extendRight, locked, hidden, period (Donchian channel), deviation (regression channel), fontSize, bold, italic, border, closed (polyline), icon (iconMarker: 'arrowUp', 'arrowDown', 'circle', 'square', 'diamond', 'triangle', 'star', 'cross', 'check'), and for positions accountSize, risk, riskMode ('percent' | 'amount'), lotSize. null in updateDrawing returns a property to its default.
Editing, selection and undo
A click selects a drawing, Shift / Ctrl+click adds to the selection, a drag moves the selected drawings, the handles move one anchor; a double click (or Enter) opens the properties panel. Methods: getDrawing(id), setDrawings(list), removeDrawing(id), clearDrawings(), selectDrawing(ids), getSelectedDrawings(), copyDrawings(ids), pasteDrawings(), cloneDrawing(id), orderDrawing(id, 'front' | 'back' | 'forward' | 'backward'), showDrawingProperties(id), hideDrawingProperties(), editDrawingText(id), stopTextEdit(). Every action is one undo step: undo(), redo(), canUndo(), canRedo(), clearHistory() (Ctrl+Z, Ctrl+Y). The clipboard is shared by the charts of the page, not the system clipboard.
The magnet snaps anchors to the open, high, low or close of the nearest bar: setMagnet('off' | 'weak' | 'strong'), getMagnet() (MAGNET_MODES); holding Ctrl / Cmd inverts it while drawing. The option drawings: magnet, visible (false hides every drawing), keepTool (stay in the tool), undoLimit (100), properties (the panel), position (defaults of the long / short positions: accountSize 10 000, risk 1, riskMode, lotSize, currency). Events: drawingAdd, drawingSelect, drawingUpdate, drawingRemove, drawingsChange, historyChange, magnetChange, drawingPropertiesOpen, drawingPropertiesClose, drawingTextEdit.
Datafeed
The adapter
With the option datafeed (or setDatafeed()) the chart loads bars from your adapter instead of data: the first page, older history when the user scrolls to the left, live updates, a cache per symbol and timeframe, retries and timeouts. The adapter is any object:
const feed = {
timeframes: ['1m', '1h', '1D'], // optional: served natively; the others are resampled
async getBars({ symbol, timeframe, to, countBack, firstRequest, signal }) {
const res = await fetch(`/api/bars?s=${symbol}&tf=${timeframe}&to=${to}&n=${countBack}`, { signal });
const bars = await res.json(); // up to countBack bars with time < to, oldest first
return { bars, noData: bars.length === 0 };
},
subscribe({ symbol, timeframe }, { onBar, onTick }) { // optional: live data
const ws = new WebSocket(`wss://example.com/${symbol}`);
ws.addEventListener('message', (m) => onTick(JSON.parse(m.data))); // { price, volume, time }
return () => ws.close(); // or a handle for unsubscribe()
},
searchSymbols: async (query) => ['AAPL', 'MSFT'].filter((s) => s.includes(query.toUpperCase())),
};
const live = VibeFoxJSTrading.createTradingChart('#app2', { datafeed: feed, symbol: 'AAPL', timeframe: '1h' });
live.setSymbol('MSFT');
Optional adapter methods: subscribe / unsubscribe, searchSymbols(query, { type, exchange, limit }) (symbol inputs and the symbol search) and getSymbolInfo(symbol) (descriptions in the watchlist). The adapter is kept by reference. Answers of requests that are no longer needed (the symbol changed) are dropped and their signal is aborted.
Loading and errors
datafeedOptions (defaults DATAFEED_DEFAULTS): pageSize (300 bars), prefetch (50: load older history when fewer bars are left of the view), retries (3), retryDelay (500 ms) and retryFactor (2), timeout (0 = none), cache and cacheSize (20 series), periodPages (50), barSpacing (8 px). Methods: getDatafeed(), getSymbol(), reloadData(), loadMoreHistory(), whenLoaded(), getLoadState() ({ loading, loadingHistory, endReached, error, resolution }). Events: symbolChange, dataLoading, dataLoad, dataError (with attempt and final), historyEnd. After the last retry the chart shows "Failed to load data"; reloadData() tries again.
MemoryDatafeed
new MemoryDatafeed(options) is a datafeed over bars in memory for prototypes, demos and tests: seeded random symbols or your bars, any timeframe resampled from baseTimeframe, latency, symbol search and info, pushBar, pushTick, start(ms) / stop() (random ticks), failNext(n).
const memory = new VibeFoxJSTrading.MemoryDatafeed({
symbols: { BTCUSD: { startPrice: 60000, description: 'Bitcoin', type: 'crypto' }, ETHUSD: { startPrice: 3000 } },
latency: [20, 80],
});
const demo = VibeFoxJSTrading.createTradingChart('#app2', { datafeed: memory, symbol: 'BTCUSD', timeframe: '5m' });
await demo.whenLoaded();
memory.start(500); // live ticks
memory.stop();
Symbol comparison
addCompare(symbol, options) draws other symbols as lines over the main series. Without data the datafeed loads them (and keeps them live). The first comparison switches a linear price scale to percent (option compare: { autoPercent, lineWidth }): every series starts at 0 % at the first visible bar.
chart.addCompare('ETH', { data: VibeFoxJSTrading.generateBars({ count: 1000, startPrice: 50, seed: 7 }), color: '#f59e0b' });
chart.addCompare('SPX', { data: VibeFoxJSTrading.generateBars({ count: 1000, startPrice: 4000, seed: 9 }), scale: 'overlay' });
console.log(chart.getCompares());
chart.removeCompare('SPX');
Options: data, color, scale ('overlay': own invisible scale outside percent mode, or 'main'), visible, lineWidth. Methods: setCompareData(symbol, bars), clearCompares(); alignCompare is the join by time they use. Events: compareAdd, compareChange, compareRemove.
Scales, navigation and navigator
Scales and the visible range
The mouse wheel and a drag zoom and pan the time; a drag or the wheel on the price scale zooms the price; a double click resets both. Price scale mode: priceScale: { mode: 'linear' | 'log' | 'percent' } or setPriceScaleMode(). timeScale: rightOffset (6 empty bars at the right), sessionBreaks (lines at the day / session starts), gaps (closed hours as empty space).
chart.setVisibleRange({ from: bars.length - 200, to: bars.length }); // bar indexes
chart.setVisibleTimeRange({ from: bars[bars.length - 300].time, to: bars[bars.length - 1].time });
chart.zoomPrice('main', 1.5); // pane id or pane; factor > 1 zooms in
console.log(chart.getVisibleRange(), chart.isPriceScaleZoomed());
chart.resetScale(); // automatic price scales + all bars
chart.scrollToRealtime();
Methods: fitContent(), scrollToRealtime(), getVisibleRange() ({ from, to, timeFrom, timeTo }), getVisibleTimeRange(), timeToIndex(time), indexToTime(index), zoomPrice(pane, factor, anchorY), resetPriceScale(pane), isPriceScaleZoomed(), resetScale(), setCrosshair({ time, price }). Events: visibleRangeChange, priceScaleChange, crosshairMove. Other display options: volume, watermark, legend, crosshair, priceLine (last price line with a pulsing dot), grid (vertical, horizontal).
Price precision
The option priceFormat: { decimals, tickSize } sets the precision of the prices in the legend, on the last price, crosshair, alert and drawing badges, in alert texts, order and position labels and screen reader texts. Both are null by default (automatic): the precision then comes from trade.tickSize or the tickSize of your broker adapter, otherwise from the data (the most decimals among the prices of the last 300 bars, at least 2; unrounded numbers get decimals by the size of the price: 2 from 1, more below 1). The labels of the price axis keep the precision of their own step.
chart.setOptions({ priceFormat: { tickSize: 0.25 } }); // or { decimals: 5 } for a currency pair
console.log(chart.getPriceFormat()); // { decimals: 2, tickSize: 0.25, source: 'tickSize' }
console.log(chart.formatPrice(101.2)); // '101.20'
getPriceFormat() returns { decimals, tickSize, source }, where source is 'decimals', 'tickSize', 'trade', 'data' or 'default' (no data: 2 decimals); formatPrice(price) formats a price with it.
Navigator and period buttons
navigator: true (or { series: 'area' | 'line', labels }) shows a strip with the whole loaded history under the chart and the visible range as a window you drag and resize. periods: true (or { items, placement: 'auto' | 'toolbar' | 'bottom' }) adds the buttons 1D, 5D, 1M, 3M, 6M, YTD, 1Y, 5Y, All (PERIODS); with a datafeed, older history is loaded until the period is covered.
chart.setOptions({ navigator: true, periods: true });
chart.setPeriod('1M');
console.log(chart.getPeriod(), chart.getPeriods().filter((p) => p.available).map((p) => p.period));
Event: periodChange (null when the range was changed another way).
Volume profile
volumeProfile: { visible: true, bins: 24 } or showVolumeProfile(true) draws the volume by price levels of the visible range with the point of control. computeVolumeProfile(bars, i0, i1, min, max, bins) computes it without a chart.
Time zones and sessions
Times are shown in UTC by default. The option timezone (or setTimezone()): 'UTC', 'local', 'exchange' (the zone of the sessions) or an IANA name such as 'America/New_York'. Daily and longer bars are dates and are never shifted.
The option sessions (or setSessions()) is the trading schedule of the exchange: bars are aggregated from the session start, pre / post market bars are shaded, daily bars come from the regular session, and VWAP and pivots restart by trading day. Give a preset ('crypto', 'nyse', 'moex': SESSION_PRESETS, examples without holidays) or your schedule:
chart.setSessions({
timezone: 'America/New_York',
pre: '0400-0930', regular: '0930-1600', post: '1600-2000',
days: [1, 2, 3, 4, 5],
holidays: ['2026-12-25'],
special: { '2026-11-27': { regular: '0930-1300', post: null } },
extended: true, highlight: true, dailyBars: 'regular',
});
chart.setTimezone('exchange');
console.log(chart.getTimezoneInfo(), chart.getSessionInfo(Date.now()));
A part is 'HHMM-HHMM' (several separated by commas) or a map by weekday (0 = Sunday); a session whose end is not after its start runs over midnight into the next trading day. Fields: preset, timezone, regular, pre, post, days, holidays, special, extended (show pre / post bars), highlight, dailyBars ('regular' | 'all'). Methods: getTimezone(), getSessions(), getSessionInfo(time) ({ kind: 'pre' | 'regular' | 'post' | null, tradingDay, start, end }). Events: timezoneChange, sessionsChange.
Alerts
An alert watches the price, the volume or an indicator and compares it with a number, an indicator, a drawing or a channel. It is checked on every tick and bar of the chart in the page.
const sma = chart.addIndicator('sma', { period: 20 });
chart.addAlert(105.5, { label: 'Resistance' }); // price line, fires on every cross
chart.addAlert({ source: 'price', condition: 'crossingUp', target: { indicator: sma }, frequency: 'oncePerBar',
message: '{symbol}: price crossed SMA at {price}', sound: true });
chart.addAlert({ source: 'volume', condition: 'above', value: 5000, frequency: 'oncePerBarClose' });
chart.on('alertTrigger', (e) => console.log(e.message, e.payload));
console.log(chart.getAlerts().map((a) => chart.describeAlert(a.id)));
| Field | Values |
|---|---|
source | 'price' (default, the last trade price), 'volume', { indicator: id, plot } |
condition | 'crossing', 'crossingUp', 'crossingDown', 'above', 'below'; with a channel 'entering', 'exiting', 'inside', 'outside' (ALERT_CONDITIONS) |
value / target | A number, { indicator, plot } or { drawing: id, level } (lines, horizontal lines, parallel channels, rectangles, price ranges, Fibonacci retracement and extension: ALERT_TOOLS) |
lower, upper / channel | Two numbers, an indicator with upper / lower lines ({ indicator }: Bollinger, Keltner, Donchian, Envelopes) or { drawing, levels } |
frequency | 'once' (default), 'oncePerBar', 'oncePerBarClose', 'everyTime' (ALERT_FREQUENCIES) |
expires | A time in ms or a Date |
sound, notify | A generated tone (true or { frequency, duration, volume, type, repeat }); a browser notification |
message, label, color, enabled | Template with {symbol}, {timeframe}, {name}, {price}, {value}, {target}, {direction}, {condition}, {alert}, {time}; name; line color; on / off |
The option alerts (defaults ALERTS_DEFAULTS): sound (default tone of every alert), notifications (allow browser notifications; ask with requestAlertNotifications() from a user action), onTrigger(alert, payload) and announce (read out). The payload is JSON-safe; the library sends nothing itself — post it to your webhook in onTrigger:
chart.setOptions({ alerts: { onTrigger: (alert, payload) =>
fetch('/api/alert-hook', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }) } });
Methods: updateAlert(id, patch), removeAlert(id), clearAlerts(), getAlert(id), openAlertDialog(values) (Alt+A on the focused chart), openAlertsDialog() (the list: stop / resume, edit, remove). Events: alertAdd, alertChange, alertTrigger, alertExpire, alertRemove.
Terminal UI
The chart has its own ready-made UI; every part is off by default and needs no other library.
chart.setOptions({
toolbar: { items: ['symbol', 'timeframes', 'seriesType', '|', 'indicators', 'compare', 'alerts', '-', 'settings', 'snapshot', 'fullscreen'],
favorites: ['5m', '1h', '1D'], symbols: ['BTCUSD', 'ETHUSD'], variant: 'outline', size: 's' },
drawingToolbar: { tools: ['trendline', 'hline', 'rect', 'fib', 'text'] },
});
chart.openIndicatorsDialog();
chart.closeDialogs();
toolbar(trueor{ items, favorites, symbols, variant, size }): items'symbol','timeframes','seriesType','indicators','compare','alerts','undo','redo','settings','snapshot','fullscreen','periods','watchlist','trade','dom','|'(separator),'-'(spacer);TOOLBAR_ITEMSis the default list.drawingToolbar(trueor{ tools, variant, size }): the drawing tools by group, magnet, stay in drawing mode, lock / hide / remove all.dialogs: the indicators dialog (search, groups, favorites, parameters, show / hide) and the settings dialog (style and theme, colors, scales, grid and watermark, chart type).null(default): with the toolbar;true: by API only;{ favorites }: favorite indicators.variant:'ghost'(default),'outline','filled';size:'s','m'(default),'l'.
Methods: openIndicatorsDialog(), openSettingsDialog(tab) ('style', 'colors', 'scales', 'grid', 'series'), closeDialogs(), toggleFullscreen(on), isFullscreen(), getFavorites(), setFavorites({ timeframes, indicators }). Events: dialogOpen, dialogClose, favoritesChange, fullscreenChange, snapshot. The favorites are part of the state (the page saves getState()).
Watchlist and symbol search
watchlist: true (or options) adds a panel with symbols, the last price, the change and a sparkline; a click switches the chart. With a datafeed the quotes come from its bars (one live feed per symbol); without one, give them with updateWatchlist().
chart.setOptions({ watchlist: {
groups: [{ title: 'Crypto', symbols: ['BTCUSD', 'ETHUSD'] }, { title: 'Stocks', symbols: ['AAPL', 'MSFT'] }],
columns: ['last', 'changePct', 'spark'], timeframe: '1D',
} });
chart.updateWatchlist('AAPL', { last: 231.4, prev: 229.9, spark: [228, 229, 231, 230, 231.4], description: 'Apple' });
chart.addToWatchlist('TSLA', 'Stocks');
chart.on('watchlistSelect', (e) => console.log(e.symbol));
Options: symbols or groups ({ id, title, symbols, collapsed }), columns (WATCHLIST_COLUMNS: 'last', 'change', 'changePct', 'spark'), timeframe, sparkline: { bars }, sort ({ key, dir }), visible, editable, title. Rows are reordered by dragging or Alt+arrows and removed with Delete. Methods: getWatchlist(), setWatchlist(config), removeFromWatchlist(symbol), getWatchlistQuotes(), toggleWatchlist(on). Event: watchlistChange.
symbolSearch: true (or { symbols, types, exchanges, recent, storageKey, limit, debounce, allowAny }) adds a search dialog: the toolbar symbol button, openSymbolSearch({ query }) or typing a letter on the focused chart opens it. Results come from datafeed.searchSymbols() or from the given symbols, with type / exchange filters and recent symbols (kept in the state; in localStorage only under your own storageKey). Event: symbolSearch.
Several charts and synchronization
createTradingLayout(target, options) shows several charts in a grid with one datafeed and synchronization; a click in a chart makes it active (and the layout watchlist switches the active chart).
const layout = VibeFoxJSTrading.createTradingLayout('#app2', {
layout: '4', // '1' '2' '2v' '3' '3v' '4' '6' '8'
datafeed: new VibeFoxJSTrading.MemoryDatafeed({ symbols: ['BTCUSD', 'ETHUSD'] }),
chart: { symbol: 'BTCUSD', toolbar: true }, // options of every chart
charts: [{ timeframe: '1m' }, { timeframe: '5m' }, { timeframe: '1h' }, { symbol: 'ETHUSD' }],
sync: { crosshair: true, symbol: false, timeframe: false, range: false, drawings: true },
});
layout.getActiveChart().addIndicator('rsi');
layout.setLayout('2');
Layout methods: setLayout(), getLayout(), getCharts(), getChart(index), getActiveChart(), getActive(), setActive(index), setSync(), getSync(), getWatchlist(), setWatchlist(), getState(), setState(). Events: layoutChange, activeChange, watchlistChange, watchlistSelect. A smaller layout keeps the states of the removed charts and gives them back when it grows again. LAYOUTS gives the columns and rows of each layout.
Any charts of the page can be synchronized without a layout: syncCharts(charts, { crosshair, symbol, timeframe, range, drawings }) returns a group with add(), remove(), set(), get(), destroy() (defaults SYNC_DEFAULTS: the crosshair only). Charts of other timeframes follow the crosshair by time; drawings go to the charts of the same symbol.
const second = VibeFoxJSTrading.createTradingChart('#app2', { data: bars, timeframe: '15m' });
const group = VibeFoxJSTrading.syncCharts([chart, second], { crosshair: true, range: true });
group.set({ timeframe: true });
group.destroy();
Trading from the chart
Broker adapter
The option trade shows your orders and positions on the chart and lets users place and change orders. The library never executes anything: every request goes to your broker adapter (trade.broker or setBroker()) or to a listener of the request event. All adapter methods are optional and may return promises.
const broker = {
async placeOrder(order) { const r = await fetch('/api/orders', { method: 'POST', body: JSON.stringify(order) }); return r.json(); },
async modifyOrder(id, changes) { return changes; },
async cancelOrder(id) { return { status: 'cancelled' }; },
async closePosition(id, { quantity }) { return { quantity: 0 }; },
subscribe({ onOrders, onPositions, onOrder, onPosition, onExecution }, { symbol }) { /* push live updates */ return () => {}; },
};
chart.setOptions({ trade: { broker, quantity: 10, tickSize: 0.01, pointValue: 1, currency: 'USD', confirm: { cancel: true, close: true } } });
chart.setPositions([{ id: 'p1', side: 'long', quantity: 10, avgPrice: 100, sl: 98, tp: 106 }]);
chart.setOrders([{ id: 'o1', side: 'buy', type: 'limit', price: 99.5, quantity: 5 }]);
Adapter methods: placeOrder(order), modifyOrder(id, changes, order), cancelOrder(id, order), closePosition(id, { quantity }, position), reversePosition(id, position), modifyPosition(id, { sl, tp }, position), getOrders(), getPositions(), subscribe(handlers, { symbol }) / unsubscribe, subscribeDepth(symbol, onDepth) / unsubscribeDepth, tickSize. An answer object is merged into the order, a string is its new id. An order is { id, symbol, side: 'buy' | 'sell', type: 'market' | 'limit' | 'stop' | 'stopLimit', quantity, price, stopPrice, tif: 'GTC' | 'DAY' | 'IOC' | 'FOK', sl, tp, status, label } (ORDER_TYPES, ORDER_TIFS); a position is { id, symbol, side: 'long' | 'short', quantity, avgPrice, sl, tp }.
On the chart
Order lines, their stop loss / take profit lines and position lines with live P&L are drawn on the price pane. Users drag a line to modify it (snapped to the tick: trade.tickSize, the tickSize of the broker adapter, otherwise the step of the price precision, see Price precision), drag the position line to set its stop loss or take profit, use the × and reverse buttons of the labels and edit the quantity in place; with the keyboard, Tab selects the lines on the focused chart. The order ticket (openOrderTicket({ side, type, price, quantity, sl, tp, tif, orderId }), toolbar item 'trade') checks the input and shows the risk, reward and R:R. The depth-of-market ladder (trade.dom, toggleDom(), toolbar item 'dom') shows bid / ask sizes from setDepth() or broker.subscribeDepth; a click on the bid / ask side places an order at that price.
chart.setOptions({ trade: { broker } }); // the adapter above
const order = await chart.placeOrder({ side: 'buy', type: 'limit', price: 99, quantity: 3, sl: 97, tp: 104 });
await chart.modifyOrder(order.id, { price: 98.5 });
await chart.cancelOrder(order.id);
chart.setDepth({ bids: [[99.9, 120], [99.8, 300]], asks: [[100.1, 80], [100.2, 250]] });
console.log(chart.getPositions(), chart.getPnl());
Requests from code are not confirmed; UI actions ask first when trade.confirm is true or names the action (place, modify, cancel, close, reverse, protect). Before the broker, the events orderPlace, orderModify, orderCancel, positionClose, positionReverse and positionModify let you answer a request yourself or cancel it:
chart.on('orderPlace', (req) => {
if (req.order.quantity > 100) return req.preventDefault(); // not sent
req.respondWith(fetch('/api/orders', { method: 'POST', body: JSON.stringify(req.order) }).then((r) => r.json()));
});
chart.on('orderReject', (e) => console.warn(e.action, e.error));
Options of trade (defaults TRADE_DEFAULTS): broker, quantity (1), qtyStep (1), tickSize (also the price precision of the chart when priceFormat is not set), pointValue (1), currency, accountSize, confirm (false), orders, positions, ticket (true), dom (false or { levels }), types, tifs, pnl ('money', 'ticks', 'percent'). Other methods: getBroker(), updateOrder(), updatePosition(), getOrders(), closePosition(), reversePosition(), modifyPosition(), getDepth(), closeOrderTicket(). Events: ordersChange, positionsChange, execution, depthChange, domToggle, orderReject.
MockBroker
new MockBroker({ latency, tickSize, depthLevels, seed, prices, symbol }) is a broker in memory for prototypes and tests: it fills orders against the prices you give (setPrice(symbol, price)) or the last price of a chart (attach(chart)), nets positions, closes them at their stop loss / take profit and makes a depth of market; rejectNext(n, message) tests errors.
const mock = new VibeFoxJSTrading.MockBroker({ latency: 50 }).attach(chart);
chart.setOptions({ trade: { broker: mock, dom: true } });
await chart.placeOrder({ side: 'buy', type: 'market', quantity: 2 });
console.log(chart.getPositions());
Backtests and strategies
A strategy
A strategy is plain JavaScript: a function onBar(ctx) or an object { name, params, indicators, init(ctx), onBar(ctx) }. It runs on every closed bar and sees only that bar and older ones (indicator values are point in time). backtest(bars, strategy, options) runs it without a chart (also in Node); setStrategy(strategy, options) runs it on the bars of a chart and draws the trades, the equity and the drawdown.
const smaCross = {
name: 'SMA cross',
params: { fast: 10, slow: 30 },
indicators: (p) => ({ fast: ['sma', { period: p.fast }], slow: ['sma', { period: p.slow }] }),
onBar(ctx) {
if (ctx.crossover('fast', 'slow')) ctx.buy({ percent: 50, slOffset: 2 });
else if (ctx.crossunder('fast', 'slow')) ctx.sell({ percent: 50 });
},
};
const result = VibeFoxJSTrading.backtest(bars, smaCross, { capital: 10000, commission: 0.05, slippage: 0.01 });
console.log(result.summary.netProfit, result.summary.winRate, result.trades.length);
chart.setStrategy(smaCross, { capital: 10000, markers: true, equity: true, drawdown: true });
chart.showBacktestReport('summary');
The context: index, time, bar, params, state (your data between bars), ind (indicator values of the bar by key; the other lines of an indicator as "key.plot"), position, equity, cash, orders, ago(n), src(field, n), value(key, n), crossover(a, b), crossunder(a, b), highest(key, n), lowest(key, n); actions buy(order), sell(order), close(order), order(order), cancel(id), cancelAll(), protect({ sl, tp }). An order: type ('market', 'limit' with price, 'stop' with stopPrice), size (qty, risk = percent of the equity lost at the stop, percent = percent of the equity in value, else the option size), sl / tp or slOffset / tpOffset, id, label.
Options and results
Backtest options (BACKTEST_DEFAULTS): capital (10 000), commission (percent, or { percent, perUnit, perOrder }), slippage (price units, or { price, percent }), size ({ type: 'qty' | 'percent' | 'risk', value }), qtyStep, pointValue, pyramiding (1), shorts (true), fill ('nextOpen' or 'close'), closeAtEnd, periodsPerYear, riskFree, params. Market orders fill at the next open; limit, stop, stop loss and take profit orders fill along the path open → nearer extreme → other extreme → close.
The result has summary (net profit, gross profit / loss, profit factor, trades, win rate, average trade, payoff, largest win / loss, consecutive wins / losses, max drawdown, Sharpe, Sortino, CAGR, Calmar, exposure, commission, buy and hold, long / short), monthly, trades (with MFE / MAE), fills, per-bar equity, drawdown, drawdownPct, position, time, and error when the strategy threw. exportBacktest(result, 'csv' | 'json', part) exports it (part: 'all', 'trades', 'report', 'monthly', 'equity').
On the chart: getStrategy(), getBacktest(), getTrades(), exportBacktest(format, { part, filename, download }), showBacktestReport(tab), hideBacktestReport(); the strategy runs again after every data change. Strategy options (STRATEGY_DEFAULTS): the backtest options and equity, drawdown, markers, labels, live, signals. Events: strategyChange, backtest, strategyTrade.
Live signals
With live: true the strategy runs on the live bars and emits signal for every action. signals: { alerts: true } turns them into alert outputs (the alerts.onTrigger hook, tone, notification); signals: { trade: true } sends them as orders to the broker adapter of the option trade.
chart.setStrategy(smaCross, { live: true, signals: { alerts: true } });
chart.on('signal', (s) => console.log(s.action, s.side, s.qty, s.close));
chart.setStrategy(null); // remove it
Parameter search
optimizeStrategy(bars, strategy, options) (or the chart method optimizeStrategy(strategy, options); null = the strategy on the chart) runs every combination of the parameters (paramGrid(spec)) in Web Workers and sorts the results by a metric.
const best = await chart.optimizeStrategy(smaCross, {
params: { fast: [5, 10, 15], slow: { from: 20, to: 60, step: 20 } },
metric: 'netProfit', top: 5,
onProgress: (p) => console.log(p.done, '/', p.total),
});
console.log(best.best.params, best.mode, best.runs);
Options (OPTIMIZE_DEFAULTS): the backtest options and params (a list, { from, to, step } or one value per key), metric (a summary key or a function), maximize, top, maxRuns (10 000), worker, workers, onProgress, signal (an AbortSignal). A strategy that cannot run alone in a worker (it reads variables outside its functions) runs on the page thread; mode and reason of the result tell which. Event: optimizeProgress.
Export
chart.exportPNG('chart.png'); // title strip, all layers, OHLCV legend
const canvas = chart.getImage({ title: 'BTC / USD', subtitle: false, legend: true });
chart.exportCSV('bars.csv'); // the displayed bars
const json = chart.exportBacktest('json', { part: 'trades', download: false });
Image options: title and subtitle (true, your text or false), legend. The toolbar item 'snapshot' downloads the same image.
Rendering and large data
The chart draws on canvas. Bars thinner than a pixel are drawn once per pixel column, so 100 000 bars stay fast, and indicators update only the last bar on a tick. The option renderer (RENDERERS): 'auto' (default: WebGL from webgl.minBars bars on screen, 5000, on a GPU), 'canvas' or 'webgl'. WebGL draws the main series, the volume and one indicator histogram per pane; everything else stays canvas 2D, and the picture and the PNG export are the same. Without WebGL or after a lost context the chart draws with canvas 2D.
chart.setRenderer('webgl');
console.log(chart.getRenderer(), chart.getRenderInfo().reason); // also right after creating
chart.on('rendererChange', (e) => console.log(e.renderer, e.reason));
getRenderer() and getRenderInfo() are correct right after createTradingChart() and after setOptions(): a frame that is due is drawn first, so there is no need to wait for the first frame.
The option webgl (WEBGL_DEFAULTS): minBars, software (true allows 'auto' on a software WebGL without a GPU, which is slower than canvas 2D). requestRender() schedules a repaint.
Touch
One finger pans, two fingers zoom the time (on the price scale: the price), a drag on a scale zooms that scale. The option touch: longPress (500 ms: a crosshair that follows the finger and the event contextMenu; 0 or false turns it off), doubleTap (resets the scales; on a drawing: its properties), inertia (kinetic scrolling, never with reduced motion), loupe (a magnifier above the finger while drawing). A right click emits contextMenu ({ x, y, pointerType, index, time, price, paneId, drawingId, order, position }) only when you listen to it; otherwise the browser menu opens.
Theming and styling
Themes
Every VibeFox JS component has the themes light (default), dark and high-contrast built into its CSS file. The optional vibefox-js-themes.css adds the theme pack: high-contrast-light, paper, paper-dark, glass, glass-dark, classic, classic-dark, ocean, ocean-dark, forest, forest-dark, sunset, sunset-dark, graphite, graphite-dark. The same file works for every VibeFox JS library.
VibeFoxJSTrading.setTheme('dark'); // the whole page
VibeFoxJSTrading.setTheme('ocean', '#sidebar'); // every component inside a container
chart.setTheme('glass'); // one component (also: the theme option)
chart.setTheme(null); // follow the page / container again
A component without its own theme follows the nearest container with a theme, then the page. After setTheme(name, container) the theme variables are set on the container itself too, so your CSS of the container can use them (#sidebar { background: var(--vfjs-bg); }). Your own theme: registerTheme(name, vars) with the theme variables (bg, fg, border, accent, accent-fg, muted, surface, radius, font, shadow, palette-0 … palette-9 and any other token); it applies at once to every component that uses it. getTheme() returns the page theme, themes lists the registered ones; the event themeChange reports a switch.
VibeFoxJSTrading.registerTheme('brand', { accent: '#e11d48', 'accent-fg': '#ffffff', radius: '10px' });
chart.setTheme('brand');
CSS variables
Every color, size, spacing, font, radius, shadow and duration of VibeFox JS Trading is a CSS variable, so any setting is changed in one place. There are three levels:
- theme variables shared by all VibeFox JS components:
--vfjs-bg,--vfjs-fg,--vfjs-border,--vfjs-accent,--vfjs-accent-fg,--vfjs-muted,--vfjs-surface,--vfjs-radius,--vfjs-font,--vfjs-shadow,--vfjs-palette-0…--vfjs-palette-9; - design tokens: spacing
--vfjs-space-1…--vfjs-space-8, font sizes--vfjs-font-size,--vfjs-font-size-smand others, radii--vfjs-radius-sm…, status colors--vfjs-danger,--vfjs-success,--vfjs-warning,--vfjs-info, the scale--vfjs-size-unit, durations--vfjs-motion-duration, the focus ring--vfjs-focus-ring-colorand--vfjs-focus-ring-width; - variables of the library,
--vfjs-trading-*, which default to the tokens above.
/* all VibeFox JS components of the page */
.vfjs { --vfjs-accent: #0f766e; --vfjs-radius: 4px; }
/* only this chart */
#prices {
--vfjs-trading-candle-up: #16a34a;
--vfjs-trading-candle-down: #dc2626;
--vfjs-trading-grid: transparent;
}
Main groups of the chart variables (about 360, all start with --vfjs-trading-): base (--vfjs-trading-bg, --vfjs-trading-fg, --vfjs-trading-muted, --vfjs-trading-accent, --vfjs-trading-font, --vfjs-trading-font-size), candles and bars (--vfjs-trading-up, --vfjs-trading-down, --vfjs-trading-candle-up, --vfjs-trading-candle-down, --vfjs-trading-wick-up, --vfjs-trading-candle-border-up, --vfjs-trading-ohlc-up, --vfjs-trading-hollow-up, --vfjs-trading-kagi-yang, --vfjs-trading-pf-x), series (--vfjs-trading-line, --vfjs-trading-area-fill, --vfjs-trading-baseline-up, --vfjs-trading-volume-up), grid and scales (--vfjs-trading-grid, --vfjs-trading-axis-text, --vfjs-trading-axis-bg, --vfjs-trading-axis-width, --vfjs-trading-crosshair), indicators (--vfjs-trading-palette-1 … --vfjs-trading-palette-6, --vfjs-trading-ind-up, --vfjs-trading-cloud-up, --vfjs-trading-band-fill), comparison (--vfjs-trading-compare-1 …), drawings (--vfjs-trading-drawing, --vfjs-trading-draw-line-width, --vfjs-trading-fib-1 …), alerts (--vfjs-trading-alert), trading (--vfjs-trading-order-buy, --vfjs-trading-order-sell, --vfjs-trading-position, --vfjs-trading-pnl-up), backtests (--vfjs-trading-bt-equity, --vfjs-trading-bt-drawdown), UI (--vfjs-trading-ui-*), navigator (--vfjs-trading-nav-*), watchlist (--vfjs-trading-wl-*), ladder (--vfjs-trading-dom-*), layout (--vfjs-trading-layout-*). The canvas redraws when a variable changes.
From JavaScript: setColors(map) sets colors on the chart element by canvas color key (candleUp, grid, …) or by variable name ({ '--vfjs-trading-candle-up': '#16a34a' }); null removes one, setColors(null) removes all; getColors() returns them (they are part of the state, event colorsChange). The settings dialog uses the same method.
Where to set them: on :root, on any container of your page (#checkout { --vfjs-accent: #0f766e; }), on the element of the component, or in a theme (registerTheme). The closest value wins; a component with its own theme (the option theme or component.setTheme(name)) keeps the theme variables of that theme even inside a container that sets them. A container inside another component (a form inside a dialog or a card) passes the variables of the library to the components in it as well. Only the shared design tokens (--vfjs-space, --vfjs-danger, --vfjs-selected-bg …) do not pass there: set them on a container outside the outer component or on the nested components themselves (#form .vfjs { … }). The variables of the toolbars --vfjs-trading-ui-btn-bg, --vfjs-trading-ui-btn-border, --vfjs-trading-ui-btn-h, --vfjs-trading-ui-font-size and --vfjs-trading-ui-icon-size are computed on each toolbar: set them on the element of the chart. Popups, menus and dialogs placed in <body> take the values set on the page (:root), not those of the container of their component.
Default values: the theme variables are registered with @property (their initial value is the light theme), so they have a value on every element of the page. The variables of the library (--vfjs-trading-*) keep their defaults inside the stylesheet, at the place where they are used, so a variable that you did not set has no value on your elements:
- in your own CSS that uses a variable of the library, give it a fallback as the library does:
var(--vfjs-trading-bg, var(--vfjs-bg)), or use a theme variable directly; - from JavaScript, read the current value with
cssVar(element, '--vfjs-trading-font-size')(exported by the library; it also returns the default value the component computes);getComputedStyle(element).getPropertyValue()can return an empty string for a variable of the library that nobody set.
/* your own element in the colors of the component */
.my-summary { background: var(--vfjs-trading-bg, var(--vfjs-bg)); color: var(--vfjs-fg); }
const el = document.querySelector('#orders');
console.log(VibeFoxJSTrading.cssVar(el, '--vfjs-trading-font-size')); // the value in use (also a default)
console.log(getComputedStyle(el).getPropertyValue('--vfjs-trading-font-size')); // can be '' unless you set it
If the CSS file of the library comes from another origin without CORS (a <link> without the crossorigin attribute), the browser does not let scripts read the stylesheet, and cssVar() returns an empty string for a variable without a value on the root of the component. From your own origin, or with that attribute, it works.
The stylesheets are written with native CSS nesting; nothing changes for including them, and your own CSS can be written in any form.
Ready-made styles
The option style (the prop variant in the framework wrappers) picks a ready-made look.
| Style | Look |
|---|---|
'classic' | Green / red candles, wicks and frames in the text color, solid grid; follows the theme. |
'terminal' | Always dark: near-black background, amber text, monospaced font, hollow green up candles and filled red down candles. |
'monochrome' | Text color only: hollow up candles, filled down candles, gray palette; follows the theme. |
'light' | Always light: white background, pale bodies with saturated wicks and frames, soft grid. |
chart.setStyle('terminal'); // or the option style: 'terminal'
chart.getStyle(); // 'terminal'
chart.setStyle(null); // the default look
TRADING_STYLES lists the names; setStyle emits styleChange. The style can also be the attribute data-vfjs-trading-style on the chart element or the class vfjs-trading-style-<name> on the chart or any container. Any other name uses your own CSS for that class (set the --vfjs-trading-* variables in it).
.vfjs-trading-style-brand { --vfjs-trading-up: #0a7cff; --vfjs-trading-down: #ff7a00; }
chart.setStyle('brand'); // your own style: the class vfjs-trading-style-brand
Density and size
Set data-vfjs-density="compact", "normal" or "comfortable" on the page or on any container: heights and paddings of every VibeFox JS component inside follow. --vfjs-size-unit (default 1px) scales all sizes of a component at once, for example #orders { --vfjs-size-unit: 1.25px; }. Sizes you give as numbers in options are pixels and are not scaled.
Default height: when the element of the component has no height of its own, it gets the class vfjs-auto-height and a default height from the variable --vfjs-trading-min-height (the chart and the layout; 400 px × --vfjs-size-unit). An element with a height of its own (height, only a min-height, a flex item or a CSS Grid item, height: 100% of a parent with a height, absolute insets) gets the class vfjs-fit and is filled exactly, also when it is smaller; the content never makes it taller. With the variable at 0 (class vfjs-content-height) the height follows the width: --vfjs-trading-aspect-ratio (default: the token --vfjs-aspect-ratio, 2 / 1).
Your own CSS
All library rules are inside the cascade layer @layer vfjs, so your own CSS always wins without !important. The class names of VibeFox JS Trading start with vfjs-trading- (state classes too, for example vfjs-trading-is-up), so other CSS frameworks on the page do not restyle it.
.vfjs-trading-legend { font-size: 13px; }
.vfjs-trading-ui-btn.vfjs-trading-is-on { font-weight: 600; }
The library ships no font files. It uses the system font stacks of the tokens --vfjs-font, --vfjs-font-mono and --vfjs-font-serif; set them to your own fonts if you want. Animations follow prefers-reduced-motion, and colors follow forced-colors mode (Windows high contrast).
The size unit scales the canvas too: axis widths, fonts, line widths, markers and drawing handles follow --vfjs-size-unit and the density.
Localization and RTL
Languages
VibeFox JS Trading comes with 14 interface languages. English (en) is built into the library file; each of the others is a language file of its own (dist/locales/vibefox-js-trading.<lang>.js in the package), and a page loads only the ones it uses: Russian (ru), Spanish (es), German (de), French (fr), Italian (it), Portuguese (Brazilian) (pt), Ukrainian (uk), Turkish (tr), Chinese (Simplified) (zh), Japanese (ja), Korean (ko), Hindi (hi) and Arabic (ar). The locale option sets the language of one component; setLocale(lang) sets the default language of the page, which every component without its own locale follows (it re-renders on a change).
VibeFoxJSTrading.setLocale('ru'); // page default
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, locale: 'en' }); // this chart only
chart.setOptions({ locale: 'de' });
The example above needs the files of the languages it uses. With script tags, load a language file after the library. The order matters: loaded first, the file adds no language and writes a warning to the console.
<link rel="stylesheet" href="vibefox-js-trading.css">
<script src="vibefox-js-trading.global.min.js"></script>
<script src="locales/vibefox-js-trading.ru.js"></script>
With npm or a bundler, import the language after the library. Without npm, an ES module page imports ./locales/vibefox-js-trading.ru.esm.js, which registers the language in vibefox-js-trading.esm.js.
import { createTradingChart } from '@vibefox/js-trading';
import '@vibefox/js-trading/locales/ru';
The .esm.js language file does not fit the minified build @vibefox/js-trading/min (it would load a second copy of the library). There, use the .json file:
import { createTradingChart, addLocale } from '@vibefox/js-trading/min';
import ru from '@vibefox/js-trading/locales/ru.json';
addLocale('ru', ru);
Without its file, locale: 'ru' shows English and writes one warning to the console.
Language codes: uk, ko, zh and pt are the real codes; ua and kr also work, as aliases of uk and ko. For each string the library tries the exact code, then the alias, the base language (pt-BR → pt, zh-CN → zh), English, and finally the key itself. normalizeLocale(code) returns the real code of an alias.
A language does not set the direction: with locale: 'ar', also set rtl: true or dir="rtl" on the container.
Adding a language
addLocale(lang, dictionary) adds strings to a language (and creates it): a language of your own, or your own wording over a language file. A missing key follows the chain above, so a partial dictionary works; addLocale('ua', …) fills uk. Add the dictionary before the components that use it are created, or switch the locale afterwards.
VibeFoxJSTrading.addLocale('de', {
'trading.noData': 'Keine Daten',
'trading.goToRealtime': 'Zu den neuesten Kursen',
});
The keys of VibeFox JS Trading start with trading. (about 680 keys: the legend, the toolbars and dialogs, indicator names trading.indicator.<name>, tool names trading.tool.<name>, alerts, trading, the backtest report, screen reader texts). The language files list every key (locales/vibefox-js-trading.ru.json); the English texts are in the readable file vibefox-js-trading.esm.js. Placeholders in braces, such as {price}, are filled in by the library. t(key, params) translates a key in the page locale, chart.t(key) in the chart's locale; getLocale() returns the page locale, onLocaleChange(fn) reports changes.
Plural forms: a text with a number has the keys <key>.zero, .one, .two, .few, .many and .other (the categories of Intl.PluralRules); .other is the fallback, so your dictionary can give only that form. {count} and {n} are filled in. tPlural(key, count, params, lang) picks the form; the method chart.tPlural(key, count, params) does it in the locale of the component.
VibeFoxJSTrading.addLocale('de', {
'trading.a11y.zoom.other': '{n} Balken angezeigt',
});
VibeFoxJSTrading.tPlural('trading.a11y.zoom', 5, {}, 'de'); // '5 Balken angezeigt'
Month names of the time axis are the key trading.monthsShort (a comma-separated list); times follow the chart time zone (see Time zones and sessions).
Right-to-left
The option rtl: true lays the component out right-to-left (dir="rtl" on its element); rtl: false forces left-to-right; without it the component follows the page or its container (<html dir="rtl">). The arrow keys follow the reading order. isRtl(element) tells the direction of an element.
In VibeFox JS Trading the chart itself is not mirrored: time runs left to right and the price scale stays on the right, as in trading terminals. The UI around it follows the direction: the drawing toolbar is at the start side (right), the watchlist and the ladder at the end side, menus and dialogs are mirrored. A text drawing in a right-to-left language is right-aligned and grows to the left of its anchor.
Accessibility
The chart is one tab stop with a keyboard bar cursor; screen readers get a summary of the chart (symbol, timeframe, visible period, trend, range, last price) and hear the bar under the cursor with its prices, change, volume and indicator values. Focus is visible (the focus ring is the CSS variables --vfjs-focus-ring-color, --vfjs-focus-ring-width, --vfjs-focus-ring-offset, --vfjs-focus-ring-style; for this library also --vfjs-trading-focus-ring-color); dialogs keep the focus inside and give it back when they close. The high-contrast and high-contrast-light themes, forced-colors mode and prefers-reduced-motion (no kinetic scrolling, no pulsing dot) are supported. Texts on the colored price badges switch to black or white when their color does not reach the contrast of a11y.contrast.
Keyboard
On macOS, Cmd works where Ctrl is listed. The keys of the drawings come first when a drawing is selected.
| Keys | Action |
|---|---|
| ← → | Bar cursor one bar back / forward (Shift: 10 bars); the bar is read out. |
| Home, End | First / last bar. |
| PageUp, PageDown | One view back / forward. |
| ↑ ↓ | Zoom in / out. |
| Esc | Leave the bar cursor; cancel a drawing; clear the selection. |
| Alt+S | Read the chart summary. |
| Alt+A | Alert dialog (a selected drawing becomes the target). |
| A letter or digit | Symbol search (option symbolSearch). |
| ] , [ | Next / previous drawing. |
| Arrows (drawing selected) | Move it by a bar / a pixel (Shift: 10). |
| Enter, Shift+Enter (drawing) | Properties panel; on a text drawing Enter edits the text. |
| Delete, Backspace (drawing) | Remove it. |
| Ctrl+Z, Ctrl+Y, Ctrl+Shift+Z | Undo / redo of the drawings. |
| Ctrl+C, Ctrl+X, Ctrl+V | Copy, cut, paste drawings. |
| Ctrl+], Ctrl+[ (+Shift) | Bring forward / send backward (to the front / back). |
Tab, Shift+Tab, ← → (option trade) | Select the order and position lines. |
| ↑ ↓, Enter, Esc, Delete (line selected) | Move the price by a tick (Shift: 10), send the change, drop it, cancel the order / close the position. |
| Arrows, Home, End (toolbars) | Move between the buttons; F marks a favorite in menus and the indicators dialog. |
| Arrows, PageUp, PageDown, Home, End, + / − (navigator) | Move or resize the visible window. |
| Arrows, Alt+↑ / Alt+↓, Delete, Enter (watchlist) | Move between rows, reorder, remove, show the symbol. |
| Arrows, PageUp, PageDown, Home, Enter, Space, Delete, Alt+↑ / Alt+↓ (ladder) | Move, place an order or open the ticket, cancel the orders of a level, move them a tick. |
Screen readers
The chart element has the role application with the description "trading chart"; aria-describedby points to the hidden summary and the key help (or the selected drawing). Toolbars are toolbars with one tab stop, menus menus, dialogs are modal and labelled, the navigator window and edges are sliders, the ladder is a grid, the symbol search input a combobox. Changes (timeframe, tool, indicators, alerts, orders, fills) are announced. The option a11y: keyboard (bar cursor), summary, contrast ('AA' default, 'AAA', a ratio or false).
Methods: getSummary(), announceSummary(), focusBar(index, { announce }), getFocusedBar(), describeBar(index). The library also exports the helpers it uses itself: announce(message), trapFocus, rovingFocus, setAria, prefersReducedMotion() and others (see API reference).
Using with other VibeFox JS libraries
VibeFox JS Trading works on its own. Every VibeFox JS library is a separate file with its own copy of the shared core, and several libraries on one page work together without conflicts: one global variable per library (VibeFoxJSTrading, VibeFoxJSCharts, …), class names with the library prefix, one page theme, the same events.
Connecting components with link()
link(source, event, target, method, transform) calls a method of one component whenever another emits an event; it returns a function that removes the link. connect(source, event, handler) subscribes and returns an unsubscribe function. bus is a page-wide event channel shared by all VibeFox JS libraries on the page.
// the crosshair of the chart fills a table of VibeFox JS Grid (both files loaded on the page)
const unlink = VibeFoxJSTrading.link(chart, 'crosshairMove', grid, 'setData', (e) => (e.bar ? [e.bar] : []));
VibeFoxJSTrading.bus.emit('prices:refresh', { at: Date.now() }); // any library can listen: VibeFoxJSGrid.bus.on('prices:refresh', fn)
What uses another library when it is on the page
- Nothing in VibeFox JS Trading needs another library: the toolbars, dialogs, watchlist, order ticket, ladder and backtest report are its own.
- Several trading charts:
syncCharts()andcreateTradingLayout()(see Several charts and synchronization), within VibeFox JS Trading.
API reference
Exports
Library: createTradingChart, VibeFoxJSTradingChart, createTradingLayout, VibeFoxJSTradingLayout, syncCharts, MemoryDatafeed, MockBroker, indicators, registerIndicator, sma, ema, wma, stdev, backtest, exportBacktest, optimizeStrategy, paramGrid, resampleBars, generateBars, mergeTick, detectInterval, toHeikinAshi, buildChartType, computeVolumeProfile, alignCompare, resolutionFor, normalizeBars, TIMEFRAMES, SERIES_TYPES, BUILT_TYPES, CHART_TYPE_DEFAULTS, TOOLS, TOOL_GROUPS, MAGNET_MODES, INDICATOR_GROUPS, TOOLBAR_ITEMS, TRADING_STYLES, PERIODS, SESSION_PRESETS, SYNC_DEFAULTS, LAYOUTS, WATCHLIST_COLUMNS, DATAFEED_DEFAULTS, ORDER_TYPES, ORDER_TIFS, TRADE_DEFAULTS, RENDERERS, WEBGL_DEFAULTS, ALERT_CONDITIONS, ALERT_FREQUENCIES, ALERT_TOOLS, ALERTS_DEFAULTS, BACKTEST_DEFAULTS, OPTIMIZE_DEFAULTS, STRATEGY_DEFAULTS.
Shared core (the same in every VibeFox JS library): setTheme, getTheme, registerTheme, themes, tokens, componentTokens, densities, cssVar, cssColor, cssLength, observeTokens, setLocale, getLocale, addLocale, normalizeLocale, t, tPlural, withLocale, onLocaleChange, link, connect, bus, Emitter, VibeFoxJSComponent, factory, toCSV, downloadFile, downloadCanvasPNG, announce, trapFocus, rovingFocus, getFocusable, focusFirst, saveFocus, setAria, ensureId, addAriaRef, removeAriaRef, isRtl, mirrorArrow, prefersReducedMotion, prefersHighContrast, motionDuration, onPreferenceChange, injectStyles, ensureBaseStyles, formatNumber, formatDate, escapeHtml, createEl, deepMerge, isPlainObject, getPath, setPath, uid, clamp, debounce, throttle, VERSION.
Options
Also every VibeFox JS component accepts theme, locale, rtl and on (see Core concepts).
| Option | Type | Default | Description |
|---|---|---|---|
data | bar[] | [] | Bars of the base resolution. |
symbol | string | 'VFJS' | Ticker (legend, watermark, datafeed). |
seriesType | string | 'candlestick' | Series type. |
timeframe | string or null | null | Displayed timeframe; null = the timeframe of the bars (with a datafeed '1m'). |
priceFormat | { decimals, tickSize } | { decimals: null, tickSize: null } | Precision of the prices (null = automatic). |
priceScale | { mode } | { mode: 'linear' } | 'linear', 'log', 'percent'. |
timeScale | object | { rightOffset: 6, sessionBreaks: true, gaps: false } | Time scale. |
timezone | string | 'UTC' | Display time zone. |
sessions | object, string or null | null | Trading sessions. |
volume | { visible } | { visible: true } | Volume pane. |
watermark | { visible, text } | { visible: true, text: null } | Watermark (default text: the symbol). |
legend, crosshair | { visible } | { visible: true } | OHLCV legend, crosshair. |
priceLine | { visible, pulse } | { visible: true, pulse: true } | Last price line and dot. |
volumeProfile | { visible, bins } | { visible: false, bins: 24 } | Volume profile. |
baseline | { value } | { value: null } | Level of the baseline series. |
markers | marker[] | [] | Bar markers. |
grid | { vertical, horizontal } | both true | Grid lines. |
datafeed | object or null | null | Datafeed adapter. |
datafeedOptions | object | {} (DATAFEED_DEFAULTS) | Paging, retries, cache. |
compare | { autoPercent, lineWidth } | { autoPercent: true, lineWidth: 1.5 } | Symbol comparison. |
indicatorLabels | { values, axis } | { values: true, axis: true } | Indicator values in legends and on the axis. |
style | string or null | null | Ready-made style. |
drawings | object | { magnet: 'off', visible: true, keepTool: false, undoLimit: 100, properties: true } | Drawing tools. |
chartTypes | object | CHART_TYPE_DEFAULTS, indicators: 'auto' | Built chart types. |
toolbar, drawingToolbar | boolean or object | false | Terminal UI bars. |
dialogs | boolean, object or null | null | Indicators and settings dialogs. |
navigator, periods | boolean or object | false | Navigator, period buttons. |
watchlist, symbolSearch | boolean or object | false | Watchlist, symbol search. |
touch | object | { longPress: 500, doubleTap: true, inertia: true, loupe: true } | Touch gestures. |
a11y | object | { keyboard: true, summary: true, contrast: 'AA' } | Accessibility. |
trade | boolean or object | false (TRADE_DEFAULTS) | Trading from the chart. |
renderer | string | 'auto' | 'auto', 'canvas', 'webgl'. |
webgl | { minBars, software } | { minBars: 5000, software: false } | WebGL renderer. |
alerts | object | { sound: false, notifications: false, onTrigger: null, announce: true } | Alerts. |
Layout options: layout ('1'), chart, charts, datafeed, sync, active, watchlist.
Events
| Event | Payload | Description |
|---|---|---|
ready, dataChange, optionsChange, themeChange, destroy | see Core concepts | Common events. |
crosshairMove | { index, time, bar, price, paneId } | Crosshair moved (bar: null outside the plot). |
visibleRangeChange | { from, to, timeFrom, timeTo } | Visible range changed. |
timeframeChange, seriesTypeChange, symbolChange | { timeframe, tfMs }, { seriesType }, { symbol } | Timeframe (also a newly detected one after setData()), type, symbol. |
barUpdate, barClose | { bar, isNew }, { bar } | Live data. |
indicatorAdd, indicatorChange, indicatorRemove | { id, name, params, visible } | Indicators. |
toolChange, drawingComplete, drawingAdd, drawingSelect, drawingUpdate, drawingRemove, drawingsChange, historyChange, magnetChange, drawingPropertiesOpen, drawingPropertiesClose, drawingTextEdit | { tool }, { drawing }, { drawing, drawings }, { id }, { reason }, { canUndo, canRedo }, { magnet }, { id, editing } | Drawings. |
markerClick | { marker } | Marker clicked. |
paneResize | { panes } | Pane heights changed. |
replayStart, replayStep, replayFinish, replayStop | { index, bar } | Replay. |
dataLoading, dataLoad, dataError, historyEnd | { symbol, timeframe, kind, count, cached, error, attempt, final } | Datafeed. |
compareAdd, compareChange, compareRemove | { symbol } | Comparison. |
alertAdd, alertChange, alertTrigger, alertExpire, alertRemove | { id, alert, price, value, direction, message, payload } | Alerts. |
styleChange, colorsChange, favoritesChange, fullscreenChange | { style, previous }, { colors }, { timeframes, indicators }, { fullscreen } | Look and UI. |
dialogOpen, dialogClose | { dialog } | 'indicators', 'settings', 'symbolSearch', 'orderTicket', 'tradeConfirm'. |
snapshot | { symbol, timeframe } | Toolbar image downloaded. |
contextMenu | { x, y, pointerType, index, time, price, paneId, drawingId, order, position } | Right click / long press. |
priceScaleChange | { paneId, zoom, auto } | Price scale zoomed / reset. |
periodChange, timezoneChange, sessionsChange | { period }, { timezone, zone }, { sessions } | Period, zone, sessions. |
watchlistChange, watchlistSelect, symbolSearch | the watchlist, { symbol }, { symbol, mode } | Watchlist, symbol search. |
orderPlace, orderModify, orderCancel, positionClose, positionReverse, positionModify | { action, order, position, changes, respondWith, preventDefault } | Trading requests. |
orderReject | { action, order, position, changes, error } | A request failed. |
ordersChange, positionsChange, execution, depthChange, domToggle | { orders }, { positions }, the fill, { depth }, { visible } | Trading state. |
rendererChange | { renderer, reason } | Canvas / WebGL switched. |
strategyChange, backtest, signal, strategyTrade, optimizeProgress | { strategy, params }, { result }, the signal, { trade }, { done, total } | Strategies. |
Layout events: layoutChange ({ layout, count }), activeChange ({ index, chart }), watchlistChange, watchlistSelect.
Methods
| Method | Returns | Description |
|---|---|---|
setData, getData, setOptions, setOption, getOption, getState, setState, setTheme, on, once, off, use, t, destroy | — | Common methods (see Core concepts). |
setTimeframe, getTimeframe, setSeriesType, getSeriesType, setPriceScaleMode | this / value | Display (getTimeframe() may return null). |
getPriceFormat(), formatPrice(price) | { decimals, tickSize, source } / string | Price precision. |
addTick(tick), updateBar(bar), setMarkers(markers) | this | Live data, markers. |
fitContent, scrollToRealtime, setVisibleRange, getVisibleRange, setVisibleTimeRange, getVisibleTimeRange, timeToIndex, indexToTime, setCrosshair | this / range / number | Viewport. |
zoomPrice, resetPriceScale, isPriceScaleZoomed, resetScale | this / boolean | Price scale. |
addIndicator, updateIndicator, removeIndicator, getIndicators, getIndicatorValues, setIndicatorVisible | id / this / list / values | Indicators. |
setTool, getTool, getDrawings, getDrawing, addDrawing, updateDrawing, setDrawings, removeDrawing, clearDrawings, selectDrawing, getSelectedDrawings, copyDrawings, pasteDrawings, cloneDrawing, orderDrawing | this / drawings / id | Drawings. |
undo, redo, canUndo, canRedo, clearHistory, setMagnet, getMagnet, showDrawingProperties, hideDrawingProperties, editDrawingText, stopTextEdit | boolean / this / mode | Drawing history and editing. |
addAlert, updateAlert, removeAlert, clearAlerts, getAlerts, getAlert, describeAlert, openAlertDialog, openAlertsDialog, requestAlertNotifications | id / this / alerts / string / Promise | Alerts. |
startReplay, pauseReplay, resumeReplay, stepReplay, stopReplay, showVolumeProfile | this | Replay, volume profile. |
exportPNG, getImage, getBarsCSV, exportCSV | this / canvas / string | Export. |
setDatafeed, getDatafeed, setSymbol, getSymbol, reloadData, loadMoreHistory, whenLoaded, getLoadState | this / Promise / state | Datafeed. |
addCompare, removeCompare, clearCompares, setCompareData, getCompares | symbol / this / list | Comparison. |
setStyle, getStyle, setColors, getColors | this / value | Look. |
getChartTypeInfo, setChartTypeParams | info / this | Built chart types. |
openIndicatorsDialog, openSettingsDialog, closeDialogs, toggleFullscreen, isFullscreen, getFavorites, setFavorites | this / value | Terminal UI. |
setPeriod, getPeriod, getPeriods | this / period / list | Period buttons. |
setTimezone, getTimezone, getTimezoneInfo, setSessions, getSessions, getSessionInfo | this / value | Time zones and sessions. |
getWatchlist, setWatchlist, addToWatchlist, removeFromWatchlist, updateWatchlist, getWatchlistQuotes, toggleWatchlist, openSymbolSearch | this / value | Watchlist and symbol search. |
getSummary, announceSummary, focusBar, getFocusedBar, describeBar | summary / this / string | Accessibility. |
setBroker, getBroker, setOrders, setPositions, updateOrder, updatePosition, getOrders, getPositions, getPnl, setDepth, getDepth | this / list | Trading state. |
placeOrder, modifyOrder, cancelOrder, closePosition, reversePosition, modifyPosition | Promise | Trading requests. |
openOrderTicket, closeOrderTicket, toggleDom | this | Ticket, ladder. |
setStrategy, getStrategy, getBacktest, getTrades, exportBacktest, showBacktestReport, hideBacktestReport, optimizeStrategy | this / result / string / Promise | Strategies. |
setRenderer, getRenderer, getRenderInfo, requestRender | this / value | Rendering. |
The layout methods are listed under Several charts and synchronization. The TypeScript declarations (vibefox-js-trading.d.ts) describe every option, payload and return type in detail: TradingOptions, TradingBar, TradingEvents, TradingState, TradingDatafeed, TradingDrawing, TradingAlertInput, TradingBroker, TradingStrategy, TradingBacktestResult, TradingLayoutOptions and others.
Troubleshooting
No styles
Link vibefox-js-trading.css next to the script. Without it the component works but is unstyled, and the console shows one warning "VibeFox JS stylesheet is not loaded". In a bundler, import @vibefox/js-trading/css. The framework wrappers do not add the CSS for you.
My CSS does not apply, or a page CSS framework changes the component
Your rules win over the library rules without !important because the library CSS is in @layer vfjs. If they still do not apply, check the class names: state classes have the library prefix (vfjs-trading-is-up, not is-up). The canvas colors are CSS variables, not CSS rules: set the variables. The library never uses generic class names, so page CSS frameworks do not change it.
ES modules do not load from disk
Browsers load <script type="module"> only over http(s). Use a local web server, or use vibefox-js-trading.global.js, which also works from file://.
Content Security Policy
The library does not use eval or inline scripts and loads nothing from the network. It sets inline styles on its elements (sizes and positions), so a policy with style-src must allow them ('unsafe-inline' for style attributes). The parameter search of strategies creates its Web Workers from a Blob URL (worker-src blob:); without that permission it runs on the main thread. Your datafeed, broker and alert hook make their own requests, so connect-src must allow their addresses.
The chart is too small or empty
The chart fills its element. Give the element a height (CSS or an inline style); the chart or the layout takes it exactly, also a small one. Without one, both are 400 px high (--vfjs-trading-min-height). The target element must exist when createTradingChart runs (a selector that finds nothing throws an error). Bar times are milliseconds: seconds (Unix time) put every bar in January 1970.
No timeframe is shown, or the wrong one
Without the option timeframe the chart takes the timeframe of your bars; bars of a length that is no timeframe (for example 2 hours) are shown as they are, without a timeframe in the legend and the toolbar. Set timeframe (or call setTimeframe()) to show the bars resampled into a timeframe of your choice. Bar times must be milliseconds.
Prices have too few or too many decimals
The precision of the prices comes from the data or the trade tick size. Set priceFormat: { decimals } or priceFormat: { tickSize }; getPriceFormat().source tells where the current precision comes from.
The datafeed shows "Failed to load data"
Listen to dataError for the reason and the attempt. getBars must return bars with time < to, oldest first; an empty answer or noData: true ends the history. reloadData() tries again.
Indicators, drawings or alerts are lost after setState
A snapshot replaces the indicators, drawings and alerts as a whole. Save and restore the full getState(), not a part of it.
No sound or notification of an alert
Browsers play sound only after a user action on the page, and notifications need the option alerts.notifications, notify: true on the alert and the permission (requestAlertNotifications() from a click).
The parameter search runs on the main thread
A strategy that reads variables outside its own functions (a closure) cannot run in a worker; put the values into params. The reason of the result says why.
Limitations
- Drawings live in the price pane only; one properties panel at a time; the panel edits the level list of a tool but does not add or remove levels; no rubber-band selection and no angle snapping with Shift; the drawing clipboard is not the system clipboard; undo covers the drawings only (not indicators or alerts).
- Text drawings are not wrapped automatically (only at your line breaks) and use the chart font; positions and measures use bar highs and lows (no order inside a bar), without commissions.
- Compared symbols are lines of the close only; there is no separate left price scale.
- Built chart types are built from bars, not ticks; Kagi uses the close only; there is no "traditional" Renko with an ATR per brick; the volume profile uses the built bars on built types.
- The navigator shows the loaded history only (closes); layout cells have equal sizes; synchronizing drawings replaces the whole list.
- Watchlist quotes come from bars (no separate quote API), one live feed per symbol; the list is not virtualized.
- Alerts are checked in the page on the chart's data: nothing runs when the page is closed; a zone counts at any time; regression and Donchian channel drawings are not alert targets; alerts are not checked during replay.
- Trading: bracket orders are stop loss / take profit fields (no OCO groups); the ladder shows sizes per price level as given; P&L is in the quote currency without fees; the MockBroker nets one position per symbol.
- Backtests: one net position (no hedging), no partial fills, no stop-limit, OCO or trailing orders (a trailing stop is
protect()on every bar), the path inside a bar is a heuristic, strategies run on closed bars only, no margin calls; the report table shows the first 2000 trades (the export has all); strategies are not part of the state. - WebGL: one WebGL part per pane; hollow and volume candles, baseline, Kagi and Point & Figure are drawn with canvas 2D; a page has a browser limit of WebGL contexts (about 16).
- Time zones follow the time zone data of the browser; the session presets have no holidays.
- The automatic price precision is read from the last 300 bars: an instrument whose older prices had more decimals shows the recent precision, and a live tick with more decimals raises it. Set
priceFormatto fix the precision. - Framework wrappers: functions in options are compared by reference; removing a prop does not reset the option to its default; Vue watches object props shallowly.
