Skip to content

Layout Management

levi edited this page Nov 6, 2025 · 2 revisions

Layout Management

Table of Contents

  1. Introduction
  2. Layout Configuration and Manipulation
  3. Chart Layout Persistence
  4. Custom UI Controls for Layout Management
  5. Multi-Chart Synchronization
  6. Responsive Dashboard Configuration
  7. State Management During Layout Changes
  8. Performance Optimization
  9. Best Practices

Introduction

PyTradingView provides comprehensive layout management capabilities for creating sophisticated multi-chart trading dashboards. The system enables developers to programmatically control chart layouts, persist user configurations, create custom UI controls, and synchronize behavior across multiple charts. This documentation details the complete layout management API, including methods for configuring layouts, saving and loading chart states, creating custom UI elements, and implementing cross-chart synchronization features.

Layout Configuration and Manipulation

The layout management system in PyTradingView centers around the TVWidget class, which provides methods for retrieving and modifying the current chart layout configuration. The layout() method returns the current layout type as a string identifier (e.g., '2h' for two horizontal charts), while layoutName() returns the saved name of the current layout if one exists.

To programmatically change the layout, the setLayout() method accepts a layout string parameter that defines the desired arrangement. For fine-grained control over multi-chart layouts, setLayoutSizes() allows precise configuration of individual chart dimensions, while resetLayoutSizes() restores default sizing. The chartsCount() method returns the number of charts in the current layout, and chart(index) retrieves a specific chart instance by index.

The system automatically handles layout change events through the indicator engine's runtime mixin, which subscribes to the layout_changed event and reinitializes chart contexts when layouts are switched, ensuring proper state management across layout transitions.

Chart Layout Persistence

PyTradingView provides robust chart persistence capabilities through server-side storage operations. The getSavedCharts() method retrieves a list of all saved chart configurations for the current user, returning an array of chart records with associated metadata. Individual saved charts can be loaded using loadChartFromServer(), which accepts a chart record obtained from getSavedCharts().

To save the current chart configuration to the server, the saveChartToServer() method stores the complete chart state, including layout, indicators, drawings, and settings. For more granular control, the load() method allows loading chart state from a custom object, enabling programmatic restoration of specific configurations.

These persistence methods enable users to create and manage multiple chart templates, switch between different analytical setups, and share configurations across sessions.

flowchart TD
A[Get Saved Charts] --> B{Charts Available?}
B --> |Yes| C[Display Chart List]
B --> |No| D[Create New Chart]
C --> E[Select Chart Template]
E --> F[Load Chart from Server]
F --> G[Apply Layout Configuration]
G --> H[Initialize Indicators]
H --> I[Restore Drawings]
I --> J[Chart Ready]
D --> K[Configure New Layout]
K --> L[Save Chart to Server]
L --> J
Loading

Custom UI Controls for Layout Management

The layout management system supports custom UI controls through the createButton() and createDropdown() methods, allowing developers to create intuitive interfaces for layout manipulation. The createButton() method creates a toolbar button with configurable text, tooltip, icon, alignment, and click callback, returning a TVHMElement instance for further customization.

For more complex layout selection, createDropdown() creates a dropdown menu with multiple items, each having a title and optional selection callback. The method returns a TVDropdownApi object that can be used to modify the dropdown after creation. These UI elements can be aligned to the left or right of the toolbar, enabling flexible interface designs.

Custom controls can be programmed to trigger layout changes, load specific templates, or perform other layout management operations, creating a seamless user experience for dashboard configuration.

classDiagram
TVWidget --> TVHMElement : creates
TVWidget --> TVDropdownApi : creates
TVHMElement --> ButtonConfig : uses
TVDropdownApi --> DropdownConfig : uses
ButtonConfig : +text : str
ButtonConfig : +title : str
ButtonConfig : +onClick : Callable
ButtonConfig : +align : str
ButtonConfig : +icon : str
DropdownConfig : +title : str
DropdownConfig : +items : ItemConfig[]
DropdownConfig : +tooltip : str
DropdownConfig : +icon : str
DropdownConfig : +align : str
ItemConfig : +title : str
ItemConfig : +onSelect : Callable
class TVWidget{
+createButton(options)
+createDropdown(title, items, tooltip, icon, align)
}
class TVHMElement{
+setTextContent(text)
+setTitle(title)
+setAlign(align)
+onClick(callback)
+setAttribute(name, value)
}
class TVDropdownApi{
+applyOptions(options)
+remove()
}
Loading

Multi-Chart Synchronization

PyTradingView offers three synchronization features for coordinated behavior across multiple charts: crosshair synchronization, date range synchronization, and interval synchronization. Each feature is controlled through dedicated methods that return TVWatchedValue objects, enabling both retrieval of current state and subscription to state changes.

The crosshairSync() method enables synchronization of crosshair position across all charts, allowing users to analyze corresponding data points simultaneously. dateRangeSync() synchronizes the visible date range, ensuring all charts display the same time period. intervalSync() synchronizes the chart interval (timeframe), so changing the interval on one chart automatically updates all others.

These synchronization features are particularly valuable for comparative analysis, technical pattern recognition, and multi-timeframe trading strategies, providing a cohesive analytical environment across the entire dashboard.

flowchart LR
A[Chart 1] < --> B[Crosshair Sync]
C[Chart 2] < --> B
D[Chart 3] < --> B
E[Chart 4] < --> B
B --> F[Coordinate Synchronization]
G[Chart 1] < --> H[Date Range Sync]
I[Chart 2] < --> H
J[Chart 3] < --> H
K[Chart 4] < --> H
H --> L[Time Period Synchronization]
M[Chart 1] < --> N[Interval Sync]
O[Chart 2] < --> N
P[Chart 3] < --> N
Q[Chart 4] < --> N
N --> R[Timeframe Synchronization]
Loading

Responsive Dashboard Configuration

The layout management system supports responsive dashboard configurations through programmatic layout switching and template management. Developers can create custom layout templates and implement logic to automatically select appropriate layouts based on screen size, device type, or user preferences.

The applyToEntireLayout() method on TVStudy objects enables copying indicators across all charts in a multi-chart layout, facilitating consistent analytical setups. By combining layout persistence with custom UI controls, applications can provide users with predefined dashboard templates optimized for different analytical tasks, such as trend analysis, momentum trading, or risk management.

Responsive configurations can be implemented by detecting screen dimensions and automatically applying the most suitable layout, ensuring optimal usability across desktop, tablet, and mobile devices.

State Management During Layout Changes

The system includes robust state management for layout changes, with the indicator engine automatically handling the layout_changed event. When a layout change occurs, the engine subscribes to this event and triggers a reinitialization process that cleans up old chart contexts and sets up new ones.

The _handle_layout_changed() method in the runtime mixin performs comprehensive cleanup of existing chart resources before reinitializing all charts in the new layout. This ensures that indicators, drawings, and event listeners are properly managed during transitions, preventing memory leaks and state corruption.

For custom indicators, the lifecycle methods on_init(), on_destroy(), and on_data_loaded() provide hooks for managing state during layout changes, allowing indicators to preserve relevant data while releasing resources associated with previous chart configurations.

sequenceDiagram
participant User
participant Widget
participant Engine
participant ChartContext
User->>Widget : Change Layout
Widget->>Widget : Emit layout_changed event
Widget->>Engine : Trigger on_layout_changed_sync
Engine->>Engine : Create async task
Engine->>Engine : _handle_layout_changed()
Engine->>Engine : _cleanup_all_charts()
Engine->>ChartContext : Clear all contexts
Engine->>Engine : _initialize_all_charts()
Engine->>Widget : Get chartsCount()
loop For each chart
Engine->>Widget : chart(index)
Engine->>ChartContext : create_context()
Engine->>Engine : _activate_default_indicators()
Engine->>Chart : onDataLoaded()
end
Engine->>User : Layout reinitialized
Loading

Performance Optimization

For complex layouts with multiple charts and indicators, performance optimization is critical. The system provides several mechanisms to optimize performance, including the ability to disable undo functionality during bulk layout operations using the disable_undo parameter in setLayoutSizes() and resetLayoutSizes().

When implementing custom layout management interfaces, it's recommended to batch layout changes and minimize the frequency of saveChartToServer() calls to reduce server load. For applications with many saved chart templates, implementing lazy loading of templates can improve initial load times.

The event-driven architecture minimizes polling and ensures that layout changes are processed efficiently, with the indicator engine's reinitialization process designed to handle resource cleanup and setup with minimal performance impact.

Best Practices

When designing layout management interfaces, consider the following best practices:

  1. Provide clear visual feedback when layouts change, such as brief animations or status messages
  2. Implement keyboard shortcuts for common layout operations to enhance accessibility
  3. Group related layout templates into logical categories using dropdown menus
  4. Include a "reset to default" option to help users recover from complex configurations
  5. Optimize for touch interfaces when supporting mobile devices, with appropriately sized controls
  6. Implement confirmation dialogs for operations that overwrite saved layouts
  7. Provide tooltips and help text to explain the purpose of different layout templates
  8. Support both programmatic layout switching and user-driven changes for maximum flexibility

By following these practices, developers can create intuitive, efficient, and accessible layout management systems that enhance the overall user experience of trading dashboards.

Clone this wiki locally