Skip to content

Core Algorithm

levi edited this page Nov 6, 2025 · 2 revisions

Core Algorithm

Table of Contents

  1. Three-Stage Detection Process
  2. State Transition Mechanism
  3. Signal Filtering Parameters
  4. Signal Generation Logic
  5. Performance Considerations

Three-Stage Detection Process

The FalseBreakoutIndicator implements a three-stage detection process to identify false breakout patterns in financial markets. The algorithm processes OHLC data through rolling windows to detect new highs and lows, with each stage building upon the previous one to confirm valid signals.

The initial breakout stage begins by calculating rolling highest and lowest prices over a configurable period using the _calculate_highest() and _calculate_lowest() methods. These methods implement a sliding window approach that examines the maximum and minimum values within the specified lookback period. The detection of new highs and lows is determined by comparing the current rolling maximum/minimum with the previous two values - a new high is identified when the current high exceeds the previous high while the previous high was less than or equal to the one before it.

The secondary confirmation stage involves tracking consecutive breakouts through the state management system. When a new high or low is detected, the algorithm updates the state counter and records the trigger price. This stage ensures that multiple breakouts within the lookback period are properly accounted for, with the counter incrementing for consecutive new lows and decrementing for consecutive new highs.

The reversal trigger stage occurs when price action moves in the opposite direction of the breakout, crossing the trigger level established during the confirmation stage. This final stage validates the false breakout pattern by checking that the price has reversed direction after the initial breakout, indicating that the breakout was not sustained.

State Transition Mechanism

The FalseBreakoutIndicator employs a state transition mechanism centered around the FalseBreakoutState.count variable to track consecutive breakouts and manage the detection process. The state object maintains three key properties: count (a counter for consecutive breakouts), val (the trigger price), and index (tracking the position of recent breakouts).

The state counter operates on a directional basis: positive values indicate consecutive new highs (upward momentum), while negative values represent consecutive new lows (downward momentum). When a new high is detected, the counter is decremented (moving toward more negative values), and when a new low is detected, the counter is incremented (moving toward more positive values). This bidirectional counting system allows the algorithm to distinguish between sustained trends and potential false breakouts.

Critical state transitions occur when the counter reaches threshold values of +2 or -2, which serve as confirmation that multiple breakouts have occurred within the lookback period. At these thresholds, the algorithm prepares to detect a reversal. The trigger price (state.val) is updated with the low price when a new high is detected and with the high price when a new low is detected, establishing the level that must be crossed for a valid false breakout signal.

The state machine resets the counter to zero after generating a signal, preventing multiple signals from the same breakout sequence and ensuring that each detected pattern is independent.

Signal Filtering Parameters

The FalseBreakoutIndicator utilizes two key parameters, min_period and max_period, to filter valid signals and prevent false positives. These parameters work in conjunction to establish temporal constraints on the detection process, ensuring that signals are generated only when market conditions meet specific criteria.

The min_period parameter defines the minimum number of bars that must separate consecutive breakouts. This filter prevents the algorithm from detecting signals when breakouts occur too frequently, which could indicate volatile but unreliable price action. A higher min_period value increases the selectivity of the indicator, requiring a more significant consolidation period between breakouts before a signal can be generated. This parameter is particularly useful in filtering out noise during choppy market conditions.

The max_period parameter establishes the maximum validity period for a detected signal. Once a breakout is identified, the corresponding signal remains active for a maximum of max_period bars. This temporal constraint ensures that reversal signals must occur within a reasonable timeframe after the initial breakout, preventing stale signals from being generated long after the market context has changed. A lower max_period value makes the indicator more responsive but potentially more prone to whipsaws, while a higher value increases the likelihood of capturing delayed reversals.

Together, these parameters create a balanced filtering system that requires both sufficient separation between breakouts (min_period) and timely reversal confirmation (max_period), significantly reducing the occurrence of false positives.

Signal Generation Logic

The FalseBreakoutIndicator generates buy and sell signals based on price crossing the trigger level (state.val) after meeting the three-stage detection criteria. The signal generation logic is implemented through conditional checks that evaluate both the state counter and price action relative to the trigger level.

Buy signals are generated when the following conditions are met simultaneously: the state counter exceeds +1 (indicating at least two consecutive new lows), the current closing price crosses above the trigger level from below, the signal is within its valid period (maxvalid), and sufficient time has passed since the previous breakout (minbars). This pattern represents a false breakout downward, where price breaks to a new low but quickly reverses upward, suggesting strong buying pressure.

Sell signals are triggered when the state counter is less than -1 (indicating at least two consecutive new highs), the current closing price crosses below the trigger level from above, and the temporal validity conditions are satisfied. This pattern represents a false breakout upward, where price reaches a new high but rapidly reverses downward, indicating strong selling pressure.

The interaction between condition detection (cond_hi/cond_lo) and signal generation is critical to the algorithm's operation. The condition arrays identify potential breakout points, while the state machine tracks the sequence of these events. Only when both the pattern recognition (conditions) and sequence validation (state) components align with the reversal price action does the algorithm generate a signal.

Performance Considerations

The current implementation of the FalseBreakoutIndicator uses loop-based processing for the rolling window calculations in the _calculate_highest() and _calculate_lowest() methods. While this approach is straightforward and easy to understand, it has performance implications for large datasets due to the O(n×period) time complexity of the nested loops.

The loop-based implementation processes each data point individually, calculating the maximum or minimum over the lookback period for each position. This can become computationally expensive when analyzing high-frequency data or long historical series, particularly with larger period values.

To improve efficiency, vectorization strategies using pandas operations should be implemented. The rolling window calculations can be replaced with pandas' built-in rolling functions, such as df['high'].rolling(window=period).max() and df['low'].rolling(window=period).min(), which are implemented in optimized C code and significantly faster than Python loops.

Additional optimization opportunities include:

  • Using pandas' shift() method to eliminate loops in the condition detection logic
  • Implementing vectorized crossover/crossunder detection using boolean operations
  • Leveraging numpy's vectorized operations for the smoothing calculations
  • Pre-allocating arrays to avoid dynamic resizing during computation

These vectorization strategies would transform the algorithm from O(n×period) to approximately O(n) complexity, resulting in substantial performance improvements, especially for real-time applications processing large volumes of market data.

Clone this wiki locally