OPEN-SOURCE SCRIPT
Cập nhật EW Probability x SuperTrend

Elliott Wave Probability × SuperTrend [EWPS]
User Description & Guide

1. What Is EWPS?
EWPS fuses classical Elliott Wave pattern recognition with a dynamic ATR trailing stop (SuperTrend). Unlike standard SuperTrend which flips indiscriminately on volatility breaks, EWPS calculates a real-time probability that the current market structure aligns with a valid 5-wave impulse sequence. It then uses this probability to filter, tint, and validate SuperTrend signals.
The result is a directional trend-follower that knows the difference between a healthy W3 extension (high probability long) and a noisy W4 chop (low probability, dimmed trail).

2. Core Architecture
Base Layer: SuperTrend
• Classic ATR-based trailing stop using hl2/close/ohlc4 source.
• Maintains upper and lower bands; flips when price closes through the opposing band.
Pattern Layer: Elliott Wave Engine
• Maintains a rolling buffer of the last 12 swing pivots (highs/lows).
• Attempts to fit a 5-wave impulse (6 pivots: 0-1-2-3-4-5) to recent price action.
• Validates waves using 4 hard rules (binary pass/fail) and 7 weighted guidelines (quality score 0.0–1.0).
Probability Layer: Live Wave Context
• Determines which wave is currently developing (e.g., "developing W3").
• Calculates base position scores (W3 and W5 development favored; W2/W4 corrections cautionary).
• Measures Fibonacci fit of the developing leg against ideal extensions/retracements.
• Quantifies invalidation risk (proximity to W0 or W1 overlap that would break the count).
• Synthesizes into a 0.0–1.0 probability via logistic (sigmoid) regression with configurable weights.
Emission Layer: Filtered Signals
• Raw SuperTrend flips are gated by probability thresholds.
• Bullish flips require bullProb ≥ gate AND bearProb ≤ fade gate.
• Trail color shifts from dim grey (low confidence) to bright green/red (high confidence) based on current probability.

3. Input Parameters
SuperTrend Settings
• ATR Length: Lookback for ATR calculation (default 10). Higher = slower trail, fewer whipsaws.
• ATR Multiplier: Distance factor for bands (default 3.0). Higher = wider stops, fewer flips.
• Source: Price input—hl2 (midpoint, default), close, ohlc4, or hlc3.
Swing Detection
• Pivot Left/Right Bars: Defines swing sensitivity. Left=4, Right=1 means a high/low must be the highest/lowest of 4 bars left and 1 bar right to qualify. Right=0 is faster but repainting; Right=1 is standard confirmation.
• Minimum Swing %: Filters noise by requiring pivots to be separated by at least 0.20% price movement.
EW Engine
• Fib Proximity Tolerance: Gaussian width for Fibonacci matching (default 0.08). Lower = stricter adherence to ideal ratios.
• Min Impulse Quality: Minimum quality score (0.0–1.0) to trust a wave count (default 0.40). Below this, the engine treats the structure as "unknown."
• Allow W4→W1 Overlap: Toggle for diagonal/triangle patterns where W4 may enter W1 territory (default false).
• Allow Truncated W5: Whether to accept W5s that fail to exceed W3 (default true), applying only a quality penalty rather than invalidation.
Probability Weights
These feed the logistic regression that produces bullProb/bearProb. Adjust to emphasize what matters for your market:
• Impulse Quality (default 2.0): Weight of the base pattern score (0–1 from guideline scoring).
• Wave Position (default 2.5): Weight of "where are we in the sequence" (W3 development strongly bullish).
• Current-Leg Fib Fit (default 1.2): Weight of how well the developing leg matches ideal Fibonacci extensions/retracements.
• Invalidation Risk (default 1.5): Penalty weight for proximity to structural breaks (W2 > 100% retrace, W4 into W1).
• Directional Bias (default 0.0): Constant shift (+ bullish, − bearish) to skew probabilities without changing pattern logic. Use if backtests show consistent directional skew.
Emission & Gates
• Min Bull/Bear Prob for Flip: Threshold to permit a SuperTrend flip in that direction (default 0.60). Flips only occur if probability supports the new direction.
• Max Opposite Prob (Fade Gate): Safety check (default 0.35). Prevents flipping long if bearProb is still dangerously high, even if bullProb is decent.
• Invert Long/Short Emission: Boolean toggle. If enabled, swaps bullProb/bearProb in the gating logic (useful if you discover via backtest that signals are more accurate when reversed—a known phenomenon in some Bayesian pattern engines).
Visuals
• Dim Trail When Prob Low: Greys out the SuperTrend line when current probability is below tier thresholds.
• Background Probability Tint: Fills background with low-opacity bull/bear color intensity scaling with probability strength.
• Show State Table: Displays the debug/info panel (top-right) showing wave position, impulse quality, Fib fit, invalidation risk, and current probabilities.

4. Interpreting the Indicator
The Trail Line
• Bright Green/Red: High confidence (≥60%) alignment with impulse direction. Safe trend-following territory.
• Muted Green/Red: Medium confidence (40–60%). Trend exists but structure is questionable or early.
• Dim Grey: Low confidence (<40%) or "gated" state. The SuperTrend is technically long/short but the EW engine sees no valid pattern supporting it. Often coincides with W2/W4 corrections or unknown wave counts.
Wave Position Readings (State Table)
The indicator displays which wave is currently developing:
• dev W2: Developing second wave (correction). Low base score; expect chop. Good for patience/waiting for W3 entry.
• dev W3 ★: Developing third wave (strongest impulse). Highest base score; ideal for momentum entries.
• dev W4: Developing fourth wave (correction). Moderate caution; prepare for W5 or failed W5 truncation.
• dev W5 ★: Developing fifth wave. Good continuation score but watch for truncation and reversal into "A" wave.
• post-W5: Structure complete; expecting ABC correction or new impulse. Lowest scores; trend exhaustion likely.
Signal Shapes
• ▲ L (Large Green Triangle): Filtered Long—SuperTrend flipped up AND probability gates passed (bullProb ≥ 0.60, bearProb ≤ 0.35).
• ▼ S (Large Red Triangle): Filtered Short—SuperTrend flipped down AND probability gates passed.
• Small X Cross: Raw flip that was gated (probability too low). Shows where SuperTrend wanted to flip but EWPS blocked it due to poor structural fit. Useful for seeing "avoided whipsaws."
Background Tint
• Intensity scales with current probability (currentQ).
• Bright = strong structural alignment.
• Absent or faint = weak alignment (even if SuperTrend direction persists).
Key Metrics in State Table
• Impulse Q: The 0.0–1.0 quality score from guideline validation. Green if ≥ minQ, orange if below.
• Fib Fit: 0.0–1.0 score of current leg vs ideal Fibonacci zones. Higher = price is at "perfect" W3 extension or W2 retracement.
• Inval Risk: 0.0–1.0 proximity to pattern invalidation. Red warning if >0.60 (price approaching W0 or overlapping W1).
• Bull P / Bear P: Final probabilities after sigmoid transformation. Colored when above respective gates.

5. Practical Usage Guidelines
Trend Entry Strategy
1. Wait for a Filtered Long (▲ L) or Filtered Short (▼ S) signal.
2. Confirm the State Table shows dev W3 or dev W5 (starred positions) for strongest momentum.
3. Check that Inval Risk is low (<0.30) and Fib Fit is high (>0.60).
4. Enter on close of signal bar; trail the SuperTrend line as stop-loss.
Avoiding False Breakouts
• If SuperTrend flips but you see a small X (gated) instead of a triangle, do not enter. The EW engine has rejected the flip due to:
◦ Low impulse quality (choppy/ranging structure).
◦ High invalidation risk (price near critical support/resistance that would break the wave count).
◦ Wave position in correction (dev W2 or dev W4) suggesting the "trend" is actually a counter-trend chop.
Wave Position Trading
• W3 Entries: When state shows "dev W3" with rising Fib Fit, add to positions or pyramid. This is the "meat of the move."
• W5 Cautions: When state shows "dev W5," tighten stops. Use the truncation allowance setting carefully—if disabled, W5 failures invalidate quickly; if enabled, you ride deeper but risk reversal.
• W2 Accumulation: When state shows "dev W2" and Inval Risk is low (not near W0), prepare limit orders for the W3 breakout rather than chasing.
Probability Divergence
• If price makes new highs but Bull P is declining while Bear P rises, the structure is weakening (W5 truncation or diagonal forming). Consider taking profits even if SuperTrend remains long.
Timeframe Adaptation
• Lower Timeframes (M1-M15): Reduce Pivot Left Bars to 2-3 for faster swing detection; increase ATR Multiplier to 4.0+ to avoid noise; tighten Fib Tolerance to 0.05 for stricter pattern quality.
• Higher Timeframes (H4-Daily): Increase Pivot Left Bars to 5-8 for significant swings; decrease ATR Multiplier to 2.0-2.5 for responsiveness; use longer SuperTrend ATR lengths (14-21).
Invert Toggle Usage
• If after 50+ trades you notice the gated (X) signals were actually better entries than the filtered triangles, enable Invert Long/Short Emission. This indicates the market is exhibiting "Bayesian mismatch" where the pattern probabilities are inverted—common in mean-reversion heavy assets.

6. Alert Conditions
The script provides four alert types:
Filtered Long
• Fires when a high-probability bullish SuperTrend flip occurs.
• Use for: Live entry notifications on W3/W5 breakouts.
Filtered Short
• Fires when a high-probability bearish SuperTrend flip occurs.
• Use for: Short entry notifications on W3/W5 down-impulse breakouts.
Raw Flip Up / Raw Flip Down
• Fires on all SuperTrend direction changes regardless of probability gating.
• Use for: Monitoring all potential trend changes (including those the EW engine rejected) for manual discretion or alternate strategies.
User Description & Guide

1. What Is EWPS?
EWPS fuses classical Elliott Wave pattern recognition with a dynamic ATR trailing stop (SuperTrend). Unlike standard SuperTrend which flips indiscriminately on volatility breaks, EWPS calculates a real-time probability that the current market structure aligns with a valid 5-wave impulse sequence. It then uses this probability to filter, tint, and validate SuperTrend signals.
The result is a directional trend-follower that knows the difference between a healthy W3 extension (high probability long) and a noisy W4 chop (low probability, dimmed trail).

2. Core Architecture
Base Layer: SuperTrend
• Classic ATR-based trailing stop using hl2/close/ohlc4 source.
• Maintains upper and lower bands; flips when price closes through the opposing band.
Pattern Layer: Elliott Wave Engine
• Maintains a rolling buffer of the last 12 swing pivots (highs/lows).
• Attempts to fit a 5-wave impulse (6 pivots: 0-1-2-3-4-5) to recent price action.
• Validates waves using 4 hard rules (binary pass/fail) and 7 weighted guidelines (quality score 0.0–1.0).
Probability Layer: Live Wave Context
• Determines which wave is currently developing (e.g., "developing W3").
• Calculates base position scores (W3 and W5 development favored; W2/W4 corrections cautionary).
• Measures Fibonacci fit of the developing leg against ideal extensions/retracements.
• Quantifies invalidation risk (proximity to W0 or W1 overlap that would break the count).
• Synthesizes into a 0.0–1.0 probability via logistic (sigmoid) regression with configurable weights.
Emission Layer: Filtered Signals
• Raw SuperTrend flips are gated by probability thresholds.
• Bullish flips require bullProb ≥ gate AND bearProb ≤ fade gate.
• Trail color shifts from dim grey (low confidence) to bright green/red (high confidence) based on current probability.

3. Input Parameters
SuperTrend Settings
• ATR Length: Lookback for ATR calculation (default 10). Higher = slower trail, fewer whipsaws.
• ATR Multiplier: Distance factor for bands (default 3.0). Higher = wider stops, fewer flips.
• Source: Price input—hl2 (midpoint, default), close, ohlc4, or hlc3.
Swing Detection
• Pivot Left/Right Bars: Defines swing sensitivity. Left=4, Right=1 means a high/low must be the highest/lowest of 4 bars left and 1 bar right to qualify. Right=0 is faster but repainting; Right=1 is standard confirmation.
• Minimum Swing %: Filters noise by requiring pivots to be separated by at least 0.20% price movement.
EW Engine
• Fib Proximity Tolerance: Gaussian width for Fibonacci matching (default 0.08). Lower = stricter adherence to ideal ratios.
• Min Impulse Quality: Minimum quality score (0.0–1.0) to trust a wave count (default 0.40). Below this, the engine treats the structure as "unknown."
• Allow W4→W1 Overlap: Toggle for diagonal/triangle patterns where W4 may enter W1 territory (default false).
• Allow Truncated W5: Whether to accept W5s that fail to exceed W3 (default true), applying only a quality penalty rather than invalidation.
Probability Weights
These feed the logistic regression that produces bullProb/bearProb. Adjust to emphasize what matters for your market:
• Impulse Quality (default 2.0): Weight of the base pattern score (0–1 from guideline scoring).
• Wave Position (default 2.5): Weight of "where are we in the sequence" (W3 development strongly bullish).
• Current-Leg Fib Fit (default 1.2): Weight of how well the developing leg matches ideal Fibonacci extensions/retracements.
• Invalidation Risk (default 1.5): Penalty weight for proximity to structural breaks (W2 > 100% retrace, W4 into W1).
• Directional Bias (default 0.0): Constant shift (+ bullish, − bearish) to skew probabilities without changing pattern logic. Use if backtests show consistent directional skew.
Emission & Gates
• Min Bull/Bear Prob for Flip: Threshold to permit a SuperTrend flip in that direction (default 0.60). Flips only occur if probability supports the new direction.
• Max Opposite Prob (Fade Gate): Safety check (default 0.35). Prevents flipping long if bearProb is still dangerously high, even if bullProb is decent.
• Invert Long/Short Emission: Boolean toggle. If enabled, swaps bullProb/bearProb in the gating logic (useful if you discover via backtest that signals are more accurate when reversed—a known phenomenon in some Bayesian pattern engines).
Visuals
• Dim Trail When Prob Low: Greys out the SuperTrend line when current probability is below tier thresholds.
• Background Probability Tint: Fills background with low-opacity bull/bear color intensity scaling with probability strength.
• Show State Table: Displays the debug/info panel (top-right) showing wave position, impulse quality, Fib fit, invalidation risk, and current probabilities.

4. Interpreting the Indicator
The Trail Line
• Bright Green/Red: High confidence (≥60%) alignment with impulse direction. Safe trend-following territory.
• Muted Green/Red: Medium confidence (40–60%). Trend exists but structure is questionable or early.
• Dim Grey: Low confidence (<40%) or "gated" state. The SuperTrend is technically long/short but the EW engine sees no valid pattern supporting it. Often coincides with W2/W4 corrections or unknown wave counts.
Wave Position Readings (State Table)
The indicator displays which wave is currently developing:
• dev W2: Developing second wave (correction). Low base score; expect chop. Good for patience/waiting for W3 entry.
• dev W3 ★: Developing third wave (strongest impulse). Highest base score; ideal for momentum entries.
• dev W4: Developing fourth wave (correction). Moderate caution; prepare for W5 or failed W5 truncation.
• dev W5 ★: Developing fifth wave. Good continuation score but watch for truncation and reversal into "A" wave.
• post-W5: Structure complete; expecting ABC correction or new impulse. Lowest scores; trend exhaustion likely.
Signal Shapes
• ▲ L (Large Green Triangle): Filtered Long—SuperTrend flipped up AND probability gates passed (bullProb ≥ 0.60, bearProb ≤ 0.35).
• ▼ S (Large Red Triangle): Filtered Short—SuperTrend flipped down AND probability gates passed.
• Small X Cross: Raw flip that was gated (probability too low). Shows where SuperTrend wanted to flip but EWPS blocked it due to poor structural fit. Useful for seeing "avoided whipsaws."
Background Tint
• Intensity scales with current probability (currentQ).
• Bright = strong structural alignment.
• Absent or faint = weak alignment (even if SuperTrend direction persists).
Key Metrics in State Table
• Impulse Q: The 0.0–1.0 quality score from guideline validation. Green if ≥ minQ, orange if below.
• Fib Fit: 0.0–1.0 score of current leg vs ideal Fibonacci zones. Higher = price is at "perfect" W3 extension or W2 retracement.
• Inval Risk: 0.0–1.0 proximity to pattern invalidation. Red warning if >0.60 (price approaching W0 or overlapping W1).
• Bull P / Bear P: Final probabilities after sigmoid transformation. Colored when above respective gates.

5. Practical Usage Guidelines
Trend Entry Strategy
1. Wait for a Filtered Long (▲ L) or Filtered Short (▼ S) signal.
2. Confirm the State Table shows dev W3 or dev W5 (starred positions) for strongest momentum.
3. Check that Inval Risk is low (<0.30) and Fib Fit is high (>0.60).
4. Enter on close of signal bar; trail the SuperTrend line as stop-loss.
Avoiding False Breakouts
• If SuperTrend flips but you see a small X (gated) instead of a triangle, do not enter. The EW engine has rejected the flip due to:
◦ Low impulse quality (choppy/ranging structure).
◦ High invalidation risk (price near critical support/resistance that would break the wave count).
◦ Wave position in correction (dev W2 or dev W4) suggesting the "trend" is actually a counter-trend chop.
Wave Position Trading
• W3 Entries: When state shows "dev W3" with rising Fib Fit, add to positions or pyramid. This is the "meat of the move."
• W5 Cautions: When state shows "dev W5," tighten stops. Use the truncation allowance setting carefully—if disabled, W5 failures invalidate quickly; if enabled, you ride deeper but risk reversal.
• W2 Accumulation: When state shows "dev W2" and Inval Risk is low (not near W0), prepare limit orders for the W3 breakout rather than chasing.
Probability Divergence
• If price makes new highs but Bull P is declining while Bear P rises, the structure is weakening (W5 truncation or diagonal forming). Consider taking profits even if SuperTrend remains long.
Timeframe Adaptation
• Lower Timeframes (M1-M15): Reduce Pivot Left Bars to 2-3 for faster swing detection; increase ATR Multiplier to 4.0+ to avoid noise; tighten Fib Tolerance to 0.05 for stricter pattern quality.
• Higher Timeframes (H4-Daily): Increase Pivot Left Bars to 5-8 for significant swings; decrease ATR Multiplier to 2.0-2.5 for responsiveness; use longer SuperTrend ATR lengths (14-21).
Invert Toggle Usage
• If after 50+ trades you notice the gated (X) signals were actually better entries than the filtered triangles, enable Invert Long/Short Emission. This indicates the market is exhibiting "Bayesian mismatch" where the pattern probabilities are inverted—common in mean-reversion heavy assets.

6. Alert Conditions
The script provides four alert types:
Filtered Long
• Fires when a high-probability bullish SuperTrend flip occurs.
• Use for: Live entry notifications on W3/W5 breakouts.
Filtered Short
• Fires when a high-probability bearish SuperTrend flip occurs.
• Use for: Short entry notifications on W3/W5 down-impulse breakouts.
Raw Flip Up / Raw Flip Down
• Fires on all SuperTrend direction changes regardless of probability gating.
• Use for: Monitoring all potential trend changes (including those the EW engine rejected) for manual discretion or alternate strategies.
Phát hành các Ghi chú
updated configurations Phát hành các Ghi chú
Updated to have inversion on by defaultPhát hành các Ghi chú
Improved wave identification logic Phát hành các Ghi chú
updated atr requirements Mã nguồn mở
Theo đúng tinh thần TradingView, tác giả của tập lệnh này đã công bố nó dưới dạng mã nguồn mở, để các nhà giao dịch có thể xem xét và xác minh chức năng. Chúc mừng tác giả! Mặc dù bạn có thể sử dụng miễn phí, hãy nhớ rằng việc công bố lại mã phải tuân theo Nội quy.
Thông báo miễn trừ trách nhiệm
Thông tin và các ấn phẩm này không nhằm mục đích, và không cấu thành, lời khuyên hoặc khuyến nghị về tài chính, đầu tư, giao dịch hay các loại khác do TradingView cung cấp hoặc xác nhận. Đọc thêm tại Điều khoản Sử dụng.
Mã nguồn mở
Theo đúng tinh thần TradingView, tác giả của tập lệnh này đã công bố nó dưới dạng mã nguồn mở, để các nhà giao dịch có thể xem xét và xác minh chức năng. Chúc mừng tác giả! Mặc dù bạn có thể sử dụng miễn phí, hãy nhớ rằng việc công bố lại mã phải tuân theo Nội quy.
Thông báo miễn trừ trách nhiệm
Thông tin và các ấn phẩm này không nhằm mục đích, và không cấu thành, lời khuyên hoặc khuyến nghị về tài chính, đầu tư, giao dịch hay các loại khác do TradingView cung cấp hoặc xác nhận. Đọc thêm tại Điều khoản Sử dụng.