Complete Suite: all 12 tools. 6 Premium desks inside.All 12 tools $606.98 one by one

$606.98 one by one $97 once Save $509.98Get the SuiteGet it
ProEA Lab · MT5, TradingView and trading research · Evidence standards

How to Convert thinkScript to Pine Script v6 (thinkorswim Port Guide)

Paste a thinkorswim study or strategy below (or drop a *STUDY.ts / .zip export) to translate it into Pine Script v6 locally in your browser, trace every line back to thinkScript, or copy a structured AI Port Spec.

Pine Script v6numbers: its thinkScript line

// Converted from thinkScript with ProEA's thinkScript to Pine converter.
// TradingView's compiler is the final word: paste it into the Pine Editor and add it to a chart.
//@version=6
indicator("EMA cross with arrows and a label", overlay = true)
// EMA cross with arrows and a label
fastLength = input.int(9, "fastLength")
slowLength = input.int(21, "slowLength")
price = input.source(close, "price")
fastAvg = ta.ema(price, fastLength)
slowAvg = ta.ema(price, slowLength)
Fast = fastAvg
Slow = slowAvg
BuySignal = ta.crossover(fastAvg, slowAvg)
SellSignal = ta.crossunder(fastAvg, slowAvg)
alertcondition(BuySignal, "EMA cross up", "EMA cross up")
p_Fast = plot(Fast, "Fast", color = #00FFFF)
p_Slow = plot(Slow, "Slow", color = #FFC800, linewidth = 2)
plotshape(BuySignal, "BuySignal", shape.arrowup, location.belowbar, color = #00FF00, size = size.small)
plotshape(SellSignal, "SellSignal", shape.arrowdown, location.abovebar, color = #FF0000, size = size.small)
fill(p_Fast, p_Slow, color = Fast > Slow ? color.new(#00FF00, 70) : color.new(#FF0000, 70))
var table _labels = table.new(position.top_left, 1, 1)
table.cell(_labels, 0, 0, fastAvg > slowAvg ? "Trend: up" : "Trend: down", bgcolor = fastAvg > slowAvg ? #00FF00 : #FF0000, text_color = color.black, text_size = size.small)

An indicator

All 19 statements converted to Pine v6

Our Pine checker finds nothing to fix. TradingView's compiler is the final word.

  • Notepick this condition in TradingView's alert dialog; the sound is chosen there too
PL · 8 min read
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.

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:

  1. Zero vs na warm-up. thinkScript treats uninitialized x[1] history as 0 in arithmetic; Pine v6 propagates na forever unless wrapped in nz().
  2. Completed higher-timeframe bars. AggregationPeriod.DAY without [1] shifts all day long; pair [1] with barmerge.lookahead_on inside request.security() for yesterday's finished level.
  3. 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:

  1. Open a chart and click Studies (the beaker icon) → Edit Studies...
  2. Locate your script on the Studies or Strategies tab, right-click it, and choose Export...
  3. thinkorswim saves a plain-text UTF-8 file named <Name>STUDY.ts or <Name>STRATEGY.ts (note that .ts here is plain thinkScript text, not TypeScript).
  4. Drag that *STUDY.ts file—or a .zip bundle 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 switchPine 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 : 0Without 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.9CompoundValue 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 _xta.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:

  1. 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 set lookahead = barmerge.lookahead_on: prevDayHigh = request.security(syminfo.tickerid, "D", high[1], lookahead = barmerge.lookahead_on) Because high[1] is already closed before the new day begins, lookahead_on aligns Monday's high cleanly starting on Tuesday's very first bar without leaking future prices.
  2. Developing higher-timeframe bar (no [1]): If your thinkScript reads close(period = AggregationPeriod.HOUR) live, omit lookahead_on (request.security(syminfo.tickerid, "60", close)), and gate any alert or signal on barstate.isconfirmed if 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, and PaintingStrategy.HISTOGRAM / POINTS into plot(series, "Title", color = ..., linewidth = 2, style = plot.style_histogram). Dynamic AssignValueColor(...) becomes a color series variable passed to color = ....
  • Boolean arrows (BOOLEAN_ARROW_UP / DOWN): Become plotshape(cond, style = shape.arrowup, location = location.belowbar, color = ...).
  • Top-corner HUD badges (AddLabel): thinkorswim stacks AddLabel(yes, "Trend: Bull", Color.GREEN) boxes across the top-left of the chart. Pine v6 has no AddLabel primitive; instead, create a single var table hud = table.new(position.top_left, ...) and update table.cell() on barstate.islast.
  • Clouds (AddCloud(upper, lower, Color.GREEN, Color.RED)): Capture the two plot handles (p1 = plot(upper), p2 = plot(lower)) and pass them to fill(p1, p2, color = upper >= lower ? color.new(color.green, 80) : color.new(color.red, 80)). (Never use transp = 80—Pine v6 removed transp.)

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, matching BUY_AUTO).
  • OrderType.BUY_TO_OPEN → if strategy.position_size <= 0 + strategy.entry(...) (or standard strategy.entry when non-pyramiding).
  • OrderType.SELL_TO_CLOSE → strategy.close("LE").
  • Always set realistic commission_type, commission_value, and slippage inside strategy()—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:

  1. Future-bar plot offsets (close[-1], high[-2]): Used inside swing-pivot studies on thinkorswim; replace with causal ta.pivothigh(left, right) / ta.pivotlow(left, right) drawn with offset = -right once right bars confirm.
  2. Options & chain feeds (imp_volatility(), open_interest(), GetATMOption()): TradingView does not expose option-chain Greeks inside Pine on standard underlying charts.
  3. Full-chart two-pass functions (HighestAll(), LowestAll(), InertiaAll()): thinkorswim scans the entire loaded chart before bar 1; in Pine v6, replace running extremes with ta.max(high) / ta.min(low) or draw full-history regressions using line.new on barstate.islast.
  4. Closed-source thinkorswim studies (TTM_Squeeze(), ZigZagHighLow()): Rebuild from open math—for example, TTM_Squeeze is a 20-period 2.0 Bollinger Band inside a 1.5 Keltner Channel (covered line by line in our Squeeze Momentum settings code read).
  5. Intrabar vwap fundamental price: thinkorswim provides per-bar vwap; Pine v6 substitutes hlc3 per bar and uses ta.vwap(hlc3) for session-anchored VWAP.
  6. Portfolio functions (GetQuantity(), GetAveragePrice()): Map only inside strategy() via strategy.position_size and strategy.position_avg_price (never inside indicator()).

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.

Continue reading

WaveTrend Oscillator Settings: LazyBear & VuManChu Cipher B Code, Read Line by Line

What Channel Length, Average Length, Signal SMA and the ±53 / ±60 bands actually compute inside LazyBear's 61,565-boost WaveTrend and VuManChu Cipher B — including line 18's zero-division trap, line 193's volume-free 'VWAP' wave, and a clean Pine Script v6 build.

Nov 11 · ProEA Lab

Explainer cover titled WaveTrend settings, read from the code. Two-pane chart over 60 simulated 15-minute candles comparing LazyBear's 10/21/4 WaveTrend oscillator against VuManChu Cipher B's faster 9/12/3 settings and yellow wt1 minus wt2 spread histogram.

Best Engulfing Candle Indicators on TradingView (2026), Code-Read.

We read the code of the 16 most-boosted open-source engulfing candle scripts on TradingView, and TradingView's own: which test the body and which the range, which need opposite colours, a bigger body, a trend or volume, and which mark the candle before it has closed.

Oct 31 · ProEA Lab

Explainer cover titled Best engulfing candle indicators, code-read: a table of the six most-boosted open-source TradingView engulfing scripts with ticks, crosses and halves for three checks: whether the new body covers the last body, whether the two candles must be opposite colours, and whether the script waits for the candle to close.

Best Power of 3 Indicators on TradingView (2026), Code-Read.

We read the code of the 15 most-boosted open-source power of 3 (PO3, AMD) scripts on TradingView: which higher-timeframe candle each one profiles, where it puts the open and what it calls the manipulation, which clock starts its day, and when it decides.

Oct 31 · ProEA Lab

Explainer cover titled Best power of 3 indicators, code-read: a table of the six most-boosted open-source TradingView power of 3 and AMD scripts with ticks, crosses and halves for three checks: whether the script draws the higher-timeframe candle beside the chart, whether it measures the manipulation from the open, and whether its day opens at midnight New York. None of the six opens the day at midnight New York.