Skip to content

Drawing Tools

levi edited this page Nov 6, 2025 · 2 revisions

Drawing Tools

Table of Contents

  1. Overview of Drawing Capabilities
  2. Shape Categories and Types
  3. Common Interface Pattern
  4. Creating Drawings Programmatically
  5. Modifying and Removing Drawings
  6. Styling and Customization
  7. Examples of Technical Analysis Patterns
  8. Performance Considerations
  9. Memory Management and Cleanup

Overview of Drawing Capabilities

PyTradingView provides extensive drawing capabilities that allow users to create, modify, and manage various graphical elements on trading charts. These tools are essential for technical analysis, enabling traders to visualize patterns, trends, and key levels. The library supports over 100 shape types across multiple categories, including trendlines, geometric shapes, Fibonacci tools, Gann indicators, and annotation elements. This comprehensive set of drawing tools empowers users to perform detailed chart analysis and implement sophisticated trading strategies.

The drawing system is built on a robust architecture that separates shape definitions from their visual properties, allowing for flexible customization and reuse. Each drawing element is represented as an object with specific properties and methods, making it easy to manipulate programmatically. The system also supports both single-point and multipoint shapes, accommodating a wide range of technical analysis requirements.

Shape Categories and Types

The drawing capabilities in PyTradingView are organized into several categories, each serving specific analytical purposes. The main categories include trendlines, geometric shapes, Fibonacci tools, Gann indicators, and annotation elements. These categories contain over 100 distinct shape types, providing comprehensive coverage for various technical analysis methodologies.

Trendline shapes include basic elements like TrendLine, Ray, and HorizontalRay, as well as more complex formations such as ParallelChannel and DisjointAngle. Geometric shapes encompass fundamental forms like Circle, Ellipse, Rectangle, and Triangle, along with specialized variants like RotatedRectangle and Path. Fibonacci tools offer advanced analytical capabilities with shapes such as FibRetracement, FibExtension, FibSpeedResistFan, and FibChannel, enabling users to identify potential support and resistance levels based on Fibonacci ratios.

Gann indicators include Gannbox, GannboxSquare, and GannboxFan, which help traders analyze price movements in relation to time and geometric angles. Annotation elements provide various ways to add textual and symbolic information to charts, including Text, Note, Comment, Callout, and Sticker. Additionally, the library supports specialized pattern recognition tools like HeadAndShoulders, ElliottImpulseWave, and TrianglePattern, which automatically detect and visualize common technical patterns.

graph TD
A[Shape Categories] --> B[Trendlines]
A --> C[Geometric Shapes]
A --> D[Fibonacci Tools]
A --> E[Gann Indicators]
A --> F[Annotation Elements]
A --> G[Pattern Recognition]
B --> B1[TrendLine]
B --> B2[Ray]
B --> B3[HorizontalRay]
B --> B4[ParallelChannel]
B --> B5[DisjointAngle]
C --> C1[Circle]
C --> C2[Ellipse]
C --> C3[Rectangle]
C --> C4[Triangle]
C --> C5[Path]
D --> D1[FibRetracement]
D --> D2[FibExtension]
D --> D3[FibSpeedResistFan]
D --> D4[FibChannel]
E --> E1[Gannbox]
E --> E2[GannboxSquare]
E --> E3[GannboxFan]
F --> F1[Text]
F --> F2[Note]
F --> F3[Comment]
F --> F4[Sticker]
G --> G1[HeadAndShoulders]
G --> G2[ElliottImpulseWave]
G --> G3[TrianglePattern]
Loading

Common Interface Pattern

The drawing system in PyTradingView follows a consistent interface pattern using the TVShape and TVShapePoint classes as foundational components. This pattern ensures uniformity across all shape types while providing the flexibility needed for specialized functionality. The TVShapePoint class represents individual points on the chart, containing both time (as a UNIX timestamp) and price information. This design allows for precise positioning of drawing elements relative to specific market data points.

The TVShape class serves as the base class for all drawing elements, providing common methods for manipulating shapes on the chart. Key methods include bringToFront(), sendToBack(), getProperties(), setProperties(), getPoints(), and setPoints(). These methods enable users to control the visual hierarchy, retrieve and modify shape properties, and manage the coordinates of multipoint shapes. The interface pattern also supports advanced features like selection control, saving options, and object tree visibility through methods such as isSelectionEnabled(), setSavingEnabled(), and isShowInObjectsTreeEnabled().

For multipoint drawings, the system uses a standardized approach where multiple TVShapePoint objects are combined to define the shape's geometry. This pattern is particularly useful for creating trend channels, Fibonacci retracements, and other multi-point technical analysis tools. The interface also supports anchored shapes that maintain their relative position as the chart's time range changes, ensuring consistent visualization across different zoom levels.

Creating Drawings Programmatically

Creating drawings programmatically in PyTradingView involves using the chart's creation methods in conjunction with specific shape objects. The process begins by instantiating a shape object with the desired configuration, including any custom styling options. For single-point shapes like arrows or vertical lines, the createShape() method is used, while multipoint shapes such as trendlines or channels require the createMultipointShape() method.

When creating drawings through indicator calculations, the process is typically automated based on the analysis results. The indicator engine processes market data and generates TVDrawable objects that contain both the shape definition and its positional data. Each TVDrawable includes a list of (time, price) tuples representing the coordinates and a shape object that defines the visual properties. The engine then calls the appropriate creation method on the chart object, passing the shape points and options.

For example, to create a trend channel programmatically, you would first define two parallel trendlines using TVTrendLine objects, then use the TVParallelChannel shape type with appropriate styling overrides. The creation process automatically handles the conversion of Python objects to the format required by the underlying TradingView API, ensuring seamless integration. The system also supports batch creation of multiple drawings, which can be useful for visualizing complex patterns or multiple time frame analyses.

Modifying and Removing Drawings

Modifying and removing drawings in PyTradingView is accomplished through a combination of shape manipulation methods and chart-level operations. Once a drawing is created, it can be modified by retrieving its properties, making changes, and applying the updated configuration. The getProperties() and setProperties() methods of the TVShape class allow for dynamic modification of visual attributes such as colors, line styles, and text content. For multipoint shapes, the getPoints() and setPoints() methods enable adjustment of the shape's geometry by modifying its coordinate points.

Drawings can be repositioned in the visual hierarchy using bringToFront() and sendToBack() methods, which control whether a shape appears above or below other elements on the chart. Individual drawings can be removed using the removeEntity() method on the chart object, which requires the entity ID of the shape to be deleted. For bulk operations, the removeAllShapes() method clears all drawings from the chart at once, which is useful when refreshing analysis or switching between different chart configurations.

The system also supports grouped operations through the TVShapesGroupController class, which allows multiple shapes to be managed as a single unit. Groups can be created from selected shapes, and operations like visibility toggling, locking, and Z-order adjustments can be applied to entire groups. This feature is particularly valuable when working with complex patterns that consist of multiple interrelated elements, such as Elliott wave counts or harmonic patterns.

Styling and Customization

Styling and customization in PyTradingView are implemented through a flexible overrides system that allows for detailed control over the visual appearance of drawing elements. Each shape type has a corresponding overrides class (e.g., TVParallelChannelOverrides, TVHeadAndShouldersOverrides) that defines the customizable properties. These properties include colors, line styles, transparency, font settings, and various display options specific to each shape type.

The styling system follows a hierarchical approach where default values are defined in the overrides class, but can be customized when instantiating the shape object. For example, a TVParallelChannel can have its line color, background transparency, and label visibility configured through the TVParallelChannelOverrides class. The system supports both solid and gradient fills, various line dash patterns, and multiple font options for text elements.

Customization extends beyond basic visual properties to include behavioral aspects such as extension options (whether lines extend beyond the defined points), label positioning, and interaction settings. Some shapes offer specialized styling options, like the TVElliottImpulseWave which includes degree settings for wave labeling, or the FibSpeedResistFan which allows configuration of fan angles. The styling system is designed to be intuitive while providing the depth needed for professional-grade chart analysis.

classDiagram
class TVBaseOverrides {
+to_json() dict
}
class TVParallelChannelOverrides {
+background_color string
+extend_left bool
+extend_right bool
+fill_background bool
+label_bold bool
+label_font_size int
+label_horz_align string
+label_italic bool
+label_text_color string
+label_vert_align string
+label_visible bool
+line_color string
+line_style int
+line_width int
+midline_color string
+midline_style int
+midline_width int
+show_midline bool
+transparency int
}
class TVHeadAndShouldersOverrides {
+background_color string
+bold bool
+color string
+fill_background bool
+font_size int
+italic bool
+line_width int
+text_color string
+transparency int
}
class TVElliottImpulseWaveOverrides {
+color string
+degree int
+line_width int
+show_wave bool
}
TVBaseOverrides <|-- TVParallelChannelOverrides
TVBaseOverrides <|-- TVHeadAndShouldersOverrides
TVBaseOverrides <|-- TVElliottImpulseWaveOverrides
Loading

Examples of Technical Analysis Patterns

PyTradingView enables the creation of common technical analysis patterns through its comprehensive drawing tools. For trend channels, the TVParallelChannel shape can be used to draw parallel trendlines that contain price movement, with customizable extension options and midline visibility. The channel's styling can be adjusted to highlight different market conditions, such as using semi-transparent fills during consolidation phases.

Head and shoulders patterns can be visualized using the TVHeadAndShoulders shape, which automatically connects the key pivot points of this reversal pattern. The shape supports customization of line colors, fill transparency, and label appearance, making it easy to distinguish between standard and inverse head and shoulders formations. The pattern's symmetry and neckline slope can be precisely controlled through the coordinate points.

Elliott wave patterns are supported through specialized shapes like TVElliottImpulseWave and TVElliottCorrection, which help identify the five-wave and three-wave structures of market cycles. These shapes include options for wave degree labeling and visual styling that emphasizes the fractal nature of Elliott wave theory. The system allows for the creation of complex wave counts by combining multiple wave shapes and connecting them with trendlines.

sequenceDiagram
participant Indicator as "Indicator Engine"
participant Chart as "TVChart"
participant Shape as "TVDrawable"
participant Point as "TVShapePoint"
Indicator->>Indicator : Process market data
Indicator->>Shape : Create TVDrawable with pattern points
Shape->>Point : Define (time, price) coordinates
Shape->>Chart : Call createMultipointShape()
Chart->>Chart : Render pattern on chart
Chart-->>Indicator : Return entity ID
Indicator->>Indicator : Store entity ID for management
Loading

Performance Considerations

Managing large numbers of drawings in PyTradingView requires careful consideration of performance implications. The system is optimized for efficient rendering, but excessive numbers of shapes can impact chart responsiveness, particularly on lower-end devices or when using complex patterns with many points. The library employs several strategies to mitigate performance issues, including batch processing of drawing operations and efficient memory management of shape objects.

One key performance consideration is the use of appropriate shape types for specific analytical needs. For example, using a single TVParallelChannel is more efficient than creating multiple individual trendlines, as it reduces the number of separate entities that need to be managed. Similarly, grouping related shapes using the TVShapesGroupController can improve performance by allowing bulk operations and reducing the overhead of individual shape management.

The system also supports lazy loading and on-demand rendering of drawings, where shapes are only fully instantiated when they become visible in the current chart view. This approach minimizes memory usage and processing overhead for patterns that extend beyond the currently visible time range. Additionally, the library provides methods for temporarily hiding or disabling non-essential drawings during intensive analysis periods, helping to maintain optimal chart performance.

Memory Management and Cleanup

Effective memory management and cleanup are critical when working with large numbers of drawings in PyTradingView. The system implements a robust object pooling mechanism through the TVObjectPool class, which manages the lifecycle of drawing objects and prevents memory leaks. This pool tracks all created shape instances and ensures proper cleanup when shapes are removed or the chart is destroyed.

The primary method for memory cleanup is the clear_all_drawings() function available in the indicator base class, which iterates through all recorded entity IDs and removes them from the chart. This method is automatically called during indicator recalculation and when indicators are destroyed, preventing accumulation of orphaned drawing objects. The system also supports selective cleanup through the removeEntity() method, allowing for targeted removal of specific shapes without affecting others.

For long-running applications, it's recommended to implement periodic cleanup routines that remove unused or expired drawings. The object pool provides monitoring capabilities that can be used to track memory usage and identify potential leaks. Additionally, the system automatically handles cleanup of temporary shapes created during user interactions, ensuring that the memory footprint remains stable over extended usage periods.

Clone this wiki locally