OPEN-SOURCE SCRIPT
Обновлено

SmartTrend Pro [WillyAlgoTrader]

26 486
📡 SmartTrend Pro is an overlay indicator built around a custom trend detection algorithm — the Adaptive Volatility Trend Engine (AVTE) — that replaces the standard Supertrend approach with Ehlers Super Smoother filtering and Kaufman adaptive ATR bands. Every trend flip is scored by a multi-factor confluence system (0–100) before becoming a signal. The result is a trend-following tool that adapts to current volatility conditions, filters out low-confidence entries, and provides dynamic TP/SL levels — all with full anti-repaint protection.


🧩 WHY THESE COMPONENTS WORK TOGETHER

A traditional Supertrend uses a simple moving average of True Range to calculate bands. This works in steady markets but produces false signals during volatility spikes and misses early reversals during compression. SmartTrend Pro replaces every component of this pipeline with an adaptive alternative, creating a system where each stage feeds the next:

Ehlers-filtered price → Kaufman-adaptive ATR → Volatility bands → Trend direction → Confluence scoring → Filtered signal → Risk levels

The Ehlers Super Smoother removes high-frequency noise from the price before the trend bands are calculated — this prevents the trend engine from reacting to random wicks. The Kaufman adaptive ATR widens bands when volatility is real (sustained directional movement) and tightens them during choppy, low-efficiency conditions — making the trend change threshold automatically adjust. The confluence scoring system then evaluates each trend flip against five independent market factors before allowing the signal to fire. And the TP/SL system freezes its risk distance at entry (using the ATR at signal time) so targets don't drift as volatility changes post-entry.

No single component here is sufficient on its own. An Ehlers filter without adaptive bands still produces false crossovers. Adaptive bands without scoring still trigger on weak trend flips. Scoring without frozen TP/SL creates drifting targets. The integrated pipeline solves all three problems simultaneously.


🔍 WHAT MAKES IT ORIGINAL

1️⃣ Adaptive Volatility Trend Engine (AVTE) — custom trend algorithm.
The AVTE replaces the standard Supertrend calculation at every stage:

Stage 1 — Price filtering: Instead of using raw price, the AVTE applies an Ehlers 2-pole Super Smoother to the source. The Ehlers filter uses the transfer function:
ss = c1 × (src + src[1]) × 0.5 + c2 × ss[1] + c3 × ss[2]
where c1 = 1 − c2 − c3, c2 = 2a × cos(√2 × π / period), c3 = −a², and a = exp(−√2 × π / period). This produces zero-lag frequency-domain filtering — it removes high-frequency noise without the phase distortion that a simple moving average introduces. The filter period is derived from the ATR period (ATR_period / 2, minimum 3).

Stage 2 — Adaptive volatility measurement: Instead of a fixed-length ATR, the AVTE uses a Kaufman Adaptive ATR. First, a standard ATR(period) is calculated. Then the Kaufman Efficiency Ratio (ER) is computed: ER = |close − close[period]| / sum(|close − close[1]|, period). The ER measures how much net directional movement exists relative to total path traveled — ranging from 0 (pure chop) to 1 (clean trend). The ER then modulates a smoothing constant: sc = (ER × (fast − slow) + slow)², where fast = 2/3 and slow = 2/31. The adaptive ATR blends: aATR = aATR[1] + sc × (rawATR − aATR[1]). In trending conditions (high ER), the adaptive ATR reacts quickly to volatility changes. In choppy conditions (low ER), it smooths aggressively, preventing false band expansions.

Stage 3 — Band calculation and trend direction: Upper band = filtered_price + sensitivity × adaptive_ATR. Lower band = filtered_price − sensitivity × adaptive_ATR. Bands ratchet in the trend direction: the lower band can only rise (never fall) during uptrends, the upper band can only fall during downtrends. When close crosses above the upper band, trend flips bullish. When close crosses below the lower band, trend flips bearish. The trend line follows the lower band in uptrends, upper band in downtrends (step-line visualization).

The Sensitivity parameter (default 2.5) controls how far the bands sit from filtered price. Lower = tighter bands, more signals, faster reaction. Higher = wider bands, fewer signals, smoother.

2️⃣ Multi-confluence scoring system (0–100).
Every AVTE trend flip is evaluated against five independent market factors before becoming a signal:

Factor 1 — EMA alignment (±15 pts): Checks whether close > EMA(50) > EMA(200) for bullish alignment, or close < EMA(50) < EMA(200) for bearish. Full alignment = +15 (bull) or −15 (bear). No alignment = 0. This confirms the trend flip aligns with the broader trend structure.

Factor 2 — RSI position (±10 pts): RSI(14) between 50–70 = +10 (bullish momentum without overextension). RSI 30–50 = −10 (bearish). Extremes (>70 or <30) score 0 — avoiding signals at overbought/oversold levels where reversals are more likely.

Factor 3 — MACD histogram direction (±12 pts): MACD(12,26,9) histogram > 0 and rising = +12 (accelerating bullish momentum). Histogram < 0 and falling = −12 (accelerating bearish). This captures momentum acceleration, not just direction.

Factor 4 — Volume confirmation (0–8 pts): Volume > 20-period SMA × 1.2 = +8. This confirms institutional participation. Auto-disabled on instruments without volume data (forex).

Factor 5 — ADX strength (0–10 pts): ADX(14) > 25 = +10, ADX > 20 = +5. Confirms the market is trending, not ranging.

The base score starts at 50. Bullish factors add, bearish factors subtract. Final score is clamped to 0–100. A buy signal fires when the AVTE flips bullish AND score ≥ Min Signal Score (default 55). A sell signal fires when AVTE flips bearish AND score ≤ (100 − Min Signal Score), creating symmetric thresholds around 50. Signals with score ≥ 75 (buy) or ≤ 25 (sell) are classified as "Strong" and receive a distinct label.

3️⃣ Ehlers Super Smoother trend cloud.
A dual-band cloud system using two Ehlers Super Smoothers at different periods. The fast period depends on the Cloud Style setting:
— Adaptive: auto-adjusts between 13 and 55 based on current volatility — calculated as 34 × (1 + stdev(close, 20) / adaptive_ATR × 0.5)
— Fast: fixed at 21 (tight cloud for scalping)
— Smooth: fixed at 55 (wide cloud for swing)
— Minimal: fixed at 34 (single line, no fill)
The slow period = fast period × 2.618 (golden ratio). Cloud is bullish when fast > slow (green fill), bearish when fast < slow (red fill). The AVTE step-line is overlaid on the cloud for immediate trend-direction clarity. An optional trend tracer (EMA, default 233-period) provides institutional-level long-term bias.

4️⃣ Four-preset system with parameter scaling.
Presets modify three core parameters simultaneously using multipliers:
— Conservative: sensitivity × 1.4, ATR period × 1.3, min score floor 70 — fewer but higher-quality signals, for swing trading
— Balanced: no modification — default parameters, good for 15M–4H
— Aggressive: sensitivity × 0.7, ATR period × 0.8, min score ceiling 45 — more signals, faster entries
— Scalping: sensitivity × 0.5, ATR period × 0.6, min score ceiling 40 — optimized for 1–5M, tightest bands
Each preset adjusts the effective sensitivity, ATR length, and minimum score threshold proportionally, so one selection adapts the entire signal pipeline rather than requiring manual tuning of individual parameters.

5️⃣ Dynamic TP/SL with frozen risk distance.
Three stop-loss modes:
— ATR: SL distance = adaptive ATR × configurable multiplier (default 1.5×)
— Percentage: SL distance = fixed percentage of entry price
— Structure: SL distance = half the recent swing range (highest high − lowest low over swing lookback)
TP levels are calculated as multiples of SL distance: TP1 = SL × 1.5 (default), TP2 = SL × 2.5, TP3 = SL × 4.0. The SL distance is frozen at entry — once a signal fires, the risk distance is locked and does not change with subsequent volatility. This prevents TP/SL levels from drifting as ATR changes post-entry. TP hit markers (×) appear on the chart as each level is reached. An optional Chandelier Exit trailing stop follows price using the ATR multiplier, ratcheting in the profit direction.

6️⃣ Pullback signals within established trends.
In addition to trend-flip signals, the indicator detects pullback entries within an existing trend:
— Bullish pullback: AVTE trend is bullish (no flip), price retraces to EMA(pullback_sensitivity × 3), RSI(pullback_sensitivity) drops below 35 then starts rising — catching the bounce off trend support
— Bearish pullback: AVTE trend is bearish, price rallies to EMA, RSI exceeds 65 then starts falling
Pullback signals appear as small circles (distinct from the main Buy/Sell labels), providing additional entries within a confirmed trend direction. They are bar-close confirmed and warmup-protected.

7️⃣ Volatility gauge with statistical normalization.
The dashboard displays a real-time volatility reading (0–100%) calculated as: gauge = (ATR(10) − (SMA(ATR, 20) − StDev(ATR, 20))) / (2 × StDev(ATR, 20)) × 100, clamped to 0–100. This measures where current volatility sits relative to its recent statistical distribution: > 70% = High (above 1 standard deviation), 40–70% = Medium, < 40% = Low. This helps you assess whether the current environment suits your strategy: high volatility favors wider stops and fewer signals, low volatility favors tighter approaches.

8️⃣ Multi-timeframe trend panel (non-repainting).
The dashboard includes an MTF panel showing trend direction on 5M, 15M, 1H, 4H, and 1D — using close[1] > EMA(200)[1] with lookahead_on for guaranteed non-repainting. When most timeframes align in one direction, trend-flip signals in that direction have higher confluence.

9️⃣ Session detection.
The dashboard shows the current active trading session: Tokyo, London, New York, Sydney, or overlaps (London/New York, Tokyo/London). Sessions are calculated using UTC-based time windows. This helps you contextualize volatility: London/New York overlap is typically the highest-volume period, while off-hours have thinner liquidity.

🔟 Four optional filters.
Each filter can be independently toggled:
— Trend filter: only signals aligned with the Ehlers cloud direction
— Volume filter: only signals with volume EMA(10) > EMA(25) — auto-disabled for instruments without volume
— ADX filter: only signals when ADX > 20 (trending market)
— Momentum filter: only signals with MACD histogram aligned (positive + rising for buys, negative + falling for sells)
All filters default to Off — enabling them progressively reduces signal frequency while increasing average quality.


⚙️ HOW IT WORKS — CALCULATION FLOW

Step 1 — Ehlers filtering: Source price is passed through the 2-pole Super Smoother with period = max(round(ATR_period / 2), 3). This removes intrabar noise while preserving trend structure.

Step 2 — Adaptive ATR: Kaufman Efficiency Ratio is calculated over the ATR period. The ER modulates the smoothing speed of ATR: trending conditions → fast adaptation, choppy conditions → slow adaptation.

Step 3 — Band construction: Upper = filtered_price + sensitivity × adaptive_ATR. Lower = filtered_price − sensitivity × adaptive_ATR. Bands ratchet: lower band can only rise in uptrends, upper band can only fall in downtrends.

Step 4 — Trend detection: Close above upper band → bullish. Close below lower band → bearish. The trend line is the active band (lower in uptrends, upper in downtrends).

Step 5 — Confluence scoring: On every bar, five factors are evaluated and combined into a 0–100 score. On a trend flip bar, the score determines whether the signal qualifies.

Step 6 — Filter gate: If any enabled filter disagrees, the signal is suppressed.

Step 7 — Signal emission: Buy or Sell label appears on the confirmed bar. Score ≥ 75 / ≤ 25 → "Strong Buy/Sell".

Step 8 — TP/SL placement: Risk distance is calculated and frozen. TP1/TP2/TP3 are placed as R:R multiples. Labels persist on the right side of the chart. Hit markers appear as each level is reached.


📖 HOW TO USE

🎯 Quick start:
1. Select a preset matching your style: Scalping (1–5M), Balanced (15M–4H), Conservative (4H–1D)
2. Add the indicator to your chart — the AVTE trend line and cloud appear immediately
3. Wait for a Buy or Sell label — the score next to it tells you the confluence quality
4. Check the dashboard: trend direction, score, market state (trending/ranging), volatility, session
5. TP/SL levels appear automatically — manage the trade using the marked levels

👁️ Reading the chart:
— 🟩 Green cloud fill = bullish trend (Ehlers fast > slow)
— 🟥 Red cloud fill = bearish trend
— Step-line on the cloud = AVTE trend boundary (the level that must break for a trend flip)
— 🟢 "Buy" / "Strong Buy" label below bar = confirmed bullish signal
— 🔴 "Sell" / "Strong Sell" label above bar = confirmed bearish signal
— 🟢 Small circle below bar = pullback buy (trend continuation entry)
— 🔴 Small circle above bar = pullback sell
— Orange line = entry price | Red line = stop loss | Green lines = TP1/TP2/TP3
— × markers = TP hit confirmations
— HH/HL/LH/LL labels (optional) = market structure swing points

📊 Dashboard fields:
— Trend: current AVTE direction (Bullish/Bearish)
— Signal: last confirmed signal (Buy/Sell/Wait)
— Score: current confluence score (0–100)
— Market: ADX-based state (Trending > 25 / Ranging > 20 / No Trend)
— Volatility: statistical gauge (High/Medium/Low with percentage)
— Session: current active session (Tokyo/London/New York/Sydney/overlaps)
— MTF Panel: 5M/15M/1H/4H/1D trend direction (close vs 200 EMA)

🔧 Tuning guide:
— Too many signals: increase Min Score, enable filters, switch to Conservative preset
— Too few signals: decrease Min Score, switch to Aggressive/Scalping, lower Sensitivity
— Signals too late: lower Sensitivity (tighter bands), use Fast cloud style
— Too many false signals: enable ADX filter (filters ranging markets), increase Min Score to 65+
— Scalping 1–5M: use Scalping preset, ATR mode SL with multiplier 1.0–1.5, TP1 R:R 1.0–1.5
— Swing 4H–1D: use Conservative preset, ATR mode SL with multiplier 2.0–3.0, TP3 R:R 5.0+


⚙️ KEY SETTINGS REFERENCE

⚙️ Main:
— Trend Sensitivity (default 2.5): AVTE band distance — lower = more signals, higher = fewer
— ATR Period (default 21): volatility measurement lookback
— Preset (default Balanced): Conservative / Balanced / Aggressive / Scalping

📡 Signal Tuning:
— Min Signal Score (default 55): minimum confluence to trigger signals
— Strong Signals Only (default Off): only show score ≥ 75
— Show Pullback Signals (default On): trend continuation entries
— Pullback Sensitivity (default 8): retracement detection lookback

☁️ Trend Cloud:
— Cloud Style (default Adaptive): Adaptive / Fast / Smooth / Minimal
— Trend Tracer (default Off): long-term EMA bias line (default 233)

🔍 Filters (all default Off):
— Trend Filter (cloud alignment) / Volume Filter / ADX Filter / Momentum Filter

🛡️ Risk Management:
— SL Mode (default ATR): ATR / Percentage / Structure
— SL ATR Multiplier (default 1.5×) / SL Percentage (default 1.0%)
— TP1/TP2/TP3 Risk:Reward (default 1.5 / 2.5 / 4.0)
— Trailing Stop (default Off): Chandelier Exit method
— Market Structure (default Off): HH/HL/LH/LL swing labels

🎨 Visual:
— Auto / Dark / Light theme
— Bar coloring: Trend Gradient / Signal Based / Momentum / None
— Background trend shading (default Off)

📊 Dashboard:
— Position, font size, MTF panel toggle


🔔 Alerts

— 🟢 Buy / Strong Buy — ticker, price, timeframe, score
— 🔴 Sell / Strong Sell — same fields
— 🎯 TP1 / TP2 / TP3 Hit — ticker, price
— 🛑 SL Hit — ticker, price
— ☁️ Cloud Cross Bullish / Bearish — ticker, timeframe
All alerts support plain text and JSON webhook format. Bar-close confirmed.


⚠️ IMPORTANT NOTES

— 🚫 No repainting. All signals require barstate.isconfirmed. TP/SL distances are frozen at entry and do not change retroactively. MTF data uses [1] + lookahead_on for non-repainting HTF values. A warmup period (minimum 200 bars or 3× ATR period) prevents signals during insufficient data.
— 📐 The AVTE is not a standard Supertrend. It replaces every component: Ehlers Super Smoother instead of raw price, Kaufman adaptive ATR instead of fixed ATR, ratcheting bands instead of simple ±ATR. The mathematics are described in detail above.
— ⚖️ The confluence score is not a win-rate predictor. A score of 75 means five independent market factors align strongly — it measures confluence quality, not outcome probability. Use it to prioritize, not to guarantee.
— 📊 The scoring system uses standard indicators (EMA, RSI, MACD, Volume, ADX) as confluence factors, not as independent signal generators. None of these indicators alone triggers a signal — they only contribute to the score that gates an AVTE trend flip.
— 🔧 Presets modify parameters proportionally. After selecting a preset, you can still adjust individual settings — the preset sets the starting point, your adjustments override it.
— 📏 TP/SL levels are frozen at entry. The SL distance calculated at the signal bar persists until the next signal — it does not drift with changing ATR. This is by design for consistent risk management.
— 🔄 Pullback signals are continuation entries, not reversal signals. They only appear within an established AVTE trend and require RSI reversion from oversold/overbought — catching bounces off trend support/resistance.
— 🛠️ This is a signal and analysis tool, not an automated trading bot. It generates signals, scores them, and visualizes TP/SL — trade decisions remain yours.
— 🌐 Works on all markets and timeframes. Volume filter auto-disables on instruments without volume data.
Информация о релизе
What's new in v1.1.0:
Bug fixes:

Fixed symmetric momentum scoring — sell signals were previously suppressed because several scoring factors only added points (bullish bias) but never subtracted. Volume and ADX factors now contribute symmetrically: volume surge on a down-move subtracts points, low volume on an up-move subtracts points, ADX with bearish DI alignment subtracts points. Buy threshold ≥ minScore, sell threshold ≤ (100 − minScore)
Fixed SL hit now properly resets position state — previously, after a stop-loss was triggered, TP lines remained visible and phantom TP hits could register on subsequent bars. Position is now marked inactive on SL hit, and all TP/SL visuals disappear
Fixed swing structure comparison — HH/HL/LH/LL labels were comparing against the previous bar's swing value instead of the actual previous swing point. Now stores prevSwingHigh/prevSwingLow separately before updating, so comparisons reflect real market structure
Fixed pullback signals now respect all active filters — previously, pullback entries fired regardless of whether Volume, ADX, Trend, or Momentum filters were enabled. They now pass through the same filter stack as main signals

New features:

Bar coloring fully implemented — was a dead input in v1.0.0 (commented out). Three modes now active: Trend Gradient (colors bars by momentum score from green through yellow to red), Signal Based (green after buy, red after sell), Momentum (highlights high-momentum bars where MACD histogram exceeds previous by 20%+)
SL hit visual marker — new ✗ label appears on the chart when stop-loss is triggered, matching the TP hit ✓ markers
Improved adaptive cloud length — now uses ATR as percentage of price (normalized volatility) instead of raw ATR/adaptive ATR ratio, producing more consistent cloud behavior across different price scales

Optimizations:

Eliminated duplicate EMA, ATR, MACD, ADX, volume, and RSI calculations — shared indicator bank computed once and reused across scoring engine, filters, cloud, and pullback detection
Risk management lines now only display while position is active — no more lingering TP/SL lines after trade closes

Отказ от ответственности

Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.