OPEN-SOURCE SCRIPT
Wisely Wealth ; M-W Pattern Scorer & Breakout Engine

# M-W Pattern Scorer & Breakout Engine
### 1. Introduction: Purpose and Overview
The **M-W Pattern Scorer & Breakout Engine** is an advanced, fully automated technical analysis indicator written in Pine Script v6 for TradingView. It is designed to identify, evaluate, and trade classic Double Top ("M-shape") and Double Bottom ("W-shape") chart reversal patterns with algorithmic precision.
Traditional pattern trading is frequently plagued by two major flaws: **human subjectivity** (traders seeing patterns where none exist) and **unfiltered false breakouts** caused by weak market structure. The primary objective of this indicator is to eliminate guesswork by transforming subjective visual chart patterns into a quantifiable, rule-based trading system. It pairs strict geometric pivot validation with a proprietary **Multi-Factor Quality Scoring System (0–100)** and dynamic Risk-to-Reward projection targets, allowing traders to systematically filter out low-probability noise and focus exclusively on textbook-grade setups.
---
### 2. Working Mechanism: In-Depth Technical Concepts
The indicator operates through a multi-stage quantitative pipeline that spans structural detection, quality scoring, confirmation filtering, and risk projection:
#### A. Algorithmic Pivot Recognition & Geometric Validation
- **Pivot Confirmation:** The script tracks swing highs and lows using `ta.pivothigh` and `ta.pivotlow` across customizable left and right lookback bars.
- **Time Distance Constraints:** It validates that the two peaks (or valleys) form within an optimal time span (`Min Bars` and `Max Bars`), preventing premature micro-patterns and overly detached swings.
- **Volatility-Adjusted Price Tolerance:** Rather than requiring identical price points, the price difference between Peak 1 and Peak 2 is dynamically measured against the Average True Range:
$$\Delta \text{Price} \le (\text{ATR} \times \text{Tolerance Multiplier})$$
- **Neckline Formulation:** The algorithm automatically searches the price action between the two peaks to pinpoint the lowest intermediate trough for Double Tops (or highest intermediate crest for Double Bottoms). It also enforces a minimum pattern height relative to ATR, discarding flat, choppy structures.
#### B. The 4-Factor Quality Scoring Matrix (0–100 Points)
Every detected pattern is evaluated across four distinct technical dimensions (up to 25 points each):
1. **Peak Price Proximity (0–25 pts):** Measures horizontal level symmetry. The closer Peak 1 and Peak 2 are in price, the higher the score.
2. **RSI Momentum Divergence (0–25 pts):** Detects momentum deceleration. For Double Tops, it rewards bearish divergence (Peak 2 RSI < Peak 1 RSI). For Double Bottoms, it rewards bullish divergence (Valley 2 RSI > Valley 1 RSI).
3. **Volume Exhaustion Divergence (0–25 pts):** Checks classical auction mechanics. Patterns where the second peak forms on noticeably lower volume than the first peak receive maximum points, confirming market exhaustion.
4. **Pattern Height vs. ATR (0–25 pts):** Evaluates structural prominence. Deeper, well-defined patterns relative to prevailing volatility score higher than compressed patterns.
*Gatekeeper Filter:* A pattern is only considered valid if its composite score meets or exceeds the **Minimum Score Threshold** (default: 60/100).
#### C. Breakout Execution & Macro Trend Filter
- **Breakout Trigger:** A **LONG** signal is triggered when a candle closes definitively above the neckline of a validated Double Bottom. A **SHORT** signal fires when a candle closes below the neckline of a validated Double Top.
- **Optional 200 EMA Filter:** When activated, Long breakouts are restricted to markets trading above the 200 EMA, and Short breakouts below the 200 EMA, keeping traders aligned with the institutional macro trend.
#### D. Dynamic Targets and Risk Levels
Upon breakout, the engine automatically calculates and plots:
- **Stop Loss (SL):** Placed beyond the extreme price of the pattern plus an ATR buffer:
$$\text{SL}_{\text{Short}} = \max(P_1, P_2) + (\text{ATR} \times \text{Buffer})$$
- **Take Profit 1 (TP1):** Neckline $\pm$ $1.0 \times \text{Pattern Height}$ (classical 100% measured move).
- **Take Profit 2 (TP2):** Neckline $\pm$ $1.618 \times \text{Pattern Height}$ (extended Fibonacci expansion).
---
### 3. How to Use: Settings, Markets, and Best Practices
#### Recommended Settings & Profiles
- **Swing / Position Trading (4H, Daily):** Set `Pivot Left/Right` to 5–7, `Min Score Threshold` to 65–70, and enable the `200 EMA Trend Filter`. This produces high-conviction, high-RR reversal setups.
- **Day Trading (5m, 15m, 1H):** Set `Pivot Left/Right` to 3–5 and `Min Score Threshold` to 55–60. Keep `Peak Matching Tolerance` tighter (0.35–0.45 ATR) to counter intraday spread and noise.
#### Market Suitability
- **Forex (Major & Minor Pairs):** Exceptional performance on liquid pairs (EUR/USD, GBP/USD, USD/JPY) where institutional support/resistance levels trigger textbook M/W double retests.
- **Indices & Commodities (S&P 500, NASDAQ, Gold, Crude Oil):** Highly effective on high-volume session opens when sweeping previous liquidity highs/lows.
- **Cryptocurrency (BTC, ETH):** Works best on higher timeframes (1H and above) with the `200 EMA Trend Filter` enabled to avoid whipsaws during aggressive trend extensions.
#### Trade Management Guidelines
Never anticipate the pattern early; always wait for a confirmed candle close through the neckline accompanied by the visual breakout marker. Consider securing partial profits (50%) at **TP1** while shifting the Stop Loss to break-even, and trailing the remainder toward **TP2** for an optimal asymmetrical risk-to-reward outcome.
### 1. Introduction: Purpose and Overview
The **M-W Pattern Scorer & Breakout Engine** is an advanced, fully automated technical analysis indicator written in Pine Script v6 for TradingView. It is designed to identify, evaluate, and trade classic Double Top ("M-shape") and Double Bottom ("W-shape") chart reversal patterns with algorithmic precision.
Traditional pattern trading is frequently plagued by two major flaws: **human subjectivity** (traders seeing patterns where none exist) and **unfiltered false breakouts** caused by weak market structure. The primary objective of this indicator is to eliminate guesswork by transforming subjective visual chart patterns into a quantifiable, rule-based trading system. It pairs strict geometric pivot validation with a proprietary **Multi-Factor Quality Scoring System (0–100)** and dynamic Risk-to-Reward projection targets, allowing traders to systematically filter out low-probability noise and focus exclusively on textbook-grade setups.
---
### 2. Working Mechanism: In-Depth Technical Concepts
The indicator operates through a multi-stage quantitative pipeline that spans structural detection, quality scoring, confirmation filtering, and risk projection:
#### A. Algorithmic Pivot Recognition & Geometric Validation
- **Pivot Confirmation:** The script tracks swing highs and lows using `ta.pivothigh` and `ta.pivotlow` across customizable left and right lookback bars.
- **Time Distance Constraints:** It validates that the two peaks (or valleys) form within an optimal time span (`Min Bars` and `Max Bars`), preventing premature micro-patterns and overly detached swings.
- **Volatility-Adjusted Price Tolerance:** Rather than requiring identical price points, the price difference between Peak 1 and Peak 2 is dynamically measured against the Average True Range:
$$\Delta \text{Price} \le (\text{ATR} \times \text{Tolerance Multiplier})$$
- **Neckline Formulation:** The algorithm automatically searches the price action between the two peaks to pinpoint the lowest intermediate trough for Double Tops (or highest intermediate crest for Double Bottoms). It also enforces a minimum pattern height relative to ATR, discarding flat, choppy structures.
#### B. The 4-Factor Quality Scoring Matrix (0–100 Points)
Every detected pattern is evaluated across four distinct technical dimensions (up to 25 points each):
1. **Peak Price Proximity (0–25 pts):** Measures horizontal level symmetry. The closer Peak 1 and Peak 2 are in price, the higher the score.
2. **RSI Momentum Divergence (0–25 pts):** Detects momentum deceleration. For Double Tops, it rewards bearish divergence (Peak 2 RSI < Peak 1 RSI). For Double Bottoms, it rewards bullish divergence (Valley 2 RSI > Valley 1 RSI).
3. **Volume Exhaustion Divergence (0–25 pts):** Checks classical auction mechanics. Patterns where the second peak forms on noticeably lower volume than the first peak receive maximum points, confirming market exhaustion.
4. **Pattern Height vs. ATR (0–25 pts):** Evaluates structural prominence. Deeper, well-defined patterns relative to prevailing volatility score higher than compressed patterns.
*Gatekeeper Filter:* A pattern is only considered valid if its composite score meets or exceeds the **Minimum Score Threshold** (default: 60/100).
#### C. Breakout Execution & Macro Trend Filter
- **Breakout Trigger:** A **LONG** signal is triggered when a candle closes definitively above the neckline of a validated Double Bottom. A **SHORT** signal fires when a candle closes below the neckline of a validated Double Top.
- **Optional 200 EMA Filter:** When activated, Long breakouts are restricted to markets trading above the 200 EMA, and Short breakouts below the 200 EMA, keeping traders aligned with the institutional macro trend.
#### D. Dynamic Targets and Risk Levels
Upon breakout, the engine automatically calculates and plots:
- **Stop Loss (SL):** Placed beyond the extreme price of the pattern plus an ATR buffer:
$$\text{SL}_{\text{Short}} = \max(P_1, P_2) + (\text{ATR} \times \text{Buffer})$$
- **Take Profit 1 (TP1):** Neckline $\pm$ $1.0 \times \text{Pattern Height}$ (classical 100% measured move).
- **Take Profit 2 (TP2):** Neckline $\pm$ $1.618 \times \text{Pattern Height}$ (extended Fibonacci expansion).
---
### 3. How to Use: Settings, Markets, and Best Practices
#### Recommended Settings & Profiles
- **Swing / Position Trading (4H, Daily):** Set `Pivot Left/Right` to 5–7, `Min Score Threshold` to 65–70, and enable the `200 EMA Trend Filter`. This produces high-conviction, high-RR reversal setups.
- **Day Trading (5m, 15m, 1H):** Set `Pivot Left/Right` to 3–5 and `Min Score Threshold` to 55–60. Keep `Peak Matching Tolerance` tighter (0.35–0.45 ATR) to counter intraday spread and noise.
#### Market Suitability
- **Forex (Major & Minor Pairs):** Exceptional performance on liquid pairs (EUR/USD, GBP/USD, USD/JPY) where institutional support/resistance levels trigger textbook M/W double retests.
- **Indices & Commodities (S&P 500, NASDAQ, Gold, Crude Oil):** Highly effective on high-volume session opens when sweeping previous liquidity highs/lows.
- **Cryptocurrency (BTC, ETH):** Works best on higher timeframes (1H and above) with the `200 EMA Trend Filter` enabled to avoid whipsaws during aggressive trend extensions.
#### Trade Management Guidelines
Never anticipate the pattern early; always wait for a confirmed candle close through the neckline accompanied by the visual breakout marker. Consider securing partial profits (50%) at **TP1** while shifting the Stop Loss to break-even, and trailing the remainder toward **TP2** for an optimal asymmetrical risk-to-reward outcome.
오픈 소스 스크립트
트레이딩뷰의 진정한 정신에 따라, 이 스크립트의 작성자는 이를 오픈소스로 공개하여 트레이더들이 기능을 검토하고 검증할 수 있도록 했습니다. 작성자에게 찬사를 보냅니다! 이 코드는 무료로 사용할 수 있지만, 코드를 재게시하는 경우 하우스 룰이 적용된다는 점을 기억하세요.
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.
오픈 소스 스크립트
트레이딩뷰의 진정한 정신에 따라, 이 스크립트의 작성자는 이를 오픈소스로 공개하여 트레이더들이 기능을 검토하고 검증할 수 있도록 했습니다. 작성자에게 찬사를 보냅니다! 이 코드는 무료로 사용할 수 있지만, 코드를 재게시하는 경우 하우스 룰이 적용된다는 점을 기억하세요.
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.