Implicit Execution & Proxies
The BacktestX script engine natively supports Pine Script-style "Implicit Execution". You can run JS inside an automatic bar loop using ctx.run(), write Direct Pine Script auto-compiled via compileScriptSource(), and access historical series through bounds-checked bracket syntax like close[1].
Using ctx.run()
Instead of manually writing for(let i = bounds.startIndex; i <= bounds.endIndex; i++), you can wrap your time-series logic inside a ctx.run() callback. The engine will loop over all bars for you.
ctx.run((bar, state) => {
// Logic executes on every bar!
});
State Persistence (The 'var' keyword)
In Pine Script, you use the var or varip keyword to initialize a variable once and persist it across bars. In raw JavaScript ctx.run() mode, you use the state object.
ctx.run((bar, state) => {
// Initialize only if undefined
state.crossCount = state.crossCount ?? 0;
if (ctx.ta.crossover(bar.close, ctx.ta.sma(ctx.bars.map(b => b.close), 14))[bar.index]) {
state.crossCount++;
}
});
JavaScript Proxies (close[1])
The bar object passed into the callback contains properties for open, high, low, close, and volume. These are not standard numbers; they are ES6 Proxy Objects.
This allows you to access historical data relative to the current bar by passing a lookback integer into the brackets.
bar.close[0]: The current bar's close price.bar.close[1]: The previous bar's close price.bar.close[10]: The close price 10 bars ago.
Direct Pine Loop & Bounds-Checked Series (v1.0.6)
In BacktestX v1.0.6, you do not have to write ctx.run() manually when coding in Pine Script. In Direct Pine Mode, compileScriptSource() transpiles Pine indicators and strategies directly into a bar-by-bar execution loop with full runtime instrumentation:
- Automatic
ctx._currentIndexsync: Updated on every bar iteration solog.info(),log.warning(), andlog.error()capture accurate bar numbers and timestamps for clickable chart bar navigation. - Bounds-checked
make_seriesproxies: Historical indexing such asclose[1]returnsNaNfor out-of-range lookbacks and blocks negative future offsets at runtime, eliminating accidental lookahead bias. Combine with//@strict-no-repaintfor compile-time diagnostics and Pine source maps. - Automatic
var/varip& Control-Flow Expressions: Top-level and expression-assignedvar/varipbindings, value-returningx = if .../x = switch ...blocks, countdownfor i = 10 to 0 by -1loops, and user-defined methods compile cleanly into the loop.
//@version=5
//@strict-no-repaint
indicator("Implicit Pine Loop", overlay=true)
var int crosses = 0
emaFast = ta.ema(close, 9)
if ta.crossover(close, emaFast)
crosses += 1
log.info("Cross #{0} at close {1}", crosses, close)
plot(emaFast, color=color.blue, linewidth=2)