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.
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): Declaringindicator(..., overlay=false)orstrategy(..., overlay=false)emitsctx.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, andlangModeonstate.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.txtfiles. - Built-in
pine_emaStarter Template: Available directly in the editor Templates dropdown for instant experimentation.
//@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)
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.
// 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.
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.
//@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:
barIndexand resolved candlebarTimealongside formatted message text and severity level (info,warn,error). - Ring/Cap Safety (
MAX_SCRIPT_LOGS = 500): Per script run, up to500structured log rows are retained to keep panning/zooming at 60 FPS without flooding DOM memory. - Deduplicated
cl:script-logsStreaming: The canvas renderer caches the latest log payloads onwindow._clScriptRuntimeLogsand dispatches deduplicatedCustomEvent('cl:script-logs')notifications picked up live by the Script Editor console.
7. Console Filtering: Pine Logs Pill, Dates & #bar Search
Inside the bottom Console Inspector, Pine runtime logs can be sliced alongside standard compiler diagnostics:
- Pine Logs Filter Pill: Toggle the dedicated
Pine Logspill (plus Info / Warn / Error severity toggles) to isolate per-bar script logs from system messages. - From / To Timestamp Range: Filter logs to a specific historical date/time window matching each log entry's candle timestamp (`barTime`).
- Text, Script &
#barIndex Search: Search by log message text, indicator name, timestamp string, or jump straight to a bar number by typing e.g.#245orbar #245.
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):
- Minimizes the editor modal temporarily so you can inspect the price action unobstructed.
- Centers
visibleBarsaround the target bar index and renders an 8-second luminous chart highlight band on that candle colored by log severity. - 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).
9. Value Conditionals, Countdown Loops & Tuples
Version 1.0.6 closes the key Pine v5/v6 control-flow gaps cleanly inside the transpiler:
// 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:
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.