OPEN-SOURCE SCRIPT
Liquidity Trail Matrix [WillyAlgoTrader]

📊 Liquidity Trail Matrix (LTM) is an overlay trend-following system that combines a four-band proportional ATR trailing stack, a 5-factor retest quality score (0–100), a non-repainting higher-timeframe bias filter, a range-distributed volume profile of the current trend segment (POC / Value Area / HVN / LVN), and a full trade engine with wick-anchored stops, three R-multiple targets, break-even automation and honest session statistics — all in one indicator.
The core insight: a single trailing stop line gives you a binary answer — "in trend" or "flipped". But price interacts with the liquidity zone around the trail in layers: shallow pullbacks, deep sweeps, and full reversals all look different. LTM replaces the single line with a graded four-band matrix, scores every pullback-and-reclaim by depth, candle quality, volume, higher-timeframe alignment and trend maturity, and overlays where volume actually accumulated during the current trend leg — so you can see whether a retest is landing on real acceptance (HVN / POC) or falling into a volume vacuum (LVN).
Works on all markets (crypto, forex, stocks, indices, commodities) and all timeframes. On zero-volume symbols the profile automatically switches to a range-weighted proxy.
🧩 WHY THESE COMPONENTS WORK TOGETHER
A trailing stop alone tells you the trend direction but nothing about entry quality — every touch of the line looks the same. A volume profile alone shows you where volume traded but has no concept of trend regime or entry timing. A retest signal alone fires on any bounce, whether it happens in a mature trend with higher-timeframe support or in the dying bars of an exhausted move. Used separately, these tools leave you guessing.
LTM chains them into one pipeline:
ATR band stack → trend flip detection → pullback depth measurement → 5-factor quality scoring → HTF bias confirmation → trade engine (entry / SL / TP / BE) → segment volume profile context → session outcome tracking
The band stack defines the trend and, critically, grades how deep each pullback penetrates (Band 1 = shallow, Band 4 = extreme). That depth becomes the largest single component of the retest score. The score is then adjusted by the reclaim candle's close location, relative volume, trend age, and the higher-timeframe EMA-50 bias — five independent dimensions that a plain trailing stop cannot see. Every confirmed signal is handed to the trade engine, which places a structure-aware stop, three risk-multiple targets and manages break-even. Meanwhile the volume profile is rebuilt from the exact flip bar of the current trend, so POC, Value Area and LVN levels always describe this leg — telling you whether your entry sits on volume acceptance or in a vacuum. Finally, every closed trade feeds the on-chart statistics, so the dashboard shows how this exact configuration has behaved on this exact chart.
Remove any link and the chain breaks: without band depth there is no meaningful score; without the score every bounce is a signal; without the segment-anchored profile the volume context is stale; without the trade engine the signals have no defined risk; without stats you never learn whether the settings fit the instrument.
🔍 WHAT MAKES IT ORIGINAL
1️⃣ Proportional four-band trail geometry — spacing that scales with width.
Most multi-line trails use fixed offsets (base, base+1, base+2 ATR). LTM computes every band as a proportion of the base multiplier:
Band K distance = base × (1 + K_offset × step), giving four multipliers:
— m1 = base
— m2 = base × (1 + step)
— m3 = base × (1 + 2 × step)
— m4 = base × (1 + 3 × step)
With the default Balanced preset (base 4.0, step 0.25) that yields 4.0 / 5.0 / 6.0 / 7.0 ATR. Because spacing is proportional, the geometry of the stack stays visually and behaviorally consistent whether you run tight Scalping bands (2.5 × ATR, step 0.20) or wide Deep Trend bands (6.0 × ATR, step 0.30). Each band ratchets independently (max-lock in uptrends, min-lock in downtrends) and never loosens.
Why this matters: fixed +1/+2/+3 offsets make the stack proportionally "fat" at small base values and "thin" at large ones — proportional spacing keeps pullback depth grading meaningful at any width.
2️⃣ Selectable flip depth — you choose which band defines a reversal.
The trend flips only when price closes beyond a user-chosen band from the previous bar: Fast (Band 2), Balanced (Band 3, default) or Deep (Band 4). Comparing against the previous bar's band value prevents same-bar feedback between the flip and the band update. A warm-up guard (max(3 × ATR length, 60) bars) suppresses all signals until the ATR stack is statistically stable.
Why this matters: flip sensitivity becomes an explicit, single-purpose setting instead of an accidental side effect of band width.
3️⃣ 5-factor retest quality score (0–100) — every signal explains itself.
When price touches any band and then reclaims Band 1 with a directional candle inside the retest window (default 8 bars), LTM computes:
— 📐 Pullback depth (max 25): Band 2 touch = 25, Band 3 = 18, Band 1 = 15, Band 4 = 10. The maximum touched depth during the pending window is used. Note the deliberate non-linearity: Band 2 scores highest — deep enough to reset liquidity, not deep enough to threaten the trend. Band 4 sweeps score lowest because they often precede full reversals.
— 🕯️ Reclaim candle (max 20): close location value CLV = (close − low) / (high − low) for longs (mirrored for shorts). CLV > 0.7 → 20 points, > 0.5 → 12, else 5. A reclaim that closes near its extreme shows commitment.
— 📊 Volume (max 20): current volume vs. the previous bar's 20-period SMA — the spike must not dampen itself by inflating its own average. Volume > 1.2 × baseline → 20, > 1.0 × → 12, else 5. Symbols without volume data receive a neutral 12.
— 🧭 HTF bias (max 20): aligned with the higher-timeframe EMA-50 direction → 20, no HTF data → 10, against bias → 0.
— ⏳ Trend age (max 15): 10–150 bars into the trend → 15 (mature, established), under 10 bars → 8 (unproven), over 150 → 5 (aging).
Signals print only when the total meets the Min Retest Score (default 80) and the shared anti-whipsaw cooldown (default 5 bars, deliberately shared across both directions) has elapsed. Every diamond label shows the score, and its tooltip breaks down all five components — no black-box signals.
4️⃣ Non-repainting higher-timeframe bias.
HTF bias compares the higher timeframe's previous closed bar close against its EMA-50, requested with confirmed-bar indexing so the value never changes retroactively. Bias is a soft score component (0/10/20 points), not a hard filter — counter-bias signals can still print if the other four factors are strong enough.
5️⃣ Segment volume profile — range-distributed, anchored to the live trend leg.
The profile is rebuilt on the last bar from the exact flip bar of the current trend (capped by Max Profile Bars, default 500) — no arbitrary lookback padding. Accumulation is range-distributed: each bar's volume is split across every price bin its high–low range overlaps, weighted by overlap fraction:
bin_volume += bar_volume × overlap(bin, bar_range) / (bar_high − bar_low)
This shows where volume actually traded, not where bars happened to close. From the histogram LTM derives:
— 🟡 POC — the highest-volume bin of the segment, drawn with price and volume label. The strongest magnet / defense level of this leg.
— 📦 Value Area (70%) — expanded symmetrically from POC by always adding the larger neighboring bin until 70% of segment volume is enclosed. VAH / VAL edges act as dynamic S/R.
— 📈 HVN — local volume peaks ≥ 0.55 × POC volume (configurable): acceptance shelves where price tends to stall.
— 🕳️ LVN — local troughs ≤ 0.30 × POC volume inside the Value Area (configurable): volume vacuums that price tends to travel through quickly. Each LVN is labeled and feeds a dedicated break alert.
On symbols with no volume feed (forex, some CFDs) the engine substitutes a true-range proxy per bar, so the profile stays structurally meaningful instead of failing.
6️⃣ Trade engine with strict signal-trade parity.
Every confirmed signal (scored retest or trend flip) acts, with unambiguous rules:
— flat → open a position in the signal direction
— opposite position → reverse (close and enter the new direction on the same bar)
— same-direction position → ignored (no pyramiding, no stop tampering)
There are exactly four closure paths: SL hit, break-even stop-out, TP3 touch, or reversal by an opposite signal. Hit detection uses three safety guards: an entry-bar guard (SL/TP are never evaluated on the entry bar itself), a pessimistic same-bar rule (if a bar touches both SL and a TP, the SL wins — statistics never get the benefit of the doubt), and a break-even latency rule (a stop moved to break-even mid-bar cannot trigger on that same bar — the engine checks against the bar-start stop value).
7️⃣ Wick-anchored stop-loss mode.
Two SL modes at entry:
— Wick-Anchored (default): SL = signal bar's wick extreme ± 0.25 × ATR buffer, with a minimum distance of 0.5 × ATR enforced. The stop hides behind the structure that produced the signal instead of floating at an arbitrary distance.
— ATR: classic fixed SL Multiplier × ATR from entry.
TP1 / TP2 / TP3 are pure risk multiples of the actual SL distance (defaults 1R / 2R / 3R), so the reward structure automatically adapts to how much room the stop needed. Four risk presets (Conservative 2.5 × ATR SL, TP 1/2/4R; Balanced 1.5, TP 1/2/3R; Aggressive 1.0, TP 1.5/2.5/4R; Scalping 0.8, TP 0.8/1.5/2R) plus full Custom control. Optional break-even moves the stop to entry after TP1.
8️⃣ Honest session statistics with a fixed win definition.
A closed trade counts as a win only if TP1 was touched before closure — including break-even stop-outs after TP1 (you banked at least 1R or protected the position). Everything else is a loss, including reversals that never reached TP1. The dashboard shows closed trades, W/L, win rate with a ▰▱ gauge, and a "Form" strip of the last 10 outcomes. Stats are session-scoped and reset on chart reload — this is transparent live tracking of the current settings on the current chart, not a backtest report.
9️⃣ Trend P&L tracker and theme-aware visual system.
An optional floating label follows price in real time and shows the directional % move since the current trend flip (a falling bear trend shows positive %), anchored by a dotted baseline at the trend start price. The label turns red when the trend is under water. The entire visual layer — band transparencies, heatmap fills, dashboard, profile, SL/TP palette — has separate Dark and Light calibrations (Auto-detected from the chart background), because bright hues that look right on dark charts wash out on white ones. TP lines recolor to solid teal with a ✓ when touched; the SL line dims and the entry label annotates "→ SL (BE)" when break-even activates. SL/TP lines persist after the trade closes as a visual record until the next entry replaces them.
⚙️ HOW IT WORKS — CALCULATION FLOW
Step 1 — Band geometry: The preset (or Custom inputs) resolves the base multiplier and proportional step; four multipliers m1–m4 are derived and multiplied by ATR (default length 13).
Step 2 — Ratcheting trail: In an uptrend each band only rises (max-lock); in a downtrend only falls (min-lock). On a flip the whole stack re-seeds on the opposite side of price.
Step 3 — Flip detection: A close beyond the previous bar's value of the chosen flip band (2/3/4) reverses the trend state. Flip labels print on confirmed bars after the warm-up period.
Step 4 — Pullback tracking: Any touch of Band 1–4 against the trend arms a pending retest with its maximum depth, valid for the retest window; pendings decay each bar and are voided on a flip.
Step 5 — Reclaim and scoring: A directional close back beyond Band 1 triggers scoring: depth (25) + candle (20) + volume (20) + HTF bias (20) + trend age (15). Score ≥ threshold and cooldown elapsed → confirmed signal on bar close.
Step 6 — Trade engine: The signal opens or reverses a position; SL is placed (wick-anchored or ATR), TP1–TP3 are projected as risk multiples; break-even, TP recolors and the four closure paths are managed bar by bar with pessimistic resolution.
Step 7 — Segment profile: On the last bar the profile is rebuilt from the flip bar: range-distributed accumulation → POC → 70% Value Area expansion → HVN/LVN detection → drawing.
Step 8 — Reporting: The dashboard updates trend state, signal state, profile levels, live trade card and session statistics; alerts fire on bar close in within-bar chronological order (management → closures → reversal → entries → info).
📖 HOW TO USE
🎯 Quick start:
1. Add the indicator to your chart and pick a Band Width Preset: Scalping for 1–15M, Balanced for most timeframes, Deep Trend for D–W position trading.
2. Set the Higher Timeframe Bias one or two steps above your chart (e.g. 1H while trading 15M).
3. Choose a Risk Preset that matches your style, or leave Balanced.
4. Watch the dashboard: Trend + HTF Bias aligned means you only consider signals in that direction with full conviction; the retest diamonds do the timing.
5. After 15–20 closed trades, read the Stats section and tune Min Retest Score up (fewer, cleaner signals) or down (more signals) for your instrument.
👁️ Reading the chart:
— 🟢 / 🔴 Band stack + heatmap = the liquidity trail zone; the deeper the fill, the closer price is to a trend flip.
— ◆ diamond with a number = confirmed scored retest entry (the number is the 0–100 quality score; hover the tooltip for the full component breakdown).
— ▲ / ▼ FLIP = confirmed trend reversal through the chosen flip band.
— Long ▲ / Short ▼ = trade entry taken by the engine on a flip (printed when there is no retest diamond on the same bar, so every entry is visibly marked).
— ENTRY / SL / TP1–TP3 lines = the live trade card; TP lines turn solid teal with ✓ when touched; a dimmed SL with "→ SL (BE)" on the entry label means the stop sits at break-even.
— 🟡 POC line = highest-volume price of the current trend leg; dashed VAH/VAL = Value Area edges; LVN labels = volume vacuums inside the Value Area.
— ▲ +X.XX% floating label (optional) = real-time directional P&L of the current trend since the flip.
📊 Dashboard fields:
— Trend / Age: direction of the band stack and bars since the last flip.
— HTF Bias: higher-timeframe EMA-50 direction (soft score component).
— Signal: current engine position — LONG, SHORT or Wait.
— Last signal: most recent event, its score, and bars elapsed.
— POC / VA High / VA Low: live segment profile levels.
— Entry / SL / TP1–TP3 / R:R / SL Dist %: the open trade card ("BE @" marks a break-even stop; ✓ marks touched targets); collapses to one row when flat.
— Trades / W-L / Win rate / Form: session statistics; ▰ = win, ▱ = loss, newest on the right.
🔧 Tuning guide:
— Too many weak signals: raise Min Retest Score toward 85–90, or increase Signal Cooldown.
— Too few signals: lower Min Retest Score toward 55–65, or widen the Retest Window to 10.
— Whipsaw flips on a choppy symbol: switch Flip Band to Deep (Band 4) or move to the Deep Trend preset.
— Flips lag too far behind on fast moves: Flip Band → Fast (Band 2) or the Scalping preset.
— Stops feel too tight / too wide: switch SL Mode between Wick-Anchored and ATR, or change the Risk Preset; on volatile symbols prefer Conservative.
— Profile looks coarse on long trends: raise Profile Rows to 50+ and Max Profile Bars toward 800.
— Counter-trend retests keep printing: set an explicit Higher Timeframe Bias — counter-bias signals lose 20 points and rarely clear a high threshold.
⚙️ KEY SETTINGS
⚙️ Trend Engine:
— Band Width Preset (default Balanced): Scalping 2.5 × ATR / step 0.20, Balanced 4.0 / 0.25, Deep Trend 6.0 / 0.30, or Custom.
— Base Multiplier (default 5.0) and Band Spacing (default 0.25): manual geometry, active in Custom preset only.
— ATR Length (default 13): lookback for band-width ATR.
— Source (default close): price series for trailing and flips.
— Flip Band (default Balanced / Band 3): which band a close must breach to flip the trend.
— Higher Timeframe Bias (default empty = chart TF): HTF for EMA-50 bias scoring.
🎯 Signals:
— Min Retest Score (default 80): 0–100 quality threshold for retest diamonds.
— Retest Window (default 8 bars): how long a band touch stays armed for a reclaim.
— Signal Cooldown (default 5 bars): minimum spacing between signals, shared across directions.
📦 Volume Profile:
— Show Segment Volume Profile (on), Profile Rows (30), Profile Width (34 bars), Max Profile Bars (500).
— Show POC (on), Show Value Area 70% (on), Show HVN / LVN Levels (on), Profile Label Size (Small).
🛡️ Risk Management:
— Risk Preset (default Balanced): Conservative / Balanced / Aggressive / Scalping / Custom.
— SL Mode (default Wick-Anchored): structure-aware wick stop vs. fixed ATR distance.
— ATR Length (Risk) (14), SL Multiplier (1.5), TP1 / TP2 / TP3 Multipliers (1.0 / 2.0 / 3.0 × risk) — Custom preset.
— Break-Even After TP1 (on): stop moves to entry once TP1 is touched.
— Show SL/TP Lines / Labels / % Distance and per-line style controls (Entry dotted, SL solid, TP dashed by default).
🎨 Visual:
— Theme (Auto / Dark / Light), Show Trail Bands, Show Band Heatmap Fill, Show Retest Signals, Show Flip Labels, Show Trend P&L Tracker (off by default), label size controls, watermark toggle, Bull / Bear color pickers.
📊 Dashboard:
— Show Dashboard (on), position (5 anchors), font size, and independent toggles for the Market, Profile, Trade and Stats sections.
🔧 Advanced:
— HVN Threshold (default 0.55 × POC volume): minimum relative volume for an acceptance node.
— LVN Threshold (default 0.30 × POC volume): maximum relative volume for a vacuum node.
🔔 ALERTS
— 🟢 LONG ENTRY / 🔴 SHORT ENTRY — ticker, timeframe, price, signal score, SL, TP1–TP3, R:R. Plain text or JSON webhook format ({"action":"buy"...}) for bot integrations.
— 🎯 TP1 / TP2 / TP3 HIT — target touches with prices (optional).
— 🛡️ BREAK-EVEN — stop moved to entry after TP1 (optional).
— 🛑 SL HIT / BE STOP-OUT — stop-loss trigger with direction, entry and stop prices; a distinct BE variant when the stop was at break-even.
— 🔄 REVERSAL — position reversed by an opposite signal, with the closed trade's outcome (after / before TP1).
— ▲ / ▼ TREND FLIP — informational flips that did not open or reverse a trade.
— ⚡ LVN BREAK — a close crossing a Low Volume Node of the live segment profile (price entering a volume vacuum often accelerates).
All alerts fire once per bar close. Alerts are ordered by within-bar chronology: trade management → closures → reversal → new entries → informational.
⚠️ IMPORTANT NOTES
— 🚫 No repainting. All signals, entries and alerts are confirmed on bar close (barstate.isconfirmed). The trend flip compares against the previous bar's band value. The HTF bias uses the higher timeframe's previous closed bar, so its value never changes retroactively. A warm-up guard suppresses signals for the first max(3 × ATR length, 60) bars.
— 📐 The segment volume profile is a live construct. It is redrawn on the last bar for the current trend leg and evolves as the leg grows — this is by design (it describes the present segment), and historical profile states are not preserved.
— 📊 Session statistics reset on chart reload. They are transparent live tracking of the current settings on the current symbol and timeframe — not a backtest, and past performance does not guarantee future results.
— ⚖️ Same-bar ambiguity is resolved pessimistically. If one bar touches both a stop and a target, the stop wins in the statistics. Intrabar sequence cannot be known from OHLC data, so the engine never gives itself the benefit of the doubt.
— 🕳️ Zero-volume symbols use a range-weighted proxy for the profile, and the volume score component defaults to a neutral value — profile shapes on such symbols reflect price dwell time, not traded volume.
— 🛠️ This is an analysis and trade-planning tool, not an automated trading bot. It detects trend state, scores retests, projects stops and targets, and tracks outcomes — trade decisions remain yours.
— 🌐 Works on all markets and timeframes.
The core insight: a single trailing stop line gives you a binary answer — "in trend" or "flipped". But price interacts with the liquidity zone around the trail in layers: shallow pullbacks, deep sweeps, and full reversals all look different. LTM replaces the single line with a graded four-band matrix, scores every pullback-and-reclaim by depth, candle quality, volume, higher-timeframe alignment and trend maturity, and overlays where volume actually accumulated during the current trend leg — so you can see whether a retest is landing on real acceptance (HVN / POC) or falling into a volume vacuum (LVN).
Works on all markets (crypto, forex, stocks, indices, commodities) and all timeframes. On zero-volume symbols the profile automatically switches to a range-weighted proxy.
🧩 WHY THESE COMPONENTS WORK TOGETHER
A trailing stop alone tells you the trend direction but nothing about entry quality — every touch of the line looks the same. A volume profile alone shows you where volume traded but has no concept of trend regime or entry timing. A retest signal alone fires on any bounce, whether it happens in a mature trend with higher-timeframe support or in the dying bars of an exhausted move. Used separately, these tools leave you guessing.
LTM chains them into one pipeline:
ATR band stack → trend flip detection → pullback depth measurement → 5-factor quality scoring → HTF bias confirmation → trade engine (entry / SL / TP / BE) → segment volume profile context → session outcome tracking
The band stack defines the trend and, critically, grades how deep each pullback penetrates (Band 1 = shallow, Band 4 = extreme). That depth becomes the largest single component of the retest score. The score is then adjusted by the reclaim candle's close location, relative volume, trend age, and the higher-timeframe EMA-50 bias — five independent dimensions that a plain trailing stop cannot see. Every confirmed signal is handed to the trade engine, which places a structure-aware stop, three risk-multiple targets and manages break-even. Meanwhile the volume profile is rebuilt from the exact flip bar of the current trend, so POC, Value Area and LVN levels always describe this leg — telling you whether your entry sits on volume acceptance or in a vacuum. Finally, every closed trade feeds the on-chart statistics, so the dashboard shows how this exact configuration has behaved on this exact chart.
Remove any link and the chain breaks: without band depth there is no meaningful score; without the score every bounce is a signal; without the segment-anchored profile the volume context is stale; without the trade engine the signals have no defined risk; without stats you never learn whether the settings fit the instrument.
🔍 WHAT MAKES IT ORIGINAL
1️⃣ Proportional four-band trail geometry — spacing that scales with width.
Most multi-line trails use fixed offsets (base, base+1, base+2 ATR). LTM computes every band as a proportion of the base multiplier:
Band K distance = base × (1 + K_offset × step), giving four multipliers:
— m1 = base
— m2 = base × (1 + step)
— m3 = base × (1 + 2 × step)
— m4 = base × (1 + 3 × step)
With the default Balanced preset (base 4.0, step 0.25) that yields 4.0 / 5.0 / 6.0 / 7.0 ATR. Because spacing is proportional, the geometry of the stack stays visually and behaviorally consistent whether you run tight Scalping bands (2.5 × ATR, step 0.20) or wide Deep Trend bands (6.0 × ATR, step 0.30). Each band ratchets independently (max-lock in uptrends, min-lock in downtrends) and never loosens.
Why this matters: fixed +1/+2/+3 offsets make the stack proportionally "fat" at small base values and "thin" at large ones — proportional spacing keeps pullback depth grading meaningful at any width.
2️⃣ Selectable flip depth — you choose which band defines a reversal.
The trend flips only when price closes beyond a user-chosen band from the previous bar: Fast (Band 2), Balanced (Band 3, default) or Deep (Band 4). Comparing against the previous bar's band value prevents same-bar feedback between the flip and the band update. A warm-up guard (max(3 × ATR length, 60) bars) suppresses all signals until the ATR stack is statistically stable.
Why this matters: flip sensitivity becomes an explicit, single-purpose setting instead of an accidental side effect of band width.
3️⃣ 5-factor retest quality score (0–100) — every signal explains itself.
When price touches any band and then reclaims Band 1 with a directional candle inside the retest window (default 8 bars), LTM computes:
— 📐 Pullback depth (max 25): Band 2 touch = 25, Band 3 = 18, Band 1 = 15, Band 4 = 10. The maximum touched depth during the pending window is used. Note the deliberate non-linearity: Band 2 scores highest — deep enough to reset liquidity, not deep enough to threaten the trend. Band 4 sweeps score lowest because they often precede full reversals.
— 🕯️ Reclaim candle (max 20): close location value CLV = (close − low) / (high − low) for longs (mirrored for shorts). CLV > 0.7 → 20 points, > 0.5 → 12, else 5. A reclaim that closes near its extreme shows commitment.
— 📊 Volume (max 20): current volume vs. the previous bar's 20-period SMA — the spike must not dampen itself by inflating its own average. Volume > 1.2 × baseline → 20, > 1.0 × → 12, else 5. Symbols without volume data receive a neutral 12.
— 🧭 HTF bias (max 20): aligned with the higher-timeframe EMA-50 direction → 20, no HTF data → 10, against bias → 0.
— ⏳ Trend age (max 15): 10–150 bars into the trend → 15 (mature, established), under 10 bars → 8 (unproven), over 150 → 5 (aging).
Signals print only when the total meets the Min Retest Score (default 80) and the shared anti-whipsaw cooldown (default 5 bars, deliberately shared across both directions) has elapsed. Every diamond label shows the score, and its tooltip breaks down all five components — no black-box signals.
4️⃣ Non-repainting higher-timeframe bias.
HTF bias compares the higher timeframe's previous closed bar close against its EMA-50, requested with confirmed-bar indexing so the value never changes retroactively. Bias is a soft score component (0/10/20 points), not a hard filter — counter-bias signals can still print if the other four factors are strong enough.
5️⃣ Segment volume profile — range-distributed, anchored to the live trend leg.
The profile is rebuilt on the last bar from the exact flip bar of the current trend (capped by Max Profile Bars, default 500) — no arbitrary lookback padding. Accumulation is range-distributed: each bar's volume is split across every price bin its high–low range overlaps, weighted by overlap fraction:
bin_volume += bar_volume × overlap(bin, bar_range) / (bar_high − bar_low)
This shows where volume actually traded, not where bars happened to close. From the histogram LTM derives:
— 🟡 POC — the highest-volume bin of the segment, drawn with price and volume label. The strongest magnet / defense level of this leg.
— 📦 Value Area (70%) — expanded symmetrically from POC by always adding the larger neighboring bin until 70% of segment volume is enclosed. VAH / VAL edges act as dynamic S/R.
— 📈 HVN — local volume peaks ≥ 0.55 × POC volume (configurable): acceptance shelves where price tends to stall.
— 🕳️ LVN — local troughs ≤ 0.30 × POC volume inside the Value Area (configurable): volume vacuums that price tends to travel through quickly. Each LVN is labeled and feeds a dedicated break alert.
On symbols with no volume feed (forex, some CFDs) the engine substitutes a true-range proxy per bar, so the profile stays structurally meaningful instead of failing.
6️⃣ Trade engine with strict signal-trade parity.
Every confirmed signal (scored retest or trend flip) acts, with unambiguous rules:
— flat → open a position in the signal direction
— opposite position → reverse (close and enter the new direction on the same bar)
— same-direction position → ignored (no pyramiding, no stop tampering)
There are exactly four closure paths: SL hit, break-even stop-out, TP3 touch, or reversal by an opposite signal. Hit detection uses three safety guards: an entry-bar guard (SL/TP are never evaluated on the entry bar itself), a pessimistic same-bar rule (if a bar touches both SL and a TP, the SL wins — statistics never get the benefit of the doubt), and a break-even latency rule (a stop moved to break-even mid-bar cannot trigger on that same bar — the engine checks against the bar-start stop value).
7️⃣ Wick-anchored stop-loss mode.
Two SL modes at entry:
— Wick-Anchored (default): SL = signal bar's wick extreme ± 0.25 × ATR buffer, with a minimum distance of 0.5 × ATR enforced. The stop hides behind the structure that produced the signal instead of floating at an arbitrary distance.
— ATR: classic fixed SL Multiplier × ATR from entry.
TP1 / TP2 / TP3 are pure risk multiples of the actual SL distance (defaults 1R / 2R / 3R), so the reward structure automatically adapts to how much room the stop needed. Four risk presets (Conservative 2.5 × ATR SL, TP 1/2/4R; Balanced 1.5, TP 1/2/3R; Aggressive 1.0, TP 1.5/2.5/4R; Scalping 0.8, TP 0.8/1.5/2R) plus full Custom control. Optional break-even moves the stop to entry after TP1.
8️⃣ Honest session statistics with a fixed win definition.
A closed trade counts as a win only if TP1 was touched before closure — including break-even stop-outs after TP1 (you banked at least 1R or protected the position). Everything else is a loss, including reversals that never reached TP1. The dashboard shows closed trades, W/L, win rate with a ▰▱ gauge, and a "Form" strip of the last 10 outcomes. Stats are session-scoped and reset on chart reload — this is transparent live tracking of the current settings on the current chart, not a backtest report.
9️⃣ Trend P&L tracker and theme-aware visual system.
An optional floating label follows price in real time and shows the directional % move since the current trend flip (a falling bear trend shows positive %), anchored by a dotted baseline at the trend start price. The label turns red when the trend is under water. The entire visual layer — band transparencies, heatmap fills, dashboard, profile, SL/TP palette — has separate Dark and Light calibrations (Auto-detected from the chart background), because bright hues that look right on dark charts wash out on white ones. TP lines recolor to solid teal with a ✓ when touched; the SL line dims and the entry label annotates "→ SL (BE)" when break-even activates. SL/TP lines persist after the trade closes as a visual record until the next entry replaces them.
⚙️ HOW IT WORKS — CALCULATION FLOW
Step 1 — Band geometry: The preset (or Custom inputs) resolves the base multiplier and proportional step; four multipliers m1–m4 are derived and multiplied by ATR (default length 13).
Step 2 — Ratcheting trail: In an uptrend each band only rises (max-lock); in a downtrend only falls (min-lock). On a flip the whole stack re-seeds on the opposite side of price.
Step 3 — Flip detection: A close beyond the previous bar's value of the chosen flip band (2/3/4) reverses the trend state. Flip labels print on confirmed bars after the warm-up period.
Step 4 — Pullback tracking: Any touch of Band 1–4 against the trend arms a pending retest with its maximum depth, valid for the retest window; pendings decay each bar and are voided on a flip.
Step 5 — Reclaim and scoring: A directional close back beyond Band 1 triggers scoring: depth (25) + candle (20) + volume (20) + HTF bias (20) + trend age (15). Score ≥ threshold and cooldown elapsed → confirmed signal on bar close.
Step 6 — Trade engine: The signal opens or reverses a position; SL is placed (wick-anchored or ATR), TP1–TP3 are projected as risk multiples; break-even, TP recolors and the four closure paths are managed bar by bar with pessimistic resolution.
Step 7 — Segment profile: On the last bar the profile is rebuilt from the flip bar: range-distributed accumulation → POC → 70% Value Area expansion → HVN/LVN detection → drawing.
Step 8 — Reporting: The dashboard updates trend state, signal state, profile levels, live trade card and session statistics; alerts fire on bar close in within-bar chronological order (management → closures → reversal → entries → info).
📖 HOW TO USE
🎯 Quick start:
1. Add the indicator to your chart and pick a Band Width Preset: Scalping for 1–15M, Balanced for most timeframes, Deep Trend for D–W position trading.
2. Set the Higher Timeframe Bias one or two steps above your chart (e.g. 1H while trading 15M).
3. Choose a Risk Preset that matches your style, or leave Balanced.
4. Watch the dashboard: Trend + HTF Bias aligned means you only consider signals in that direction with full conviction; the retest diamonds do the timing.
5. After 15–20 closed trades, read the Stats section and tune Min Retest Score up (fewer, cleaner signals) or down (more signals) for your instrument.
👁️ Reading the chart:
— 🟢 / 🔴 Band stack + heatmap = the liquidity trail zone; the deeper the fill, the closer price is to a trend flip.
— ◆ diamond with a number = confirmed scored retest entry (the number is the 0–100 quality score; hover the tooltip for the full component breakdown).
— ▲ / ▼ FLIP = confirmed trend reversal through the chosen flip band.
— Long ▲ / Short ▼ = trade entry taken by the engine on a flip (printed when there is no retest diamond on the same bar, so every entry is visibly marked).
— ENTRY / SL / TP1–TP3 lines = the live trade card; TP lines turn solid teal with ✓ when touched; a dimmed SL with "→ SL (BE)" on the entry label means the stop sits at break-even.
— 🟡 POC line = highest-volume price of the current trend leg; dashed VAH/VAL = Value Area edges; LVN labels = volume vacuums inside the Value Area.
— ▲ +X.XX% floating label (optional) = real-time directional P&L of the current trend since the flip.
📊 Dashboard fields:
— Trend / Age: direction of the band stack and bars since the last flip.
— HTF Bias: higher-timeframe EMA-50 direction (soft score component).
— Signal: current engine position — LONG, SHORT or Wait.
— Last signal: most recent event, its score, and bars elapsed.
— POC / VA High / VA Low: live segment profile levels.
— Entry / SL / TP1–TP3 / R:R / SL Dist %: the open trade card ("BE @" marks a break-even stop; ✓ marks touched targets); collapses to one row when flat.
— Trades / W-L / Win rate / Form: session statistics; ▰ = win, ▱ = loss, newest on the right.
🔧 Tuning guide:
— Too many weak signals: raise Min Retest Score toward 85–90, or increase Signal Cooldown.
— Too few signals: lower Min Retest Score toward 55–65, or widen the Retest Window to 10.
— Whipsaw flips on a choppy symbol: switch Flip Band to Deep (Band 4) or move to the Deep Trend preset.
— Flips lag too far behind on fast moves: Flip Band → Fast (Band 2) or the Scalping preset.
— Stops feel too tight / too wide: switch SL Mode between Wick-Anchored and ATR, or change the Risk Preset; on volatile symbols prefer Conservative.
— Profile looks coarse on long trends: raise Profile Rows to 50+ and Max Profile Bars toward 800.
— Counter-trend retests keep printing: set an explicit Higher Timeframe Bias — counter-bias signals lose 20 points and rarely clear a high threshold.
⚙️ KEY SETTINGS
⚙️ Trend Engine:
— Band Width Preset (default Balanced): Scalping 2.5 × ATR / step 0.20, Balanced 4.0 / 0.25, Deep Trend 6.0 / 0.30, or Custom.
— Base Multiplier (default 5.0) and Band Spacing (default 0.25): manual geometry, active in Custom preset only.
— ATR Length (default 13): lookback for band-width ATR.
— Source (default close): price series for trailing and flips.
— Flip Band (default Balanced / Band 3): which band a close must breach to flip the trend.
— Higher Timeframe Bias (default empty = chart TF): HTF for EMA-50 bias scoring.
🎯 Signals:
— Min Retest Score (default 80): 0–100 quality threshold for retest diamonds.
— Retest Window (default 8 bars): how long a band touch stays armed for a reclaim.
— Signal Cooldown (default 5 bars): minimum spacing between signals, shared across directions.
📦 Volume Profile:
— Show Segment Volume Profile (on), Profile Rows (30), Profile Width (34 bars), Max Profile Bars (500).
— Show POC (on), Show Value Area 70% (on), Show HVN / LVN Levels (on), Profile Label Size (Small).
🛡️ Risk Management:
— Risk Preset (default Balanced): Conservative / Balanced / Aggressive / Scalping / Custom.
— SL Mode (default Wick-Anchored): structure-aware wick stop vs. fixed ATR distance.
— ATR Length (Risk) (14), SL Multiplier (1.5), TP1 / TP2 / TP3 Multipliers (1.0 / 2.0 / 3.0 × risk) — Custom preset.
— Break-Even After TP1 (on): stop moves to entry once TP1 is touched.
— Show SL/TP Lines / Labels / % Distance and per-line style controls (Entry dotted, SL solid, TP dashed by default).
🎨 Visual:
— Theme (Auto / Dark / Light), Show Trail Bands, Show Band Heatmap Fill, Show Retest Signals, Show Flip Labels, Show Trend P&L Tracker (off by default), label size controls, watermark toggle, Bull / Bear color pickers.
📊 Dashboard:
— Show Dashboard (on), position (5 anchors), font size, and independent toggles for the Market, Profile, Trade and Stats sections.
🔧 Advanced:
— HVN Threshold (default 0.55 × POC volume): minimum relative volume for an acceptance node.
— LVN Threshold (default 0.30 × POC volume): maximum relative volume for a vacuum node.
🔔 ALERTS
— 🟢 LONG ENTRY / 🔴 SHORT ENTRY — ticker, timeframe, price, signal score, SL, TP1–TP3, R:R. Plain text or JSON webhook format ({"action":"buy"...}) for bot integrations.
— 🎯 TP1 / TP2 / TP3 HIT — target touches with prices (optional).
— 🛡️ BREAK-EVEN — stop moved to entry after TP1 (optional).
— 🛑 SL HIT / BE STOP-OUT — stop-loss trigger with direction, entry and stop prices; a distinct BE variant when the stop was at break-even.
— 🔄 REVERSAL — position reversed by an opposite signal, with the closed trade's outcome (after / before TP1).
— ▲ / ▼ TREND FLIP — informational flips that did not open or reverse a trade.
— ⚡ LVN BREAK — a close crossing a Low Volume Node of the live segment profile (price entering a volume vacuum often accelerates).
All alerts fire once per bar close. Alerts are ordered by within-bar chronology: trade management → closures → reversal → new entries → informational.
⚠️ IMPORTANT NOTES
— 🚫 No repainting. All signals, entries and alerts are confirmed on bar close (barstate.isconfirmed). The trend flip compares against the previous bar's band value. The HTF bias uses the higher timeframe's previous closed bar, so its value never changes retroactively. A warm-up guard suppresses signals for the first max(3 × ATR length, 60) bars.
— 📐 The segment volume profile is a live construct. It is redrawn on the last bar for the current trend leg and evolves as the leg grows — this is by design (it describes the present segment), and historical profile states are not preserved.
— 📊 Session statistics reset on chart reload. They are transparent live tracking of the current settings on the current symbol and timeframe — not a backtest, and past performance does not guarantee future results.
— ⚖️ Same-bar ambiguity is resolved pessimistically. If one bar touches both a stop and a target, the stop wins in the statistics. Intrabar sequence cannot be known from OHLC data, so the engine never gives itself the benefit of the doubt.
— 🕳️ Zero-volume symbols use a range-weighted proxy for the profile, and the volume score component defaults to a neutral value — profile shapes on such symbols reflect price dwell time, not traded volume.
— 🛠️ This is an analysis and trade-planning tool, not an automated trading bot. It detects trend state, scores retests, projects stops and targets, and tracks outcomes — trade decisions remain yours.
— 🌐 Works on all markets and timeframes.
오픈 소스 스크립트
트레이딩뷰의 진정한 정신에 따라, 이 스크립트의 작성자는 이를 오픈소스로 공개하여 트레이더들이 기능을 검토하고 검증할 수 있도록 했습니다. 작성자에게 찬사를 보냅니다! 이 코드는 무료로 사용할 수 있지만, 코드를 재게시하는 경우 하우스 룰이 적용된다는 점을 기억하세요.
10 years in trading. For all inquiries, contact me on my Telegram channel: t.me/WillyAlgoTrader or Instagram: @willytraderbtc
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.
오픈 소스 스크립트
트레이딩뷰의 진정한 정신에 따라, 이 스크립트의 작성자는 이를 오픈소스로 공개하여 트레이더들이 기능을 검토하고 검증할 수 있도록 했습니다. 작성자에게 찬사를 보냅니다! 이 코드는 무료로 사용할 수 있지만, 코드를 재게시하는 경우 하우스 룰이 적용된다는 점을 기억하세요.
10 years in trading. For all inquiries, contact me on my Telegram channel: t.me/WillyAlgoTrader or Instagram: @willytraderbtc
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.