//@version=6 // ╔═══════════════════════════════════════════════════════════════════════════╗ // ║ Liq Heat Map and Vol Prof + HTF Reversal Divergences | Pine v6 ║ // ║ + Kalman D7 | Version 22 (v20 + level-1 fixes, 17 Sep 2026) ║ // ║ v22: ⑮ iceberg counted per side (VAL→buy, VAH→sell) · ⑮ RQ level uses ║ // ║ slow kernel only · ⑮ MC band must be within its projection window ║ // ║ · ⑳ Donchian BO fires once per direction (was every new high) ║ // ║ · ⑳ zone/table say 'rally-sell' in downtrends · ATR moved global ║ // ║ · LBMA windows in Europe/London, CME window in America/New_York ║ // ║ · defaults = user's live H1 settings (TFH1 build) · v21 (session AVWAP) skipped ║ // ║ AMT Rejection → QC_SovereignMatrix v2.1 §5 global + §14 (verbatim) ║ // ║ Volume Profile → QC_SovereignMatrix v2.1 §25 (verbatim) ║ // ║ Liq Heatmap → EA Quantum FundOS v2.1 §7 + §9 (verbatim) ║ // ║ HTF Reversal → LuxAlgo (CC BY-NC-SA 4.0) ║ // ║ Kalman D7 → et20tradeview (MPL 2.0) ║ // ║ Monte Carlo → LuxAlgo Predictive Monte Carlo Engine (CC BY-NC-SA) ║ // ╠═══════════════════════════════════════════════════════════════════════════╣ // ║ v3 → v4 Changelog: ║ // ║ ⑩ Hilbert Transform Dominant Cycle (Adaptive HM/VP Lookback) ║ // ║ ⑪ RQ-Kernel Rational Quadratic Regression Lines + Uncertainty Band ║ // ║ ⑫ Shannon Entropy Market Quality Filter ║ // ║ ⑬ VPIN Proxy Informed Flow Detector ║ // ╠═══════════════════════════════════════════════════════════════════════════╣ // ║ v4 → v5 Changelog (nothing from v4 removed — pure addition): ║ // ║ ⑭ Predictive Monte Carlo Engine (GBM / SRW / Historical Shuffle) ║ // ║ • Regime filter (Trend SMA / Momentum RSI), anchor mode ║ // ║ • Percentile path coloring, envelope, average path ║ // ║ • S/R projection zones + Monte Carlo dashboard + forecast candle ║ // ║ All MC identifiers namespaced (mc_/MC_) to avoid any collision. ║ // ╠═══════════════════════════════════════════════════════════════════════════╣ // ║ v5 → v8 Changelog (pure addition, nothing removed): ║ // ║ ⑮ Confluence BUY/SELL Signal — fires when ALL align: ║ // ║ • Price INSIDE Monte Carlo band (between S1 and R1) ║ // ║ • Near a significant level (AMT VWMA value band / RQ-Kernel) ║ // ║ • Multi-TF OB/OS : current(M5) + (H1 or H4) agree ║ // ║ • Order-flow confirm: rejection / iceberg / delta (≥ N of 3) ║ // ║ • Kalman turn + Shannon-Entropy quality (optional confluence) ║ // ║ Independent toggles: Labels on/off · Arrows(plotshape) on/off ║ // ║ + 2 alerts (Confluence BUY / SELL) ║ // ╠═══════════════════════════════════════════════════════════════════════════╣ // ║ v8 → v9 Changelog (pure default tuning, nothing removed or added): ║ // ║ INPUT DEFAULT CHANGES: ║ // ║ ⑭ MC Regime Filter: None → Trend (SMA) ║ // ║ ⑭ MC Historical Lookback: 100 → 200 ║ // ║ ⑭ MC Volatility Multiplier: 1.0 → 1.2 ║ // ║ ⑮ Confluence MC band zone: Inside (S1-R1) → Lower/Upper half ║ // ╠═══════════════════════════════════════════════════════════════════════════╣ // ║ v9 → v10 Changelog (pure addition, nothing from v9 removed): ║ // ║ ⑯ Triple MTF Conf Signal — overlay ★ CONF BUY / ★ CONF SELL labels ║ // ║ Condition: M5 + H1 + H4 ALL show WMA-RSI OS (BUY) / OB (SELL) ║ // ║ + AMT Rejection on the same bar (_rej_bot / _rej_top) ║ // ║ OS = WMA(RSI(5),mw) < WMA(RSI(20),mw) AND slow < 50 at ALL 3 TFs ║ // ║ OB = WMA(RSI(5),mw) > WMA(RSI(20),mw) AND slow > 50 at ALL 3 TFs ║ // ║ mw=20 matches MoConf v11 momentumWindow (same fast/slow RSI WMAs ║ // ║ as the MLMI kNN features — no state divergence, no init artefacts) ║ // ║ Independent toggles: Labels on/off · Arrows(plotshape) on/off ║ // ║ + 2 alertconditions ║ // ╠═══════════════════════════════════════════════════════════════════════════╣ // ║ v10 → v11 Changelog (targeted fix, nothing from v10 removed): ║ // ║ ⑯ Fixed false positives — added absolute fast WMA RSI threshold ║ // ║ Root cause: "fastslow AND fast>i_tri_ob(60) AND slow>50 — ALL 3 TFs ║ // ║ 2 new inputs: i_tri_os (default 40) · i_tri_ob (default 60) ║ // ╠═══════════════════════════════════════════════════════════════════════════╣ // ║ v11 → v12 Changelog (pure addition, nothing from v11 removed): ║ // ║ ⑰ ML YZ — Adaptive Yang-Zhang Volatility Bands (ML YZ v1) ║ // ║ • Pure Yang-Zhang 3-component estimator (OC + RS + CO) ║ // ║ • kNN regime classifier: 3 features (BW-ROC / RelVol / PriceDist) ║ // ║ → Balance(1) / Neutral(0) / Imbalance(-1) via YZ vol rank label ║ // ║ • Adaptive band width: tighter on Balance, wider on Imbalance ║ // ║ • KAMA middle band (or EMA/SMA/WMA/HMA — selectable) ║ // ║ • AMT signals: Initiative BUY/SELL + Responsive BUY/SELL ║ // ║ • Value Area inner bands + VWAP-proxy POC line ║ // ║ • Regime label on last bar + 4 alertconditions ║ // ╠═══════════════════════════════════════════════════════════════════════════╣ // ║ v12 → v16 Changelog (bug fix only — no logic/inputs/signals changed): ║ // ║ ⑰ FIX: ML YZ Regime label stacked up on every bar close (see report). ║ // ║ Cause: the last-bar label used a bare label.new() with no var/delete ║ // ║ → each closed bar committed its label permanently while the next ║ // ║ bar drew another, piling up IMBALANCE/BALANCE/NEUTRAL · YZ=x.xx. ║ // ║ Fix: var label _yz_lbl + label.delete() before redraw (same idiom ║ // ║ as the §14b market-quality label) → exactly ONE YZ label persists. ║ // ╠═══════════════════════════════════════════════════════════════════════════╣ // ║ v16 → v17 Changelog (pure addition, nothing removed — display-only): ║ // ║ ⑱ HV-Pivot Levels + CLV-Delta (default OFF — levels-eyes, no gate) ║ // ║ • Volume-gated pivots (BigBeluga concept, ported as a FILTER not the ║ // ║ full zone system): ta.pivothigh/low kept only if the pivot bar's ║ // ║ volume[len] > SMA(volume, maLen) × mult. ║ // ║ • CVD via CLV×vol : ((C−L)−(H−C))/(H−L) × volume — replaces the ║ // ║ weak candle-direction proxy (close≥open?+v:−v). Same principle as ║ // ║ KV-MACD v8 ㉓ leg-delta → one delta definition across the suite. ║ // ║ • Draws ONE horizontal ray per level (extend right) + a CVD label. ║ // ║ NO boxes · NO polylines · capped last N per side (default 3) → ║ // ║ ≤ 6 lines + ≤ 6 labels total. Anti-bloat by construction. ║ // ║ • Does NOT touch ⑮/⑯/⑰ signals. Additive; delete §22 to revert. ║ // ╠═══════════════════════════════════════════════════════════════════════════╣ // ║ v17 → v18 Changelog (OPT-IN entry-logic — ALL gates default OFF): ║ // ║ ⑱ CVD-Confluence GATE — wire the HV-Pivot levels into ⑮/⑯ as an extra ║ // ║ directional confluence (KV-MACD i_ladGate discipline: OFF by default).║ // ║ • BUY passes only if price is within Xatr of an HV-SUPPORT whose ║ // ║ CLV-CVD ≥ min (accumulation-confirmed floor). ║ // ║ • SELL passes only if price is within Xatr of an HV-RESISTANCE whose ║ // ║ CLV-CVD ≤ −min (distribution-confirmed ceiling). ║ // ║ • Independent toggles i_hv_gate_sig (⑮) / i_hv_gate_tri (⑯); both ║ // ║ auto-relax to no-op unless ⑱ levels are enabled. When OFF the ⑮/⑯ ║ // ║ signals are byte-for-byte the validated v11 behaviour. ║ // ║ • §18b computes the gate booleans BEFORE §19 (reads prior-bar levels, ║ // ║ no lookahead). §22 detection/labels unchanged. ║ // ║ ⚠ CHANGES ENTRY LOGIC when enabled → must pass walk-forward OOS before ║ // ║ any live use (gospel: no un-OOS'd entry change reaches capital). ║ // ╚═══════════════════════════════════════════════════════════════════════════╝ // ╠═══════════════════════════════════════════════════════════════════════════╣ // ║ v19 → v20 Changelog (pure addition, nothing removed): ║ // ║ ⑳ Trend Breakout + Correction Meter (M5) — DISPLAY-ONLY. ║ // ║ (A) Donchian N-bar high/low breakout lines (100 + 200) = trend- ║ // ║ follow trigger, with BO up/down markers. (B) Correction Meter ║ // ║ table = MR-into-trend read: after a breakout, measures pullback ║ // ║ depth as a Fib retrace of the impulse (deeper = higher-prob ║ // ║ continuation), plus a dip-buy zone box (Fib .5–.618). Uses only ║ // ║ line/label/box/table → 0 plot-budget (no RE10140 risk). Nothing ║ // ║ feeds any signal / gate / score — pure visual reference. ║ // ╠═══════════════════════════════════════════════════════════════════════════╣ // ║ v18 → v19 Changelog (pure addition, nothing removed): ║ // ║ ⑲ VWAP Stdev Bands (session-anchored, tuned for M5) — DISPLAY-ONLY. ║ // ║ Ported from "VWAP Stdev Bands v2 Mod" (Pine v2 → v6). Session VWAP ║ // ║ + up to 5 stdev band groups + over/under fills + optional VWAP-zone ║ // ║ bar color (default OFF so it never fights existing bar coloring). ║ // ║ Daily anchor = correct intraday VWAP on M5. Nothing fed to any ║ // ║ signal / gate / score — pure visual reference. ║ // ╚═══════════════════════════════════════════════════════════════════════════╝ indicator( title = "Liq Heat Map and Vol Prof v22 TFH1", shorttitle = "LiqHM+VP+Kalman+MC v22 TFH1", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_polylines_count= 100, max_bars_back = 500) // ═══════════════════════════════════════════════════════════════════════════ // §1 UDT // ═══════════════════════════════════════════════════════════════════════════ type pivot float value int index float volume_ float vol bool isLower // ── ⑱ HV-Pivot level (one persistent ray + its snapshot CLV-CVD) ─────────── type hvLevel line ln float price float cvd type HTFData float o float h float l float c int oIdx int hIdx int lIdx float delta int startTime type HTFCandleUI box body line wick line oM line hM line lM line cM label oL label hL label lL label cL label dL label tL // ── ⑭ Monte Carlo UDT (LuxAlgo) ─────────────────────────────────────────── type LCG int seed method next(LCG this) => this.seed := (1103515245 * this.seed + 12345) % 2147483647 if this.seed < 0 this.seed += 2147483647 float(this.seed) / 2147483647.0 method nextInt(LCG this, int min, int max) => this.seed := (1103515245 * this.seed + 12345) % 2147483647 if this.seed < 0 this.seed += 2147483647 min + (this.seed % (max - min + 1)) method nextGaussian(LCG this) => float u1 = this.next() if u1 <= 0.00001 u1 := 0.00001 float u2 = this.next() math.sqrt(-2.0 * math.log(u1)) * math.cos(2.0 * math.pi * u2) type Path array pts float endPrice // ═══════════════════════════════════════════════════════════════════════════ // §2 INPUTS // ═══════════════════════════════════════════════════════════════════════════ // ── ① AMT Rejection ──────────────────────────────────────────────────────── const string G_AMT = "① AMT Rejection (VWMA50 ± StdDev50 × 1.5 — Fixed)" bool i_show_amt = input.bool(true, "Show Iceberg / Rejection Signals", group=G_AMT) // ── ② Volume Profile ─────────────────────────────────────────────────────── const string G_VP = "② Volume Profile (QC_SovereignMatrix v2.1)" bool i_show_vp = input.bool(false, "Show Volume Profile", group=G_VP) int i_vp_bars = input.int(500, "VP Lookback Bars", group=G_VP, minval=20, maxval=500) int i_vp_rows = input.int(100, "VP Row Count", group=G_VP, minval=5, maxval=100) float i_vp_pct = input.float(90.0, "Value Area %", group=G_VP, minval=0, maxval=100) bool i_vp_show_boxes = input.bool(false, "Show VP Boxes (Volume Histogram)", group=G_VP) bool i_vp_show_poc = input.bool(false, "Show POC Line", group=G_VP) color i_c_poc_line = input.color(color.new(#FF1744, 0), "POC Color", group=G_VP) string i_poc_style = input.string("Dotted", "POC Style", group=G_VP, options=["Solid","Dashed","Dotted"]) int i_poc_width = input.int(2, "POC Width", group=G_VP, minval=1, maxval=5) bool i_vp_show_poc_lbl = input.bool(true, "Show POC Label", group=G_VP) bool i_vp_show_vah = input.bool(true, "Show VAH Line", group=G_VP) color i_c_vah_line = input.color(color.new(#00BCD4, 0), "VAH Color", group=G_VP) string i_vah_style = input.string("Dotted", "VAH Style", group=G_VP, options=["Solid","Dashed","Dotted"]) int i_vah_width = input.int(2, "VAH Width", group=G_VP, minval=1, maxval=5) bool i_vp_show_vah_lbl = input.bool(true, "Show VAH Label", group=G_VP) bool i_vp_show_val = input.bool(true, "Show VAL Line", group=G_VP) color i_c_val_line = input.color(color.new(#00BCD4, 0), "VAL Color", group=G_VP) string i_val_style = input.string("Dotted", "VAL Style", group=G_VP, options=["Solid","Dashed","Dotted"]) int i_val_width = input.int(2, "VAL Width", group=G_VP, minval=1, maxval=5) bool i_vp_show_val_lbl = input.bool(true, "Show VAL Label", group=G_VP) // ── ③ Liquidity Heatmap ──────────────────────────────────────────────────── const string grp_hm = "③ Liquidity Heatmap (EA Quantum FundOS v2.1)" int lookBack_hm = input.int(377, "Calculated Bars", group=grp_hm, minval=10, maxval=500) int hm_offset = input.int(30, "➡️ Profile X-Axis Offset", group=grp_hm, minval=0, maxval=150) bool displPf = input.bool(true, "Show Profile", group=grp_hm) bool i_hm_show_boxes = input.bool(true, "Show Heatmap Boxes", group=grp_hm) bool i_hm_show_lines = input.bool(true, "Show Heatmap Lines", group=grp_hm) int bins = input.int(85, "Resolution (Bins)", group=grp_hm, minval=5, maxval=200) color sellColor = input.color(color.new(#FF6D00, 0), "Sell Liquidity Color", group=grp_hm) color buyColor = input.color(color.new(#00E676, 0), "Buy Liquidity Color", group=grp_hm) int i_sell_tr = input.int(19, "Sell Line Transparency (0=opaque)", group=grp_hm, minval=0, maxval=100) int i_buy_tr = input.int(19, "Buy Line Transparency (0=opaque)", group=grp_hm, minval=0, maxval=100) bool poc_show = input.bool(true, "Show POC", group=grp_hm) color maxColor = input.color(color.new(#6A1E9A, 0), "Max Point (POC) Color", group=grp_hm) // ── ④ LBMA / CME Fix Windows ─────────────────────────────────────────────── const string G_FIX = "④ LBMA / CME Fix Windows" bool i_show_fix = input.bool(true, "Show Fix Window Backgrounds", group=G_FIX, tooltip="Highlights LBMA AM, LBMA PM, and CME NY fix windows on the price chart.\nTimes are based on UTC+0.") bool i_fix_am_en = input.bool(true, "LBMA AM Fix (10:00 – 10:30 London)", group=G_FIX) bool i_fix_pm_en = input.bool(true, "LBMA PM Fix (15:00 – 15:15 London)", group=G_FIX) bool i_fix_cme_en = input.bool(true, "CME NY Close (13:20 – 13:30 New York)", group=G_FIX) int i_fix_utc = input.int(0, "Extra hour offset (normally 0)", group=G_FIX, minval=-12, maxval=14) color i_col_fix_am = input.color(color.new(#4CAF50, 88), "LBMA AM Color", group=G_FIX) color i_col_fix_pm = input.color(color.new(#4CAF50, 88), "LBMA PM Color", group=G_FIX) color i_col_fix_cme = input.color(color.new(#4CAF50, 88), "CME NY Color", group=G_FIX) // ── ⑤ HTF Reversal Patterns ──────────────────────────────────────────────── const string G_HTF = "⑤ HTF Reversal Patterns (LuxAlgo)" string htfInput = input.timeframe("60", "High Timeframe", group=G_HTF, tooltip="Timeframe to check for reversal patterns.") bool showEngulfingInput = input.bool(true, "Show Engulfing Patterns", group=G_HTF) bool showPinBarsInput = input.bool(true, "Show Pin Bars", group=G_HTF, tooltip="Includes Hammer and Shooting Star patterns.") color bullPatternColInput = input.color(#00E676, "Bullish Pattern Color", group=G_HTF, inline="HTFcol") color bearPatternColInput = input.color(#FF6D00, "Bearish Pattern Color", group=G_HTF, inline="HTFcol") // ── ⑥ RSI Divergence ─────────────────────────────────────────────────────── const string G_RSI = "⑥ RSI Divergence (LuxAlgo)" bool showDivInput = input.bool(false, "Show RSI Divergences", group=G_RSI) int rsiLenInput = input.int(14, "RSI Length", group=G_RSI, minval=1) int lbRInput = input.int(5, "Pivot Right Lookback", group=G_RSI) int lbLInput = input.int(5, "Pivot Left Lookback", group=G_RSI) color bullDivColInput = input.color(#089981, "Bullish Div Color", group=G_RSI, inline="DIVcol") color bearDivColInput = input.color(#f23645, "Bearish Div Color", group=G_RSI, inline="DIVcol") // ── ⑦ HTF PO3 ────────────────────────────────────────────────────────────── const string G_PO3 = "⑦ HTF PO3 (LuxAlgo)" bool showPo3Input = input.bool(false, "Show HTF PO3", group=G_PO3, tooltip="Projects HTF candles to the right of price.") int candleCountInput = input.int(3, "Candles to Show", group=G_PO3, minval=1, maxval=10) int po3OffsetInput = input.int(50, "Right Offset (Bars)", group=G_PO3, minval=5, tooltip="If Heatmap Profile is also enabled, increase this to avoid overlap.") bool showPo3LabelsInput = input.bool(true, "Show PO3 Price Labels", group=G_PO3) bool showPo3DeltaInput = input.bool(true, "Show PO3 Running Delta", group=G_PO3) // ── ⑧ Alerts ─────────────────────────────────────────────────────────────── const string G_ALERT = "⑧ Alerts" bool alertBullDivInput = input.bool(true, "Bullish Divergence", group=G_ALERT) bool alertBearDivInput = input.bool(true, "Bearish Divergence", group=G_ALERT) bool alertBullEngInput = input.bool(true, "Bullish Engulfing", group=G_ALERT) bool alertBearEngInput = input.bool(true, "Bearish Engulfing", group=G_ALERT) bool alertHammerInput = input.bool(true, "Hammer", group=G_ALERT) bool alertStarInput = input.bool(true, "Shooting Star", group=G_ALERT) // ── ⑨ Kalman D7 (et20tradeview — MPL 2.0) ──────────────────────────────── const string G_KLM = "⑨ Kalman D7 (et20tradeview)" bool show_pul = input.bool(false, "Show EMA", group=G_KLM) source = input(close, "Source", group=G_KLM) float factor = input.float(0.5, "EMA Length 1", minval=0.1, step=0.1, group=G_KLM) float factor2 = input.float(0.5, "EMA Length 2", minval=0.1, step=0.1, group=G_KLM) int r_ratiob = input.int(200, "R base", step=5, group=G_KLM, tooltip="Uncertainty measurement lookback") float q_ratiob = input.float(0.002, "q multiplier base", step=0.001, group=G_KLM, tooltip="Process noise variance, higher = more responsive") float r_gate_multb = input.float(1.5, "R Gate Multiplier base", step=0.1, group=G_KLM, tooltip="R sensitivity baseline") int r_ratios = input.int(20, "R fast", step=5, group=G_KLM, tooltip="Uncertainty measurement lookback (fast)") float q_ratios = input.float(0.005, "q multiplier fast", step=0.001, group=G_KLM, tooltip="Process noise variance (fast), higher = more responsive") float r_gate_mults = input.float(1.2, "R Gate Multiplier fast", step=0.1, group=G_KLM, tooltip="R sensitivity baseline (fast)") // ── ⑩ Hilbert DC — Adaptive Line Reach ──────────────────────────────────── // DC adaptive controls HM LINE REACH (how far back lines extend on chart). // Pivot stats (h_l array, vb_max, step_bin) always use full lookBack_hm input // to keep box text identical to v3. VP always uses full i_vp_bars input. const string G_DC = "⑩ Hilbert DC — Adaptive HM Line Reach" bool i_dc_en = input.bool(true, "Enable Adaptive DC Line Reach (HM)", group=G_DC, tooltip="Adjusts how far Heatmap lines extend back based on dominant cycle.\nPivot stats and box text are unchanged (identical to v3).\nVP lookback is also unaffected.") bool i_dc_show_lbl = input.bool(true, "Show DC Info Label", group=G_DC) int i_dc_hm_mult = input.int(13, "HM Line Reach Multiplier (×DC)", group=G_DC, minval=4, maxval=30, tooltip="Heatmap line reach = DC × this bars. Default 13 (Fibonacci). Fast market → shorter reach. Slow market → longer reach.") // ── ⑪ RQ-Kernel (Rational Quadratic Regression) ─────────────────────────── const string G_RQ = "⑪ RQ-Kernel (Rational Quadratic Regression)" bool i_rq_en = input.bool(true, "Enable RQ-Kernel Lines", group=G_RQ) int i_rq_h_fast = input.int(8, "Fast Bandwidth (h)", group=G_RQ, minval=2, maxval=50) int i_rq_h_slow = input.int(25, "Slow Bandwidth (h)", group=G_RQ, minval=5, maxval=100) float i_rq_alpha = input.float(1.0, "Alpha (Multi-Scale)", group=G_RQ, step=0.25, minval=0.25, maxval=10.0) int i_rq_len = input.int(50, "Max Lookback (bars)", group=G_RQ, minval=10, maxval=200) bool i_rq_show_ub = input.bool(true, "Show Uncertainty Band", group=G_RQ) color i_rq_fast_col = input.color(color.new(#00E5FF, 10), "RQ Fast Color", group=G_RQ) color i_rq_slow_col = input.color(color.new(#FF6F00, 10), "RQ Slow Color", group=G_RQ) color i_rq_ub_col = input.color(color.new(#607D8B, 88), "Uncertainty Band Color", group=G_RQ) // ── ⑫ Shannon Entropy (Market Quality Filter) ───────────────────────────── const string G_ENT = "⑫ Shannon Entropy (Market Quality Filter)" bool i_ent_en = input.bool(true, "Enable Entropy Filter", group=G_ENT) int i_ent_len = input.int(50, "Lookback (bars)", group=G_ENT, minval=20, maxval=200) int i_ent_bins = input.int(8, "Discretization Bins", group=G_ENT, minval=4, maxval=16) bool i_ent_show_lbl = input.bool(true, "Show Entropy Label", group=G_ENT) float i_ent_str_thr = input.float(0.35, "Structured Threshold (<)", group=G_ENT, step=0.05, minval=0.10, maxval=0.60) float i_ent_ran_thr = input.float(0.65, "Random Threshold (>)", group=G_ENT, step=0.05, minval=0.40, maxval=0.90) // ── ⑬ VPIN — Informed Flow Detector ─────────────────────────────────────── const string G_VPIN = "⑬ VPIN — Informed Flow Detector" bool i_vpin_en = input.bool(true, "Enable VPIN Detection", group=G_VPIN) int i_vpin_len = input.int(20, "Smoothing Length (bars)", group=G_VPIN, minval=5, maxval=100) float i_vpin_tox = input.float(0.35, "Toxic Flow Threshold", group=G_VPIN, step=0.05, minval=0.15, maxval=0.70) float i_vpin_bal = input.float(0.15, "Balanced Flow Threshold", group=G_VPIN, step=0.05, minval=0.05, maxval=0.40) bool i_vpin_show_lbl = input.bool(true, "Show VPIN Label", group=G_VPIN) color i_vpin_tox_col = input.color(color.new(#FF1744, 0), "Toxic Color", group=G_VPIN) color i_vpin_bal_col = input.color(color.new(#00E676, 0), "Balanced Color", group=G_VPIN) // ── ⑭ Predictive Monte Carlo Engine (LuxAlgo) ───────────────────────────── // Verbatim LuxAlgo logic; identifiers namespaced mc_/MC_ to coexist with v4. const string MC_METHOD_GBM = "Geometric Brownian Motion" const string MC_METHOD_SRW = "Simple Random Walk" const string MC_METHOD_HS = "Historical Shuffle" const string MC_REGIME_NONE = "None" const string MC_REGIME_TREND = "Trend (SMA)" const string MC_REGIME_MOMENTUM = "Momentum (RSI)" const color MC_DATA = #DBDBDB const color MC_HEADERS = #808080 const color MC_BACKGROUND = #161616 const color MC_BORDERS = #2E2E2E const string MC_TOP_RIGHT = 'Top Right' const string MC_BOTTOM_RIGHT = 'Bottom Right' const string MC_BOTTOM_LEFT = 'Bottom Left' const string MC_TINY = 'Tiny' const string MC_SMALL = 'Small' const string MC_NORMAL = 'Normal' const string MC_LARGE = 'Large' const string MC_HUGE = 'Huge' const string G_MC = "⑭ Monte Carlo — Settings (LuxAlgo)" const string G_MC_STY = "⑭ Monte Carlo — Style" const string G_MC_DASH = "⑭ Monte Carlo — Dashboard" bool mc_enableInput = input.bool(true, "Enable Monte Carlo Engine", group=G_MC, tooltip="Master switch for the Predictive Monte Carlo module. When off, no MC drawings or dashboard are rendered.") string mc_methodInput = input.string(MC_METHOD_GBM, "Simulation Method", options = [MC_METHOD_GBM, MC_METHOD_SRW, MC_METHOD_HS], group = G_MC, tooltip = "Select the mathematical method used to project the future price paths.") string mc_regimeInput = input.string(MC_REGIME_TREND, "Regime Filter", options = [MC_REGIME_NONE, MC_REGIME_TREND, MC_REGIME_MOMENTUM], group = G_MC, tooltip = "Only sample past returns and volatilities that match the current market regime. Works for all methods.") int mc_lookbackInput = input.int(200, "Historical Lookback", minval = 10, maxval = 1000, group = G_MC, tooltip = "Number of historical bars used to calculate drift and volatility.") int mc_projInput = input.int(50, "Projection Length", minval = 5, maxval = 200, group = G_MC, tooltip = "Number of bars to project into the future.") int mc_simInput = input.int(200, "Simulation Count", minval = 2, maxval = 200, group = G_MC, tooltip = "Number of paths to simulate. Max 200.") float mc_volMulti = input.float(1.2, "Volatility Multiplier", minval = 0.1, maxval = 5.0, step = 0.1, group = G_MC, tooltip = "Multiply the historical volatility to stress-test projections. Higher values make GBM and SRW deviate more.") int mc_seedInput = input.int(12345, "Random Seed", group = G_MC, tooltip = "Change this value to generate an entirely new set of random paths.") bool mc_anchorInput = input.bool(true, "Enable Anchor Mode", group = G_MC, tooltip = "Locks the projection and only updates every X bars, leaving historical S/R zones on the chart to see how price reacted.") int mc_anchorStep = input.int(100, "Anchor Update Step (Bars)", minval = 10, group = G_MC, tooltip = "How often to cast a new historical projection when Anchor Mode is enabled.") bool mc_anchorPaths = input.bool(false, "Draw Paths in Anchor Mode", group = G_MC, tooltip = "TradingView only allows 100 polylines per chart. Enabling this in Anchor Mode will cause older envelopes to disappear.") float mc_topPercentile = input.float(90.0, "Top Path Percentile", minval = 50.0, maxval = 100.0, group = G_MC_STY, tooltip = "Paths ending above this percentile are colored with the Top Color.") float mc_botPercentile = input.float(10.0, "Bottom Path Percentile", minval = 0.0, maxval = 50.0, group = G_MC_STY, tooltip = "Paths ending below this percentile are colored with the Bottom Color.") color mc_topColor = input.color(color.rgb(255, 77, 0, 0), "Top Color", group = G_MC_STY, inline = "mccolors") color mc_midColor = input.color(color.gray, "Middle Color", group = G_MC_STY, inline = "mccolors") color mc_bottomColor = input.color(color.rgb(89, 255, 0, 0), "Bottom Color", group = G_MC_STY, inline = "mccolors") int mc_transpInput = input.int(60, "Path Transparency", minval = 0, maxval = 100, group = G_MC_STY) color mc_avgColor = input.color(color.new(color.white, 0), "Average Line Color", group = G_MC_STY) color mc_envColor = input.color(color.new(color.gray, 90), "Envelope Fill Color", group = G_MC_STY) bool mc_srInput = input.bool(true, "Show S/R Levels", group = G_MC_STY, tooltip = "Display horizontal support and resistance lines based on the projection limits.") bool mc_dashboardInput = input.bool(true, 'Show Dashboard', group = G_MC_DASH, tooltip = "Enable or disable the Monte Carlo dashboard.") string mc_dashboardPositionInput = input.string(MC_TOP_RIGHT, 'Position', group = G_MC_DASH, tooltip = "Select the dashboard location.", options = [MC_TOP_RIGHT, MC_BOTTOM_RIGHT, MC_BOTTOM_LEFT]) string mc_dashboardSizeInput = input.string("Small", 'Size', group = G_MC_DASH, tooltip = "Select the dashboard size.", options = [MC_TINY, MC_SMALL, MC_NORMAL, MC_LARGE, MC_HUGE]) bool mc_dash2Input = input.bool(false, 'Show Next Candle Prediction', group = G_MC_DASH) color mc_bullColor = input.color(#089981, "Bullish Color", group = G_MC_DASH, inline = "mcc1") color mc_bearColor = input.color(#f23645, "Bearish Color", group = G_MC_DASH, inline = "mcc1") // ── ⑮ Confluence Buy/Sell Signal ─────────────────────────────────────────── const string G_SIG = "⑮ Confluence Buy/Sell Signal" bool i_sig_en = input.bool(true, "Enable Confluence Signal (master)", group=G_SIG, tooltip="Master switch. Fires only when ALL conditions align:\n• Price INSIDE Monte Carlo band (between S1 and R1)\n• Near a significant level (AMT value band / RQ-Kernel)\n• Multi-TF OB/OS : current(M5) + (H1 or H4)\n• Order-flow confirm: rejection / iceberg / delta\n• (optional) Kalman turn + Entropy quality") bool i_sig_show_lbl= input.bool(true, " Show LABELS (▲BUY / ▼SELL)", group=G_SIG) bool i_sig_show_shp= input.bool(true, " Show ARROWS (plotshape)", group=G_SIG) bool i_sig_confirm = input.bool(true, "Signal on bar close only (less repaint)", group=G_SIG) string i_sig_band = input.string("Lower/Upper half", "MC band zone", group=G_SIG, options=["Inside (S1-R1)","Lower/Upper half"], tooltip="Inside = price anywhere between S1 and R1.\nLower/Upper half = BUY only below mean, SELL only above mean.") bool i_sig_use_kal = input.bool(true, "Require Kalman turn confirm", group=G_SIG, tooltip="BUY: Kalman fast ticking up. SELL: ticking down.") bool i_sig_use_ent = input.bool(true, "Require Entropy quality", group=G_SIG, tooltip="Skip signals when market is RANDOM (low quality).") bool i_sig_ent_str = input.bool(false, " Entropy must be STRUCTURED", group=G_SIG, tooltip="Stricter: require STRUCTURED (not just not-random).") int i_sig_rsi_len = input.int(14, "RSI Length (OB/OS)", group=G_SIG, minval=2) float i_sig_ob = input.float(70.0, "Overbought level (≥)", group=G_SIG, step=1.0) float i_sig_os = input.float(30.0, "Oversold level (≤)", group=G_SIG, step=1.0) string i_sig_htf1 = input.timeframe("60", "HTF 1 (H1)", group=G_SIG) string i_sig_htf2 = input.timeframe("240", "HTF 2 (H4)", group=G_SIG) float i_sig_mc_tol = input.float(0.0, "MC band edge tolerance ($)", group=G_SIG, step=0.1, minval=0.0, tooltip="How far inside/outside the MC R1/S1 band still counts as 'at edge'. 0 = exact edge.") float i_sig_lvl_atr = input.float(0.5, "Significant-level proximity (xATR14)", group=G_SIG, step=0.05, tooltip="Price must be within this × ATR of a significant level (AMT VWMA value band / RQ-Kernel).") int i_sig_need_of = input.int(1, "Min order-flow confirms (1-3)", group=G_SIG, minval=1, maxval=3, tooltip="Need at least this many of: rejection · iceberg · delta direction.") int i_sig_gap = input.int(5, "Min bars between signals", group=G_SIG, minval=1, maxval=50) bool i_sig_use_rq = input.bool(true, "Include RQ-Kernel as a level", group=G_SIG) color i_sig_buy_col = input.color(#00E676, "BUY Label Color", group=G_SIG) color i_sig_sell_col= input.color(#FF1744, "SELL Label Color", group=G_SIG) string i_sig_size = input.string("Normal", "Label Size", group=G_SIG, options=["Tiny","Small","Normal","Large"]) // ── ⑯ Triple MTF Conf Signal ────────────────────────────────────────────── const string G_TRI = "⑯ Triple MTF Conf Signal (M5+H1+H4 WMA-RSI + AMT Rejection)" bool i_tri_en = input.bool(true, "Enable Triple MTF Conf Signal", group=G_TRI, tooltip="★ CONF BUY : WMA(RSI) bearish on ALL 3 TFs + AMT rejection ↑ (wick below VAL, close above).\n★ CONF SELL: WMA(RSI) bullish on ALL 3 TFs + AMT rejection ↓ (wick above VAH, close below).\nOS : fast WMA(RSI(5),mw) < slow WMA(RSI(20),mw) AND slow < 50 at all 3 TFs.\nOB : fast > slow AND slow > 50.\nMatches MoConf v11 MLMI momentum direction (same RSI features, no state divergence).") bool i_tri_show_lbl = input.bool(true, " Show Labels (★ CONF BUY / SELL)", group=G_TRI) bool i_tri_show_shp = input.bool(true, " Show Arrows (plotshape)", group=G_TRI) string i_tri_m5_tf = input.timeframe("5", "Base TF (M5)", group=G_TRI, tooltip="Timeframe for the shortest momentum check. Default M5 — explicit, not chart-TF dependent.") string i_tri_htf1 = input.timeframe("60", "HTF 1 (H1)", group=G_TRI) string i_tri_htf2 = input.timeframe("240", "HTF 2 (H4)", group=G_TRI) int i_tri_mw = input.int(20, "Momentum Window (WMA length of RSI)", group=G_TRI, minval=5, maxval=100, tooltip="WMA length applied to both RSI(5) and RSI(20).\nDefault 20 = MoConf v11 momentumWindow.\nLarger → smoother, fewer signals. Smaller → faster, more noise.") float i_tri_os = input.float(40.0, "OS threshold (fast WMA RSI ≤)", group=G_TRI, step=1.0, minval=20.0, maxval=49.0, tooltip="Fast WMA(RSI(5),mw) must be below this at ALL 3 TFs for OS (BUY setup).\nDefault 40 — matches genuine MLMI kNN OS zone.\nRejects mildly bearish fast=41–49 that MLMI does NOT classify as OS.\nExample: fast=18 passes, fast=41 is rejected.") float i_tri_ob = input.float(60.0, "OB threshold (fast WMA RSI ≥)", group=G_TRI, step=1.0, minval=51.0, maxval=80.0, tooltip="Fast WMA(RSI(5),mw) must be above this at ALL 3 TFs for OB (SELL setup).\nDefault 60 — matches genuine MLMI kNN OB zone.\nRejects mildly bullish fast=51–59 that MLMI does NOT classify as OB.") int i_tri_gap = input.int(3, "Min bars between signals", group=G_TRI, minval=1, maxval=50) color i_tri_buy_col = input.color(color.new(#00E676, 0), "BUY Label Color", group=G_TRI) color i_tri_sell_col = input.color(color.new(#FF1744, 0), "SELL Label Color", group=G_TRI) // ── ⑰ ML YZ — Adaptive Volatility Bands ────────────────────────────────── const string G_YZ1 = "⑰ ML YZ — Yang-Zhang" const string G_YZ2 = "⑰ ML YZ — ML / kNN" const string G_YZ3 = "⑰ ML YZ — AMT Zones" const string G_YZ4 = "⑰ ML YZ — Display" bool i_yz_en = input.bool (false, "Enable ML YZ Bands", group=G_YZ1) int i_yz_len = input.int (20, "YZ Period", minval=5, maxval=300, group=G_YZ1) float i_yz_mult = input.float (1.5, "Band Multiplier",minval=0.1, step=0.1, group=G_YZ1) string i_yz_ma_type = input.string("KAMA", "Middle Band MA", options=["EMA","HMA","SMA","WMA","KAMA"], group=G_YZ1) int i_yz_ma_len = input.int (20, "MA Period", minval=5, maxval=200, group=G_YZ1) int i_yz_knn_k = input.int (5, "kNN — K Neighbors", minval=3, maxval=20, group=G_YZ2) int i_yz_knn_lb = input.int (100, "kNN — Lookback", minval=50,maxval=300,group=G_YZ2) bool i_yz_adapt = input.bool (true, "Adaptive Band Width", group=G_YZ2) float i_yz_mul_low = input.float (0.8, "Low-Vol Multiplier", minval=0.5,maxval=1.0,step=0.1,group=G_YZ2) float i_yz_mul_high = input.float (1.4, "High-Vol Multiplier",minval=1.0,maxval=2.0,step=0.1,group=G_YZ2) int i_yz_poc_len = input.int (50, "VA / POC Lookback", minval=10,maxval=200, group=G_YZ3) float i_yz_va_pct = input.float (70.0, "Value Area %", minval=50.0,maxval=95.0, group=G_YZ3) bool i_yz_show_va = input.bool (true, "Show Value Area", group=G_YZ3) bool i_yz_show_poc = input.bool (true, "Show POC (VWAP proxy)", group=G_YZ3) bool i_yz_col_bars = input.bool (false, "Color Bars by YZ State", group=G_YZ4, tooltip="Bar color override: Bull=green / Bear=red / Neutral=grey.\nDefault OFF — LiqHM already colours bars via Kalman direction.") bool i_yz_show_sig = input.bool (true, "Show YZ AMT Signals", group=G_YZ4) bool i_yz_show_lbl = input.bool (true, "Show YZ Regime Label", group=G_YZ4) // ── ⑱ HV-Pivot Levels + CLV-Delta (BigBeluga concept, display-only) ─────── const string G_HV = "⑱ HV-Pivot Levels (volume-gated S/R + CLV-CVD)" bool i_hv_en = input.bool (false, "Enable HV-Pivot Levels", group=G_HV, tooltip="Ports ONLY the volume-gated-pivot concept from BigBeluga's High-Volume Pivot S/R (not the box/CVD-polyline system).\nA pivot high/low is kept as an S/R level ONLY if the pivot bar traded on high volume.\nDisplay-only: draws one ray + a CVD label per level. Does not feed the ⑮/⑯/⑰ signals.\nDefault OFF.") int i_hv_res_len = input.int (144, "Resistance Pivot Length", minval=2, maxval=240, group=G_HV, tooltip="Bars required before AND after a swing high to confirm a resistance pivot (BigBeluga default 144). Larger = fewer, more structural levels. Confirms len bars late (non-repainting once confirmed).\nCapped at 240: the pivot needs 2×len bars of history and the indicator declares max_bars_back=500.") int i_hv_sup_len = input.int (144, "Support Pivot Length", minval=2, maxval=240, group=G_HV, tooltip="Bars required before AND after a swing low to confirm a support pivot.\nCapped at 240 (2×len must fit max_bars_back=500).") int i_hv_vol_ma = input.int (89, "Volume MA Length", minval=1, group=G_HV, tooltip="SMA length of volume used as the baseline for the high-volume test (BigBeluga default 89 in your setup).") float i_hv_vol_mult = input.float(1.5, "Volume Threshold Multiplier", minval=0.1, step=0.1, group=G_HV, tooltip="Pivot bar's volume must exceed SMA(volume, maLen) × this to qualify (your setup = 1.5). Higher = stricter = fewer levels.") int i_hv_keep = input.int (3, "Levels Kept Per Side", minval=1, maxval=15, group=G_HV, tooltip="Only the most-recent N resistance and N support levels are drawn; older ones are deleted. Caps object count (≤ 2×N lines + 2×N labels). Anti-bloat control.") bool i_hv_show_cvd = input.bool (true, "Show CVD Label (CLV×vol)", group=G_HV, tooltip="Label each level with its formation-window CVD, computed as CLV×volume ( ((C−L)−(H−C))/(H−L) × vol ) summed over the pivot window.\nPositive = accumulation into the level, negative = distribution. This is the CLV×vol fix vs the raw candle-direction proxy.") color i_hv_res_col = input.color(color.new(#2196F3, 0), "Resistance Color", group=G_HV) color i_hv_sup_col = input.color(color.new(#FFC13B, 0), "Support Color", group=G_HV) // ── ⑱ CVD-Confluence GATE (v18 — OPT-IN, changes entry logic, default OFF) ─ const string G_HVG = "⑱ HV-Pivot — CVD Confluence Gate (v18, default OFF)" bool i_hv_gate_sig = input.bool (true, "Gate ⑮ Confluence by CVD-level", group=G_HVG, tooltip="When ON, the ⑮ Confluence BUY/SELL fires ONLY if price is also at a CVD-confirmed HV-Pivot level (BUY→accumulation support, SELL→distribution resistance).\nWhen OFF (default) ⑮ is byte-for-byte the validated behaviour.\nAuto-relaxes to no-op unless ⑱ Enable HV-Pivot Levels is also ON.\n⚠ Changes entry logic — walk-forward OOS before any live use.") bool i_hv_gate_tri = input.bool (true, "Gate ⑯ Triple MTF by CVD-level", group=G_HVG, tooltip="Same CVD-level requirement applied to the ⑯ Triple MTF Conf signal. Default OFF.\n⚠ Changes entry logic — OOS before live.") float i_hv_gate_atr = input.float(0.5, "Level proximity (×ATR14)", minval=0.05, step=0.05, group=G_HVG, tooltip="Price must be within this × ATR(14) of the HV-level for the gate to allow the signal. Same units as the ⑮ significant-level proximity.") float i_hv_gate_cvd = input.float(0.0, "Min |CVD| to confirm level", minval=0.0, step=100.0, group=G_HVG, tooltip="Minimum formation CVD magnitude for a level to count: a support needs CVD ≥ +this, a resistance needs CVD ≤ −this.\n0 = sign only (any accumulation counts for support, any distribution for resistance). Raise to demand stronger accumulation/distribution.") // ═══════════════════════════════════════════════════════════════════════════ // §3 COLORS // ═══════════════════════════════════════════════════════════════════════════ color C_CYAN = color.new(#00BCD4, 0) color C_GOLD = color.new(#FFD700, 0) const color NEUTRAL_COLOR = #787b86 // ── ⑰ ML YZ colors ──────────────────────────────────────────────────────── const color YZ_BULL = #2DD204 const color YZ_BEAR = #D2042D const color YZ_NEUT = #B0B0B0 const color YZ_BLUE = #00BFFF // ═══════════════════════════════════════════════════════════════════════════ // §4 FUNCTIONS (HTF + Kalman + RQ-Kernel + Shannon Entropy + Monte Carlo) // ═══════════════════════════════════════════════════════════════════════════ formatDelta(float val) => string sign = val > 0 ? "+" : "" float absVal = math.abs(val) absVal >= 1000000 ? sign + str.format("{0,number,#.#}M", val / 1000000) : absVal >= 1000 ? sign + str.format("{0,number,#.#}K", val / 1000) : sign + str.tostring(val) drawHtfPattern(string name, float h, float l, float o, float c, int tStart, int tEnd, color col, bool isBullish) => string timeStr = str.format_time(tStart, "HH:mm", syminfo.timezone) string labelTxt = name + "\n" + timeStr int midTime = math.round((tStart + tEnd) / 2) int timeInset = math.round((tEnd - tStart) * 0.1) box.new(tStart, h, tEnd, l, xloc=xloc.bar_time, bgcolor=color.new(col, 90), border_color=color.new(col, 50), border_width=1) box.new(tStart + timeInset, math.max(o, c), tEnd - timeInset, math.min(o, c), xloc=xloc.bar_time, bgcolor=color.new(col, 60), border_color=color.new(col, 20), border_width=1) line.new(midTime, h, midTime, l, xloc=xloc.bar_time, color=color.new(col, 20), width=1) label.new(midTime, isBullish ? l : h, labelTxt, xloc=xloc.bar_time, yloc=yloc.price, color=#00000000, textcolor=col, style=isBullish ? label.style_label_up : label.style_label_down, size=size.small) // Kalman helper: custom EMA pine_ema(float src, float length) => float alpha = 2 / (length + 1) float sum = src sum := alpha * src + (1 - alpha) * nz(sum[1]) // Kalman helper: clamp klm_clamp(float x, float a, float b) => math.min(math.max(x, a), b) // Kalman core filter function calc_kalman(float src, float p_state, float p_cv, float R_raw, float Q_raw, float res_var, float q_ratio, float gate_mult) => float q_process = klm_clamp(nz(Q_raw, 0.1), 0.001, 10.0) * q_ratio float r_dynamic_floor = res_var * gate_mult float r_adaptive = math.max(nz(R_raw, 1.0), r_dynamic_floor) float current_p_cov = p_cv + q_process float k_gain = current_p_cov / (current_p_cov + r_adaptive + 1e-10) float next_state = nz(p_state, src) float next_cov = current_p_cov if not na(k_gain) next_state := next_state + k_gain * (src - next_state) next_cov := (1 - k_gain) * current_p_cov [next_state, next_cov] // RQ-Kernel function f_rq_kernel(float src, int h, float alpha, int len) => float _ws = 0.0 float _wv = 0.0 float _2ah2 = 2.0 * alpha * float(h) * float(h) for _i = 0 to len - 1 float _w = math.pow(1.0 + float(_i * _i) / _2ah2, -alpha) _wv += nz(src[_i]) * _w _ws += _w _ws > 0.0 ? _wv / _ws : src // Shannon Entropy function f_shannon_entropy(float src, int len, int n_bins) => float _hi = src float _lo = src for _k = 1 to len - 1 _hi := math.max(_hi, nz(src[_k], src)) _lo := math.min(_lo, nz(src[_k], src)) float _rng = math.max(_hi - _lo, syminfo.mintick * 10.0) float _step = _rng / float(n_bins) float _ent = 0.0 for _b = 0 to n_bins - 1 float _blo = _lo + _step * float(_b) float _bhi = _blo + _step int _cnt = 0 for _i = 0 to len - 1 float _v = nz(src[_i], src) if _v >= _blo and _v < _bhi _cnt += 1 float _p = float(_cnt) / float(len) if _p > 0.0 _ent -= _p * math.log(_p) / math.log(2.0) float _max = math.log(float(n_bins)) / math.log(2.0) _max > 0.0 ? _ent / _max : 0.5 // ── ⑭ Monte Carlo dashboard helpers (LuxAlgo) ───────────────────────────── var string mc_parsedDashboardPosition = switch mc_dashboardPositionInput MC_TOP_RIGHT => position.top_right MC_BOTTOM_RIGHT => position.bottom_right MC_BOTTOM_LEFT => position.bottom_left => position.top_right var string mc_parsedDashboardSize = switch mc_dashboardSizeInput MC_TINY => size.tiny MC_SMALL => size.small MC_NORMAL => size.normal MC_LARGE => size.large MC_HUGE => size.huge => size.normal mc_cell(table t_able, int column, int row, string data, color text_col = #FFFFFF, string align = text.align_right, color background = na, float height = 0) => t_able.cell(column, row, data, text_color = text_col, text_size = mc_parsedDashboardSize, text_halign = align, bgcolor = background, height = height) mc_divider(table t_able, int row, int lastColumn) => string rowDivider = '━━━━━━━━━━━━━━' t_able.merge_cells(0, row, lastColumn, row) mc_cell(t_able, 0, row, rowDivider, text_col = MC_BORDERS, align = text.align_center, height = 0.5) // ── ⑯ TF name helper ────────────────────────────────────────────────────── f_tri_tf_name(string tf) => switch tf "1" => "M1" "5" => "M5" "15" => "M15" "30" => "M30" "60" => "H1" "120" => "H2" "240" => "H4" "D" => "D1" "W" => "W1" => tf // ── ⑰ Yang-Zhang pure volatility estimator ──────────────────────────────── // σ²_YZ = σ²_OC + k·σ²_CO + (1-k)·σ²_RS // OC = overnight, CO = open-to-close, RS = Rogers-Satchell yzVol(int per) => float k = 0.34 / (1.34 + (per + 1.0) / math.max(per - 1.0, 1.0)) float lnOC = math.log(open / nz(close[1], close)) float lnCO = math.log(close / open) float lnHO = math.log(high / open) float lnLO = math.log(low / open) float rs = lnHO * (lnHO - lnCO) + lnLO * (lnLO - lnCO) float vOC = ta.variance(lnOC, per) float vCO = ta.variance(lnCO, per) float vRS = ta.sma(rs, per) math.sqrt(math.max(vOC + k * vCO + (1.0 - k) * vRS, 0.0)) // ── ⑰ Kaufman Adaptive MA ───────────────────────────────────────────────── // ER = net direction / path noise; SC = (ER*(fast-slow)+slow)² kamaCalc(float src, int len) => float fast = 2.0 / 3.0 float slow = 2.0 / 31.0 float dir = math.abs(src - nz(src[len], src)) float noise = math.sum(math.abs(src - nz(src[1], src)), len) float er = noise > 0.0 ? dir / noise : 0.0 float sc = math.pow(er * (fast - slow) + slow, 2.0) var float _kv = na _kv := na(_kv) ? src : _kv + sc * (src - _kv) _kv // ── ⑰ kNN regime classifier ─────────────────────────────────────────────── // 3-feature Euclidean kNN → Balance(1) / Neutral(0) / Imbalance(-1) knnRegime(float f1, float f2, float f3, float lbl_s, int k_n, int lb) => float[] dists = array.new_float(lb, 0.0) for i = 1 to lb float d = math.sqrt( math.pow(f1 - f1[i], 2.0) + math.pow(f2 - f2[i], 2.0) + math.pow(f3 - f3[i], 2.0)) array.set(dists, i - 1, d) float[] srt = array.copy(dists) array.sort(srt, order.ascending) float thr = array.get(srt, math.min(k_n - 1, array.size(srt) - 1)) float vote = 0.0 int cnt = 0 for i = 0 to lb - 1 if array.get(dists, i) <= thr and cnt < k_n float lbl = 0.0 if lbl_s[i + 1] > 0.65 lbl := -1.0 else if lbl_s[i + 1] < 0.35 lbl := 1.0 vote += lbl cnt += 1 vote > 0.0 ? 1 : vote < 0.0 ? -1 : 0 // ═══════════════════════════════════════════════════════════════════════════ // §5 GLOBAL TA PRECOMPUTE // ═══════════════════════════════════════════════════════════════════════════ // ── AMT ─────────────────────────────────────────────────────────────────── float _vol_ma50 = ta.sma(volume, 50) float _mass = _vol_ma50 > 0.0 ? volume / _vol_ma50 : 1.0 float _m_mean = ta.vwma(close, 50) float _m_dev = ta.stdev(close, 50) * 1.5 float _m_vah = _m_mean + _m_dev float _m_val = _m_mean - _m_dev float _tol_z = _m_dev * 0.1 // ── VP range ────────────────────────────────────────────────────────────── float _vp_top = ta.highest(i_vp_bars) float _vp_bot = ta.lowest(i_vp_bars) // ── Heatmap ─────────────────────────────────────────────────────────────── float _hm_vol = math.sum(volume, 10) float _hm_vol_max = ta.highest(_hm_vol, lookBack_hm) float _nVol = _hm_vol_max > 0 ? (_hm_vol / _hm_vol_max * 100) : 0.0 float _atr_hm = ta.atr(5) / 50 float _hm_atr_off = ta.highest(_atr_hm * _nVol, lookBack_hm) // ── 2-bar pivot detection ───────────────────────────────────────────────── float _h2 = ta.highest(2) float _l2 = ta.lowest(2) // ── Fix Window Detection ────────────────────────────────────────────────── // v22: LBMA auctions are 10:30 / 15:00 LONDON time and COMEX settles 13:30 NEW YORK — evaluate each in its own zone (DST-safe) int _fx_hm = (hour(time, "Europe/London") + i_fix_utc) * 100 + minute(time, "Europe/London") int _fx_ny = (hour(time, "America/New_York") + i_fix_utc) * 100 + minute(time, "America/New_York") bool _fx_am = _fx_hm >= 1000 and _fx_hm < 1030 bool _fx_pm = _fx_hm >= 1500 and _fx_hm < 1515 bool _fx_cme = _fx_ny >= 1320 and _fx_ny < 1330 // ── RSI + divergence pivots ─────────────────────────────────────────────── float rsiValue = ta.rsi(close, rsiLenInput) float phRsi = ta.pivothigh(rsiValue, lbLInput, lbRInput) float plRsi = ta.pivotlow(rsiValue, lbLInput, lbRInput) // ── ⑮ Multi-TF RSI for confluence signal (current TF + H1 + H4) ─────────── float sig_rsi_cur = ta.rsi(close, i_sig_rsi_len) float sig_rsi_h1 = request.security(syminfo.tickerid, i_sig_htf1, ta.rsi(close, i_sig_rsi_len), barmerge.gaps_off, barmerge.lookahead_off) float sig_rsi_h4 = request.security(syminfo.tickerid, i_sig_htf2, ta.rsi(close, i_sig_rsi_len), barmerge.gaps_off, barmerge.lookahead_off) // ── ⑯ Triple MTF WMA-RSI momentum ───────────────────────────────────────── // rq = fast = WMA(RSI(5), mw) rs = slow = WMA(RSI(20), mw) // OS: fast < slow AND slow < 50 (bearish momentum in bearish regime) // OB: fast > slow AND slow > 50 (bullish momentum in bullish regime) // Using same RSI features as MoConf v11 MLMI kNN (rsi_quick / rsi_slow), // computed directly — no kNN state divergence, no initialisation artefacts. [_tri_rq_m5, _tri_rs_m5] = request.security(syminfo.tickerid, i_tri_m5_tf, [ta.wma(ta.rsi(close, 5), i_tri_mw), ta.wma(ta.rsi(close, 20), i_tri_mw)], barmerge.gaps_off, barmerge.lookahead_off) [_tri_rq_h1, _tri_rs_h1] = request.security(syminfo.tickerid, i_tri_htf1, [ta.wma(ta.rsi(close, 5), i_tri_mw), ta.wma(ta.rsi(close, 20), i_tri_mw)], barmerge.gaps_off, barmerge.lookahead_off) [_tri_rq_h4, _tri_rs_h4] = request.security(syminfo.tickerid, i_tri_htf2, [ta.wma(ta.rsi(close, 5), i_tri_mw), ta.wma(ta.rsi(close, 20), i_tri_mw)], barmerge.gaps_off, barmerge.lookahead_off) string _tri_tf0n = f_tri_tf_name(i_tri_m5_tf) string _tri_tf1n = f_tri_tf_name(i_tri_htf1) string _tri_tf2n = f_tri_tf_name(i_tri_htf2) // ── HTF bar detection + data fetch ─────────────────────────────────────── bool htfNewBar = nz(ta.change(time(htfInput))) != 0 [hOpen, hHigh, hLow, hClose, hPrevOpen, hPrevClose, hTimeStart, hTimeEnd] = request.security(syminfo.tickerid, htfInput, [open[1], high[1], low[1], close[1], open[2], close[2], time[1], time_close[1]]) // ── Kalman EMA state measurement ────────────────────────────────────────── int qlen = 5 float ema1 = pine_ema(source, factor) float ema2 = pine_ema(ema1, factor2) // ── Kalman base filter state ────────────────────────────────────────────── var float kf_stateb = na var float p_covb = 1.0 float residualb = ema2 - nz(kf_stateb[1], ema2) float _atr14_g = ta.atr(14) // v22: single global ATR14 (was also called inside barstate.islast → na label) float vol_baseb = math.max(_atr14_g, 1e-6) float residual_varianceb = math.pow(residualb, 2) / math.pow(vol_baseb, 2) float R_rawb = nz(ta.rma(residual_varianceb, r_ratiob), 1.0) float Q_rawb = nz(ta.rma(residual_varianceb, qlen), 0.1) [new_valb, new_covb] = calc_kalman(ema2, kf_stateb, p_covb, R_rawb, Q_rawb, residual_varianceb, q_ratiob, r_gate_multb) kf_stateb := new_valb p_covb := new_covb float smoothb = pine_ema(kf_stateb, 3) // ── Kalman fast filter state ────────────────────────────────────────────── var float kf_states = na var float p_covs = 1.0 float residuals = ema2 - nz(kf_states[1], ema2) float vol_bases = math.max(ta.atr(14), 1e-6) float residual_variances = math.pow(residuals, 2) / math.pow(vol_bases, 2) float R_raws = nz(ta.rma(residual_variances, r_ratios), 1.0) float Q_raws = nz(ta.rma(residual_variances, qlen), 0.1) [new_vals, new_covs] = calc_kalman(ema2, kf_states, p_covs, R_raws, Q_raws, residual_variances, q_ratios, r_gate_mults) kf_states := new_vals p_covs := new_covs float smooths = pine_ema(kf_states, 5) // ═══════════════════════════════════════════════════════════════════════════ // §5b NEW v4 COMPUTATIONS // ═══════════════════════════════════════════════════════════════════════════ // ── Hilbert Transform Dominant Cycle (Ehlers Homodyne Discriminator) ────── var float _ht_smooth = 0.0 var float _ht_dtr = 0.0 var float _ht_I1 = 0.0 var float _ht_Q1 = 0.0 var float _ht_jI = 0.0 var float _ht_jQ = 0.0 var float _ht_I2 = 0.0 var float _ht_Q2 = 0.0 var float _ht_Re = 0.0 var float _ht_Im = 0.0 var float _ht_per = 20.0 var float _ht_dc = 20.0 float _ht_coef = 0.075 * nz(_ht_dc, 20.0) + 0.54 _ht_smooth := (4.0*close + 3.0*nz(close[1]) + 2.0*nz(close[2]) + nz(close[3])) / 10.0 _ht_dtr := (0.0962*_ht_smooth + 0.5769*nz(_ht_smooth[2]) - 0.5769*nz(_ht_smooth[4]) - 0.0962*nz(_ht_smooth[6])) * _ht_coef _ht_I1 := nz(_ht_dtr[3]) _ht_Q1 := (0.0962*_ht_dtr + 0.5769*nz(_ht_dtr[2]) - 0.5769*nz(_ht_dtr[4]) - 0.0962*nz(_ht_dtr[6])) * _ht_coef _ht_jI := (0.0962*_ht_I1 + 0.5769*nz(_ht_I1[2]) - 0.5769*nz(_ht_I1[4]) - 0.0962*nz(_ht_I1[6])) * _ht_coef _ht_jQ := (0.0962*_ht_Q1 + 0.5769*nz(_ht_Q1[2]) - 0.5769*nz(_ht_Q1[4]) - 0.0962*nz(_ht_Q1[6])) * _ht_coef _ht_I2 := 0.2*(_ht_I1 - _ht_jQ) + 0.8*nz(_ht_I2[1]) _ht_Q2 := 0.2*(_ht_Q1 + _ht_jI) + 0.8*nz(_ht_Q2[1]) _ht_Re := 0.2*(_ht_I2*nz(_ht_I2[1]) + _ht_Q2*nz(_ht_Q2[1])) + 0.8*nz(_ht_Re[1]) _ht_Im := 0.2*(_ht_I2*nz(_ht_Q2[1]) - _ht_Q2*nz(_ht_I2[1])) + 0.8*nz(_ht_Im[1]) if _ht_Im != 0.0 and _ht_Re != 0.0 _ht_per := 2.0 * math.acos(-1.0) / math.atan(_ht_Im / _ht_Re) if _ht_per > 1.5 * nz(_ht_per[1], 20.0) _ht_per := 1.5 * nz(_ht_per[1], 20.0) if _ht_per < 0.67 * nz(_ht_per[1], 20.0) _ht_per := 0.67 * nz(_ht_per[1], 20.0) _ht_per := math.max(6.0, math.min(50.0, _ht_per)) _ht_dc := 0.2*_ht_per + 0.8*nz(_ht_dc[1]) int dc_int = math.max(6, math.min(50, math.round(_ht_dc))) // DC adaptive: HM lookback only — VP always uses user's full i_vp_bars setting // VP needs maximum history for accurate POC/VAH/VAL; shrinking it via DC would // cause the exact v3→v4 regression visible in the before/after screenshots. int hm_lb_adapt = math.max(30, math.min(lookBack_hm, dc_int * i_dc_hm_mult)) int hm_lb_eff = i_dc_en ? hm_lb_adapt : lookBack_hm int vp_lb_eff = i_vp_bars // always full user input — never DC-reduced // ── RQ-Kernel ───────────────────────────────────────────────────────────── float rq_fast = i_rq_en ? f_rq_kernel(close, i_rq_h_fast, i_rq_alpha, i_rq_len) : na float rq_slow = i_rq_en ? f_rq_kernel(close, i_rq_h_slow, i_rq_alpha, i_rq_len) : na // ── Shannon Entropy ─────────────────────────────────────────────────────── float _ent_norm = i_ent_en ? f_shannon_entropy(close, i_ent_len, i_ent_bins) : 0.5 bool _ent_struct = _ent_norm < i_ent_str_thr bool _ent_random = _ent_norm > i_ent_ran_thr string _ent_str = _ent_struct ? "STRUCTURED" : _ent_random ? "RANDOM" : "TRANSITIONAL" color _ent_col = _ent_struct ? color.new(#00E676,0) : _ent_random ? color.new(#FF1744,0) : color.new(#FFD700,0) int _ent_tr_add = i_ent_en ? int(_ent_norm * 60.0) : 0 // ── VPIN Proxy ──────────────────────────────────────────────────────────── float _vp_rng_b = math.max(high - low, syminfo.mintick) float _vpin_bvol = volume * ((close - low) / _vp_rng_b) float _vpin_svol = volume * ((high - close) / _vp_rng_b) float _vpin_imb = math.abs(_vpin_bvol - _vpin_svol) float _vpin_smi = ta.sma(_vpin_imb, i_vpin_len) float _vpin_smt = math.max(ta.sma(volume, i_vpin_len), 1.0) float _vpin_val = math.min(_vpin_smi / _vpin_smt, 1.0) bool _vpin_toxic = i_vpin_en and _vpin_val >= i_vpin_tox bool _vpin_blncd = i_vpin_en and _vpin_val <= i_vpin_bal float _vpin_net = ta.sma(_vpin_bvol - _vpin_svol, i_vpin_len) bool _vpin_tox_bull = _vpin_toxic and _vpin_net > 0.0 bool _vpin_tox_bear = _vpin_toxic and _vpin_net < 0.0 string _vpin_str = _vpin_toxic ? (_vpin_tox_bull ? "TOXIC-BUY" : "TOXIC-SELL") : _vpin_blncd ? "BALANCED" : "NEUTRAL" color _vpin_col = _vpin_tox_bull ? i_vpin_tox_col : _vpin_tox_bear ? i_vpin_tox_col : _vpin_blncd ? i_vpin_bal_col : color.new(#607D8B,0) // ═══════════════════════════════════════════════════════════════════════════ // §5c ⑭ MONTE CARLO — CORE LOGIC (LuxAlgo, namespaced) // ═══════════════════════════════════════════════════════════════════════════ var array mc_logReturns = array.new() var array mc_simReturns = array.new() var array mc_regimes = array.new() var array mc_polylines = array.new() var array mc_srLines = array.new() var array