Lemrin

Security() Correction - Realtime vs. Historical Bars

Problem
Pine's implementation of the security() function behaves differently in realtime vs. historical bars. Specifically, for historical bars, calling security() for a time frame (TF) larger/slower than the current chart's TF will return information about the last completed bar of the higher TF. However, for realtime bars (i.e. if you allow the chart to continue to plot in realtime), security() returns information about the presently in-progress bar of the higher TF. Clearly, this leads to discontinuity that is arbitrarily dependent upon when the user last loaded or refreshed the chart.

Solution
Fortunately, after understanding the problem, solving it is trivial: use security() normally for historical bars, but switch to explicitly requesting prior candle bars once the indicator is operating on realtime bars. I leave the source open here for any to use as they see fit. For testing, I include an input to allow switching back and forth between standard and corrected behavior.

Figure 1 displays the standard behavior we see in security() calls, and Figure 2 displays the behavior after my correction:

Figure 1: Typical security() behavior in Pine

Figure 2: Corrected security() behavior, forcing historical and realtime bars to refer to the same higher TF bar offset.

I publish this mostly as a reminder to myself, so I will not forget and then have to figure it out again next time it comes up in my scripting.

V21: Initial release.
Script open-source

Nello spirito di condivisione promosso da TradingView, l'autore (al quale vanno i nostri ringraziamenti) ha deciso di pubblicare questo script in modalità open-source, così che chiunque possa comprenderlo e testarlo. Puoi utilizzarlo gratuitamente, ma il riutilizzo del codice è subordinato al rispetto del Regolamento. Per aggiungerlo al grafico, mettilo tra i preferiti.

Declinazione di responsabilità

Le informazioni ed i contenuti pubblicati non costituiscono in alcun modo una sollecitazione ad investire o ad operare nei mercati finanziari. Non sono inoltre fornite o supportate da TradingView. Maggiori dettagli nelle Condizioni d'uso.

Vuoi usare questo script sui tuoi grafici?