OPEN-SOURCE SCRIPT

Market Phase Detector [JOAT]

2 177
Market Phase Detector [JOAT]

Introduction

Market Phase Detector is an open-source market structure classification engine that continuously identifies whether price is operating in a Bullish Trend, Bearish Trend, or Range state. The classification uses three independent inputs that must align simultaneously before a regime is confirmed, making the output robust against single-factor noise and false positives that plague simpler trend detectors.

The problem Market Phase Detector solves is context. Trend-following entries during range conditions produce whipsaws. Mean-reversion entries during strong trending moves produce losses against the dominant flow. Knowing the regime before interpreting any other signal improves the relevance of every decision made from it. Market Phase Detector makes that determination automatically, updates it bar by bar, and visualizes both the current regime and every structural event that contributed to it — including labeled BOS and CHoCH events with horizontal level lines, live swing extension lines at the right edge, and an institutional-grade dashboard.

ekran görüntüsü

Core Concepts

1. Swing Detection and Pivot Tracking

Price structure is derived from pivot highs and lows confirmed using ta.pivothigh() and ta.pivotlow() with a configurable symmetric lookback. The lookback controls sensitivity — a value of 5 requires 5 bars on each side of the pivot to confirm it, producing only the most structurally significant swings. Each confirmed pivot updates the tracked level and resets its broken flag to allow new break detection on the next cycle:

Pine Script®
pivHi = ta.pivothigh(high, swingLen, swingLen) pivLo = ta.pivotlow(low, swingLen, swingLen) if not na(pivHi) topLevel := pivHi topBroken := false


2. Break of Structure vs Change of Character

Two structural event types are distinguished and tracked independently. A Break of Structure (BOS) occurs when price closes through the previous swing extreme in the same direction as the current structural bias — confirming continuation. A Change of Character (CHoCH) occurs when price closes through the previous swing extreme against the current structural bias — signaling a potential regime flip:

Pine Script®
bosBull = bullBreak and structureBias == 1 chochBull = bullBreak and structureBias != 1


Every event is labeled directly on the chart with a horizontal line at the break level and a text label (BOS +, BOS -, CHoCH +, CHoCH -). Running counts of each type are tracked and displayed in the dashboard.

3. Three-Factor Regime Gate

The regime classification evaluates all three inputs simultaneously before assigning a state. Structure bias is set by BOS and CHoCH events. The volatility gate compares current ATR to a moving average of ATR multiplied by a contraction threshold — when ATR falls below this level the market is classified as compressed and the regime defaults to Range regardless of structure or momentum. Momentum uses a smoothed rate-of-change that must confirm the structural direction:

Pine Script®
if isLowVol regime := 0 // Range — volatility gate overrides everything else if strBias == 1 and roc > 0 regime := 1 // Bullish else if strBias == -1 and roc < 0 regime := -1 // Bearish else regime := 0 // Inconclusive — range


A confidence score (1-3) counts how many of the three factors currently agree and is displayed in the dashboard, allowing the trader to distinguish a fully confirmed 3/3 regime from a weaker 2/3 reading.

4. Swing Level Extension Lines

The current unbroken swing high and swing low are extended as dotted horizontal lines to the right edge of the chart with price labels. These serve as the nearest structural reference levels — the next points where a BOS or CHoCH could occur. They are deleted and redrawn each bar using barstate.islast so they remain current without consuming the indicator's line budget:

Pine Script®
if barstate.islast and showSwingExt line.delete(swingHiLine) swingHiLine := line.new(topBar, topLevel, bar_index + 4, topLevel, color=color.new(#E65100, 45), style=line.style_dotted, width=2)


5. Regime Background Shading

The chart background is tinted according to the current regime — faint teal for Bullish, faint orange for Bearish, neutral gray for Range. This gives immediate context at a glance without adding visual noise to the price action.

ekran görüntüsü

Features

  • Three-state regime output: Bullish, Bearish, and Range states derived from structure, volatility, and momentum alignment
  • BOS and CHoCH event labels: Every structural break labeled on-chart with event type, direction, and horizontal level line
  • Independent BOS and CHoCH counters: Running totals of each structural event type in the dashboard
  • Swing level extension lines: Dotted right-edge lines at the current unbroken swing high and low with price labels
  • ATR-based volatility gate: Low-volatility contraction forces a Range classification regardless of structure or momentum
  • Smoothed momentum confirmation: Rate-of-change must align with structure before a trending regime is confirmed
  • Confidence scoring (1/3 to 3/3): Quantifies how many of the three classification factors are currently aligned
  • Regime background shading: Chart background tint reflects the current regime in real time
  • Institutional dashboard (top right): 15-row table with regime state, confidence, last break direction and age, BOS and CHoCH counts, swing levels, and ATR
  • Fully configurable colors: Bullish, bearish, and ranging tints plus structure line colors are independently adjustable
  • All signals confirmed bar only: No repainting — all structural events fire on barstate.isconfirmed


Input Parameters

Structure Detection:
  • Swing Lookback: Left/right bars required for pivot confirmation (default: 5)
  • ATR Period: ATR calculation length (default: 14)


Regime Classification:
  • Volatility MA Length: MA length for ATR comparison (default: 20)
  • Range Contraction Multiplier: ATR fraction below which the market is classified as ranging (default: 0.7)
  • Momentum Lookback: Rate-of-change lookback and EMA smoothing period (default: 10)


Display:
  • Regime Background Shading toggle
  • Show Dashboard toggle
  • Show Structure Lines toggle
  • Show Swing Level Extensions toggle


How to Use This Indicator

Step 1: Read the Current Regime
Check the REGIME row in the dashboard. BULLISH, BEARISH, or RANGE appears in its corresponding color. This is the primary output. Use it to establish directional bias before consulting any other signal source.

Step 2: Check Confidence Score
The Confidence row shows how many of the three inputs align (e.g., 2/3). A 3/3 reading means structure, volatility, and momentum all agree. A 2/3 reading means one factor is diverging. Weight directional decisions higher during full 3/3 alignment.

Step 3: Monitor CHoCH Events
Each CHoCH label marks a structural break against the current bias — a warning that the regime may be shifting. When a CHoCH appears, watch whether subsequent bars confirm a new opposing BOS or whether the previous regime resumes.

Step 4: Use Swing Extension Lines as Forward Reference
The dotted right-edge lines mark the current unbroken swing levels — the nearest structural break zones. Knowing how close price is to these levels frames where the next BOS or CHoCH could occur.

Step 5: Apply Regime as a Filter
Market Phase Detector is designed as a context layer, not a standalone signal generator. Apply the regime output as a filter to your existing tools: only take long signals when the regime is Bullish, only take short signals when Bearish, and step aside or apply mean-reversion logic when Range is active.

Indicator Limitations

  • Pivot detection confirms swingLen bars after the pivot forms, creating a natural offset between the candle where the swing occurred and when it is labeled. This is intentional non-repainting behavior
  • The volatility gate may temporarily classify a new trend as Range immediately after a volatility expansion if ATR has not yet risen above the threshold. This resolves within a few bars as ATR normalizes
  • In slow, grinding markets, momentum may repeatedly lag structure, resulting in extended Range readings during mild trends
  • Market Phase Detector classifies current market state. It does not predict future price direction or generate entry/exit signals


Originality Statement

Market Phase Detector is original in its three-factor gate requiring independent alignment of structure, volatility, and momentum before any regime is confirmed. This indicator is published because:

  • The combination of CHoCH and BOS structural logic, an ATR contraction gate, and a smoothed momentum filter into a single lightweight classifier that produces a confidence score is uncommon in published open-source Pine Script v6
  • Distinguishing BOS from CHoCH within the same indicator — with independent event counts and labeled historical events — provides structural context that standalone trend indicators do not offer
  • The confidence scoring system (1-3) quantifies the strength of the current regime reading across three independent analytical dimensions, not just a single oscillator value
  • Swing level extension lines provide live structural reference at the right edge of the chart without requiring the user to manually draw levels or add a separate pivot indicator


Disclaimer

This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Regime classifications are based on historical price data and do not guarantee any future market behavior. All three factors can produce inaccurate readings in atypical market conditions. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.

-Made with passion by jackofalltrades

Feragatname

Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, alım satım veya diğer türden tavsiye veya öneriler anlamına gelmez ve teşkil etmez. Kullanım Koşulları bölümünde daha fazlasını okuyun.