-
Notifications
You must be signed in to change notification settings - Fork 1
API Reference
The TVEngine class serves as the central indicator engine in PyTradingView, implementing a singleton pattern to ensure a globally unique instance. It provides modular functionality through various mixins including configuration management, module loading, indicator management, remote calls, drawing capabilities, and runtime control. The engine is thread-safe and uses a lock mechanism to ensure concurrent safety during initialization.
Initialization occurs only on the first call to the constructor, with subsequent calls returning the existing instance without re-initialization. The engine supports dynamic configuration updates at runtime and provides complete Electron IPC support for remote calls. Event communication is handled through an EventBus system, enabling event-driven architecture.
The engine lifecycle is managed through setup and run methods. The setup() method configures the engine with an indicator directory path, auto-activation settings, and widget configuration. The run() method serves as the main entry point, handling configuration validation, indicator loading, widget callback registration, event listener setup, and starting the Bridge service.
classDiagram
class TVEngine {
+get_instance() TVEngine
+setup(indicators_dir : str, auto_activate : bool, config : Dict) TVEngineRuntime
+run(widget_config : Dict, indicators_dir : str, on_port : int) None
+update_config(config_dict : Dict) TVEngineConfig
+get_config() Dict
+set_config(config : Dict) TVEngineConfig
+get_indicator_config(name : str, chart_id : str) Dict
+update_indicator_config(name : str, config_dict : Dict, chart_id : str) Tuple[bool, List]
+update_indicator_input(name : str, input_id : str, value : Any, chart_id : str) Tuple[bool, str]
+update_indicator_style(name : str, style_id : str, chart_id : str, **kwargs) Tuple[bool, str]
+recalculate_indicator(name : str, chart_id : str) Tuple[bool, str]
+recalculate_all_indicators(chart_id : str) Dict[str, Tuple[bool, str]]
+get_all_configs(chart_id : str) Dict[str, Dict]
}
class TVEngineRuntime {
+__init__(config : TVWidgetConfig) None
+setup(indicators_dir : str, auto_activate : bool, config : Dict) TVEngineRuntime
+run(widget_config : Dict, indicators_dir : str, on_port : int) None
}
class TVEngineConfig {
+update_config(config_dict : Dict) TVEngineConfig
+get_config() Dict
+set_config(config : Dict) TVEngineConfig
+get_indicator_config(name : str, chart_id : str) Dict
+update_indicator_config(name : str, config_dict : Dict, chart_id : str) Tuple[bool, List]
+update_indicator_input(name : str, input_id : str, value : Any, chart_id : str) Tuple[bool, str]
+update_indicator_style(name : str, style_id : str, chart_id : str, **kwargs) Tuple[bool, str]
+recalculate_indicator(name : str, chart_id : str) Tuple[bool, str]
+recalculate_all_indicators(chart_id : str) Dict[str, Tuple[bool, str]]
+get_all_configs(chart_id : str) Dict[str, Dict]
}
TVEngine --> TVEngineRuntime : "inherits"
TVEngine --> TVEngineConfig : "inherits"
TVEngineRuntime --> TVEngineDrawing : "inherits"
TVEngineConfig --> TVEngineManager : "inherits"
The TVWidget class provides a comprehensive Python interface to the TradingView Widget API, allowing interaction with TradingView charts. It enables creation, configuration, and control of TradingView chart widgets. Key methods include chart management (activeChart, chart, chartsCount), UI element creation (createButton, createDropdown), theme management (changeTheme), and state management (load, save).
The TVChart class represents a single chart panel within the widget and provides methods for chart manipulation and property access. It supports asynchronous operations for real-time interaction with the chart. Key capabilities include study management (createStudy, getAllStudies, removeAllStudies), shape creation (createShape, createMultipointShape, createAnchoredShape), data access (getBars, exportData), and event subscription (onDataLoaded, onIntervalChanged, onSymbolChanged).
Both classes support error handling through proper exception management and return type validation. The widget class handles callbacks through registered callback functions that are invoked when specific events occur in the frontend.
classDiagram
class TVWidget {
+activeChart() TVChart
+activeChartIndex() int
+addCustomCSSFile(url : str) None
+applyOverrides(overrides : Dict) None
+applyStudiesOverrides(overrides : Dict) None
+applyTradingCustomization(config : Dict) None
+changeTheme(theme_name : str, options : Dict, callback : CallBackParams) None
+chart(index : int) TVChart
+chartsCount() int
+clearUndoHistory() None
+closePopupsAndDialogs() None
+createButton(options : Dict) TVHMElement
+createDropdown(title : str, items : List[Dict], tooltip : str, icon : str, align : str) TVDropdownApi
+load(state : Dict, extended_data : Dict) None
+loadChartFromServer(record : Dict) None
+save() None
+saveChartToServer() None
+setLayout(layout : str) None
+setSymbol(symbol : str) None
+showConfirmDialog(title : str, text : str, callback : CallBackParams) None
+showNoticeDialog(text : str) None
+showSaveAsChartDialog() None
+subscribe(event : str, callback : CallBackParams) None
+unsubscribe(event : str) None
+widgetbar() TVWidgetbar
}
class TVChart {
+applyLineToolsState(state : Any, callback : CallBackParams) 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
+createAnchoredShape(position : TVShapePosition, options : TVAnchorShape) EntityId
+createExecutionShape(options : Any) TVExecutionLine
+createMultipointShape(points : List[TVShapePoint], options : TVMultipleShape) EntityId
+createOrderLine(options : Any) TVOrderLine
+createPositionLine(options : Any) TVPositionLine
+createShape(point : TVShapePoint, options : TVSingleShape) EntityId
+createStudy(name : str, forceOverlay : bool, lock : bool, inputs : Dict, overrides : Any, options : Any, callback : CallBackParams) str
+createStudyTemplate(options : Any) Dict
+crossHairMoved() None
+dataReady(callback : CallBackParams) bool
+endOfPeriodToBarTime(unixTime : int) int
+executeActionById(actionId : str) None
+exportData(options : Any, callback : CallBackParams) Any
+getAllPanesHeight() List[int]
+getAllShapes() List[Dict]
+getAllStudies() List[Dict]
+getCheckableActionState(actionId : str) bool
+getLineToolsState() Any
+getPanes() List[TVPane]
+getPriceToBarRatio() 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
+marketStatus() Any
+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 : str) None
+requestSelectBar(callback : CallBackParams) None
+resetData() None
+restoreChart() None
+sendBackward(sources : Any) None
+sendToBack(sources : Any) None
+setAllPanesHeight(heights : List[int]) None
+setChartType(chartType : str) None
+setDebugMode(enabled : bool) None
+setDragExportEnabled(enabled : bool) None
+setPriceToBarRatio(ratio : float) None
+setPriceToBarRatioLocked(locked : bool) None
+setResolution(resolution : str) None
+setScrollEnabled(enabled : bool) None
+setSymbol(symbol : str) None
+setSymbolOptions(options : Dict) None
+setTimeFrame(timeframe : str) None
+setVisibleRange(range : Dict) None
+setZoomEnabled(enabled : bool) None
+shapesGroupController() TVShapesGroupController
+showPropertiesDialog() None
+symbol() str
+symbolExt() str
+timeSync() TVWatchedValue
+zoomOut() None
}
TVWidget --> TVChart : "contains"
TVChart --> TVSubscription : "returns"
TVChart --> TVStudy : "returns"
TVChart --> TVShape : "returns"
TVChart --> TVSeries : "returns"
TVChart --> TVTimeScale : "returns"
TVChart --> TVTimezone : "returns"
TVChart --> TVPane : "returns"
The TVIndicator base class defines a standardized interface for custom indicators in PyTradingView. All custom indicators must inherit from this class and implement the required methods. The class provides a comprehensive lifecycle management system with initialization, data loading, calculation, drawing, and destruction callbacks.
Key methods include get_config() which returns the indicator configuration, and calculate(df) which performs the core indicator calculations on the provided DataFrame containing OHLC data. The optional draw() method allows for custom chart element rendering. The base class also provides helper methods for configuration management, including update_config(), update_input_value(), and update_style().
The indicator lifecycle includes several callback methods: on_init() for initialization, on_data_loaded() when data is loaded, on_calculate_start() and on_calculate_end() around calculation, on_draw_start() and on_draw_end() around drawing, and on_destroy() for cleanup. The class supports automatic recalculation when configuration changes through the needs_recalculate() and recalculate_and_redraw() methods.
classDiagram
class TVIndicator {
<<abstract>>
+__init__(chart_id : str) None
+get_config() IndicatorConfig
+calculate(df : DataFrame) Tuple[List[TVSignal], List[TVDrawable]]
+draw(chart : TVChart, df : DataFrame, signals : List[TVSignal], drawables : List[TVDrawable]) None
+on_init(widget : TVWidget, chart : TVChart, chart_id : str) None
+on_data_loaded(df : DataFrame) None
+on_calculate_start() None
+on_calculate_end(signals : List[TVSignal], drawables : List[TVDrawable]) None
+on_draw_start() None
+on_draw_end() None
+on_destroy() None
+get_chart() TVChart
+get_widget() TVWidget
+get_chart_id() str
+set_chart_id(chart_id : str) None
+add_drawn_entity(entity_id : str) None
+get_drawn_entities() List[str]
+clear_all_drawings() None
+get_config_dict() Dict
+update_config(config_dict : Dict) Tuple[bool, List]
+update_input_value(input_id : str, value : Any) Tuple[bool, str]
+update_style(style_id : str, **kwargs) Tuple[bool, str]
+needs_recalculate() bool
+mark_recalculate_done() None
+recalculate_and_redraw() Tuple[bool, str]
}
class TVSignal {
+signal_type : str
+timestamp : int
+price : float
+metadata : Dict
}
class TVDrawable {
+points : List[Tuple[int, float]]
+shape : Any
+metadata : Dict
}
class IndicatorConfig {
+name : str
+version : str
+description : str
+author : str
+enabled : bool
+debug : bool
+inputs : List[InputDefinition]
+styles : List[StyleDefinition]
+on_config_changed : Callable
+get_input_value(input_id : str) Any
+set_input_value(input_id : str, value : Any) Tuple[bool, str]
+set_input_values(values : Dict) Tuple[bool, List]
+get_style(style_id : str) StyleDefinition
+update_style(style_id : str, **kwargs) Tuple[bool, str]
+validate_all() Tuple[bool, List]
+to_dict() Dict
+from_dict(data : Dict) IndicatorConfig
+reset_to_defaults() None
}
class InputDefinition {
+id : str
+display_name : str
+type : InputType
+default_value : Any
+value : Any
+tooltip : str
+options : List[InputOption]
+min_value : float
+max_value : float
+step : float
+visible : bool
+group : str
+validate() Tuple[bool, str]
+to_dict() Dict
}
class StyleDefinition {
+id : str
+display_name : str
+color : str
+line_width : int
+line_style : int
+transparency : int
+visible : bool
+group : str
+validate() Tuple[bool, str]
+to_dict() Dict
}
TVIndicator <|-- CustomIndicator : "inherits"
TVIndicator --> TVSignal : "returns"
TVIndicator --> TVDrawable : "returns"
TVIndicator --> IndicatorConfig : "uses"
IndicatorConfig --> InputDefinition : "contains"
IndicatorConfig --> StyleDefinition : "contains"
The TVDatafeed base class provides a complete implementation of the TradingView datafeed API, combining external datafeed, chart API, and quotes API interfaces. It serves as the foundation for implementing custom data sources that can provide historical and real-time market data to TradingView charts.
The class implements several key interfaces: TVIExternalDatafeed for configuration, TVIDatafeedChartApi for chart data, and TVIDatafeedQuotesApi for quote data. Core methods include onReady() for providing datafeed configuration, searchSymbols() for symbol search functionality, resolveSymbol() for resolving symbol information, getBars() for retrieving historical bars, and subscribeBars() for real-time bar updates.
For real-time data streaming, the class maintains subscriber dictionaries to manage active subscriptions. The subscribeBars() method registers a listener for real-time bar updates, while unsubscribeBars() removes a listener. Similarly, subscribeQuotes() and unsubscribeQuotes() handle real-time quote data subscriptions.
classDiagram
class TVDatafeed {
+__init__() None
+onReady(callback : TVOnReadyCallback) None
+searchSymbols(userInput : str, exchange : str, symbolType : str, onResult : TVSearchSymbolsCallback) None
+resolveSymbol(symbolName : str, onResolve : TVResolveCallback, onError : TVDatafeedErrorCallback, extension : TVSymbolResolveExtension) None
+getBars(symbolInfo : TVLibrarySymbolInfo, resolution : ResolutionString, periodParams : TVPeriodParams, onResult : TVHistoryCallback, onError : TVDatafeedErrorCallback) None
+subscribeBars(symbolInfo : TVLibrarySymbolInfo, resolution : ResolutionString, onTick : TVSubscribeBarsCallback, listenerGuid : str, onResetCacheNeededCallback : Callable) None
+unsubscribeBars(listenerGuid : str) None
+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 TVIExternalDatafeed {
<<interface>>
+onReady(callback : TVOnReadyCallback) None
}
class TVIDatafeedChartApi {
<<interface>>
+searchSymbols(userInput : str, exchange : str, symbolType : str, onResult : TVSearchSymbolsCallback) None
+resolveSymbol(symbolName : str, onResolve : TVResolveCallback, onError : TVDatafeedErrorCallback, extension : TVSymbolResolveExtension) None
+getBars(symbolInfo : TVLibrarySymbolInfo, resolution : ResolutionString, periodParams : TVPeriodParams, onResult : TVHistoryCallback, onError : TVDatafeedErrorCallback) None
+subscribeBars(symbolInfo : TVLibrarySymbolInfo, resolution : ResolutionString, onTick : TVSubscribeBarsCallback, listenerGuid : str, onResetCacheNeededCallback : Callable) None
+unsubscribeBars(listenerGuid : str) None
}
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 TVBar {
+time : int
+open : float
+high : float
+low : float
+close : float
+volume : float
}
class TVLibrarySymbolInfo {
+name : str
+description : str
+type : str
+session : str
+exchange : str
+listed_exchange : str
+timezone : str
+format : str
+pricescale : int
+minmov : int
+has_intraday : bool
+supported_resolutions : List[str]
}
TVDatafeed --|> TVIExternalDatafeed : "implements"
TVDatafeed --|> TVIDatafeedChartApi : "implements"
TVDatafeed --|> TVIDatafeedQuotesApi : "implements"
TVIDatafeedChartApi --> TVBar : "returns"
TVIDatafeedChartApi --> TVLibrarySymbolInfo : "uses"