Chartsv26.10.18
Pro edition

Strategies and backtest

The declarative strategy language - inputs, entry and exit conditions, the risk block - and the backtest engine over paged history with the metrics of the report.

The strategy layer turns a trading idea into data: a small declarative text that parses into a structure, never into code. The same structure runs through the backtest engine over historical bars, and the report reads the numbers the engine produced.

Runs 0 · trades 0 · net P&L 0
Data only: the parser never executes code.

Fix the parse error and run the strategy to see the report.

The chart above is the live feed; the entry and exit markers are the tail trades of the current run and the lines mark the newest one. The report recomputes over the growing history every few ticks. The editor opens with a momentum sample tuned to this history, so the page starts on a real run; the chips load the library templates as they ship, levels included. The language is the one the library ships: name, inputs, rules over the condition catalogue and an optional risk block; the limits (16 conditions per rule, 24 in total, 40 characters of the name) and the round-trip serializer are the same public contract a host binds from its own code or dialog.

Type in the editor: the preset chips load the three shipped strategies, the text is parsed by parseStrategy - data, never code - and the run button pushes it through the real backtest engine over the live history of the chart above; the report reads the engine numbers and a typo comes back as a problem with its line and column. Every press of Run backtest answers in the status line next to the button - the run number, the trades found, the net P&L and the walk time in milliseconds - and the report block pulses, so the press is visible even when the numbers of the walk repeat. A rejected source turns the status line red and gives the problem back with its line and column. The entry and exit markers of the tail trades ride the events lane of that chart and the newest trade carries its entry and exit price lines, so the chart tells the story of the run. The editor opens with a momentum sample tuned to this history; the chips load the templates as they ship, levels included.

The strategy text

A strategy declares its inputs, its entry and exit rules as conditions of the alert catalogue, and an optional risk block. Comments start with #.

# Moving average cross
strategy ma-cross
input symbol = SBER
input timeframe = 1H
input size = 20
input commission = 0.0005
input slippage = 0.0003
input leverage = 1
entry when indicatorCross(fast=ema10, slow=ema30, direction=up)
exit when indicatorCross(fast=ema10, slow=ema30, direction=down)
risk stop = 1.5%
risk target = 3%
import { parseStrategy, serializeStrategy } from '@unifin/chart-core/strategy';

const strategy = parseStrategy(text);
strategy.inputs.size; // 20
strategy.entry?.conditions[0]; // { kind: 'indicatorCross', fast: 'ema10', slow: 'ema30', direction: 'up' }
serializeStrategy(strategy); // canonical text, stable round-trip

A rule combines conditions with and or or; mixing the two in one rule is refused. Conditions take positional arguments, so an error names the line and the column: an unknown condition, an unknown parameter (unknown parameter "lvl" of priceCross; expected level, direction) or a value outside an enum all come back as problems of one StrategySyntaxError. The rule limits are declared constants (STRATEGY_MAX_RULES, STRATEGY_MAX_TOTAL_RULES) and checked at parse time.

Conditions the engine runs on bars

The engine executes price and indicator rules on plain bars; conditions that need chart objects are refused with a named error instead of being ignored.

Runs on barsNeeds chart objects
priceCross, priceUp, priceDown, changePercentdrawingTouch, drawingBreak
volumeSpike, rangeExitcandlePattern
indicatorCross, indicatorLevelformula (a host evaluator)

History and the backtest

History arrives through a paged source: the host feeds pages of bars and the engine never reaches for the network itself. A page carries a cursor and the loader walks it while the page limit and the bar limit hold; a failed page comes back as HistoryLoadError with a reason (page-failed, page-limit, bar-limit, empty-history).

import { collectHistory, parseStrategy, runBacktest } from '@unifin/chart-core/strategy';

const bars = await collectHistory(source); // paged backend contract
const result = runBacktest(parseStrategy(text), { bars });
result.metrics.totalPnl; // commission and slippage are applied to every trade

The engine marks the position to market on every bar: an entry buys at the close plus slippage, the stop is checked before the target inside the same bar (the conservative order), the margin gate compares the notional of the position against the cash and the leverage, and an open position is closed at the last bar.

The report

BacktestPanel renders the finished result of the engine: trades, wins, losses, win rate, total and average P&L, profit factor (- when there were no losses), the maximum drawdown, the Sharpe ratio and the largest win and loss, next to the equity curve. The panel never computes - it reads BacktestResult.

import { BacktestPanel } from '@unifin/chart-react/pro';

<BacktestPanel result={result} locale="en" formatMoney={(value) => value.toFixed(2)} />

From the chart

Setting a strategy from the chart is the same composition the editor above demonstrates: the gallery (or the host's own dialog) hands a strategy source to the host, the host parses it, runs the backtest and paints the entries and exits next to the bars. The language stays declarative, so the host keeps every platform gate - orders still leave only through TradingAdapter and the six trading-ms types. The text the trader types goes through the same parseStrategy, so an unknown condition or parameter comes back as a problem with its line and column, never as executed code.

Whole strategy presets live in the template gallery: the EMA cross, the range breakout and the mean reversion are declarative sources of @unifin/chart-core/studies. See Research studies for the gallery and the study contract.

On this page