AETHERFLOW REVERSAL MATRIX (ARM)

Michael_Fx_Trader · study · 1084 行 · 点赞 184 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  AETHERFLOW REVERSAL MATRIX (ARM)
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//
//  ┌─ OWNERSHIP, AUTHORSHIP AND PUBLISHER DECLARATION ───────────────────────────────────────────┐
//  │  Indicator name ........ AETHERFLOW REVERSAL MATRIX (ARM)                                   │
//  │  Author ................ Michael_Fx_Trader                                                  │
//  │  Publisher ............. Michael_Fx_Trader                                                  │
//  │  Rights holder ......... Michael_Fx_Trader                                                  │
//  │  Copyright ............. © 2026 Michael_Fx_Trader. All rights reserved.                     │
//  │  Platform / language ... TradingView, Pine Script™ version 6                                │
//  │  First release ......... 2026-10-29 (v1.0.0)                                                │
//  └──────────────────────────────────────────────────────────────────────────────────────────────┘
//
//  ORIGINALITY VERIFICATION AND DECLARATION
//  ----------------------------------------
//  I, Michael_Fx_Trader, declare and verify the following regarding this script:
//   1. This script is an ORIGINAL implementation, written from scratch for the ARM project.
//   2. No source code, internal code structure, variable naming, or proprietary implementation
//      detail of any other published or closed-source indicator has been copied, decompiled,
//      reverse-engineered, or reused. The architecture, state machines, drawing engine, dashboard,
//      alert engine and all variable names are independently written.
//   3. The analytical ideas used (closing-price comparison sequences, low/high structure tests,
//      weighted open/close range pivots, volume-weighted candle-body pressure, volume-to-average
//      ratios) are general technical-analysis CONCEPTS that are widely documented. Every formula
//      actually used is written out in the "METHODOLOGY" section below, so the behaviour is fully
//      transparent. Where a formula adapts a general concept, it is identified as the ARM
//      implementation's own chosen methodology.
//   4. This script does NOT claim to reproduce the exact algorithm of any other product, and it is
//      not affiliated with, endorsed by, or derived from any third-party indicator or vendor.
//   5. All rights to this script, its structure, naming, visual identity and documentation belong
//      to Michael_Fx_Trader. Redistribution, resale, modification for republication, or
//      re-publishing under another name without written permission of the author is prohibited.
//
//  DISCLAIMER
//  ----------
//  ARM is an analytical / educational tool. It organizes market information. It does not predict
//  reversals, does not provide trade entries, does not calculate probabilities of profit, and does
//  not provide financial advice. Pressure percentages are volume-weighted candle-body ratios, NOT
//  probabilities. Invalidation levels and targets are analytical references, NOT stop-loss or
//  take-profit instructions. Trade decisions remain the responsibility of the user.
//
// ───────────────────────────────────────────────────────────────────────────────────────────────
//  METHODOLOGY (exact formulas implemented in this script)
// ───────────────────────────────────────────────────────────────────────────────────────────────
//  TERMINOLOGY
//    Buy-side exhaustion  = a DOWNWARD sequence (close < close[4]); may eventually create conditions
//                           for a bullish reversal. Markers sit BELOW bars.
//    Sell-side exhaustion = an UPWARD sequence (close > close[4]); may eventually create conditions
//                           for a bearish reversal. Markers sit ABOVE bars.
//    This describes the exhaustion being monitored. It is not an instruction to enter a trade.
//
//  1. MOMENTUM EXHAUSTION (count 1..9)
//     down = close < close[4]   |   up = close > close[4]
//     EQUAL RULE: close == close[4] satisfies neither condition. It INTERRUPTS both sequences
//     (counts reset to 0), so contradictory signals are impossible.
//     State machine per side:
//       * A sequence may START only when that side is "armed". A side becomes armed after at least
//         one bar (with 4+ bars of history) on which its condition was FALSE. Arming is consumed when
//         a sequence starts and again requires a genuine break of the relationship. This guarantees
//         that (a) a continuing move does not restart a sequence after step 9, (b) a chart that
//         loads mid-run does not start counting from an unknown state.
//       * While the condition stays TRUE: count increases by 1 per bar, max 9.
//       * Count 9 = COMPLETION (one distinct event). The state stays "locked" at 9 until the
//         relationship breaks; it can not re-trigger.
//       * Condition FALSE (or equal prices) on any bar: the active side resets to 0.
//     Buy-side and sell-side are mutually exclusive on any bar (a bar can not be both < and > close[4]).
//
//  2. STRUCTURAL QUALIFICATION (evaluated once, on the completion bar)
//     N = "Qualification Neighbour Bars" (default 2).  NbLow = lowest low of bars at offsets 2..N+1
//     (defaults: the two bars labelled 6 and 7 of a nine-bar phase when evaluated on bar 9).
//     Buy-side qualified  : low[0] <= NbLow  OR  low[1] <= NbLow   (bar 9 or bar 8 vs bars 6/7)
//     Sell-side qualified : high[0] >= NbHigh OR high[1] >= NbHigh (NbHigh = highest high, offsets 2..N+1)
//     Equal values qualify when "Treat Equal As Qualifying" is on; otherwise strict (< / >) is used.
//     Qualification never starts/stops the Terminal phase unless the optional rule
//     "Require Qualified Momentum Phase" is explicitly enabled.
//
//  3. TERMINAL EXHAUSTION (count 1..13, independent state)
//     ARMING : when a Momentum phase completes (and qualification is not required, or the phase is
//              qualified if the optional rule is on). A completion of the OPPOSITE side cancels an
//              active Terminal phase (state "Cancelled"). A same-side completion while a Terminal
//              phase is active is ignored (no reset, no duplicate).
//     COUNTING (starts on the completion bar itself or any later bar, then not necessarily consecutive):
//              Buy-side  : close <= low[2]       Sell-side : close >= high[2]
//              The FIRST qualifying bar starts count 1 (initiation condition); bars that do not
//              satisfy the price condition are simply not counted.
//     BAR 8  : the close of the bar that makes the count 8 is stored (Reference Close).
//     BAR 13 : requires the price condition AND final validation:
//              Buy-side  valid when low  <= Reference Close
//              Sell-side valid when high >= Reference Close
//              If validation fails the count stays at 12 (a "validation failure" event is raised) and
//              the next qualifying bar tries again. Completion is recorded only on success.
//     It runs independently of the Momentum counter (a new Momentum phase may develop meanwhile).
//
//  4. PHASE SUPPORT / RESISTANCE (separate from Range Pivots)
//     Completed buy-side phase  -> RESISTANCE = highest high of the nine phase bars.
//     Completed sell-side phase -> SUPPORT    = lowest low  of the nine phase bars.
//     Drawn as continuous STEP LINES (one resistance line, one support line): the line starts on the
//     completion bar, holds its level, steps to the new level when a newer phase of the same type completes,
//     and ENDS when crossed (close or intrabar basis - user choice). A crossed level is never re-activated.
//
//  5. INVALIDATION BOUNDARIES (analytical references only)
//     TR = true range of a bar.
//     Momentum, buy-side : lowest low of the phase minus the TR of the bar that printed that low.
//     Momentum, sell-side: highest high of the phase plus the TR of the bar that printed that high.
//     Terminal : same construction using the extremes recorded between terminal count 1 and the
//                terminal completion bar (its own state; never borrowed from the Momentum phase).
//     Crossing : buy-side boundary crossed when price goes BELOW it; sell-side when price goes ABOVE it
//                (close basis: close; intrabar basis: low/high). A crossing is reported once.
//                An ordinary touch that does not satisfy the basis is not a crossing.
//
//  6. TERMINAL TARGET (ARM chosen methodology)
//     Buy-side : Target = H + (H - Lc) * k,  H = highest high of terminal phase,
//                                              Lc = lowest close of terminal phase, k = projection factor.
//     Sell-side: Target = L - (Hc - L) * k,  L = lowest low of terminal phase,
//                                              Hc = highest close of terminal phase.
//     Inputs are frozen at completion. Default k = 0.618. A target is a reference, not a forecast.
//
//  7. RANGE PIVOTS (ARM weighted open/close range pivot)
//     X = H + 2L + C   if C < O
//     X = 2H + L + C   if C > O
//     X = H + L + 2C   if C = O
//     Central Pivot P = X / 4 ;  Support S = X / 2 - H ;  Resistance R = X / 2 - L
//     O,H,L,C come from the previous COMPLETED higher-timeframe bar (request.security with [1]
//     offsets + lookahead_on, the standard no-lookahead technique), so historical bars never see
//     information that was not yet available.
//     AUTOMATIC mapping (chart timeframe -> pivot range):
//       <=5m->1H | <=30m->4H | <=4H->Daily | <1D->Weekly | 1D->Monthly | 1W->Quarterly | 1M+->Yearly
//     If a manually chosen range is shorter than the chart timeframe, the chart timeframe is used.
//     Developing pivots use the CURRENT forming range and are drawn on the last bar only (never used
//     as if they were fixed at range start). Distance = (Pivot - Close) / Close * 100, signed:
//     negative = pivot below price, positive = pivot above price. Rounded to 2 decimals.
//
//  8. VOLUME PRESSURE OSCILLATOR (0..100)
//     range = high - low. Usable bar: range > 0 AND volume available (> 0).
//     contribution = volume * (close - open) / range        (signed, bounded by +/- volume)
//     PosSum = sum of positive contributions over N bars; NegSum = sum of |negative contributions|.
//     Buy% = 100 * PosSum / (PosSum + NegSum);  Sell% = 100 - Buy%.
//     Total = 0 -> neutral 50.  No usable volume in the window / incomplete window -> na (suppressed).
//     Signal = SMA(Buy%, signal length). Histogram = Buy% - Signal.
//     Display placement inside the price pane uses a LINEAR map: y = base + value/100 * height, where the
//     base/height are derived from the highest high / lowest low of the last 200 bars. The drawn
//     y-position is a display coordinate, not a financial price.
//
//  9. RELATIVE VOLUME CANDLES
//     MA = SMA(volume, 89). High = volume > MA * 1.618. Low = volume < MA * 0.618.
//     Bullish = close > open, bearish = close < open. Otherwise ordinary chart colour.
//
// ───────────────────────────────────────────────────────────────────────────────────────────────
//  REPAINTING DISCLOSURE
//     * Completion events, crossings, markers, levels, targets and alerts are processed on CONFIRMED
//       bars only (barstate.isconfirmed). They do not change after the bar closes.
//     * The dashboard (optionally) reads the last confirmed bar; with that option off it shows the
//       live forming bar, whose counts can change before close (legitimate intrabar change).
//     * Developing pivots are provisional by design and change while the higher-timeframe bar forms.
//     * Objects are created at bar close, so on a LIVE chart they appear one tick after the close.
//     * This script is not described as "completely non-repainting"; behaviour was designed to
//       be consistent but must be verified by the user on their own instruments and timeframes.
// ───────────────────────────────────────────────────────────────────────────────────────────────
//  ALERT USAGE
//     Option A: Create alert -> Condition: ARM -> "Any alert() function call" -> gives detailed
//               messages (symbol, timeframe, event, direction, count, level, close, pressure, time).
//     Option B: Create alert -> Condition: ARM -> pick a single named alert condition.
//     Do not use both for the same event, to avoid duplicate notifications.
// ═══════════════════════════════════════════════════════════════════════════════════════════════
 
indicator(title = "AETHERFLOW REVERSAL MATRIX (ARM)", shorttitle = "ARM", overlay = true, max_lines_count = 500, max_labels_count = 500, max_bars_back = 500)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  TYPES
// ═══════════════════════════════════════════════════════════════════════════════════════════════
// One persistent horizontal reference. cls: 0 phase S/R | 1 momentum invalidation | 2 terminal invalidation | 3 target
// kind: +1 = upper reference (crossed upward) | -1 = lower reference (crossed downward)
type Lvl
    line  ln       = na
    label lb       = na
    float price    = na
    int   kind     = 0
    int   cls      = 0
    bool  active   = true
    int   startBar = 0
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  INPUT GROUPS
// ═══════════════════════════════════════════════════════════════════════════════════════════════
G_GEN   = "01 General Configuration"
G_MOM   = "02 Momentum Exhaustion"
G_QUAL  = "03 Structural Qualification"
G_TERM  = "04 Terminal Exhaustion"
G_LVL   = "05 Phase Support and Resistance"
G_INV   = "06 Invalidation Levels"
G_TGT   = "07 Target Projections"
G_PIV   = "08 Range Pivot Engine"
G_PIVH  = "09 Developing and Historical Pivots"
G_VP    = "10 Volume Pressure"
G_VOL   = "11 Volume-Weighted Bars"
G_DASH  = "12 Dashboard"
G_VIS   = "13 Visual Appearance"
G_ALERT = "14 Alert Configuration"
 
// 01 General
markerMode = input.string("Completed Phases Only", "Phase Marker Mode", options = ["All Sequence Steps", "Completed Phases Only", "Hidden"], group = G_GEN, tooltip = "All Sequence Steps: numbered markers for every counted step (Momentum numbers, Terminal numbers prefixed with T). Completed Phases Only: only completion markers. Hidden: no phase markers.")
maxLbl     = input.int(300, "Maximum Step Labels Kept", minval = 50, maxval = 400, group = G_GEN, tooltip = "History limit for step labels and crossing markers. Older labels are deleted to respect TradingView's drawing limits.")
confDash   = input.bool(true, "Dashboard Reads Last Confirmed Bar", group = G_GEN, tooltip = "ON: the dashboard shows the last closed bar (stable). OFF: it shows the live forming bar, whose values can change before the bar closes.")
 
// 02 Momentum
enMom   = input.bool(true, "Enable Momentum Exhaustion", group = G_MOM, tooltip = "Master switch of the primary module. When off, Terminal, phase levels, invalidation and targets have nothing to work with.")
colBuy  = input.color(#26a69a, "Buy-side Exhaustion Colour", group = G_MOM)
colSell = input.color(#f7525f, "Sell-side Exhaustion Colour", group = G_MOM)
 
// 03 Qualification
enQual = input.bool(true, "Enable Structural Qualification", group = G_QUAL, tooltip = "Adds the Q flag on completed phases whose local structure passes the high/low test. It describes structure only - it is not a probability or quality score.")
qualN  = input.int(2, "Qualification Neighbour Bars", minval = 1, maxval = 5, group = G_QUAL, tooltip = "Number of reference bars compared against (offsets 2..N+1 from the completion bar). Default 2 = bars 6 and 7 of a nine-bar phase.")
qualEq = input.bool(true, "Treat Equal Highs/Lows As Qualifying", group = G_QUAL, tooltip = "ON: <= / >= comparison. OFF: strict < / > comparison.")
showUnq = input.bool(false, "Show Unqualified Completion Markers", group = G_QUAL, tooltip = "OFF (reference-chart look): only qualified completed phases (M/Q) get a marker. ON: unqualified completions are also marked with a plain M.")
 
// 04 Terminal
enTerm      = input.bool(true, "Enable Terminal Exhaustion", group = G_TERM)
termReqQual = input.bool(false, "Require Qualified Momentum Phase To Arm Terminal", group = G_TERM, tooltip = "OPTIONAL documented rule. Default OFF: qualification is independent and never blocks the Terminal phase.")
showTFail   = input.bool(true, "Mark Failed Final Validation (13)", group = G_TERM)
colTBuy     = input.color(#1b8a3a, "Terminal Buy-side Colour", group = G_TERM)
colTSell    = input.color(#b3222e, "Terminal Sell-side Colour", group = G_TERM)
 
// 05 Phase S/R
enLvl      = input.bool(true, "Enable Phase Support / Resistance", group = G_LVL)
colLvRes   = input.color(#f7525f, "Resistance Colour", group = G_LVL)
colLvSup   = input.color(#26a69a, "Support Colour", group = G_LVL)
lvWidth    = input.int(1, "Line Width", minval = 1, maxval = 4, group = G_LVL)
lvBasis    = input.string("Close", "Crossing Basis", options = ["Close", "Intrabar High/Low"], group = G_LVL, tooltip = "Close: a level is crossed when the CLOSE is beyond it. Intrabar: when the HIGH/LOW trades beyond it. Both are evaluated on confirmed bars.")
lvMark     = input.bool(true, "Show Crossing Marker", group = G_LVL, tooltip = "Phase levels are drawn as continuous step lines (one resistance line, one support line). A line ends when crossed and steps to a new level when a new phase completes.")
 
// 06 Invalidation
enInvMom  = input.bool(true, "Enable Momentum Invalidation Levels", group = G_INV)
enInvTerm = input.bool(true, "Enable Terminal Invalidation Levels", group = G_INV)
colInvMom = input.color(#ff9800, "Momentum Invalidation Colour", group = G_INV)
colInvTrm = input.color(#9c27b0, "Terminal Invalidation Colour", group = G_INV)
colRetired= input.color(color.new(#9598a1, 30), "Crossed / Retired Colour", group = G_INV)
ivStyle   = input.string("Dashed", "Line Style", options = ["Solid", "Dashed", "Dotted"], group = G_INV)
ivWidth   = input.int(1, "Line Width", minval = 1, maxval = 4, group = G_INV)
ivKeep    = input.int(4, "Levels Kept (per type)", minval = 1, maxval = 30, group = G_INV)
ivBasis   = input.string("Close", "Crossing Basis", options = ["Close", "Intrabar High/Low"], group = G_INV, tooltip = "Close basis is stricter (fewer invalidations). Intrabar basis reacts to wicks.")
ivLabel   = input.bool(true, "Show Labels", group = G_INV)
 
// 07 Targets
enTgt     = input.bool(true, "Enable Terminal Targets", group = G_TGT)
tgtFactor = input.float(0.618, "Projection Factor (k)", minval = 0.1, maxval = 5.0, step = 0.1, group = G_TGT, tooltip = "Buy-side: H + (H - lowest close) * k.  Sell-side: L - (highest close - L) * k, computed from the terminal phase and frozen at completion.")
colTgt    = input.color(#2962ff, "Target Colour", group = G_TGT)
tgStyle   = input.string("Dotted", "Line Style", options = ["Solid", "Dashed", "Dotted"], group = G_TGT)
tgWidth   = input.int(1, "Line Width", minval = 1, maxval = 4, group = G_TGT)
tgLabel   = input.bool(true, "Show Target Label", group = G_TGT)
tgKeep    = input.int(3, "Targets Kept", minval = 1, maxval = 30, group = G_TGT)
tgExtend  = input.bool(true, "Extend Right Until Reached", group = G_TGT, tooltip = "OFF: the target is drawn as a short fixed-length segment (20 bars).")
 
// 08 Range pivots
enPiv    = input.bool(true, "Enable Range Pivot Engine", group = G_PIV)
pvMode   = input.string("Automatic", "Pivot Range Mode", options = ["Automatic", "Manual"], group = G_PIV, tooltip = "Automatic: <=5m->1H, <=30m->4H, <=4H->Daily, <1D->Weekly, 1D->Monthly, 1W->Quarterly, 1M+->Yearly.")
pvManual = input.string("Monthly", "Manual Pivot Range", options = ["1 Hour", "4 Hour", "Daily", "Weekly", "Monthly", "Quarterly", "Yearly"], group = G_PIV)
colPvS   = input.color(#089981, "Support (S) Colour", group = G_PIV)
colPvP   = input.color(#2962ff, "Central Pivot (P) Colour", group = G_PIV)
colPvR   = input.color(#f23645, "Resistance (R) Colour", group = G_PIV)
pvStyle  = input.string("Solid", "Line Style", options = ["Solid", "Dashed", "Dotted"], group = G_PIV)
pvWidth  = input.int(2, "Line Width", minval = 1, maxval = 4, group = G_PIV)
pvLabels = input.bool(true, "Show Pivot Labels", group = G_PIV)
 
// 09 Developing / Historical pivots
enPvDev   = input.bool(false, "Show Developing Range Pivots (provisional)", group = G_PIVH, tooltip = "Pivots computed from the CURRENTLY FORMING higher-timeframe range. They change until the range closes and are drawn on the last bar only.")
enPvHist  = input.bool(false, "Show Historical Range Pivots", group = G_PIVH)
pvHistN   = input.int(4, "Historical Ranges Kept", minval = 1, maxval = 30, group = G_PIVH)
colPvDev  = input.color(color.new(#ff9800, 0), "Developing Pivot Colour", group = G_PIVH)
 
// 10 Volume pressure
enVP      = input.bool(true, "Enable Volume Pressure Oscillator", group = G_VP)
vpLen     = input.int(13, "Lookback Period", minval = 2, maxval = 200, group = G_VP)
sigLen    = input.int(9, "Signal Average Period", minval = 1, maxval = 100, group = G_VP)
vpUpper   = input.float(75.0, "Upper Threshold", minval = 50.0, maxval = 100.0, group = G_VP)
vpLower   = input.float(25.0, "Lower Threshold", minval = 0.0, maxval = 50.0, group = G_VP)
showSig   = input.bool(true, "Show Signal Line", group = G_VP)
showHist  = input.bool(true, "Show Histogram", group = G_VP)
vpPos     = input.string("Bottom", "Oscillator Position", options = ["Top", "Middle", "Bottom"], group = G_VP, tooltip = "Position of the oscillator block inside the price pane. Its vertical position is a display coordinate, not a price.")
vpHeight  = input.float(12.0, "Oscillator Height (% of recent price range)", minval = 4.0, maxval = 40.0, step = 1.0, group = G_VP)
colOsc    = input.color(#00bcd4, "Oscillator Colour", group = G_VP)
colSig    = input.color(#ff9800, "Signal Colour", group = G_VP)
colBand   = input.color(color.new(#787b86, 20), "Threshold / Mid Line Colour", group = G_VP)
colHPU    = input.color(#26a69a, "Histogram: Positive & Increasing", group = G_VP)
colHPD    = input.color(#a8dcd5, "Histogram: Positive & Decreasing", group = G_VP)
colHNU    = input.color(#f8c6c9, "Histogram: Negative & Increasing", group = G_VP)
colHND    = input.color(#ef5350, "Histogram: Negative & Decreasing", group = G_VP)
 
// 11 Volume-weighted bars
enRV     = input.bool(true, "Enable Relative-Volume Candle Colouring", group = G_VOL)
rvLen    = input.int(89, "Volume Moving Average Length", minval = 2, maxval = 500, group = G_VOL)
rvHiMult = input.float(1.618, "High-Volume Multiplier", minval = 0.5, step = 0.1, group = G_VOL)
rvLoMult = input.float(0.618, "Low-Volume Multiplier", minval = 0.05, step = 0.1, group = G_VOL)
colHiBull= input.color(#0b6b2e, "High-Volume Bullish", group = G_VOL)
colHiBear= input.color(#8b1a1a, "High-Volume Bearish", group = G_VOL)
colLoBull= input.color(#a5e8e0, "Low-Volume Bullish", group = G_VOL)
colLoBear= input.color(#ff9800, "Low-Volume Bearish", group = G_VOL)
 
// 12 Dashboard
enDash     = input.bool(true, "Show Dashboard", group = G_DASH)
dashPos    = input.string("Top Right", "Position", options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group = G_DASH)
dashSize   = input.string("Small", "Font Size", options = ["Tiny", "Small", "Normal", "Large"], group = G_DASH)
dashBg     = input.color(#d1d4dc, "Background Colour", group = G_DASH)
dashTr     = input.int(25, "Background Transparency", minval = 0, maxval = 100, group = G_DASH)
dashBorder = input.color(#ffffff, "Border Colour", group = G_DASH)
dashText   = input.color(#131722, "Text Colour", group = G_DASH)
dashLabel  = input.color(#131722, "Label Colour", group = G_DASH)
 
// 14 Alerts
alMaster = input.bool(true, "Enable alert() Detailed Messages", group = G_ALERT, tooltip = "Master switch for the detailed alert() messages. The named alert conditions are always available in the alert dialog.")
alMom    = input.bool(true, "Momentum Exhaustion Completion", group = G_ALERT)
alTerm   = input.bool(true, "Terminal Exhaustion Completion", group = G_ALERT)
alPhSup  = input.bool(true, "Phase Support Crossing", group = G_ALERT)
alPhRes  = input.bool(true, "Phase Resistance Crossing", group = G_ALERT)
alMomInv = input.bool(true, "Momentum Invalidation Crossing", group = G_ALERT)
alTrmInv = input.bool(true, "Terminal Invalidation Crossing", group = G_ALERT)
alPvS    = input.bool(true, "Range Pivot Support Crossing", group = G_ALERT)
alPvP    = input.bool(true, "Range Pivot Central Crossing", group = G_ALERT)
alPvR    = input.bool(true, "Range Pivot Resistance Crossing", group = G_ALERT)
alPUp    = input.bool(true, "Pressure Enters Upper Zone", group = G_ALERT)
alPDn    = input.bool(true, "Pressure Enters Lower Zone", group = G_ALERT)
alHiVol  = input.bool(true, "High-Volume Bar", group = G_ALERT)
alQual   = input.bool(false, "Qualified Momentum Phase (optional)", group = G_ALERT)
alTFail  = input.bool(false, "Terminal Validation Failure (optional)", group = G_ALERT)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  HELPER FUNCTIONS
// ═══════════════════════════════════════════════════════════════════════════════════════════════
lineStyleOf(string s) =>
    s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
 
posOf(string s) =>
    switch s
        "Top Left"      => position.top_left
        "Top Center"    => position.top_center
        "Top Right"     => position.top_right
        "Middle Left"   => position.middle_left
        "Middle Center" => position.middle_center
        "Middle Right"  => position.middle_right
        "Bottom Left"   => position.bottom_left
        "Bottom Center" => position.bottom_center
        "Bottom Right"  => position.bottom_right
        => position.top_right
 
sizeOf(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        => size.small
 
f_autoTf() =>
    int s = timeframe.in_seconds()
    s <= 300 ? "60" : s <= 1800 ? "240" : s <= 14400 ? "D" : s < 86400 ? "W" : s < 604800 ? "M" : s < 2592000 ? "3M" : "12M"
 
f_manualTf(string s) =>
    switch s
        "1 Hour"    => "60"
        "4 Hour"    => "240"
        "Daily"     => "D"
        "Weekly"    => "W"
        "Monthly"   => "M"
        "Quarterly" => "3M"
        "Yearly"    => "12M"
        => "D"
 
f_tfLabel(string tf) =>
    switch tf
        "60"  => "1H"
        "240" => "4H"
        "D"   => "D"
        "W"   => "W"
        "M"   => "M"
        "3M"  => "Q"
        "12M" => "Y"
        => timeframe.period
 
delLvl(Lvl l) =>
    if not na(l.ln)
        line.delete(l.ln)
    if not na(l.lb)
        label.delete(l.lb)
    true
 
// Keeps at most `keep` entries of class `cls`, deleting the oldest first.
trimLvls(array<Lvl> a, int cls, int keep) =>
    int cnt = 0
    for l in a
        if l.cls == cls
            cnt += 1
    int i = 0
    while cnt > keep and i < a.size()
        Lvl l2 = a.get(i)
        if l2.cls == cls
            delLvl(l2)
            a.remove(i)
            cnt -= 1
        else
            i += 1
    cnt
 
addLvl(array<Lvl> a, int cls, int kind, float price, int x1, int x2, color c, string sty, int w, bool ext, string txt, int keep) =>
    Lvl l = Lvl.new(na, na, price, kind, cls, true, x1)
    l.ln := line.new(x1, price, x2, price, xloc.bar_index, ext ? extend.right : extend.none, c, lineStyleOf(sty), w)
    if txt != ""
        l.lb := label.new(x2, price, txt, xloc.bar_index, yloc.price, color.new(c, 85), label.style_label_left, c, size.tiny)
    a.push(l)
    trimLvls(a, cls, keep)
    l
 
retireLvl(Lvl l, color c) =>
    l.active := false
    line.set_extend(l.ln, extend.none)
    line.set_x2(l.ln, bar_index)
    line.set_color(l.ln, c)
    line.set_style(l.ln, line.style_dotted)
    if not na(l.lb)
        label.set_textcolor(l.lb, c)
        label.set_color(l.lb, color.new(c, 90))
    true
 
capLabels(array<label> a, int keep) =>
    while a.size() > keep
        label.delete(a.shift())
    a.size()
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  GLOBAL STATE
// ═══════════════════════════════════════════════════════════════════════════════════════════════
bool  conf    = barstate.isconfirmed
float trBar   = ta.tr(true)
 
var array<Lvl>   lvls     = array.new<Lvl>()
var array<label> markLbls = array.new<label>()
var float curRes = na   // active phase resistance (step line)
var float curSup = na   // active phase support (step line)
 
// Momentum state
var int   mSide      = 0        // +1 buy-side (downward sequence), -1 sell-side (upward sequence), 0 none
var int   mCnt       = 0
var bool  mQual      = false
var bool  buyArmed   = false
var bool  sellArmed  = false
var int   mStart     = 0
var float pHigh      = na
var float pLow       = na
var float pHighTR    = na
var float pLowTR     = na
 
// Terminal state: tState 0 idle | 1 armed | 2 counting | 3 completed | 4 invalidated | 5 cancelled
var int   tState     = 0
var int   tSide      = 0
var int   tCnt       = 0
var float t8Close    = na
var int   tStart     = 0
var float tExtHigh   = na
var float tExtLow    = na
var float tExtHighTR = na
var float tExtLowTR  = na
var float tLoClose   = na
var float tHiClose   = na
var float tInv       = na
var bool  tInvActive = false
var float tFinInv    = na
var float tFinTarget = na
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  MODULE 1 + 2: MOMENTUM EXHAUSTION AND STRUCTURAL QUALIFICATION
// ═══════════════════════════════════════════════════════════════════════════════════════════════
bool  barValid = bar_index >= 4
bool  dnRel    = barValid and close < close[4]
bool  upRel    = barValid and close > close[4]
float nbLow    = ta.lowest(low, qualN)[2]
float nbHigh   = ta.highest(high, qualN)[2]
 
bool rawMomBuy  = false
bool rawMomSell = false
bool mAdv       = false
 
if enMom
    // ---- Buy-side (downward) branch ----
    if dnRel
        if mSide == 1 and mCnt >= 1 and mCnt < 9
            mCnt += 1
            mAdv := true
            if high > pHigh
                pHigh := high
                pHighTR := trBar
            if low < pLow
                pLow := low
                pLowTR := trBar
            if mCnt == 9
                rawMomBuy := true
                mQual := enQual and (qualEq ? (low <= nbLow or low[1] <= nbLow) : (low < nbLow or low[1] < nbLow))
        else if mSide != 1 and buyArmed
            mSide := 1
            mCnt := 1
            mAdv := true
            buyArmed := false
            mQual := false
            mStart := bar_index
            pHigh := high
            pHighTR := trBar
            pLow := low
            pLowTR := trBar
    // ---- Sell-side (upward) branch ----
    if upRel
        if mSide == -1 and mCnt >= 1 and mCnt < 9
            mCnt += 1
            mAdv := true
            if high > pHigh
                pHigh := high
                pHighTR := trBar
            if low < pLow
                pLow := low
                pLowTR := trBar
            if mCnt == 9
                rawMomSell := true
                mQual := enQual and (qualEq ? (high >= nbHigh or high[1] >= nbHigh) : (high > nbHigh or high[1] > nbHigh))
        else if mSide != -1 and sellArmed
            mSide := -1
            mCnt := 1
            mAdv := true
            sellArmed := false
            mQual := false
            mStart := bar_index
            pHigh := high
            pHighTR := trBar
            pLow := low
            pLowTR := trBar
    // ---- Interruptions (relationship broken or equal prices) ----
    if not dnRel and mSide == 1
        mSide := 0
        mCnt := 0
        mQual := false
    if not upRel and mSide == -1
        mSide := 0
        mCnt := 0
        mQual := false
    // ---- Re-arming requires a genuine break of the relationship ----
    if barValid and not dnRel
        buyArmed := true
    if barValid and not upRel
        sellArmed := true
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  MODULE 3: TERMINAL EXHAUSTION (independent state)
// ═══════════════════════════════════════════════════════════════════════════════════════════════
bool  ivClose = ivBasis == "Close"
float cIvUp   = ivClose ? close : high
float cIvDn   = ivClose ? close : low
 
bool rawTermBuy   = false
bool rawTermSell  = false
bool rawTFailBuy  = false
bool rawTFailSell = false
bool rawTInvProg  = false
bool tAdv         = false
 
if enTerm and enMom
    // 1) Arming / cancellation by a Momentum completion
    if rawMomBuy or rawMomSell
        int  newSide   = rawMomBuy ? 1 : -1
        bool eligible  = not termReqQual or mQual
        bool activeNow = tState == 1 or tState == 2
        if activeNow and tSide != newSide
            tState := 5
            activeNow := false
        if not activeNow and eligible
            tState := 1
            tSide := newSide
            tCnt := 0
            t8Close := na
            tInvActive := false
    // 2) Invalidation check against the boundary known BEFORE this bar
    if (tState == 2 or tState == 3) and tInvActive
        bool crossedT = tSide == 1 ? cIvDn < tInv : cIvUp > tInv
        if crossedT
            if tState == 2
                rawTInvProg := true
            tState := 4
            tInvActive := false
    // 3) Update recorded extremes while counting
    if tState == 2
        if high > tExtHigh
            tExtHigh := high
            tExtHighTR := trBar
        if low < tExtLow
            tExtLow := low
            tExtLowTR := trBar
        tLoClose := math.min(tLoClose, close)
        tHiClose := math.max(tHiClose, close)
        tInv := tSide == 1 ? tExtLow - tExtLowTR : tExtHigh + tExtHighTR
    // 4) Counting
    if tState == 1 or tState == 2
        bool tCond = tSide == 1 ? close <= low[2] : close >= high[2]
        if tCond
            if tCnt == 12
                bool valid13 = tSide == 1 ? low <= t8Close : high >= t8Close
                if valid13
                    tCnt := 13
                    tState := 3
                    tAdv := true
                    tFinInv := tInv
                    tFinTarget := tSide == 1 ? tExtHigh + (tExtHigh - tLoClose) * tgtFactor : tExtLow - (tHiClose - tExtLow) * tgtFactor
                    if tSide == 1
                        rawTermBuy := true
                    else
                        rawTermSell := true
                else
                    if tSide == 1
                        rawTFailBuy := true
                    else
                        rawTFailSell := true
            else if tCnt < 12
                tCnt += 1
                tAdv := true
                if tCnt == 1
                    tState := 2
                    tStart := bar_index
                    tExtHigh := high
                    tExtHighTR := trBar
                    tExtLow := low
                    tExtLowTR := trBar
                    tLoClose := close
                    tHiClose := close
                    tInv := tSide == 1 ? low - trBar : high + trBar
                    tInvActive := enInvTerm
                if tCnt == 8
                    t8Close := close
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  CONFIRMED EVENTS
// ═══════════════════════════════════════════════════════════════════════════════════════════════
bool evMomBuy    = conf and rawMomBuy
bool evMomSell   = conf and rawMomSell
bool evTermBuy   = conf and rawTermBuy
bool evTermSell  = conf and rawTermSell
bool evTFailBuy  = conf and rawTFailBuy
bool evTFailSell = conf and rawTFailSell
bool evQualPh    = (evMomBuy or evMomSell) and mQual
 
bool  evPhRes     = false
bool  evPhSup     = false
bool  evMomInvX   = false
bool  evTermInvLv = false
float xPhRes      = na
float xPhSup      = na
float xMomInv     = na
float xTermInv    = na
 
bool  lvClose = lvBasis == "Close"
float cLvUp   = lvClose ? close : high
float cLvDn   = lvClose ? close : low
 
// ---- Lifecycle of existing levels: crossings / retirement (checked BEFORE creating new ones) ----
if conf
    for l in lvls
        if l.active
            bool hit = false
            if l.cls == 3
                hit := l.kind == 1 ? high >= l.price : low <= l.price
            else if l.kind == 1
                hit := (l.cls == 0 ? cLvUp : cIvUp) > l.price
            else
                hit := (l.cls == 0 ? cLvDn : cIvDn) < l.price
            if hit
                retireLvl(l, colRetired)
                if l.cls == 0
                    if l.kind == 1
                        evPhRes := true
                        xPhRes := l.price
                    else
                        evPhSup := true
                        xPhSup := l.price
                else if l.cls == 1
                    evMomInvX := true
                    xMomInv := l.price
                else if l.cls == 2
                    evTermInvLv := true
                    xTermInv := l.price
                if lvMark and l.cls != 3
                    markLbls.push(label.new(bar_index, l.price, "", xloc.bar_index, yloc.price, l.cls == 0 ? (l.kind == 1 ? colLvRes : colLvSup) : (l.cls == 1 ? colInvMom : colInvTrm), label.style_xcross, color.white, size.tiny))
 
// ---- Phase support / resistance step lines: crossing ends the line (checked BEFORE new levels are set) ----
if conf and enLvl
    if not na(curRes) and cLvUp > curRes
        evPhRes := true
        xPhRes := curRes
        if lvMark
            markLbls.push(label.new(bar_index, curRes, "", xloc.bar_index, yloc.price, colLvRes, label.style_xcross, color.white, size.tiny))
        curRes := na
    if not na(curSup) and cLvDn < curSup
        evPhSup := true
        xPhSup := curSup
        if lvMark
            markLbls.push(label.new(bar_index, curSup, "", xloc.bar_index, yloc.price, colLvSup, label.style_xcross, color.white, size.tiny))
        curSup := na
 
// ---- Creation of new levels at confirmed events ----
if evMomBuy
    if enLvl
        curRes := pHigh
    if enInvMom
        addLvl(lvls, 1, -1, pLow - pLowTR, bar_index, bar_index, colInvMom, ivStyle, ivWidth, true, ivLabel ? "INV-M" : "", ivKeep)
if evMomSell
    if enLvl
        curSup := pLow
    if enInvMom
        addLvl(lvls, 1, 1, pHigh + pHighTR, bar_index, bar_index, colInvMom, ivStyle, ivWidth, true, ivLabel ? "INV-M" : "", ivKeep)
if evTermBuy
    if enInvTerm
        addLvl(lvls, 2, -1, tFinInv, bar_index, bar_index, colInvTrm, ivStyle, ivWidth, true, ivLabel ? "INV-T" : "", ivKeep)
    if enTgt
        addLvl(lvls, 3, 1, tFinTarget, bar_index, bar_index + 20, colTgt, tgStyle, tgWidth, tgExtend, tgLabel ? "TGT " + str.tostring(tFinTarget, format.mintick) : "", tgKeep)
if evTermSell
    if enInvTerm
        addLvl(lvls, 2, 1, tFinInv, bar_index, bar_index, colInvTrm, ivStyle, ivWidth, true, ivLabel ? "INV-T" : "", ivKeep)
    if enTgt
        addLvl(lvls, 3, -1, tFinTarget, bar_index, bar_index + 20, colTgt, tgStyle, tgWidth, tgExtend, tgLabel ? "TGT " + str.tostring(tFinTarget, format.mintick) : "", tgKeep)
 
bool evTermInvX = conf and rawTInvProg or evTermInvLv
 
plot(enLvl ? curRes : na, "ARM Phase Resistance", color = colLvRes, linewidth = lvWidth, style = plot.style_linebr)
plot(enLvl ? curSup : na, "ARM Phase Support", color = colLvSup, linewidth = lvWidth, style = plot.style_linebr)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  MODULE 7: RANGE PIVOT ENGINE
// ═══════════════════════════════════════════════════════════════════════════════════════════════
string tfSel = pvMode == "Automatic" ? f_autoTf() : f_manualTf(pvManual)
string tfEff = timeframe.in_seconds(tfSel) < timeframe.in_seconds() ? timeframe.period : tfSel
 
// Completed higher-timeframe range (previous completed bar; no lookahead exposure)
[pvO, pvH, pvL, pvC] = request.security(syminfo.tickerid, tfEff, [open[1], high[1], low[1], close[1]], lookahead = barmerge.lookahead_on)
// Developing (currently forming) higher-timeframe range
[dvO, dvH, dvL, dvC] = request.security(syminfo.tickerid, tfEff, [open, high, low, close], lookahead = barmerge.lookahead_off)
 
float pvX = pvC < pvO ? pvH + 2.0 * pvL + pvC : pvC > pvO ? 2.0 * pvH + pvL + pvC : pvH + pvL + 2.0 * pvC
float pvP = pvX / 4.0
float pvS = pvX / 2.0 - pvH
float pvR = pvX / 2.0 - pvL
 
float dvX = dvC < dvO ? dvH + 2.0 * dvL + dvC : dvC > dvO ? 2.0 * dvH + dvL + dvC : dvH + dvL + 2.0 * dvC
float dvP = dvX / 4.0
float dvS = dvX / 2.0 - dvH
float dvR = dvX / 2.0 - dvL
 
bool newRange = barstate.isfirst or timeframe.change(tfEff)
var int rangeStart = 0
if newRange
    rangeStart := bar_index
 
var line  lnS = na
var line  lnP = na
var line  lnR = na
var array<line> pvOld = array.new<line>()
 
if enPiv and newRange and conf and not na(pvP)
    if not na(lnS)
        line.set_extend(lnS, extend.none)
        line.set_extend(lnP, extend.none)
        line.set_extend(lnR, extend.none)
        line.set_x2(lnS, bar_index - 1)
        line.set_x2(lnP, bar_index - 1)
        line.set_x2(lnR, bar_index - 1)
        line.set_color(lnS, color.new(colPvS, 55))
        line.set_color(lnP, color.new(colPvP, 55))
        line.set_color(lnR, color.new(colPvR, 55))
        line.set_style(lnS, line.style_dotted)
        line.set_style(lnP, line.style_dotted)
        line.set_style(lnR, line.style_dotted)
        pvOld.push(lnS)
        pvOld.push(lnP)
        pvOld.push(lnR)
    lnS := line.new(bar_index, pvS, bar_index, pvS, xloc.bar_index, extend.none, colPvS, lineStyleOf(pvStyle), pvWidth)
    lnP := line.new(bar_index, pvP, bar_index, pvP, xloc.bar_index, extend.none, colPvP, lineStyleOf(pvStyle), pvWidth)
    lnR := line.new(bar_index, pvR, bar_index, pvR, xloc.bar_index, extend.none, colPvR, lineStyleOf(pvStyle), pvWidth)
    int keepLines = enPvHist ? pvHistN * 3 : 0
    while pvOld.size() > keepLines
        line.delete(pvOld.shift())
 
// Persistent label / developing objects (created once, updated on the last bar)
var label lbS  = label.new(na, na, "", xloc.bar_index, yloc.price, color.new(color.gray, 100), label.style_label_left, colPvS, size.small)
var label lbP  = label.new(na, na, "", xloc.bar_index, yloc.price, color.new(color.gray, 100), label.style_label_left, colPvP, size.small)
var label lbR  = label.new(na, na, "", xloc.bar_index, yloc.price, color.new(color.gray, 100), label.style_label_left, colPvR, size.small)
var line  dLnS = line.new(na, na, na, na, xloc.bar_index, extend.none, colPvDev, line.style_dashed, 1)
var line  dLnP = line.new(na, na, na, na, xloc.bar_index, extend.none, colPvDev, line.style_dashed, 1)
var line  dLnR = line.new(na, na, na, na, xloc.bar_index, extend.none, colPvDev, line.style_dashed, 1)
var label dLbS = label.new(na, na, "", xloc.bar_index, yloc.price, color.new(color.gray, 100), label.style_label_left, colPvDev, size.tiny)
var label dLbP = label.new(na, na, "", xloc.bar_index, yloc.price, color.new(color.gray, 100), label.style_label_left, colPvDev, size.tiny)
var label dLbR = label.new(na, na, "", xloc.bar_index, yloc.price, color.new(color.gray, 100), label.style_label_left, colPvDev, size.tiny)
 
if barstate.islast and enPiv and not na(pvP) and not na(lnS)
    line.set_x2(lnS, bar_index + 3)
    line.set_x2(lnP, bar_index + 3)
    line.set_x2(lnR, bar_index + 3)
 
if barstate.islast and enPiv and pvLabels and not na(pvP)
    label.set_xy(lbS, bar_index + 3, pvS)
    label.set_text(lbS, "S (" + str.tostring(pvS, format.mintick) + ")")
    label.set_xy(lbP, bar_index + 3, pvP)
    label.set_text(lbP, "P (" + str.tostring(pvP, format.mintick) + ")")
    label.set_xy(lbR, bar_index + 3, pvR)
    label.set_text(lbR, "R (" + str.tostring(pvR, format.mintick) + ")")
 
if barstate.islast and enPiv and enPvDev and not na(dvP)
    line.set_xy1(dLnS, rangeStart, dvS)
    line.set_xy2(dLnS, bar_index + 3, dvS)
    line.set_xy1(dLnP, rangeStart, dvP)
    line.set_xy2(dLnP, bar_index + 3, dvP)
    line.set_xy1(dLnR, rangeStart, dvR)
    line.set_xy2(dLnR, bar_index + 3, dvR)
    label.set_xy(dLbS, bar_index + 3, dvS)
    label.set_text(dLbS, "dS (" + str.tostring(dvS, format.mintick) + ")")
    label.set_xy(dLbP, bar_index + 3, dvP)
    label.set_text(dLbP, "dP (" + str.tostring(dvP, format.mintick) + ")")
    label.set_xy(dLbR, bar_index + 3, dvR)
    label.set_text(dLbR, "dR (" + str.tostring(dvR, format.mintick) + ")")
 
// Crossings of the completed-range pivots (same-range comparison only)
bool crossS = ta.cross(close, pvS)
bool crossP = ta.cross(close, pvP)
bool crossR = ta.cross(close, pvR)
bool evPvS = enPiv and conf and not newRange and crossS
bool evPvP = enPiv and conf and not newRange and crossP
bool evPvR = enPiv and conf and not newRange and crossR
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  MODULE 8: VOLUME PRESSURE OSCILLATOR
// ═══════════════════════════════════════════════════════════════════════════════════════════════
float rngBar  = high - low
bool  volOk   = not na(volume) and volume > 0
bool  barOk   = rngBar > 0 and volOk
float contrib = barOk ? volume * (close - open) / rngBar : 0.0
float posSum  = math.sum(math.max(contrib, 0.0), vpLen)
float negSum  = math.sum(math.max(-contrib, 0.0), vpLen)
float okCnt   = math.sum(barOk ? 1.0 : 0.0, vpLen)
float totSum  = posSum + negSum
float buyPct  = bar_index < vpLen - 1 or okCnt == 0 ? na : (totSum > 0 ? 100.0 * posSum / totSum : 50.0)
float sellPct = na(buyPct) ? na : 100.0 - buyPct
float sigAvg  = ta.sma(buyPct, sigLen)
float histVal = buyPct - sigAvg
 
bool evPUp = enVP and conf and not na(buyPct) and buyPct >= vpUpper and nz(buyPct[1], 0.0) < vpUpper
bool evPDn = enVP and conf and not na(buyPct) and buyPct <= vpLower and nz(buyPct[1], 100.0) > vpLower
 
// ---- display mapping inside the price pane ----
float rngHi    = nz(ta.highest(high, 200), high)
float rngLo    = nz(ta.lowest(low, 200), low)
float spanV    = math.max(rngHi - rngLo, syminfo.mintick * 10)
float oscH     = spanV * vpHeight / 100.0
float histH    = oscH * 0.45
float gapV     = spanV * 0.015
float totH     = oscH + gapV + histH
float stackBot = vpPos == "Top" ? rngHi + spanV * 0.04 : vpPos == "Middle" ? (rngHi + rngLo) / 2.0 - totH / 2.0 : rngLo - spanV * 0.04 - totH
float histBase = stackBot + histH / 2.0
float oscBot   = stackBot + histH + gapV
 
float yOsc  = enVP and not na(buyPct) ? oscBot + buyPct / 100.0 * oscH : na
float ySig  = enVP and showSig and not na(sigAvg) ? oscBot + sigAvg / 100.0 * oscH : na
float yUp   = enVP ? oscBot + vpUpper / 100.0 * oscH : na
float yMid  = enVP ? oscBot + 0.5 * oscH : na
float yLow  = enVP ? oscBot + vpLower / 100.0 * oscH : na
float yHist = enVP and showHist and not na(histVal) ? histBase + math.max(math.min(histVal, 50.0), -50.0) / 50.0 * (histH / 2.0) : na
color histCol = na(histVal) ? na : histVal >= 0 ? (histVal > nz(histVal[1], histVal) ? colHPU : colHPD) : (histVal > nz(histVal[1], histVal) ? colHNU : colHND)
 
pOsc = plot(yOsc, "ARM Pressure Oscillator", color = colOsc, linewidth = 1)
plot(ySig, "ARM Pressure Signal", color = colSig, linewidth = 1)
pUp  = plot(yUp, "ARM Upper Threshold", color = colBand, linewidth = 1, style = plot.style_circles)
plot(yMid, "ARM Midline", color = colBand, linewidth = 1, style = plot.style_circles)
pLo  = plot(yLow, "ARM Lower Threshold", color = colBand, linewidth = 1, style = plot.style_circles)
fill(pUp, pLo, color = color.new(colOsc, 92), title = "ARM Pressure Zone")
plotcandle(histBase, math.max(histBase, nz(yHist, histBase)), math.min(histBase, nz(yHist, histBase)), yHist, title = "ARM Pressure Histogram", color = histCol, wickcolor = na, bordercolor = histCol)
plot(buyPct, "ARM Buy Pressure %", display = display.data_window)
plot(sellPct, "ARM Sell Pressure %", display = display.data_window)
plot(histVal, "ARM Histogram Value", display = display.data_window)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  MODULE 9: RELATIVE-VOLUME CANDLES
// ═══════════════════════════════════════════════════════════════════════════════════════════════
float volMA  = ta.sma(volume, rvLen)
bool  hiVol  = volOk and not na(volMA) and volume > volMA * rvHiMult
bool  loVol  = volOk and not na(volMA) and volume < volMA * rvLoMult
bool  isBull = close > open
bool  isBear = close < open
color rvCol  = enRV ? (hiVol ? (isBull ? colHiBull : isBear ? colHiBear : na) : loVol ? (isBull ? colLoBull : isBear ? colLoBear : na) : na) : na
barcolor(rvCol, title = "ARM Relative Volume Candles")
bool evHiVol = conf and hiVol
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  MODULE 11: MARKERS
// ═══════════════════════════════════════════════════════════════════════════════════════════════
bool mkOn = markerMode != "Hidden"
plotshape(mkOn and showUnq and evMomBuy and not mQual, "ARM Momentum Complete Buy-side", shape.labelup, location.belowbar, color = color.new(colBuy, 50), text = "M", textcolor = color.white, size = size.tiny)
plotshape(mkOn and evMomBuy and mQual, "ARM Momentum Complete Buy-side Qualified", shape.labelup, location.belowbar, color = colBuy, text = "M\nQ", textcolor = color.white, size = size.tiny)
plotshape(mkOn and showUnq and evMomSell and not mQual, "ARM Momentum Complete Sell-side", shape.labeldown, location.abovebar, color = color.new(colSell, 50), text = "M", textcolor = color.white, size = size.tiny)
plotshape(mkOn and evMomSell and mQual, "ARM Momentum Complete Sell-side Qualified", shape.labeldown, location.abovebar, color = colSell, text = "M\nQ", textcolor = color.white, size = size.tiny)
plotshape(mkOn and evTermBuy, "ARM Terminal Complete Buy-side", shape.labelup, location.belowbar, color = colTBuy, text = "T", textcolor = color.white, size = size.tiny)
plotshape(mkOn and evTermSell, "ARM Terminal Complete Sell-side", shape.labeldown, location.abovebar, color = colTSell, text = "T", textcolor = color.white, size = size.tiny)
plotshape(mkOn and showTFail and evTFailBuy, "ARM Terminal Validation Failed Buy-side", shape.xcross, location.belowbar, color = #ff9800, size = size.tiny)
plotshape(mkOn and showTFail and evTFailSell, "ARM Terminal Validation Failed Sell-side", shape.xcross, location.abovebar, color = #ff9800, size = size.tiny)
 
if conf and markerMode == "All Sequence Steps"
    string bTxt = ""
    string sTxt = ""
    if mAdv and mCnt >= 1 and mCnt <= 8
        if mSide == 1
            bTxt := str.tostring(mCnt)
        else if mSide == -1
            sTxt := str.tostring(mCnt)
    if tAdv and tCnt >= 1 and tCnt <= 12
        string tTxt = "T" + str.tostring(tCnt)
        if tSide == 1
            bTxt := bTxt == "" ? tTxt : bTxt + "\n" + tTxt
        else
            sTxt := sTxt == "" ? tTxt : tTxt + "\n" + sTxt
    if bTxt != ""
        color bCol = (mAdv and mSide == 1) ? colBuy : colTBuy
        markLbls.push(label.new(bar_index, low, bTxt, xloc.bar_index, yloc.belowbar, color.new(color.gray, 100), label.style_label_up, bCol, size.tiny))
    if sTxt != ""
        color sCol = (mAdv and mSide == -1) ? colSell : colTSell
        markLbls.push(label.new(bar_index, high, sTxt, xloc.bar_index, yloc.abovebar, color.new(color.gray, 100), label.style_label_down, sCol, size.tiny))
 
if conf
    capLabels(markLbls, maxLbl)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  MODULE 10: DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════════════════════════
var table tbl = na
if barstate.isfirst and enDash
    tbl := table.new(posOf(dashPos), 2, 5, bgcolor = color.new(dashBg, dashTr), frame_color = dashBorder, frame_width = 1, border_color = dashBorder, border_width = 1)
    table.cell(tbl, 0, 0, "AetherFlow Reversal Matrix", text_color = dashText, text_size = sizeOf(dashSize), bgcolor = color.new(dashBg, dashTr), tooltip = "AETHERFLOW REVERSAL MATRIX (ARM) by Michael_Fx_Trader. An analytical dashboard: it describes conditions and does not predict reversals or provide trade entries.")
    table.merge_cells(tbl, 0, 0, 1, 0)
 
if barstate.islast and enDash
    int di = (confDash and barstate.isrealtime and not barstate.isconfirmed) ? 1 : 0
    int  xmSide = mSide[di]
    int  xmCnt  = mCnt[di]
    bool xmQual = mQual[di]
    int  xtState = tState[di]
    int  xtSide  = tSide[di]
    int  xtCnt   = tCnt[di]
 
    // Momentum row
    string momTxt = "No active phase"
    color  momCol = dashText
    if enMom and xmSide != 0
        momTxt := (xmSide == 1 ? "Buy-side " : "Sell-side ") + str.tostring(xmCnt) + "/9" + (xmCnt == 9 ? (xmQual ? " Done+Q" : " Done") : "")
        momCol := xmSide == 1 ? colBuy : colSell
    // Terminal row
    string trmTxt = "No active phase"
    color  trmCol = dashText
    if enTerm and enMom
        string sName = xtSide == 1 ? "Buy-side" : "Sell-side"
        color  sCol2 = xtSide == 1 ? colBuy : colSell
        if xtState == 1
            trmTxt := sName + " armed - awaiting"
            trmCol := sCol2
        else if xtState == 2
            trmTxt := sName + " " + str.tostring(xtCnt) + "/13" + (xtCnt == 12 ? " (validating)" : "")
            trmCol := sCol2
        else if xtState == 3
            trmTxt := sName + " 13/13 completed"
            trmCol := sCol2
        else if xtState == 4
            trmTxt := sName + " invalidated"
            trmCol := color.gray
        else if xtState == 5
            trmTxt := "Cancelled (opposite phase)"
            trmCol := color.gray
    // Pivot row
    string pvTxt = "n/a"
    color  pvCol = dashText
    if enPiv
        float cl = close[di]
        float vS = pvS[di]
        float vP = pvP[di]
        float vR = pvR[di]
        float bestD = 1.0e18
        string nName = ""
        float  nVal  = na
        color  nCol  = dashText
        if not na(vS) and math.abs(cl - vS) < bestD
            bestD := math.abs(cl - vS)
            nName := "S"
            nVal := vS
            nCol := colPvS
        if not na(vP) and math.abs(cl - vP) < bestD
            bestD := math.abs(cl - vP)
            nName := "P"
            nVal := vP
            nCol := colPvP
        if not na(vR) and math.abs(cl - vR) < bestD
            bestD := math.abs(cl - vR)
            nName := "R"
            nVal := vR
            nCol := colPvR
        if not na(nVal) and cl != 0
            float distPct = (nVal - cl) / cl * 100.0
            pvTxt := nName + " " + (distPct >= 0 ? "+" : "") + str.tostring(math.round(distPct, 2), "0.00") + "%"
            pvCol := nCol
    // Pressure row
    string prTxt = "n/a (no volume)"
    color  prCol = dashText
    float  bp = buyPct[di]
    if enVP and not na(bp)
        int buyR  = int(math.round(bp))
        int sellR = 100 - buyR
        prTxt := buyR > sellR ? str.tostring(buyR) + "% Bull | " + str.tostring(sellR) + "% Bear" : str.tostring(sellR) + "% Bear | " + str.tostring(buyR) + "% Bull"
        prCol := buyR > sellR ? colBuy : buyR < sellR ? colSell : dashText
 
    string fs = sizeOf(dashSize)
    table.cell(tbl, 0, 1, "Momentum", text_color = dashLabel, text_halign = text.align_left, text_size = fs, bgcolor = color.new(dashBg, dashTr), tooltip = "Primary exhaustion count (0-9) from the four-bar closing comparison. Buy-side = downward sequence being monitored; Sell-side = upward sequence. 'Done' = step 9 reached, '+Q' = structural qualification passed. It does NOT mean price has reversed.")
    table.cell(tbl, 1, 1, momTxt, text_color = momCol, text_halign = text.align_right, text_size = fs, bgcolor = color.new(dashBg, dashTr))
    table.cell(tbl, 0, 2, "Terminal", text_color = dashLabel, text_halign = text.align_left, text_size = fs, bgcolor = color.new(dashBg, dashTr), tooltip = "Later-stage exhaustion count (0-13). Non-consecutive count; step 13 needs final validation against the stored step-8 close. 'validating' = count is 12 and the final check is pending. Completed only after validation passes.")
    table.cell(tbl, 1, 2, trmTxt, text_color = trmCol, text_halign = text.align_right, text_size = fs, bgcolor = color.new(dashBg, dashTr))
    table.cell(tbl, 0, 3, "Pivot [" + f_tfLabel(tfEff) + "]", text_color = dashLabel, text_halign = text.align_left, text_size = fs, bgcolor = color.new(dashBg, dashTr), tooltip = "Nearest completed-range pivot (S, P or R). Value = (pivot - close) / close * 100. Negative = pivot below price; positive = pivot above price. It is a distance measurement, not a forecast.")
    table.cell(tbl, 1, 3, pvTxt, text_color = pvCol, text_halign = text.align_right, text_size = fs, bgcolor = color.new(dashBg, dashTr))
    table.cell(tbl, 0, 4, "Pressure", text_color = dashLabel, text_halign = text.align_left, text_size = fs, bgcolor = color.new(dashBg, dashTr), tooltip = "Volume-weighted candle-body ratio over the lookback period. Buy% + Sell% = 100. It is NOT a probability of a profitable trade. Shown as n/a when volume is unavailable.")
    table.cell(tbl, 1, 4, prTxt, text_color = prCol, text_halign = text.align_right, text_size = fs, bgcolor = color.new(dashBg, dashTr))
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════
//  MODULE 12: ALERTS
// ═══════════════════════════════════════════════════════════════════════════════════════════════
// ---- Named alert conditions (static text with placeholders) ----
alertcondition(evMomBuy, "ARM 01 Momentum Complete - Buy-side", 'ARM {{ticker}} {{interval}} | Momentum Exhaustion COMPLETE (Buy-side, 9/9) | Close {{close}} | Buy Pressure {{plot("ARM Buy Pressure %")}} | {{time}}')
alertcondition(evMomSell, "ARM 01 Momentum Complete - Sell-side", 'ARM {{ticker}} {{interval}} | Momentum Exhaustion COMPLETE (Sell-side, 9/9) | Close {{close}} | Buy Pressure {{plot("ARM Buy Pressure %")}} | {{time}}')
alertcondition(evTermBuy, "ARM 02 Terminal Complete - Buy-side", 'ARM {{ticker}} {{interval}} | Terminal Exhaustion COMPLETE (Buy-side, 13/13) | Close {{close}} | Buy Pressure {{plot("ARM Buy Pressure %")}} | {{time}}')
alertcondition(evTermSell, "ARM 02 Terminal Complete - Sell-side", 'ARM {{ticker}} {{interval}} | Terminal Exhaustion COMPLETE (Sell-side, 13/13) | Close {{close}} | Buy Pressure {{plot("ARM Buy Pressure %")}} | {{time}}')
alertcondition(evPhSup, "ARM 03 Phase Support Crossed", 'ARM {{ticker}} {{interval}} | Momentum phase SUPPORT crossed | Close {{close}} | {{time}}')
alertcondition(evPhRes, "ARM 04 Phase Resistance Crossed", 'ARM {{ticker}} {{interval}} | Momentum phase RESISTANCE crossed | Close {{close}} | {{time}}')
alertcondition(evMomInvX, "ARM 05 Momentum Invalidation Crossed", 'ARM {{ticker}} {{interval}} | Momentum INVALIDATION level crossed | Close {{close}} | {{time}}')
alertcondition(evTermInvX, "ARM 06 Terminal Invalidation Crossed", 'ARM {{ticker}} {{interval}} | Terminal INVALIDATION level crossed | Close {{close}} | {{time}}')
alertcondition(evPvS, "ARM 07 Range Pivot Support Crossed", 'ARM {{ticker}} {{interval}} | Range Pivot SUPPORT crossed | Close {{close}} | {{time}}')
alertcondition(evPvP, "ARM 08 Range Pivot Central Crossed", 'ARM {{ticker}} {{interval}} | Range Pivot CENTRAL crossed | Close {{close}} | {{time}}')
alertcondition(evPvR, "ARM 09 Range Pivot Resistance Crossed", 'ARM {{ticker}} {{interval}} | Range Pivot RESISTANCE crossed | Close {{close}} | {{time}}')
alertcondition(evPUp, "ARM 10 Pressure Entered Upper Zone", 'ARM {{ticker}} {{interval}} | Pressure entered UPPER zone | Buy Pressure {{plot("ARM Buy Pressure %")}} | Close {{close}} | {{time}}')
alertcondition(evPDn, "ARM 11 Pressure Entered Lower Zone", 'ARM {{ticker}} {{interval}} | Pressure entered LOWER zone | Buy Pressure {{plot("ARM Buy Pressure %")}} | Close {{close}} | {{time}}')
alertcondition(evHiVol, "ARM 12 High-Volume Bar", 'ARM {{ticker}} {{interval}} | HIGH-VOLUME bar detected | Close {{close}} | {{time}}')
alertcondition(evQualPh, "ARM 13 Qualified Momentum Phase", 'ARM {{ticker}} {{interval}} | Momentum phase QUALIFIED | Close {{close}} | {{time}}')
alertcondition(evTFailBuy or evTFailSell, "ARM 14 Terminal Validation Failed", 'ARM {{ticker}} {{interval}} | Terminal final validation FAILED (count stays 12) | Close {{close}} | {{time}}')
 
// ---- Detailed alert() messages (single message per bar, confirmed events only) ----
string ctxTxt  = "ARM | " + syminfo.ticker + " | " + timeframe.period
string tailTxt = " | Close " + str.tostring(close, format.mintick) + (na(buyPct) ? "" : " | Buy/Sell " + str.tostring(math.round(buyPct)) + "/" + str.tostring(100 - math.round(buyPct))) + " | " + str.format_time(time, "yyyy-MM-dd HH:mm", syminfo.timezone)
string msgAll  = ""
if alMaster and conf
    if alMom and evMomBuy
        msgAll += ctxTxt + " | Momentum Exhaustion COMPLETE | Buy-side | 9/9 | " + (mQual ? "Qualified" : "Unqualified") + " | Phase high " + str.tostring(pHigh, format.mintick) + tailTxt + "\n"
    if alMom and evMomSell
        msgAll += ctxTxt + " | Momentum Exhaustion COMPLETE | Sell-side | 9/9 | " + (mQual ? "Qualified" : "Unqualified") + " | Phase low " + str.tostring(pLow, format.mintick) + tailTxt + "\n"
    if alQual and evQualPh
        msgAll += ctxTxt + " | Momentum phase QUALIFIED" + tailTxt + "\n"
    if alTerm and evTermBuy
        msgAll += ctxTxt + " | Terminal Exhaustion COMPLETE | Buy-side | 13/13 | Invalidation " + str.tostring(tFinInv, format.mintick) + " | Target " + str.tostring(tFinTarget, format.mintick) + tailTxt + "\n"
    if alTerm and evTermSell
        msgAll += ctxTxt + " | Terminal Exhaustion COMPLETE | Sell-side | 13/13 | Invalidation " + str.tostring(tFinInv, format.mintick) + " | Target " + str.tostring(tFinTarget, format.mintick) + tailTxt + "\n"
    if alTFail and (evTFailBuy or evTFailSell)
        msgAll += ctxTxt + " | Terminal validation FAILED | " + (evTFailBuy ? "Buy-side" : "Sell-side") + " | 12/13 | Reference close " + str.tostring(t8Close, format.mintick) + tailTxt + "\n"
    if alPhSup and evPhSup
        msgAll += ctxTxt + " | Momentum phase SUPPORT crossed | Level " + str.tostring(xPhSup, format.mintick) + tailTxt + "\n"
    if alPhRes and evPhRes
        msgAll += ctxTxt + " | Momentum phase RESISTANCE crossed | Level " + str.tostring(xPhRes, format.mintick) + tailTxt + "\n"
    if alMomInv and evMomInvX
        msgAll += ctxTxt + " | Momentum INVALIDATION crossed | Level " + str.tostring(xMomInv, format.mintick) + tailTxt + "\n"
    if alTrmInv and evTermInvX
        msgAll += ctxTxt + " | Terminal INVALIDATION crossed | Level " + str.tostring(na(xTermInv) ? tInv : xTermInv, format.mintick) + tailTxt + "\n"
    if alPvS and evPvS
        msgAll += ctxTxt + " | Range Pivot SUPPORT crossed | Level " + str.tostring(pvS, format.mintick) + tailTxt + "\n"
    if alPvP and evPvP
        msgAll += ctxTxt + " | Range Pivot CENTRAL crossed | Level " + str.tostring(pvP, format.mintick) + tailTxt + "\n"
    if alPvR and evPvR
        msgAll += ctxTxt + " | Range Pivot RESISTANCE crossed | Level " + str.tostring(pvR, format.mintick) + tailTxt + "\n"
    if alPUp and evPUp
        msgAll += ctxTxt + " | Pressure entered UPPER zone" + tailTxt + "\n"
    if alPDn and evPDn
        msgAll += ctxTxt + " | Pressure entered LOWER zone" + tailTxt + "\n"
    if alHiVol and evHiVol
        msgAll += ctxTxt + " | HIGH-VOLUME bar" + tailTxt + "\n"
if msgAll != ""
    alert(msgAll, alert.freq_once_per_bar_close)

← 返回列表