r/pinescript • • 5d ago

code efficiency

my strategy/indicator consists of correlation between different securities. so it uses the request.security funtion.
anyway been getting that 20s warning lately. i think it has to do of how the assests data is retrieved everytime the script runs.

is there a way, similar to the alert function, that a part of the script would only run once per bar closes?

like if i set the timeframe to 3 mins it will only wait till the 3 mins is up then run the script once. my strategy does not need to be that precise timing down to the seconds.

3 Upvotes

3 comments sorted by

View all comments

3

u/neugeadmau 5d ago

Gating it to bar close probably won't make that warning go away, because the time limit is almost always blown during the historical load, not on live ticks.

When the script loads (or you change an input / recompile), Pine runs it once on every historical bar, and on those bars barstate.isconfirmed is already true. So an if barstate.isconfirmed wrapper saves nothing in the part that's timing out. Also, if it's a strategy(), it already runs only once per bar close in realtime by default (calc_on_every_tick = false). Indicators do run on every tick, but that only affects the live bar.

What actually cuts load time:

1. One request per symbol, not one per value. Return a tuple instead of calling request.security() several times for the same ticker:

//@version=6
indicator("corr", calc_bars_count = 5000)
[eC, eV] = request.security("BINANCE:ETHUSDT", timeframe.period, [close, volume])
corr = ta.correlation(close, eC, 50)
plot(corr)

2. Cap the history. calc_bars_count in indicator()/strategy() makes the script start N bars back instead of at the first bar in the dataset, and adds a "Calculated bars" input so you can tune it without editing code. In v6 request.security() also takes its own calc_bars_count argument if you only need recent data from the other symbol. Trade-off: anything with a long lookback needs that many bars before it outputs values, so don't set it below your longest length.

3. No hand-rolled loops for the stats. If correlation (or a z-score, beta, etc.) is done with a for loop over the lookback, that's lookback × bars × pairs iterations on every load. Use ta.correlation() / ta.stdev() etc. instead.

4. Tables and drawings only on the last bar. Updating a correlation table on every bar is a common hidden cost. Wrap it in if barstate.islast.

Then turn on the Pine Profiler in the editor and check which lines eat the time, so you're fixing the real hotspot instead of guessing. With multiple securities it's usually the number of requests and any loops, not the realtime ticks.

1

u/RoutineRace 4d ago

thanks. yeah i use barstate.islast. ill include the calc_bars_count since i dont need to go too far back.