Auto Trendline Break Quality [AGPro Series]Auto Trendline Break Quality
🔹 OVERVIEW
Auto Trendline Break Quality is a structural break-quality engine. It automatically detects bullish and bearish trendlines from swing pivots, monitors every break event in real time, and assigns each break a 0–100 quality score derived from four independent quantitative factors. The tool separates Major (structural) and Minor (tactical) trendlines, so the same break can be evaluated against multiple layers of market structure at once.
The script is purpose-built to answer the single most practical question a price-action trader faces at a trendline break: "Is this break real, or is it a fake-out?"
🧭 UNIQUE EDGE
Most trendline scripts either draw trendlines or flag a break. They stop there. This indicator continues where they stop — and measures the break.
Key differentiators:
• Four-factor composite quality score (Volume · Slope · Impulse · Retest) calibrated to ATR, so the scoring is consistent across assets and timeframes.
• Major/Minor trendline hierarchy. A Major structural break automatically earns a score bonus and is visually flagged with a "MAJ" tag, so structural breaks are never confused with noise breaks.
• State-based visual language. Active trendlines render in a neutral tone. On break, the trendline transitions to the break-direction color (bullish break = bull color, bearish break = bear color), so the chart communicates state without ambiguity.
• Retest logic built directly into the score. A break that is retested and holds within the defined window receives an upgrade; a failed retest downgrades the score. The chart label reflects the final, updated quality.
• Optional zone-band rendering around Major trendlines, letting the user see each structural line as a reaction zone rather than a bare line.
• Label confluence grouping to prevent chart clutter when multiple breaks occur near the same price level.
⚙️ METHODOLOGY
1) Trendline detection
Pivots are identified using standard pivot-high and pivot-low logic with two configurable lookbacks — one for Major trendlines and one for Minor. A new trendline is validated between the two most recent same-side pivots when the slope (ATR-normalized) exceeds the minimum threshold. Nearly-flat trendlines are rejected by design.
2) Break detection
A trendline is considered broken when the current candle closes on the opposite side of the projected line while the previous candle closed on the valid side. This one-bar confirmation rule avoids intra-bar flicker.
3) Quality scoring (0–100)
• Volume expansion vs 20-bar average — up to 25 points
• ATR-normalized slope steepness — up to 20 points
• Break-bar impulse measured in ATR from the line — up to 25 points
• Retest base score — 18 points, upgraded by +15 on a held retest, or reduced by 10 on a failed retest
• Major trendline bonus — +10 points
4) Retest tracking
After a break, the script watches a configurable window (default 3–8 bars) for price to return to the broken trendline within an ATR tolerance. Held retests and failed retests are tracked independently and reflected in the panel's Retest Held Rate. Retest markers are offset from the trendline in ATR units to prevent overlap with candles.
📊 SIGNALS & STATES
• Break label: "BREAK Q: · " and an optional "MAJ" tag for Major trendlines. Label color tier: High quality renders in full state color, Medium quality in neutral amber, Low quality in a muted tone.
• Retest marker: Small circular marker with "retest held" or "retest failed" text, offset from the trendline for clarity.
• Break bar border: Optional candle-border color that reflects break direction.
• Panel: Active trendlines per side, last break score and direction, overall break-direction breakdown, retest held rate, quality distribution (High/Medium/Low), total breaks tracked, and the current detection mode.
• Alerts: "High Quality Trendline Break" and "Major Trendline Break" — both standard alertcondition entries.
🎛️ KEY INPUTS
• Major / Minor Pivot Length — controls how many bars each side of a pivot must be a local extreme.
• Show Minor Trendlines — toggle tactical layer on top of structural layer.
• Max Active Trendlines per Side — caps the chart clutter.
• Volume Spike Threshold (x Avg) — ratio at which a volume expansion is considered full.
• Retest Min/Max Bars — bar range for a valid retest.
• Retest Tolerance (ATR) — how close price must come to the broken line to count as a retest.
• High / Medium Quality Thresholds — cutoffs for the three quality tiers (defaults: 70 / 50).
• Show Trendline Zone Band — renders a subtle ATR-based band around Major trendlines.
• Zone Band Width (ATR) — controls the thickness of the zone band.
• Label Confluence Grouping (ATR) — merges break labels that land within this ATR distance on nearby bars.
• Label Offset (ATR) — vertical padding so labels never embed in candles.
• Label / Panel / Help font sizes — all default to Normal.
• Panel Position and Theme — six positions, Dark/Light theme.
🧩 HOW TO USE
The indicator is a decision-support layer, not a standalone trading system.
• Treat a break with Q ≥ 70 and a "MAJ" tag as a structural event worth reviewing the higher-timeframe bias for.
• Use the retest window as a patience filter. A break with Q 55–69 that retests and holds often upgrades to a higher-quality setup after the retest.
• Failed retests are not "bad" — they are information. A failed retest on a low-quality break is a strong hint that the break was noise.
• The neutral-color active trendlines are intentional — they tell you where structure exists without biasing your read. Color appears only when structure breaks.
• Combine with your own confluence (volume profile, horizontal support/resistance, higher-timeframe trend). The script does not enter trades; it tells you how reliable a break looks at the moment it happens.
⚠️ LIMITATIONS & TRANSPARENCY
• Quality scores describe historical pattern behavior. They are not predictive probabilities.
• Trendlines are generated from pivots; the final pivot is always confirmed after the pivot-length bars have elapsed. This is standard pivot behavior and is not a repaint of historical marks — past labels remain fixed once a break bar closes.
• The script draws up to the platform's line/label limits. Older trendlines are removed when the active cap is reached.
• Parameter defaults target 4H–1D charts; lower timeframes benefit from smaller pivot lengths and tighter retest windows.
📜 RISK DISCLOSURE
This script is an analytical tool. It does not provide financial advice, investment recommendations, or a trading strategy. Past performance of any pattern, including trendline breaks, does not guarantee future results. Always perform your own analysis and apply proper risk management before making any trading decision. Indicator

Market Structure Trend Matrix [BigBeluga]Market Structure Trend Matrix is a comprehensive technical analysis framework engineered for traders who demand precision in identifying market regimes and trend expansions. By integrating automated Market Structure (MS) detection with volatility-adjusted risk parameters, this indicator provides a systematic roadmap for navigating complex price action.
The tool focuses on the Change of Character (ChoCh) —the critical moment when a previous trend structure breaks and a new directional bias begins.
🔵 ARCHITECTURE & CORE LOGIC
Automated Structure Mapping: The engine uses a sophisticated pivot-detection algorithm (MS Length) to scan for institutional-grade swing highs and lows. It ignores minor retail noise, drawing structural lines only when significant supply or demand zones are breached.
The ChoCh Engine: When price crosses a recent pivot high or low, the indicator prints a "ChoCh" label. This represents a fundamental shift in market sentiment, signaling that the current trend has likely terminated and a new cycle has begun.
Infinite Expansion Targets: One of the most advanced features of the Matrix is its ability to project sequential, infinite targets. These levels are not static; they are calculated using Average True Range (ATR) multipliers, meaning they expand and contract based on current market volatility.
Volatility-Anchored Trailing Stop: To ensure professional-grade risk management, the indicator plots a dynamic ATR Trailing Stop . This line acts as a "ratchet" mechanism—it moves closer to price during the trend expansion but stays firm during minor pullbacks, providing a clear exit point if the trend truly fails.
🔵 ADVANCED FEATURES & UPDATES
Target History Control: This latest version includes a Show History toggle. You can choose to keep the chart clean by only displaying the Active Target , or you can enable history to see a visual record of every target hit during the trend, complete with historical percentage labels.
Dynamic Trailing Stop Visibility: The Show Trailing Stop feature allows you to toggle the visibility of the ATR stop line and its associated background fill, giving you full control over the visual "weight" on your workspace.
Percentage Profit Labels: Every time price reaches an expansion target, the script automatically plots a label showing the percentage gain from the initial ChoCh entry point.
Volatility-Adjusted Spacing: Both the trailing stop and the target steps use ATR-based calculations. This ensures that the indicator remains effective across all asset classes—from volatile Cryptocurrencies to stable Forex pairs.
🔵 HOW TO INTERPRET THE MATRIX
Bullish State (Green Matrix): Activated when price breaks above a major Pivot High. The indicator projects upward expansion targets and maintains a trailing stop below the price.
Bearish State (Pink Matrix): Activated when price breaks below a major Pivot Low. The indicator projects downward targets and maintains a trailing stop above the price.
The Target Cascade: As price hits a target, the indicator instantly projects the next level. If price continues to expand, you will see a "cascade" of dashed lines, each representing a deeper extension into the trend.
🔵 APPLICATION IN TRADING
Scalping & Day Trading: Set the Market Structure Length to a lower value (e.g., 5-8) to capture fast intraday pivots and expansion moves on 1m or 5m charts.
Swing Trading: Use a higher length (e.g., 15-20) to identify macro structure shifts on Daily or H4 timeframes, allowing the ATR targets to guide your long-term profit-taking.
Risk-Reward Management: The distance between the ChoCh Entry and the ATR Trailing Stop provides an objective risk measurement, while the sequential targets provide clear reward milestones.
Filtering False Breaks: By using an ATR Multiplier for the trailing stop, the Matrix avoids many of the common "whipsaws" found in standard trend-following systems.
🔵 CONCLUSION
Market Structure Trend Matrix is more than a signal tool; it is a visual framework for objective decision-making. By anchoring your trading to structural pivots and volatility-based targets, you remove the guesswork from trend following. Whether you are looking for a clean "ChoCh" entry or a systematic way to trail your profits during a massive expansion, the Trend Matrix provides the data and clarity required to trade like a professional. Indicator

Trend Strength Meter [AGPro Series]Trend Strength Meter
⚡ OVERVIEW
Trend Strength Meter is a multi-factor composite oscillator that quantifies how strong a directional trend actually is, on a single 0-to-100 score. It merges five independent trend dimensions (ADX, slope angle, momentum ROC, moving-average alignment, and pullback depth) into one weighted reading, then classifies the market into three clear states: Strong Trend (80+), Mild Trend (50-80), and Weak / Range (<50). The goal is to give a trader the answer to one of the most common daily questions in technical analysis: "Is the trend strong enough to act on right now, or is it fading?"
The indicator is built for discretionary and systematic traders who want a single, normalized number instead of reading half a dozen separate trend tools. It is scale-invariant (ATR-normalized) and works across timeframes and instruments.
🎯 UNIQUE EDGE
Trend-strength tools usually give a single-factor reading (for example, ADX alone) which can be misleading. ADX can be high during range contractions, slopes can spike during noise, MA stacks can be aligned while price sits deep in pullback. This indicator fuses all five dimensions so that no single factor can dominate the score without confirmation from the others.
Three design choices set it apart:
1. Weighted multi-factor composite. Every factor is independently normalized to 0-100, then combined with user-adjustable weights that auto-normalize. A Strong reading therefore requires broad agreement across independent trend dimensions, not just one signal firing.
2. Dominant Factor readout. The information panel shows which of the five factors is contributing most to the current score, so the trader understands why the score is where it is. A score of 84 driven by ADX and a score of 84 driven by Alignment are structurally different markets, and the readout makes that visible.
3. Historical context built in. The panel exposes Historical Max Score over a configurable lookback window, and Strong-Trend Duration (how many bars the score has held above the Strong threshold). Both of these help gauge trend maturity and exhaustion risk.
📊 METHODOLOGY
The composite score is built from five independently scored factors, each normalized to 0-100:
• Factor 1 — ADX. Directional movement strength from the standard DMI/ADX system, linearly mapped so that ADX = 60 maps to a score of 100.
• Factor 2 — Slope Angle. The slope of an EMA over its length window, normalized by ATR to be scale-invariant, then converted to a 0-100 score via an arctangent curve. High slope in either direction yields a high score.
• Factor 3 — Momentum ROC. Rate of Change normalized by ATR and converted to a bounded 0-100 value. Captures impulse magnitude independent of price scale.
• Factor 4 — MA Alignment. Stacked EMA alignment across Fast / Mid / Slow timeframes, plus price position relative to the fast MA. Full bullish or bearish stack yields 100; partial stacks are scored proportionally (70, 40, or 15).
• Factor 5 — Pullback Depth. Distance from the nearest recent extreme (highest high or lowest low over lookback) measured in ATR units. Shallow pullback = strong trend = high score.
Each factor is multiplied by its weight, summed, and divided by total weight to produce the final 0-100 score. All five weights are independently adjustable and auto-normalize, so changing one weight does not force manual rebalancing of the others.
Directional bias (Bull / Bear / Range) is determined by the combination of DMI crossover state and close-vs-mid-MA position. State color shifts between strong bull green, strong bear magenta, neutral yellow, and weak gray based on score plus direction.
🔥 VISUAL SYSTEM
Six coordinated visual elements deliver the information without clutter:
• Score histogram on the sub-panel, colored per bar by that bar's own score level (green for Strong, yellow for Mild, gray for Weak / Range). Each historical bar shows its true state at the time, not the current state.
• Horizontal reference lines at the Strong (green) and Mild (yellow) thresholds on the sub-panel.
• Historical Max step line in indigo accent, showing the highest score reached within the lookback window, so past trend peaks are immediately visible.
• Mini Gauge on the right edge of the sub-panel. A compact vertical meter split into two halves: left half shows the fixed 0-100 zone reference (Weak / Mild / Strong), right half fills up to the current score, with a bold needle line marking the exact level.
• Price badge floating above the last candle, showing "TSM " so the reading is visible without needing to look at the panel.
• Information panel on the price chart with seven rows: Score, State, Direction, Dominant Factor, Historical Max, and Strong Bars duration.
🧭 SIGNALS AND ALERTS
Three built-in alerts:
• Strong Bull Entry — Score crosses above the Strong threshold while directional bias is Bull.
• Strong Bear Entry — Score crosses above the Strong threshold while directional bias is Bear.
• Trend Fade — Score drops below the Mild threshold, indicating the trend is weakening.
All alerts fire once per bar close, so there is no intra-bar repainting.
🧮 KEY INPUTS
Core Settings
• ADX Length, Slope MA Length, Momentum ROC Length, MA Alignment Fast / Mid / Slow, Pullback ATR Length
• Score Smoothing (EMA applied to score for optional overlay line)
• Strong Threshold (default 80), Mild Threshold (default 50), Historical Lookback (default 100 bars)
Factor Weights (auto-normalized)
• ADX 30, Slope 20, Momentum 20, Alignment 20, Pullback 10
Visual
• Badge toggle, Background tint toggle, Reference lines toggle, Mini Gauge toggle, Historical Max line toggle, Smoothed Score line toggle, Label size, Badge ATR offset
Panel
• Show / hide, Position (6 anchors), Theme (Dark / Light), Font size
📈 HOW TO USE
1. Add the indicator to any chart and any timeframe. Defaults are calibrated for 4H / Daily; for lower timeframes consider reducing the ADX and ROC lengths.
2. Use the 0-100 score as a regime filter. Many trend-following setups perform better when the score is above 50, and breakout / continuation setups perform best when the score is crossing above 80 with a clear Bull or Bear direction.
3. Watch the Dominant Factor. A score of 85 driven primarily by Momentum may fade fast; the same score driven by Alignment tends to be more structural.
4. Use Historical Max and Strong Bars to gauge maturity. A Strong-Bars reading of 30+ on a daily chart often signals late-cycle conditions where continuation risk increases and fresh entries need tighter risk management.
5. Combine with structure tools (support / resistance, order blocks, market-structure tools) for entries. This indicator is designed to answer "how strong is the trend," not "where do I enter."
⚠️ LIMITATIONS AND TRANSPARENCY
• This is an indicator, not a trading strategy. It does not produce buy / sell recommendations and it does not backtest trade outcomes.
• The score is a lagging composite built from historical price data. It does not predict future price movement.
• During sharp regime transitions (news events, gap opens), the score can change rapidly from one bar to the next. This is by design, not a bug.
• Factor weights are user-adjustable. Defaults are a reasonable starting point but may need tuning per instrument / timeframe.
• The Pullback factor assumes trending behavior. In tight consolidations it can read misleadingly high, which is why the Dominant Factor readout exists as a cross-check.
• No-repaint: all calculations are based on confirmed (closed) bar data; alerts fire on bar close only.
📌 RISK DISCLOSURE
Trading carries substantial risk. This indicator is an analytical tool for research and study purposes and does not constitute financial advice, a trading signal, or a recommendation to buy or sell any instrument. Past behavior of any indicator is not indicative of future results. Users are solely responsible for their trading decisions and should conduct their own due diligence and risk management.
Indicator

Adaptive Friction Filter (AFF) [QuantAlgo]🟢 Overview
The Adaptive Friction Filter (AFF) identifies trending market conditions by applying a physics-inspired friction model to price movement. Rather than smoothing price through fixed averaging, it introduces a dynamic noise threshold derived from recent market volatility, which means price must generate enough force to overcome this threshold before the filter moves at all. Once breached, the filter closes the gap at a configurable rate, producing a step-like trend line that holds steady through noise and responds decisively to genuine directional moves. This allows traders to distinguish between meaningful trend continuation and low-conviction chop across any instrument or timeframe.
🟢 How It Works
The AFF's core methodology is built around a two-stage mechanism: a volatility-derived friction threshold that gates filter movement, and a catch-up scalar that governs how much of the gap the filter closes on each bar once that threshold is exceeded.
First, the friction threshold is computed as the simple moving average of absolute bar-to-bar price changes over the configured lookback window, scaled by the friction coefficient. This makes the threshold inherently self-adjusting; it widens during volatile conditions and contracts during quiet ones, without requiring any manual recalibration:
friction = ta.sma(math.abs(src - src ), lookback) * friction_mult
Next, the raw displacement between current price and the filter's last position is evaluated as force. The filter only advances if this force exceeds the friction threshold. When it does, the filter moves toward price by a fraction of the gap governed by the catch-up scalar, rather than closing the full distance immediately, producing a controlled and progressive response:
force = src - aff_line
aff_line := math.abs(force) > friction ? aff_line + force * catchup_scalar : aff_line
Trend direction is then resolved by comparing the current filter value to its prior bar value. The direction state persists when the filter is flat, so no transition is registered on bars where the filter does not move:
trend_dir := aff_line > aff_line ? 1 : aff_line < aff_line ? -1 : trend_dir
Finally, the filter is rendered as two overlapping plots at the same value: a step-line that traces the filter's path and a circle overlay positioned at each bar's filter value. The circles serve a visual purpose, reinforcing the current filter level at each step and making it easier to read the filter's position at a glance, particularly during flat periods where the step-line alone can be harder to track. Together they produce a dotted step appearance that improves legibility across different chart zoom levels and timeframes.
🟢 Signal Interpretation
▶ Bullish Trend (AFF Line Rising with Bullish Colour): When price generates enough upward force to exceed the friction threshold, the filter begins stepping higher and the line shifts to the bullish colour. The step-line rendering makes the transition visually clear; flat segments indicate bars where force was insufficient to move the filter, while upward steps reflect bars where it was. The bullish trend state persists until force in the downward direction is large enough to push the filter lower, at which point trend direction flips and the line shifts to the bearish colour.
▶ Bearish Trend (AFF Line Declining with Bearish Colour): When price generates enough downward force to exceed the friction threshold, the filter begins stepping lower and shifts to the bearish colour. As with the bullish state, the filter holds its last value on bars where force is insufficient to breach the threshold, and the direction state remains unchanged on those bars. A full reversal back to bullish requires upward force to exceed the friction threshold and push the filter higher, at which point trend direction flips and the colour transitions accordingly.
🟢 Features
▶ Preconfigured Presets: Three parameter sets cover a range of trading styles and timeframes. "Default" delivers balanced noise filtering for swing trading on 4-hour and daily charts. "Fast Response" lowers the friction threshold and accelerates the catch-up rate for intraday and scalping use on 5-minute to 1-hour charts, producing earlier filter movement in response to smaller price displacements. "Smooth Trend" raises the threshold and slows the catch-up rate for position trading on daily and weekly charts, requiring larger price displacements relative to the average noise level before the filter advances.
▶ Built-in Alerts: Three alert conditions support automated monitoring of trend transitions. "Bullish Trend Signal" fires on the first bar trend direction flips from bearish to bullish. "Bearish Trend Signal" fires on the first bar trend direction flips from bullish to bearish. "Any Trend Change" triggers on either transition for traders who want a single unified alert regardless of direction. All alerts include the exchange, ticker, and timeframe in the message for immediate context.
▶ Visual Customisation: Six colour presets, Classic, Aqua, Cosmic, Cyber, Neon, and Custom, provide coordinated bullish and bearish colour pairings suited to different chart themes and personal preferences. Selecting Custom exposes independent colour pickers for full manual control over both states. Optional bar colouring tints price candles with the active trend colour using a configurable transparency level, and optional background colouring extends the trend state tint across the full chart pane at a separately configurable transparency.
Indicator

Indicator

Indicator

Trend Quality [AGPro Series]Trend Quality
Trend Quality fuses three independent regime dimensions — ADX directional strength, Kaufman Efficiency Ratio, and ATR-normalized EMA slope — into a single 0–100 composite Trend Quality Score. A hysteresis + confirmation + cooldown gate turns that score into a stable TREND / CHOP regime, enhanced with HTF confirmation, lifecycle phases, score velocity, breakout grading, directional dominance, and a full adaptive on-chart quality window. The goal is simple: replace noisy "is this a trend?" guessing with a transparent, multi-dimensional, low-lag quality reading you can read in one glance.
🎯 OVERVIEW
Most trend filters fail at the same thing — they tell you a trend exists, but not whether that trend is clean, accelerating, fading, or already exhausted. Trend Quality answers the harder question. Every bar is scored on three independent dimensions that each measure a different physical property of price movement:
• ADX — directional strength (how strongly one side dominates)
• Kaufman Efficiency Ratio (ER) — path efficiency (how little wasted motion)
• ATR-normalized EMA slope — normalized trend velocity (how fast, relative to volatility)
These three signals are combined into one 0–100 Trend Quality Score. A hysteresis band + confirmation bars + cooldown filter convert that score into a stable TREND / CHOP regime — no single-bar flipping, no false recovery wicks. On top of the core regime, the indicator layers Score Velocity, Lifecycle phases (Emerging → Confirmed → Exhausting), Breakout Quality grading (A / B / C), directional dominance, and a visual Quality Window that tracks the active trend zone and projects it forward.
💎 UNIQUE EDGE
What separates Trend Quality from a standard ADX filter, an EMA slope indicator, or a generic regime meter:
• Tri-factor fusion (not a single metric) — ADX alone misses path quality; ER alone misses direction; slope alone misses choppy-but-strong moves. Weighted fusion (45% ADX, 35% ER, 20% Slope) neutralizes each component's blind spot.
• Stable regime, not a flickering line — the TREND / CHOP state passes through a 3-layer filter: hysteresis band around the threshold, N confirmation bars, and a cooldown window after every transition. The result is a regime reading that holds through pullbacks without flipping.
• Score Velocity Engine — a second-derivative layer that watches how fast the score itself is changing. Surges flag momentum ignition; collapses flag quality breakdown before price confirms it. A bearish divergence detector fires when price makes new highs while quality is fading.
• Lifecycle phases — inside every TREND regime, the script distinguishes Emerging (young, fresh, accelerating), Confirmed (mature, stable, above buffer), and Exhausting (score rolling over from a peak). This lets you see whether you are entering early, running mid-trend, or catching the end.
• Breakout Quality Badge (A / B / C) — every CHOP → TREND transition receives a graded badge based on composite score plus velocity bonus. Grade A breakouts are rare and have an optional dedicated alert.
• HTF confirmation with Auto-HTF mapping — the same engine runs on a higher timeframe. When LTF is trending but HTF is not, the regime is marked BLOCKED (not forced to CHOP) so you retain full transparency about why the regime is gated.
• Adaptive Quality Window — a live rectangular zone that tracks the full trend's high/low from its start bar, projects forward, shows ceiling/floor projection labels, and preserves historical windows with directional color coding (green for up-trends, pink for down-trends, amber for HTF-blocked trends).
🧪 METHODOLOGY
Core composite score (every bar, LTF):
Score = 100 × (0.45 × ADX_norm + 0.35 × ER_norm + 0.20 × Slope_norm)
• ADX_norm = min(ADX / 50, 1)
• ER_norm = |close − close | / (SMA(|Δclose|, N) × N)
• Slope_norm = min(|EMA − EMA | / ATR × 10, 1)
Regime gating:
• Hysteresis: +3 above threshold to enter TREND, −3 below to enter CHOP
• Confirmation: N consecutive bars above/below the hysteresis band
• Cooldown: N bars after every regime flip where no new flip is allowed
MTF confirmation (optional, default ON):
The same core function is called via request.security on the HTF (Auto: 30m→4H, 4H→Daily, Daily→Weekly, Weekly→Monthly in Strict mode). When LTF=TREND but HTF=CHOP, the regime is tagged BLOCKED — a transparent third state that is neither forced-CHOP nor accepted-TREND.
Lifecycle logic:
• Emerging: TREND is young (bars since start ≤ Emerging Bars) OR score slope ≥ 0 and score below buffer
• Confirmed: score ≥ threshold + Confirmed Buffer AND HTF passes (optional)
• Exhausting: score slope < 0 AND pullback from peak ≥ Exhaustion Pullback
Score velocity:
velocity = score − score (default 5-bar look-back)
Breakout quality grading:
bqScore = score + velocity_bonus (bonus: +15 if vel>15, +7 if vel>5, else 0)
A ≥ 82, B ≥ 67, C < 67
🔔 SIGNALS & ALERTS
The script exposes 12 alert conditions — all moderator-safe, educational, non-solicitating:
• CHOP → TREND / TREND → CHOP regime flips with LTF+HTF context
• Strong Trend composite conviction threshold
• HTF Blocked / HTF Unblocked third-state transparency events
• Emerging / Confirmed / Exhausting Trend lifecycle phase changes
• Velocity Surge / Velocity Collapse second-derivative extremes
• Grade-A Breakout rare high-conviction breakouts
• Bearish Divergence price up, quality down warning
On-chart visual events (also filterable via inputs):
• Breakout Quality badge (A / B / C) at every CHOP → TREND
• Bearish divergence ⚠ marker at trend peaks where quality fades
• State tag near backbone: EMERGING / CONFIRMED / EXHAUSTING / HTF BLOCKED
• Quality Window label: ACTIVE + phase
• Projection labels on the right edge: QUALITY CEILING / TREND FLOOR
All badge and warning labels are gated with an 8-bar cooldown so the chart stays clean even on repeated intra-swing triggers.
⚙️ KEY INPUTS
Core engine:
• ADX Length (14) — directional strength look-back
• Efficiency Length (20) — ER path-efficiency window
• Slope EMA Length (50) — trend backbone reference
• ATR Length (14) — volatility normalization
• TREND Threshold (55) — composite score level to enter TREND
• Confirmation Bars (1) — bars of persistence before flipping
• Strong Trend Offset (15) — extra score above threshold for STRONG tag
MTF:
• HTF Confirmation (ON) — enable/disable HTF gate
• Auto HTF (ON, Strict) — smart HTF mapping per chart TF
• Manual HTF (240) — override timeframe
Stability:
• Change Cooldown Bars (2) — lock-out window after any regime flip
Lifecycle:
• Emerging Phase Bars (4) — max trend age to stay Emerging
• Confirmed Buffer (8.0) — score must clear threshold+buffer
• Exhaustion Pullback (4.0) — peak-to-current drop to flag Exhausting
Visual Overlay:
• Backbone + Glow + Zone + State Candles + Quality Window + Historical Windows + Projection Box + Guides + Midline (all toggleable)
Panel, Theme, Layout, Help rows, Alerts, Score Velocity Engine, Breakout Quality Badge, Divergence Detector — every layer has its own input group and can be shown/hidden independently.
📘 HOW TO USE
Read-in-one-glance panel (standard AGPro format):
• Blue header row: script title
• Line 2: REGIME / LIFECYCLE · Score N/100 · Velocity state
• Line 3: LTF regime · Direction · Directional Dominance
• Line 4: HTF regime · MTF PASS/BLOCKED · Active Window state · Streak
Quick playbook:
1. CHOP on LTF → wait. No setup, no commitment.
2. CHOP → TREND transition with Grade A badge + HTF PASS → highest-conviction regime start.
3. CONFIRMED phase with DOM HIGH and rising score → the middle of the trend, usually the cleanest section.
4. Velocity COLLAPSE or EXHAUSTING phase with bearish divergence ⚠ → quality is deteriorating; reduce exposure or tighten stops.
5. HTF BLOCKED amber window → LTF trend exists but higher timeframe disagrees; treat as lower-conviction and be aware of mean-reversion risk.
The indicator does NOT issue buy/sell signals, does NOT define entry/exit prices, and is NOT a strategy. It is a regime-quality reading — a context layer you pair with your own trade management.
⚠️ LIMITATIONS & TRANSPARENCY
• Trend-quality indicators are inherently trend-following. In low-volatility ranges the score can stay above threshold on minor moves; in very fast markets the score can lag by 1–3 bars while the filters stabilize.
• HTF confirmation introduces a natural HTF delay. This is intentional (it removes noise) but means the HTF gate may lift several LTF bars after price has already moved.
• All composite signals rely on look-backs (ADX 14, ER 20, Slope EMA 50, ATR 14). On very short intraday timeframes with low bar counts these need calibration.
• Lifecycle phases are structural readings, not predictions. EXHAUSTING means the score is rolling over — not that price must reverse.
• Past performance of any visual regime does not imply future performance. Charts showing clean historical windows are illustrative of the indicator's logic, not trading results.
• No repainting on historical bars. The HTF call uses lookahead_off and barmerge.gaps_off. Score and regime values on closed bars are final.
🛡️ RISK DISCLOSURE
This script is published as an educational and analytical tool. It does not provide financial advice, does not generate trade signals of any kind, and must not be used as a standalone decision system. Markets involve substantial risk of loss. Past behavior of any market regime, indicator output, or historical visual window is no guarantee of future results. Always combine any indicator with independent risk management, position sizing, a tested plan, and — where appropriate — the guidance of a licensed professional. You are solely responsible for any trading decisions you make. Indicator

Regime Transition Intelligence [AGPro Series]Regime Transition Intelligence
Most regime scripts answer a single question: "what regime are we in right now?". Regime Transition Intelligence is designed to answer a different, more actionable set of questions: how long does this regime usually last, how close to its typical end is it, how likely is it to flip within the next N bars, and where does it historically go when it does flip. Instead of treating the current regime as a standalone snapshot, it builds a living, self-calibrating statistical profile of the symbol's own regime behavior and presents it in a compact on-chart dashboard.
The engine runs on three independent axes — Trend Strength (Kaufman Efficiency Ratio + ADX), Chop Risk (Choppiness Index + inverse trend), and Volatility (ATR% normalized over a user-defined lookback). Each axis is classified as LOW / MID / HIGH, either with fixed 33/67 thresholds or with an adaptive percentile rank engine that learns the symbol's own statistical envelope over a rolling window. The three axes are then combined into a discrete regime state: TREND, MIXED, or RANGE / CHOP.
🟦 Overview / What it does
Regime Transition Intelligence is a single-pane overlay indicator that continuously classifies the market into one of three regimes and then layers a full transition intelligence stack on top of that classification:
- A per-regime dwell-time distribution learned from the chart's own completed regime blocks
- A Bayesian-style flip probability that answers "how likely is a regime change within the next N bars, given the current age"
- A 3x3 transition matrix that ranks the most likely next regime with a secondary fallback
- A fatigue score comparing the current regime's age to its historical mean (FRESH / MATURE / EXTENDED)
- A confidence decay tracker that shows whether conviction is BUILDING, STABLE, or FADING within the current regime block
- A compact history ribbon showing the last completed regime blocks with their durations
- Higher-timeframe alignment with a SYNC / DIV indicator and a live beacon at the right edge of the chart
All of this is delivered inside a single configurable dashboard, a directional transition marker layer on the chart, optional regime tint and candle coloring, and a right-edge beacon summarizing the current state.
🟣 Unique Edge / Why it is not a basic mashup
Standard regime indicators report the current state and stop there. Regime Transition Intelligence adds six distinct statistical layers that together form a transition-aware view:
1. Dwell Time Statistics — the script stores every completed regime block in a rolling array (configurable depth) and continuously updates running mean, running variance, running max, and running count per regime code. Statistics are only shown after a minimum number of blocks per regime have been collected, so the user always knows when the sample size is still too small.
2. Exponential Hazard Flip Probability — the baseline flip probability uses P(flip within H bars) = 1 - exp(-H / mean), a standard survival-analysis construction assuming constant hazard. The result is then fatigue-adjusted: if the current age is far above the historical mean, the probability is boosted; if the regime has just started, the probability is damped. The final value is capped at 95% to avoid certainty claims.
3. Transition Matrix — a 3x3 counter records every observed regime transition and is read as a conditional distribution: "given the current regime ends, which regime is it most likely to move to, and what is the runner-up". Both the top candidate and the secondary candidate are displayed with their percentages.
4. Fatigue Score — the ratio of the current age to the historical mean is bucketed into three zones (FRESH, MATURE, EXTENDED) using user-configurable thresholds. It tells the user whether the current regime is still in its early lifecycle or already past its typical end.
5. Confidence Decay Tracker — conviction in the current regime is sampled at the start of each new block and compared to the current conviction. The delta is classified as BUILDING, STABLE, or FADING, which gives an early read on whether the regime is strengthening or losing its grip.
6. History Ribbon — the last N completed regime blocks are compressed into a single compact line such as "C2·M4·C8·M1·M7*", where letters are regime codes and numbers are bar counts, with the current block marked by an asterisk. It gives immediate context on recent regime rhythm at a single glance.
None of these layers is a repackaged classic indicator. They are built on top of a trend / chop / volatility engine but deliver information that is categorically different from a simple "regime yes / no" readout.
🟢 Methodology / Conceptual data flow
1. Feature extraction. Kaufman Efficiency Ratio (net move over lookback divided by summed absolute moves) and normalized ADX are combined into a trend score. The Choppiness Index is normalized against its operating range and blended with inverse trend to produce a chop score. ATR as a percentage of price is normalized against its own lookback min/max to produce a volatility score.
2. Classification. Each score is mapped to LOW / MID / HIGH using either fixed thresholds (Static mode) or percentile rank over an adaptive lookback (Adaptive mode). The three bands are combined into a discrete regime state: TREND when trend is HIGH and chop is LOW, RANGE / CHOP when chop is HIGH, and MIXED otherwise.
3. Block tracking. Every time the regime state changes on a confirmed bar, the previous block is closed: its duration is pushed to a rolling history array and added to the running sum / sum-of-squares / count / max for its regime code. When the history array exceeds its configured depth, the oldest block is popped and its contribution is subtracted from the running totals, which keeps the statistics adaptive and non-expanding.
4. Transition matrix update. When a block closes into a new regime, the 3x3 counter is incremented at the corresponding cell, and the row total is incremented. The conditional distribution for the current regime is read from its row at display time.
5. Statistical outputs. Mean dwell, fatigue ratio, exponential-hazard flip probability, fatigue-adjusted flip probability, top and secondary next regimes, and confidence delta are all derived from the running state and rendered into the dashboard.
6. Higher-timeframe alignment. The same three-axis engine is run on a user-selected higher timeframe via request.security and compared against the current-timeframe regime; the result appears as SYNC or DIV in the header and as an optional HTF row in the dashboard.
🔔 Signals & Alerts / Interpretation
Regime Transition Intelligence is a state-mapping and statistical context tool rather than a directional buy / sell engine. The main on-chart events are:
- Regime Shift — fires when the regime state changes on a confirmed bar
- High Flip Probability — fires when the fatigue-adjusted flip probability crosses a high threshold
- Regime Fatigue Extended — fires on the transition into the EXTENDED fatigue zone
- Confidence Fading — fires on the transition into the FADING confidence zone
How to read the panel:
- Summary + Age tells the user which regime is active and how long it has been active.
- Dwell Context compares the current age to the historical mean in the form "age / mean · % of typical lifespan".
- Fatigue summarizes that comparison as FRESH, MATURE, or EXTENDED.
- Flip Probability reports the statistical odds of a regime change within the user-defined horizon.
- Next Likely names the most probable next regime with its percentage and a secondary fallback.
- Confidence and Conf Decay together tell the user whether the current read is reliable and whether conviction is rising or fading.
- History gives quick situational awareness of recent regime rhythm.
None of these rows should be interpreted as a trade instruction. They are a context layer meant to be combined with the user's own structure and entry framework.
🎛️ Key Inputs
Regime Engine Core — Trend Persistence Length, DMI/ADX Length, Chop Length, ATR Length, Volatility Normalize Lookback.
Adaptive Boundaries — Band Classification Mode (Adaptive / Static), Adaptive Lookback, Adaptive Low / High Percentile.
Transition Intelligence — Regime History Depth, Flip Probability Horizon, Min Blocks Before Stats Activate, Fatigue Fresh / Extended thresholds.
HUD — Display Mode (PRO / MINIMAL), HUD Position, Text Size, transparency controls, individual row toggles, history ribbon length.
Add-ons — Chart Regime Tint, Regime Candle Coloring (Soft / Strong), HTF Peek Timeframe, Transition Markers (location, cooldown, stagger, size, ATR offset), Live Regime Beacon (position, size, stats toggle).
🧭 How to use
1. Add the script to any chart and timeframe. The engine is tuned to work from 15m up to Daily; very low timeframes on illiquid instruments can produce unstable regime blocks and are not the intended use case.
2. Give the script time to collect blocks. Statistics stay in N/A until the configured minimum number of completed blocks per regime has accumulated. On a fresh chart or an illiquid instrument this is expected behavior, not a bug.
3. Read the dashboard top-down. Start with the three axis rows to understand the current market shape, then move to Summary and Age to see what is active and for how long, then use Dwell / Fatigue / Flip / Next Likely to place the current regime inside its historical distribution, and finally use Conf Decay and HTF to sanity-check reliability and alignment.
4. Treat EXTENDED fatigue and high flip probability as context, not as a reversal signal. Regimes can remain in the EXTENDED zone for a while before actually flipping; the statistical profile is descriptive, not deterministic.
5. Combine with structural context. The script does not know about support / resistance, order blocks, or news. It only knows about the symbol's own regime rhythm. Use it as a regime-aware filter on top of the user's existing framework.
⚠️ Limitations & Transparency
This is not a strategy and not a complete trading system. It does not predict price direction and does not generate buy or sell signals. All statistics are estimated from a rolling history of the chart's own regime blocks, so they are sensitive to the chosen engine parameters, the timeframe, and the symbol; different timeframes and different instruments will produce different statistical profiles, and that is by design.
The exponential-hazard flip probability assumes a constant hazard within the current regime, which is a simplification. Real-world regime durations are not perfectly memoryless and the fatigue multiplier is a heuristic correction, not a formal model. The probability is capped at 95% on purpose, because even a heavily aged regime cannot be considered a certainty and the script deliberately avoids certainty language.
The transition matrix is read as a conditional frequency over completed blocks; it is informative about the symbol's own past behavior and should not be interpreted as a forward-looking forecast. Very small samples produce unstable conditional probabilities, which is why stats stay in N/A until a minimum number of blocks is collected.
Regime classification itself reacts to confirmed bars and can change as new data arrives, which is expected for any regime filter. Users who prefer fully non-repainting alerts should rely on the barstate.isconfirmed-gated alert conditions provided.
📜 Risk Disclosure
Trading involves substantial risk of loss and is not suitable for every investor. Past performance is not indicative of future results. This indicator is provided for educational and analytical purposes only and should not be interpreted as financial advice, an investment recommendation or a solicitation to trade. Always combine multiple forms of analysis, manage position size responsibly, and never risk capital you cannot afford to lose. Indicator

Pivot Channel Map [AGPro Series]Pivot Channel Map
🔹 OVERVIEW
Pivot Channel Map is a structural channel engine that automatically detects and classifies market structure channels from confirmed swing pivots. It organises every qualified channel into a clear 8-family taxonomy (Major / Minor × External / Internal × Up / Down) and renders them as a living map of trend, range and reversal context. The script works on all instruments and timeframes, with a focus on intraday and swing analysis.
Instead of plotting a single trendline or band, the engine maintains a continuously updated structural map: active channels, their midlines, interaction pockets around the rails, preserved broken channels, and post-break retest / reclaim signals. A compact right-corner panel summarises live channel counts, qualification state, nearest channel distance in ATR units, and the prevailing Major tilt.
The goal is to give discretionary traders a moderation-safe, clutter-controlled view of where price is inside the broader structure — not to predict future prices.
🔸 UNIQUE EDGE
Most channel indicators draw one or two parallel lines and call it a day. Pivot Channel Map adds structural classification, qualification, memory and post-event follow-through on top of the channel geometry:
- Eight channel families instead of a single pair of rails
- ATR-normalised qualification engine (Off / Balanced / Strict) to filter structurally weak channels
- Broken Channel Memory that preserves invalidated structure as faded historical context
- Interaction Zones (right-edge ATR pockets) around active channel rails
- Post-Break Retest / Reclaim tracker that tags the first valid touch after a confirmed break
- Break and React event markers on Major channels
- ATR-based distance tagging in the info panel (Near / Mid / Wide / Far)
The result is a richer structural read than a standard channel script, while still staying visually clean through emphasis, opacity and clutter controls.
🔹 METHODOLOGY
1. Pivot detection. A configurable Pivot Period drives ta.pivothigh and ta.pivotlow to produce confirmed swing pivots. The script then classifies each pivot into H / HH / LH / HL / LL / L roles and promotes / demotes them between Major (M*) and Minor (m*) status based on close breaks versus the current Major range.
2. Channel construction. From the classified pivot stream, eight channel families are built:
- Major External Up / Down
- Major Internal Up / Down
- Minor External Up / Down
- Minor Internal Up / Down
External channels trace structural HH/LL extremes, Internal channels trace LH/HL interior swings.
3. Qualification. Each candidate channel is width-measured against ATR and span-measured in bars. The Qualification Engine (Off / Balanced / Strict) filters out structurally weak channels before they are drawn.
4. Life-cycle management. Active channels are redrawn and extended forward each bar until an origin-rail or channel-rail break is confirmed. On break, the previous structure can be preserved by Broken Channel Memory (Off / Major Only / All) with its own style and opacity.
5. Event detection. Confirmed origin-rail breaks produce BREAK events; wick-through-then-close-back moves produce REACT events on Major channels. A cooldown and an ATR-based price-distance filter prevent label clusters when price oscillates around the same rail.
6. Post-break follow-through. After a confirmed break, the script tracks the first valid touch inside a configurable window and tags it as RETEST (channel-rail break) or RECLAIM (origin-rail break).
🔸 SIGNALS & ALERTS
On-chart events:
- BREAK — confirmed close-based break of a Major channel rail
- REACT — wick through the Major rail with a close back inside, filtered by bar cooldown and ATR distance
- RETEST / RECLAIM — first valid touch of the broken rail inside the post-break window
- Interaction Zone contact — visual ATR pocket around active channel rails
- Channel Quick Tags (MEX / MIN / mEX / mIN, Up / Dn) — compact family labels on active channels
Alert conditions (all 16 toggleable, Major alerts On by default, Minor Off by default):
- Break: Major External Up / Down
- React: Major External Up / Down
- Break: Major Internal Up / Down
- React: Major Internal Up / Down
- Break: Minor External Up / Down
- React: Minor External Up / Down
- Break: Minor Internal Up / Down
- React: Minor Internal Up / Down
Message frequency is configurable (All / Once Per Bar / Once Per Bar Close). Alerts include symbol, timeframe, time zone and event description.
🔹 KEY INPUTS
- Pivot Engine: Pivot Period (default 5)
- Per-family Visibility: 8 Show / Delete-Previous / Color / Style / Extend / Width groups
- Channel Qualification: Mode (Off / Balanced / Strict), Apply To (All / Major Only / Minor Only), ATR Length
- Broken Channel Memory: Scope (Off / Major Only / All), Keep (Last 1 / Last 2), Style
- Channel Midline: Show, Apply To, Scope, Style, Width, Opacity
- Active Map Clarity: Line Emphasis, Base-Line Focus, Event Markers, React Cooldown, React Min Price Distance, Quick Tags, Tag Scope, Tag Size, Event / Quick Tag Vertical Offsets
- Interaction Zones: Scope, Rails, Zone Width ATR, Extend Bars, Opacity, Zone Text
- Post-Break Retest / Reclaim: Scope, Window Bars, Label Offset ATR
- Panel: Show, Position, Font Size
- Alerts: 16 per-family Break / React toggles, Alert Name, Frequency, Time Zone
🔸 HOW TO USE
Getting started:
1. Apply the indicator on any symbol and timeframe.
2. Start with default settings: Qualification Off so the full structural map is visible.
3. If the chart feels busy on lower timeframes, switch Qualification to Balanced or Strict.
Reading the panel:
- Major Live / Minor Live — active channels per class
- Nearest Channel — closest active channel, with ATR distance and Near / Mid / Wide / Far tag
- Qualification — current filter mode and scope
- Interaction — interaction zone scope and rails
- Post-Break — tracker scope, window and prevailing Major tilt
Common workflows:
- Trend continuation: wait for price to hold an Active Major channel and look for a REACT at the rail inside the channel direction.
- Break-and-retest: after a BREAK event, watch for the RETEST / RECLAIM label inside the Post-Break window.
- Confluence: use Interaction Zones to spot where Major and Minor rails meet at the right edge of the chart.
- Higher-timeframe context: open a higher timeframe tab with the same script to map macro structure around your execution timeframe.
Suggested defaults:
- Intraday traders: 15m–1H base TF, Balanced qualification
- Swing traders: 4H–1D base TF, Balanced or Off qualification
- Higher-timeframe context: 1D–1W with Qualification Off
🔹 LIMITATIONS & TRANSPARENCY
- Pivot-based. Pivots require the configured number of bars to confirm, so the most recent swing always lags by Pivot Period bars. This is a structural property of confirmed pivots, not a bug.
- Redraw behaviour. Active channels are extended forward each bar until a break is confirmed on close. Channel end-points can therefore adjust as new pivots qualify.
- Alerts fire on confirmed conditions. Break and React alerts require barstate.isconfirmed, so intra-bar touches do not trigger alerts.
- Timeframe behaviour. On very high timeframes with limited history (e.g. weekly / monthly on newer instruments), the total pivot count can be small. Keep Qualification at Off on higher timeframes to avoid over-filtering.
- This is a visualisation / structure tool. It is not a trading strategy, it does not manage risk, and it does not generate buy / sell recommendations. All entries and exits are the trader’s responsibility.
🔸 RISK DISCLOSURE
This script is a technical analysis tool intended for educational and analytical purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any asset. Past chart behaviour does not guarantee future results. Trading involves significant risk and can result in the loss of capital. Always do your own research, use proper risk management, and consider consulting a licensed financial advisor before making trading decisions. Indicator

Dynamic Trend Pivots [BOSWaves]Dynamic Trend Pivots - Conviction-Driven Trend Detection with Pulse-Adaptive Exhaustion Level Mapping
Overview
Dynamic Trend Pivots is a conviction-based trend identification and structural level mapping system that tracks directional price commitment through a pulse accumulation engine, where band width, trend confidence, and exhaustion level placement are driven by real-time measurement of close-position conviction across consecutive bars rather than arbitrary moving average relationships or fixed volatility multiples.
Instead of relying on standard crossover logic or static band thresholds, trend state, adaptive band behavior, and exhaustion level generation are determined through bar-level conviction scoring, pulse saturation modeling, and peak-to-trough saturation drop detection that identifies genuine momentum exhaustion events as they occur.
This creates a trend framework that reflects actual directional commitment rather than lagged price averages - tightening bands during high-conviction pulse saturation when trend confidence is elevated, expanding bands as conviction decays and directional commitment weakens, and planting structural exhaustion levels at the precise price points where pulse energy peaked before collapsing, marking locations of maximum prior commitment for future reference.
Price is therefore evaluated against bands and structural levels that respond to measurable conviction dynamics rather than conventional indicator thresholds.
Conceptual Framework
Dynamic Trend Pivots is founded on the principle that meaningful trend signals and structural reference levels emerge from the accumulation and exhaustion of bar-level directional conviction, not from price crossing smoothed averages or breaching fixed statistical bands.
Traditional trend-following approaches identify directional changes through indicator crossovers or band penetrations that treat all bars equally regardless of their internal structure and conviction quality. This framework replaces undifferentiated price-level logic with conviction-weighted pulse tracking that distinguishes between bars demonstrating genuine directional commitment and bars that merely move price without close-position confirmation.
Three core principles guide the design:
Trend conviction should be measured through close positioning within the bar range combined with directional agreement, not through price displacement alone.
Band width must dynamically reflect pulse saturation state, contracting during high-conviction conditions and expanding as conviction decays.
Structural reference levels should be planted at exhaustion events — the precise price points where accumulated conviction peaked before collapsing — rather than at arbitrary pivot formations.
This shifts trend analysis from static threshold detection into a continuously updating conviction framework anchored in measurable bar-level directional commitment.
Theoretical Foundation
The indicator combines close-position conviction measurement, pulse accumulation and decay modeling, MAD-based adaptive band construction, and saturation peak tracking for exhaustion event detection.
Conviction bars are identified through close positioning within the bar range: a bull conviction bar closes in the upper fraction of its range on an up-close bar, and a bear conviction bar closes in the lower fraction on a down-close bar. A pulse counter accumulates these conviction readings up to a configurable saturation cap, while decaying exponentially between conviction events. Saturation drives the band multiplier interpolation between tight and wide settings, reflecting real-time trend confidence. Exhaustion detection monitors saturation's relationship to its recent peak, planting structural levels when saturation drops sufficiently from that peak.
Four internal systems operate in tandem:
Pulse Accumulation Engine : Evaluates each bar for directional conviction based on close positioning within the high-low range, accumulating bull and bear pulse counters independently with configurable decay between conviction events.
Saturation Measurement System : Converts raw pulse counts into a normalized saturation reading relative to the pulse cap, providing the continuous 0-1 conviction metric that drives all adaptive behavior.
MAD Adaptive Band Construction : Applies Mean Absolute Deviation-scaled bands around an EMA baseline, with the band multiplier dynamically interpolating between minimum and maximum settings based on current saturation.
Exhaustion Level Engine : Tracks saturation peaks with their associated price and direction, planting structural zone levels when saturation drops below a configurable fraction of its recent peak, with lifecycle management including break detection, zone extension, and retest identification.
This design allows trend confidence and structural reference levels to reflect actual conviction dynamics rather than responding mechanically to price or indicator crossovers.
How It Works
Dynamic Trend Pivots evaluates price through a sequence of conviction-aware processes:
Conviction Bar Classification : Each bar's close position within its high-low range is measured; bars closing in the upper fraction on an up-close qualify as bull conviction bars, and bars closing in the lower fraction on a down-close qualify as bear conviction bars.
Pulse Counter Update : Bull or bear pulse counters increment by one on each qualifying conviction bar up to the saturation cap, and decay multiplicatively by the configured decay rate when conviction bars are absent.
Saturation Calculation : The dominant pulse counter (bull or bear) divided by the pulse cap yields a normalized saturation value, with signed directional pulse providing the complete conviction state.
Saturation Peak Tracking : The system continuously monitors saturation, recording the peak value, direction, associated price level (high for bull, low for bear), and bar index when each new saturation maximum is established.
Exhaustion Event Detection : When current saturation drops below the configured fraction of the recorded saturation peak, an exhaustion event fires, triggering structural level placement at the recorded peak price.
Adaptive Band Construction : The band multiplier interpolates between the minimum (saturated, tight) and maximum (exhausted, wide) settings based on current saturation, scaling MAD to determine upper and lower band distances from the EMA baseline.
Trend State Logic : Price crossing above the raw upper band triggers bullish state; crossing below the raw lower band triggers bearish state; state persists until the opposite breach occurs.
Signal Generation : State transitions from bearish to bullish produce buy labels; bullish to bearish transitions produce sell labels, both plotted at MAD-scaled offsets from price.
Exhaustion Level Lifecycle : Planted levels extend rightward with zone boxes, dashed midlines, and price labels until price closes beyond the zone boundary with ATR buffer confirmation, at which point the level is removed.
Retest Detection : When price re-enters an active exhaustion zone after the minimum origin bar offset, a retest signal fires with a configurable cooldown enforced between subsequent retests on the same level.
Together, these elements form a continuously updating conviction map that simultaneously tracks trend state and marks the structural fingerprints left by exhausted momentum.
Interpretation
Dynamic Trend Pivots should be interpreted as a conviction-weighted trend framework with exhaustion-derived structural reference levels:
Bullish Trend State (Green) : Established when price closes above the raw adaptive upper band, indicating a conviction-supported upward directional breach.
Bearish Trend State (Magenta) : Established when price closes below the raw adaptive lower band, signaling a conviction-supported downward directional breach.
Band Cloud : Visual gradient zone fills between the outer band edge and close, with opacity and color reflecting current trend state and providing a continuous conviction boundary reference.
Band Width Dynamics : Tight bands indicate high pulse saturation (elevated conviction), while wide bands reflect saturation decay (diminished conviction and increased caution).
▲ Buy Signals : Green upward triangles mark bullish state initiations at upper band crossovers, plotted below the bar at a MAD-scaled offset.
▼ Sell Signals : Red downward triangles mark bearish state initiations at lower band crossunders, plotted above the bar at a MAD-scaled offset.
Exhaustion Zone : ATR-scaled rectangular zones centered on the saturation peak price mark prior conviction exhaustion locations, with colored borders and subtle fills distinguishing bull from bear exhaustion origin.
Exhaustion Midline : Dashed line through the precise saturation peak price within each zone provides a high-precision structural reference at the exact level of maximum prior conviction.
◆ Origin Marker : Diamond label plotted on the bar where each exhaustion event occurred, marking the conviction peak location for retrospective analysis.
✦ Retest Signals : Small star diamonds mark price re-entry into active exhaustion zones after the origin buffer period, identifying potential reaction points within proven conviction regions.
Retest Extension Lines : Horizontal lines projected forward from retest bar highs or lows mark the retest price level for ongoing reference.
Colored Candles : Optional bar coloring reflects trend state and fades toward neutral as saturation decays, providing an immediate visual exhaustion cue. Note: The original chart candles must be disabled in chart settings for the conviction-colored candles to display properly.
Saturation state, band width dynamics, and exhaustion level proximity outweigh isolated price movements in isolation.
Signal Logic & Visual Cues
Dynamic Trend Pivots presents two primary trend interaction signals alongside a continuous exhaustion level monitoring system:
Buy Signal (▲) : Green triangle appears when trend state switches from bearish to bullish via upper band crossover, indicating conviction-supported directional shift to the upside.
Sell Signal (▼) : Red triangle displays when trend state switches from bullish to bearish via lower band crossunder, indicating conviction-supported directional shift to the downside.
Exhaustion zone retests provide secondary structural signals when price revisits prior conviction peak regions after the minimum origin offset, subject to per-level cooldown enforcement.
Alert generation covers bullish and bearish state switches, exhaustion events triggering new level placement, and both bullish and bearish retest occurrences for systematic structural monitoring.
Strategy Integration
Dynamic Trend Pivots fits within conviction-informed and structural level-based trading approaches:
Conviction-Confirmed Entries : Use band crossover signals as trend initiation points where saturation-supported conviction has driven price through the adaptive boundary, rather than acting on low-conviction crossovers during band expansion.
Saturation-Based Position Sizing : Scale exposure relative to current pulse saturation — favor larger positions during high-saturation fresh trend conditions and reduce sizing as conviction decays and bands widen.
Band-Width Risk Calibration : Expect tighter price ranges and more reliable directional follow-through during contracted band periods; treat expanded bands as a signal of reduced trend reliability requiring tighter risk management.
Exhaustion Level Trade Planning : Use planted exhaustion zones as anticipatory structural levels — price reactions at these zones reflect the influence of the same conviction dynamics that originally caused the momentum peak and collapse.
Retest-Based Re-entry : Treat exhaustion zone retests as lower-risk re-entry or continuation opportunities within established trends, using the midline as a precision reference for entry and invalidation.
Multi-Timeframe Conviction Hierarchy : Apply higher-timeframe trend state and exhaustion level locations as directional bias filters while using lower-timeframe pulse signals for entry precision.
Technical Implementation Details
Core Engine : EMA-based trend baseline with MAD volatility measurement
Conviction Model : Close-position ratio within high-low range with directional agreement gating
Pulse System : Capped accumulation with configurable multiplicative decay between conviction events
Band Construction : Linear interpolation between min/max multipliers based on saturation, scaling MAD offset from EMA baseline
Exhaustion Detection : Saturation peak tracking with configurable drop threshold triggering level placement
Visualization : Gradient-filled band cloud with ATR-scaled exhaustion zones, dashed midlines, and retest extension lines
Signal Logic : Raw band crossover state-switch detection with saturation-faded candle coloring
Performance Profile : Optimized for real-time execution with configurable level caps managing object count
Optimal Application Parameters
Timeframe Guidance:
1 - 5 min : Micro-structure conviction tracking for scalping with responsive pulse and tight band settings
15 - 60 min : Intraday trend identification with balanced decay characteristics and moderate exhaustion sensitivity
4H - Daily : Swing-level conviction trend mapping with sustained pulse persistence and wider exhaustion zone tolerance
Suggested Baseline Configuration:
Trend Length : 21
Close Zone : 0.30
Pulse Decay : 0.85
Pulse Cap : 8
MAD Length : 17
Band Min (Saturated) : 1.4
Band Max (Exhausted) : 2.2
Exhaustion Drop : 0.4
Max Levels : 8
Break Buffer (ATR) : 0.25
Show Band Cloud : Enabled
Color Candles : Enabled (requires disabling original chart candles in chart settings)
Show Buy/Sell Signals : Enabled
These suggested parameters should be used as a baseline; their effectiveness depends on the instrument's volatility characteristics, conviction frequency, and preferred signal density, so fine-tuning is expected for optimal performance.
Parameter Calibration Notes
Use the following adjustments to refine behavior without altering the core logic:
Excessive signal noise : Increase Trend Length for a smoother baseline or tighten Close Zone toward 0.2 to demand more extreme close positioning before conviction is registered.
Missed conviction events : Widen Close Zone toward 0.4 for more inclusive bar qualification or decrease Trend Length for a more reactive baseline.
Pulse sustains too long : Decrease Pulse Decay toward 0.5 for faster conviction fade between qualifying bars, accelerating band expansion during low-conviction periods.
Pulse fades too quickly : Increase Pulse Decay toward 0.99 to sustain saturation longer between conviction events, maintaining tighter bands through minor pullbacks.
Bands too tight or wide across the board : Adjust Band Min and Band Max multipliers to rescale the full saturation-to-exhaustion band range for the instrument's volatility characteristics.
Too many exhaustion levels forming : Increase Exhaustion Drop threshold toward 0.6 to demand a more severe saturation collapse before a level is planted, filtering for higher-conviction exhaustion events only.
Levels not forming frequently enough : Decrease Exhaustion Drop toward 0.2 to plant levels on more modest saturation pullbacks, increasing structural level density.
Levels breaking too easily : Increase Break Buffer ATR multiplier to require a more decisive close beyond the zone boundary before invalidation occurs.
Adjustments should be incremental and evaluated across multiple session types rather than isolated market conditions.
Performance Characteristics
High Effectiveness:
Trending markets with clear conviction phases where pulse saturation builds and sustains before exhausting at structural turning points
Instruments with consistent bar structure where close positioning within the range reliably reflects directional commitment
Momentum continuation strategies entering on fresh pulse saturation signals with contracted bands
Structural level frameworks benefiting from exhaustion-derived reference zones rather than arbitrary pivot-based support and resistance
Reduced Effectiveness:
Choppy, low-conviction environments where close positioning provides unreliable directional signals and pulse saturation builds and collapses rapidly without sustained directional follow-through
Extremely gapped or news-driven markets where bar range structure becomes discontinuous and close positioning loses meaningful conviction interpretation
Mean-reversion dominant conditions where band breaches quickly reverse without sufficient pulse saturation to sustain directional state
Low-volatility compression periods where MAD scaling produces narrow bands that generate frequent false crossovers
Consolidation and sideways conditions where conviction builds in alternating directions without achieving the sustained saturation required for reliable trend state establishment
Integration Guidelines
Confluence : Combine with BOSWaves order flow tools, volume analysis, or multi-timeframe structure indicators for layered confirmation
Saturation Respect : Prioritize signals and level interactions occurring during high-saturation periods; treat low-saturation crossovers and retests with reduced confidence
Exhaustion Awareness : Monitor candle fade coloring as an early warning of declining conviction before formal signal generation confirms a state change
Level Hierarchy : Treat exhaustion levels planted during peak saturation events as higher-conviction structural references than levels formed during moderate saturation peaks
Retest Discipline : Use exhaustion zone retests as continuation confirmation rather than reversal triggers unless accompanied by opposing band crossover signals
Disclaimer
Dynamic Trend Pivots is a professional-grade conviction analysis and structural level mapping tool. It uses pulse accumulation modeling with adaptive band construction and exhaustion-driven level placement but does not predict future price movements. Results depend on market conditions, instrument conviction characteristics, parameter selection, and disciplined execution. BOSWaves recommends deploying this indicator within a broader analytical framework that incorporates order flow context, volume analysis, and comprehensive risk management. Indicator

Volatility Shape Classifier [AGPro Series]Volatility Shape Classifier
🔹 Overview
Volatility Shape Classifier is a context and diagnostics tool that does not stop at telling you whether volatility is high or low. Instead it classifies the SHAPE of that volatility on every bar — Smooth, Chaotic, Choppy, Drift, or Dead — using three independent dimensions combined into a single regime read. The result is a continuous visual narrative made of a subtle background tint, throttled transition badges, and a compact metrics panel.
It is designed to sit on your chart as a pure awareness layer. It does not generate buy or sell signals and it is not a trading strategy.
🔷 Unique Edge
Most volatility tools compress the market into one axis — high vs low (ATR, Bollinger Band Width), or trend vs range (Choppiness Index, ADX). They answer half of the question.
This script asks three questions at once and fuses the answers:
1. Magnitude — is ATR above or below its own long baseline?
2. Smoothness — are bar-to-bar moves consistent in size, or erratic?
3. Directional Consistency — do bars point the same way, or cancel each other?
Only the combination of these three can distinguish a controlled trend run (Smooth) from a violent whipsaw (Chaotic) from a wide directionless thrash (Choppy) — all three of which can show identical ATR readings. That shape distinction is the core value this script adds, and it is the gap left by standard volatility and chop indicators.
🔶 Methodology
Engine layer (per bar):
• Volatility Level = ATR(volLen) / SMA(ATR, volLen * 3)
• Smoothness = StDev(|close − close |) / SMA(|close − close |) over volLen
• Direction = |sum(close − close )| / sum(|close − close |) over volLen
Classification layer maps the three readings into six mutually exclusive codes:
0 — Forming (warm-up / in-between space, no tint)
1 — Expansion · Smooth (high vol, low CV, directional)
2 — Expansion · Chaotic (high vol, high CV)
3 — Expansion · Choppy (high vol, low direction)
4 — Low-Vol · Drift (low vol, low CV, mild direction)
5 — Low-Vol · Dead (low vol, low CV, no direction)
Stability layer applies a configurable Confirmation Bars window so a new shape must persist for N consecutive bars before the chart commits to it. This prevents single-bar flicker. Between-state readings do not reset the current shape, they hold it — avoiding the classic "blink to neutral" problem of switch-based classifiers.
🔸 Signals & Alerts
Four alert conditions are published:
• Shape Shifted to Smooth Expansion
• Shape Shifted to Chaotic Expansion
• Shape Shifted to Choppy Expansion
• Shape Collapsed (any expansion state falling into low-vol Drift or Dead)
Alerts fire only on confirmed shape transitions and only on bar close, so repaint on the signal bar is not a concern.
🔹 Key Inputs
• Volatility Length — window for ATR, smoothness, and direction (default 20)
• Confirmation Bars — persistence requirement before committing to a new shape (default 3)
• Badge Cooldown — minimum bars between visible badges (default 15; tint updates continuously regardless)
• Panel Position / Size — six anchor points, four size presets
• Badge Font Size — four size presets
🔷 How to Use
• Use the SHAPE read as a setup filter, not as the signal itself. Smooth Expansion is where trend-following tools tend to perform well. Chaotic and Choppy Expansion are where they tend to fail even when the raw volatility reading looks attractive.
• The Drift state often precedes an expansion in the direction of the drift.
• The Dead state is a compression warning — a shape collapse alert from Expansion into Dead is a common precursor to a fresh expansion move in either direction.
• Pair with your own entry logic (structure, moving averages, volume). This tool answers "what kind of market am I in right now?" — it does not answer "where do I enter?"
🔶 Limitations & Transparency
• Thresholds (1.15x / 0.70x / 0.80 / 1.10 / 0.18) were tuned on crypto and FX data across 15m to 1D timeframes. Very illiquid instruments and very low timeframes (< 5m) may require a longer Volatility Length.
• Shape classification is inherently backward-looking (it reads the last volLen bars). It describes the character of recent volatility, not future volatility.
• The script is a context layer. It is not a strategy and should not be used in isolation for trade decisions.
• Past behavior of a shape does not guarantee future behavior.
🔸 Risk Disclosure
This indicator is an educational and analytical tool. It does not constitute financial advice, trade recommendations, or a signal service. All trading involves risk. You are solely responsible for your own trading decisions. Indicator

Delivery Regime Map [AGPro Series]Delivery Regime Map
🔹 Overview
Delivery Regime Map classifies the market's delivery character into four distinct regimes — Balanced, Directional, Fragmented, and Exhausted — giving traders instant context on whether the tape is trending with conviction, consolidating, breaking into volatile chop, or fading after an extended move. Rather than asking "is this bullish or bearish?", DRM answers a more useful question: "what kind of market am I in, and what kind of setup is appropriate here?"
The indicator overlays a soft state ribbon across the chart, prints confirmed regime shift labels at the moment of transition, and maintains a compact status panel with the active regime, a composite conviction score, regime duration, and time since the last shift. All outputs are confirmed on bar close with dwell-based hysteresis to suppress noise.
🎯 Unique Edge
Most regime or trend-strength tools collapse the market into a single linear axis (strong ↔ weak, bullish ↔ bearish). Delivery Regime Map is categorical, not linear — it identifies the qualitative character of price delivery by fusing four independent dimensions:
• Displacement quality (how much of each bar's range is body vs. wick)
• Directional persistence (close-to-close consistency + EMA slope alignment)
• Continuity (same-side runs penalized by gap noise)
• Range expansion (current range normalized by ATR baseline)
These dimensions combine into a composite score, but the regime classification uses banded thresholds with hysteresis — meaning a Directional tape must decisively lose its edge before flipping to Fragmented or Exhausted. This produces sparse, high-conviction transitions rather than the constant flipping typical of single-value strength meters.
⚙️ Methodology
The engine computes five rolling metrics across a user-defined window (default 20 bars):
1. Displacement Quality — |close − open| / range, smoothed. High values mean strong, decisive bars with minimal wick rejection.
2. Directional Persistence — average signed close direction plus an EMA slope-alignment check. Rewards tapes that move one way without reversing.
3. Continuity — the proportion of consecutive same-side candles, penalized by an average gap-size term (opens far from prior closes indicate fractured delivery).
4. Range Expansion — current range vs. ATR baseline, clipped to . High expansion combined with low continuity flags Fragmented tapes.
5. Exhaustion Proxy — the decay rate of displacement quality after a period of high persistence. Triggers near trend terminations where bars shrink while direction lingers.
A classifier selects the active regime by priority (Directional → Exhausted → Fragmented → Balanced), and a dwell-bar confirmation (default 5 bars, or 8 under Strict mode) plus a minimum-gap filter (default 10 bars) prevent whipsaw transitions.
🚦 Signals & Alerts
Four alert conditions are built in, each firing only on a confirmed regime shift:
• Regime shifted to Directional — conviction is rising; the tape is trending
• Regime shifted to Fragmented — wide, disconnected bars; chop risk elevated
• Regime shifted to Exhausted — prior trend is losing steam; mean-reversion risk
• Regime shifted to Balanced — low-conviction state; breakout potential building
All alerts include the ticker and interval in the message payload.
🎛️ Key Inputs
• Regime Window (8–60) — length of the measurement window
• Regime Sensitivity (Low / Normal / High) — hysteresis band width
• Strict Classifier — extends dwell requirement from 5 to 8 bars
• Minimum Bars Between Shifts — anti-chop spacing filter
• Show State Ribbon / Regime Shift Labels — visual toggles
• Panel Position + Font Size — 6 anchor positions, 5 size options
• Label Font Size — matches user's chart density preference
Every input carries an inline tooltip explaining its behavior and tradeoffs.
📚 How to Use
• Use Directional regimes to favor trend-following entries and trailing stops
• Use Balanced regimes to prepare for breakouts; volatility compression often precedes expansion
• Use Fragmented regimes as a caution flag — reduce size, widen stops, or stand aside
• Use Exhausted regimes to tighten trailing stops on open trend positions; the edge may be fading
DRM is designed to be asset-agnostic and timeframe-agnostic. On lower timeframes (1m–15m), consider Strict mode and a larger minimum-gap value. On daily charts, defaults typically work well. Combine with any entry framework — order blocks, breakout levels, VWAP reclaims — as a regime filter that answers "should I even be looking for a setup here?"
⚠️ Limitations & Transparency
• The classifier is reactive, not predictive — it confirms regime changes on close, so a Directional label appears a few bars after the trend has begun. This is by design: dwell confirmation is the primary noise filter.
• Regime definitions are categorical interpretations of price statistics. They are not forecasts.
• The composite score reflects regime conviction, not directional bias. A high score in Fragmented means "confidently choppy", not "confidently bullish".
• This indicator is not a strategy. It produces no entry signals, no take-profit targets, and no stop-loss levels. It is a market-context tool intended to be combined with a trader's existing framework.
• Past regime behavior does not guarantee future regime behavior. Market character can change abruptly on news or macro events.
📜 Risk Disclosure
This indicator is published for educational and analytical purposes only. It does not constitute financial advice, a trading recommendation, or an offer to buy or sell any instrument. Trading and investing carry risk of loss, and past performance does not guarantee future results. Users are solely responsible for their own decisions and should consult qualified professionals before committing capital. Indicator

Mean Reversion Corridors [AGPro Series]Mean Reversion Corridors
🔹 Overview
Mean Reversion Corridors is a volatility-adaptive deviation framework that maps how far price has stretched from a chosen fair-value center and classifies that stretch into two actionable zones. An inner corridor marks the early reversion band where price is meaningfully extended but not yet extreme; an outer corridor marks statistical exhaustion where continuation becomes less probable under normal conditions. A higher-timeframe trend filter separates controlled mean reversion from failure-continuation expansions, so traders can tell fading the edge from respecting a real break — all from a single clean overlay.
🔸 Unique Edge
Most band systems (Bollinger, Keltner, ATR channels) offer a single width engine and a single band pair, leaving the trader to guess whether a tag is an exhaustion or a breakout. Mean Reversion Corridors is built around three ideas that work together:
- A dual-engine width unit that linearly blends ATR (range-based) and Standard Deviation (dispersion-based) so the corridor is stable on both gap-heavy and low-dispersion regimes.
- A two-layer corridor with distinct roles — inner for early stretch, outer for exhaustion — rendered as transparent zones you can read at a glance.
- A regime-aware state machine that uses a higher-timeframe trend filter to reclassify outer tags as either reversion candidates or failure-continuation, tracked as explicit REV and FAIL states with a bounded confirmation window.
🧠 Methodology
- Center Model — user choice of EMA, VWMA (volume-aware, default) or HMA (responsive), calculated on chart closes.
- Width Unit — the current volatility unit is a linear blend: (1 − blend) × ATR + blend × StDev, protected against empty volatility periods.
- Corridors — inner band at ±(width × inner multiplier), outer band at ±(width × outer multiplier). Stretch is reported in width-unit sigma.
- Trend Filter — the same center model is evaluated on a higher-timeframe via request.security with lookahead off, and its slope is normalized by ATR so the "strong" threshold is volatility-aware, not symbol-specific.
- State Machine — tracks the most recent outer-band extreme with a rolling 20-bar confirmation window. A reversion is confirmed only when price closes back inside the inner corridor and the trend filter is not strongly aligned with the original stretch. When the trend is strongly aligned, the outer break is reclassified as corridor failure (continuation).
- All conditions evaluate on confirmed bars to avoid repainting behavior.
⚡ Signals & Alerts
On-chart markers:
- REV — reversion confirmed back through the inner band after an outer extreme, trend-filtered.
- FAIL — corridor failure / trend-aligned continuation beyond the outer band.
Six bar-close alert conditions:
- Inner corridor entered — upside stretch
- Inner corridor entered — downside stretch
- Outer corridor hit — upside exhaustion
- Outer corridor hit — downside exhaustion
- Reversion confirmed
- Corridor failure (continuation)
⚙️ Key Inputs
- Center Model — EMA / VWMA / Hull
- Center Length and Volatility Length — independent lookbacks
- ATR ↔ StDev Blend — balance between range and dispersion engines
- Inner Corridor Width and Outer Corridor Width — in volatility units
- Trend Filter — enable, timeframe, length, strength threshold
- Visuals — outer-only mode, center line, fills, edge tags, state labels, label size
- Info Panel — show/hide, position (six options), font size
- Alerts — individually toggleable for each of the six events
📖 How to Use
- Start with the defaults on your main chart timeframe. The 34-period VWMA center, balanced blend and 1.0 / 2.2 inner/outer multipliers are chosen to work as a neutral starting point across liquid markets.
- Inner corridor tags are early stretch cues — they flag that price is extended, not that a turn is due. Use them as context for setups, not as standalone signals.
- Outer corridor tags with the trend filter neutral or opposed are the primary mean reversion setup; wait for a REV confirmation back inside the inner band before acting.
- When FAIL appears, the stretch is trend-aligned; treat the outer band as continuation, not resistance. This is the signal to stop fading.
- Use the Info Panel to read current state, reversion bias, trend regime and stretch magnitude in sigma at a glance.
⚠️ Limitations & Transparency
- This is an analytical tool, not a trading strategy or financial advice. It does not predict future price.
- Band-based classification assumes statistical behavior; during shocks, news events or illiquid sessions the width engine can lag.
- The trend filter uses a higher-timeframe slope — it reacts slower than short-term momentum by design, which is the intended behavior.
- Signals are evaluated on confirmed bars; intrabar crosses are not counted as events.
- Past behavior of any indicator does not guarantee future results. Always apply your own risk management. Indicator

Trend Stability Ribbon [AGPro Series]Trend Stability Ribbon
🔹 OVERVIEW
Most trend tools tell you WHICH WAY price is going. Trend Stability Ribbon tells you HOW WELL it is getting there. By pairing an ATR-normalized slope engine with a Kaufman path-efficiency score, it projects every bar into one of four rules-based states — Stable Up, Noisy Up, Stable Down, Noisy Down — and paints them onto a clean, adaptive ribbon that stays out of the candles' way. The result is a context layer that separates decisive trending from directional-but-choppy travel, without adding a second indicator pane.
🧭 UNIQUE EDGE — WHY THIS IS NOT "JUST ANOTHER TREND INDICATOR"
Direction alone is cheap. Every moving-average cross, every supertrend, every slope color tells you "up" or "down" — and then leaves you holding the bag when the trend is technically up but structurally a mess.
Trend Stability Ribbon adds the missing second dimension: path quality. The same 34-bar window that defines direction also feeds a Kaufman efficiency calculation (net travel divided by total path travel). An ER near 1.00 means price walked a near-straight line; an ER near 0.00 means it zig-zagged its way to the same point. Mapping that score against a calibrated threshold band produces the four composite states — and a visual language that finally distinguishes "trend worth trusting" from "trend worth fading".
Additional design choices that set it apart:
• Dual-layer event engine — direction flips, stability upgrades, and stability downgrades are tracked as independent transitions, each with its own alert.
• Badge/alert separation — on-chart badges are throttled by a cooldown for visual hygiene, but alerts are always raw so automation pipelines never miss an event.
• Reset state — when the slope-confirmation filter rejects a direction, the ribbon goes neutral instead of flipping false. Chop gets ignored, not misreported.
🧪 METHODOLOGY
1. TREND DIRECTION ENGINE
• A slow EMA (default length 34) anchors the trend path and serves as the ribbon centerline.
• Slope is measured over a 3-bar lookback and normalized by a 14-period ATR, making it instrument-agnostic across crypto, FX, equities, and futures.
• With Slope Confirmation enabled (default), direction is only accepted when price position AND slope agree. Disagreement returns a Reset state.
2. PATH EFFICIENCY (STABILITY) ENGINE
• ER = |close − close | ÷ Σ|close − close | over the same trend window.
• Three classes: Stable (ER ≥ 0.45), Noisy (ER ≤ 0.25), Mixed (between). Thresholds scale with the Stability Sensitivity input.
• The Mixed zone is a deliberate dead-band — during uncertain phases the previous state persists rather than flickering.
3. COMPOSITE STATE MACHINE
• Direction × Stability yields five possible states: Stable Up, Noisy Up, Stable Down, Noisy Down, Reset.
• Bars-in-state is tracked live, giving a simple persistence read on each state.
4. RIBBON RENDERING
• Ribbon is anchored to the EMA centerline with height driven by ATR × a user-selected multiplier (Thin / ATR-Adaptive / Thick).
• Fill opacity and border weight shift by state — Stable states are saturated, Noisy states are faded, Reset is a soft amber.
🔔 SIGNALS & ALERTS
Three transition events are detected and exposed as separate, user-toggled alerts:
• Trend State Flipped — direction changed (Up ↔ Down). Raw, never throttled.
• Stability Improved — path upgraded from Noisy to Stable while direction held. Raw — delivered regardless of badge cooldown.
• Stability Degraded — path downgraded from Stable to Noisy while direction held. Raw — delivered regardless of badge cooldown.
Matching on-chart badges appear at the same moments, subject to the Stability Badge Cooldown for visual cleanliness. Direction-flip badges are never throttled.
⚙️ KEY INPUTS
Engine
• Trend Length (default 34) — lookback for both direction and path-efficiency windows.
• Stability Sensitivity (default 1.0) — scales the Stable / Noisy thresholds.
• Require Slope Confirmation (default on) — enforces price-and-slope agreement; rejects chop.
Ribbon & Badge
• Ribbon Height — Thin / ATR-Adaptive / Thick.
• Show State Badge — toggle on-chart transition labels.
• Label Font Size — tiny / small / normal / large (default normal).
• Minimal Mode — hides panel and badges for pairing with other overlays.
• Stability Badge Cooldown (default 5 bars) — visual throttle for stability transitions.
Info Panel
• Panel Position, Panel Font Size, Efficiency Ratio display, Active Thresholds display.
Alerts
• Independent toggles for each of the three transition events.
🧠 HOW TO USE
• CONTEXT FILTER — use Stable states as a "green light" for continuation setups on your primary system; treat Noisy states as a headwind.
• REGIME BREAKS — a Stability Degraded event mid-trend is often an early warning that the move is maturing, even before price has flipped.
• CLEAN ENTRIES — pair a direction flip (Trend Up / Trend Down) with an immediate Stable classification to filter out whipsaw-prone breakouts.
• CHOP AVOIDANCE — when the ribbon sits in a Reset or Mixed state, the script is telling you the underlying path is not tradeable as a trend. Stand aside or switch to range tactics.
• PAIRING — with Minimal Mode on, the ribbon layers cleanly under structure tools, VWAPs, or S/R zones without visual conflict.
⚠️ LIMITATIONS & TRANSPARENCY
• This is an indicator, NOT a strategy. It does not generate buy or sell orders, has no backtest, and makes no claim of performance.
• Efficiency Ratio is a lagging measure — it describes the path already travelled. The ribbon should be read as context, not as a leading signal.
• The Mixed zone is intentional persistence; expect the composite state to hold through brief chop rather than flipping on every bar.
• Lower timeframes (<5m on thin-liquidity markets) can push ER values into erratic ranges. Start with the defaults on 15m–4h and tune from there.
• All calculations are closed-bar. Intra-bar values may shift until the bar confirms.
🛡️ RISK DISCLOSURE
This script is published for educational and analytical purposes only. It is not financial advice, not a signal service, and not a solicitation to buy or sell any instrument. Past behavior of markets does not predict future results. Always do your own research, apply proper risk management, and consult a licensed professional before making trading decisions. The author assumes no responsibility for losses incurred through use of this indicator. Indicator

Turtle Soup Reversal Map [AGPro Series]Turtle Soup Reversal Map
🔹 Overview
Turtle Soup Reversal Map is a mean-reversion pattern detector inspired by Linda Raschke's classic "Turtle Soup" setup — a counter-attack on failed 20-bar breakouts. When price pierces a multi-bar extreme and then closes back inside the prior range, institutional traders often interpret it as trapped breakout participants being flushed. This script automates the detection, qualifies each setup with a transparent 0–100 score, and projects a reference target alongside an auto-resolving rejection zone. It is designed for traders who want a disciplined, rule-based way to spot failed breakouts without drawing them manually.
🔹 Unique Edge
Unlike generic liquidity-sweep or wick-rejection indicators, Turtle Soup Reversal Map is built around Raschke's specific 20-bar-extreme rule — a pattern with decades of documented performance in swing-trading literature. Three characteristics separate it from similar tools:
• Strict N-bar-extreme definition (not a simple swing-high/low fade). Price must violate the exact prior-lookback extreme, not just a minor pivot.
• Five-component adaptive quality score — wick rejection, volume spike, overshoot magnitude, higher-timeframe trend alignment, and key-level proximity. Each component is a transparent weighted contribution, with clear A+ / A / B / C grades.
• Full lifecycle state engine — Pending → Fired → Target/Stop/Invalidated. Setups that do not confirm within their window are auto-invalidated (not left hanging), and live win-rate plus average R-multiple are tracked over the most recent resolved setups.
🔹 Methodology
The script continuously monitors for price piercing the highest high or lowest low of the prior N bars (default 20, range 10–50). When a sweep occurs, a Pending setup is created. Confirmation is then evaluated in one of two user-selectable modes:
• Same-Bar Close — the violating bar must close back inside the prior range on the same bar (faster, more signals).
• Next-Bar Close — Raschke's original specification; the next bar must close back inside the prior range (slower, higher reliability).
If confirmation fires, the setup becomes Fired and a reference target is projected from the confirmation close (default 2.5 × ATR(14)). Stop is placed at the sweep extreme plus a configurable ATR buffer. Setups that fail to confirm within their window, or where price overshoots the stop before confirmation, are automatically invalidated.
The quality score blends: wick-to-range ratio at the extreme bar, relative volume spike versus its 20-bar average, overshoot magnitude (ATR-normalized with a sweet-spot curve), counter-trend alignment against a user-defined higher timeframe, and proximity to round numbers or recent pivot levels.
🔹 Signals & Alerts
The script produces three alert types, all configurable:
• Pending — sweep detected, awaiting confirmation.
• Fired — confirmation closed back inside prior range.
• Invalidated — setup dismissed due to overshoot or window timeout.
Each alert message includes direction (Bull/Bear), current grade, ticker, and timeframe. Fired setups are visualized with a labeled confirmation marker, a dashed target-projection line, a dotted stop-reference line, and an auto-closing rejection zone. Labels display the Soup-Bull / Soup-Bear name, grade, and numeric score.
🔹 Key Inputs
• Lookback Bars — size of the extreme window (default 20, range 10–50).
• Confirmation Mode — Same-Bar Close or Next-Bar Close.
• Invalidation Distance (ATR) — stop buffer beyond the sweep extreme (default 0.5).
• Target Projection (ATR) — reference reversal target distance from entry (default 2.5).
• Quality Score Components — each of the five score components can be toggled independently for custom configurations.
• HTF for Trend — higher timeframe used for the trend-alignment component (default 240 min).
• Stats Sample Size — rolling window of resolved setups used for win-rate and average reward metrics (default 30).
• Visual & Panel Options — zones, lines, labels, target projection, panel location, font sizes, and per-element toggles.
🔹 How to Use
1. Apply to any liquid instrument and timeframe. The pattern's rule set is symbol-agnostic but performs differently across assets — review the live Win Rate and Avg Reward metrics in the panel to calibrate expectations.
2. Watch the Status field in the panel. Idle means no active setup; Pending Bull/Bear means a sweep has occurred and the script is waiting for confirmation; Fired Bull/Bear means confirmation closed and a target has been projected.
3. Filter setups by grade. A+ and A setups have stronger confluence — particularly wick rejection, volume, and HTF alignment. B setups are acceptable under favorable market regimes; C grades are educational only.
4. Treat the target projection as a reference, not a trade instruction. The stop reference line marks where the structural invalidation lies. Always combine with your own risk management.
5. The historical Win Rate is computed over the last N resolved setups on the current chart; it reflects the pattern's fit with the current symbol and timeframe, not a guarantee.
🔹 Limitations & Transparency
This indicator identifies historical setups algorithmically. It does not predict future price movement, and no indicator does. Turtle Soup is a counter-trend mean-reversion pattern — in strong trending regimes, false signals increase; in consolidation and range-bound conditions, it performs best. The displayed Win Rate and Avg Reward are historical, rolling, chart-dependent, and should not be interpreted as future expectations. Target and stop references are geometric projections based on ATR, not optimized parameters.
🔹 Risk Disclosure
This script is a technical analysis tool for educational and research purposes. It is not a trading strategy, not a recommendation, and not financial advice. Past performance does not guarantee future results. Always conduct your own analysis and use proper risk management. Trade at your own risk. Indicator

Indicator

MTF Trend Agreement Map [AGPro Series]MTF Trend Agreement Map
🔹 **Overview**
MTF Trend Agreement Map is a multi-timeframe alignment engine that reads the trend across five timeframes at once and distills the result into a single transparent agreement score. Instead of forcing you to flip between charts, the map tells you, on every bar, how many timeframes agree, which side wins, and whether the market is in a locked regime, a forming trend, or a conflict phase. It is built for swing traders, HTF-bias scalpers, position traders, and anyone who uses top-down analysis as part of their process.
🔸 **What Makes It Different**
Most MTF indicators show a single method (usually a moving-average cross) repeated across timeframes, which means five rows that all agree with each other by construction. This map does something different: for each timeframe it runs three independent methods — an EMA regime filter, a pivot-based market-structure read (HH/HL vs LH/LL), and a normalized momentum slope — and blends their individual votes into the final score. You see not only the agreement across timeframes but also the agreement across methods, which exposes weak or borderline regimes that a single-method tool would quietly hide.
🔺 **Methodology**
• EMA Trend: a timeframe is bullish when EMA50 is above EMA200 and price is above EMA50; bearish on the mirror condition; neutral otherwise.
• Market Structure: confirmed pivots are tracked in real time. A timeframe is bullish while the last two confirmed swings form higher highs and higher lows, bearish on lower highs and lower lows.
• Momentum Slope: the change in linear regression across a configurable lookback, normalized by ATR so that fast and slow assets are comparable.
• Consensus per timeframe: each active method casts a vote; bulls minus bears determines the row's net direction and strength.
• Overall alignment: bull and bear votes are summed across all active timeframes; the dominant side's share defines the agreement percentage.
◆ **Three-State Regime Engine**
• **LOCKED** — agreement above the strong threshold (default 80%). High-conviction regime, continuation-friendly, background tint activates.
• **TRENDING** — agreement between 50% and the strong threshold. Directional bias forming but not yet fully aligned. Trade with reduced size or wait for confirmation.
• **SPLIT** — agreement below 50%. Timeframes are in conflict, no majority side. Classic chop phase, favors mean-reversion strategies or standing aside.
🔔 **Signals & Alerts**
• Regime Lock (Bull or Bear): fires the first bar agreement crosses above the strong threshold while one side dominates. Designed as a continuation trigger, not a reversal signal.
• Chop / Conflict: fires when no side holds the majority, a classic filter for mean-reversion systems or a stand-aside cue for trend traders.
• Both generic and directional alertcondition() hooks are exposed so you can wire the map into automations.
⚙️ **Key Inputs**
• Core Engine: toggle any of the three methods on or off, and tune the pivot length and momentum lookback independently.
• Timeframes: four user-selected timeframes plus an optional Current row that auto-adapts to the chart TF. If the chart TF matches any selected TF, the Current row is hidden automatically to avoid double-counting.
• Panel: six location presets, four text sizes (default Normal), dark or light theme, optional per-method breakdown row.
• Background Tint: enable or disable, set the strong-alignment threshold (50–95%) and control transparency (70–99) to keep the chart premium.
📖 **How to Use**
• Top-down confirmation: take trades on your execution timeframe only when the higher rows in the map agree with your thesis.
• Regime filter: enable Regime Lock alerts to catch moments when the full map snaps into alignment — these are typical continuation windows.
• Conflict filter: when the map prints SPLIT, widen stops, reduce size, or step aside; trend strategies historically underperform during these phases.
• Method debugging: turn on the per-method breakdown to see which methods are driving the score and which are fighting it.
⚠️ **Limitations & Transparency**
• All timeframe values are non-repainting at bar close (lookahead is disabled), but intrabar values can update until the parent bar closes — this is expected MTF behavior.
• Market Structure requires enough history on each timeframe to confirm two swings; on very young assets or short charts the structure vote may be neutral until pivots print.
• The map is a context tool, not a standalone entry system — combine it with your own execution logic, risk management, and bias.
📌 **Risk Disclosure**
This script is provided for educational and analytical purposes only. It does not constitute financial advice, a recommendation, or a solicitation to trade any instrument. Markets involve substantial risk and past behavior does not guarantee future results. Always do your own research and manage risk responsibly. Indicator

HH/HL/LH/LL Structure Tracker [AGPro Series]HH/HL/LH/LL Structure Tracker
🔹 Overview
HH/HL/LH/LL Structure Tracker automatically classifies every confirmed swing on your chart using pure Dow Theory — the original price-action framework that precedes and underlies every modern market-structure methodology. Each pivot high is labeled as a Higher High (HH) or Lower High (LH), and each pivot low as a Higher Low (HL) or Lower Low (LL). The sequence of the last four swings derives a live trend state: Bullish, Bearish, or Ranging.
No oscillators. No lagging averages. Just the raw geometry of price.
💎 What Makes This Different
While most "market structure" indicators focus on Break-of-Structure or Change-of-Character logic layered with Smart Money terminology, this script returns to the foundation: the four-swing classification that Charles Dow documented over a century ago. The result is an uncluttered, universally readable overlay that communicates structural context at a glance — regardless of which higher-level methodology you apply next (SMC, Wyckoff, Elliott, or classical technical analysis).
Key differentiators versus generic HH/HL scripts on the public library:
• Live structure range zone that dynamically recolors with the trend state (bullish teal, bearish pink, ranging amber).
• Bull Streak and Bear Streak counters — a quantifiable measure of trend persistence (e.g. "3 consecutive HH-HL swings").
• Semantic break classification: the panel distinguishes a continuation break (HH or LL broken in trend direction) from a reversal break (LH or HL broken against the prior structure).
• Progressive label offset algorithm: when several same-type swings cluster without an intervening opposite swing, each subsequent label is offset further from price, eliminating the overlap that plagues most swing scripts on fast-moving charts.
• AGPro design language: premium info panel, adjustable font size and theme, and a disciplined color palette.
🧠 Methodology
1. Pivot detection. A confirmed swing high is a bar whose high exceeds the preceding and following N bars (N = Pivot Length, default 5). Confirmed swing lows mirror the rule. Confirmation occurs N bars after the pivot bar, never repaints.
2. Swing classification. Each new confirmed high is compared to the previous confirmed high. If greater, it is HH; if lesser, LH. Lows are compared to the previous low: greater means HL, lesser means LL.
3. Trend derivation. If the most recent high is HH and the most recent low is HL, the trend state is Bullish. If LH and LL, Bearish. Any mixed sequence (HH + LL, LH + HL) returns Ranging.
4. Structure range zone. A rectangle is drawn between the most recent swing high and most recent swing low. The zone is always current: as new swings confirm, the zone updates in place. Zone color tracks the trend state.
5. Structure break. A close above the most recent swing high (or below the most recent swing low) fires a break event. The type of swing broken is reported — breaking an LH or HL typically precedes a trend reversal; breaking an HH or LL typically signals continuation.
📊 Signals & Alerts
Three optional alert types are available, each using "once per bar close" frequency to prevent intrabar noise:
• New Higher High confirmed — fires when a fresh HH is classified.
• New Lower Low confirmed — fires when a fresh LL is classified.
• Structure break — fires on a close outside the current structure range, labeled as either (reversal signal) or (continuation).
The live info panel reports: Trend state, Bull Streak, Bear Streak, Last High (with type and price), and Last Break (with type and price).
⚙️ Key Inputs
• Pivot Length — sensitivity of swing detection (2 to 50). Lower values capture minor structure; higher values isolate major swings only. Typical: 3–8 intraday, 5–15 swing trading.
• Max Visible Labels — caps the number of historical labels kept on the chart to preserve a premium uncluttered look.
• Label & Panel Font Size — five sizes from Tiny to Huge, default Normal.
• Label Distance from Price (ATR) — base vertical offset of labels from pivot candles.
• Structure Range Zone — toggle, transparency, and border.
• Trend Background Tint — subtle bullish or bearish chart shading.
• Info Panel — toggle, location (six positions), and theme (Dark or Light).
• Alerts — independent toggles for new HH, new LL, and structure break.
🎯 How to Use
Context tool, not a standalone signal generator. Use the trend state to filter entries from your primary methodology: take long setups only while Trend is Bullish and Bull Streak is building, or vice versa. The structure range zone highlights the active battleground between buyers and sellers — trades taken inside the zone are counter-trend by definition, trades taken on a decisive break of the zone align with the emerging new trend.
Reversal breaks (LH or HL broken) are high-information events — they are often the first objective signal that a prevailing trend is losing conviction, ahead of any moving-average cross or momentum divergence. Continuation breaks (HH or LL broken) are confirmation events that validate staying with the trend.
Works on all markets and all timeframes. Particularly effective on liquid instruments with clear structural rhythm: major crypto pairs, FX majors, index futures, and large-cap equities.
⚠️ Limitations & Transparency
• Pivot confirmation requires N bars after the swing; the most recent unconfirmed swing is never labeled.
• In low-volatility sideways regimes, pivot clustering is inevitable — the Pivot Length input should be raised to filter noise on ranging charts.
• The trend state is derived from only the last two swings; it does not account for higher-timeframe context. Pair with a higher-timeframe version of the same script for multi-timeframe confluence.
• Does not provide entry, stop, or target levels. It is a structural framework, not a complete trading system.
📌 Risk Disclosure
This indicator is for educational and analytical purposes only. It does not constitute financial advice, a trading recommendation, or a guarantee of future performance. All trading involves risk of loss. Past structural patterns do not guarantee future outcomes. Always conduct your own due diligence and use appropriate risk management. Indicator

Indicator

Multi-Oscillator Consensus Engine [AGPro Series]Multi-Oscillator Consensus Engine
🔹 Overview
Multi-Oscillator Consensus Engine aggregates ten independent momentum
oscillators into a single regime classifier with overlay Consensus Zones,
flip event labels, and agreement persistence tracking. Instead of watching
ten charts separately, traders see one unified answer: are the oscillators
in agreement, and what is the consensus saying right now?
The script monitors RSI, Stochastic, CCI, MFI, Williams %R, ROC, Ultimate
Oscillator, MACD, DMI balance, and Aroon balance. Each oscillator is
normalized to a 0–100 scale and votes bullish, bearish, or neutral against
configurable thresholds. The aggregated vote determines the market regime
and drives everything else on the chart.
🔹 Unique Edge
Most multi-oscillator tools stop at a dashboard or a simple agreement
percentage. This engine goes further:
- Regime Classification — four distinct states (Consensus Bull, Consensus
Bear, Divergent, Transition) instead of a binary signal.
- Consensus Zones — a horizontal price zone is born at every regime flip
and stays alive while the regime holds. When the regime ends, the zone
becomes historical structure.
- Flip Event Labels — regime transitions are marked directly on price
with merged flip + extreme agreement tags.
- Persistence Tracking — streak bars, last flip distance, and historical
extreme rate tell you how trustworthy the current consensus is.
- Label Discipline — cooldown, horizontal stagger, and flip+extreme merge
logic keep the chart readable even in choppy regimes.
🔹 Methodology
Step 1. Ten oscillators are computed with their classic defaults and
normalized to a 0–100 range. Indicators with native 0–100 output (RSI,
Stochastic, MFI, Ultimate) pass through directly. Others (CCI, ROC, MACD
histogram) are rescaled against their own recent range. Williams %R is
flipped from its native -100..0 scale.
Step 2. Each normalized oscillator casts a vote. Values above the bullish
threshold vote +1, values below the bearish threshold vote -1, everything
else is neutral. Vote counts and agreement percentage are computed bar by bar.
Step 3. Regime is assigned from the vote distribution. Seven or more votes
in one direction triggers Consensus Bull or Consensus Bear. A tight spread
(bull-bear difference ≤ 2) triggers Divergent. Everything else is a
Transition state.
Step 4. On every bull↔bear regime entry, a new Consensus Zone is born at
the current close ± a configurable ATR multiple. The zone extends forward
while the regime is active and locks in place when the regime ends. A
maximum of five active zones keeps the chart clean.
Step 5. Labels are rendered only when cooldown and merge rules allow.
Extreme agreement events (80%+ by default) are either merged into the flip
label or drawn separately with larger offset.
🔹 Signals & Alerts
Seven alert conditions ship with the script:
- Consensus Bull Entry — regime has just entered Consensus Bull
- Consensus Bear Entry — regime has just entered Consensus Bear
- Consensus Bull Flip — direct Bear → Bull transition
- Consensus Bear Flip — direct Bull → Bear transition
- Extreme Bullish Agreement — agreement crosses the extreme threshold up
- Extreme Bearish Agreement — same, on the bearish side
- Consensus Streak 20+ — current regime has held for twenty bars
🔹 Key Inputs
- Oscillator Periods — individual length settings for all ten oscillators
- Bullish / Bearish Thresholds — the normalized levels that define a vote
- Consensus Threshold — how many oscillators must agree for a regime (default 7/10)
- Extreme Agreement — agreement percentage for extreme events (default 80%)
- Consensus Zones — show/hide, ATR length and multiplier, max active count,
closed zone trail
- Label Cooldown — minimum bars between flip labels, prevents clutter
- Merge Flip + Extreme — combine same-bar events into one label
- Panel — six location options, Dark/Light theme, font sizes
🔹 How to Use
Trend traders: wait for a Consensus Bull or Consensus Bear regime to
establish (streak > 5 bars), then use pullbacks into the active Consensus
Zone as entries in the regime direction. Exit on opposite regime flip.
Reversion traders: Extreme Agreement events mark moments where all
oscillators are stretched in the same direction. These are classic mean
reversion setups. Wait for a regime flip against the extreme, confirmed on
the next bar.
Regime filter: overlay the panel on any chart and use the Regime and
Agreement readings as a binary filter for your primary system. Only take
longs when regime is Bull, only take shorts when regime is Bear.
Works on all timeframes from 1m to 1W. Higher timeframes produce fewer
but higher-conviction signals.
🔹 Limitations & Transparency
- The oscillator votes use normalized thresholds. On extremely narrow
ranges, the normalization may produce unstable votes. Raising the
Bullish/Bearish Thresholds reduces this sensitivity.
- Consensus Zones are drawn from close price at the flip bar. Large wick
bars may place the zone slightly away from the visual pivot.
- The script is not a standalone trading system. It is a confluence and
regime tool to combine with your own structure, volume, or price action
analysis.
- All signals repaint only within the current forming bar. Once a bar
closes and barstate.isconfirmed is true, flip labels and zones are final.
🔹 Risk Disclosure
This indicator is provided for educational and analytical purposes only.
It is not financial advice. Trading involves substantial risk. Past
behavior of regime transitions does not guarantee future performance.
Always use proper risk management and never risk more than you can afford
to lose. Indicator

Histogram by RumiancevRumiancev Histogram R/S/M
Rumiancev Histogram R/S/M is an open-source momentum indicator designed to combine three analytical layers in a single pane: a histogram-based Ergodic-style momentum model, two optional EMA overlays applied directly to the histogram, and an optional Adaptive RSI module with its own signal line and centered levels.
The goal of this script is to provide a compact but flexible momentum workspace. Instead of forcing the user to stack several separate tools on the chart, this script brings the main momentum histogram, short smoothing overlays, and an additional adaptive strength filter together in one place. The result is a cleaner workflow for traders who want to read momentum shifts, short-term acceleration, slowing conditions, and auxiliary RSI-style confirmation from a single panel.
General idea
The script is built around a normalized momentum histogram. It measures bar-to-bar price change, smooths that movement in multiple stages, and compares directional movement against total movement. This allows the oscillator to focus not only on whether price is rising or falling, but also on how efficiently price is moving in one direction relative to overall fluctuation.
A signal line is applied to the main oscillator value, and the histogram represents the distance between the oscillator and that signal. This makes the histogram useful for tracking momentum expansion and momentum contraction around the zero line.
In addition to the histogram, the script can display two optional EMA lines derived from the histogram itself. These lines help users visually filter short-term noise and better judge whether recent histogram movement is strengthening, fading, or transitioning.
The script also includes an optional Adaptive RSI module. This is not plotted in the classic RSI panel style. Instead, it is centered around zero and scaled so it can coexist with the histogram in the same pane. This gives the user an extra confirmation layer without requiring a separate indicator window.
How the main histogram works
The core oscillator uses the change in closing price from one bar to the next. First, the script calculates the raw directional change. Then it calculates the absolute value of that same change. These two series represent direction and total movement.
Both series are then smoothed in two stages. The first stage uses the selected fast smoothing method and fast length. The second stage uses the selected slow smoothing method and slow length. After these smoothing steps, the script divides the smoothed directional movement by the smoothed absolute movement and multiplies the result by 100. This creates a normalized momentum reading.
That normalized reading becomes the main oscillator value. A separate signal line is then calculated using the selected signal smoothing method and signal length. The histogram is the difference between the main oscillator and the signal line.
This construction allows the histogram to react to changing momentum conditions while remaining more structured than a simple unsmoothed rate-of-change style plot.
How to read the histogram
When the histogram is above zero, the main oscillator is above its signal line, which suggests positive momentum pressure. When the histogram is below zero, the main oscillator is below its signal line, which suggests negative momentum pressure.
If histogram bars are growing while already above zero, that often means bullish momentum is strengthening. If histogram bars are shrinking above zero, bullish pressure may still be present, but it is losing force. The same logic applies below zero: expanding negative bars can suggest increasing bearish pressure, while shrinking negative bars can suggest that bearish momentum is weakening.
The zero line is the main structural reference. Crosses above and below zero can be used to identify transitions in short-term momentum balance. However, like any momentum tool, the histogram should be interpreted in context, especially when price is ranging or when volatility suddenly expands.
EMA overlays on the histogram
The script includes two optional EMA lines, named Yellow EMA and Blue EMA in the settings. These are calculated from the histogram values, not from price.
Their purpose is visual smoothing. Some traders prefer to read the raw histogram alone. Others prefer to see one or two smoothed references that make short swings easier to interpret. Because these EMAs are applied to the histogram, they can help reveal whether momentum is accelerating into a move, flattening, or starting to roll over before a more visible shift in the histogram bars occurs.
The Yellow EMA is typically used as the faster smoothing line, while the Blue EMA can be treated as the slower companion line. Users may keep both hidden, display one of them, or display both depending on their preferred chart-reading style.
Adaptive RSI module
The Adaptive RSI included in this script is designed as an auxiliary momentum filter rather than a standard standalone RSI replacement. Instead of using the classic up-close versus down-close averaging approach only, this version evaluates directional pressure using the relationship between recent range expansion, recent range contraction, and ordinary bar-to-bar movement.
The script first examines the highest and lowest values over the selected RSI length. From there it measures whether the recent range is expanding upward, expanding downward, or whether current movement is better represented by the direct step from one bar to the next. That directional movement is then smoothed, compared to its absolute magnitude, and transformed into an RSI-style value centered around 50.
To make this RSI usable inside the same pane as the histogram, the script recenters it around zero by subtracting 50 and then multiplying the result by the RSI Scale input. The signal line for the Adaptive RSI is calculated separately using its own signal length and smoothing mode.
This gives the user a secondary confirmation line that can be visually aligned with the histogram without opening another indicator panel.
How to read the Adaptive RSI in this script
Because the Adaptive RSI is centered and scaled, it should not be interpreted exactly like a classic RSI pane. Its purpose here is relative confirmation.
If the Adaptive RSI is rising and the histogram is also strengthening, the two layers are confirming each other. If the histogram is trying to recover while the Adaptive RSI remains weak or rolls over quickly, that may suggest the move has limited follow-through. If both the histogram and the Adaptive RSI signal line turn together, momentum alignment is clearer. If one improves while the other lags, the market may be in transition or lacking conviction.
The optional overbought, midline, and oversold levels provide extra visual structure for this centered RSI display. Since the RSI is scaled into the histogram pane, these levels are translated into centered equivalents instead of being shown as standard 70, 50, and 30 horizontal lines in a separate RSI panel.
Input settings explained
Fast Length controls the first smoothing stage of the main momentum calculation. Smaller values make the oscillator more responsive. Larger values make it smoother and slower.
Slow Length controls the second smoothing stage of the main oscillator. Increasing it generally reduces noise further and creates a more stable but slower-moving histogram.
Signal Length controls how quickly the oscillator signal line responds. A shorter signal length makes the histogram react faster because the gap between oscillator and signal changes more quickly. A longer signal length tends to produce smoother histogram transitions.
Fast Smoothing determines the smoothing method used in the first stage of the oscillator calculation. Slow Smoothing determines the smoothing method used in the second stage. Signal Smoothing determines the smoothing method used for the oscillator signal line. Available choices are EMA, SMA, RMA, WMA, HMA, and TMA.
Yellow EMA enables or disables the first histogram EMA overlay. Blue EMA enables or disables the second histogram EMA overlay.
Yellow EMA Length sets the period for the faster EMA overlay on the histogram. Blue EMA Length sets the period for the second EMA overlay.
Show Adaptive RSI enables or disables the centered Adaptive RSI line.
Show RSI Signal enables or disables the signal line of the Adaptive RSI.
Show RSI Levels enables or disables the centered overbought, midline, and oversold reference levels for the Adaptive RSI display.
RSI Source defines which price source is used for the Adaptive RSI calculation. The default is HLC3, but the user can choose any source supported by Pine input.source.
RSI Length controls the lookback used by the Adaptive RSI model.
RSI Smoothing selects the smoothing method applied inside the Adaptive RSI calculation.
RSI Signal Length controls the smoothing length of the Adaptive RSI signal line.
Signal Smoothing in the RSI section selects the smoothing method used for the Adaptive RSI signal line.
RSI Scale controls how strongly the centered RSI is expanded or compressed inside the histogram pane. Lower values make the RSI layer more compact. Higher values make it visually more pronounced.
RSI Overbought sets the upper reference threshold used by the Adaptive RSI.
RSI Oversold sets the lower reference threshold used by the Adaptive RSI.
Smoothing modes explained briefly
EMA responds relatively quickly and is often a good default for momentum work.
SMA is straightforward and balanced, but usually a bit slower in turning points.
RMA is smoother and often produces steadier transitions.
WMA places more emphasis on recent values than SMA.
HMA is generally more responsive and may suit users who want faster turning behavior with reduced lag.
TMA is heavily smoothed and may suit users who prefer a calmer visual structure over fast reaction.
Different smoothing combinations can materially change the character of the indicator. A user looking for responsiveness may prefer faster lengths and more reactive smoothing types. A user focused on broader trend pressure may prefer heavier smoothing and longer lengths.
Practical ways to use the script
One common approach is to use the histogram as the primary trigger layer and the Adaptive RSI as a confirmation filter. In that workflow, the user watches for histogram recovery from negative values, histogram expansion above zero, or histogram contraction below zero, then checks whether the Adaptive RSI is moving in the same direction.
Another approach is to focus on momentum quality rather than signals. In that case, the user may ignore exact crosses and instead study whether histogram bars are expanding, flattening, or diverging in behavior from price structure. The EMA overlays can be helpful here because they smooth the histogram without hiding its basic structure.
Some users may also treat the script as a trend-phase tool. Sustained positive histogram behavior combined with a stable or rising Adaptive RSI can support a bullish phase reading. Sustained negative histogram behavior combined with weak Adaptive RSI behavior can support a bearish phase reading. Mixed readings can indicate consolidation, transition, or an early reversal attempt that still lacks confirmation.
Important interpretation notes
This indicator is designed to measure momentum structure, not to predict the future. It should not be treated as a standalone trading system.
Momentum indicators can remain strong or weak for longer than expected during trending conditions. They can also produce frequent transitions during sideways markets. For that reason, this script is best used with price structure, higher timeframe context, risk management, and the user’s own trade process.
No divergence module is included in this version. The focus of the script is the histogram engine, histogram EMA overlays, and the Adaptive RSI confirmation layer.
Who this script may be useful for
This script may be useful for traders who want a momentum-focused indicator that remains visually compact while still offering more than a single raw oscillator line. It can suit discretionary traders who read chart structure manually, as well as users who want a clean supporting tool for directional bias, momentum confirmation, or timing refinement.
It may be especially useful for users who like histogram-based momentum analysis but also want an additional internal filter without loading a second separate RSI pane.
Open-source note
This script is published as open-source so traders and Pine users can study the logic, verify how it works, adapt it to their own process, and build on it if they find it useful. Indicator

Rolling Midpoint Engine [AGPro Series]Rolling Midpoint Engine
### Overview
Rolling Midpoint Engine is an on-chart study that converts the geometric midpoint of the last N bars' high-low range into a living control line. The midline is tracked through three behavioral states — Accepted Above, Accepted Below, and Fight — and a fourth modifier (Strong) highlights high-conviction acceptance beyond an ATR threshold. The goal is to surface how price behaves around a single dominant reference level, not to predict direction or issue trade signals.
### Unique Edge
Most midpoint tools plot a static line and let the user eyeball whether price accepts or rejects it. Rolling Midpoint Engine formalises that observation into a finite state machine that requires consecutive body-closes on one side of the midline before declaring acceptance. This filters single-bar noise and distinguishes casual tags from genuine commitment. The ATR-based Strong modifier adds a second axis of information — how firmly the current side is being held — without multiplying states or cluttering the chart with additional lines.
### Methodology
The midline is computed as the average of the highest high and the lowest low over a user-defined rolling window. Optional light EMA smoothing reduces visual jitter without materially shifting the level; a Strict Reset mode disables smoothing for pure rolling output.
Acceptance is evaluated through two streak counters tracking consecutive closes (or full bars, if the user prefers a stricter rule) on each side of the midline. When a streak reaches the Acceptance Bars threshold, the state transitions to Accepted Above or Accepted Below. If the running streak is positive but below threshold, the state is Fight. A Strong flag activates whenever the current distance from the midline exceeds a configurable ATR multiple.
All logic uses confirmed bar closes. The script does not repaint historical states once a bar has closed.
### States & Alerts
States:
- Fight — price is oscillating around the midline without sustained commitment
- Accepted Above — body-closes above the midline for the required number of bars
- Accepted Below — body-closes below the midline for the required number of bars
- Strong (modifier) — current Accepted state is held beyond the ATR threshold
Alerts:
- Midline Crossed Up / Down — raw price cross of the midline
- Accepted Above / Below — state transitions into acceptance
- Midline Rejection — state flip between Accepted Above and Accepted Below, or collapse from an Accepted state back to Fight
### Key Inputs
- Rolling Length — number of bars defining the range window
- Strict Reset Mode — toggle between pure rolling midline and lightly smoothed output
- Acceptance Bars — consecutive body-closes required for acceptance
- Use Body Close vs. Full Bar — strictness of the side-determination rule
- Strong Threshold — ATR multiple that qualifies an accepted side as Strong
- Label Style / Size — Edge Only, Edge + Transitions, or Off
- Panel Location / Theme / Font Size — four corners plus Middle Right, Dark / Light / Auto themes
- Color Midline by State — toggle state-coloring on the dominant line
### How to Use
Apply the indicator to any symbol and timeframe. The midline acts as a rolling control level; the state label on the right edge summarises the current behavior. Treat Accepted Above / Below as evidence that the midline is holding as support or resistance on the corresponding side. A transition into Strong indicates the holding is well beyond routine noise. A rejection event — the state flipping or collapsing back to Fight — suggests the prior control has been compromised.
This is a contextual reading tool. It does not produce entries, exits, targets, or stops, and should not be read as a recommendation to transact.
### Limitations & Transparency
The midline reflects past price data only and will adapt as new highs or lows enter the rolling window. On illiquid or very low-timeframe charts, the streak-based acceptance logic can feel slow; increasing Acceptance Bars on noisier instruments or lowering it on cleaner ones is expected tuning. The Strong Threshold is volatility-relative via ATR but still an arbitrary cut — defaults are calibrated for typical liquid markets and may need adjustment for thinly traded symbols.
The script uses confirmed closes and does not alter historical state once a bar has closed. Intrabar, the displayed state can update in line with current price, as with any live indicator.
### Risk Disclosure
This indicator is an analytical study. It is not a strategy, not a signal service, and not financial advice. It does not forecast future prices and does not guarantee any outcome. Past behavior of price around the midline does not imply future behavior. Every trading decision is the sole responsibility of the user. Use appropriate risk management and test the tool in a non-committed environment before incorporating it into any workflow. Indicator

HeikinAshiTrendUtilities
Library HeikinAshiTrendUtilities
This library contains reusable Heikin Ashi helpers for building Pine scripts that use Heikin Ashi as more than a candle style.
It centralizes the Heikin Ashi foundation, HA-based oscillator engines, streak and confirmed-trend logic, Pressure Meter helpers, max-move scanning, Fib Backbone structure helpers, and Primary Trend helpers so those parts do not need to be rewritten across multiple scripts.
Everything on the example chart is materially driven by the library, whether through the Heikin Ashi calculations themselves, the HA-based oscillator and pressure engine, the predictive close logic, the smoothed HA overlay, the Fib Backbone context window, or the structure geometry used to project key analytical visuals.
How to use
Import the library near the top of your script in global scope, alongside any other imports, before you start calling its helpers.
Typical placement:
• //@version=6
• indicator(...) or strategy(...)
• import MYNAMEISBRANDON/HeikinAshiTrendUtilities/1 as haUtils
For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script User Manual: www.pulsewire.com
➖Heikin Ashi Core Helpers➖
These helpers handle the basic building blocks of Heikin Ashi. They let a script create standard HA candles, estimate the price needed to flip the current HA candle, and generate a smoothed HA version for a cleaner trend view. In other words, this region provides the core HA math used to build the rest of the library’s trend, engine, and structure tools.
heikinAshi(openValue, closeValue, highValue, lowValue, haOpenPrev, haClosePrev)
Builds one Heikin Ashi candle from real OHLC and prior HA state
Parameters:
openValue (float): Real open
closeValue (float): Real close
highValue (float): Real high
lowValue (float): Real low
haOpenPrev (float): Prior Heikin Ashi open
haClosePrev (float): Prior Heikin Ashi close
Returns: HA open, HA close, HA high, HA low, is HA up, is HA down
haPredictClose(haOpen, openValue, highValue, lowValue)
Estimates the real close price needed to flip the current HA candle
Parameters:
haOpen (float): Current Heikin Ashi open
openValue (float): Real open
highValue (float): Real high
lowValue (float): Real low
Returns: Predicted real close needed to flip the HA candle
smoothedHeikinAshi(openValue, highValue, lowValue, closeValue, len1, len2)
Builds double-smoothed Heikin Ashi values from real OHLC inputs
Parameters:
openValue (float): Real open
highValue (float): Real high
lowValue (float): Real low
closeValue (float): Real close
len1 (simple int): First EMA smoothing length applied to real OHLC
len2 (simple int): Second EMA smoothing length applied to HA OHLC
Returns: Smoothed HA open, smoothed HA high, smoothed HA low, smoothed HA close, is smoothed HA up, is smoothed HA down
➖HA Oscillator Foundation Helpers➖
These helpers turn raw Heikin Ashi candle movement into a usable oscillator foundation. They measure the HA candle’s bullish or bearish range, normalize that movement so it can be compared more consistently across bars, and build upper/lower guide levels that help a script judge when that oscillator is stretching into stronger trend pressure. In other words, this region creates the base signal that the HA Blend, HA Range Base, color engine, and Pressure Meter can build from.
haSignedRangePct(haHigh, haLow, haClose, haIsBull, haIsBear)
Returns the signed HA range-percent foundation used by the oscillator engine
Parameters:
haHigh (float): Heikin Ashi high
haLow (float): Heikin Ashi low
haClose (float): Heikin Ashi close
haIsBull (bool): True when the current HA candle is bullish
haIsBear (bool): True when the current HA candle is bearish
Returns: Signed HA range-percent foundation
haPreparedOscSource(signedSrc, normLen, useClamp, clampRange)
Returns the normalized / optionally clamped HA oscillator source
Parameters:
signedSrc (float): Signed HA foundation
normLen (simple int): Normalization lookback length
useClamp (simple bool): Whether the normalized result should be clamped
clampRange (float): Absolute clamp boundary when useClamp is true
Returns: Prepared HA oscillator source
haOscGuides(src, lookback, guideFactor)
Returns upper and lower threshold guides from an oscillator series
Parameters:
src (float): Oscillator series
lookback (simple int): Guide lookback window
guideFactor (float): Scaling factor applied to the highest/lowest values
Returns: Upper guide, lower guide
➖HA Blend Engine Helpers➖
These helpers take the prepared HA oscillator source and turn it into a smoother trend engine by blending multiple EMA pairs together. They let the script choose a faster, more balanced, or slower blend profile, then optionally smooth that final output one more time. In other words, this region builds the more layered, trend-following version of the HA oscillator engine.
haBlendPairStackText(pairSet)
Returns the active EMA pair-stack text for the selected HA Blend pair set
Parameters:
pairSet (simple string): Pair-set label. Expected values: "Fast", "Balanced", or "Slow"
Returns: Pair-stack text
haBlendEngineCore(src, pairSet)
Returns the raw HA Blend engine core before final smoothing
Parameters:
src (float): Prepared HA signed source used by the blend engine
pairSet (simple string): Pair-set label. Expected values: "Fast", "Balanced", or "Slow"
Returns: Raw HA Blend engine core
haBlendEngine(src, pairSet, useFinalSmooth, finalSmoothLen, finalSmoothType)
Returns the final HA Blend engine with optional final smoothing
Parameters:
src (float): Prepared HA signed source used by the blend engine
pairSet (simple string): Pair-set label. Expected values: "Fast", "Balanced", or "Slow"
useFinalSmooth (simple bool): Whether final smoothing should be applied
finalSmoothLen (simple int): Final smoothing length
finalSmoothType (simple string): Final smoothing type. Expected values: "EMA" or "SMA"
Returns: Final HA Blend engine
➖HA Range Base Engine Helpers➖
These helpers take the prepared HA oscillator source and smooth it in a more direct way than the Blend engine. Instead of combining multiple EMA pairs, they use one selected smoothing length and MA type to create a cleaner base trend signal, with the option to smooth that result one more time. In other words, this region builds the simpler, more straightforward version of the HA oscillator engine.
haRangeEngineCore(src, rangeLen, rangeMaType)
Returns the raw HA Range Base engine core before final smoothing
Parameters:
src (float): Prepared HA signed source used by the Range Base engine
rangeLen (simple int): Core smoothing length used by the Range Base engine
rangeMaType (simple string): Core smoothing type. Expected values: "EMA" or "SMA"
Returns: Raw HA Range Base engine core
haRangeEngine(src, rangeLen, rangeMaType, useFinalSmooth, finalSmoothLen, finalSmoothType)
Returns the final HA Range Base engine with optional final smoothing
Parameters:
src (float): Prepared HA signed source used by the Range Base engine
rangeLen (simple int): Core smoothing length used by the Range Base engine
rangeMaType (simple string): Core smoothing type. Expected values: "EMA" or "SMA"
useFinalSmooth (simple bool): Whether final smoothing should be applied
finalSmoothLen (simple int): Final smoothing length
finalSmoothType (simple string): Final smoothing type. Expected values: "EMA" or "SMA"
Returns: Final HA Range Base engine
➖HA Threshold Color Helpers➖
This helper takes centered oscillator behavior and turns it into a usable visual color state. It helps a script decide when the HA-based oscillator is rising or falling above or below its guide levels so candles, rows, or other visuals can reflect stronger or weaker trend pressure.
haThresholdStateColor(src, upperGuide, lowerGuide, aboveUpperRiseColor, aboveZeroRiseColor, aboveZeroFallColor, belowZeroFallColor, belowLowerFallColor, belowZeroRiseColor)
Resolves a visual color from centered-oscillator threshold state
Parameters:
src (float): Source series
upperGuide (float): Upper threshold guide
lowerGuide (float): Lower threshold guide
aboveUpperRiseColor (color): Color used when src is above the upper guide and rising
aboveZeroRiseColor (color): Color used when src is above zero and rising
aboveZeroFallColor (color): Color used when src is above zero and falling
belowZeroFallColor (color): Color used when src is below zero and falling
belowLowerFallColor (color): Color used when src is below the lower guide and falling
belowZeroRiseColor (color): Color used when src is below zero and rising
Returns: Resolved visual color
➖HA Structure Scan Helpers➖
This helper scans a chosen lookback window and finds the strongest completed move inside it. It compares bullish and bearish candidates in the same scan, then returns whichever move was stronger along with the start and end anchors. In other words, this region gives a script a reusable way to locate the dominant move that can later be used for Fib Backbone structure, Primary Max Move logic, or other trend-structure work. :contentReference {index=0} :contentReference {index=1}
haScanMaxMove(lookback, includeCurrentBar, highSeries, lowSeries)
Scans a lookback window for the strongest upward or downward percentage move
Parameters:
lookback (simple int): Number of bars to scan
includeCurrentBar (simple bool): Whether bar 0 should be included in the scan
highSeries (float): High series used for upward and downward move detection
lowSeries (float): Low series used for upward and downward move detection
Returns: Winning direction, winning percent move, winning start bars-ago, winning end bars-ago, winning span bars
➖HA Streak Helpers➖
These helpers let a script keep track of active Heikin Ashi streaks. They determine whether the current HA sequence is bullish or bearish, count how long that streak has been running, assign a tier color based on streak length, and measure how far price has moved from the streak’s starting point. In other words, this region helps turn raw HA trend runs into usable streak state, color, and percent-move data for candles, rows, labels, and trend readouts. :contentReference {index=0}
haStreakState(haOpen, haClose, bullCountPrev, bearCountPrev)
Resolves raw HA bull/bear state, streak counts, and streak start offset
Parameters:
haOpen (float): Current Heikin Ashi open
haClose (float): Current Heikin Ashi close
bullCountPrev (int): Prior bullish streak count
bearCountPrev (int): Prior bearish streak count
Returns: is HA bullish, is HA bearish, bullish streak count, bearish streak count, current streak length, streak start bars-ago
haStreakTierColor(isHaBull, isHaBear, bullCount, bearCount, streakTierBars, bullTier1, bullTier2, bullTier3, bullTier4, bearTier1, bearTier2, bearTier3, bearTier4, neutralColor)
Returns the active streak-tier color from bull/bear streak counts
Parameters:
isHaBull (bool): True when the current HA streak is bullish
isHaBear (bool): True when the current HA streak is bearish
bullCount (int): Current bullish streak count
bearCount (int): Current bearish streak count
streakTierBars (simple int): Number of bars required before advancing to the next tier
bullTier1 (color): Bullish tier 1 color
bullTier2 (color): Bullish tier 2 color
bullTier3 (color): Bullish tier 3 color
bullTier4 (color): Bullish tier 4 color
bearTier1 (color): Bearish tier 1 color
bearTier2 (color): Bearish tier 2 color
bearTier3 (color): Bearish tier 3 color
bearTier4 (color): Bearish tier 4 color
neutralColor (color): Fallback color when no active streak is available
Returns: Active streak-tier color
haStreakPct(isHaBull, isHaBear, streakBars, highSeries, lowSeries)
Returns the wick-based percent move from the streak start to the current bar
Parameters:
isHaBull (bool): True when the current HA streak is bullish
isHaBear (bool): True when the current HA streak is bearish
streakBars (int): Current active streak length
highSeries (float): High series used for streak measurement
lowSeries (float): Low series used for streak measurement
Returns: Wick-based streak percent move
➖Confirmed HA Trend Helpers➖
These helpers let a script work with a slower, confirmation-based HA trend instead of flipping immediately on the first opposite HA candle. They track the currently confirmed direction, count how many opposite candles are building toward the next possible flip, project the confirmed trend using regular-price body or wick anchors, and measure how far that confirmed trend has moved from its confirmed start. In other words, this region helps scripts build a more stable HA trend model that filters out some of the noise of raw HA flips. :contentReference {index=0} :contentReference {index=1}
haConfirmedTrendState(enabled, rawDir, confirmBars, dirPrev, oppCountPrev, startBarPrev, firstOppBarPrev)
Resolves confirmed trend direction, build count, and confirmed start bar
Parameters:
enabled (simple bool): Whether the confirmed-trend engine is active
rawDir (int): Current raw HA direction: +1 bull, -1 bear, 0 neutral
confirmBars (simple int): Consecutive opposite raw HA bars required to confirm a flip
dirPrev (int): Prior confirmed direction
oppCountPrev (int): Prior opposite-side build count
startBarPrev (int): Prior confirmed trend start bar index
firstOppBarPrev (int): Prior first opposite raw HA bar index
Returns: Confirmed direction, opposite-side build count, confirmed start bar index, first opposite raw HA bar index, confirmed leg bars, confirmed start bars-ago
haConfirmedTrendProjection(confirmedDir, startOffset, openValue, highValue, lowValue, closeValue, anchorMode, pathMode, forwardBars)
Returns confirmed trend projection geometry from body/wick anchor rules
Parameters:
confirmedDir (int): Confirmed direction: +1 bull, -1 bear, 0 neutral
startOffset (int): Confirmed start bars-ago offset
openValue (float): Regular-price open
highValue (float): Regular-price high
lowValue (float): Regular-price low
closeValue (float): Regular-price close
anchorMode (simple string): Projection anchor mode: "Body" or "Wick"
pathMode (simple string): Projection path mode: "Same Side" or "Opposite Side"
forwardBars (simple int): Number of bars forward for projection
Returns: Has valid projection, start Y, current Y, future Y, slope
haConfirmedTrendPct(confirmedDir, startOffset, highSeries, lowSeries)
Returns confirmed streak percent movement from the confirmed start bar
Parameters:
confirmedDir (int): Confirmed direction: +1 bull, -1 bear, 0 neutral
startOffset (int): Confirmed start bars-ago offset
highSeries (float): HA high series used for confirmed move measurement
lowSeries (float): HA low series used for confirmed move measurement
Returns: Confirmed streak percent move
➖HA Pressure Meter Helpers➖
These helpers take the HA-based oscillator engine and convert it into an easier 0–100 pressure reading. They help a script decide when bullish or bearish pressure is becoming active, assign matching tier colors for rows or other visuals, and return the color state for a pressure strip or similar chart-edge signal. In other words, this region turns the HA oscillator into a simpler pressure model that is easier to read at a glance.
haPressureMeter(rawOsc, bullAnchor, bearAnchor)
Normalizes a raw oscillator value into a 0-100 Pressure Meter
Parameters:
rawOsc (float): Raw oscillator value
bullAnchor (float): Raw oscillator value that should map to 100
bearAnchor (float): Raw oscillator value that should map to 0
Returns: Pressure Meter value in the 0-100 range
haPressureState(pressureMeter, bullThreshold, bearThreshold)
Resolves bullish, bearish, and neutral threshold state from the Pressure Meter
Parameters:
pressureMeter (float): Normalized Pressure Meter value
bullThreshold (float): Meter level where bullish pressure becomes active
bearThreshold (float): Meter level where bearish pressure becomes active
Returns: Bull-active, bear-active, neutral-between
haPressureTierColors(pressureMeter, bullTier1, bullTier2, bullTier3, bullTier4, bearTier1, bearTier2, bearTier3, bearTier4, fallbackBg)
Returns tier-based pressure-row background and readable text color
Parameters:
pressureMeter (float): Normalized Pressure Meter value
bullTier1 (color): Bull tier 1 color
bullTier2 (color): Bull tier 2 color
bullTier3 (color): Bull tier 3 color
bullTier4 (color): Bull tier 4 color
bearTier1 (color): Bear tier 1 color
bearTier2 (color): Bear tier 2 color
bearTier3 (color): Bear tier 3 color
bearTier4 (color): Bear tier 4 color
fallbackBg (color): Fallback background when the meter is na
Returns: Row background color, row text color
haPressureStripColor(pressureMeter, bullThreshold, bearThreshold, bullTier1, bullTier2, bullTier3, bullTier4, bearTier1, bearTier2, bearTier3, bearTier4, neutralColor, activeTransp, neutralTransp)
Returns active or neutral strip color from the Pressure Meter state
Parameters:
pressureMeter (float): Normalized Pressure Meter value
bullThreshold (float): Meter level where bullish pressure becomes active
bearThreshold (float): Meter level where bearish pressure becomes active
bullTier1 (color): Bull tier 1 color
bullTier2 (color): Bull tier 2 color
bullTier3 (color): Bull tier 3 color
bullTier4 (color): Bull tier 4 color
bearTier1 (color): Bear tier 1 color
bearTier2 (color): Bear tier 2 color
bearTier3 (color): Bear tier 3 color
bearTier4 (color): Bear tier 4 color
neutralColor (color): Neutral-zone base color
activeTransp (int): Transparency used when bull or bear pressure is active
neutralTransp (int): Transparency used inside the neutral zone
Returns: Strip color
➖Fib Backbone Structure Helpers➖
These helpers take a winning max-move scan and turn it into the structure a script can use for Fib Backbone analysis. They define the backbone’s start and end anchors, determine the related support/resistance anchor geometry, calculate Fib level prices between those anchors, and measure how far current price is from those levels. In other words, this region helps convert a dominant move into a reusable backbone structure that can support diagonals, S/R anchors, boxes, and Fib-based readouts.
haFibBackboneStructure(dir, startBA, endBA, openValue, highValue, lowValue, closeValue)
Returns backbone coordinates, S/R anchors, and anchor-box geometry
Parameters:
dir (int): Winning move direction: +1 bull, -1 bear, 0 none
startBA (int): Winning move start bars-ago
endBA (int): Winning move end bars-ago
openValue (float): Regular-price open
highValue (float): Regular-price high
lowValue (float): Regular-price low
closeValue (float): Regular-price close
Returns: ok, xStart, xEnd, yStart, yEnd, startIsRes, endIsRes, anchorTopS, anchorBotS, anchorTopE, anchorBotE, isTopS, isTopE
haFibLevelPrice(yStart, yEnd, fibLevel)
Returns the price of one fib level between the backbone anchors
Parameters:
yStart (float): Backbone start anchor price
yEnd (float): Backbone end anchor price
fibLevel (float): Fib level such as 0.236, 0.382, 0.50, 0.618, 0.786
Returns: Fib level price
haFibPctFromClose(closeValue, fibPrice)
Returns percent distance from close to a fib level
Parameters:
closeValue (float): Current close
fibPrice (float): Fib level price
Returns: Percent from close to fib level
➖Fib Backbone Context Window Helpers➖
These helpers build the larger context window around the active Fib Backbone lookback. They let a script define the left/right range of that window, calculate its current high and low bounds, and find the midpoint of the same structure. In other words, this region helps frame the broader area that the active backbone move is being selected from, so the move can be viewed in context rather than in isolation.
haFibContextWindow(lookback, includeCurrentBar, sourceMode, highValue, lowValue, closeValue)
Returns the active Fib Backbone context window geometry
Parameters:
lookback (simple int): Context-window lookback length
includeCurrentBar (simple bool): Whether the current bar participates in the active window
sourceMode (simple string): Source selection. Expected values: "Wicks" or "Closes"
highValue (float): Regular-price high
lowValue (float): Regular-price low
closeValue (float): Regular-price close
Returns: ok, leftX, rightX, windowBars, windowHigh, windowLow, leftHigh, leftLow
haFibContextMidpoint(ok, windowHigh, windowLow)
Returns the midpoint of the active Fib Backbone context window
Parameters:
ok (bool): Whether the context window is valid
windowHigh (float): Active context-window high
windowLow (float): Active context-window low
Returns: Context-window midpoint
➖Primary Trend Window Helpers➖
These helpers scan a lookback window to find the strongest completed HA streak and turn that winner into usable trend information. They identify the winning streak, assign it the correct tier color, and return the anchor coordinates needed to project that streak as a chart-side diagonal. In other words, this region helps a script reduce a larger HA trend window down to its most important completed streak structure.
haPrimaryTrendWinner(lookback, haBull, haBear, bullCount, bearCount, haHigh, haLow)
Returns the strongest completed HA streak inside the lookback window
Parameters:
lookback (simple int): Number of bars to scan
haBull (bool): Bullish HA state series
haBear (bool): Bearish HA state series
bullCount (int): Bullish HA streak-count series
bearCount (int): Bearish HA streak-count series
haHigh (float): HA high series used for wick-based streak measurement
haLow (float): HA low series used for wick-based streak measurement
Returns: Winning streak length, winning direction, winning percent move, winning start bars-ago, winning end bars-ago, winning validity state
haPrimaryTrendTierColor(dir, streakLen, streakTierBars, bullTier1, bullTier2, bullTier3, bullTier4, bearTier1, bearTier2, bearTier3, bearTier4, fallbackBg)
Returns the winning Primary Trend tier color
Parameters:
dir (int): Winning streak direction: +1 bull, -1 bear, 0 none
streakLen (int): Winning streak length
streakTierBars (simple int): Number of bars required before advancing to the next tier
bullTier1 (color): Bullish tier 1 color
bullTier2 (color): Bullish tier 2 color
bullTier3 (color): Bullish tier 3 color
bullTier4 (color): Bullish tier 4 color
bearTier1 (color): Bearish tier 1 color
bearTier2 (color): Bearish tier 2 color
bearTier3 (color): Bearish tier 3 color
bearTier4 (color): Bearish tier 4 color
fallbackBg (color): Fallback background when no valid winner exists
Returns: Winning tier color
haPrimaryTrendCoords(dir, startBA, endBA, highSeries, lowSeries)
Returns diagonal coordinates from the winning streak anchors
Parameters:
dir (int): Winning streak direction: +1 bull, -1 bear, 0 none
startBA (int): Winning start bars-ago
endBA (int): Winning end bars-ago
highSeries (float): High series used for line anchors
lowSeries (float): Low series used for line anchors
Returns: ok, x1, x2, y1, y2
NOTES
This is a Heikin-Ashi-specific utility library. It is meant to provide the reusable HA math, state, and structure layer. Final rendering choices such as plot style, line objects, boxes, labels, tables, and overall UI layout are expected to remain script-level decisions.
Thanks to SimpleCryptoLife for the open-source HA core functions heikinAshi() & haPredictClose() and thus the inspiration that they've given me to create HA-based indicators for the HA trader enthusiast.
Library
