Backtest results
Subscribe to strategy runs, compute full StrategyReport metrics in code, persist backtests to a backend, and build custom report panels.
Whenever a strategy finishes computing, its chart emits a script:run event carrying the account state at the last bar and a lazy accessor for the trade ledger. Passing a run's output to buildStrategyReport produces the performance metrics, equity curve, and trade breakdowns used by the Strategy tester, so you can persist backtests to your backend, compare parameter sets, or render a custom report UI.
Subscribing to strategy runs
import { VelaWorkspace, type WorkspaceScriptRun } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { buildStrategyReport, enableVelaPro } from '@luxalgo/vela-pro';
enableVelaPro();
const workspace = new VelaWorkspace('#chart', {
symbol: 'BTCUSDT',
timeframe: '60',
live: true,
providers: { binance: () => new BinanceProvider() },
persist: true,
});
async function saveBacktest(run: WorkspaceScriptRun): Promise<void> {
if (!run.strategy) return;
const report = buildStrategyReport({ title: run.title, state: run.strategy, trades: await run.trades() });
const cell = workspace.cell(run.cell);
await fetch('/api/backtests', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
symbol: cell?.symbol,
timeframe: cell?.timeframe,
strategy: report.title,
netProfit: report.netPnl,
maxDrawdown: report.maxDrawdown,
trades: report.all.trades,
winRate: report.all.winRate,
profitFactor: report.all.profitFactor,
sharpe: report.engine?.sharpe ?? null,
from: report.firstTime,
to: report.lastTime,
}),
});
}
workspace.on('script:run', (run) => {
// Ticks and new bars extend a backtest that is already stored.
if (run.cause === 'tick' || run.cause === 'bar' || !run.complete) return;
saveBacktest(run).catch((err) => console.error('Backtest not saved', err));
});script:run is emitted by Vela's open-source core. Subscribing on workspace relays events from every chart cell in the workspace grid, including cells added later when the layout changes, and populates run.cell with the originating cell ID. To listen to a single chart instead, call workspace.chart.on('script:run', handler), which delivers the same payload without cell. Both methods return an unsubscribe function.
The trade ledger is not attached eagerly to the event payload. Calling run.trades() fetches the trades on demand so listeners that only inspect top-level equity avoid transferring thousands of trade records on every run.
Execution metadata
| Field | Description |
|---|---|
id | Indicator instance ID matching IndicatorHandle.id |
title | Script title declared in indicator() or strategy() |
kind | 'indicator' or 'strategy' |
cause | Execution trigger (see Filtering runs) |
complete | false while deeper historical bars are still loading and a follow-up run is pending |
forming | true while the latest bar remains open, which is always true on a live chart |
strategy | StrategyState at the last bar, present when reported by the engine |
trades() | Async method resolving StrategyTrade[] round trips, ordered with closed trades first and open trades last |
cell | Originating chart cell ID (present on workspace-level events only) |
StrategyState holds end-of-run account metrics, including position (signed quantity), avgPrice, equity, openPnl, netPnl, grossProfit, grossLoss, wins, losses, even, maxDrawdown, maxRunup, and initialCapital. Engines that compute bar-level statistics also populate cagr, sharpe, sortino, buyHoldPnl, buyHoldPct, and outperformance.
StrategyTrade represents a single round trip containing id, side, qty, entry, open, and (once closed) exit. Both entry and exit include the order id, time, price, and optional comment. Engines that maintain a detailed per-trade ledger also provide pnl (net of commission), commission, maxDrawdown, and maxRunup. All timestamps are epoch milliseconds.
Both StrategyState and StrategyTrade are exported from @luxalgo/vela/plugin. For the remaining fields on script:run (including plot values, exported variables, and runtime warnings), see Capturing what a script computes in the core's API reference.
Filtering runs
The cause field identifies why a strategy ran, letting you separate full historical recalculations from incremental live updates:
cause | When it fires |
|---|---|
'history' | Initial computation across the loaded historical bars |
'inputs' | An input or strategy property changed via the settings dialog, setInputs, or setProps |
'code' | Script source was replaced in place via updateCode |
'market' | Chart symbol or timeframe changed, triggering a fresh run |
'bar' | A new bar opened on a live feed, finalizing the previous bar |
'tick' | The open bar updated on a live feed (throttled to roughly one run per second per script) |
'viewport' | The visible bar range changed (only for scripts that read viewport bounds) |
'history', 'inputs', 'code', and 'market' recompute the entire backtest from the start of the series. On a live chart, 'bar' and 'tick' extend an existing backtest incrementally as new market data arrives, which is why the example above skips them. To keep a live forward test updated in storage, persist runs when cause is 'bar' and ignore 'tick' because intrabar fills and P&L can still change before the bar closes.
Building a StrategyReport
buildStrategyReport accepts { title, state, trades } and returns a structured StrategyReport:
| Field | Description |
|---|---|
title, initialCapital, finalEquity, netPnl, position | End-of-run account summary read from StrategyState |
maxDrawdown, maxDrawdownPct, maxRunup | Engine-reported drawdown and run-up (maxDrawdownPct is calculated relative to the equity peak before the drawdown) |
engine | Optional object with sharpe, sortino, buyHoldPnl, buyHoldPct, and outperformance as reported by the engine (omitted when the engine reports none) |
all, long, short | SideMetrics objects for combined, long, and short trades (net and gross profit, profit factor, commission, trade counts, win rate, averages, largest win and loss, durations, and consecutive streaks) |
sharpe, sortino, cagr, calmar | Computed by buildStrategyReport from the trade ledger (sharpe and sortino use annualized calendar-month returns of closed trades) |
equity | EquityPoint[] items containing time, equity (cumulative closed-trade net profit), drawdown (distance below the running peak), and the trade index and side |
trades | ReportTrade[] items ordered with closed trades in exit order followed by open trades (index, side, qty, entry and exit timestamps and prices, pnl, pnlPct, cumulative, runup, drawdown, and commission) |
distribution | Histogram buckets grouping closed trades by percentage return |
daily, weekday, weekdayTrades | Realized profit, trade count, and win count grouped by UTC exit day, plus realized profit and trade counts by weekday (Monday first) |
firstTime, lastTime | Timestamps of the first entry and last exit |
Any metric that cannot be derived from the ledger is null rather than a synthetic 0. Percentages use a 0 to 100 scale (such as winRate: 62.5) and durations are reported in milliseconds. Call timeframeMs('60') to get a single bar's duration in milliseconds when converting durations to bar counts.
report.engine.sharpe and report.sharpe represent different calculations. report.engine.sharpe comes from the engine across every bar of the series, whereas report.sharpe is computed from closed trades only. The strategy tester displays the engine's Sharpe and Sortino values, and applies panel-specific formulas to certain summary table cells (such as fixed-base CAGR and per-day or per-week averages), so not every UI row matches the corresponding SideMetrics field.
StrategyReport, SideMetrics, ReportTrade, and EquityPoint are exported alongside buildStrategyReport from @luxalgo/vela-pro. See Replay and strategy in the API reference for every field.
Comparing runs
To compare stored backtest results across parameter changes, record the input and property values that produced each run. Use run.id to find the matching IndicatorHandle on the chart:
import type { VelaWorkspace, WorkspaceScriptRun } from '@luxalgo/vela/workspace';
declare const workspace: VelaWorkspace;
function settingsOf(run: WorkspaceScriptRun) {
const chart = workspace.cell(run.cell)?.chart;
const handle = chart?.indicators().find((h) => h.id === run.id);
return { inputs: handle?.inputValues(), props: handle?.propValues() };
}Include these settings when saving the report so every edit to an input or strategy property stores a self-contained configuration snapshot alongside its performance metrics.
To run a strategy once purely to capture its output without keeping it on the chart, call the core's chart.runScript(source, options) method, which resolves the initial run and provides a remove() method for cleanup. See Executing a script and capturing its result.
Custom report UI
When building a custom bottom panel, StrategyTracker manages chart subscriptions and report caching automatically. It follows the active chart cell, maintains one entry per strategy, and rebuilds reports immediately after historical or parameter runs and at most once per second while a live chart streams.
import { enableVelaPro, registerBottomPanel, StrategyTracker } from '@luxalgo/vela-pro';
enableVelaPro({ strategyTester: false });
registerBottomPanel({
id: 'acme.backtest',
title: 'Backtest',
icon: 'vp-strategy',
mount: (ctx, body) => {
const tracker = new StrategyTracker(ctx);
const render = (): void => {
const report = tracker.selected?.report;
body.textContent = report
? `${report.title}: ${report.netPnl.toFixed(2)} over ${report.all.trades} trades`
: 'No backtest yet';
};
const off = tracker.onChange(render);
render();
return {
destroy: () => {
off();
tracker.destroy();
},
};
},
});Call registerBottomPanel before constructing VelaWorkspace. The bottom dock adds a corresponding panel button to the side rail automatically. tracker.list() returns every strategy that has reported on the active chart as { id, title, report } (report is null until the first report completes), and tracker.select(id) selects which strategy tracker.selected returns.
StrategyTracker requires the WidgetContext passed to a panel's mount callback. See Custom panels and widgets for details on registering bottom panels. Outside of a panel context, subscribe to script:run directly as shown in Subscribing to strategy runs.
Engine independence
The backtest reporting pipeline is independent of the built-in Pine engine:
script:run,StrategyState, andStrategyTradebelong to the core and work with any scripting runtime, including whenstrategyTester: falsedisables the default UI panel.run.strategyandrun.trades()reflect whatever the active runtime reports. When an engine reports no strategy state,run.strategyisundefinedandrun.trades()resolves to an empty array.report.engineis omitted whenever an engine does not report Sharpe, Sortino, or benchmark values (including Pine runs that are too short to calculate them).buildStrategyReportrequires neither a chart nor an engine instance, so you can pass itStrategyStateandStrategyTrade[]payloads produced by a backend service.
Setting pineEngine: false without registering Custom runtimes disables script execution completely, so script:run will not fire. To execute Pine Script® backtests in Node.js or a worker without mounting a chart, run scripts directly with PineTS as documented in the strategy reference.