-
Notifications
You must be signed in to change notification settings - Fork 1
False Breakout Indicator Implementation
- Architecture Overview
- Core Components
- Configuration System
- Signal Generation Logic
- Mathematical Calculations
- Performance Considerations
- Common Issues and Tuning
The False Breakout Indicator follows a modular architecture that integrates with the PyTradingView framework through standardized interfaces. The implementation leverages the decorator pattern for automatic registration and inherits from the base TVIndicator class to ensure compatibility with the indicator engine.
classDiagram
class TVIndicator {
+get_config() IndicatorConfig
+calculate(df) Tuple[List[TVSignal], List[TVDrawable]]
+draw(chart, df, signals, drawables) None
}
class FalseBreakoutIndicator {
+get_config() IndicatorConfig
+calculate(df) Tuple[List[TVSignal], List[TVDrawable]]
+_calculate_highest(data, period) np.ndarray
+_calculate_lowest(data, period) np.ndarray
+_apply_smoothing(data, ma_type, length) np.ndarray
+_wma(data, length) np.ndarray
+_hma(data, length) np.ndarray
}
class FalseBreakoutState {
count : int
val : float
index : Optional[List[int]]
__post_init__()
}
class IndicatorConfig {
name : str
version : str
inputs : List[InputDefinition]
styles : List[StyleDefinition]
get_input_value(id) Any
get_style(id) StyleDefinition
}
class TVSignal {
signal_type : str
timestamp : int
price : float
metadata : Dict[str, Any]
}
class TVDrawable {
points : List[Tuple[int, float]]
shape : Any
metadata : Dict[str, Any]
}
class TVTrendLine {
overrides : TVTrendLineOverrides
}
TVIndicator <|-- FalseBreakoutIndicator
FalseBreakoutIndicator --> FalseBreakoutState
FalseBreakoutIndicator --> IndicatorConfig
FalseBreakoutIndicator --> TVSignal
FalseBreakoutIndicator --> TVDrawable
FalseBreakoutIndicator --> TVTrendLine
The False Breakout Indicator implementation consists of several core components that work together to detect and visualize false breakout patterns in financial markets. The architecture begins with the @register_indicator decorator, which automatically registers the indicator with the PyTradingView framework, making it available for use in trading charts.
The indicator inherits from TVIndicator, which provides the foundational interface for all custom indicators in the system. This inheritance ensures that the False Breakout Indicator conforms to the expected API and can be properly integrated with the indicator engine. The primary entry point for the indicator's functionality is the calculate method, which processes OHLC (Open, High, Low, Close) data to identify false breakout patterns.
A key component of the implementation is the FalseBreakoutState class, which uses the @dataclass decorator to define a simple data structure for tracking the state of the false breakout detection algorithm. This state object maintains three critical pieces of information: a counter (count) that tracks the direction and magnitude of price movements, the trigger price (val) at which a breakout occurred, and the indices (index) of the most recent price extremes that initiated the potential false breakout pattern.
The indicator generates two types of output: TVSignal objects for trading actions and TVDrawable objects for visual annotations. The TVSignal objects contain information about buy or sell signals, including the signal type, timestamp, price level, and styling metadata. The TVDrawable objects are used to create visual elements on the chart, specifically horizontal trend lines that mark the false breakout levels, using the TVTrendLine shape from the shapes library.
The False Breakout Indicator features a comprehensive configuration system that allows users to customize its behavior through both input parameters and visual styling options. The configuration is defined within the get_config method, which returns an IndicatorConfig object containing all configurable aspects of the indicator.
The input parameters are organized into two main groups: "Main Settings" and "Advanced Smoothing." The Main Settings group includes three integer parameters: period (default 20), which defines the lookback period for detecting new highs and lows; min_period (default 5), which specifies the minimum number of bars between consecutive price extremes; and max_period (default 5), which determines how many bars a false breakout signal remains valid. These parameters work together to filter out noise and ensure that detected patterns meet minimum criteria for significance.
The Advanced Smoothing group provides sophisticated filtering options to refine the detection algorithm. Users can select from three smoothing types via the ma_type parameter: "Diamond" (no smoothing, represented by 💎), "WMA" (Weighted Moving Average), and "HMA" (Hull Moving Average). The ma_length parameter (default 10) controls the period for the selected smoothing algorithm. Additionally, an aggressive boolean parameter enables a more sensitive detection mode that can identify patterns in volatile markets.
Visual styling is configured through two StyleDefinition objects: false_breakout_up and false_breakout_down. These styles control the appearance of the horizontal trend lines drawn on the chart, with the upward breakout style using a red color (#f23645) and the downward breakout style using a green color (#6ce5a0). Both styles have a line width of 2 and solid line style, ensuring clear visibility on the trading chart.
flowchart TD
A[Configuration System] --> B[Input Parameters]
A --> C[Style Definitions]
B --> D[Main Settings]
B --> E[Advanced Smoothing]
D --> D1["period: Integer (2-100)"]
D --> D2["min_period: Integer (0-100)"]
D --> D3["max_period: Integer (1-100)"]
E --> E1["ma_type: Options (💎, WMA, HMA)"]
E --> E2["ma_length: Integer (1-100)"]
E --> E3["aggressive: Boolean"]
C --> C1["false_breakout_up: Style"]
C --> C2["false_breakout_down: Style"]
C1 --> C1a["color: #f23645"]
C1 --> C1b["line_width: 2"]
C1 --> C1c["line_style: 0"]
C2 --> C2a["color: #6ce5a0"]
C2 --> C2b["line_width: 2"]
C2 --> C2c["line_style: 0"]
The signal generation logic in the False Breakout Indicator follows a multi-step process that detects price patterns indicative of false breakouts. The algorithm begins by calculating rolling highest and lowest values over the specified period, with an option for aggressive mode that inverts the high/low detection logic for increased sensitivity.
The detection process uses two boolean arrays, cond_hi and cond_lo, to identify new highs and new lows. A new high is detected when the current highest value exceeds the previous value, which in turn was less than or equal to the value before that (creating a peak pattern). Similarly, a new low is detected with the inverse pattern. This three-bar pattern recognition ensures that only significant price extremes are considered.
The state machine, implemented through the FalseBreakoutState object, tracks the progression of potential false breakout patterns. When a new high is detected, the state counter is decremented (indicating a downward bias), and when a new low is detected, the counter is incremented (indicating an upward bias). The absolute value of the counter must exceed 1 for a signal to be generated, requiring at least two consecutive price extremes in the same direction.
Signal validation involves three key checks: the minimum period constraint ensures sufficient time has passed between the initial breakout and the current price action; the maximum validity period limits how long a signal remains active; and the price action check confirms that the current close has crossed back over the trigger price, confirming the "false" nature of the breakout. For upward false breakouts (sell signals), this means the price broke below the trigger level after creating a new low; for downward false breakouts (buy signals), it means the price broke above the trigger level after creating a new high.
When a valid signal is detected, the indicator generates both a TVSignal for trading actions and a TVDrawable with a TVTrendLine for visual annotation. The signal includes metadata for styling, ensuring consistent appearance with the configured colors. The drawable creates a horizontal line from the time of the initial breakout to the current bar, visually marking the false breakout level on the chart.
sequenceDiagram
participant Data as OHLC Data
participant Indicator as FalseBreakoutIndicator
participant State as FalseBreakoutState
participant Output as Signals & Drawables
Data->>Indicator : Provide OHLC DataFrame
Indicator->>Indicator : Calculate rolling highs/lows
Indicator->>Indicator : Apply smoothing (if configured)
Indicator->>Indicator : Detect new highs/lows
loop For each bar
Indicator->>State : Update state based on price action
State->>Indicator : Return current state
Indicator->>Indicator : Check signal conditions
alt Valid signal detected
Indicator->>Output : Create TVSignal (buy/sell)
Indicator->>Output : Create TVDrawable (trend line)
end
end
Indicator->>Output : Return signals and drawables
The False Breakout Indicator employs several mathematical calculations to identify price patterns and smooth data for more reliable signal generation. The core calculations include rolling maximum and minimum functions, weighted moving averages (WMA), and Hull moving averages (HMA), each serving a specific purpose in the detection algorithm.
The _calculate_highest and _calculate_lowest methods implement rolling window calculations to identify price extremes over a specified period. For each data point, these methods examine a window of period bars extending back from the current position, using np.max() and np.min() to find the highest and lowest values respectively. The window start is calculated as max(0, i - period + 1) to prevent index underflow at the beginning of the dataset. This approach ensures that the indicator can detect new highs and lows relative to recent price action, which is essential for identifying breakout patterns.
The smoothing algorithms provide noise reduction and trend filtering capabilities. The Weighted Moving Average (_wma) assigns greater weight to more recent data points, with weights increasing linearly from 1 to the length of the period. This creates a weighted sum where recent prices have more influence than older prices, calculated as the sum of price-weight products divided by the sum of weights. The formula implemented is: WMA = Σ(price_i × weight_i) / Σ(weight_i), where weights are [1, 2, ..., n] for an n-period WMA.
The Hull Moving Average (_hma) implements a more sophisticated smoothing technique designed to reduce lag while maintaining smoothness. It follows a three-step process: first, it calculates a WMA over the full period; second, it calculates a WMA over half the period; third, it computes 2×WMA(half_period) - WMA(full_period), and finally applies another WMA with a period equal to the square root of the original period. This double smoothing approach creates a responsive yet stable moving average that can help filter out false signals in volatile markets.
These mathematical calculations work together to transform raw price data into meaningful signals. The rolling extremes identify potential breakout points, while the smoothing algorithms help confirm the significance of these breakouts by filtering out noise and short-term fluctuations. The combination of these calculations allows the indicator to adapt to different market conditions and timeframes.
flowchart TD
A[Mathematical Calculations] --> B[Rolling Extremes]
A --> C[Smoothing Algorithms]
B --> B1["_calculate_highest\nRolling Maximum"]
B --> B2["_calculate_lowest\nRolling Minimum"]
C --> D[Weighted Moving Average]
C --> E[Hull Moving Average]
D --> D1["Weights: [1,2,...,n]"]
D --> D2["Formula: Σ(P×W)/ΣW"]
D --> D3["Reduces noise, emphasizes recent data"]
E --> E1["Step 1: WMA(n)"]
E --> E2["Step 2: WMA(n/2)"]
E --> E3["Step 3: 2×WMA(n/2) - WMA(n)"]
E --> E4["Step 4: WMA(√n) on result"]
E --> E5["Minimizes lag, maintains smoothness"]
The False Breakout Indicator implementation presents several performance considerations when processing large datasets, particularly in real-time trading environments. The algorithm's computational complexity is primarily determined by the nested loops and rolling window calculations that form the core of the detection logic.
The most significant performance bottleneck lies in the rolling maximum and minimum calculations (_calculate_highest and _calculate_lowest), which have O(n×p) time complexity where n is the number of data points and p is the lookback period. For each of the n bars, the algorithm examines up to p previous bars to find the extreme values, resulting in potentially millions of operations for large datasets. This nested loop structure is repeated in both the WMA and HMA calculations, further compounding the computational load.
Memory usage is relatively efficient, with the indicator creating several numpy arrays of length n (for highs, lows, close prices, and boolean conditions) plus additional arrays for the smoothed values. However, the use of pandas DataFrames and numpy arrays does require contiguous memory allocation, which can become problematic with very large datasets that approach system memory limits.
To optimize performance, several strategies can be employed. First, the rolling calculations could be replaced with more efficient algorithms using deque-based sliding windows or specialized libraries like pandas.rolling() which are implemented in C and significantly faster than pure Python loops. Second, the algorithm could implement incremental updates rather than recalculating from scratch on each new bar, maintaining running maximum/minimum values and updating them with each new data point.
For real-time applications, the indicator could implement data sampling or use lower timeframe data to reduce the number of calculations while still providing meaningful signals. Additionally, the smoothing calculations could be conditionally applied only when enabled in the configuration, avoiding unnecessary computation when the diamond (no smoothing) option is selected.
Caching mechanisms could also improve performance, particularly for backtesting scenarios where the same historical data is analyzed repeatedly. By caching calculation results for specific time ranges, the indicator could avoid redundant computations when zooming or panning within previously analyzed data.
The False Breakout Indicator, while effective in identifying reversal patterns, is susceptible to several common issues that traders should be aware of when using this tool. The most prevalent issue is false signal generation in highly volatile markets, where rapid price swings can trigger multiple breakout signals that quickly reverse, creating a series of losing trades. This occurs because the algorithm's sensitivity to price extremes can interpret normal market noise as significant breakout patterns.
To address this issue, traders can employ several tuning strategies. Increasing the period parameter from its default of 20 to 30 or 40 bars makes the indicator less sensitive to short-term fluctuations, requiring more significant price movements to register as new highs or lows. Similarly, adjusting the min_period parameter to a higher value (e.g., 8-10) ensures that sufficient time passes between consecutive price extremes, filtering out rapid-fire breakouts that are more likely to be false.
For different asset classes, specific tuning recommendations apply. In highly volatile cryptocurrencies, using the HMA smoothing with a longer ma_length (15-20) can help filter out noise while maintaining responsiveness. For slower-moving assets like blue-chip stocks, the WMA smoothing with a shorter length (5-8) may be more appropriate to capture meaningful breakouts without excessive lag. Forex pairs with strong trends might benefit from disabling smoothing entirely (using the diamond option) and focusing on longer timeframes with higher period settings.
The aggressive mode parameter offers another tuning dimension, particularly useful in ranging markets where price frequently tests support and resistance levels. When enabled, this mode inverts the high/low detection logic, potentially identifying breakout patterns that might be missed by the standard algorithm. However, this increased sensitivity comes with a higher risk of false signals, so it should be used judiciously and combined with other confirmation indicators.
Traders should also consider the market context when interpreting signals. In strong trending markets, false breakout signals may indicate temporary pullbacks rather than genuine reversals, suggesting that signals should be filtered based on the overall trend direction. Combining the False Breakout Indicator with trend-following indicators like moving averages can help distinguish between genuine reversal signals and temporary countertrend moves.