Dynamic Swing VWAP [WillyAlgoTrader]📊 Dynamic Swing VWAP is an overlay indicator that anchors a volume-weighted average price (VWAP) to each swing pivot — restarting the calculation every time the market structure changes direction. Unlike session-based VWAP (which resets at midnight) or fixed-anchor VWAP (which you drag manually), this VWAP automatically re-anchors to every swing high or swing low detected by the built-in pivot engine, producing a segmented VWAP line where each segment represents the volume-weighted fair value of the current trend leg. The VWAP is computed using an Exponential Weighted Moving Average (EWMA) with configurable tracking speed that can adapt to ATR-based volatility — plus deviation bands using EWMA-smoothed ATR and full market structure labeling (HH/HL/LH/LL).
The core insight: a VWAP anchored to the start of the current swing leg tells you the average price at which volume traded since the trend began — this is where institutional positions are concentrated for this specific move. Price above the swing VWAP = the move is in profit for participants who entered at the start of the leg. Price below = the move is underwater. Each new swing resets the context, keeping the VWAP relevant to the current market structure.
🧩 WHY THESE COMPONENTS WORK TOGETHER
Session VWAP tells you the average price for today — but a trend that started three days ago doesn't care about today's session boundary. Fixed-anchor VWAP lets you pick a start point but requires manual adjustment. And standard VWAP has no concept of market structure — it doesn't know when a swing reversal invalidated the previous leg.
This indicator solves all three problems:
Swing detection → Structure classification (HH/HL/LH/LL) → VWAP anchor at pivot → EWMA VWAP with adaptive tracking → ATR deviation bands → Trend direction coloring
The swing detector identifies alternating highs and lows from price action. Each new swing is classified by its relationship to the previous swing of the same type (Higher High, Lower Low, etc.). On each qualifying swing, the VWAP resets and begins accumulating from the pivot bar — so the VWAP always represents the current leg's volume-weighted average. The EWMA tracking speed controls how responsive the VWAP is to new price/volume data. And the ATR bands show where price is extended relative to the VWAP within the current leg.
Without swing anchoring, the VWAP drifts from stale reference points. Without structure classification, you don't know if the current swing is trend-continuing (HH/HL) or reversing (LH/LL). Without EWMA tracking, the VWAP would be a rigid cumulative calculation that can't adapt to changing conditions. Without bands, you can't gauge how extended the move is relative to fair value.
🔍 WHAT MAKES IT ORIGINAL
1️⃣ EWMA-based VWAP with half-life tracking.
Instead of the standard cumulative VWAP (which weights every bar equally since the anchor), this indicator uses an Exponential Weighted Moving Average approach:
alpha = 1 − exp(−ln(2) / APT)
Where APT (Adaptive Price Tracking) is the configurable half-life in bars. This means: a bar that is APT bars old has exactly half the weight of the current bar. The EWMA updates:
P = (1 − alpha) × P + alpha × (source × volume)
V = (1 − alpha) × V + alpha × volume
VWAP = P / V
This produces a VWAP that naturally decays the influence of older bars — recent volume-weighted prices matter more. With APT=21 (default), a bar from 21 bars ago has half the weight of the current bar, and a bar from 42 bars ago has one-quarter.
The key advantage over cumulative VWAP: after 200 bars, a cumulative VWAP barely moves — every new bar is 1/200th of the total. The EWMA VWAP continues to track price meaningfully because old data decays.
2️⃣ ATR-adaptive tracking speed.
When "Adapt APT by ATR Ratio" is enabled, the tracking speed automatically adjusts based on current vs average volatility:
adjustedAPT = baseAPT / (atrRatio ^ volatilityBias)
Where atrRatio = ATR(50) / RMA(ATR, 50). When volatility spikes (ratio > 1), APT decreases → VWAP tracks price faster (captures the volatile move). When volatility contracts (ratio < 1), APT increases → VWAP smooths out (avoids overreacting to noise). The volatility bias parameter (default 10.0) controls the sensitivity — higher values produce more dramatic speed changes.
The adjusted APT is clamped to to prevent extreme behavior.
3️⃣ Swing-anchored segment reset with backfill.
When a new swing is detected, the VWAP doesn't just reset on the current bar — it backfills from the actual pivot bar to the present. This is critical because pivots are detected with a delay (the swing high/low is only confirmed after prdInput bars have passed). Without backfill, the VWAP would start from the current bar instead of the actual swing point.
The backfill process:
— Seed the EWMA at the pivot bar with the source price and volume at that bar
— Walk forward bar by bar from the pivot to the current bar
— Apply the EWMA update at each step
— Optionally ramp the alpha (smooth re-anchor) to reduce initial jitter
This produces a VWAP line that appears to start exactly at the swing point — even though the detection happened later.
4️⃣ Smooth re-anchor with alpha ramping.
When enabled (default), the first 5 bars after a new anchor use a ramped alpha: rampFactor = 0.5 + 0.5 × barsFromSeed/5. This starts at 50% of the full alpha and ramps to 100% over 5 bars. The effect: the VWAP doesn't jerk to the new price immediately but smoothly transitions from the seed — reducing visual noise at segment boundaries.
5️⃣ Volume spike capping.
When enabled (default), individual bar volumes are capped at 3× SMA(volume, 20). This prevents a single extreme volume bar (block trade, liquidation cascade, exchange glitch) from disproportionately pulling the VWAP. On crypto and small-cap stocks where volume spikes of 10–50× average are common, this produces a much more stable VWAP.
Additionally, zero-volume bars (some instruments report 0 on certain bars) are replaced with the 50-bar median volume — preventing division-by-zero and maintaining continuity.
6️⃣ Market structure labels (HH/HL/LH/LL/EH/EL).
Each swing is classified by comparing it to the previous swing of the same type:
— HH (Higher High): current swing high > previous swing high — bullish continuation
— HL (Higher Low): current swing low > previous swing low — bullish structure
— LH (Lower High): current swing high < previous — bearish pressure
— LL (Lower Low): current swing low < previous — bearish continuation
— EH (Equal High): same level as previous high — potential double top
— EL (Equal Low): same level as previous low — potential double bottom
— IH/IL (Initial): first swing detected (no previous to compare)
These labels are placed at the actual swing bar position (not the detection bar), providing accurate structure mapping.
7️⃣ LL/HH-only anchor filter.
When "Only LL/HH Anchors" is enabled, the VWAP only resets on Lower-Low and Higher-High swings — the strongest continuation signals. HL and LH swings still get labels (for visual structure reference) but don't reset the VWAP segment. This produces longer, smoother VWAP segments that only restart on major trend-confirming swings.
8️⃣ EWMA ATR deviation bands.
The bands use the same EWMA smoothing applied to ATR values (not a separate calculation):
ewmaATR = (1 − alpha) × ewmaATR + alpha × ATR
Upper band = VWAP + ewmaATR × bandMultiplier
Lower band = VWAP − ewmaATR × bandMultiplier
The band multiplier defaults to 0.618 (Fibonacci golden ratio). The bands are rendered as a filled polyline contour — upper points forward, lower points backward, forming a closed polygon. The fill color matches the trend direction (green for bullish, red for bearish) with configurable transparency.
9️⃣ Polyline rendering for clean visual output.
The VWAP line and bands use Pine Script's polyline type — not plot(). Each segment is a separate polyline object drawn from the pivot bar to the current bar. On segment reset, the old polyline is finalized (frozen on chart) and a new one begins. This produces clean, non-overlapping segments with distinct colors per direction — something that plot() cannot achieve without workarounds.
⚙️ HOW IT WORKS — CALCULATION FLOW
Step 1 — Swing detection: ta.highestbars/ta.lowestbars with configurable period. When the highest bar = current bar → swing high. When lowest = current bar → swing low. Direction tracks which was more recent.
Step 2 — Structure classification: Each new swing is compared to the previous swing of the same type → HH/HL/LH/LL/EH/EL label.
Step 3 — Anchor decision: If LL/HH filter is off, every swing anchors. If on, only LL and HH (plus initial) anchor. Non-anchoring swings still get labels.
Step 4 — VWAP reset + backfill: Seed EWMA at pivot bar. Walk forward applying EWMA update at each bar with alpha from half-life. Optional smooth ramp over first 5 bars.
Step 5 — Normal bar update: Each new bar: compute alpha from APT (optionally ATR-adapted), update EWMA P and V, compute VWAP = P/V, push point to polyline, update band contour.
Step 6 — Segment visualization: Old segment finalized as frozen polyline. New segment drawn live. Bands rendered as filled contour polygon.
📖 HOW TO USE
🎯 Quick start:
1. Add the indicator — colored VWAP segments appear, anchored to each swing
2. Green line = bullish leg VWAP, red = bearish leg VWAP
3. HH/HL/LH/LL labels show market structure at each pivot
4. Price above VWAP = current leg is in profit, below = underwater
👁️ Reading the chart:
— 🟢 Green VWAP line = bullish swing leg (anchored from swing low)
— 🔴 Red VWAP line = bearish swing leg (anchored from swing high)
— 🟢🔴 Filled bands = deviation from VWAP (brighter = more volatile)
— HH / HL labels = bullish structure (trend up)
— LH / LL labels = bearish structure (trend down)
— EH / EL labels = equal level (potential reversal zone)
— Price crosses VWAP from below → bullish (reclaiming fair value)
— Price crosses VWAP from above → bearish (losing fair value)
🔧 Tuning guide:
— VWAP too smooth (lagging): decrease APT (10–15), or enable ATR adaptation
— VWAP too noisy: increase APT (30–50), enable Smooth Re-Anchor
— Too many segments (choppy): increase Swing Period (40–80), or enable LL/HH Only mode
— Bands too tight: increase Band Multiplier (1.0–1.618)
— Bands too wide: decrease Band Multiplier (0.382–0.5)
— Volume spikes distorting: enable Cap Volume Spikes (default on)
⚙️ KEY SETTINGS REFERENCE
⚙️ Main:
— Swing Period (default 55): lookback for pivot detection — larger = bigger swings
— Adaptive Price Tracking (default 21): EWMA half-life in bars — lower = faster tracking
— Adapt APT by ATR Ratio (default Off): auto-adjust speed by volatility
— Volatility Bias (default 10.0): ATR adaptation sensitivity
— Cap Volume Spikes (default On): limit extreme bars to 3× average
— Smooth Re-Anchor (default On): gradual alpha ramp on new segments
— Only LL/HH Anchors (default Off): reset VWAP only on continuation swings
📐 Bands:
— Band Multiplier (default 0.618): ATR × this value for band width
— Band Fill Transparency (default 90): fill opacity
🎨 Visual:
— Swing labels, trend background (all toggleable)
— Line width configurable (1–5)
— Auto / Dark / Light theme
🔔 Alerts
— 🟢 BULLISH / 🔴 BEARISH — trend direction change with swing label (HH/LL/etc.), ticker, price, timeframe
All support plain text and JSON webhook format. Bar-close confirmed.
⚠️ IMPORTANT NOTES
— 🚫 No repainting. Alerts require barstate.isconfirmed. Swing pivots are confirmed with equal left/right lookback — the actual swing point is in the past by swingPeriod bars. The VWAP backfills from the confirmed pivot bar to the present, so the line appears at the correct location — this is backfill computation, not repainting of future values.
— 📐 The EWMA VWAP is not the same as standard cumulative VWAP . Standard VWAP weights every bar equally since the anchor. EWMA VWAP applies exponential decay — recent bars dominate, old bars fade. This makes the VWAP continue to track price meaningfully even after hundreds of bars, while cumulative VWAP would barely move.
— 📊 The half-life parameter (APT) means a bar APT bars ago has exactly half the weight of the current bar. APT=21 → 21 bars ago = 50% weight, 42 bars ago = 25% weight, 63 bars ago = 12.5% weight.
— ⚖️ Volume spike capping at 3× SMA(20) prevents single anomalous bars from hijacking the VWAP. Zero-volume bars are replaced with the 50-bar median. Both features ensure VWAP stability on instruments with unreliable volume data.
— 🔄 The LL/HH filter mode produces longer VWAP segments because HL and LH swings don't reset the calculation. The VWAP continues accumulating through counter-trend pullbacks, only resetting on trend-confirming swings.
— 📏 The polyline contour for bands is rebuilt every bar (old polyline deleted, new one created). Arrays are capped at 2000 points to prevent memory overflow on very long segments.
— 🛠️ This is a volume-weighted trend analysis tool , not a signal generator. It shows where volume-weighted fair value sits for the current swing leg, how extended price is from that fair value, and what the market structure looks like — trade decisions remain yours.
— 🌐 Works on all markets and timeframes. Volume features auto-adapt to instruments with zero or unreliable volume data.
Wskaźnik Pine Script®














