-
Notifications
You must be signed in to change notification settings - Fork 1
TVWidget and TVChart API
- Introduction
- TVWidget Class
- TVWidgetConfig Class
- TVChart Class
- Relationship Between TVWidget and TVChart
- Usage Examples
- Performance Optimization
- Conclusion
The PyTradingView library provides Python interfaces for controlling TradingView widgets and charts through the TVWidget and TVChart classes. These classes enable developers to embed, configure, and interact with TradingView charts programmatically. The TVWidget class serves as the primary interface for widget initialization, configuration, and lifecycle management, while the TVChart class provides methods for chart manipulation, series control, event subscription, and interaction with drawing tools. This documentation details the comprehensive API for both classes, including configuration options, event handling patterns, and asynchronous operations.
The TVWidget class is the main interface for interacting with the TradingView Chart Widget. It provides methods for initialization, configuration, connection lifecycle management, and multi-chart layout control. The class mirrors the functionality of the JavaScript ChartingLibraryWidgetConstructor and serves as the entry point for all widget operations.
The TVWidget is initialized with an object ID and provides access to configuration through the TVWidgetConfig class. The configuration manager handles default values, validation, and merging of user-provided settings.
classDiagram
class TVWidget {
+__init__(object_id : str)
+activeChart() TVChart
+activeChartIndex() int
+addCustomCSSFile(url : str) None
+applyOverrides(overrides : Dict[str, Any]) None
+applyStudiesOverrides(overrides : Dict[str, Any]) None
+applyTradingCustomization(config : Dict[str, Any]) None
+changeTheme(theme_name : str, options : Optional[Dict] = None, callback : CallBackParams = None) None
+chart(index : int = 0) TVChart
+chartsCount() int
+clearUndoHistory() None
+closePopupsAndDialogs() None
+createButton(options : Dict[str, Any]) TVHMElement
+createDropdown(title : str, items : List[Dict[str, Any]], tooltip : Optional[str] = None, icon : Optional[str] = None, align : Optional[str] = None) TVDropdownApi
+crosshairSync() TVWatchedValue[bool]
+currencyAndUnitVisibility() TVWatchedValue[Any]
+customSymbolStatus() TVCustomSymbolStatus
+customThemes() TVCustomThemes
+dateFormat() TVWatchedValue[str]
+dateRangeSync() TVWatchedValue[bool]
+drawOnAllChartsEnabled() TVWatchedValue[bool]
+exitFullscreen() None
+getCSSCustomPropertyValue(name : str) str
+getIntervals() List[str]
+getLanguage() str
+getSavedCharts() List[Dict[str, Any]]
+getStudiesList() List[str]
+getStudyInputs(study_name : str) List[Dict[str, Any]]
+getStudyStyles(study_name : str) Dict[str, Any]
+getTheme() str
+headerReady(callback : CallBackParams) None
+hideAllDrawingTools() TVWatchedValue[bool]
+intervalSync() TVWatchedValue[bool]
+layout() str
+layoutName() Optional[str]
+load(state : Dict[str, Any], extended_data : Optional[Dict] = None) None
+loadChartFromServer(record : Dict[str, Any]) None
+lockAllDrawingTools() TVWatchedValue[bool]
+magnetEnabled() TVWatchedValue[bool]
+magnetMode() TVWatchedValue[int]
+mainSeriesPriceFormatter() Any
+navigationButtonsVisibility() TVWatchedValue[Any]
+news() Any
+onChartReady(callback : CallBackParams) None
+onContextMenuProxy(itemList : List[TVContextMenuItem]) None
+onGrayedObjectClicked(callback : CallBackParams) None
+onShortcut(shortCut : Union[str, int, List[Union[str, int]]], callback : CallBackParams) None
+paneButtonsVisibility() TVWatchedValue[Any]
+remove() None
+removeButton(button_id : str) None
+removeChartFromServer(chart_id : Union[str, int]) None
+resetCache() None
+resetLayoutSizes(disable_undo : bool = False) None
+save(options : Optional[Dict] = None) Dict[str, Any]
+saveChartToServer(options : Optional[Dict] = None) None
+selectLineTool(linetool : str, options : Optional[Dict] = None) None
+selectedLineTool() str
+setActiveChart(index : int) None
+setCSSCustomProperty(name : str, value : str) None
+setDebugMode(enabled : bool) None
+setLayout(layout : str) None
+setLayoutSizes(sizes : Dict[str, Any], disable_undo : bool = False) None
+setSymbol(symbol : str, interval : str, callback : CallBackParams) None
+showConfirmDialog(params : Dict[str, Any]) None
+showLoadChartDialog() None
+showNoticeDialog(params : Dict[str, Any]) None
+showSaveAsChartDialog() None
+startFullscreen() None
+subscribe(event : str, callback : Callable[[Any], None]) None
+supportedChartTypes() Any
+symbolInterval() dict
+symbolSync() TVWatchedValue[bool]
+takeClientScreenshot(options : Optional[Dict] = None) Any
+takeScreenshot() None
+timeHoursFormat() TVWatchedValue[Any]
+timeSync() TVWatchedValue[bool]
+undoRedoState() Any
+unloadUnusedCharts() None
+unsubscribe(event : str, callback : Callable[[Any], None]) None
+watchList() Any
+watermark() Any
+widgetbar() Any
}
The TVWidget class provides several methods for managing the connection lifecycle and initialization process. The onChartReady method registers a callback to be called when the chart is ready, while headerReady registers a callback for when the top toolbar is ready. These asynchronous operations ensure that the widget is fully initialized before interaction.
The subscribe and unsubscribe methods allow for event subscription management, enabling developers to listen for specific widget events such as symbol changes, interval changes, or chart type changes. The event system uses callback functions that are invoked when the corresponding events are fired.
TVWidget provides comprehensive support for multi-chart layouts through methods like chartsCount, activeChart, activeChartIndex, and setActiveChart. Developers can retrieve the number of charts in the current layout and switch between active charts programmatically. The layout method returns the current chart layout type, while setLayout allows changing the layout programmatically.
For managing chart sizes in multi-chart layouts, the setLayoutSizes method sets the sizes of each chart, and resetLayoutSizes resets them to default values. The unloadUnusedCharts method optimizes memory usage by unloading invisible charts in a multi-chart layout, which is particularly useful for performance optimization in complex dashboards.
The TVWidgetConfig class manages the initialization configuration for the TradingView widget. It provides type-safe configuration management, avoiding the use of global variables and ensuring configuration validity.
classDiagram
class TVWidgetConfig {
DEFAULT_CONFIG : Dict[str, Any]
+__init__(config : Optional[Dict[str, Any]] = None)
+update(config : Dict[str, Any]) None
+get(key : str, default : Any = None) Any
+set(key : str, value : Any) None
+to_dict() Dict[str, Any]
+validate() bool
}
The class includes a default configuration with essential parameters such as symbol, interval, theme, locale, and timezone. Developers can update the configuration using the update method, retrieve specific configuration items with get, and set individual items with set. The validate method ensures that required fields are present before initialization.
The TVChart class provides methods for controlling chart behavior, managing studies, creating shapes, handling events, and customizing chart appearance. Each chart instance corresponds to a single chart panel in the widget and can be accessed through the TVWidget's chart or activeChart methods.
classDiagram
class TVChart {
+__init__(object_id = "")
+applyLineToolsState(state : Any, callback : CallBackParams = None) None
+applyStudyTemplate(template : Any) None
+availableZOrderOperations(sources : Any) Any
+barTimeToEndOfPeriod(unixTime : int) int
+bringForward(sources : Any) None
+bringToFront(sources : Any) None
+canZoomOut() bool
+cancelSelectBar() None
+chartType() SeriesType
+clearMarks(marksToClear : Any = None) None
+createAnchoredShape(position : TVShapePosition, options : TVAnchorShape) EntityId
+createExecutionShape(options : Any = None) TVExecutionLine
+createMultipointShape(points : list[TVShapePoint], options : TVMultipleShape) EntityId
+createOrderLine(options : Any = None) TVOrderLine
+createPositionLine(options : Any = None) TVPositionLine
+createShape(point : TVShapePoint, options : TVSingleShape) EntityId
+createStudy(name : str, forceOverlay : Optional[bool] = None, lock : Optional[bool] = None, inputs : Optional[Dict[str, Any]] = None, overrides : Optional[Any] = None, options : Optional[Any] = None, callback : Optional[CallBackParams] = None) None
+createStudyTemplate(options : Any) dict
+crossHairMoved() None
+dataReady() bool
+endOfPeriodToBarTime(unixTime : int) int
+executeActionById(actionId : str) None
+exportData(options : Optional[Any] = None, callback : CallBackParams = None) None
+getAllPanesHeight() List[int]
+getAllShapes() List[Dict[str, Any]]
+getAllStudies() List[Dict[str, Any]]
+getCheckableActionState(actionId : str) Optional[bool]
+getLineToolsState() Any
+getPanes() List[TVPane]
+getPriceToBarRatio() Optional[float]
+getSeries() TVSeries
+getShapeById(entityId : str) TVShape
+getStudyById(entityId : str) TVStudy
+getTimeScale() TVTimeScale
+getTimezoneApi() TVTimezone
+getVisibleRange() Any
+isMaximized() bool
+isPriceToBarRatioLocked() bool
+isSelectBarRequested() bool
+loadChartTemplate(templateName : str, callback : CallBackParams = None) None
+maximizeChart() None
+onChartTypeChanged() TVSubscription
+onDataLoaded() TVSubscription
+onHoveredSourceChanged() TVSubscription
+onIntervalChanged() TVSubscription
+onSymbolChanged() TVSubscription
+onVisibleRangeChanged() TVSubscription
+priceFormatter() Any
+refreshMarks() None
+reloadLineToolsFromServer() None
+removeAllShapes() None
+removeAllStudies() None
+removeEntity(entityId : Any, options : Optional[Any] = None) None
+requestSelectBar(callback : CallBackParams) None
+resetData() None
+resolution() Any
+restoreChart() None
+selection() TVSelection
+sendBackward(sources : List[Any]) None
+sendToBack(entities : List[Any]) None
+setAllPanesHeight(heights : List[int]) None
+setChartType(type : Any, callback : Optional[Callable[[], None]] = None) None
+setDragExportEnabled(enabled : bool) None
+setPriceToBarRatio(ratio : float, options : Optional[Any] = None) None
+setPriceToBarRatioLocked(value : bool, options : Optional[Any] = None) None
+setResolution(resolution : Any, options : Optional[Union[Any, Callable[[], None]]] = None, callback : CallBackParams = None) Awaitable[bool]
+setScrollEnabled(enabled : bool) None
+setSymbol(symbol : str, options : Optional[Union[Any, Callable[[], None]]] = None) None
+setTimeFrame(timeFrame : Any) None
+setVisibleRange(range : Any, options : Optional[Any] = None, callback : CallBackParams = None) None
+setZoomEnabled(enabled : bool) None
+shapesGroupController() TVShapesGroupController
+showPropertiesDialog(studyId : Any) None
+symbol() str
+symbolExt() Optional[Any]
+zoomOut() None
}
The TVChart class offers extensive methods for chart manipulation, including changing the chart type with setChartType, setting the resolution (interval) with setResolution, and controlling the visible range with setVisibleRange. The zoomOut method executes a chart zoom out operation, while canZoomOut checks whether zooming out is possible.
For time-based operations, the class provides barTimeToEndOfPeriod to get the end-of-period time for a Unix timestamp and endOfPeriodToBarTime to convert end-of-period time to a bar timestamp. The getTimeScale method returns the time scale API object for further customization.
Series control is managed through methods like getSeries which returns the API object for the main series, and setSymbol which changes the trading symbol. The symbol method returns the current chart's trading symbol name, while symbolExt provides extended information about the symbol.
The class also supports price formatting with priceFormatter and mainSeriesPriceFormatter, allowing developers to format price display according to their requirements. The getPriceToBarRatio and related methods provide control over the chart's price-to-bar ratio, which can be locked or unlocked as needed.
Event subscription in TVChart is implemented through dedicated methods that return TVSubscription objects. These include onChartTypeChanged, onDataLoaded, onHoveredSourceChanged, onIntervalChanged, onSymbolChanged, and onVisibleRangeChanged. Each method allows subscribing to specific chart events with callback functions.
The subscription pattern follows a consistent interface: call the method to get a subscription object, then use its subscribe method to register a callback. This enables real-time monitoring of chart state changes and user interactions, facilitating responsive applications that react to user actions on the chart.
The TVChart class provides comprehensive support for creating and managing drawing tools through various shape creation methods. These include createShape for single-point shapes like vertical lines, createMultipointShape for multi-point shapes like trend lines, and createAnchoredShape for shapes that maintain relative position as the chart range changes.
For trading platform functionality, the class offers createOrderLine, createPositionLine, and createExecutionShape to create trading-related markers. Shape management is further enhanced by methods like getAllShapes, getShapeById, and removeAllShapes, allowing complete control over the chart's drawing elements.
The Z-order of shapes can be manipulated with bringForward, bringToFront, sendBackward, and sendToBack methods. Additionally, the selection method returns a selection API object for managing shape selection, while shapesGroupController provides access to group operations for multiple shapes.
The TVWidget and TVChart classes have a hierarchical relationship where TVWidget serves as the container and controller for one or more TVChart instances. This relationship enables the management of complex multi-chart layouts while maintaining individual chart control.
classDiagram
TVWidget --> TVChart : contains
TVWidget --> TVWidgetConfig : uses
TVChart --> TVSeries : controls
TVChart --> TVStudy : manages
TVChart --> TVShape : creates
TVWidget ..> TVSubscription : subscribes to events
TVChart ..> TVSubscription : subscribes to events
The TVWidget acts as the primary interface for widget-level operations such as initialization, configuration, and global settings, while delegating chart-specific operations to individual TVChart instances. This separation of concerns allows for both global widget management and granular chart control.
In multi-chart layouts, the TVWidget manages the overall layout and coordinates between charts, while each TVChart maintains its own state and configuration. Methods like activeChart and chart provide access to specific chart instances, enabling targeted operations on individual charts within a layout.
# Initialize widget configuration
config = TVWidgetConfig({
"symbol": "BTCUSDT",
"interval": "1D",
"theme": "Dark",
"locale": "en"
})
# Create and initialize the widget
widget = TVWidget("widget_1")
await widget.onChartReady(lambda: print("Chart is ready"))# Get the active chart and customize it
chart = await widget.activeChart()
await chart.setChartType("candle")
await chart.setResolution("4H")
# Add an indicator
await chart.createStudy("Moving Average", inputs={"length": 20})
# Create a drawing
shape_id = await chart.createShape(
TVShapePoint(100, 50000),
TVSingleShape({"shape": "vertical_line"})
)# Subscribe to symbol changes
subscription = await chart.onSymbolChanged()
await subscription.subscribe(lambda symbol: print(f"Symbol changed to {symbol}"))
# Subscribe to visible range changes
range_subscription = await chart.onVisibleRangeChanged()
await range_subscription.subscribe(lambda range: print(f"Visible range: {range}"))When managing multiple charts, several performance optimization strategies should be employed:
-
Unload Unused Charts: Use the
unloadUnusedChartsmethod to release memory from invisible charts in multi-chart layouts. This is particularly important after layout changes. -
Efficient Event Handling: Properly manage event subscriptions by unsubscribing when they are no longer needed to prevent memory leaks and unnecessary callback executions.
-
Batch Operations: When performing multiple chart operations, consider the order and grouping of operations to minimize redraws and updates.
-
Cache Management: Use
resetCacheto clear cached data for all symbols when necessary, such as after network recovery or data refresh. -
Resource Cleanup: Call the
removemethod on the TVWidget when it's no longer needed to clean up all associated resources and prevent memory leaks.
The TVWidget and TVChart classes provide a comprehensive API for controlling TradingView widgets and charts in Python applications. The TVWidget class serves as the main interface for widget initialization, configuration, and lifecycle management, while the TVChart class offers detailed control over individual chart behavior, series, and drawing tools.
The relationship between these classes enables both high-level widget management and granular chart control, making it possible to create complex multi-chart layouts with customized behavior. The event-driven architecture supports real-time updates and interactive applications, while the asynchronous design ensures non-blocking operations.
By following the documented patterns for configuration, event handling, and performance optimization, developers can create responsive and efficient TradingView integrations that meet various application requirements.