Vela, our next-generation charting platform, is live at vela.luxalgo.com.
LuxAlgo
Backtesting

Strategies

Run Pine Script® strategies on Vela Pro charts, configure capital and commission properties, and set workspace-wide defaults.

View as Markdown

A Pine Script® strategy is any script declared with strategy(). The default Pine engine registered by enableVelaPro() executes strategy scripts against the chart's bars, simulates order fills, and reports backtest metrics. Running a strategy draws order fills on the price pane, adds a Properties tab to the settings dialog for capital and cost configuration, and populates the Strategy tester in the bottom dock.

Adding a strategy

Pass the Pine Script® source string to addIndicator on a chart instance. There is no separate method for strategies because the strategy() declaration identifies the script type automatically.

import { VelaWorkspace } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro } from '@luxalgo/vela-pro';

enableVelaPro();

const workspace = new VelaWorkspace('#chart', {
    layout: false,
    symbol: 'BTCUSDT',
    timeframe: '60',
    live: true,
    providers: { binance: () => new BinanceProvider() },
    persist: true,
});

const strategy = workspace.chart.addIndicator(`//@version=5
strategy("EMA cross", overlay=true, initial_capital=10000,
     default_qty_type=strategy.percent_of_equity, default_qty_value=10)
fast = ta.ema(close, input.int(9, "Fast"))
slow = ta.ema(close, input.int(21, "Slow"))
plot(fast, "Fast", color.orange)
plot(slow, "Slow", color.blue)
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long)
if ta.crossunder(fast, slow)
    strategy.close("Long")`);

strategy.on('error', ({ error }) => console.error(error.message));

addIndicator returns an IndicatorHandle immediately while the backtest runs in a Web Worker by default. workspace.chart targets the active chart cell, or you can target a specific cell in a multi-chart grid via workspace.cell('btc')?.chart.

Workspace persistence does not save scripts added programmatically with addIndicator, so call addIndicator on each page load if the script should always be present. See Indicator persistence for details on saved scripts. Users can also add strategies interactively from the Indicator menu or write them in the Pine code editor.

See Pine Script® with PineTS for supported language features and the PineTS strategy reference for the strategy.* namespace.

Chart and legend display

When a strategy runs on a chart, Vela Pro displays three interface elements:

  • Order fills on the price pane: Each fill renders a directional arrow at its execution bar (buy arrows point up below the bar's low and sell arrows point down above the bar's high), the order ID (replaced by comment= when set on the order), the signed quantity, and a tick mark at the fill price.
  • Legend controls: Strategy rows match standard indicator legend rows and add a Strategy report button that opens the strategy tester.
  • Strategy tester dock: Opens beneath the chart area the first time a strategy reports backtest results.

Vela's open-source core renders trade fills on the canvas through the tradeMarkers renderer feature. For example, calling workspace.chart.renderer.set('tradeMarkers', { qty: false }) hides fill quantities on the chart. See Renderer features for all tradeMarkers options.

Strategy properties

Arguments declared in strategy() (such as initial_capital, commission_value, and pyramiding) become configurable strategy properties. Opening the settings dialog from the legend row displays these fields in a Properties tab alongside the script's Inputs tab. Changing any property triggers a full strategy replay.

The pineEngine.props option controls which scripts show the Properties tab and which fields appear in it:

propsProperties tab behavior
'strategy' (default)Shown on strategies with all supported properties. Hidden on indicators.
'all'Shown on both strategies and indicators.
'none'Hidden on all scripts.
string[]Shows only the listed property keys, in array order. Hidden on scripts that support none of those keys.

With 'strategy', the tab includes every argument accepted by strategy(), including display settings such as precision, scale, and max_lines_count. Pass an explicit key array to limit the dialog to capital and execution settings:

import { enableVelaPro } from '@luxalgo/vela-pro';

enableVelaPro({
    pineEngine: {
        props: [
            'initial_capital',
            'currency',
            'default_qty_type',
            'default_qty_value',
            'pyramiding',
            'commission_type',
            'commission_value',
            'slippage',
            'margin_long',
            'margin_short',
            'process_orders_on_close',
        ],
        defaultProps: { initial_capital: 50_000, commission_value: 0.05 },
    },
});

props only filters which controls appear in the settings dialog. Hidden properties retain the values declared in the script and remain writable from code via setProps.

Pass pineEngine options in your initial enableVelaPro() call. Because enableVelaPro() installs each feature once, calling it a second time with different pineEngine options has no effect.

Default property values

defaultProps supplies fallback values for any property that a script does not explicitly set in strategy(). With the configuration above, a strategy that omits initial_capital starts at 50_000 instead of the built-in Pine Script® default of 1_000_000, while a script declaring initial_capital=10000 keeps 10_000. The Properties tab opens with these resolved defaults, and clicking Reset defaults in the dialog restores them.

If a script sets an argument to the built-in Pine Script® default value (such as initial_capital=1000000), the engine treats that argument as undeclared and applies your defaultProps override.

Updating properties at runtime

The IndicatorHandle returned by addIndicator exposes a strategy's property definitions and current values. Pass initial overrides through props when adding the strategy, or update them later with setProps:

import type { VelaWorkspace } from '@luxalgo/vela/workspace';

declare const workspace: VelaWorkspace;
declare const source: string;

const strategy = workspace.chart.addIndicator(source, {
    props: { initial_capital: 25_000 },
});

strategy.on('ready', () => {
    // Property descriptors shown on the Properties tab for this script.
    console.log(strategy.props.map((p) => p.key));
});

document.querySelector('#flat-fee')?.addEventListener('click', () => {
    // Applies both changes together and replays the strategy once.
    strategy.setProps({ commission_type: 'cash_per_order', commission_value: 1 });
    console.log(strategy.propValues()); // current property values
});

setProps only updates a running strategy after initialization completes. Calling setProps immediately after addIndicator (before ready fires) has no effect, so pass initial values via addIndicator(source, { props }) instead.

Property values resolve in strict precedence order from highest to lowest: runtime overrides (setProps, addIndicator({ props }), or edits in the Properties tab), arguments in the script's strategy() declaration, defaultProps, and finally built-in Pine Script® defaults. Unknown property keys or out-of-range values are skipped with a console warning. See IndicatorHandle for the complete handle reference.

Custom scripting engines

The strategy tester does not depend on Pine Script® syntax. It consumes the core's engine-agnostic strategy types, so Custom runtimes populate the same report UI whenever a session's getContext() returns:

  • strategy: A StrategyState object containing final position, equity, net profit, drawdown, and initial capital at the last bar. Including strategy marks the execution as a strategy run.
  • trades: An array of StrategyTrade round trips with realized pnl on closed trades, plus per-trade maxRunup and maxDrawdown values to populate the MFE and MAE columns in the trades log.
  • Bar-series metrics on StrategyState: Optional sharpe, sortino, buyHoldPnl, buyHoldPct, and outperformance fields for statistics that require bar-by-bar equity data.

Trade markers on the price pane are drawn from the trades array on the engine's chart model output. Note that the Strategy report legend button checks whether a line of the script source starts with strategy(. Custom languages with different strategy declarations may not display the legend button, although the strategy tester still opens automatically when a run reports a StrategyState.

See Backtest results for the StrategyState and StrategyTrade schemas, and the core's engine guide for the ScriptingEngine contract.

On this page