OPEN-SOURCE SCRIPT

Experimental Supertrend [CHE]

140
Experimental Supertrend [CHE] — Combines EMA crossovers for trend regime detection with an adaptive ATR-based hull that selects the narrowest band to contain recent highs and lows, minimizing false breaks in varying volatility.

Summary
This indicator overlays a dynamic supertrend boundary around a midline derived from dual EMAs, using EMA crossovers to switch between bullish and bearish regimes. The hull adapts by evaluating multiple ATR periods and selecting the tightest one that fully encloses price action over a specified window, which helps in creating more stable trend lines that hug price without excessive gaps or breaches. Fills between the midline and hull provide visual cues for trend strength, darkening temporarily after regime changes to highlight transitions. Alerts trigger on crossovers, and markers label entry points, making it suitable for trend-following setups where standard supertrends might whipsaw. Overall, it offers robustness through auto-adjustment, reducing sensitivity to noise while maintaining responsiveness to genuine shifts.

Motivation: Why this design?
Standard supertrend indicators often flip prematurely in choppy markets due to fixed multipliers that do not account for localized volatility patterns, leading to frequent false signals and eroded confidence in trends. This design addresses that by incorporating an EMA-based regime filter for directional bias and an auto-adaptive hull that dynamically tunes the band width based on recent price containment needs. By prioritizing the narrowest effective enclosure, it avoids over-wide bands in calm periods that cause lag or under-wide ones in volatility spikes that invite breaks, providing a more consistent trailing reference without manual tweaking.

What’s different vs. standard approaches?
- Reference baseline: Diverges from the classic ATR-multiplier supertrend, which uses a single fixed period and constant factor applied to close or high/low deviations.
- Architecture differences:
- Auto-selection from candidate ATR lengths to find the optimal period for current conditions.
- Dynamic multiplier clamped between floor and cap values, adjusted by padding to ensure reliable containment.
- Regime-gated rendering, where hull position flips based on EMA relative positioning.
- Post-transition visual fading to emphasize change points without altering core logic.
- Practical effect: Charts show tighter, more reactive bands that rarely breach during trends, reducing visual clutter from flips; the adaptive nature means less intervention across assets, as the hull self-adjusts to volatility clusters rather than applying a one-size-fits-all scale.

How it works (technical)
The indicator first computes two EMAs from close prices using lengths derived from a preset pair or manual inputs, establishing a midline as their average. This midline serves as the central reference for the hull. True range values are then smoothed into multiple ATR candidates using exponential weighting over the specified lengths. For each candidate, deviations of recent highs and lows from the midline are ratioed against the ATR to determine a required multiplier that would enclose all extremes in the containment window—the highest ratio plus padding sets the base, clamped to user-defined bounds. Among valid candidates (those with sufficient history), the one yielding the narrowest overall band width is selected. The hull boundaries are then offset from the midline by this multiplier times the chosen ATR, and further smoothed with a fixed EMA to reduce jitter. Regime direction from EMA comparison gates which boundary acts as support or resistance, with initialization seeding arrays on the first bar to handle state persistence. No higher timeframe data is used, so all logic runs on the chart's native bars without lookahead.

Parameter Guide

EMA Pair — Selects preset lengths for fast and slow EMAs, influencing regime sensitivity and midline stability. Default: "21/55". Trade-offs/Tips: Faster pairs like "9/21" increase cross frequency for scalping but raise false signals; slower like "50/200" smooths for swings, potentially missing early turns. Use Manual for fine control.

Manual Fast — Sets fast EMA length when Manual mode is active; shorter values make regime switches quicker. Default: 21. Trade-offs/Tips: Lower than 10 risks over-reactivity; pair with slow at least double for clear separation.

Manual Slow — Sets slow EMA length when Manual mode is active; longer values anchor the midline more firmly. Default: 55. Trade-offs/Tips: Above 100 adds lag in trends; balance with fast to avoid perpetual neutrality.

ATR Lengths (comma-separated) — Defines candidate periods for ATR smoothing; more options allow finer auto-selection. Default: "7,10,14,21,28,35". Trade-offs/Tips: Fewer candidates speed computation but may miss optimal fits; keep under 10 for efficiency.

Containment Window — Number of recent bars the hull must fully enclose highs/lows of; larger windows favor stability. Default: 50. Trade-offs/Tips: Shorter (under 20) adapts faster to breaks but increases breach risk; longer smooths but delays response.

Min Multiplier Floor — Lowest allowed multiplier for hull width; prevents overly tight bands in low volatility. Default: 0.5. Trade-offs/Tips: Raise to 0.75 for conservative enclosures; too low allows pinches that flip easily.

Max Multiplier Cap — Highest allowed multiplier; caps expansion in spikes to avoid wide, lagging bands. Default: 1.0. Trade-offs/Tips: Lower to 0.75 tightens overall; higher permits more room but risks detachment from price.

Padding (+) — Adds buffer to the auto-multiplier for safer containment without exact touches. Default: 0.05. Trade-offs/Tips: Increase to 0.10 in gappy markets; minimal values hug closer but may still breach on outliers.

Fill Between (Mid ↔ Supertrend) — Toggles shaded area between midline and active hull for trend visualization. Default: true. Trade-offs/Tips: Disable for cleaner charts; pairs well with transparency tweaks.

Base Fill Transparency (0..100) — Sets default opacity of fills; higher values make them subtler. Default: 80. Trade-offs/Tips: Under 50 overwhelms price action; adjust with darken boost for emphasis.

Darken on Trend Change — Enables temporary opacity increase after regime shifts to spotlight transitions. Default: true. Trade-offs/Tips: Off for steady visuals; on aids spotting reversals in real-time.

Darken Fade Bars — Duration in bars for the darken effect to ramp back to base; longer prolongs highlight. Default: 8. Trade-offs/Tips: Shorter (4-6) for fast-paced charts; longer holds attention on changes.

Darken Boost at Change (Δ transp) — Intensity of opacity reduction at crossover; higher values make shifts more prominent. Default: 50. Trade-offs/Tips: Cap at 70 to avoid blackout; tune down if fades obscure details.

Show Supertrend Line — Displays the active hull boundary as a line. Default: true. Trade-offs/Tips: Hide for fill-only views; linewidth fixed at 3 for visibility.

Show EMA Cross Markers — Places circles and labels at crossover points for entry cues. Default: true. Trade-offs/Tips: Disable in clutter; labels show "Buy"/"Sell" at absolute positions.

Alert: EMA Cross Up (Long) — Triggers notification on bullish crossover. Default: true. Trade-offs/Tips: Pair with filters; once-per-bar frequency.

Alert: EMA Cross Down (Short) — Triggers notification on bearish crossover. Default: true. Trade-offs/Tips: Use for exits; ensure broker integration.

Show Debug — Reveals internal diagnostics like selected ATR details (if implemented). Default: false. Trade-offs/Tips: Enable for troubleshooting selections; minimal overhead.

Reading & Interpretation
Bullish regime shows a green line below price as support, with upward fill from midline; bearish uses red line above as resistance, downward fill. Crossovers flip the active boundary, marked by tiny green/red circles and "Buy"/"Sell" labels at the hull level. Fills start at base transparency but darken sharply at changes, fading over the specified bars to signal fresh momentum. If the hull rarely breaches during trends, containment is effective; frequent touches without flips indicate tight adaptation. Debug mode (when enabled) overlays text or plots for selected length and multiplier, helping verify auto-choices.

Practical Workflows & Combinations
- Trend following: Enter long on green "Buy" label above prior low structure; confirm with higher high. Trail stops along the green hull line, tightening as fills stabilize post-fade.
- Exits/Stops: Conservative exit on opposite crossover or hull breach; aggressive hold until fade completes if volume supports. Use darken boost as a volatility cue—high delta suggests waiting for confirmation.
- Multi-asset/Multi-TF: Defaults suit forex/stocks on 15m-4h; for crypto, widen containment to 75 for gaps. Layer on volume oscillator for cross filters; avoid on low-liquidity assets where ATR candidates skew.

Behavior, Constraints & Performance
Closed-bar logic ensures signals confirm at bar end, with live bars updating hull adaptively but no repaints since no future data or security calls are used. Arrays persist ATR states across bars, initialized once with candidates parsed from string. Small fixed loops (over 6 lengths max, inner up to 50) run per bar, capped by max_bars_back=500 for history needs. Resources stay low with 500 labels/lines limits, but dense charts may hit on markers. Known limits include initial lag until containment history builds (50+ bars), potential wide bands on gaps, and suboptimal selections if candidates omit ideal lengths.

Sensible Defaults & Quick Tuning
Start with "21/55" pair, 50-window, 0.5-1.0 multipliers, and 80% transparency for balanced responsiveness on daily charts. For too many flips, raise min floor to 0.75 or add lengths like "42"; for sluggishness, shorten window to 30 or pick faster pair. In high-vol environments, boost padding to 0.10; for smoother visuals, extend fade bars to 12.

What this indicator is—and isn’t
This is a visualization and signal layer for trend regime and adaptive boundaries, aiding entry/exit timing in directional markets. It is not a standalone system—pair with price structure, risk sizing, and broader context. Not predictive of turns, just reactive to containment and crosses.

Disclaimer

The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.

Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.

By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.

Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.

Happy trading

Chervolino

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.