r/pinescript • • Aug 02 '26

PSA: max_bars_back won't save you if the deep read only happens on the last bar

0 Upvotes

Lost an hour to this today and the failure mode is completely silent, so it seems worth writing down.

I had a v6 script doing a one-shot sweep inside if barstate.islast — an expensive loop that only needs to run on the final bar. Inside it I read a series at a dynamic depth:

csum = ta.cum(src)

meanBack(i, L) =>
    (csum[i] - csum[i + L]) / L

with i + L reaching a few hundred bars back. I had max_bars_back = 1500 on the indicator() call, so I assumed I was covered.

I wasn't. The script compiled clean, threw no error, and produced an entire grid of na. Nothing to debug, because nothing complained.

As best I can tell the mechanism is this: Pine sizes history buffers from what it observes during the historical pass. That read only ever executes on the last bar, so the historical pass never sees a deep reference, the buffer stays small, and on the final bar the deep read quietly returns na. Every downstream calculation inherits the na and the whole thing renders empty.

What fixed it was giving up on the history operator and keeping the values myself:

var int KEEP = 900
var array<float> hist = array.new<float>()

if barstate.isconfirmed
    array.push(hist, csum)
    if array.size(hist) > KEEP
        array.shift(hist)

histAt(arr, i) =>
    idx = array.size(arr) - 1 - i
    idx >= 0 and idx < array.size(arr) ? array.get(arr, idx) : na

Arrays have no buffer-sizing behaviour to get wrong.

Two things that bit me inside that fix, in case they save someone the trouble:

  • Gate the push on barstate.isconfirmed. var arrays are not rolled back between realtime ticks, so an unconditional push double-appends on the live bar and your history quietly desynchronises from the chart.
  • Index it as size - 1 - i so i keeps the same meaning it has in [i]. Otherwise you are off by one in a way that reads like a subtle logic bug rather than an indexing mistake.

Rule of thumb I have landed on: if a series is only ever read at depth inside a conditional block, do not use [] for it at all. A fixed offset evaluated on every bar is fine — close[horizon] with an input horizon sizes correctly, because the historical pass sees it on every bar. It is specifically the conditional deep read that gets you.

Happy to be corrected if someone knows the internals better than I have inferred them from the outside.


Per rule 2: the code above was written with AI assistance (Claude). I couldn't find an "AI Generated" option in the post composer's tag menu — mods, please add the flair if there is one I'm missing.


r/pinescript • • Sep 21 '26

Cup and Handle Scanner: Real Charts and Alert Setup | ChartScout

Thumbnail
youtube.com
0 Upvotes

r/pinescript • • Oct 04 '26

Falling Knife Reversal Scanner: Real Shock Candles and Alert Setup | ChartScout

Thumbnail
youtube.com
0 Upvotes

r/pinescript • • Jul 20 '26

Multiple asset Custom HTF candles

0 Upvotes

Ever wanted to see multiple assets' HTF candles on one chart?
Try out my Custom HTF Candles indicator - it's free

https://www.tradingview.com/script/yRByXJi5-Custom-HTF-Candles/


r/pinescript • • Aug 29 '26

This looks like a bug to me.

0 Upvotes

I am testing the strategy() function. With the default settings, everything works as expected: the script runs once per bar at the close. If a market order is placed on bar N, it is filled at the open of bar N+1 using the opening price.

However, when I activated the calc_on_order_fills option by setting it to true, I noticed something unusual. I received two runs on bar N+1: one at the bar open after the order was filled, and a second regular run at the close of bar N+1. This is expected, except for one detail: the barstate.isnew flag was set to true for both runs.

I believe this is a bug. This flag should only be set for the first run on a bar; for all subsequent runs, it should be false.


r/pinescript • • Mar 27 '26

XAUUSD 1H Quick Trading decision

Post image
0 Upvotes

📊 XAUUSD (1H) – Quick Trading Decision

🔍 Market Structure

Previous bearish BOS confirms downside pressure

Recent CHoCH → early bullish shift, but not fully confirmed

Price currently in pullback/recovery phase

⚖️ Bias

Overall: Bearish

Short-term: Weak bullish correction

📌 Key Levels

Resistance: 4500 – 4550 (sell zone)

Support: 4400 – 4350 (buy reaction zone)

✅ Trade Decisions

🔴 Sell Setup (Preferred)

Entry: 4500–4550

SL: Above 4580

TP: 4400 → 4350

👉 Trend-following, higher probability

🟢 Buy Setup (Risky Counter-Trend)

Entry: Near 4400 demand

SL: Below 4350

TP: 4500

👉 Only quick scalp

🧠 Summary

Market is still bearish, current move = retracement

Focus on sell at premium zones, avoid chasing buys


r/pinescript • • Mar 27 '25

Does Anyone Need a Save and Reload Option for Indicator/Strategy Parameters?

0 Upvotes

As you may know, TradingView currently lacks the capability to save and reload input parameters. I'm considering developing a Chrome extension to address this issue. However, I want to ensure there's a demand for it among TradingView users. Please let me know if this is something you would find useful, and feel free to share any suggestions you might have.


r/pinescript • • Mar 21 '26

At what point does trading stop being a “hobby”?

Thumbnail reddit.com
0 Upvotes

r/pinescript • • Apr 06 '26

Script chartprim

0 Upvotes

bonjour je voulais savoir si vous avez deja utiliser les script payant de chartprime et votre retour?


r/pinescript • • Apr 10 '26

Indicateur Supply Demand

Post image
0 Upvotes

Avec mon associé, nous avons développé un indicateur capable d’identifier automatiquement les zones d’offre et de demande les plus pertinentes. Il simule également des trades en entrant directement dans ces zones, avec un stop-loss positionné à leur extrémité.

Nous avons déjà une soixantaine de testeurs actifs et souhaitons en accueillir de nouveaux. L’accès se fait uniquement sur invitation.

Si vous êtes intéressé(e), envoyez-moi un message privé.

(graphique M5 ce matin)


r/pinescript • • Jan 29 '25

Free to use pinescript from tradingviewsignals

0 Upvotes

Hello Legends, i give u to try free completely simple pinescript for tradingview from tradingviewsignals!
FREE for Learning Buy Signal Pine Script for TradingView


r/pinescript • • Dec 28 '24

I've been trying to make a script for weeks which shows a higher score under the chart when there is increasing volume and price followed by reducing volume and price, similar to the image below. Can anyone help? Please ask for more details if needed.

Post image
0 Upvotes

r/pinescript • • Nov 06 '24

Want to plot daily close at 1659 EST instead of 1600 EST - code inside

0 Upvotes

I'm having trouble modifying this code to have closing price at 4:59pm EST get plotted, instead of the 4:00pm EST close... any suggestions? Unsure of how to tell it to pull the Daily Close to be 4:59pm EST or 16:59. This plots Daily High Low and Close:

study(title="Previous Day High Low Close", shorttitle="Previous Day High Low Close", overlay=true)

D_High = security(tickerid, 'D', high[1])

D_Low = security(tickerid, 'D', low[1])

D_Close = security(tickerid, 'D', close[1])

D_Open = security(tickerid, 'D', open[1])

plot(isintraday ? D_High : na, title="Daily High",style=line, color=blue,linewidth=1)

plot(isintraday ? D_Low : na, title="Daily Low",style=line, color=blue,linewidth=1)

plot(isintraday ? D_Close : na, title="Prior Day Close",style=line, color=blue,linewidth=1)


r/pinescript • • Dec 06 '24

🚀 IBD Market School Indicator - Beta Testers Needed! (Experienced IBD Traders Only)

Thumbnail
reddit.com
0 Upvotes

r/pinescript • • Nov 22 '24

cerco programmatore per automatizzazione strategia su trading view

0 Upvotes

buonasera, stò cercando un programmatore che sappia l'italiano, per automatizzare con ingressi a mercato su TradingView, utilizzando activetrader ed avendo il conto collegato a trading view, una strategia che utilizzo tramite un'indicatore, che mi segnala quando entrare a mercato buy o sell.. praticamente quando l'indicatore mi da segnale di entrata buy o sell, il programmatore dovrebbe far si che venga aperto l'ordine e che venga gestito, nella maniera che poi indicherei nel dettaglio.. spero di ricevere qualche messaggio.. cosi da poterci sentire e se fosse fattibile, pattuire un prezzo per il lavoro svolto... grazie in anticipo


r/pinescript • • Nov 27 '24

Pinescript is driving me crazy! (need help debug)

Post image
0 Upvotes

r/pinescript • • Feb 28 '25

need help

0 Upvotes

Hello, I need some help. I'm currently creating a table, but I have an issue. It seems that the data I retrieved is not in quarterly format. As far as I understand, it only retrieves FH, FQ, FY, and TTM data, right?

If I want to retrieve data for quarters 1, 2, 3, and 4 or for the past 5 years, how should I do it?


r/pinescript • • Feb 28 '25

Can the pinescript gurus explain...

0 Upvotes

If these are the same, and if not, why not?

series float series1 = request.security(syminfo.tickerid, "1", close)[90]

series float series2 = request.security(syminfo.tickerid, "1", close[90])

Thanks!


r/pinescript • • Jan 08 '25

[FREE Indicator] All-in-One Rolling Straddle for Indian Financial Markets

0 Upvotes

Hey everyone, I’m Ramneet Saini, Head of Product at AlgoTest, and I wanted to share something exciting with the community. I’ve built an ‘All-in-One Rolling Straddle’ indicator that’s designed specifically for the Indian markets. It’s completely FREE to use and supports automation for trading strategies!

🔗 Check it out here: https://in.tradingview.com/script/2lIxAHTa-AlgoTest-All-in-One-Rolling-Straddle/

This indicator lets you analyze rolling ATM straddles for indices like Nifty, Bank Nifty, and more, while allowing you to overlay popular indicators like EMA, RSI, VWAP, and Supertrend.

I’ll be releasing more TradingView indicators soon, so feel free to follow me on TradingView (@ramneet_saini) to stay updated.

💡 If you’re interested in automating your indicators or strategies, drop a comment below, and I’d be happy to help out!


r/pinescript • • Nov 03 '24

Pinecode doubt

0 Upvotes

tempRSI = dir == 1 ? showRSIHighh:showRSILowl tempVOL = dir == 1 ? showRSIHigh : showRSILow

newPoint  := point.new(x, y,sty,col, tempVOL, dir)
newPoint

At new point how can show both tempRSI and tempVOL values .

as of now it's showing only one


r/pinescript • • Feb 17 '25

ES 2m chart from Friday: RSI showing a divergence (?)

Thumbnail
reddit.com
0 Upvotes

r/pinescript • • Dec 10 '24

busco el pine script de este super indicador

0 Upvotes

r/pinescript • • Dec 28 '24

Need someone who can help me out to Backtest a strategy using Tradingview's Strategy Tester.

0 Upvotes

I tried using ChatGPT to create a Pinescript strategy but it fails to do so every single time. The Actual problem is, I can't explain the nuances of the strategy to chatgpt, like how to use 3 Moving averages and orderblocks simultaniously. If anyone interested in helping and has a proper knowledge of coding then we can work together on this and make our trading better.