Exciting Update: Version 1.0.6 is now available, introducing Direct Pine Script Mode, Pine Logs Runtime Bridge, Zero-Repaint Linting, Source Maps, Intrabar MFE/MAE Stats, and expanded Pine v5/v6 Transpiler Parity. Read more
Version: 1.0.6 Pine v5/v6 + ES2020 Dual Engine

Direct Pine Script Mode, Pine Logs & Language Guide

Starting in v1.0.6, you no longer need to run a manual converter modal before running TradingView Pine Script on BacktestX charts. Write Pine v5/v6 code directly in the Script Editor with automatic language detection, live IDE intellisense, streaming Pine Logs with one-click chart bar jumping, and full support for modern control-flow expressions, UDTs, enums, methods, built-in series metadata, and math/string libraries.

Part I — Direct Pine Script Mode & IDE Tooling

1. Auto-Detection & Language Mode Switcher (langModeBtn)

Every editor tab maintains an independent langMode setting ('auto', 'pine', or 'js') reflected by the toolbar button next to the script name input. In the default Auto mode, BacktestX inspects your script header and syntax on every keystroke and switches seamlessly between native JavaScript and Pine Script transpilation.

Button State Label Stored langMode Resolution Behavior
Auto · Pine 'auto' Detected Pine heuristics (e.g. //@version=, indicator(...), strategy(...), study(...), or Pine directives/constructs); compiles cleanly via transpilePineToJSWithMap.
Auto · JS 'auto' No Pine signature found; evaluates directly as native ES2020 Canvas JavaScript with ctx.
Mode · Pine 'pine' Pinned override: forces Pine syntax highlighting, Pine indentation folding, and transpilation even on headerless snippets.
Mode · JS 'js' Pinned override: forces raw JavaScript parsing, highlighting, and evaluation.

Clicking langModeBtn cycles auto -> pine -> js -> auto, immediately re-syncs syntax highlighting, and triggers live gutter linting (runLiveLint).

2. Unified Pipeline, Sub-Panes, Persistence & .pine I/O

All editor workflows—Live Lint, Benchmark Profiler, Save, Run (Add to chart), and Revision History—share a single compilation function: compileScriptSource(rawCode, langMode).

  • Automatic Sub-Pane Routing (overlay=false): Declaring indicator(..., overlay=false) or strategy(..., overlay=false) emits ctx.pane = 'new' and allocates a dedicated lower oscillator pane automatically on run.
  • Editable Pine Source Persistence: Running or saving stores the compiled JS alongside original Pine sourceCode, lang, and langMode on state.customScripts. Reopening a chart script restores your clean editable Pine code rather than transpiled JS.
  • Import & Export Extensions: The file picker and download exporter natively accept .pine, .pinescript, .js, and .txt files.
  • Built-in pine_ema Starter Template: Available directly in the editor Templates dropdown for instant experimentation.
Pine Script (pine_ema starter)
//@version=5
indicator("Pine EMA Cross + Logs", overlay=true)

fastLen = input.int(9, "Fast EMA")
slowLen = input.int(21, "Slow EMA")

fast = ta.ema(close, fastLen)
slow = ta.ema(close, slowLen)

plot(fast, title="Fast EMA", color=color.green, linewidth=2)
plot(slow, title="Slow EMA", color=color.red, linewidth=2)

bullCross = ta.crossover(fast, slow)
plotshape(bullCross, title="Buy", style=shape.triangleup, location=location.belowbar, color=color.green)

if bullCross
    log.info("Bullish EMA cross at {0}", close)

3. IDE Intellisense, Hover Docs, Folding & Formatting

Both JavaScript and Pine tabs benefit from full v1.0.6 editor ergonomics powered by an auto-indexed API catalog plus live AST/symbol scanning of your active script.

Prefix-Ranked Autocomplete

Suggests ctx.ta.*, ctx.log.*, ctx.plot*, ctx.polyline.new, ctx.polygon.new, Pine namespaces (ta.*, strategy.*, log.*, input.*, request.security, na, nz), and locally declared user variables/functions/methods. Trigger manually with Ctrl + Space.

Live Signature Hints (signatureBox)

Whenever your cursor sits inside (...), a floating signature box displays the function's parameter list and highlights the active argument index as you type commas. Dismiss at any time with Escape.

Upgrade Hover Tooltips

Hovering any ctx.* method, Pine built-in, or local symbol shows parameter types, return values, and usage notes via the unified API_DOC_INDEX.

Pine Folding & String-Safe Formatting

Gutter folding understands Pine indentation headers (if, else if, else, for, while, switch, type, enum, method, =>, and multi-line (...)). Pressing Enter inserts 4 spaces under block starters, and Format preserves Pine indent while ignoring braces inside strings/comments.

4. Quote/Comment-Safe Out-of-Order Named Arguments

In standard Pine Script, users frequently reorder named arguments or use short aliases (such as len=, src=, or atrlen=). BacktestX's transpiler masks string literals and strips trailing // comments first, then resolves named parameters against exact signature tables (`PINE_FN_SIGNATURES`) before lowering calls to JS.

Pine Script Named Arguments
// Out-of-order + short alias arguments are automatically reordered
ema20 = ta.ema(length=20, source=hlc3)
[mid, upper, lower] = ta.bb(mult=2.5, length=20, src=close)
[stVal, stDir] = ta.supertrend(atrlen=10, factor=3.0)

// Object-options functions preserve named keys cleanly
lbl = label.new(x=bar_index, y=high, text="len=20 // stays untouched", tooltip="Swing High")

Built-in aliases include src→source, ser→series, len→length, atrlen/atrlength→atrPeriod, left→leftbars, right→rightbars, occ→occurrence, cond→condition, sym→symbol, tf→timeframe, and msg→message.

Part II — Pine Logs Runtime Telemetry & Bar Jump

5. Pine Logging APIs (log.info, log.warning, log.error)

Standard runtime logging works identically in both Pine Script (log.*) and native JavaScript (ctx.log.*). Messages support Pine-style positional placeholders ({0}, {1}, ...) as well as variadic arguments. Numbers format cleanly up to 6 significant decimal digits, and arrays/objects serialize to compact JSON strings.

Pine Script Logging Examples
//@version=5
indicator("Pine Logs Demo", overlay=true)
r = ta.rsi(close, 14)

if r < 30
    log.info("Oversold RSI={0} at close={1}", r, close)
else if r > 80
    log.warning("Extreme overbought RSI={0} on bar {1}", r, bar_index)
else if na(r)
    log.error("RSI unavailable at bar {0}", bar_index)

Note: log.warn(...) is supported as an alias for log.warning(...).

6. Runtime Telemetry Bridge (_currentIndex & cl:script-logs)

During bar replay and chart canvas redraws, the transpiled bar loop keeps ctx._currentIndex = barIdx synchronized on every candle before executing your script body. Each log.* call captures:

  • Exact Bar Metadata: barIndex and resolved candle barTime alongside formatted message text and severity level (info, warn, error).
  • Ring/Cap Safety (MAX_SCRIPT_LOGS = 500): Per script run, up to 500 structured log rows are retained to keep panning/zooming at 60 FPS without flooding DOM memory.
  • Deduplicated cl:script-logs Streaming: The canvas renderer caches the latest log payloads on window._clScriptRuntimeLogs and dispatches deduplicated CustomEvent('cl:script-logs') notifications picked up live by the Script Editor console.

8. Click-to-Chart Bar Highlight & Restore Banner

Every Pine log row displays a clickable Bar #N · YYYY-MM-DD HH:mm badge. Clicking the row triggers highlightBarOnChart(entry):

  1. Minimizes the editor modal temporarily so you can inspect the price action unobstructed.
  2. Centers visibleBars around the target bar index and renders an 8-second luminous chart highlight band on that candle colored by log severity.
  3. Mounts the floating bottom banner (Highlighting Bar #N) with two actions: Back to Script Editor (reopens the editor right where you left off) and Dismiss (clears the highlight).
Part III — Pine v5/v6 Syntax, Types & Built-in Series

9. Value Conditionals, Countdown Loops & Tuples

Version 1.0.6 closes the key Pine v5/v6 control-flow gaps cleanly inside the transpiler:

Pine Control-Flow Expressions
// 1. Value-returning x = if ... else if ... else
bias = if close > open
    1
else if close < open
    -1
else
    0

// 2. Value-returning switch & standalone single/multi-line switch
regimeColor = switch bias
    1 => color.green
    -1 => color.red
    => color.gray

// 3. Countdown for loop (runtime step-sign check)
for i = 10 to 0 by -1
    if close[i] > open[i]
        log.info("Bull bar lookback {0}", i)

// 4. Tuple loop iteration over arrays
for [idx, val] in myArray
    log.info("idx={0} val={1}", idx, val)

// 5. Tuple returns from custom user functions
hlRange(srcH, srcL) =>
    [srcH - srcL, (srcH + srcL) / 2]

[rng, mid] = hlRange(high, low)

10. User-Defined Types (type), enum & method Dispatch

Define structured domain objects using type, typed categorical sets with enum, and type-dispatched dot methods using method with automatic this binding on single-line and multi-line bodies:

Pine UDT, Enum & Method Example
enum SignalBias
    bull = "BULL"
    bear = "BEAR"

type SwingLevel
    int idx
    float price
    SignalBias bias = SignalBias.bull

method isBroken(SwingLevel this, float px) =>
    this.bias == SignalBias.bull ? px < this.price : px > this.price

var lastPivot = SwingLevel.new(idx=bar_index, price=low, bias=SignalBias.bull)
if lastPivot.isBroken(close)
    log.warning("Swing broken at {0}", close)

11. Built-in Price Series, Calendar, barstate.*, syminfo.* & session.*

All core TradingView derived series and chart metadata namespaces are wired into the transpiler header and runtime context:

Category Available Series / Identifiers
Price & Bar Bounds hl2, hlc3, ohlc4, hlcc4, last_bar_index, last_bar_time, timenow
Calendar Functions hour, minute, second, dayofmonth, dayofweek (.sunday=1 .. .saturday=7), month, year, weekofyear (both bar-scalar call & fn(t, tz))
barstate.* isfirst, islast, ishistory, isrealtime, isnew, isconfirmed, islastconfirmedhistory
syminfo.* ticker, tickerid, prefix, root, description, currency, basecurrency, timezone, mintick, pointvalue, type ('crypto'|'forex'|'stock')
session.* session.in_range(t?, sess), session.ismarket, session.ispremarket, session.ispostmarket, session.regular ('0930-1600:23456'), session.extended ('0400-2000:23456')
timeframe.* & ticker.* timeframe.period, timeframe.isintraday/isdaily/isweekly/ismonthly, timeframe.change(tf), ticker.new, ticker.standard, ticker.heikinashi, ticker.renko, ticker.kagi, ticker.pointfigure

12. Expanded math.* & str.* Standard Libraries

math.* Namespace

max, min, abs, ceil, floor, round, pow, sqrt, log, log10, exp, sign, sin, cos, tan, asin, acos, atan, todegrees, toradians, random, sum, avg
Constants: math.pi, math.e, math.phi, math.rphi

str.* Namespace

tostring, tonumber, format, format_time(t, fmt, tz), replace, replace_all, trim, startswith, endswith, contains, split, match, pos, substring, length, lower, upper

Next Recommended Guides

Learn how to enforce zero lookahead leakage with Zero-Repaint Auditing & Source Maps, or configure commissions, slippage, pyramiding, and intrabar excursion stats in Advanced Strategy Accounting & MFE/MAE.