OPEN-SOURCE SCRIPT
更新済

StealthTrail SuperTrend ML Pro [WillyAlgoTrader]

10 659
🤖 StealthTrail SuperTrend ML Pro is an overlay indicator that builds on the adaptive SuperTrend core from StealthTrail and adds three layers of intelligence: an instrument profiling engine that classifies the market into Trending, Ranging, or Volatile regimes and auto-tunes all SuperTrend parameters accordingly; a 13-feature machine learning scoring system that evaluates every candidate signal on momentum, trend, volatility, structure, volume, HTF alignment, divergence, session quality, and regime context — producing a 0–100 confidence score; and a self-learning mechanism that tracks signal outcomes over time and dynamically adjusts the confidence gate to optimize signal quality. The result is a SuperTrend that configures itself, scores its own signals, and learns from its results.


🧩 WHY THESE COMPONENTS WORK TOGETHER

A standard SuperTrend has fixed parameters that work well in one market regime and fail in another. Manually tuning ATR length, multiplier, and filters for each instrument and timeframe is time-consuming and becomes outdated when conditions change.

This indicator solves the problem through a three-layer intelligence stack:

Layer 1 — Regime classification → Auto-tuning: The instrument profiler continuously measures efficiency ratio (trend strength), autocorrelation (serial dependence), volatility clustering, and normalized volatility — classifying the market into TRENDING, RANGING, or VOLATILE. Each regime produces different optimal SuperTrend parameters. The auto-tuner interpolates ATR length, multiplier, cushion, cooldown, and RSI threshold using regime-weighted blending — so the SuperTrend self-configures for current conditions.

Layer 2 — ML signal scoring: Even with auto-tuned parameters, not every SuperTrend flip is a good trade. The 13-feature ML engine evaluates each flip against momentum, volume, trend efficiency, volatility shock, band distance, MACD, price structure, regime confidence, MTF alignment, ADX strength, RSI divergence, volume profile zone, and session quality. Each feature is normalized to 0–100, weighted, passed through a sigmoid function, and combined into a single confidence score. Signals below the confidence gate are rejected — they pass the classic SuperTrend logic but fail the multi-dimensional quality check.

Layer 3 — Self-learning gate: The ML confidence gate itself adapts over time. The system tracks each signal's outcome (win/loss evaluated after N bars using the ATR at entry for fair comparison). When the win rate exceeds 70%, the gate lowers (allowing more signals). When it drops below 50%, the gate raises (becoming stricter). A decay factor prevents old signals from dominating. This creates a feedback loop: the indicator learns which confidence level produces profitable signals on this specific instrument and timeframe.

Without auto-tuning, the SuperTrend uses static parameters. Without ML scoring, good and bad flips are treated equally. Without self-learning, the confidence gate is a fixed guess. Each layer eliminates a specific category of bad signals that the previous layer can't catch.


🔍 WHAT MAKES IT ORIGINAL

1️⃣ Instrument profiling and regime classification.
The profiler computes four metrics over a configurable lookback (default 100 bars):

— 📐 Efficiency Ratio: ER = |close − close[N]| / sum(|close − close[1]|, N). Measures net directional movement vs total path. ER → 1.0 = pure trend, ER → 0.0 = pure chop.
— 🔄 Autocorrelation: correlation between return[t] and return[t−1] over a sliding window. High positive autocorrelation = trending persistence. Near-zero = random. Negative = mean-reverting.
— 📏 Volatility Clustering: ratio of short-term ATR (20 bars) to long-term ATR (lookback). Values > 1.0 indicate a volatility spike (breakout or crash). Values < 1.0 indicate compression.
— 📈 Normalized Volatility: ATR / close × 100. Measures absolute volatility as percentage of price — allows cross-instrument comparison.

These are smoothed with EMA and combined into three regime scores:
— trendScore = ER × regimeSensitivity
— rangeScore = (1 − ER) × (1 − |autocorrelation|) × regimeSensitivity
— volatScore = clamp(volClustering − 1, 0, 2) × regimeSensitivity

The highest score determines the regime: TRENDING, RANGING, or VOLATILE. Regime confidence = highest_score / total_scores × 100%.

2️⃣ Regime-weighted auto-tuning (6 parameters).
Each SuperTrend parameter is computed as a weighted blend of regime-optimal values:

effectiveParam = wT × trendOptimal + wR × rangeOptimal + wV × volatileOptimal

Where wT, wR, wV are the normalized regime weights. The parameters and their regime-optimal ranges:

— ATR Length: Trending=10, Ranging=16, Volatile=21 (further scaled by normalized volatility)
— Base Multiplier: Trending=2.0, Ranging=3.2, Volatile=3.8 (scaled by normalized vol)
— Flip Cushion: Trending=0.05, Ranging=0.25, Volatile=0.15
— Signal Cooldown: Trending=2, Ranging=5, Volatile=3
— RSI Threshold: Trending=40, Ranging=52, Volatile=45
— RSI Length: derived as ATR Length × 0.9
— Adaptive Smoothing: ATR Length × 4.0

This means in a trending regime, the SuperTrend uses shorter ATR, lower multiplier (tighter bands), minimal cushion, and permissive RSI — catching trends early. In a ranging regime: longer ATR, wider multiplier, large cushion, strict RSI — avoiding chop. In volatile conditions: intermediate settings with wider bands to accommodate spikes.

3️⃣ 13-feature ML scoring engine.
Each feature is normalized to 0–100, multiplied by its weight, summed, normalized by total weight, and passed through a sigmoid function to produce the final 0–100 confidence score.

Features and their weights:
— 💪 F1: Momentum (RSI alignment with trend) — w=0.15
— 📈 F2: Volume Surge (volume / SMA ratio) — w=0.08
— 📐 F3: Trend Efficiency (ER × 100) — w=0.15
— ⚡ F4: Volatility Shock (inverted vol clustering) — w=−0.08 (negative = penalizes vol spikes)
— 📏 F5: Band Distance (sigmoid of close-to-band ATR distance) — w=0.10
— 📊 F6: MACD (normalized histogram vs ATR) — w=0.08
— 🏗️ F7: Price Structure (HH/HL for bull, LL/LH for bear over 10 bars) — w=0.08
— 🧠 F8: Regime Confidence (% confidence in current regime) — w=0.04
— 🌐 F9: MTF Confluence (aligned with HTF = 100, not = 0) — w=0.12
— 💪 F10: ADX Strength (ADX × 2.5, capped at 100) — w=0.10
— 🔀 F11: RSI Divergence (aligned div = 100, counter div = 10) — w=0.08
— 📊 F12: Volume Profile Zone (proximity to highest-volume bar) — w=0.06
— 🕐 F13: Session Quality (hour-based scoring for optimal trading sessions) — w=0.04

The raw weighted sum is normalized, then passed through: mlScore = 100 / (1 + exp(−0.08 × (normalizedScore − 50))). This sigmoid compresses extreme values and centers the output around 50.

All 13 weights plus the bias term are user-configurable — you can adjust how much each factor contributes. Negative weights penalize a factor (e.g., W4 = −0.08 means high volatility shock reduces the score).

4️⃣ Self-learning confidence gate.
The system maintains 5 pending signal slots. Each stores the entry price, direction, bar index, and ATR at entry. After the evaluation horizon (default 15 bars), the outcome is assessed:

win = (close − entryPrice) × direction > 0.5 × entryATR (profitable by at least half an ATR, using the ATR at entry time — not current ATR — for fair comparison)

A decay factor (0.98) is applied to historical totals before adding new results, preventing stale data from dominating. When total tracked signals ≥ 8:
— Win rate > 70% → gate decreases by 1.5 (more permissive)
— Win rate < 50% → gate increases by 1.5 (more restrictive)
— Gate is clamped to [20, 85]

The dashboard shows the current gate value, whether it's auto-adjusted, and the tracked win rate with sample size.

5️⃣ Multi-timeframe confluence with auto-HTF selection.
The indicator automatically selects the appropriate higher timeframe based on your current TF: 1M→15M, 5M→30M, 15M→1H, 1H→4H, 4H→D, D→W. Or you can manually specify the HTF.

Three strictness levels:
— Loose: MTF misalignment adds negative ML score but doesn't block
— Moderate: MTF misalignment reduces signal quality
— Strict: MTF misalignment hard-blocks the signal entirely

HTF trend is determined by EMA(20) vs EMA(50) on the higher timeframe.

6️⃣ Adaptive SuperTrend core (from StealthTrail).
The band calculation uses pre-computed interpolated ATR values (ATR bank at 9 fixed periods with lerp interpolation) for smooth adaptation to any auto-tuned ATR length. Same mechanics as StealthTrail: adaptive multiplier (ATR / SMA ratio), band ratcheting, flip cushion, and cooldown — but now all parameters are regime-driven.

7️⃣ Three-mode trailing TP/SL system.
Three SL modes: ATR (entry ± mult × ATR), Band (SuperTrend band as SL), Fixed % (percentage from entry).
Three trailing modes:
ATR: trail at fixed ATR distance from price — simple, consistent
Band: use the SuperTrend band itself as trailing stop — structurally anchored
ATR → Band (hybrid): start with tight ATR trail, switch to band when it catches up — best of both

The trail only ratchets in the profit direction (never moves away from price). TP1/TP2/TP3 hit markers (✓) appear on the chart. On TP3 or SL hit, the trade closes and lines are removed.

8️⃣ RSI divergence detection.
Scans for bullish divergence (price lower low, RSI higher low, RSI < 40) and bearish divergence (price higher high, RSI lower high, RSI > 60). Divergences aligned with the signal direction boost the ML score (F11 = 100). Counter-divergences penalize it (F11 = 10). Optional visualization as dots on the chart.

9️⃣ Volume profile zone proximity.
Tracks the highest-volume bar in the last 50 bars. Proximity to this bar's price level is scored: within 1.5× ATR = 100 (near institutional activity), further = proportionally lower. Signals near high-volume zones tend to have more follow-through.

🔟 Session quality scoring.
For intraday timeframes, each hour receives a quality score based on typical institutional activity: London/NY overlap (13–17 UTC) = 100, European session (8–12) = 80, US afternoon (18–20) = 70, Asian session (0–7) = 30. An optional kill zone filter suppresses all signals during specified hours.


⚙️ HOW IT WORKS — CALCULATION FLOW

Step 1 — Instrument profiling: ER, autocorrelation, vol clustering, normalized vol → EMA-smoothed → regime classification (TRENDING / RANGING / VOLATILE) with confidence %.

Step 2 — Auto-tuning: Regime weights blend optimal parameters for ATR length, multiplier, cushion, cooldown, RSI threshold/length.

Step 3 — SuperTrend calculation: Interpolated ATR from pre-computed bank → adaptive multiplier (ATR/SMA ratio) → upper/lower bands → ratcheting → flip detection with cushion + cooldown.

Step 4 — Classic filters: Momentum (RSI), volume, session, MTF hard-block (if strict).

Step 5 — ML feature extraction: 13 features normalized to 0–100 from current market state.

Step 6 — ML scoring: Weighted sum → weight normalization → sigmoid → 0–100 confidence score.

Step 7 — Signal decision: Classic filters pass AND (ML disabled OR mlScore ≥ gate) → confirmed signal.

Step 8 — Self-learning: Signal stored in pending slot → evaluated after horizon bars → win rate updated → gate adjusted.

Step 9 — TP/SL placement: SL from band/ATR/fixed% → TPs as ATR multiples → trailing stop ratchets per mode.


📖 HOW TO USE

🎯 Quick start:
1. Add the indicator — Auto-Tune is ON by default, parameters self-configure
2. The SuperTrend band and Long/Short labels appear
3. Dashboard shows: trend, strength, regime, ML score, gate, win rate, TP/SL status
4. Enable ML Filter for quality scoring (off by default — enable after reviewing signal quality)
5. Self-Learning auto-adjusts the gate over time

👁️ Reading the chart:
— 🟢 Green band + "Long" label = confirmed bullish signal
— 🔴 Red band + "Short" label = confirmed bearish signal
— ⚫ Gray dot = classic filter blocked the flip
— 🟡 Yellow triangle = ML rejected the signal (score below gate)
— 🟢 Green dot below bar = bullish RSI divergence
— 🔴 Red dot above bar = bearish RSI divergence
— 📈 Regime badge = current market classification (📈 TRENDING / 📊 RANGING / ⚡ VOLATILE)
— 🟢 Green dashed = TP1/TP2/TP3, 🔴 Red dashed = SL, 🔵 Blue dotted = entry
— "TP1 ✓" / "SL ✗" labels = outcome markers

📊 Dashboard sections:
Main: trend, signal, strength, ADX, HTF alignment
🤖 ML Engine: ML score, confidence gate (fixed or auto), win rate with sample size
🎯 Position: status (LONG/SHORT/FLAT), entry, SL (with trail mode icon), TP levels (✓ for hit), R:R ratio
🧠 Regime: classification + confidence %

🔧 Tuning guide:
Start simple: Auto-Tune ON, ML OFF — let the regime engine handle parameters
Add ML: Enable ML Filter after 50+ signals to see which score level produces winners
Enable Self-Learning: after 100+ bars of ML being active — let the gate auto-calibrate
Adjust weights: if you know your market (e.g., volume is unreliable on forex → set W2 to 0)
Strict MTF: for higher-timeframe alignment — reduces signals, increases quality
Trail Mode: Band for trend-following, ATR for scalping, ATR→Band for hybrid


⚙️ KEY SETTINGS REFERENCE

⚙️ Main:
Auto-Tune (default On): regime-driven parameter self-configuration
ATR Length / Base Multiplier: manual overrides when auto-tune is off

🧠 Adaptive Engine:
Profiling Lookback (default 100): bars for regime classification
Regime Sensitivity (default 1.0): scaling factor for regime scores

📐 Multi-Timeframe:
MTF Confluence (default On): Auto/Manual HTF selection
Strictness (default Moderate): Loose / Moderate / Strict

🤖 ML Signal Filter:
Enable ML (default Off): activate 13-feature scoring
Confidence Gate (default 21): minimum ML score to pass
Self-Learning (default On): auto-adjust gate from tracked outcomes
Evaluation Horizon (default 15 bars): outcome assessment window
13 individual weights + bias: fully configurable feature importance

🔍 Filters:
— Flip Cushion, Cooldown, RSI Momentum, Volume, Session Kill Zone

🎯 TP/SL:
SL Mode (default Band): ATR / Band / Fixed %
Trail Mode (default Band): ATR / Band / ATR → Band
TP Levels (1–3): ATR multipliers (default 1.5 / 2.5 / 4.0)


🔔 Alerts

— 🟢 LONG / 🔴 SHORT — ticker, price, TF, band, ML score, ADX, HTF, SL, TP1, regime
— 🎯 TP1 / TP2 / TP3 HIT — trade progress
— 🛑 SL HIT — stopped out
All support plain text and JSON webhook format. Bar-close confirmed.


⚠️ IMPORTANT NOTES

— 🚫 No repainting. All signals require barstate.isconfirmed. The confirmed trend direction is stored separately from the real-time calculation — signals only fire on closed bars. HTF data uses lookahead_off. A warmup period (max of profiling lookback and 55 bars) prevents signals during insufficient data.
— 🤖 The ML scoring is not machine learning in the neural network sense. It's a weighted linear model with sigmoid activation — a logistic regression analog. The 13 features are hand-crafted from market microstructure, and the weights are configurable by the user. There is no gradient descent, backpropagation, or training phase. The "self-learning" adjusts only the confidence gate threshold, not the feature weights.
— 📐 Auto-tuning produces different parameters on every bar as the regime shifts. The ATR length and multiplier change continuously — this is by design. If you prefer fixed parameters, disable Auto-Tune.
— ⚖️ The self-learning gate requires at least 8 tracked signals before it begins adjusting. With the decay factor (0.98), the effective sample is weighted toward recent signals. The gate moves slowly (±1.5 per adjustment) and is clamped to [20, 85].
— 📊 Win rate evaluation uses ATR at entry time, not current ATR. A signal is a "win" if price moves > 0.5× entry ATR in the signal direction within the evaluation horizon. This prevents volatile periods from inflating win counts.
— 🔄 The pre-computed ATR bank (9 fixed periods with lerp interpolation) is a performance optimization that allows smooth ATR adaptation to any auto-tuned length without calling ta.atr() dynamically — which Pine Script doesn't support with variable-length arguments.
— 📏 Volume Profile Zone tracks the single highest-volume bar in the last 50 bars, not a full volume profile. It decays after 50 bars with no new volume peak.
— 🕐 Session scoring uses UTC-based hours. On daily or higher timeframes, session quality defaults to 50 (neutral) as intraday session distinctions don't apply.
— 🛠️ This is a signal scoring and analysis tool, not an automated trading bot. It classifies regimes, scores signals, tracks outcomes, and manages TP/SL — trade decisions remain yours.
— 🌐 Works on all markets and timeframes. Volume features auto-adapt to instruments without volume data.
リリースノート
What's new:

TP default multipliers rebalanced for better risk-to-reward: TP1 1.5× → 2×, TP2 2.5× → 4×, TP3 4.0× → 6× ATR — wider targets capture more of the move in trending conditions
Added vertical R:R range line on the signal bar connecting SL to the highest TP — instantly visualizes the full risk-to-reward window at entry
SL label now reads "TR SL" instead of "SL" — clearly indicates the stop is trailing, not static

免責事項

これらの情報および投稿は、TradingViewが提供または承認する金融、投資、取引、またはその他の種類の助言もしくは推奨であることを意図したものではなく、またこれらに該当するものでもありません。詳細は利用規約をご覧ください。