Pine Script v6 Migration Guide: v5 Changes and AI Fixes
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).
- Open this v6 strategy in the free browser judge to check sealed trades, drawdown, and fee impact.
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:
- Keeping
when=insidestrategy.entry()orstrategy.close(). Move the condition into anifblock. - Wrapping booleans in
nz()orna()(such asnz(buySignal[1], false)). Remove the wrapper; shifted booleans default tofalsein v6. - Using an integer as a condition (
if bar_indexorif state). Writeif bar_index > 0orif state != 0. - Placing
ta.*calls insideifor afterand/or. Move all indicator calls to the global scope. - 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 usewhen=in strategy calls, never passbooltona()ornz(), use explicit comparisons for numbers, wrap truncating integer division inint(), and compute allta.*calls in global scope beforeif,and, oror.
Migration workflow and exact browser judge behavior
Separate compilation checks (in TradingView's Pine Editor) from out-of-sample testing:
- Record your v5 trade count, drawdown, and net profit in TradingView's Strategy Tester.
- Use the Pine Editor's Convert code to v6 action, then audit divisions,
forbounds,strategy.exit()pairs, andand/orexpressions. - Confirm clean v6 compilation and matching trades in TradingView before changing any rule.
- 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, andfill_orders_on_standard_ohlc. - Judged, with a warning: under
//@version=6, the judge still runswhen=,nz(bool, false)andif 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()andlog.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 BTCUSDT1d(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.