r/pinescript • • 1h ago

PO3, CISD, FVG Set.

Post image
1 Upvotes

Estou utilizando estes indicadores que encontrei principalmente no Github através das traderskills diversas disponíveis na plataforma, é muito bom saber que por trás dos Scripts sempre existem pessoas com boas intenções de compartilhar seus trabalhos gratuitamente sem cobrarem por mensalidades ou compra única por um preço absurdo. Sem palavras

Estou me familiarizando com esses conceitos e estou gostando muito, vejo muitos comentários depreciativos sobre esses conceitos, porém ao testarmos percebi uma grande oportunidade de utilizar essas ferramentas ao meu favor, acho muito interessante como todos os textos e vídeos que assitir estão todos os dias detalhados na tela do meu celular e PC é como um dejavu de todos os conteúdos assistidos.


r/pinescript • • 5h ago

Integrate options chain data

2 Upvotes

As a futures trader I would love to see the options chain data available in pinescript so I can model GEX levels and show the open interest ladder. Is this something that's on the roadmap?


r/pinescript • • 19h ago

Create an indicator that help me make more profit in the last 3 weeks then in 6 years NSFW Spoiler

Post image
12 Upvotes

One day I was going threw Instagram watching trading strategy making them into indicator to see if it's profitable and see if it's true what they promised I only short back test long forward test all failed accept one structure and price accepts pure price action I can't really explain it here the guy I got from explain it better then I can so took couple of his videos trans script it put it into Claude ai made couple edits while I was trading the system to point I'm happy with it dm me if you want the code unfortunately I don't not pay for TV I use the free I also made it for mt5 that's what I trade on every thing is free I don't charge on what I create especially when I didn't pay for the strategy or if it's some else strategy the createtor of the strategy Instagram is forex_cheatcodes my trading that works for me is the hour timeframe using his method and I don't use risk to reward I take 2 trades a day in the morning and at night or morning and afternoon when the market reopen morning trades I target the close gray line or until four clock close the trade same night trade close line same for after noon closes line the only time I stay in trade is when I'm watching it and move my stop loss in profits I always put my stop in profit I have originally stop loss the always move it into profit that way if it reversed full reverse I still made money you still lose money if you move stop loss to break even because you still pay commission those commissions add up they small depending on lot size but you still losing when you break even I rather win small amount to grow my account bigger then break even we trade to make profit and remember any trading system is not guaranteed to make money I'm not a financial I'm just sharing my journey you can lose all money always practice and fully understand any system before using real money I'm not liable for your losses or wins using my indicator it's for educational purpose. //@version=6

// LQ Swing Levels H4 v1.40 (Pine v6)

// Liquidity lines only. 4 Hour swing levels. 1 Hour acceptance.

// Swept / accepted lines deleted, or kept gray (setting).

// Same lines on every chart timeframe (1m up to 1D and above).

// Alerts fire only when a new line prints.

indicator("LQ Swing H4", overlay = true, max_lines_count = 500, max_labels_count = 500, max_bars_back = 500)

//=========================== INPUTS =================================

G1 = "4 Hour Levels"

objTf = input.timeframe("240", "Levels TF", group = G1)

accTf = input.timeframe("60", "Acceptance TF (deletes swept / accepted lines)", group = G1)

piv = input.int(3, "Swing length", minval = 2, group = G1)

maxLv = input.int(4, "Lines kept per side", minval = 1, maxval = 20, group = G1)

accBufM = input.float(0.15, "Acceptance buffer (ATR x)", step = 0.05, group = G1)

lw = input.int(3, "Line width", minval = 1, maxval = 5, group = G1)

cHigh = input.color(color.red, "High line", group = G1)

cLow = input.color(color.lime, "Low line", group = G1)

alertOn = input.bool(true, "Alert on new lines", group = G1)

keepOld = input.bool(false, "Keep old lines (swept / accepted) on chart", group = G1)

GV = "Visuals"

cDone = input.color(color.gray, "Old line color (swept / accepted)", group = GV)

oldMax = input.int(4, "Old lines kept per side", minval = 1, maxval = 20, group = GV)

bgOn = input.bool(true, "Tint background by H4 trend", group = GV)

cBgBull = input.color(color.new(color.rgb(10, 45, 45), 40), "Background bullish", group = GV)

cBgBear = input.color(color.new(color.rgb(55, 15, 15), 40), "Background bearish", group = GV)

showPanel = input.bool(true, "Show trend panel", group = GV)

fontIn = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = GV)

ATR_LEN = 14

lblSize = fontIn == "Tiny" ? size.tiny : fontIn == "Normal" ? size.normal : size.small

objMs = timeframe.in_seconds(objTf) * 1000

accMs = timeframe.in_seconds(accTf) * 1000

chartS = timeframe.in_seconds()

// chart above the levels / acceptance TF: read every intrabar so nothing is skipped

lowerObj = chartS > timeframe.in_seconds(objTf)

lowerAcc = chartS > timeframe.in_seconds(accTf)

//=========================== TYPES / HELPERS ========================

type Level

float price

line ln

label lb

string when

f_tfName(string tf) =>

string r = tf

if tf == "D" or tf == "1D"

r := "D1"

else if tf == "W" or tf == "1W"

r := "W1"

else if not na(str.tonumber(tf))

float n = str.tonumber(tf)

r := n % 60 == 0 ? "H" + str.tostring(n / 60) : "M" + tf

r

NM = f_tfName(objTf)

f_px(float p) => str.tostring(p, format.mintick)

f_tag(int t) => str.format_time(t, "yyyy.MM.dd HH:mm", syminfo.timezone)

// Levels TF: pivot confirmed on this bar, swing time, trend, bar time

f_obj(int pl) =>

float hc = high[pl]

float lc = low[pl]

bool isH = bar_index >= 2 * pl

bool isL = isH

for k = 1 to pl

if high[pl + k] >= hc or high[pl - k] > hc

isH := false

if low[pl + k] <= lc or low[pl - k] < lc

isL := false

var float lastH = na

var float lastL = na

var int trend = 0

if isH

lastH := hc

if isL

lastL := lc

if not na(lastH) and close > lastH

trend := 1

else if not na(lastL) and close < lastL

trend := -1

float phv = isH ? hc : na

float plv = isL ? lc : na

int pt = time[pl]

[phv, plv, pt, trend, time]

// last CLOSED levels bar (no repaint)

f_objPrev(int pl) =>

[a, b, c, d, e] = f_obj(pl)

[a[1], b[1], c[1], d[1], e[1]]

f_acc() =>

[high, low, close, ta.atr(ATR_LEN), time]

f_accPrev() =>

[h, l, c, a, t] = f_acc()

[h[1], l[1], c[1], a[1], t[1]]

//=========================== STATE ==================================

var array<Level> highs = array.new<Level>()

var array<Level> lows = array.new<Level>()

var array<Level> oldHighs = array.new<Level>()

var array<Level> oldLows = array.new<Level>()

var int trendNow = 0

f_add(array<Level> arr, float p, int t, bool isHigh, float tol) =>

bool dup = false

for lv in arr

if math.abs(lv.price - p) <= tol

dup := true

if not dup

color col = isHigh ? cHigh : cLow

string when = f_tag(t)

line ln = line.new(t, p, t + objMs, p, xloc.bar_time, extend.right, col, line.style_solid, lw)

label lb = label.new(bar_index, p, NM + (isHigh ? " HIGH " : " LOW ") + f_px(p) + " | " + when, xloc.bar_index, yloc.price, color(na), label.style_label_lower_left, col, lblSize)

arr.push(Level.new(p, ln, lb, when))

if arr.size() > maxLv

Level o = arr.shift()

line.delete(o.ln)

label.delete(o.lb)

not dup

// swept / accepted: delete, or keep gray and dashed

f_retire(array<Level> arr, int idx, array<Level> old, string txt) =>

Level lv = arr.remove(idx)

if keepOld

line.set_style(lv.ln, line.style_dashed)

line.set_width(lv.ln, 1)

line.set_color(lv.ln, cDone)

label.set_text(lv.lb, NM + " " + txt + " " + f_px(lv.price) + " | " + lv.when)

label.set_textcolor(lv.lb, cDone)

old.push(lv)

if old.size() > oldMax

Level o = old.shift()

line.delete(o.ln)

label.delete(o.lb)

else

line.delete(lv.ln)

label.delete(lv.lb)

true

f_checkAcc(float h1, float l1, float c1, float atr1) =>

float buf = nz(atr1) * accBufM

if highs.size() > 0

for i = highs.size() - 1 to 0

float p = highs.get(i).price

if h1 > p and c1 < p

f_retire(highs, i, oldHighs, "SWEPT")

else if c1 > p + buf

f_retire(highs, i, oldHighs, "ACCEPTED ABOVE")

if lows.size() > 0

for i = lows.size() - 1 to 0

float p = lows.get(i).price

if l1 < p and c1 > p

f_retire(lows, i, oldLows, "SWEPT")

else if c1 < p - buf

f_retire(lows, i, oldLows, "ACCEPTED BELOW")

true

f_moveLabels(array<Level> arr, int x) =>

for lv in arr

label.set_x(lv.lb, x)

//=========================== DATA ===================================

[sPH, sPL, sPT, sTR, sOT] = request.security(syminfo.tickerid, objTf, f_objPrev(piv), lookahead = barmerge.lookahead_on)

[sAH, sAL, sAC, sAA, sAT] = request.security(syminfo.tickerid, accTf, f_accPrev(), lookahead = barmerge.lookahead_on)

m1Atr = request.security(syminfo.tickerid, "1", ta.atr(ATR_LEN)[1], lookahead = barmerge.lookahead_on)

objNew = not na(sOT) and (na(sOT[1]) or sOT != sOT[1])

accNew = not na(sAT) and not na(sAT[1]) and sAT != sAT[1]

// duplicate filter: 0.25 x M1 ATR, same on every chart TF. Falls back to acceptance ATR.

float tol = not na(m1Atr) ? m1Atr * 0.25 : nz(sAA) * 0.05

// events closed during this chart bar, oldest first

ePH = array.new<float>()

ePL = array.new<float>()

ePT = array.new<int>()

eTR = array.new<int>()

eEnd = array.new<int>()

aH = array.new<float>()

aL = array.new<float>()

aC = array.new<float>()

aA = array.new<float>()

aEnd = array.new<int>()

if lowerObj

[xPH, xPL, xPT, xTR, xOT] = request.security_lower_tf(syminfo.tickerid, objTf, f_obj(piv))

int n = xOT.size()

int lim = barstate.isconfirmed ? n : n - 1 // skip the H4 bar still forming

if lim > 0

for i = 0 to lim - 1

ePH.push(xPH.get(i))

ePL.push(xPL.get(i))

ePT.push(xPT.get(i))

eTR.push(xTR.get(i))

eEnd.push(xOT.get(i) + objMs)

else if objNew

ePH.push(sPH)

ePL.push(sPL)

ePT.push(sPT)

eTR.push(sTR)

eEnd.push(sOT + objMs)

if lowerAcc

[yH, yL, yC, yA, yT] = request.security_lower_tf(syminfo.tickerid, accTf, f_acc())

int n = yT.size()

int lim = barstate.isconfirmed ? n : n - 1 // skip the 1H bar still forming

if lim > 0

for i = 0 to lim - 1

aH.push(yH.get(i))

aL.push(yL.get(i))

aC.push(yC.get(i))

aA.push(yA.get(i))

aEnd.push(yT.get(i) + accMs)

else if accNew

aH.push(sAH)

aL.push(sAL)

aC.push(sAC)

aA.push(sAA)

aEnd.push(sAT + accMs)

//=========================== PROCESS ================================

// acceptance bars that closed before each H4 close run first, then the new pivots print

int j = 0

if tol > 0

if eEnd.size() > 0

for k = 0 to eEnd.size() - 1

while j < aEnd.size() and aEnd.get(j) <= eEnd.get(k)

f_checkAcc(aH.get(j), aL.get(j), aC.get(j), aA.get(j))

j += 1

float ph = ePH.get(k)

float pl = ePL.get(k)

int pt = ePT.get(k)

if not na(ph)

if f_add(highs, ph, pt, true, tol) and alertOn

alert(syminfo.ticker + " LQ " + NM + ": new HIGH line printed at " + f_px(ph) + " (swing " + f_tag(pt) + ")", alert.freq_once_per_bar)

if not na(pl)

if f_add(lows, pl, pt, false, tol) and alertOn

alert(syminfo.ticker + " LQ " + NM + ": new LOW line printed at " + f_px(pl) + " (swing " + f_tag(pt) + ")", alert.freq_once_per_bar)

trendNow := eTR.get(k)

while j < aEnd.size()

f_checkAcc(aH.get(j), aL.get(j), aC.get(j), aA.get(j))

j += 1

//=========================== BACKGROUND =============================

bgcolor(bgOn ? (trendNow == 1 ? cBgBull : trendNow == -1 ? cBgBear : na) : na)

//=========================== LABELS + PANEL =========================

var table panel = table.new(position.top_right, 1, 2, bgcolor = color.new(color.black, 30), frame_color = color.gray, frame_width = 1)

if barstate.islast

f_moveLabels(highs, bar_index + 3)

f_moveLabels(lows, bar_index + 3)

f_moveLabels(oldHighs, bar_index + 3)

f_moveLabels(oldLows, bar_index + 3)

if showPanel

table.cell(panel, 0, 0, "LQ SWING LEVELS (H4)", text_color = color.white, text_size = lblSize, text_halign = text.align_left)

table.cell(panel, 0, 1, NM + " levels (" + f_tfName(accTf) + " acceptance): " + (trendNow == 1 ? "BULLISH" : trendNow == -1 ? "BEARISH" : "NEUTRAL"), text_color = color.white, text_size = lblSize, text_halign = text.align_left)


r/pinescript • • 3d ago

building a Pine script... logic failure

5 Upvotes

I'm trying to build a "flip-flop level" indicator, where the script would look for the peak low, retested by a peak high, but...

My knowledge of Pine is below minimal.
Thus, I rely on google assistance, and, its logic is failing me by only looking at 5 bars behind, 5 bars ahead.

Truth is, I find that limiting such a search to just a number of bars defeats the logic.

Any ideas, please?


r/pinescript • • 3d ago

Three reasons your Pine backtest looks better than reality — and the exact lines to check

4 Upvotes

I've been going through public strategies for a while now. The same three bugs show up again and again, and all three make the equity curve look better than it can possibly be.

  1. request.security() that leaks the future

// leaks: you are reading a bar that had not closed yet

htfClose = request.security(syminfo.tickerid, "D", close)

The default is barmerge.lookahead_off, so this one is usually fine on its own. The problem starts when people copy a snippet that passes lookahead_on explicitly, or when they write close[1] inside the call "to avoid repainting" — which does the opposite of what they think on historical bars.

// correct: last COMPLETED higher-timeframe bar, no leak

htfClose = request.security(syminfo.tickerid, "D", close[1], lookahead = barmerge.lookahead_on)

Yes — lookahead_on together with close[1] is the correct combination. It looks backwards. That is the whole point.

2. Signal on the close, fill on the close

strategy.entry() fills at the open of the next bar by default. If your entry condition uses close and you assume you got that price, you are buying at a price you could not have known when the decision was made. On a fast 5m or 15m signal this alone can turn a losing system into a "profitable" one.

Check: you did not set process_orders_on_close = true, and your entry price in the list of trades matches the next bar's open, not the signal bar's close.

3. No costs at all

If commission_type and slippage are unset, TradingView assumes zero. A strategy that fires 40 times a month on a 15m chart pays 40 × (spread + commission) whether or not you model it.

strategy("x",

commission_type = strategy.commission.percent,

commission_value = 0.05,

slippage = 2)

Those three explain most of the gap between backtest and reality. What's left is repainting: barstate.isconfirmed never checked, ta.* called inside an if block so it only updates on some bars, calc_on_every_tick = true.

If you want a second pair of eyes: paste the relevant part of your script in the comments (or DM me) and I'll tell you which of these I'd check first. No charge, no link, nothing to buy — I'm just trying to find out how often each one actually shows up in the wild.


r/pinescript • • 5d ago

Volume bubbles: trading buyer/seller absorption

1 Upvotes

Do you have any experience trading with indicators that highlight unusually large buy/sell volume? That's basically what volume bubbles are.

I've been backtesting a strategy based on absorption of either side. When price is going up, a large buy bubble appears, but price fails to hold that level and a big wick forms. That's my long/short signal.

Entry: the level of the bubble.
SL: discretionary, based on previous support/resistance zones or volume profile key levels.
TP: same logic as SL, at least 2R.

This type of strategy seems to have some potential, but it definitely needs improvement.

I'd appreciate any advice or ideas. If you've tried coding absorption in Pine, how did you define it?


r/pinescript • • 5d ago

4 exact reasons profitable PineScript strategies diverge when ported to MT5 (MQL5)

5 Upvotes

Porting a TradingView PineScript strategy to MetaTrader 5 looks straightforward until the MT5 backtest or live demo starts taking different trades than the TradingView chart. Almost every parity mismatch I have traced comes from four structural differences between the two engines.

  1. Bar-close evaluation in Pine vs intra-bar tick reads in MQL5 By default, PineScript evaluates conditions on bar close (unless calc_on_every_tick is enabled). A very common bug when translating to MQL5 is reading CopyBuffer() or price arrays at index 0 inside OnTick(). That evaluates an unfinished candle on every tick, triggers early entries that disappear before the bar closes, and creates heavy live divergence. Clean parity requires detecting a new bar via iTime(_Symbol, tf, 0) and reading every indicator buffer and OHLC value strictly at shift >= 1.
  2. Indicator math is not always identical between TradingView and MT5 Even with the same period length, several built-in functions differ under the hood. Pine's ta.rsi() and ta.atr() use Wilder's RMA smoothing, whereas some MT5 custom ports accidentally substitute EMA or SMA. Pine's ta.stdev() uses population standard deviation (dividing by N) by default, while some MQL5 implementations use sample standard deviation (N - 1). Before trusting any converted EA, export 20 to 30 closed-bar values from TradingView and compare them side by side against the MQL5 buffer values at shift=1.
  3. Chart-price fills vs real Bid/Ask spreads and rollover widening TradingView backtests fill long and short orders off the single chart price stream with a flat slippage setting unless you manually model spread. In MT5, buys open at Ask and close at Bid, while sells open at Bid and close at Ask. Strategies with tight stops or small targets that look fine on TradingView often degrade once real ECN commissions and 00:00 server rollover spread spikes hit the MT5 fills.
  4. Broker execution rules and Hedging vs Netting position logic PineScript never rejects an order for broker constraints. In live MT5, an EA will silently drop entries or exits if it ignores SYMBOL_TRADE_STOPS_LEVEL, SYMBOL_TRADE_FREEZE_LEVEL, OrderCalcMargin(), or the broker's supported filling mode (ORDER_FILLING_FOK, IOC, or RETURN). Account mode also matters: Pine's pyramiding and reversal rules behave differently when mapped to an MT5 Hedging account (separate position tickets) versus a Netting account (single aggregated position per symbol).

If you have ported Pine strategies to MT5, which mismatch gave you the hardest time to track down: indicator math (RMA/stdev/bar history) or live Bid/Ask execution differences?


r/pinescript • • 5d ago

strategy() defaults that quietly shape a backtest: zero commission, zero slippage, touch-fills on limits, 1:1 margin

2 Upvotes

A lot of "why does my backtest look so much better than live" questions come down to properties nobody set. Here is what the current v6 docs say the broker emulator does when you leave the strategy() declaration alone, and what each setting actually changes.

Commission: none by default. If you don't pass commission_type and commission_value, every fill is free. You can model a flat fee per order, a fee per contract/share/lot/unit, or a percentage of the transaction value. Cost scales with trade count, so high-turnover strategies are the ones most distorted by leaving this at zero.

Slippage: 0 ticks by default. slippage is a fixed number of ticks applied in the unfavorable direction (higher fills for longs, lower for shorts). Because it is constant, the docs point out it can push simulated fills outside the candle's range, so piling on slippage makes results unrealistically worse rather than more honest. Pick a value you can justify for the instrument's tick size and liquidity.

Limit orders: touch = fill by default. backtest_fill_limits_assumption defaults to 0, meaning a limit order fills as soon as price reaches its level. Setting it to N requires price to move N ticks beyond the level before the order fills. The "Limit order execution" input in Settings/Properties can override it. Strategies built on limit entries near local extremes are the most sensitive to this, since a level that was only touched is exactly where a real queue may not have filled you.

Margin: 100% by default (1:1). margin_long and margin_short default to 100; lower values show up as the "Long/Short leverage" inputs. If available funds drop below the required margin, the emulator generates a margin call and liquidates four times the quantity needed to cover the loss, to avoid repeated margin calls on the following bars. strategy.margin_liquidation_price returns the price at which that would trigger. The docs also flag margin below about 0.2% (leverage above 500:1) as typically unrealistic, and 0% as equivalent to infinite leverage.

Pyramiding: 1 by default. Repeated strategy.entry() calls in the same direction won't add to an open position until you raise pyramiding. One documented exception: if several strategy.entry() calls create limit, stop or stop-limit orders on the same tick, the emulator fills each one that price triggers, which can exceed the limit.

Order size: qty beats the defaults. A non-na qty in strategy.entry() or strategy.order() ignores default_qty_type / default_qty_value. Pass na when you want the default size to apply.

The declaration is only a default. All of the above can be overridden in Settings/Properties. When comparing your numbers with a published strategy, check the publication's "Properties" tab first: it lists the initial capital, order size, leverage, pyramiding, commission and slippage the author used.

A simple habit that helps: set commission, slippage and the limit-fill assumption explicitly in the declaration, even with rough first guesses, so the zero-cost case is a choice rather than an accident.

For those running limit-order strategies: do you use backtest_fill_limits_assumption = 1, or something larger tied to the instrument's typical spread?

Reference: TradingView Pine Script v6 docs, Concepts > Strategies (sections on commission, slippage and unfilled limits, margin and leverage, pyramiding, position sizing).


r/pinescript • • 6d ago

TradingView’s October update: live earnings calls, AI crypto screening, Desktop tab groups, and more

Thumbnail
reddit.com
1 Upvotes

r/pinescript • • 6d ago

MOR stddev Indicator

Post image
11 Upvotes

Encontrei este indicador que gera sinais e a 3 semana ele vem alcançando todos os alvos da abertura de 00:00 NY vocês o conhecem ?


r/pinescript • • 6d ago

Reproducing a closed-source TradingView indicator's 3 levels (high, mid, low) from a 4H window

1 Upvotes

I'm trying to reproduce the behavior of a closed-source TradingView indicator that draws 3 horizontal levels (high, mid, low) from a 4H window. I can read the levels from the chart for given days and timeframes, but I can't see the source. Fixed grids (Murrey Math) and standard pivot indicators did not match. Has anyone modeled this kind of rule (which bars define the window, how the mid is computed) or know open-source scripts that behave similarly? Any pointers welcome.


r/pinescript • • 6d ago

Feature Request: Expanding the 500 Future Bar Drawing Limit (xloc.bar_index) in Pine Script v6

Post image
2 Upvotes

Dear TradingView Support Team,

I am writing to submit a feature request regarding the current line and label drawing limitations in Pine Script, specifically concerning projectable drawing limits into future bars using xloc.bar_index.

Currently, Pine Script imposes a strict hard limit of 500 bars when drawing lines into the future beyond the current real-time bar (bar_index + 500).

While developing advanced long-term projection tools—such as 4-cycle Gann Boxes (e.g., 4 x 144 = 576 bars) and multi-timeframe geometric cycle models—we frequently run into this 500-bar ceiling. To prevent scripts from failing or throwing runtime rendering errors, developers currently have to implement complex custom math algorithms to dynamically calculate slopes and clip lines at bar_index + 490.

While these workarounds keep the scripts functional, they restrict full structural visualization for long-term strategic cycle analysis.

If technically feasible within your rendering pipeline and engine architecture, we kindly request the following enhancements in upcoming Pine Script updates:

  1. Increased Future Bar Projection Limit: Expanding the future bar drawing limit beyond 500 bars (e.g., to 1,000 bars or higher, especially for premium/pro tier users).
  2. Dynamic Limit Option: Providing a configurable parameter or native function in line.new() that allows drawing to project uninterruptedly across long timeframes without requiring manual line-clipping logic.

Thank you for your continuous dedication to improving Pine Script and supporting the developer community.


r/pinescript • • 7d ago

Whats this supposed to mean?

Post image
1 Upvotes

r/pinescript • • 7d ago

ta.* calls inside if blocks, ternaries and v6 "and"/"or": why the result drifts, and the CW10003 warning

2 Upvotes

If you've ever seen "The function ... should be called on each calculation for consistency" and ignored it, this is what it's actually warning about.

Local scopes don't get a history entry on every bar

Pine commits a value to a series' historical buffer only when the scope containing it is evaluated on the bar's closing tick. Global variables get a new entry on every bar, so x[1] always means "one bar ago". Code inside an if, a loop, a function body, or the unused branch of a ternary may not run on a given bar, and then nothing gets committed for that bar.

Per the docs (Execution model > Time series in scopes), [] on a local series therefore means "last committed value as of N bars back", not "value from N bars back". If the scope last ran 10 bars ago, localVar[1] through localVar[9] all return that 10-bar-old value.

Function parameters count as local too: each call site has its own buffer for its arguments, even when you pass a global like close.

Same thing applies to built-ins

Anything in ta.* that looks at past values internally (ta.sma, ta.rsi, ta.ema, ta.crossover, ...) keeps its own history of the source you pass. Call ta.sma(close, 20) only on bars where some condition is true and you get an average of the last 20 calls, not the last 20 bars. It compiles fine and looks plausible on the chart, which is why it's easy to miss.

The v6 trap: lazy and / or

In v5, and/or evaluated both operands every time. In v6 they short-circuit. The migration guide's own example: if close > open and ta.rsi(close, 14) > 50 gave correct RSI values in v5, but in v6 ta.rsi is skipped whenever close > open is false, so its internal history has gaps and the values are wrong. A script ported from v5 can change behavior with no compile error. The ternary ?: was already lazy in v5, so cond ? ta.sma(close, 20) : na has the same problem in both versions.

The fix is boring

Evaluate history-dependent calls once per bar in the global scope, store the result, and use the variable in your conditions:

  • rsi = ta.rsi(close, 14) then if close > open and rsi > 50
  • sma = ta.sma(close, 20) then cond ? sma : na
  • Same for your own functions that use [] on a parameter.

Lazy evaluation is still useful where you want to skip work, e.g. array.size(a) > 0 and array.first(a) > 0 no longer throws on an empty array in v6. The rule of thumb is just: guards can be lazy, anything with memory can't.

A couple of edge cases I'd like to hear how people handle: loops that call a history-dependent function per iteration (one buffer per call site, so iterations overwrite each other), and switch arms that each call a different ta.* function. Do you precompute every variant globally, or restructure some other way?


r/pinescript • • 7d ago

Go back!

Thumbnail reddit.com
1 Upvotes

I pay good money for Trading View. The recent updates to the Phone app are terrible. The timeframe and stock swipe left and right are a terrible idea. Also, the horizontal screen size got smaller. It wasn’t broken, are you just looking for reasons to screw it up? Go back or tell me how to get the older version back.


r/pinescript • • 7d ago

Go back!

Thumbnail reddit.com
1 Upvotes

r/pinescript • • 8d ago

I built two automated stock & options screeners running on $0/mo infrastructure (Python + GitHub Actions + Vercel)

1 Upvotes

>I kept paying for bloated finance screeners or spending 30+ minutes a morning digging through option chains and SEC filings manually, so I automated two lightweight scanners running on Python + GitHub Actions + Vercel + Resend:

Would love feedback on the UI, scoring logic, or which filters/metrics you'd want next!


r/pinescript • • 8d ago

An Open Letter to Management: Forcing Free Users Out is a Terrible Strategy

Thumbnail reddit.com
1 Upvotes

r/pinescript • • 8d ago

Sonar battery squeeze indicator freebie

Thumbnail
gallery
12 Upvotes

r/pinescript • • 8d ago

Hundreds of indicators were contributed by the community free of charge

Thumbnail reddit.com
3 Upvotes

r/pinescript • • 9d ago

Tradingview has HORRIBLE CUSTOMER SERVICE communications.

Thumbnail reddit.com
1 Upvotes

r/pinescript • • 9d ago

The settings I check before I believe a Pine backtest (including the July strategy changes)

1 Upvotes

I used to trust the strategy report a lot more than I should have. [One line of your own here: the strategy or setting that fooled you.]

These days I go through the same short list before I get excited about any result. Posting it in case it saves someone a bad week, and because I'd like to know what I'm still missing.

Fees first. Commission and slippage are zero unless you set them, and for anything that trades often that's the whole result. I set both, then run it again at double the commission. If it only works at the cheap number, it doesn't work.

Then fills. By default your order fills at the next bar's open, which is honest. Filling on the same bar's close looks better and is a price you mostly couldn't have had. Since July this lives under "Order execution delay" in Properties; process_orders_on_close still sets the default.

History and live don't run the same way. On past bars your script runs once per bar; live, with calc_on_every_tick, it runs on every tick. That gap is where a lot of "it worked in the tester" comes from. The new calc_on_every_history_tick closes some of it if you're on Premium or Ultimate.

Watch request.security(). Higher-timeframe data with lookahead on and no offset hands your script tomorrow's close. If you use lookahead_on, offset by one bar:

htfClose = request.security(syminfo.tickerid, "D", close[1], lookahead=barmerge.lookahead_on)

Heikin Ashi will lie to you. Orders fill at prices that never traded. Test on a standard chart, or set fill_orders_on_standard_ohlc=true (now "Heikin Ashi mode").

And size. 100% of equity with compounding makes almost any curve look steep. I start with a small fixed fraction so I'm looking at the strategy and not the leverage.

Where I start from:

//@version=6

strategy("Honest defaults", overlay=true,

initial_capital=10000,

default_qty_type=strategy.percent_of_equity,

default_qty_value=10,

commission_type=strategy.commission.percent,

commission_value=0.05,

slippage=2,

process_orders_on_close=false,

calc_on_every_tick=false,

use_bar_magnifier=true,

fill_orders_on_standard_ohlc=true)

None of this proves a strategy is good. It just stops the settings from flattering it.

The one I still don't have a clean answer for is walk-forward testing, since Pine can't hold data back. How are you all handling that?


r/pinescript • • 9d ago

Why does a good 1D strategy fall apart on 1m or 5m?

3 Upvotes

A lot of the time the logic isn't the problem. The costs are.

A simple way to see it is to compare a typical move with what one trade costs you.

On my BTC chart, ATR(14) on the daily is about 3% of price. On the 1m it's about 0.08%. If a round trip costs around 0.1% in fees and slippage, that's a small part of a daily move, but more than an entire typical 1m move.

So the same rules that capture, say, a fifth of the typical move can be profitable on the daily and below zero on the 1m. That's also why so many low-timeframe backtests look great with zero costs and go flat or negative once you add them.

Before tuning anything on a low timeframe, I'd check how big the average move is compared to the costs. If costs eat a big part of it, more optimization won't fix it.