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.
Skrip sumber terbuka

Dalam semangat TradingView yang sebenar, penulis skrip ini telah menerbitkannya dengan menggunakan sumber terbuka supaya pedagang-pedagang dapat memahami dan mengesahkannya. Sorakan kepada penulis! Anda dapat menggunakannya secara percuma tetapi penggunaan semula kod ini dalam penerbitan adalah dikawalselia oleh Peraturan Dalaman. Anda boleh menyukainya untuk menggunakannya pada carta.

Penafian

Maklumat dan penerbitan adalah tidak dimaksudkan untuk menjadi, dan tidak membentuk, nasihat untuk kewangan, pelaburan, perdagangan dan jenis-jenis lain atau cadangan yang dibekalkan atau disahkan oleh TradingView. Baca dengan lebih lanjut di Terma Penggunaan.

Ingin menggunakan skrip ini pada carta?