To convert thinkScript to Pine Script v6 without breaking your signals, translate the syntax first, then audit four execution differences between thinkorswim and TradingView: recursive def state, higher-timeframe AggregationPeriod locks, folded plot declarations, and AddOrder next-bar fills. Paste your code or drop an exported *STUDY.ts / .zip file into the converter above to draft the Pine v6 script locally in your browser; if you only need a quick syntax lookup table, see our standalone thinkScript to Pine Script converter reference.
Three checks separate a clean TradingView port from a naive AI rewrite that compiles yet plots wrong numbers:
- Zero vs
nawarm-up. thinkScript treats uninitializedx[1]history as0in arithmetic; Pine v6 propagatesnaforever unless wrapped innz(). - Completed higher-timeframe bars.
AggregationPeriod.DAYwithout[1]shifts all day long; pair[1]withbarmerge.lookahead_oninsiderequest.security()for yesterday's finished level. - Extended-hours session bars. An intraday EMA or VWAP on thinkorswim with Show Extended-Hours Trading Session unchecked will never match a TradingView chart set to Electronic (ETH) hours until both charts use the same session template.
How do you export a .ts study from thinkorswim?
You do not need to retype code from screenshots. Inside desktop thinkorswim:
- Open a chart and click Studies (the beaker icon) → Edit Studies...
- Locate your script on the Studies or Strategies tab, right-click it, and choose Export...
- thinkorswim saves a plain-text UTF-8 file named
<Name>STUDY.tsor<Name>STRATEGY.ts(note that.tshere is plain thinkScript text, not TypeScript). - Drag that
*STUDY.tsfile—or a.zipbundle of exported studies—onto the converter above, or click Upload .ts / .zip. Everything runs in browser memory; your proprietary rules are never uploaded to a server.
(Built-in Charles Schwab / thinkorswim studies with a padlock icon allow viewing source on open studies via double-click, while locked vendor studies hide their source code just like TradingView invite-only scripts.)
How do thinkScript declarations and recursive def map to Pine v6?
thinkScript is case-insensitive, coerces numbers to 1/0 booleans freely, and lets any def reference its own [1] value on bar 1. Pine Script v6 (//@version=6) enforces strict bool vs float/int types and evaluates lazy and/or branches conditionally—meaning a ta.* call hidden inside if or and will fail consistency checks unless hoisted to run on every bar.
| thinkScript (thinkorswim) | Pine Script v6 (TradingView) | Why naive ports break |
|---|---|---|
input length = 14; | length = input.int(14, "length") | ta.sma / ta.ema require int, not float |
input avgType = AverageType.WILDERS; | avgType = input.string("WILDERS", ...) + helper switch | Pine has separate ta.sma, ta.ema, ta.rma, ta.wma, ta.hma calls |
def c = if up then c[1] + 1 else 0; | var float c = 0.0 then c := up ? nz(c[1]) + 1 : 0 | Without nz(c[1]), na + 1 stays na on every bar in Pine |
def x = CompoundValue(1, x[1] * 0.9, close); | float x = na then x := bar_index < 1 ? close : nz(x[1]) * 0.9 | CompoundValue seeds bar 1 explicitly (initExpr is argument 3, stepExpr is argument 2) |
def ok = close - open; then if ok then ... | ok = close - open then nz(ok) != 0 ? ... | Pine v6 removed implicit numeric-to-bool truthiness (Pine v6 migration guide) |
def sig = a > b and c crosses above Average(c, 9); | bool _x = ta.crossover(c, ta.sma(c, 9)) then sig = a > b and _x | ta.crossover & ta.sma must execute on every bar, never inside short-circuit and |
How do you convert AggregationPeriod without repainting?
In thinkScript, timeframe overrides sit inline on price series: high(period = AggregationPeriod.DAY) or Average(close(period = AggregationPeriod.HOUR), 20).
There are two distinct cases when porting to Pine Script v6:
- Completed prior higher-timeframe bar (
[1]) — zero repaint: When a thinkorswim study marks yesterday's high (high(period = AggregationPeriod.DAY)[1]), you want every 5-minute bar of Tuesday to show Monday's final daily high. In Pine v6, put the[1]inside the tuple/expression and setlookahead = barmerge.lookahead_on:prevDayHigh = request.security(syminfo.tickerid, "D", high[1], lookahead = barmerge.lookahead_on)Becausehigh[1]is already closed before the new day begins,lookahead_onaligns Monday's high cleanly starting on Tuesday's very first bar without leaking future prices. - Developing higher-timeframe bar (no
[1]): If your thinkScript readsclose(period = AggregationPeriod.HOUR)live, omitlookahead_on(request.security(syminfo.tickerid, "60", close)), and gate any alert or signal onbarstate.isconfirmedif you only want closed-candle triggers. You can verify any converted script in our Pine Script repaint & v6 checker.
How do plot, AddLabel, AddChartBubble, and AddCloud fold into Pine v6?
thinkScript separates calculation from styling across 3 to 5 statements (plot Avg = ...; Avg.SetDefaultColor(...); Avg.SetPaintingStrategy(...); Avg.SetLineWeight(2);). Pine Script v6 passes all styling into a single plot() or plotshape() call:
- Line & histogram plots: Fold
SetDefaultColor,SetLineWeight, andPaintingStrategy.HISTOGRAM/POINTSintoplot(series, "Title", color = ..., linewidth = 2, style = plot.style_histogram). DynamicAssignValueColor(...)becomes acolorseries variable passed tocolor = .... - Boolean arrows (
BOOLEAN_ARROW_UP/DOWN): Becomeplotshape(cond, style = shape.arrowup, location = location.belowbar, color = ...). - Top-corner HUD badges (
AddLabel): thinkorswim stacksAddLabel(yes, "Trend: Bull", Color.GREEN)boxes across the top-left of the chart. Pine v6 has noAddLabelprimitive; instead, create a singlevar table hud = table.new(position.top_left, ...)and updatetable.cell()onbarstate.islast. - Clouds (
AddCloud(upper, lower, Color.GREEN, Color.RED)): Capture the two plot handles (p1 = plot(upper),p2 = plot(lower)) and pass them tofill(p1, p2, color = upper >= lower ? color.new(color.green, 80) : color.new(color.red, 80)). (Never usetransp = 80—Pine v6 removedtransp.)
Combine multiple thinkorswim studies into a single indicator slot if you are on TradingView's Basic or Essential plan using our Pine Script multi-indicator merger.
How does AddOrder translate to a Pine v6 strategy()?
A classic thinkorswim trap hides inside strategy fill prices. Because thinkorswim historically evaluated AddOrder in ways where authors wanted next-bar-open fills, thousands of public thinkScript strategies write:
AddOrder(OrderType.BUY_AUTO, crossUp, tickColor = GetColor(1), arrowColor = GetColor(1), name = "LE", price = open[-1]);
Notice open[-1]. In an indicator, [-1] is a future-bar leak (1 bar ahead). Inside AddOrder, the author was simply asking thinkorswim to fill at the next bar's open after crossUp closed true!
In Pine Script v6, strategy(..., process_orders_on_close = false) (the default) already fills market orders on the next bar's open after a bar closes! So:
OrderType.BUY_AUTO→strategy.entry("LE", strategy.long)(reverses any open short automatically, matchingBUY_AUTO).OrderType.BUY_TO_OPEN→if strategy.position_size <= 0+strategy.entry(...)(or standardstrategy.entrywhen non-pyramiding).OrderType.SELL_TO_CLOSE→strategy.close("LE").- Always set realistic
commission_type,commission_value, andslippageinsidestrategy()—thinkorswim's Floating P/L report defaults to zero friction unless configured. If your end goal is automated execution on MetaTrader 5 rather than TradingView, take your verified Pine v6 code into our Pine Script to MQL5 converter.
Worked example: clean-room Pine v6 port of a thinkorswim Prior-Day + ATR Trail study
Below is a complete, runnable Pine Script v6 indicator that demonstrates all four patterns together: non-repainting prior-day high/low (AggregationPeriod.DAY[1]), Wilder's ATR (WildersAverage(TrueRange(...), 14)), CompoundValue-style var float state ratcheting, a top-right AddLabel HUD table, and closed-bar barstate.isconfirmed alerts. Compare its structure with our production Opening Range Desk in Pine Pro Library.
//@version=6
indicator("Prior-Day Levels + Wilder ATR Trail (thinkScript Port)", shorttitle = "PD + ATR v6", overlay = true)
atrLen = input.int(14, "Wilder ATR Length", minval = 1)
mult = input.float(2.5, "ATR Trail Multiplier", minval = 0.5, step = 0.1)
showPrevDay = input.bool(true, "Show Prior Day High / Low")
showHud = input.bool(true, "Show Top-Right AddLabel HUD")
// 1. AggregationPeriod.DAY[1] -> completed prior-day levels without repainting
[pdHigh, pdLow] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead = barmerge.lookahead_on)
// 2. WildersAverage(TrueRange(high, close, low), 14) -> ta.atr(atrLen)
atrVal = ta.atr(atrLen)
longBand = hl2 - mult * atrVal
shortBand = hl2 + mult * atrVal
// 3. CompoundValue / recursive def -> explicit var float + := with nz()
var float trail = na
var int dir = 1
prevTrail = nz(trail[1], longBand)
prevDir = nz(dir[1], 1)
if prevDir == 1
trail := close < prevTrail ? shortBand : math.max(longBand, prevTrail)
dir := close < prevTrail ? -1 : 1
else
trail := close > prevTrail ? longBand : math.min(shortBand, prevTrail)
dir := close > prevTrail ? 1 : -1
flippedBull = barstate.isconfirmed and dir == 1 and prevDir == -1
flippedBear = barstate.isconfirmed and dir == -1 and prevDir == 1
// 4. Folded plots +BOOLEAN_ARROW_UP / DOWN equivalents
trailColor = dir == 1 ? color.teal : color.orange
plot(trail, "ATR Trail", color = trailColor, linewidth = 2)
plot(showPrevDay ? pdHigh : na, "Prior Day High", color = color.new(color.blue, 35), style = plot.style_steplinebr)
plot(showPrevDay ? pdLow : na, "Prior Day Low", color = color.new(color.purple, 35), style = plot.style_steplinebr)
plotshape(flippedBull, "Confirmed Bull Flip", shape.triangleup, location.belowbar, color.teal, size = size.tiny)
plotshape(flippedBear, "Confirmed Bear Flip", shape.triangledown, location.abovebar, color.orange, size = size.tiny)
// 5. AddLabel(...) -> Pine v6 table HUD updated on the last bar
var table hud = table.new(position.top_right, 2, 2, bgcolor = color.new(color.black, 20), border_width = 1)
if showHud and barstate.islast
table.cell(hud, 0, 0, "Regime", text_color = color.silver, text_size = size.small)
table.cell(hud, 1, 0, dir == 1 ? "BULL TRAIL" : "BEAR TRAIL", text_color = trailColor, text_size = size.small)
table.cell(hud, 0, 1, "Prior Day H / L", text_color = color.silver, text_size = size.small)
table.cell(hud, 1, 1, str.tostring(pdHigh, format.mintick) + " / " + str.tostring(pdLow, format.mintick), text_color = color.white, text_size = size.small)
alertcondition(flippedBull, "Closed-Bar Bull Trail Flip", "ATR Trail flipped bullish on bar close")
alertcondition(flippedBear, "Closed-Bar Bear Trail Flip", "ATR Trail flipped bearish on bar close")
What cannot convert 1-to-1 (and how to finish TODO lines)
Six thinkorswim constructs have no direct 1-to-1 line in Pine Script v6:
- Future-bar plot offsets (
close[-1],high[-2]): Used inside swing-pivot studies on thinkorswim; replace with causalta.pivothigh(left, right)/ta.pivotlow(left, right)drawn withoffset = -rightoncerightbars confirm. - Options & chain feeds (
imp_volatility(),open_interest(),GetATMOption()): TradingView does not expose option-chain Greeks inside Pine on standard underlying charts. - Full-chart two-pass functions (
HighestAll(),LowestAll(),InertiaAll()): thinkorswim scans the entire loaded chart before bar 1; in Pine v6, replace running extremes withta.max(high)/ta.min(low)or draw full-history regressions usingline.newonbarstate.islast. - Closed-source thinkorswim studies (
TTM_Squeeze(),ZigZagHighLow()): Rebuild from open math—for example,TTM_Squeezeis a 20-period2.0Bollinger Band inside a1.5Keltner Channel (covered line by line in our Squeeze Momentum settings code read). - Intrabar
vwapfundamental price: thinkorswim provides per-barvwap; Pine v6 substituteshlc3per bar and usesta.vwap(hlc3)for session-anchored VWAP. - Portfolio functions (
GetQuantity(),GetAveragePrice()): Map only insidestrategy()viastrategy.position_sizeandstrategy.position_avg_price(never insideindicator()).
Whenever the converter encounters one of those six constructs, it emits a typed placeholder so the rest of your Pine v6 file still compiles, highlights the line in amber, and packages every flagged note when you click Copy AI Port Spec—ready to paste into Claude or Cursor alongside Pine Fixer.
Frequently asked questions
How do I export a study from thinkorswim to convert to Pine Script?
In thinkorswim, click Studies, Edit Studies, right-click your custom study or strategy, and click Export to save a plain-text file ending in STUDY.ts or STRATEGY.ts. Drop that .ts file (or a .zip archive containing it) directly into the converter above—no code leaves your browser.
How do recursive def and CompoundValue translate to Pine Script v6?
In thinkScript, def trail = trail[1] + 1 initializes prior bars to 0 automatically, and CompoundValue(1, stepExpr, initExpr) seeds bar 1 explicitly. In Pine Script v6, self-referencing series must be declared first (for example var float trail = na) and reassigned with := using nz(trail[1]) so na does not propagate across the entire chart.
How do I convert AggregationPeriod.DAY without repainting in Pine Script v6?
In thinkScript, high(period = AggregationPeriod.DAY)[1] reads yesterday's completed daily high. In Pine Script v6, write request.security(syminfo.tickerid, 'D', high[1], lookahead = barmerge.lookahead_on). Offsetting by 1 inside the expression before enabling lookahead locks every intraday bar onto the finished prior day without leaking today's unfinished high.
Why does thinkorswim AddOrder use open[-1] and what is the Pine Script v6 equivalent?
Many thinkorswim strategies pass open[-1] as the price argument in AddOrder(OrderType.BUY_AUTO, condition, open[-1]) to simulate filling at the next bar's open after a signal bar closes. Pine Script v6 strategies already fill market orders at the next bar's open by default when process_orders_on_close is false, so strategy.entry('Buy', strategy.long) inside if condition matches that fill timing without reading future bars.
Why do WildersAverage and ExpAverage numbers differ slightly after porting?
ExpAverage maps to ta.ema and WildersAverage maps to ta.rma in Pine Script v6. Both formulas match after warm-up, whereas early bars on short chart histories can differ by a few ticks if thinkorswim's chart loads a different number of pre-session or extended-hours bars than TradingView.
What thinkScript functions cannot convert 1-to-1 into Pine Script v6?
Negative future-bar offsets such as close[-1] inside indicator plots, thinkorswim-only options feeds such as imp_volatility and open_interest, full-chart passes such as HighestAll(), and closed-source studies such as TTM_Squeeze() have no direct 1-to-1 call in Pine. The converter marks those exact lines with TODO(thinkScript) and packages them into Copy AI Port Spec so the rest of your script still compiles.
![Explainer diagram titled thinkScript to Pine v6, line for line: four side-by-side rows mapping thinkorswim CompoundValue recursive state, AggregationPeriod.DAY[1] higher-timeframe reads, multi-statement plot styling, and AddOrder(OrderType.BUY_AUTO) strategy orders into verified TradingView Pine Script v6.](/_next/image?url=%2Fblog%2Fthinkscript-to-pine-script.jpg&w=3840&q=75&dpl=dpl_BiEhRQzj8TcRZ2HYquKCfA5CnSZb)


