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

Dans le véritable esprit de TradingView, l'auteur de ce script l'a publié en open-source, afin que les traders puissent le comprendre et le vérifier. Bravo à l'auteur! Vous pouvez l'utiliser gratuitement, mais la réutilisation de ce code dans une publication est régie par le règlement. Vous pouvez le mettre en favori pour l'utiliser sur un graphique.

Clause de non-responsabilité

Les informations et les publications ne sont pas destinées à être, et ne constituent pas, des conseils ou des recommandations en matière de finance, d'investissement, de trading ou d'autres types de conseils fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.

Vous voulez utiliser ce script sur un graphique ?