Skip to content

TVDatafeed API

levi edited this page Nov 6, 2025 · 2 revisions

TVDatafeed API

Table of Contents

  1. Introduction
  2. Core Components
  3. Interface Contracts
  4. Implementation Methods
  5. Data Structures
  6. Callback System
  7. Example Implementation
  8. Integration with TradingView
  9. Error Handling and Performance
  10. Best Practices

Introduction

The TVDatafeed API provides a comprehensive framework for integrating custom market data sources with the TradingView charting system. This API implementation enables developers to create custom datafeeds that support symbol discovery, historical data retrieval, and real-time streaming capabilities. The core class, TVDatafeed, serves as a complete implementation that combines external datafeed, chart API, and quotes API interfaces, allowing for seamless integration with TradingView's charting library.

The API follows the charting_library datafeed-api.d.ts specification and is designed to be extended by subclasses that provide actual data retrieval logic from various sources. The framework supports both polling and WebSocket-based data delivery mechanisms, making it suitable for a wide range of market data providers and use cases.

Core Components

The TVDatafeed API consists of several core components that work together to provide a complete data integration solution. The primary component is the TVDatafeed class, which implements the TVIExternalDatafeed, TVIDatafeedChartApi, and TVIDatafeedQuotesApi interfaces. This class serves as the foundation for custom datafeed implementations and provides the necessary infrastructure for handling data requests and maintaining subscriber state.

The API also includes supporting components such as data structures for bars, symbols, and configuration, as well as callback definitions for asynchronous operations. These components are organized in a modular fashion, allowing developers to focus on implementing the specific methods required for their data source while leveraging the provided infrastructure for common functionality.

Interface Contracts

The TVDatafeed API defines its functionality through a set of interface contracts that specify the required methods for data integration. These interfaces establish the contract between the TradingView charting system and the custom datafeed implementation.

classDiagram
class TVIExternalDatafeed {
+onReady(callback : TVOnReadyCallback) void
}
class TVIDatafeedChartApi {
+searchSymbols(userInput : str, exchange : str, symbolType : str, onResult : TVSearchSymbolsCallback) void
+resolveSymbol(symbolName : str, onResolve : TVResolveCallback, onError : TVDatafeedErrorCallback, extension : Optional[TVSymbolResolveExtension]) void
+getBars(symbolInfo : TVLibrarySymbolInfo, resolution : ResolutionString, periodParams : TVPeriodParams, onResult : TVHistoryCallback, onError : TVDatafeedErrorCallback) void
+subscribeBars(symbolInfo : TVLibrarySymbolInfo, resolution : ResolutionString, onTick : TVSubscribeBarsCallback, listenerGuid : str, onResetCacheNeededCallback : Callable[[], None]) void
+unsubscribeBars(listenerGuid : str) void
}
class TVIDatafeedQuotesApi {
+getQuotes(symbols : List[str], onDataCallback : TVQuotesCallback, onErrorCallback : TVQuotesErrorCallback) void
+subscribeQuotes(symbols : List[str], fastSymbols : List[str], onRealtimeCallback : TVQuotesCallback, listenerGUID : str) void
+unsubscribeQuotes(listenerGUID : str) void
}
TVDatafeed --|> TVIExternalDatafeed
TVDatafeed --|> TVIDatafeedChartApi
TVDatafeed --|> TVIDatafeedQuotesApi
Loading

Implementation Methods

The TVDatafeed API requires the implementation of several key methods to support custom market data integration. These methods form the core functionality of the datafeed and are called by the TradingView charting system to retrieve data and manage subscriptions.

resolveSymbol()

The resolveSymbol method is responsible for resolving a symbol name to its corresponding symbol information. This method should be implemented to provide detailed metadata about the trading symbol, including its exchange, timezone, trading sessions, price format, and capabilities.

sequenceDiagram
participant TradingView as TradingView Chart
participant Datafeed as TVDatafeed
participant Implementation as Custom Implementation
TradingView->>Datafeed : resolveSymbol(symbolName, onResolve, onError)
Datafeed->>Implementation : Call overridden resolveSymbol()
alt Success
Implementation->>Datafeed : onResolve(symbolInfo)
Datafeed->>TradingView : Return symbol information
else Error
Implementation->>Datafeed : onError(errorMessage)
Datafeed->>TradingView : Return error
end
Loading

getBars()

The getBars method retrieves historical bar data for a specified symbol and time period. This method should be implemented to fetch OHLCV (Open, High, Low, Close, Volume) data from the data source and return it to the TradingView charting system.

sequenceDiagram
participant TradingView as TradingView Chart
participant Datafeed as TVDatafeed
participant Implementation as Custom Implementation
TradingView->>Datafeed : getBars(symbolInfo, resolution, periodParams, onResult, onError)
Datafeed->>Implementation : Call overridden getBars()
alt Success
Implementation->>Datafeed : onResult(bars, metadata)
Datafeed->>TradingView : Return historical bars
else Error
Implementation->>Datafeed : onError(errorMessage)
Datafeed->>TradingView : Return error
end
Loading

subscribeBars()

The subscribeBars method establishes a real-time subscription for bar updates. This method should be implemented to initiate a connection to a real-time data source (such as a WebSocket) and push new bar data to the TradingView charting system as it becomes available.

sequenceDiagram
participant TradingView as TradingView Chart
participant Datafeed as TVDatafeed
participant Implementation as Custom Implementation
participant DataSource as Real-time Data Source
TradingView->>Datafeed : subscribeBars(symbolInfo, resolution, onTick, listenerGuid, onResetCacheNeededCallback)
Datafeed->>Implementation : Call overridden subscribeBars()
Implementation->>DataSource : Connect to real-time feed
loop New bar data available
DataSource->>Implementation : Push new bar
Implementation->>Datafeed : onTick(newBar)
Datafeed->>TradingView : Update chart with new bar
end
Loading

Data Structures

The TVDatafeed API includes several key data structures that define the format of data exchanged between the datafeed and the TradingView charting system.

TVBar

The TVBar class represents a single bar of OHLCV data for a specific time period. It contains the open, high, low, close prices, and volume for a given time interval.

classDiagram
class TVBar {
+time : int
+open : float
+high : float
+low : float
+close : float
+volume : Optional[float]
+to_dict() dict
}
Loading

TVLibrarySymbolInfo

The TVLibrarySymbolInfo class contains comprehensive metadata about a trading symbol, including its name, description, type, exchange, timezone, and various configuration options.

classDiagram
class TVLibrarySymbolInfo {
+name : str
+description : str
+type : str
+session : str
+exchange : str
+listed_exchange : str
+timezone : Timezone
+format : SeriesFormat
+pricescale : int
+minmov : int
+ticker : Optional[str]
+base_name : Optional[str]
+long_description : Optional[str]
+has_intraday : bool
+supported_resolutions : Optional[List[ResolutionString]]
+volume_precision : int
}
Loading

TVDatafeedConfiguration

The TVDatafeedConfiguration class defines the capabilities and options supported by the datafeed implementation, including supported exchanges, resolutions, and feature flags.

classDiagram
class TVDatafeedConfiguration {
+exchanges : Optional[List[TVExchange]]
+supported_resolutions : Optional[List[ResolutionString]]
+units : Optional[Dict[str, List[TVUnit]]]
+currency_codes : Optional[List]
+supports_marks : Optional[bool]
+supports_time : Optional[bool]
+supports_timescale_marks : Optional[bool]
+symbols_types : Optional[List[TVDatafeedSymbolType]]
+symbols_grouping : Optional[Dict[str, str]]
}
Loading

Callback System

The TVDatafeed API uses a callback-based system to handle asynchronous operations and communicate results back to the TradingView charting system. The TVCallbacks module defines type aliases for all callback functions used in the API.

classDiagram
class TVCallbacks {
+TVOnReadyCallback : Callable[[TVDatafeedConfiguration], None]
+TVSearchSymbolsCallback : Callable[[List[TVSearchSymbolResultItem]], None]
+TVResolveCallback : Callable[[TVLibrarySymbolInfo], None]
+TVDatafeedErrorCallback : Callable[[str], None]
+TVHistoryCallback : Callable[[List[TVBar], Optional[TVHistoryMetadata]], None]
+TVSubscribeBarsCallback : Callable[[TVBar], None]
+TVQuotesCallback : Callable[[List[TVQuoteData]], None]
+TVQuotesErrorCallback : Callable[[str], None]
}
Loading

Example Implementation

The BADatafeed class provides an example implementation of the TVDatafeed API, demonstrating how to inherit from the base class and implement the required methods for a custom data source.

classDiagram
class TVDatafeed {
+__init__() void
+onReady(callback : TVOnReadyCallback) void
+searchSymbols(userInput : str, exchange : str, symbolType : str, onResult : TVSearchSymbolsCallback) void
+resolveSymbol(symbolName : str, onResolve : TVResolveCallback, onError : TVDatafeedErrorCallback, extension : Optional[TVSymbolResolveExtension]) void
+getBars(symbolInfo : TVLibrarySymbolInfo, resolution : ResolutionString, periodParams : TVPeriodParams, onResult : TVHistoryCallback, onError : TVDatafeedErrorCallback) void
+subscribeBars(symbolInfo : TVLibrarySymbolInfo, resolution : ResolutionString, onTick : TVSubscribeBarsCallback, listenerGuid : str, onResetCacheNeededCallback : Callable[[], None]) void
+unsubscribeBars(listenerGuid : str) void
+getQuotes(symbols : List[str], onDataCallback : TVQuotesCallback, onErrorCallback : TVQuotesErrorCallback) void
+subscribeQuotes(symbols : List[str], fastSymbols : List[str], onRealtimeCallback : TVQuotesCallback, listenerGUID : str) void
+unsubscribeQuotes(listenerGUID : str) void
}
class BADatafeed {
+__init__() void
+onReady(callback : TVOnReadyCallback) void
+searchSymbols(userInput : str, exchange : str, symbolType : str, onResult : TVSearchSymbolsCallback) void
+resolveSymbol(symbolName : str, onResolve : TVResolveCallback, onError : TVDatafeedErrorCallback, extension : Optional[TVSymbolResolveExtension]) void
+getBars(symbolInfo : TVLibrarySymbolInfo, resolution : ResolutionString, periodParams : TVPeriodParams, onResult : TVHistoryCallback, onError : TVDatafeedErrorCallback) void
+subscribeBars(symbolInfo : TVLibrarySymbolInfo, resolution : ResolutionString, onTick : TVSubscribeBarsCallback, listenerGuid : str, onResetCacheNeededCallback : Callable[[], None]) void
}
BADatafeed --|> TVDatafeed
Loading

Integration with TradingView

The TVDatafeed API integrates with the TradingView charting system through a well-defined interface that supports both polling and WebSocket-based data delivery. The integration points include symbol discovery, historical data retrieval, and real-time streaming.

For polling-based datafeeds, the getBars method is called periodically by the TradingView charting system to retrieve historical data, while the subscribeBars method establishes a subscription for real-time updates. For WebSocket-based datafeeds, the subscribeBars method initiates a WebSocket connection to receive real-time data, which is then pushed to the charting system using the onTick callback.

The API also supports integration with TradingView's quote system through the getQuotes and subscribeQuotes methods, allowing for real-time price updates and market depth information.

Error Handling and Performance

The TVDatafeed API includes comprehensive error handling mechanisms to ensure robust operation in various scenarios. Each method that retrieves data includes an onError callback parameter that should be called when an error occurs during data retrieval.

For performance optimization, the API provides mechanisms for efficient data delivery, including the use of metadata to indicate when no more data is available and the ability to reset the cache when necessary. The onResetCacheNeededCallback parameter in the subscribeBars method allows the datafeed to notify the charting system when cached data should be invalidated.

Rate limiting considerations are important for high-frequency data delivery, and implementations should include appropriate throttling mechanisms to prevent overwhelming the data source or the client. The API's design supports both push and pull models, allowing developers to choose the most appropriate approach for their specific use case.

Best Practices

When implementing a custom datafeed using the TVDatafeed API, several best practices should be followed to ensure optimal performance and reliability:

  1. Data Consistency: Ensure that historical and real-time data are consistent and properly aligned to prevent charting artifacts.
  2. Error Handling: Implement comprehensive error handling and provide meaningful error messages to aid in debugging.
  3. Resource Management: Properly manage subscriptions and clean up resources when unsubscribing to prevent memory leaks.
  4. Performance Optimization: Implement efficient data retrieval and caching strategies to minimize latency and maximize throughput.
  5. Configuration Validation: Validate configuration parameters and provide sensible defaults when possible.
  6. Logging: Include appropriate logging to facilitate monitoring and troubleshooting.
  7. Testing: Thoroughly test the implementation with various scenarios, including edge cases and error conditions.

Following these best practices will help ensure a robust and reliable integration with the TradingView charting system.

Clone this wiki locally