OPEN-SOURCE SCRIPT

Markov Level Validity Engine [PhenLabs]

388
📊 Markov Level Validity Engine [PhenLabs]

Version: PineScript™ v6

📌 Description
Every support and resistance tool draws levels. Few tell you whether a level is still worth trusting the next time price comes back to it. The Markov Level Validity Engine answers that question with your chart’s own history. Each time price tests a swing level, the test is resolved as a HOLD (price reacts away), a BREAK (price closes through) or a STALL (nothing decisive happens). The engine records every outcome and learns how levels on this symbol and timeframe usually behave.

The key insight is that a level’s next test depends on what happened at its last test. A fresh level, a level that just held, and a broken level that flipped roles (support turned resistance) behave differently. So does a level approached slowly versus one hit with speed. MLVE keeps a separate tally for each of these situations. When a new test starts, it reads the matching tally and shows you the empirical chance of a hold, a break or a stall, together with the sample size behind it.

Signals fire only when the reaction you actually see on the candle agrees with what the history says is likely, and only when that history beats the chart’s own average. The result is a level tool that tells you when to fade, when to trade the break, and when to skip. No manual anchors, no setup, works on every plan.

🚀 Points of Innovation
  • Level tests are modelled as a Markov chain: the next outcome is conditioned on the level’s previous outcome, stored in a Pine matrix of transition counts.
  • Approach speed is a second conditioning dimension, so a fast push into a level is never pooled with a slow drift into it.
  • Probabilities come from the current chart only, with Laplace smoothing and a visible sample size. No fixed scores, no curve-fit weights.
  • Signals require two agreements: the candle’s reaction (rejection close or break close) and a historical probability that clears both your threshold and the chart-wide base rate.
  • Role reversal is first-class: a broken level flips side and its next test is read from the dedicated “after break” rows.
  • Theme-adaptive dashboard that reads cleanly on dark and light charts, laid out to stay legible if you move it into the new bottom panel.


🔧 Core Components
  • Level Registry: confirmed swing highs and lows become resistance and support, capped per side so the chart stays clean. The oldest level on a side is retired when a new one forms, and levels retire after six resolved tests.
  • Test Lifecycle: a test starts when price approaches a level from its origin side and touches it. It resolves as BREAK (close beyond the level plus a buffer), HOLD (move away of at least the reaction size in ATR) or STALL (the test window runs out).
  • Transition Matrix: a 6 × 3 matrix counts outcomes for every combination of previous outcome (first test / after hold / after break) and approach speed (slow / fast).
  • Signal Gate: compares the live reaction with the matching row’s probability, the minimum probability, the minimum sample size and the chart’s base rate.
  • Plan Projection: the target is the nearest active opposing level. Invalidation sits one break buffer beyond the signal level.


🔥 Key Features
  • HOLD and BREAK signals in both directions, each firing at most once per test.
  • Per-level tags at the right edge showing side, hold probability for its next test and sample size, for example “S · H 64% · n 37”.
  • Ray opacity scales with hold probability, so the strongest levels stand out at a glance.
  • LEARNING state until a row has enough samples. The script tells you when it does not know yet instead of guessing.
  • Optional fragile-test markers when a test starts on a level whose history favours a break.
  • Signal Types selector: Hold + Break, Hold only, or Break only.
  • Three alert conditions (bull, bear, any) and three Pine Screener columns.


🎨 Visualization
  • Level rays: short dashed rays from the pivot to a few bars past price. Teal for support, coral for resistance. They turn solid after a role reversal, and stronger levels are more opaque.
  • Right-edge tags: side, hold probability for the next test and sample count.
  • Signal labels: placed off the candle (below for bullish, above for bearish) reading HOLD or BREAK with the probability. Hover for level, target and invalidation.
  • Plan lines: one dotted target line and one dashed invalidation line for the latest signal, 15 bars long.
  • Dashboard: nearest support and resistance with their prior outcome, Hold / Break / Stall percentages with n, a verdict (VALID, FRAGILE, UNDECIDED or LEARNING), last signal with target and invalidation, total tests with base hold rate, and the data mode.


📖 Usage Guidelines
Levels
  • Pivot Length — Default: 5 — Range: 2-30 — Bars on each side that confirm a swing. Higher values give fewer, more significant levels that appear later.
  • Levels per Side — Default: 3 — Range: 1-5 — Live levels kept for support and for resistance.

Test Model
  • Test Window (bars) — Default: 12 — Range: 3-100 — Bars a test has to resolve before it counts as a STALL.
  • Hold Reaction (ATR) — Default: 1.0 — Range: 0.2-5.0 — Move away from the level needed to count a HOLD. Raise it for stricter holds.
  • Break Buffer (ATR) — Default: 0.25 — Range: 0.05-2.0 — How far beyond the level a candle must close to count a BREAK. Also sets the invalidation distance.
  • Min Probability — Default: 0.55 — Range: 0.34-0.95 — Minimum historical probability for a signal. The row must also beat the chart’s base rate.
  • Min Samples per Row — Default: 20 — Range: 5-500 — Resolved tests a row needs before it can signal.

Signals
  • Signal Types — Default: Hold + Break — Choose fades, breakouts or both.
  • Show Target / Invalidation — Default: on — Draws the latest signal’s plan.
  • Show Fragile-Test Markers — Default: off — Small x when a test begins on a level that historically tends to break.

Display
  • Show Dashboard — Default: on.
  • Table Size — Default: Normal — Small, Normal or Large. Only shown when the dashboard is on.
  • Bull / Support and Bear / Resistance colors — Default: teal and coral.


✅ Best Use Cases
  • Deciding whether to fade a test of a support or resistance level or wait for the break.
  • Trading role reversals: broken levels retested from the other side, read from their own history.
  • Skipping trades at levels whose history is undecided or still learning.
  • Screening a watchlist for symbols sitting on a level with a high hold probability.
  • Works on crypto, forex, indices, futures and stocks, on any timeframe with enough history.


⚠️ Limitations
  • Swing levels are confirmed Pivot Length bars after the swing, which is the price of not repainting.
  • Probabilities describe what has happened on the loaded history of this chart. They are not guarantees, and they change as new tests resolve.
  • A row needs Min Samples resolved tests before it can signal, so short histories and very high timeframes stay in LEARNING longer.
  • A BREAK signal says a break was the historically likely outcome. It does not measure how far the break will travel. Use the target and invalidation for that.
  • Gaps and very low-liquidity symbols produce fewer clean tests.


💡 What Makes This Unique
  • Measured, not scored: the dashboard shows empirical frequencies and their sample size instead of a hand-weighted 0-100 rating.
  • Memory per level: each level carries its last outcome, so a retest after a break is read differently from a first test.
  • Honest uncertainty: LEARNING, UNDECIDED and n are always visible.


⚙️ Under the Hood
  • Matrix transition counts: a persistent 6 × 3 Pine matrix stores HOLD, BREAK and STALL counts for each previous-outcome × approach-speed state. Reading a row gives a conditional probability no static level grade can provide.
  • Laplace-smoothed probabilities: P = (count + 1) / (row total + 3), so small rows are pulled toward one-third instead of jumping to 0% or 100%.
  • Out-of-sample by construction: a test’s probability is read before that test is counted, and all state changes run on confirmed bars only. No lookahead, no request.* calls, no repainting.
  • User-defined level type: each level stores price, side, previous outcome, test count, pending-test state and its drawing handles, so rays and tags update in place and are deleted with the level.
  • Theme-adaptive colors: dashboard text and frames use chart.fg_color and chart.bg_color, so the table reads correctly on dark and light themes.
  • Data mode / plan note: OHLC only. Every TradingView plan, including free, gets the full engine. The dashboard’s Data row shows “OHLC · ALL PLANS · closed bars”.
  • Screener & alerts: Pine Screener columns “Support P(hold) %”, “Resistance P(hold) %” and “Signal code” (+2 bull break, +1 bull hold, -1 bear hold, -2 bear break, 0 none). Alert conditions: MLVE Bull signal, MLVE Bear signal, MLVE Any signal.


🔬 How It Works
  • Levels: confirmed pivot highs become resistance and pivot lows become support, up to the per-side cap.
  • Test start: when price approaches a level from its origin side and touches it, a test begins. The engine records which row it belongs to: previous outcome × slow or fast approach (5-bar move of at least 1 ATR toward the level).
  • Read the model: the row’s HOLD, BREAK and STALL probabilities come from previously resolved tests only.
  • Signal: a HOLD signal fires on a rejection close when P(hold) clears Min Probability and the base hold rate. A BREAK signal fires on a close beyond the buffer when P(break) clears Min Probability and the base break rate. Opposite signals on the same bar cancel each other.
  • Resolve: the test is counted as BREAK, HOLD or STALL, in that priority. A break flips the level’s role, and its next test is read from the after-break rows.
  • Plan: the latest signal projects a target at the nearest opposing level and an invalidation one buffer beyond the signal level.


💡 Note:
Load as much history as your plan allows and wait for the Model row to show a healthy test count before relying on signals. The verdict row is the quickest read: VALID means the level’s next test historically holds more often than your threshold, FRAGILE means it tends to break, and UNDECIDED or LEARNING means stand aside. Pair signals with your own risk management and market context. This tool is an analytical aid, not financial advice.

คำจำกัดสิทธิ์ความรับผิดชอบ

ข้อมูลและบทความไม่ได้มีวัตถุประสงค์เพื่อก่อให้เกิดกิจกรรมทางการเงิน, การลงทุน, การซื้อขาย, ข้อเสนอแนะ หรือคำแนะนำประเภทอื่น ๆ ที่ให้หรือรับรองโดย TradingView อ่านเพิ่มเติมใน ข้อกำหนดการใช้งาน