Xem Tiếng Việt
Chương 2Original (EN)

Chapter 2: Quantifying Market Structure at Multiple Scales (Hierarchical Directional Change)


Chapter Overview — 00:00

Financial price series are notoriously noisy at granular timeframes. Most turning points identified on individual candles are insignificant market noise. To build robust algorithmic strategies around support, resistance, and market trends, traders need a systematic way to group turning points into distinct levels of structural significance.

This chapter details an algorithmic framework to quantify market structure at multiple scales:

  1. Level 0 Baseline: Extract alternating local highs and lows using an Average True Range (ATR) based Directional Change algorithm.
  2. Hierarchical Recursive Upgrades: Recursively promote extremes that stand out relative to their neighbors (e.g., a high flanked by two lower highs) into higher structural tiers (Level 1, Level 2, etc.).
  3. No-Repainting Guarantee: Ensure every confirmed level is mathematically fixed—extremes never repaint, though higher levels inherently require more lag before confirmation.

The concept adapts the market structure framework originally described in Larry Williams' classic text, Long-Term Secrets to Short-Term Trading, formalizing it into clean, recursive Python code.


1. The Directional Change Algorithm (Level 0 Foundation) — 00:15

Core Principle

Directional Change identifies alternating market extremes—guaranteeing that every confirmed peak (top) is followed by a trough (bottom) and vice versa. It filters out intrabar fluctuations by requiring price to retrace by a predefined volatility threshold before confirming that a turning point has occurred.

       [Pending High]
          /\
         /  \
        /    \  <--- Retraces by >= ATR
       /      v [Confirm High!]
      /
[Confirmed Low]

Confirmation Mechanics

  • Searching for a Top (Upward Move):
    • Track the highest price seen since the last confirmed bottom (pending_high).
    • As new candles arrive, if candle.high > pending_high, update pending_high.
    • If no new high is reached, check whether candle.low falls below the confirmation threshold: Thresholdtop=pending_high−ATR\text{Threshold}_{\text{top}} = \text{pending\_high} - \text{ATR}
    • Once the low breaches this threshold, the pending high is formally confirmed as a local top.
  • Searching for a Bottom (Downward Move):
    • Symmetrically track the lowest price seen since the last confirmed top (pending_low).
    • Update pending_low whenever a lower low forms.
    • If no new low is reached, check whether candle.high climbs above: Thresholdbottom=pending_low+ATR\text{Threshold}_{\text{bottom}} = \text{pending\_low} + \text{ATR}
    • Once breached, confirm the pending low as a local bottom.

Data Model & Volatility Metric

Because swing points can only be known in hindsight, storing the moment of confirmation separately from the moment of occurrence is critical for backtest integrity:

  • LocalExtreme Data Structure:
    • type: +1 (top) or -1 (bottom).
    • price, index, timestamp: When the peak/trough actually formed in the price data.
    • confirmed_index, confirmed_timestamp: The exact bar when the threshold was breached and the extreme became tradable.
  • ATR Lookback Choice:
    • For 1-minute Bitcoin data, the author employs a 24-hour ATR window (1,440 bars).
    • Rule of thumb: Avoid over-optimizing the ATR window. Choose a reasonably long lookback that captures baseline session volatility.
    • Efficiency optimization: Maintain a running rolling sum of True Range values (adding the newest and subtracting the oldest) rather than re-computing the mean over 1,440 bars on every tick.

2. Building Hierarchical Scales: Recursive Upgrades — 03:08

The Structural Definition

Level 0 extremes generated directly from raw candlesticks contain many micro-swings. To build macro structure:

  • Level 1 Top: A Level 0 top that is strictly higher than both the preceding Level 0 top and the subsequent Level 0 top (a peak surrounded by two lower peaks).
  • Level 1 Bottom: A Level 0 bottom that is strictly lower than both the preceding and subsequent Level 0 bottoms (a valley surrounded by two higher valleys).
Level 1 Top:         /\ (Level 1 Top)
                    /  \
      /\           /    \           /\
     /  \         /      \         /  \
    /    \_______/        \_______/    \
  (L0 Top 1)                     (L0 Top 2)

Enforcing Strict Alternation

When applying this rule, the market may occasionally produce two consecutive upgraded tops without an intervening upgraded bottom (or vice versa). To preserve the alternating invariant:

  • If two upgraded tops occur back-to-back, identify all Level 0 bottoms that occurred between them.
  • Find the bottom with the lowest price and force-upgrade it to Level 1 first.
  • Only then append the new Level 1 top.

Recursive Multi-Scale Hierarchy

Once Level 1 extremes are established:

  • Apply the exact same logic to Level 1 extremes to yield Level 2 extremes.
  • Apply it to Level 2 to yield Level 3, and so forth.
  • This creates an organized multi-scale pyramid of market swings where each tier represents a larger order of price cycle.

3. Implementation Details & Recursive Engine — 03:54

The HierarchicalExtremes class encapsulates multi-scale tracking:

  1. Storage: Extremes are stored in a nested list extremes[level], where each element contains confirmed LocalExtreme objects for that scale.
  2. Bar Update Loop:
    • On each bar, call DirectionalChange.update().
    • If a new Level 0 extreme is confirmed, trigger the recursive upgrade pipeline.
  3. The Recursive Upgrade Step (new_top / new_bottom):
    • Base Condition: If level >= max_levels - 1, terminate recursion.
    • Candidate Selection: Look back at previous tops at the current level. Since extremes alternate, previous tops reside at indices [-2, -4, -6, ...]. At least three tops are needed to test the "surrounded by lower tops" condition.
    • Double Tops & Equal Prices: If two peaks share identical prices, the algorithm chooses the earlier occurrence to anchor the swing.
    • Timestamp Updating: When promoting an extreme from Level NN to Level N+1N+1, the extreme's original price and occurrence timestamp are preserved, but its confirmed_index and confirmed_timestamp are updated to reflect the bar where the higher-level pattern was officially verified.
  4. Code Consolidation:
    • Because the logic for tops and bottoms is purely symmetrical, production implementations combine both into a single new_extreme(level, type) function with dynamic comparison operators (> vs <).

4. Characteristics, Lag, and Algorithmic Applications — 07:02

The Inherent Lag vs. Significance Trade-Off

When tracking multiple levels (e.g., Level 0 in white, Level 1 in blue, Level 2 in purple):

  • Zero Repainting: Once an extreme line is drawn on the chart, it is permanently locked. There is no retrospective curve-fitting or redraw.
  • Confirmation Delay: Higher-level structures require substantially more bars to confirm. A major Level 2 swing low may only be confirmed hundreds of bars after the exact bottom occurred, as price must rally, form higher micro-swings, and meet all recursive threshold criteria.

Practical Trading Uses

  1. Dynamic Stop-Loss Placement: Placing protective stops behind Level 1 or Level 2 swing points rather than volatile Level 0 wicks reduces premature stop-outs during choppy consolidation.
  2. Market Regime & Trend Filters: Define an uptrend mathematically as a sequence of higher Level 1 highs and higher Level 1 lows.
  3. Breakout Triggers: Use breaches of major Level 1/Level 2 horizontal extremes to trigger momentum entries while ignoring Level 0 noise.

Key Takeaways

  • Directional Change eliminates time distortion: Unlike fixed-period indicators, it samples price only when meaningful volatility occurs (1×ATR1 \times \text{ATR}).
  • Recursion yields scale invariance: The same rule that groups bars into swings can group swings into trends, and trends into macro cycles.
  • Hindsight awareness is non-negotiable: Never backtest using extreme.index as the trade entry time; always execute on extreme.confirmed_index to prevent lookahead bias.
  • Reference: Larry Williams, Long-Term Secrets to Short-Term Trading (Chapter on Market Structure).

Nguồn duy nhất: Kênh YouTube chính thức của neurotrader. Nội dung được hệ thống hóa phục vụ học tập & tra cứu — bấm các mốc thời gian trong bài để xem trực tiếp video gốc của tác giả.