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.
Mã nguồn mở

Với tinh thần TradingView, tác giả của tập lệnh này đã xuất bản nó dưới dạng mã nguồn mở, vì vậy các nhà giao dịch có thể hiểu và xác minh nó. Chúc mừng tác giả! Bạn có thể sử dụng mã này miễn phí, nhưng việc sử dụng lại mã này trong một ấn phẩm chịu sự điều chỉnh của Nội quy nội bộ. Bạn có thể yêu thích nó để sử dụng nó trên biểu đồ.

Thông báo miễn trừ trách nhiệm

Thông tin và ấn phẩm không có nghĩa là và không cấu thành, tài chính, đầu tư, kinh doanh, hoặc các loại lời khuyên hoặc khuyến nghị khác được cung cấp hoặc xác nhận bởi TradingView. Đọc thêm trong Điều khoản sử dụng.

Bạn muốn sử dụng tập lệnh này trên biểu đồ?