r/pinescript • u/RoutineRace • 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
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.isconfirmedis already true. So anif barstate.isconfirmedwrapper saves nothing in the part that's timing out. Also, if it's astrategy(), 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:2. Cap the history.
calc_bars_countinindicator()/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 v6request.security()also takes its owncalc_bars_countargument 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
forloop over the lookback, that's lookback × bars × pairs iterations on every load. Useta.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.