OPEN-SOURCE SCRIPT
Telah dikemas kini

Adaptive Volatility Stop MTF

391
# Adaptive Volatility Stop MTF (AVS MTF) — v1.2

**Open-source • Pine Script® v6 • Mozilla Public License 2.0**

---

## What this indicator does

AVS MTF is a multi-timeframe volatility-stop indicator. It runs four independent volatility-stop engines — one on the chart timeframe and one each on synthetically derived 3×, 5×, and 15× higher timeframes — and combines their directional states into a weighted bias score from −10 to +10.

Every stop adapts its ATR period and ATR multiplier in real time using the **Kaufman Efficiency Ratio (ER)**, so stops tighten in trending markets and widen in choppy ones.

Three additional integrated subsystems sit on top of the base engine:

- A **Hawkes self-exciting point process** that detects volatility clustering and proportionally raises the firing threshold during vol cascades
- A **data-integrity layer** that auto-detects asset class and flags degraded data (HEALTH = OK / Degraded / Critical)
- An **optional calibration tracker** that reports the engine's measured past hit rate per signal tier with Wilson 95% confidence intervals

The indicator does not predict future prices. It is a structured visualization tool for reading multi-timeframe trend agreement and volatility regime.

---

## Why this is a "mashup" — and why each component is necessary

This script combines four documented techniques:

1. **Volatility Stop** (Chande)
2. **Kaufman Efficiency Ratio**
3. **Multi-Timeframe Aggregation**
4. **Hawkes Self-Exciting Process**

Each component addresses a specific failure mode of the previous one. The integration is what makes the indicator useful:

**1. Volatility Stop (base layer)** — A trailing stop that ratchets in the trend direction by `ATR × multiplier`. By itself this is a classic indicator. Its weakness is well known: in choppy markets it flips constantly because ATR alone cannot tell whether price movement is directional or noise.

**2. Kaufman Efficiency Ratio (adaptation layer)** — ER = (net move) / (total path traveled), bounded in [0, 1]. High ER = trending; low ER = ranging. We use ER to adapt the volatility stop's ATR period (shorter in trends) AND ATR multiplier (tighter in trends). This addresses the choppy-flip problem of the bare volatility stop.

**3. Multi-Timeframe Aggregation (context layer)** — Adapting a single-TF stop is not enough. A "buy" signal on the chart TF means little if the dominant 15× TF is firmly bearish. We run the same adaptive engine on 4 timeframe tiers (Chart, 3×, 5×, 15×) and compute a weighted bias score where higher TFs carry more weight (1, 2, 3, 4). The score gates which signal tiers may fire.

**4. Hawkes Volatility-Cluster Detector (suppression layer)** — Even an adaptive, multi-TF stop fires false signals inside volatility cascades (news events, gap-and-go opens). A Hawkes process tracks an "intensity" that rises with each shock and decays each bar. When intensity / its own baseline exceeds a configurable multiple, the engine raises the bias-score floor required to fire new signals. The lift is proportional — at mild excess only marginal signals are held back; at severe excess only Major-tier flips can fire. A "vol+ / vol++ / vol+++" badge in the dashboard shows the current suppression level.

The combination is what's original here. None of these four components on its own solves the problems the other three address. AVS MTF chains them in a specific order so each layer compensates for the prior layer's weakness.

---

## How to use it

**Setup is minimal.** Add to chart, default settings work on intraday timeframes (5m, 15m, 1H) on liquid instruments (futures, large-cap equities, major crypto pairs).

**Read the dashboard top-down:**

- **SCORE** (−10 to +10): weighted MTF agreement. ≥ +4 = bullish bias, ≤ −4 = bearish.
- **BIAS**: text translation of the score (STRONG BULLISH / BULLISH BIAS / NEUTRAL / etc.).
- **REGIME**: TRENDING / DIRECTIONAL / CHOPPY / TRANSITION.
- **CONVERG**: how tightly the four stops cluster — HIGH = strong cross-TF agreement.
- **HEALTH**: OK / DGR / CRIT. Tooltip shows per-source detail. **Important: if HEALTH shows CRIT, the indicator is unreliable on this instrument.**

**Read the HTF Alignment Ribbon (top of chart):** four colored cells — Chart, 3×, 5×, 15× — showing each timeframe's directional state. When all four match color, you have full HTF alignment.

**Signal hierarchy (visual priority):**

- ▲ / ▼ **Filled label** (Major flip on 15× TF) — highest conviction
- ▲ / ▼ **Small triangle** (Trend flip on 5× TF) — strong
- ▲ / ▼ **Tiny triangle** (Scalp flip on 3× TF) — short-horizon
- ● **Circle** (pullback / band re-touch entry, opt-in display) — momentum continuation
- ✚ **Gold cross** (all higher TFs aligned simultaneously, opt-in display) — rare alignment event

**The Hawkes badge is your filter cue.** When you see `DGR vol++` in the regime row, the indicator is suppressing weak signals. You will see fewer Scalp/Trend signals during these periods. This is intentional — those are the periods where false flips cluster.

**The Calibration Panel (optional, off by default)** reports the engine's measured hit rate on past Trend and Major signals with Wilson 95% confidence intervals. The evaluation rule: a signal is counted as "hit" if price moves at least 0.5 × ATR in the signal direction within N bars (default 10). This is past-only descriptive data — **not a backtest, not a forward prediction, and it does not account for transaction costs, slippage, or execution.**

---

## What's in v1.2 (this version)

- **Flip Persistence Filter** — three modes (Off / Strict / Adaptive). Strict requires a 2-bar close hold beyond the new stop; Adaptive requires the flip-bar close to clear the prior stop by ≥ N × ATR (default 0.5×). Reduces wick-flip whiplash at HTF transitions. Default = Off (preserves v1.1 behavior).
- **Session-Opening Signal Filter** — suppresses Trend and Major flips during the first N bars of each intraday session (default 3 bars). Overnight gap bars contaminate ATR and produce spurious flips at the open. Affects intraday TFs only; ignored on daily/weekly. Default = Off.
- **Conviction-Strength Labels** — optional small label next to Trend and Major signals showing the bias score at firing time. Four modes (Auto / Minimal / Verbose / Off). Auto mode adapts size to chart TF and hides on ≤2-min charts where signals cluster densely. Drawing objects only — no plot-slot cost.
- **HTF Alignment Ribbon** — compact 4-cell horizontal strip showing the bull/bear state of every timeframe. Auto-places opposite the dashboard. Drawing object — no plot-slot cost.
- **Alert system reorganized** — the alert dialog now exposes the 10 most actionable conditions. All other event notifications fire automatically via `alert()` blocks. Set up an alert with condition **"Any alert() function call"** on this script to receive every event.

---

## Originality / what makes this different from existing public scripts

There are many volatility-stop indicators on TradingView, and several multi-timeframe wrappers. AVS MTF differs in three specific ways:

1. **Independent ER adaptation per timeframe.** Most MTF wrappers compute a single ER on the chart TF and apply the same multiplier across timeframes. AVS MTF runs a separate ER calculation on each tier so adaptation is mathematically correct at every timeframe — the 15× TF doesn't get the chart TF's noise-window applied to it.
2. **Proportional Hawkes suppression integrated with the bias-score gate.** The Hawkes lift is added directly to the score-floor used by the signal-firing logic. This is not a binary "block signals during high volatility" filter — the suppression scales smoothly with measured volatility-cluster intensity.
3. **Asset-class-aware data integrity.** Auto-detects Equity / Futures / Index / FX / Crypto and adjusts which validation checks apply (e.g., the volume filter is auto-disabled on volumeless instruments like spot indices, where it would silently mis-fire).

---

## Settings worth knowing

- **Adaptive Mode** = "Both" (default): adapts both ATR period AND multiplier from ER. Set to "Off" for fixed-parameter behavior comparable to a classic volatility stop.
- **Fast/Slow ATR Bounds**: the range across which ER adaptation moves the ATR period. Wider = more dramatic adaptation.
- **Hawkes Max Score Lift**: how aggressive the volatility-cluster suppression is. Default 2.0 = at peak intensity, a signal needing |score| > 2 will need |score| > 4. Set to 0 to disable suppression while keeping the badge descriptive.
- **Flip Persistence Filter** (v1.2): Off / Strict / Adaptive. Use Strict on slow trending markets, Adaptive on faster-moving instruments.
- **Session-Opening Filter** (v1.2): Off by default. Turn on for markets with strong open-bar volatility (NSE, NYSE, etc.).
- **Conviction Labels** (v1.2): Auto by default. Adapts to chart TF automatically.
- **Calibration Panel**: OFF by default. Turn on to see past hit rates with Wilson 95% CIs.

---

## Important disclaimer

This indicator is provided for **educational and informational purposes only**. It does NOT constitute financial, investment, trading, or any other form of advice.

- Past performance of any signal does not guarantee future results.
- The calibration panel reports descriptive past-only outcomes using a fixed evaluation rule. It is NOT a backtest, NOT a forward prediction, and does NOT account for transaction costs, slippage, or execution.
- All trading involves substantial risk of loss.
- Use proper risk management including position sizing and stop-loss orders.
- The author is not a licensed financial advisor. Consult a qualified professional before making any financial decisions.

---

## License

Released under the Mozilla Public License 2.0 (TradingView default open-source license).

---

## References

- Perry Kaufman — *Trading Systems and Methods* (Efficiency Ratio + KAMA framework)
- Alan Hawkes (1971) — *Spectra of some self-exciting and mutually exciting point processes*
- Edwin B. Wilson (1927) — *Probable inference, the law of succession, and statistical inference* (Wilson score interval)

Open-source — feedback, forks, and improvement suggestions welcome via the script comments.

Nota Keluaran
// ───────────────── CHANGELOG / UPGRADE NOTES (v1.2 → v1.3) ──────────────
// v1.3 is a VISUAL / USABILITY upgrade only. The signal engine, the bias
// score, the Hawkes filter, the data-integrity layer, the calibration
// tracker, all alerts and all data-window exports are UNCHANGED from v1.2 —
// signals fire on exactly the same conditions, so existing alerts keep
// working as-is. What changed on screen:
// • ADAPTIVE PANEL THEME — the dashboard and calibration panel read the
// chart background (chart.bg_color) and recolor for maximum contrast on
// any background (dark / light / sepia / custom). A manual "Panel Theme"
// override (Auto / Force Dark / Force Light) handles gradient or image
// backgrounds. Score, regime, momentum, convergence and health colors
// switch to dark-saturated variants on light charts so nothing washes out.
// • SINGLE UNIFIED VERTICAL DASHBOARD — the former separate Dashboard, HTF
// Ribbon and Legend tables are folded into ONE vertical table with zebra
// striping, a colored 4-tier timeframe block (the built-in alignment
// ribbon), the full stats stack, the health row, and an optional in-panel
// legend. Sections still toggle via the existing show_* inputs.
// • TIERED GREEN / RED BANDS — band fills now encode DIRECTION by hue
// (green = bull, red = bear) and TIMEFRAME TIER by depth (Chart = lightest
// → 5×/15× = deepest), replacing the old per-tier multi-hue scheme. Fills
// are a touch richer by default (band transparency 82 → 67) and adapt to a
// light background. The vstop lines and edge labels follow the same hues.
// • DEFAULTS — pullback markers and the all-HTF-aligned markers now display
// by default; background bias shading is now OFF by default for a cleaner
// chart. All remain user-toggleable.
Nota Keluaran
UPDATE — Adaptive Volatility Stop MTF (v1.4)
============================================

This update makes the stop engine anticipatory and the indicator usable on any
market. Existing alerts keep working.

NEW · Path-Dependent Volatility scaling (optional)
--------------------------------------------------
Each timeframe tier's stop DISTANCE is now multiplied by a factor read from the
recent return path — activity clustering, leverage (recent down-moves widen the
stop), and upside convexity (strong up-moves widen it a touch). The effect: stops
PRE-EXPAND going into volatility and re-tighten as it calms, instead of reacting
only after Average True Range catches up.

• This is the first signal-affecting change since v1.1 — while enabled, stop
distances (and therefore flip timing) can differ from the previous version.
• Fully reversible: set the Path-Dependent Vol module Enable = OFF (or Influence
Weight = 0) and every stop, band, signal and alert is identical to before —
the factor collapses to x1.00.
• A new "VOL FCST" dashboard row and an EXP_PDV_Multiplier data-window export
show the live factor ( ">1 expanding" / "<1 calming" ).

NEW · Price Source input (works on any symbol, any market)
----------------------------------------------------------
A "Price Source" setting now drives the engine on every tier. Default close;
choose hl2 / hlc3 / ohlc4 for smoother stops, or any other indicator's output to
drive it off a custom series. True Range for the ATR is always taken from OHLC,
so the tool stays robust on stocks, futures, FX, crypto and indices.

HOUSEKEEPING
------------
• Terminology generalised to universal technical terms throughout (no behaviour
change to any signal).
• To stay within plot limits, two niche data-window exports were retired
(15x direction — visible from the 15x line; cluster lift — shown in the
HEALTH tooltip). BiasScore, 15x VStop, Convergence and the new PDV multiplier
remain exported.

The bias score, the volatility-cluster filter, the data-integrity layer and the
calibration tracker (which keeps its own independent ATR yardstick) are
otherwise unchanged.

For educational and informational purposes only. Not financial advice. Past
performance does not guarantee future results. Manage your risk.

Penafian

Maklumat dan penerbitan adalah tidak bertujuan, dan tidak membentuk, nasihat atau cadangan kewangan, pelaburan, dagangan atau jenis lain yang diberikan atau disahkan oleh TradingView. Baca lebih dalam Terma Penggunaan.