Skip to content
All library documents

Using Binary Search to Retrieve Historical Chart Bars by Time

Article TradingView scripts

Summary

This indicator demonstrates how to locate a chart bar corresponding to a timestamp a chosen number of years before the current bar. It constructs the target timestamp by subtracting a user-selected number of years while retaining the current month, day, and time components.

To find the matching historical bar, the script applies a binary search over bar timestamps, then plots calendar fields from the selected bar. The example is a practical technique for time-based historical lookup in a charting script, rather than a trading strategy or market analysis. Its implementation assumes a bounded history of up to 9,999 bars and searches that indexed range; the excerpt does not explain behavior when the requested date falls outside available data or between bars. It offers no trading results or validation beyond showing the method.

Key ideas

  • The indicator forms a target timestamp by shifting the current year backward by a user-selected amount.
  • A binary search over bar timestamps selects the historical index associated with that target time.
  • Calendar components from the selected bar are plotted for inspection.
  • The search is bounded by a configured history of 9,999 bars, so availability limits may affect the lookup.

Tags

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.