-
Notifications
You must be signed in to change notification settings - Fork 1
Installation and Setup
- Installation Methods
- Development Environment Setup
- Dependency Configuration
- Integration with TradingView Advanced Charts
- TVEngine Initialization and Verification
- Troubleshooting Common Issues
The PyTradingView library can be installed through multiple methods to accommodate different use cases and development workflows. The library requires Python 3.8 or higher, as specified in the project configuration.
The recommended method for installing PyTradingView is through the Python Package Index (PyPI) using pip. This approach provides the stable release version of the library with all dependencies automatically resolved.
pip install pytradingviewlibThis command installs the latest published version of PyTradingView from PyPI, making it immediately available for use in your Python environment. The package name pytradingviewlib is used on PyPI to distinguish it from potential naming conflicts.
For users who need the latest development features or wish to contribute to the project, installing directly from the source repository is recommended. This method provides access to the most recent code changes and allows for modification of the library itself.
To install from source, first clone the repository and then install the package in editable mode:
git clone https://github.com/great-bounty/pytradingview.git
cd pytradingview
pip install -e .The -e flag creates an editable installation, meaning that changes to the source code will be immediately reflected without requiring a reinstallation. This is particularly useful for development and debugging purposes.
Setting up a proper development environment is essential for contributing to the PyTradingView project or extending its functionality for custom use cases.
The project includes a comprehensive set of development tools for testing, code quality assurance, and documentation. These can be installed using the [dev] extras syntax, which automatically installs both the main package and development dependencies:
pip install -e ".[dev]"Alternatively, the development dependencies can be installed from the requirements files:
pip install -r requirements.txt
pip install -r requirements-dev.txtThe development dependencies include pytest for testing, black for code formatting, ruff for linting, mypy for type checking, and other tools that ensure code quality and consistency.
flowchart TD
A[Clone Repository] --> B[Create Virtual Environment]
B --> C[Install Dependencies]
C --> D[Run Verification Tests]
D --> E[Start Development]
C --> C1[Install Main Dependencies]
C --> C2[Install Development Tools]
C1 --> D
C2 --> D
PyTradingView relies on several key dependencies that enable its core functionality for interacting with TradingView charts and processing financial data.
The library requires the following core dependencies, as specified in the pyproject.toml file:
- FastAPI: Provides the web server framework for the bridge between Python and JavaScript
- uvicorn: ASGI server for running the FastAPI application
- websocket-client: Enables WebSocket communication with the TradingView widget
- pandas: Data manipulation and analysis library for handling financial time series data
- aiohttp: Asynchronous HTTP client/server framework
- pandas-ta: Technical analysis library for implementing trading indicators
These dependencies are automatically installed when using pip to install the package. The minimum required versions ensure compatibility with the library's features while allowing for reasonable flexibility in the user's environment.
The library includes a configuration management system through the TVWidgetConfig class, which handles widget initialization parameters. The default configuration includes settings for symbol, interval, theme, locale, and other display options.
DEFAULT_CONFIG: Dict[str, Any] = {
"symbol": "BTCUSDT",
"interval": "1D",
"theme": "Dark",
"locale": "zh",
"fullScreen": True,
"debug": False,
"autosize": True,
"timezone": "Asia/Shanghai"
}Users can override these defaults by providing a custom configuration dictionary when initializing the engine.
classDiagram
class TVWidgetConfig {
+DEFAULT_CONFIG : Dict[str, Any]
+__init__(config : Optional[Dict[str, Any]])
+update(config : Dict[str, Any])
+get(key : str, default : Any)
+set(key : str, value : Any)
+to_dict()
+validate()
}
TVEngine --> TVWidgetConfig : "uses"
Integrating PyTradingView with TradingView Advanced Charts requires proper configuration of the widget and establishing a connection between the Python backend and the JavaScript frontend.
The integration process begins with configuring the TradingView widget to communicate with the Python server. The library uses a bridge pattern to facilitate communication between the Python application and the TradingView JavaScript library.
The configuration process involves:
- Setting up the widget with appropriate parameters (symbol, interval, theme, etc.)
- Establishing a WebSocket connection between the frontend and backend
- Registering callbacks for chart events and data updates
- Initializing the indicator engine to process and display trading signals
The TVBridge class handles the communication between Python and JavaScript, exposing Python methods to the frontend and receiving events from the chart widget.
The connection is established when the TVEngine is initialized and the run() method is called. This starts the FastAPI server and uvicorn, creating an endpoint that the TradingView widget can connect to via WebSocket.
The bridge service registers configuration providers and chart ready callbacks, ensuring that the widget is properly configured and that the engine responds to chart initialization events.
The TVEngine class serves as the main entry point for the PyTradingView library, providing a singleton pattern implementation that ensures a single instance manages all interactions with TradingView charts.
The TVEngine follows a modular design with several key components:
- Singleton Management: Ensures global unique instance
- Module Loading: Handles loading of indicator modules
- Indicator Management: Manages activation and deactivation of indicators
- Configuration Management: Handles widget and engine configuration
- Remote Call: Supports Electron IPC for remote control
- Event-driven Architecture: Uses EventBus for communication
To initialize the engine:
from pytradingview import TVEngine
# Get singleton instance
engine = TVEngine.get_instance()
# Configure and run the engine
engine.setup('./indicators', config={'symbol': 'BTCUSDT'}).run()The setup() method configures the engine with the indicators directory and optional configuration parameters, while the run() method starts the bridge service and begins listening for chart events.
To verify a successful installation and connection, users can perform a basic connectivity test by initializing the engine and checking its status:
# Get engine instance
engine = TVEngine.get_instance()
# Check if engine is properly initialized
if engine._initialized:
print("PyTradingView engine initialized successfully")
# Get engine status
status = engine.remote_get_status()
print(f"Engine status: {status}")The engine emits log messages during startup that can be used to verify successful initialization:
INFO: Starting Indicator Engine...
INFO: Widget config: {'symbol': 'BTCUSDT', 'interval': '1D', ...}
INFO: TVEngine singleton initialized
These logs confirm that the engine has started, the configuration has been loaded, and the singleton instance has been created.
sequenceDiagram
participant User as "User Code"
participant Engine as "TVEngine"
participant Bridge as "TVBridge"
participant Widget as "TradingView Widget"
User->>Engine : get_instance()
Engine->>Engine : Create singleton instance
User->>Engine : setup(indicators_dir, config)
Engine->>Engine : Update configuration
Engine->>Engine : Load indicators
User->>Engine : run()
Engine->>Bridge : register_config_provider()
Engine->>Bridge : register_chart_ready_callback()
Engine->>Bridge : run()
Bridge->>Bridge : start_http_server()
Bridge->>Widget : Establish WebSocket connection
Widget->>Engine : Chart ready event
Engine->>Engine : Initialize charts and indicators
Dependency conflicts can occur when other packages in the environment require different versions of shared dependencies. To resolve these issues:
- Use a virtual environment to isolate the PyTradingView installation
- Check for version conflicts using
pip check - Update all packages to compatible versions
- Consider using
pip-toolsto manage dependency resolution
If you encounter missing package errors, ensure that:
- You have installed the package using the correct name (
pytradingviewlib) - Your Python environment is activated (if using virtual environments)
- You have internet connectivity for package downloads
- Your pip version is up to date
On Windows systems, you may encounter issues with long file paths. To resolve this:
- Enable long path support in Windows
- Install the package in a directory with a short path
- Use the Windows Subsystem for Linux (WSL) for development
On macOS, ensure that you have the latest version of Xcode command line tools installed, as some dependencies may require compilation.
If the connection between Python and the TradingView widget fails:
- Verify that the FastAPI server is running
- Check that the WebSocket connection is established
- Ensure that the widget configuration matches the expected format
- Verify that the port is not blocked by a firewall