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.
オープンソーススクリプト

TradingViewの精神に則り、このスクリプトの作者は、トレーダーが理解し検証できるようにオープンソースで公開しています。作者に敬意を表します!無料で使用することができますが、このコードを投稿で再利用するには、ハウスルールに準拠する必要があります。 お気に入りに登録してチャート上でご利用頂けます。

免責事項

これらの情報および投稿は、TradingViewが提供または保証する金融、投資、取引、またはその他の種類のアドバイスや推奨を意図したものではなく、またそのようなものでもありません。詳しくは利用規約をご覧ください。

チャートでこのスクリプトを利用したいですか?