-
Notifications
You must be signed in to change notification settings - Fork 1
Quotes Integration
- Introduction
- Quote Data Retrieval Methods
- Data Structures
- Batch vs Real-Time Quote Processing
- Implementation Examples
- Common Issues and Solutions
- Performance Optimization
- Error Handling and Disconnection Management
This document provides comprehensive guidance on implementing quote data functionality within the TradingView integration framework. It covers the core methods for retrieving and managing financial instrument quotes, including batch retrieval and real-time streaming capabilities. The documentation details the structure of quote data objects, implementation patterns, and best practices for reliable quote delivery in trading applications.
The quote data functionality is implemented through three primary methods defined in the TVIDatafeedQuotesApi interface: getQuotes, subscribeQuotes, and unsubscribeQuotes. These methods enable both on-demand and continuous quote data retrieval.
classDiagram
class TVIDatafeedQuotesApi {
<<interface>>
+getQuotes(symbols : List[str], onDataCallback : TVQuotesCallback, onErrorCallback : TVQuotesErrorCallback) None
+subscribeQuotes(symbols : List[str], fastSymbols : List[str], onRealtimeCallback : TVQuotesCallback, listenerGUID : str) None
+unsubscribeQuotes(listenerGUID : str) None
}
class TVDatafeed {
+getQuotes(symbols : List[str], onDataCallback : TVQuotesCallback, onErrorCallback : TVQuotesErrorCallback) None
+subscribeQuotes(symbols : List[str], fastSymbols : List[str], onRealtimeCallback : TVQuotesCallback, listenerGUID : str) None
+unsubscribeQuotes(listenerGUID : str) None
-_quote_subscribers : Dict[str, Dict]
}
TVDatafeed --|> TVIDatafeedQuotesApi : implements
The getQuotes method retrieves current quote data for a specified list of symbols in a batch operation. This synchronous method returns the latest available quote information through the provided callback. The implementation in TVDatafeed serves as a base that should be overridden by concrete datafeed implementations to connect to actual market data sources.
The subscribeQuotes method establishes a real-time subscription for continuous quote updates. It accepts both regular symbols and fastSymbols parameters, where fastSymbols are used for high-frequency updates. The method stores subscription information including the listener GUID and callback function for delivering real-time quote data as it becomes available.
The unsubscribeQuotes method terminates an active quote subscription using the listener GUID that was provided during subscription. This method removes the subscription from the internal _quote_subscribers dictionary, stopping further quote updates for that listener.
The quote data system uses two primary data structures to represent quote information: TVQuoteData and TVDatafeedQuoteValues. These classes define the format and content of quote responses.
classDiagram
class TVQuoteData {
+s : QuoteStatus
+n : str
+v : Union[TVDatafeedQuoteValues, dict]
+__init__(s : QuoteStatus, n : str, v : Union[TVDatafeedQuoteValues, dict]) None
}
class TVDatafeedQuoteValues {
+ch : Optional[Any]
+chp : Optional[Any]
+short_name : Optional[Any]
+exchange : Optional[Any]
+description : Optional[Any]
+lp : Optional[Any]
+ask : Optional[Any]
+bid : Optional[Any]
+spread : Optional[Any]
+open_price : Optional[Any]
+high_price : Optional[Any]
+low_price : Optional[Any]
+prev_close_price : Optional[Any]
+volume : Optional[Any]
+original_name : Optional[Any]
+__init__(**kwargs) None
}
TVQuoteData --> TVDatafeedQuoteValues : contains
The TVDatafeedQuoteValues class contains the actual quote values for a financial instrument. Key fields include:
- lp: Last price (most recent trade price)
- bid: Current bid price
- ask: Current ask price
- spread: Difference between ask and bid prices
- volume: Today's trading volume
- ch: Price change from open price
- chp: Price change percentage
- open_price: Today's opening price
- high_price: Today's high price
- low_price: Today's low price
- prev_close_price: Previous session's closing price
All properties are optional but should be populated where available to support full trading functionality across widgets like Order Ticket, Watchlist, and Depth of Market.
The TVQuoteData class represents the response structure for quote data requests, encapsulating both successful and error responses:
- s: Status code ("ok" for success, "error" for failure)
- n: Symbol name (must match the request exactly)
- v: Quote values (TVDatafeedQuoteValues instance for "ok" status, dictionary for "error" status)
This structure allows the system to handle both successful quote data and error conditions in a consistent manner.
The system supports two distinct approaches for quote data retrieval: batch requests for on-demand data and real-time subscriptions for continuous updates.
flowchart TD
A[Client Request] --> B{Request Type?}
B --> |Single Request| C[getQuotes]
B --> |Continuous Updates| D[subscribeQuotes]
C --> E[Retrieve Current Quotes]
E --> F[Process Batch Response]
F --> G[Return TVQuoteData Array]
G --> H[Display in Widgets]
D --> I[Register Subscription]
I --> J[Store listenerGUID & Callback]
J --> K[Connect to Real-time Feed]
K --> L[Receive Quote Updates]
L --> M[Format as TVQuoteData]
M --> N[Call onRealtimeCallback]
N --> O[Update UI Components]
P[unsubscribeQuotes] --> Q[Remove Subscription]
Q --> R[Stop Data Delivery]
Batch quote retrieval through getQuotes is designed for scenarios where current market data is needed at specific moments, such as:
- Initial widget population
- On-demand price checks
- Periodic refresh operations
- Symbol search result enrichment
This approach retrieves the latest available quote data in a single response, making it efficient for situations where real-time updates are not required.
Real-time quote streaming through subscribeQuotes is optimized for applications requiring continuous price updates:
- Active trading interfaces
- Real-time watchlists
- Dynamic chart legends
- Order entry systems
- Market monitoring dashboards
The streaming approach maintains an open connection to the data source, delivering quote updates as they occur with minimal latency.
The BADatafeed class provides an example implementation of the datafeed interface, demonstrating how quote functionality can be integrated with actual market data sources.
sequenceDiagram
participant Client
participant Datafeed
participant MarketData
Client->>Datafeed : getQuotes(["BTCUSDT", "ETHUSDT"])
Datafeed->>MarketData : Request current quotes
MarketData-->>Datafeed : Return quote data
Datafeed->>Datafeed : Format as TVQuoteData
Datafeed-->>Client : Call onDataCallback with results
Client->>Datafeed : subscribeQuotes(["BTCUSDT"], ["BTCUSDT"], callback, "guid123")
Datafeed->>Datafeed : Store subscription
Datafeed->>MarketData : Establish real-time connection
loop Continuous Updates
MarketData->>Datafeed : Push quote update
Datafeed->>Datafeed : Format as TVQuoteData
Datafeed->>Client : Call onRealtimeCallback
end
Client->>Datafeed : unsubscribeQuotes("guid123")
Datafeed->>Datafeed : Remove subscription
Stale quotes occur when the datafeed fails to receive timely updates from the market data source. This can be mitigated by:
- Implementing heartbeat mechanisms to detect connection issues
- Setting appropriate timeout values for quote updates
- Using the fastSymbols parameter for high-priority symbols
- Implementing quote age validation in the client
When batch requests return incomplete data, consider:
- Validating symbol names before inclusion in requests
- Implementing retry logic for failed symbols
- Providing fallback values for missing fields
- Using partial success responses rather than failing the entire request
The fastSymbols parameter in subscribeQuotes is designed for symbols requiring high-frequency updates. Best practices include:
- Limiting fastSymbols to actively traded instruments
- Monitoring bandwidth usage when using multiple fastSymbols
- Dynamically adjusting fastSymbols based on user focus
- Implementing rate limiting to prevent overwhelming the data source
Optimizing quote delivery performance involves several strategies:
flowchart TD
A[Performance Optimization] --> B[Connection Management]
A --> C[Data Filtering]
A --> D[Memory Efficiency]
A --> E[Error Resilience]
B --> B1[Reuse WebSocket connections]
B --> B2[Batch subscription requests]
B --> B3[Implement connection pooling]
C --> C1[Filter unnecessary fields]
C --> C2[Use fastSymbols selectively]
C --> C3[Implement data sampling]
D --> D1[Object pooling for TVQuoteData]
D --> D2[Efficient string handling]
D --> D3[Minimize memory allocations]
E --> E1[Automatic reconnection]
E --> E2[Circuit breaker pattern]
E --> E3[Graceful degradation]
Key optimization techniques include:
- Minimizing the number of active subscriptions
- Using connection pooling for WebSocket-based data sources
- Implementing efficient data serialization
- Reducing callback overhead through batching
- Optimizing memory usage with object pooling
Robust error handling is critical for maintaining reliable quote delivery:
stateDiagram-v2
[*] --> Idle
Idle --> Subscribed : subscribeQuotes
Subscribed --> Reconnecting : Connection Lost
Reconnecting --> Subscribed : Reconnect Success
Reconnecting --> Failed : Max Retries Exceeded
Subscribed --> Idle : unsubscribeQuotes
Failed --> Idle : Manual Recovery
Subscribed --> ErrorState : Critical Error
ErrorState --> Idle : dispose
note right of Reconnecting
Implement exponential backoff
Validate reconnection parameters
Monitor network conditions
end note
note left of Subscribed
Heartbeat monitoring
Quote age validation
Bandwidth throttling
end note
Effective disconnection management should include:
- Automatic reconnection with exponential backoff
- State preservation during reconnection
- Graceful degradation when updates are unavailable
- Comprehensive logging for troubleshooting
- User notifications for prolonged outages
The system provides error callbacks (onErrorCallback for getQuotes and implicit error handling in subscriptions) to allow clients to respond appropriately to data delivery issues.