-
Notifications
You must be signed in to change notification settings - Fork 1
Examples and Use Cases
- Basic Engine Setup
- Indicator Implementation Walkthrough
- False Breakout Indicator Analysis
- Custom Datafeed Implementation
- Architectural Patterns
- Deployment and Productionization
- Use Case Extensions
The PyTradingView engine initialization follows a modular singleton pattern that ensures thread safety and global instance uniqueness. The engine setup process begins with creating a singleton instance and configuring the indicator directory path. The minimal setup requires only two lines of code: one to instantiate the engine and another to run it with the specified indicators directory.
The engine architecture employs a mixin-based inheritance hierarchy that separates concerns into distinct functional modules: singleton management, module loading, indicator management, configuration management, remote call handling, drawing functionality, and runtime control. This design enables maintainability and extensibility while ensuring that each component has a single responsibility.
The setup process automatically handles indicator discovery, registration, and activation based on configuration parameters. When calling the setup method, developers can specify the indicators directory path, enable auto-activation of enabled indicators, and provide custom configuration parameters that will be applied to the widget.
Creating custom indicators in PyTradingView follows a standardized interface defined by the TVIndicator base class. All custom indicators must inherit from this abstract base class and implement the required methods: get_config() for configuration definition and calculate() for signal generation. The indicator lifecycle is managed by the engine, which handles initialization, data loading, calculation, and cleanup events.
The implementation pattern uses dataclasses to define structured data types for signals and drawable elements. TVSignal represents trading signals with properties for signal type (buy/sell), timestamp, price, and metadata. TVDrawable encapsulates visual elements with points (time, price) coordinates and shape configuration. This separation of concerns allows indicators to focus on logic while the engine handles visualization.
Indicators can override optional lifecycle methods such as on_init(), on_data_loaded(), on_calculate_start(), and on_destroy() to implement custom behavior at different stages of the indicator lifecycle. The engine automatically manages chart references, widget connections, and data caching, allowing indicators to focus on their core algorithmic logic without worrying about infrastructure concerns.
The false breakout indicator demonstrates advanced pattern recognition techniques by detecting price movements that break through recent highs or lows but quickly reverse direction. This sophisticated implementation showcases multiple advanced features including dynamic configuration parameters, custom drawing elements, and multi-condition signal generation.
The indicator configuration defines several input parameters that users can adjust: the false breakout period (number of bars for high/low detection), minimum period (minimum bars between breakouts), signal validity period, smoothing type (diamond, WMA, or HMA), smoothing length, and aggressive mode toggle. These parameters are organized into logical groups (Main Settings and Advanced Smoothing) for better user experience.
The calculation algorithm implements a state machine using the FalseBreakoutState dataclass to track the sequence of price movements. It detects new highs and lows using rolling window calculations, applies configurable smoothing filters, and identifies false breakouts when price reverses through the trigger level within the validity period. The implementation includes both upward false breakouts (price breaks new low then reverses up) and downward false breakouts (price breaks new high then reverses down).
For visualization, the indicator creates directional arrows (TVArrowUp/TVArrowDown) at signal points and draws horizontal trend lines at the breakout levels. The styling is configurable through the indicator configuration, allowing users to customize colors, line widths, and visibility. The drawing logic automatically handles timestamp conversion and applies the appropriate overrides to the shape objects.
flowchart TD
Start([Start Calculation]) --> ValidateData["Validate Data Length"]
ValidateData --> DataValid{"Data Valid?"}
DataValid --> |No| ReturnEmpty["Return Empty Lists"]
DataValid --> |Yes| GetConfig["Get Configuration Parameters"]
GetConfig --> CalculateHighLow["Calculate Rolling High/Low"]
CalculateHighLow --> ApplySmoothing["Apply Selected Smoothing Filter"]
ApplySmoothing --> DetectConditions["Detect New High/Low Conditions"]
DetectConditions --> TrackState["Update Breakout State"]
TrackState --> CheckBreakout["Check False Breakout Conditions"]
CheckBreakout --> ValidBreakout{"Valid False Breakout?"}
ValidBreakout --> |Yes| GenerateSignal["Create TVSignal Object"]
ValidBreakout --> |No| ContinueLoop["Continue to Next Bar"]
GenerateSignal --> CreateDrawable["Create TVDrawable with Trend Line"]
CreateDrawable --> AddToResults["Add to Results Lists"]
AddToResults --> ContinueLoop
ContinueLoop --> LoopEnd{"End of Data?"}
LoopEnd --> |No| ProcessNextBar["Process Next Bar"]
LoopEnd --> |Yes| ReturnResults["Return Signals and Drawables"]
**Diagram sources **
Implementing a custom datafeed in PyTradingView requires extending the TVDatafeed base class and implementing the required methods for symbol resolution, historical data retrieval, and real-time updates. The datafeed architecture follows the TradingView Charting Library API specification, ensuring compatibility with the frontend widget.
The TVDatafeed class implements three core interfaces: IExternalDatafeed for general configuration, IDatafeedChartApi for chart-related functionality, and IDatafeedQuotesApi for quote data. Key methods that must be implemented include resolveSymbol() for symbol information, getBars() for historical OHLC data, and subscribeBars() for real-time bar updates. The datafeed maintains subscriber dictionaries to manage multiple chart instances and their respective callbacks.
A production-ready datafeed implementation would connect to a market data provider API, cache frequently requested data, handle authentication and rate limiting, and implement proper error handling and logging. The base implementation provides a foundation with logging and subscriber management, allowing developers to focus on the specific data source integration.
When implementing real-time updates, the datafeed should push new bar data to all subscribed listeners through their onTick callbacks. For historical data, the getBars method should return candlestick data in the format expected by TradingView, along with metadata indicating whether more data is available for pagination.
PyTradingView employs several architectural patterns that facilitate the development of robust trading systems, alerting engines, and backtesting platforms. The core architecture follows a modular, mixin-based inheritance pattern that promotes separation of concerns and code reuse.
For trading systems, the recommended pattern involves creating specialized indicator classes that generate trading signals (buy/sell) and integrating them with order execution systems. The TVExecutionLine, TVOrderLine, and TVPositionLine classes provide visualization for trading activities, while the indicator engine handles the signal generation logic.
Alerting engines can be built by extending the indicator base class to monitor specific conditions and trigger notifications when met. The engine's event-driven architecture, based on EventBus, allows for decoupled communication between components. Developers can subscribe to chart events such as onDataLoaded, onIntervalChanged, or onSymbolChanged to implement responsive alerting logic.
Backtesting platforms leverage the same indicator calculation engine but operate on historical data sets. The pattern involves loading historical market data into a pandas DataFrame, running indicators on the complete dataset, and analyzing the generated signals for performance metrics. The TVExportedData class facilitates data export from the chart for backtesting purposes.
The multi-chart support architecture uses a ChartContextManager to maintain separate contexts for each chart in a layout. This allows indicators to be managed independently per chart while sharing the same engine instance. When the layout changes, the engine automatically cleans up old chart contexts and initializes new ones, ensuring proper resource management.
classDiagram
class TVEngine {
+setup(indicators_dir, auto_activate, config)
+run(widget_config, indicators_dir, on_port)
+activate_indicator(name, chart_id)
+deactivate_indicator(name, chart_id)
+update_indicator_config(name, config_dict, chart_id)
+recalculate_indicator(name, chart_id)
}
class TVIndicator {
+get_config()
+calculate(df)
+draw(chart, df, signals, drawables)
+on_init(widget, chart, chart_id)
+on_destroy()
}
class TVDatafeed {
+onReady(callback)
+resolveSymbol(symbolName, onResolve, onError, extension)
+getBars(symbolInfo, resolution, periodParams, onResult, onError)
+subscribeBars(symbolInfo, resolution, onTick, listenerGuid, onResetCacheNeededCallback)
+getQuotes(symbols, onDataCallback, onErrorCallback)
+subscribeQuotes(symbols, fastSymbols, onRealtimeCallback, listenerGUID)
}
class TVChart {
+createStudy(name, forceOverlay, lock, inputs, overrides, options, callback)
+createMultipointShape(points, options)
+createShape(point, options)
+getSeries()
+getTimeScale()
+onDataLoaded()
+onIntervalChanged()
+onSymbolChanged()
}
class TVWidget {
+activeChart()
+chart(index)
+chartsCount()
+headerReady(callback)
+onChartReady(callback)
+createButton(options)
+createDropdown(title, items, tooltip, icon, align)
}
TVEngine --> TVIndicator : "manages"
TVEngine --> TVDatafeed : "integrates with"
TVEngine --> TVWidget : "controls"
TVWidget --> TVChart : "contains"
TVChart --> TVIndicator : "hosts"
TVDatafeed ..> TVChart : "provides data to"
**Diagram sources **
Moving from examples to production systems requires addressing several deployment considerations and implementing productionization patterns. The first step involves containerizing the application using Docker to ensure consistent environments across development, testing, and production.
For production deployment, implement proper logging and monitoring using structured logging with appropriate log levels. The existing logging framework should be extended to include application metrics, error tracking, and performance monitoring. Integrate with centralized logging solutions like ELK stack or cloud-based monitoring services.
Security considerations include protecting API keys and credentials through environment variables or secret management services, implementing proper input validation, and ensuring secure communication channels. For datafeeds connecting to external APIs, implement rate limiting, circuit breakers, and retry mechanisms with exponential backoff.
Performance optimization patterns include caching frequently accessed data, implementing connection pooling for database and API connections, and optimizing indicator calculations through vectorized operations with pandas and numpy. For high-frequency data processing, consider implementing asynchronous processing and message queues.
Configuration management should be separated from code using environment-specific configuration files or configuration services. Implement health checks and readiness probes for container orchestration platforms like Kubernetes. Set up automated testing and continuous integration/continuous deployment (CI/CD) pipelines to ensure code quality and reliable deployments.
The PyTradingView framework can be extended for specific use cases across different financial markets. For cryptocurrency trading, extend the datafeed implementation to connect to popular crypto exchange APIs such as Binance, Coinbase, or Kraken. Implement specialized indicators that account for the unique characteristics of cryptocurrency markets, including high volatility, 24/7 trading, and correlation between different digital assets.
For stock analysis, integrate with financial data providers like Alpha Vantage, Yahoo Finance, or Bloomberg to access fundamental data, earnings reports, and analyst ratings. Develop indicators that combine technical analysis with fundamental metrics, such as price-to-earnings ratio overlays or earnings surprise detectors. Implement sector and industry grouping to enable relative strength analysis across market segments.
Futures markets require handling contract rollover logic, where the active contract changes as expiration approaches. Implement a datafeed that automatically manages the transition between front-month and back-month contracts, providing continuous price series for technical analysis. Develop indicators that account for contango and backwardation in futures curves, and implement seasonality analysis for commodities.
Additional use cases include building algorithmic trading systems with risk management rules, creating portfolio monitoring dashboards with multiple correlated instruments, and developing educational tools for technical analysis pattern recognition. The modular architecture allows for combining multiple indicators and strategies, enabling sophisticated multi-timeframe and multi-asset analysis.