Skip to main content
← Back to blog

Pine Script v6 Migration Guide: v5 Changes and AI Fixes

📅 Published
✍️ Strategy Arena
TradingView Pine Script Pine Script v6 migration backtest AI coding

Migrating a TradingView strategy from Pine Script v5 to v6 requires replacing the removed when= parameter with if blocks, removing na() or nz() calls on booleans, writing explicit comparisons instead of numeric truthiness, wrapping constant integer divisions in int() when truncation is intended, and moving history-dependent functions out of lazy and or or expressions. TradingView released Pine Script v6 in December 2024 as its current standard, while keeping v5 scripts running until you upgrade.

You can run this guide's main v6 strategy in the free browser judge on BTCUSDT 1d candles (0.10% fees per side, final 20% unseen).

Published 29 November 2026. Educational research on past data, not investment advice.

What changed between Pine Script v5 and v6

TradingView's official migration guide (To Pine Script version 6) and release notes detail a focused set of breaking changes and structural upgrades:

Area Pine Script v5 Pine Script v6 (official TradingView docs)
Booleans and na bool could hold na; na(), nz(), fixnan() accepted bool Strictly true or false; na(), nz(), fixnan() reject bool
Numeric truthiness int and float cast implicitly to bool Implicit casting removed; write flag > 0 or bool(x)
Logical and / or Strict: both sides evaluated on every bar Lazy (short-circuit): right side skipped once outcome is known
when= parameter Deprecated, still accepted in strategy.*() Removed; use standard if blocks
const int division 19 / 2 truncated to integer 9 Returns float 9.5; wrap with int(19 / 2) for integer truncation
request.*() calls Static unless dynamic_requests=true was set dynamic_requests=true by default; callable in loops and if blocks
9,000-order limit Exceeding 9,000 orders halted with a runtime error Automatically trims the oldest trades instead of stopping
Default margin margin_long and margin_short defaulted to 0 Both default to 100
strategy.exit() Absolute targets could override relative ones Evaluates relative and absolute pairs and uses whichever triggers first
for loop bound End boundary evaluated once at loop entry End boundary re-evaluated before every iteration
Negative array indices Required array.size(arr) - 1 Supported array.*() calls accept -1, -2, and so on
[] and timeframe.period [] worked on literals and UDT fields; "D" valid [] disallowed on literals and UDT fields; "1D" includes multiplier

Before and after: migrating a v5 strategy to clean v6

This legacy v5 script combines four patterns that TradingView's v6 compiler rejects: 19 / 2 used as an EMA length, calling nz() on a boolean, testing an integer directly as a condition, and passing when= to strategy.entry() and strategy.close().

Before — legacy v5 code (compiles in v5, fails compilation in TradingView v6):

//@version=5
// BEFORE (v5): compiles in v5, fails in TradingView v6 (int division, when=, nz on bool, int as bool)
strategy("EMA 9/21 v5 legacy", overlay=true,
     initial_capital=10000,
     default_qty_type=strategy.percent_of_equity,
     default_qty_value=100,
     commission_type=strategy.commission.percent,
     commission_value=0.1)

fastLen   = 19 / 2
slowLen   = input.int(21, "Slow EMA", minval=5)
fast      = ta.ema(close, fastLen)
slow      = ta.ema(close, slowLen)
trendFlag = close > slow ? 1 : 0
crossUp   = nz(ta.crossover(fast, slow), false)

strategy.entry("Long", strategy.long, when=trendFlag and crossUp)
strategy.close("Long", when=ta.crossunder(fast, slow))

Look at fastLen = 19 / 2. In TradingView v5, dividing two integer constants truncated the result, so 19 / 2 gave 9 (EMA 9/21). In v6 the same division returns the float 9.5, and ta.ema() refuses a float length: the script no longer compiles. The fix is not cosmetic: writing 9.5 or rounding it to 10 would silently change the rule. Wrap the division in int() to keep the original length.

After — clean Pine Script v6 strategy:

//@version=6
strategy("EMA 9/21 v6 Clean", overlay=true,
     initial_capital=10000,
     default_qty_type=strategy.percent_of_equity,
     default_qty_value=100,
     commission_type=strategy.commission.percent,
     commission_value=0.1)

fastLen   = int(19 / 2)
slowLen   = input.int(21, "Slow EMA", minval=5)
fast      = ta.ema(close, fastLen)
slow      = ta.ema(close, slowLen)
trendFlag = close > slow ? 1 : 0
crossUp   = ta.crossover(fast, slow)
crossDn   = ta.crossunder(fast, slow)

if trendFlag > 0 and crossUp
    strategy.entry("Long", strategy.long)
if crossDn
    strategy.close("Long")

Run in the judge on BTCUSDT 1d (10 bps per side), int(19 / 2) restores exact length 9 and returns 16 sealed trades and +2.87% (No evidence of an edge yet: 3 of 4 steps passed).

Lazy evaluation in v6 (and / or short-circuiting)

In v6, if trend and ta.crossover(fast, slow) skips the right-hand side whenever trend is false. That safely guards array.size(arr) > 0 and array.get(arr, 0) > 0, but skipping history-dependent calls (ta.ema(), ta.rsi(), ta.crossover(), or tuples like ta.dmi()) leaves gaps in their rolling state. For tuple history indexing, see using [1] on ta.dmi, ta.macd and other tuples.

Evaluate every indicator and crossover once in the global scope before if:

//@version=6
strategy("EMA 9/21 + EMA 50 Filter v6", overlay=true,
     initial_capital=10000,
     default_qty_type=strategy.percent_of_equity,
     default_qty_value=100,
     commission_type=strategy.commission.percent,
     commission_value=0.1)

fast    = ta.ema(close, 9)
slow    = ta.ema(close, 21)
trend   = close > ta.ema(close, 50)
// Evaluate history-dependent calls on every bar before lazy `and`
crossUp = ta.crossover(fast, slow)
crossDn = ta.crossunder(fast, slow)

if trend and crossUp
    strategy.entry("Long", strategy.long)
if crossDn
    strategy.close("Long")

In the judge on BTCUSDT 1d (10 bps per side), this EMA 50 filter records 11 sealed trades and −5.14% (No evidence of an edge, for now).

enum, input.enum(), and negative array indices

Enumerations (enum with input.enum()) replace error-prone string menus, while v6 negative indices let array.get(closes, -1) fetch the last bar directly:

//@version=6
strategy("EMA/SMA Enum + Negative Index v6", overlay=true,
     initial_capital=10000,
     default_qty_type=strategy.percent_of_equity,
     default_qty_value=100,
     commission_type=strategy.commission.percent,
     commission_value=0.1)

enum MaKind
    ema = "EMA"
    sma = "SMA"

maKind = input.enum(MaKind.ema, "Moving average")
var closes = array.new_float()
array.push(closes, close)
if array.size(closes) > 30
    array.shift(closes)

lastClose = array.size(closes) > 0 ? array.get(closes, -1) : close
fast = maKind == MaKind.ema ? ta.ema(lastClose, 9) : ta.sma(lastClose, 9)
slow = maKind == MaKind.ema ? ta.ema(close, 21) : ta.sma(close, 21)

if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long)
if ta.crossunder(fast, slow)
    strategy.close("Long")

On BTCUSDT 1d (10 bps per side), the judge runs this v6 script and produces 16 sealed trades and +2.87% (No evidence of an edge yet: 3 of 4 steps passed).

Five Pine Script v6 bugs frequent in AI-generated code

ChatGPT, Claude, and Grok frequently emit a //@version=6 header paired with v5 habits:

  1. Keeping when= inside strategy.entry() or strategy.close(). Move the condition into an if block.
  2. Wrapping booleans in nz() or na() (such as nz(buySignal[1], false)). Remove the wrapper; shifted booleans default to false in v6.
  3. Using an integer as a condition (if bar_index or if state). Write if bar_index > 0 or if state != 0.
  4. Placing ta.* calls inside if or after and/or. Move all indicator calls to the global scope.
  5. Applying [] to a UDT field (myObj.val[1]) or duplicating a parameter name. Copy the field to a local variable first.

Append this rule to your AI prompt to prevent those compiler errors:

Write strictly valid TradingView Pine Script v6 (//@version=6). Never use when= in strategy calls, never pass bool to na() or nz(), use explicit comparisons for numbers, wrap truncating integer division in int(), and compute all ta.* calls in global scope before if, and, or or.

Migration workflow and exact browser judge behavior

Separate compilation checks (in TradingView's Pine Editor) from out-of-sample testing:

  1. Record your v5 trade count, drawdown, and net profit in TradingView's Strategy Tester.
  2. Use the Pine Editor's Convert code to v6 action, then audit divisions, for bounds, strategy.exit() pairs, and and/or expressions.
  3. Confirm clean v6 compilation and matching trades in TradingView before changing any rule.
  4. Test on held-out data via our free out-of-sample guide on TradingView Basic or the free browser judge.

Tested directly on the production judge (sa_pine_vm, BTCUSDT 1d):

  • Accepted: //@version=6, enum + input.enum(), dynamic_requests=true, array.get(arr, -1), int(19 / 2), barstate.isconfirmed, barstate.isrealtime, varip, calc_on_every_tick, and fill_orders_on_standard_ohlc.
  • Judged, with a warning: under //@version=6, the judge still runs when=, nz(bool, false) and if intVar, and shows a warning on the line concerned, because TradingView v6 will not compile them. Fix those lines before going back to TradingView.
  • Ignored: log.info(), log.warning() and log.error() (Pine Logs) have no effect on orders; the judge skips them, so you can paste the script as it is:
//@version=6
// Valid in TradingView v6 (Pine Logs); the browser judge skips log.info
strategy("EMA 9/21 with log.info", overlay=true,
     initial_capital=10000,
     default_qty_type=strategy.percent_of_equity,
     default_qty_value=100,
     commission_type=strategy.commission.percent,
     commission_value=0.1)

fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
if ta.crossover(fast, slow)
    log.info("Long entry")
    strategy.entry("Long", strategy.long)
if ta.crossunder(fast, slow)
    strategy.close("Long")

Next steps: 7 free checks for a reliable TradingView backtest, 5 measured reasons a Pine strategy loses live, and fixing repainting in Pine Script.

FAQ

What breaks frequently when migrating a Pine Script v5 strategy to v6?

Four v5 patterns stop compiling in TradingView v6: the removed when= parameter in strategy calls, passing a bool to na() or nz(), using an int or float directly as a boolean condition, and relying on const int division to truncate toward zero without int().

Does TradingView provide an automatic converter from Pine Script v5 to v6?

Yes. The Pine Editor includes a Convert code to v6 action that handles syntax updates, though scripts relying on lazy evaluation side effects, integer division, or loop bounds still need manual review.

Why do ChatGPT and Claude generate Pine Script v6 code that fails to compile?

Language models mix v5 and v6 habits: they write //@version=6 on the first line while still emitting strategy.entry(..., when=...), nz(boolCond, false), or if flag on an integer variable.

Does the free Strategy Arena browser judge accept Pine Script v6?

Yes. The browser judge runs //@version=6 scripts, enum declarations with input.enum(), dynamic_requests=true, and negative array indices. It warns on legacy syntax that TradingView v6 refuses, and skips Pine Logs such as log.info().

How does lazy evaluation of and/or affect indicators in Pine Script v6?

In v6, if the left side of an and expression is false, the right side is skipped on that bar. Moving history-dependent calls like ta.crossover() or ta.ema() to the global scope ensures they update on every bar.

Sources

  • TradingView Pine Script User Manual, To Pine Script version 6 (https://www.tradingview.com/pine-script-docs/migration-guides/to-pine-version-6/), consulted 29 November 2026.
  • TradingView Pine Script User Manual, Release notes (https://www.tradingview.com/pine-script-docs/release-notes/), consulted 29 November 2026.
  • Strategy Arena production judge (sa_pine_vm) runs on BTCUSDT 1d (10 bps per side, final 20% sealed window), 29 November 2026.

Research on past data, not investment advice. Past results do not guarantee future results.

⚠️ Disclaimer — This article is for informational and educational purposes only. It does not constitute investment advice or a buy/sell recommendation. Past performance does not guarantee future results. Strategy Arena is an educational simulator with virtual capital. Always do your own research before making investment decisions.

Enjoyed this article? Share it

𝕏 Share on X ✈️ Telegram

Turn a local result into durable proof

The Lab runs free on your PC. Certificates and audit dossiers use credits: 1 credit = 1 certificate or 1 dossier, 2 offered when you open an account; paying never changes the verdict.

Get the Lab (free)Audit a TradingView export Pricing and credits Publish a Lab Report Lab Reports Hall
TradingView Starter
Choose the account path. Prove the strategy separately.
Your first chart and price alert do not require the Lab. Strategy Arena proof remains required before trusting or exporting a strategy.
Partner attribution is for first-time users and web purchases only. Strategy Arena may earn a commission on eligible purchases; starting with a free account needs no payment.
I have never had an account · Start free I already have an account Check a strategy
More TradingView paths
Evidence-gated Pine review