Skip to content

Historical Data Fetching

levi edited this page Nov 6, 2025 · 2 revisions

Historical Data Fetching

Table of Contents

  1. Introduction
  2. Core Parameters of getBars Method
  3. Symbol Information and Metadata
  4. Resolution Handling and Time Granularity
  5. Period Parameters and Time Window Definition
  6. Bar Data Structure and Timestamp Alignment
  7. Callback Mechanisms and Error Handling
  8. Implementation Example and Validation
  9. Common Issues and Troubleshooting

Introduction

The getBars method in the TVDatafeed implementation is a core component of the TradingView datafeed API, responsible for retrieving historical market data for financial instruments. This method serves as the primary interface between the charting library and the underlying data source, enabling the visualization of price movements over time. The implementation must properly handle symbol metadata, time granularity, temporal windowing, and callback mechanisms to ensure accurate and efficient data delivery. This document provides a comprehensive analysis of the method's parameters, their interrelationships, and proper implementation patterns to ensure compatibility with the TradingView charting library.

Core Parameters of getBars Method

The getBars method accepts five essential parameters that define the data retrieval request: symbolInfo, resolution, periodParams, onResult, and onError. These parameters work in concert to specify exactly what data should be retrieved, how it should be formatted, and how the results should be communicated back to the calling system. The method signature follows the abstract interface defined in TVIDatafeedChartApi, ensuring consistency across different datafeed implementations. Each parameter plays a distinct role in the data fetching process, from identifying the financial instrument to defining the temporal characteristics of the requested data and handling the asynchronous response.

flowchart TD
A[getBars Method] --> B[symbolInfo]
A --> C[resolution]
A --> D[periodParams]
A --> E[onResult]
A --> F[onError]
B --> G[Symbol Metadata]
C --> H[Time Granularity]
D --> I[Time Window]
E --> J[Success Callback]
F --> K[Error Callback]
style A fill:#f9f,stroke:#333
Loading

Symbol Information and Metadata

The symbolInfo parameter is an instance of TVLibrarySymbolInfo that contains comprehensive metadata about the financial instrument being requested. This metadata is crucial for proper data alignment and interpretation, as it includes essential information such as the symbol's timezone, trading session, and price scale. The timezone field, specified in OlsonDB format (e.g., "America/New_York"), ensures that timestamps are correctly interpreted relative to the exchange's local time. The session field defines the trading hours during which the instrument is actively traded, which is important for filtering relevant data points. The pricescale parameter indicates the decimal precision of price values, allowing for proper formatting and calculation of price movements. Additional metadata such as the instrument type, exchange information, and classification data help contextualize the data within the broader market structure.

classDiagram
class TVLibrarySymbolInfo {
+string name
+string description
+string type
+string session
+string exchange
+string listed_exchange
+string timezone
+string format
+int pricescale
+int minmov
+string ticker
+string base_name
+string long_description
+string session_display
+string session_holidays
+string corrections
+bool fractional
+int minmove2
+bool variable_tick_size
+bool has_intraday
+string[] supported_resolutions
+string[] intraday_multipliers
+bool has_seconds
+bool has_ticks
+string[] seconds_multipliers
+bool build_seconds_from_ticks
+bool has_daily
+string[] daily_multipliers
+bool has_weekly_and_monthly
+string[] weekly_multipliers
+string[] monthly_multipliers
+bool has_empty_bars
+string visible_plots_set
+int volume_precision
+string data_status
+int delay
+bool expired
+string expiration_date
+string sector
+string industry
+string currency_code
+string original_currency_code
+string unit_id
+string original_unit_id
+string unit_conversion_types
+string subsession_id
+TVLibrarySubsessionInfo[] subsessions
+string price_source_id
+TVSymbolInfoPriceSource[] price_sources
+string[] logo_urls
+string exchange_logo
+string library_custom_fields
}
Loading

Resolution Handling and Time Granularity

The resolution parameter, typed as ResolutionString, specifies the time granularity of the requested historical data. This string-based parameter supports various time intervals including minute-based resolutions (e.g., "1", "5", "15"), daily ("1D"), weekly ("1W"), and monthly ("1M") intervals. The resolution directly impacts how the data is aggregated and presented on the chart, with higher resolutions providing more detailed price movements but requiring more data points. Implementations must validate that the requested resolution is supported by the underlying data source, which can be checked through the supported_resolutions field in the symbolInfo object. Different resolutions require different timestamp alignment strategies, with intraday bars typically aligned to specific minute boundaries and daily/weekly/monthly bars aligned to calendar days at 00:00 UTC.

graph TD
A[Resolution String] --> B["1" (1 minute)]
A --> C["5" (5 minutes)]
A --> D["15" (15 minutes)]
A --> E["30" (30 minutes)]
A --> F["60" (1 hour)]
A --> G["1D" (1 day)]
A --> H["1W" (1 week)]
A --> I["1M" (1 month)]
B --> J[Intraday Data]
C --> J
D --> J
E --> J
F --> J
G --> K[Daily+ Data]
H --> K
I --> K
style A fill:#f9f,stroke:#333
Loading

Period Parameters and Time Window Definition

The periodParams object, an instance of TVPeriodParams, defines the temporal window for the historical data request through three key properties: from_, to, and countBack. The from_ and to parameters specify the Unix timestamps (in milliseconds) that define the leftmost and rightmost boundaries of the requested data range, with the to timestamp being non-inclusive. The countBack parameter specifies the exact number of bars to retrieve, taking precedence over the from_ parameter when both are provided. This allows for efficient pagination of historical data, where subsequent requests can retrieve additional bars beyond the initial set. The firstDataRequest flag indicates whether this is the initial call for a particular chart, which can influence caching and data retrieval strategies. These parameters work together to enable flexible data windowing, supporting both fixed time range requests and dynamic count-based requests.

classDiagram
class TVPeriodParams {
+int from_
+int to
+int countBack
+bool firstDataRequest
}
Loading

Bar Data Structure and Timestamp Alignment

The historical data returned by getBars consists of TVBar objects, each representing a single time period with OHLCV (Open, High, Low, Close, Volume) data. The time field of each bar is specified in milliseconds since the Unix epoch in UTC timezone, ensuring consistent temporal alignment across different timezones. For daily, weekly, and monthly bars, the timestamp is expected to represent the trading day at 00:00 UTC, rather than the session start time in the local exchange timezone. This standardization simplifies chart rendering and comparison across different instruments. The timestamp alignment must account for the requested resolution, snapping to appropriate boundaries (e.g., minute boundaries for intraday data, day boundaries for daily data). The TVHistoryMetadata object accompanying the bar data provides additional context, including a noData flag to indicate when no more historical data is available and a nextTime field to suggest when the next bar might become available.

classDiagram
class TVBar {
+int time
+float open
+float high
+float low
+float close
+float volume
}
class TVHistoryMetadata {
+bool noData
+int nextTime
}
TVBar --> TVHistoryMetadata : "returned with"
Loading

Callback Mechanisms and Error Handling

The getBars method employs an asynchronous callback pattern with two distinct callback functions: onResult and onError. The onResult callback, typed as TVHistoryCallback, is invoked with the retrieved bar data and associated metadata when the request completes successfully. This callback accepts a list of TVBar objects and an optional TVHistoryMetadata object, allowing the charting library to process and display the historical data. The onError callback, typed as TVDatafeedErrorCallback, is invoked when an error occurs during data retrieval, receiving a string error message that can be displayed to the user. This separation of success and error paths ensures robust error handling and provides clear feedback to the user interface. Proper implementation should wrap data retrieval operations in try-catch blocks to ensure that all exceptions are properly communicated through the onError callback rather than allowing them to propagate unhandled.

sequenceDiagram
participant Client as "Charting Library"
participant Datafeed as "TVDatafeed"
participant DataSource as "Data Source"
Client->>Datafeed : getBars(symbolInfo, resolution, periodParams)
Datafeed->>DataSource : Retrieve historical data
alt Success
DataSource-->>Datafeed : Return bars and metadata
Datafeed->>Client : onResult(bars, metadata)
else Error
DataSource-->>Datafeed : Exception
Datafeed->>Client : onError(errorMessage)
end
Note over Datafeed,DataSource : Implementation must handle<br/>all exceptions and route<br/>through proper callback
Loading

Implementation Example and Validation

A proper implementation of the getBars method should include comprehensive validation of input parameters before attempting data retrieval. This includes verifying that the requested resolution is supported by the symbol (using the supported_resolutions field in symbolInfo), ensuring that the from_ and to timestamps are valid and in the correct order, and confirming that countBack is a positive integer. The implementation should also validate that the symbol is not expired and that the data source is available. After validation, the method should retrieve the appropriate historical data from the underlying data source, format it as TVBar objects with correctly aligned timestamps, and invoke the onResult callback with the data and appropriate metadata. If any validation fails or an error occurs during data retrieval, the onError callback should be invoked with a descriptive error message. The BADatafeed class provides an example implementation that demonstrates these patterns, including proper exception handling and metadata generation.

Common Issues and Troubleshooting

Several common issues can arise when implementing the getBars method, including invalid symbol resolution support, out-of-range timestamps, and missing data sources. Resolution-related issues often occur when a client requests a time interval that is not supported by the specific financial instrument, which should be validated against the supported_resolutions list in the symbolInfo object. Timestamp issues can arise from incorrect timezone conversions or from requesting data outside the available historical range, which should be handled by checking the data_status field and providing appropriate metadata. Data source connectivity issues should be caught and communicated through the onError callback with descriptive messages. Another common issue is improper timestamp alignment, where bar times are not correctly snapped to resolution boundaries, leading to display artifacts on the chart. Implementations should also handle cases where no data is available by setting the noData flag in the TVHistoryMetadata object rather than returning an empty array without context.

Clone this wiki locally