STRAT Trap & VWAP Engine [WillyAlgoTrader]📊 STRAT Trap & VWAP Engine is an overlay toolkit that reads every candle through the lens of The STRAT methodology, detects failed-breakout "trap" candles, and turns them into fully managed trade plans — entry, structural stop, three R-multiple targets, break-even automation and webhook alerts — filtered by a volatility regime engine and accompanied by a pivot-anchored VWAP trail.
The core insight: the most information-dense candle on any chart is the one that breaks a prior extreme and then closes against its own break. The market went hunting for liquidity, found it, and failed to follow through. This indicator classifies every bar the STRAT way, catches exactly those divergence candles, and manages the resulting trade for you — while a regime filter keeps you out of chop and an anchored VWAP shows where the volume-weighted crowd is positioned inside the current trend leg.
Works on all markets (crypto, forex, stocks, indices, futures) and all timeframes.
📚 THE STRAT IN 60 SECONDS (for beginners)
The STRAT is a price-action methodology popularized by veteran floor trader Rob Smith. Its power is its simplicity: every candle on every chart is one of only three types, defined purely by its relationship to the previous candle's range:
— 1 (Inside bar) : the candle's entire range fits inside the previous candle (high <= prior high AND low >= prior low). The market is in equilibrium — nobody won.
— 2 (Directional bar) : the candle breaks ONE side of the previous candle. 2U breaks the prior high only; 2D breaks the prior low only. One side won.
— 3 (Outside bar) : the candle breaks BOTH sides (high > prior high AND low < prior low). Maximum disagreement — both sides were swept.
Sequences of these numbers form repeatable patterns. A 2D-2U is a reversal (sellers pushed down, buyers answered). A 2-1-2 is a pause-and-go. A 3-1-2 is compression after chaos resolving into direction. Because the classification is purely mechanical, there is zero subjectivity — two traders looking at the same chart will always count the same sequence.
The second pillar of The STRAT is Full Timeframe Continuity (FTC) : checking whether the higher timeframes (hourly, daily, weekly, monthly) are all trading in the same direction as your entry. When the 15-minute, hourly and daily candles are all green, a long is swimming with the current, not against it.
This indicator automates all of it — and then adds the twist that gives it its name.
🧩 WHY THESE COMPONENTS WORK TOGETHER
A STRAT pattern tells you a structure formed — but not whether the breakout that follows is genuine. A trap detector spots failed breakouts — but without structural context it fires in the middle of chop. A regime filter knows trend from range — but generates no entries by itself. A VWAP shows positioning — but a session VWAP resets at midnight regardless of what the trend is doing. None of these alone produces a complete, managed trade.
Bar classification → pattern matrix → trigger FSM → trap detection → regime + volume + FTC filters → trade engine (SL/TP1-3/BE) → anchored VWAP context
The classifier turns raw candles into STRAT numbers. The pattern matrix scans the sequence for tradeable combinations and arms a setup with exact trigger and stop levels. The trigger FSM waits for a confirmed break — or the Trap engine fires instead when a candle breaks an extreme and closes against it. Every prospective entry then passes through three independent gates (PVTE regime, volume confirmation, FTC alignment) before the trade engine takes over: structural stop, three R-multiple targets, automatic break-even, and a webhook alert at every stage. The anchored VWAP restarts at each confirmed structural pivot inside the regime, showing the volume-weighted average of the current leg — the reference institutional participants care about.
Remove any link and the chain breaks: patterns without triggers are just decoration; traps without a regime filter fade every wiggle; a trade engine without structural stops places arbitrary lines; a VWAP without pivot anchoring measures the wrong leg.
🔍 WHAT MAKES IT ORIGINAL
1️⃣ Mechanical STRAT classifier with a data-driven pattern matrix.
Every bar is classified exhaustively:
— Inside (1): high <= high and low >= low
— Outside (3): high > high and low < low
— 2U: high > high and low >= low
— 2D: low < low and high <= high
Patterns are not hardcoded if-chains — they live in a priority-ordered matrix scanned longest-first, so a 2-2-2 continuation (Extended mode) outranks the 2-2 it contains, and overlapping patterns resolve deterministically. Core set: 2-2 Rev/Cont, 3-2, 3-2-2, 2-1-2 Rev/Cont, 3-1-2, 1-2-2 RevStrat. Extended (opt-in): 2-2-2, 2-2-2-2 "Randy Jackson", 1-bar 3 RevStrat (outside bar closing beyond the prior bar's range).
2️⃣ Three-stage trigger FSM: SETUP → PENDING → TRIGGERED.
When a pattern completes on a confirmed close, the engine arms: trigger = the final pattern bar's high (bull) or low (bear), stop = the opposite side. A wick break of the trigger level on a later confirmed bar fires TRIGGERED. An adverse CLOSE beyond the stop side invalidates. No break within Setup Expiry bars (default 3) expires the setup. On an outside bar that pierces both sides, the adverse close wins — the conservative read, because the intrabar touch order is unknowable.
3️⃣ Trap Bar entry engine — the headline feature (default mode).
A trap bar is a candle whose body color contradicts its STRAT direction:
— Red 2U : broke the prior high, closed below its open → buyers were trapped above the break → SHORT
— Green 2D : swept the prior low, closed above its open → sellers were trapped below → LONG
Entry = trap bar close; stop = beyond the sweep extreme (the trap bar's own high/low) + 0.25×ATR buffer, with a 0.5×ATR minimum distance always enforced. Dojis (close == open) never qualify. Three Entry Modes: Trap Bar (default), STRAT Trigger (classic breakout entries), Both — where a trap candle on a trigger bar overrides the trigger's direction, because the failed breakout IS the trade.
4️⃣ Structural stop anchoring, four modes.
For trigger entries the SL Anchor input chooses: Trigger Level (default — just beyond the broken high/low; price trading back through the broken level means the breakout failed), Setup Bar (opposite side of the setup bar — wider, fully structural), Wick-Anchored (beyond the entry bar's own wick), or ATR (close ± SL Multiplier × ATR). All structural modes use:
stop_long = min(anchor − 0.25×ATR, close − 0.5×ATR)
which simultaneously applies the buffer and guarantees the minimum distance. A Max Risk cap (default 3×ATR, 0 = off) skips entries whose structural risk is too wide — outside-bar setups are the usual offenders.
5️⃣ Full trade management with honest intrabar accounting.
TP1/TP2/TP3 are R-multiples of the actual entry→stop distance (Risk Presets: Conservative 1R/2R/4R with 2.5×ATR stop, Balanced 1R/2R/3R, Aggressive, Scalping, or Custom). After TP1 is touched the stop moves to entry ( break-even ) — and a BE moved on a bar cannot stop that same bar out (the SL check uses the bar-start stop). When SL and a first TP1/TP3 touch land on the same bar, the TP registers and blocks the SL — an optimistic intrabar model, disclosed openly : the true touch order inside one bar is unknowable without tick data. A trade closes only at TP3, SL, or a BE stop-out. Win = TP1 was touched.
6️⃣ PVTE Regime Filter — two-threshold hysteresis, ON by default.
A 3-state regime engine (BULL / BEAR / NEUTRAL) built on a selectable basis kernel (EMA default, DEMA, HMA, KAMA; length 21) and ATR bands (length 100):
outer band = basis ± ATR × 3.0
inner band = basis ± ATR × (3.0 − 1)
Regime is entered on a confirmed close through an outer band and exits to NEUTRAL only on a close through the OPPOSITE inner band — the two-threshold gap kills flip-flopping in chop. Longs pass only in BULL, shorts only in BEAR; NEUTRAL blocks both by default (Allow mode available). Every entry — trap or trigger — must pass this gate, which converts the naturally counter-trend trap fade into a trend-continuation tool: only sweeps AGAINST the regime get faded, in the regime's direction.
7️⃣ Pivot-anchored VWAP trail.
Inside an active regime, the VWAP anchors at each confirmed structural pivot (Pivot Length 13 bars each side) in the regime direction, backfills from the pivot bar in one pass, then accumulates incrementally:
aVWAP = Σ(price × volume) / Σ(volume), from the anchor bar
It re-anchors on every new in-regime pivot and hard-resets on regime change — so the dotted trail always represents the current leg's volume-weighted average, not a stale session artifact. Pivot confirmation is honest lag: the swing is only KNOWN Pivot Length bars after it forms; the trail is drawn from the confirmed pivot forward. Delayed confirmation, not repainting.
8️⃣ FTC strip and FTC Alignment filter.
A top-center strip shows every timeframe above your chart (15m → Quarter): green/red for the current higher-TF candle direction, with ·I / ·O flags when that candle is inside/outside its predecessor. The optional Min FTC Aligned filter (default 0 = off) requires N visible higher timeframes to agree with your entry direction. Honesty note, stated in the tooltip as well: continuity is a live-state concept, so the strip and this filter read the FORMING higher-TF candles — the only reload-unstable element in the indicator; everything else is confirmed-close based.
9️⃣ Volume confirmation gate.
Optional filter requiring entry-bar volume > SMA20 × threshold (default 1.2), automatically bypassed on instruments without volume data. Applies to both entry sources.
🔟 Bot-grade alert architecture.
Every event emits a structured JSON webhook (or human-readable text): setup_bull/bear, trigger_bull/bear, trap_long/short, be, tp1_hit, tp2_hit, tp3_close, sl_hit. Entry payloads carry pattern, price, entry, sl, tp1-3, the PVTE regime (−1/0/1) and a compact FTC string like "1H+4H+D-W+". Closure payloads carry the result (win/loss) and a be_stop flag — built from pre-reset snapshots so same-bar event collisions can never produce NaN fields. Alerts follow a fixed intrabar chronology (management → closures → entries → setups) and five category toggles let a bot mute any stream it doesn't act on. Nine static alertcondition entries cover the TV alert dialog.
⚙️ HOW IT WORKS — CALCULATION FLOW
Step 1 — Classify: On every bar the STRAT type (1 / 2U / 2D / 3) is computed and, on confirmed close, appended to the sequence.
Step 2 — Match: The pattern matrix scans the sequence newest-first, longest patterns first; the first match arms a setup with trigger/stop at the final pattern bar's extremes.
Step 3 — Resolve: A pending setup is checked each confirmed bar: adverse close → invalidated; wick break of the trigger → TRIGGERED; expiry (default 3 bars) → expired. Setup lines freeze and dim on any resolution.
Step 4 — Detect traps: Independently, every confirmed bar is tested for the trap condition (2U closing red / 2D closing green).
Step 5 — Filter: The prospective entry (trap first in Both mode) must pass PVTE regime, volume and FTC gates, then the Max Risk cap.
Step 6 — Open & manage: Entry at close; SL/TP1-3 computed; each later confirmed bar checks TP touches (TP priority), moves BE after TP1, and closes on TP3/SL/BE stop-out. Lines project forward, extend while active, persist after close as a record, and recolor teal on TP hits.
Step 7 — Track context: The PVTE regime FSM updates on closes; the anchored VWAP accumulates, re-anchors on new pivots, resets on regime change.
Step 8 — Report: Dashboard sections refresh (sequence, setup state, trade, session stats), and the alert engine emits events in fixed chronological order.
📖 HOW TO USE
🎯 Quick start:
1. Add the indicator to a clean chart. Defaults are ready to observe: Trap Bar entries, PVTE filter ON, regime bands and anchored VWAP visible.
2. Watch the numbers under the candles: 1 = pause, 2 = direction, 3 = sweep of both sides. This alone teaches you The STRAT faster than any book.
3. Wait for a LONG · Trap 2D or SHORT · Trap 2U label — the indicator found a failed break aligned with the regime and opened a managed plan.
4. Follow the plan on the chart: dotted entry line, solid red stop, dashed green targets. Watch TP1 turn teal and the entry label switch to "→ SL (BE)".
5. Once comfortable, create ONE TradingView alert with condition "Any alert() function call" and paste your webhook URL — every event now reaches your phone or bot in JSON.
👁️ Reading the chart:
— Numbers 1/2/3 under bars = STRAT types (amber, green/red, magenta)
— 🟢 LONG · / 🔴 SHORT · labels = trade entries with the source pattern; the tooltip shows entry, SL, TP1-3 and risk
— ▲ / ▼ labels = STRAT triggers that did NOT open a trade (engine busy or filtered) — still valid signals for manual traders
— Solid/dotted horizontal pairs after a pattern = pending trigger (colored) and stop (muted); they dim if invalidated or expired
— Small triangles = hammer (below) / shooter (above), wick-dominant candles by the Actionable Wick fraction (default 0.75)
— Colored bands = PVTE regime envelope; dotted trail = anchored VWAP of the current leg
— Dashed horizontal levels = previous Day/Week/Month high/low with price tags (lookahead-safe)
— Top-center strip = Full Timeframe Continuity at a glance
📊 Dashboard fields:
— Seq: the last four confirmed STRAT types, oldest left
— Setup: pending pattern, direction and bars-waited/expiry — or "idle"
— Levels: the pending trigger (T) and stop (S) prices
— Candle: Hammer / Shooter / Inside on the current bar (informational)
— PVTE: current regime — BULL / BEAR / NEUTRAL / Off
— Trade section: entry, stop (with "BE @" after break-even), TP1-3 with ✓ marks, R:R at TP1, stop distance in %
— Stats section: trades, wins, losses, win rate with gauge, and the ▰▱ form strip of the last 10 — for the selected period (24H / 30D / All-Time)
🔧 Tuning guide:
— Too few trades: switch In NEUTRAL Regime to Allow, or set Entry Mode to Both, or raise Max Risk
— Too many shallow trades in chop: keep NEUTRAL = Block, raise the PVTE ATR Multiplier (wider regime bands), or add Min FTC Aligned = 2
— Stops feel too tight: change SL Anchor to Setup Bar (structural, wider) — targets scale with the wider risk automatically
— Stopped out by noise at breakeven: that is the cost of the BE rule; disable Break-Even After TP1 if you prefer to let trades breathe
— Chart too busy: Setup Labels, Trigger Labels and bar coloring are already off by default; Regime Bands and the VWAP trail have their own toggles
— Learning mode: turn Setup Labels and Trigger Labels ON and Trade Engine OFF — the chart becomes a pure STRAT trainer
⚙️ KEY SETTINGS
🎨 Appearance: Theme (Auto/Dark/Light — the palette adapts, signals stay readable on white and black), watermark, bar coloring (off), bar numbers (on), Signal Label Size.
📐 Pattern Engine: Extended Patterns (off), Setup Labels (off), Max Pattern Drawings (60, FIFO).
🎯 Trigger Engine: Setup Expiry (3 bars), Trigger/Stop Lines (on), Trigger Labels (off).
🛡️ Risk Management: Trade Engine (on), Entry Mode (Trap Bar), Risk Preset (Balanced), SL Anchor (Trigger Level), SL Buffer (0.25×ATR), ATR Length (14), TP1/2/3 multipliers (Custom preset), Max Risk (3×ATR), Break-Even After TP1 (on), line styles, label toggles, % distance on labels.
🔍 Filters: Volume Confirmation (off, ×1.2 SMA20), Min FTC Aligned (0 = off).
🌊 PVTE Regime Filter: filter toggle (on), Basis Kernel (EMA), Basis Length (21), ATR Length (100), ATR Multiplier (3.0), NEUTRAL behavior (Block), Regime Bands (on), Anchored VWAP (on), VWAP Pivot Length (13), VWAP Source (Close).
🕯️ Actionable Candles: hammer/shooter marks (on), Min Wick Fraction (0.75).
📊 Dashboard: position, size (Small-Huge), Market/Trade/Stats section toggles, Win Rate Period.
🔔 Alerts: master Enable, JSON/Text format, five category toggles (Entries, TP/BE, SL, Filtered Triggers, Setups).
🔔 ALERTS
— 🟢 trigger_bull / trap_long — entry with pattern, price, entry, sl, tp1-3, regime, ftc
— 🔴 trigger_bear / trap_short — mirrored short payload
— 🎯 tp1_hit / tp2_hit — target touches with level and entry
— 🛡️ be — stop moved to break-even
— 🏆 tp3_close — final target, result "win"
— 🛑 sl_hit — stop-out with be_stop flag and win/loss result
— 📐 setup_bull / setup_bear — a pattern armed with its trigger/stop levels
— Plain trigger alerts for signals that did not open a trade (filters/engine busy)
All fire on confirmed bar close. One alert covers everything: condition "Any alert() function call". Nine static alertcondition entries are also available in the TV dialog.
⚠️ IMPORTANT NOTES
— 🚫 No repainting of signals. Classification is fixed on bar close; all setups, triggers, traps, entries and closures are evaluated on barstate.isconfirmed only; pivots for the VWAP anchor use equal left/right lookback (delayed confirmation, drawn forward from the confirmed bar). One disclosed exception by design: the FTC strip and the optional FTC Alignment filter read the FORMING higher-timeframe candles, because timeframe continuity is a live-state concept — an entry allowed live can look filtered after a reload. That filter is OFF by default.
— 📐 Optimistic intrabar model. When SL and a first TP touch share one bar, the TP is credited (TP priority). Session statistics use this model and the "win = TP1 touched" definition; they reset on chart reload and are NOT a backtest — no commissions, slippage or position sizing.
— ⚖️ Trap entries are regime-gated fades. With the PVTE filter off, the trap engine will fade every divergence candle, including mid-range noise. The default configuration (NEUTRAL = Block) is intentional.
— 🛠️ This is an analysis tool, not an automated bot. It provides classification, signals, trade plans and alerts — trade decisions remain yours.
— 🌐 Works on all markets and timeframes. Instruments without volume data: the VWAP falls back to the price source and the volume filter bypasses automatically.
— 📚 The STRAT is a public price-action methodology popularized by Rob Smith. This is an original clean-room implementation: no third-party code is reused, and the pattern engine, trap logic, trade management and regime integration are built from scratch as described above.
Chỉ báo






















