Absolute Dollar Agent - Ultron Alpha

absolutedollar · study · 3016 行 · 点赞 83 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © 2026 AbsoluteDollar
 
//@version=6
// ═══════════════════════════════════════════════════════════════════════════════
//  ABSOLUTE DOLLAR AGENT — ULTRON ALPHA
//  Speculative Probabilistic Core · Zone Confidence · HTF Fib Projection
// ═══════════════════════════════════════════════════════════════════════════════
//
//  LICENSE
//  ─────────────────────────────────────────────────────────────────────────────
//  Published on TradingView as a PUBLIC / OPEN-SOURCE script under the
//  Mozilla Public License 2.0. You are free to read, study, fork, modify,
//  and redistribute this code under the terms of the MPL 2.0.
//
//  "Absolute Dollar Agent" and "ULTRON" are the names of this script. They
//  are not trademarks. You may fork the code; you may not present a fork as
//  the official Absolute Dollar Agent.
//
//  Third-party concepts and methods are credited in the Attribution section
//  below. Those references identify conceptual foundations; they do not imply
//  endorsement, sponsorship, or affiliation.
//
//
// ═══════════════════════════════════════════════════════════════════════════════
//  WHY THIS EXISTS
// ═══════════════════════════════════════════════════════════════════════════════
//
//  This is a glass box augmented intelligence agent written as a Pine Script
//  indicator. Each of those terms matters.
//
//  GLASS BOX — the opposite of a black box. Every formula, threshold,
//  weighting relationship, and decision sequence is visible in the open
//  source. The tooltips show node-by-node reasoning with ✓ or ✗ markers.
//  Nothing is hidden. You are not asked to trust an opaque model. You are
//  invited to read the logic.
//
//  AUGMENTED INTELLIGENCE — the system enhances human judgment rather than
//  replacing it. It does not predict. It does not execute. It organizes
//  market information into observable states, scores conviction, grades
//  zone confidence, and presents its reasoning. The decision remains yours.
//
//  AGENT — the system perceives, remembers, and scores. It perceives the
//  market through structure, momentum, volatility, session context,
//  liquidity, and Fib regime. It remembers recent events through an
//  episodic memory buffer. It scores conviction through an 8-node discrete
//  count and a 14-node continuous posterior. It narrates its perception
//  through alerts and reports. It does not place orders. It does not have
//  independent agency. It is a decision-support agent — an intelligence
//  layer between you and the market.
//
//  I built this for myself. I wanted a way to read the market not as a
//  series of signals to react to, but as a set of observable states that
//  could be read, understood, and reasoned about. Every layer in this
//  script answers a question that the previous layer raised.
//
//  The result is not a prediction engine. It is a spatial and contextual
//  framework — a way of organizing price information so that structure,
//  direction, momentum, volatility, and session context are all visible at
//  once, without one hiding behind another.
//
//  This is not artificial intelligence. It is not machine learning. It is
//  not a trained model. It is a deterministic, transparent, rule-based
//  system that applies established market concepts (ICT, SMC, Hull, RSI,
//  ATR, Fibonacci) through a weighted fusion architecture — and shows you
//  every step of the reasoning.
//
//  The word "neural" appears in the interface as a descriptive label for
//  the weighted fusion layer, not a reference to neural networks.
//
//  I am publishing it open-source because I think this way of seeing is
//  worth sharing. If you use it and find something in it, tell me. That
//  is the only thing I am asking for.
//
// ═══════════════════════════════════════════════════════════════════════════════
//  BUILT FOR GMT+3
// ═══════════════════════════════════════════════════════════════════════════════
//
//  Most trading tools are built for New York or London. They render killzones
//  at 3 AM Nairobi time, format timestamps in EST, and assume the trader is
//  awake when the Western session opens.
//
//  This script was built the other way around. The default timezone is GMT+3
//  (East Africa Time). Every session block — Asia, London, NY AM, LDN-NY,
//  NY PM — is tuned so that the label on the chart matches the clock on the
//  wall of a trader in Nairobi, Kampala, Dar es Salaam, Addis Ababa, Cairo,
//  Riyadh, or Moscow.
//
//  The session blocks are ICT-inspired, not literal ICT killzone boundaries.
//  They were chosen because they cover the trading day a GMT+3 trader actually
//  sees — from the Asian open to the New York close — without forcing them to
//  mentally translate time zones every time they look at the chart.
//
//  Every timestamp in the script — HUD, tooltips, analysis report, episodic
//  memory — renders in GMT+3. If you trade from a different zone, the timezone
//  selector lets you change it. But the default was chosen deliberately.
//
//
// ═══════════════════════════════════════════════════════════════════════════════
//  THE TOOLTIPS ARE A COMPLETE TRADING PLAN
// ═══════════════════════════════════════════════════════════════════════════════
//
//  Most indicators give you a label. Hover it, and you get a name. Maybe a
//  number. That is all.
//
//  This script gives you a plan. Every signal label, every zone label, and
//  every entry label carries a tooltip that contains everything you need to
//  place and manage the trade — without opening a single additional panel.
//
//  SIGNAL TOOLTIP — the trade thesis:
//      • Direction and score (x/8)
//      • Execution mode and product (Signal / Multipliers / Vanilla)
//      • Contract direction, multiplier, risk sizing
//      • Stop loss price, distance in points and ticks
//      • TP1 / TP2 / TP3 prices with R multiples
//      • Fib regime source, HTF timeframe, LTF and HTF states, bars since flip
//      • Gate pass/block status for both directions
//      • Posterior probabilities, probability edge, zone confidence
//      • Node-by-node reasoning — every confluence node with ✓ or ✗
//      • Active killzone, timestamp in GMT+3, chart link
//
//  ENTRY TOOLTIP — the execution slip:
//      • Direction (CALL / PUT / LONG / SHORT) and execution mode
//      • Score and posterior
//      • Entry mode and entry price
//      • Stop loss with distance
//      • TP1 / TP2 / TP3 with distance for each
//      • Strike and expiry (options) or contract and multiplier (multipliers)
//
//  ZONE TOOLTIP — the spatial brief:
//      • Zone direction and event type
//      • High, low, and range
//      • Trail state and Ultron Gate state
//      • LTF Fib and HTF Fib regime
//      • Gate agreement status
//      • Zone confidence and posterior probabilities
//
//  The intent is that a trader never has to look anywhere else. The chart
//  tells you what is happening. The tooltip tells you what to do about it,
//  and why. Whether you take the trade is still your decision — but the
//  information is all in one place, on the hover.
//
//
// ═══════════════════════════════════════════════════════════════════════════════
//  CONCEPTS, ATTRIBUTION & ORIGINALITY
// ═══════════════════════════════════════════════════════════════════════════════
//
//  ULTRON Alpha is an integrated market-analysis implementation developed to
//  organize multiple dimensions of price information into a unified spatial
//  and contextual framework.
//
//  The system incorporates established market-analysis concepts together with
//  original integration, state handling, filtering, visual interpretation,
//  event processing, and analytical presentation developed by the author.
//
//
//  CONCEPT & METHOD ATTRIBUTION
//  ─────────────────────────────────────────────────────────────────────────────
//
//  • ICT / Inner Circle Trader concepts
//      Market-structure terminology, killzones, liquidity concepts, BOS/CHoCH,
//      order-block concepts, fair-value-gap concepts, premium/discount
//      concepts, liquidity sweeps, and related price-action terminology.
//      Session windows are ICT-inspired but tuned to GMT+3 (East Africa
//      Time), not literal ICT killzone boundaries. See "BUILT FOR GMT+3".
//
//  • Smart Money Concepts (SMC) — LuxAlgo
//      The SMC structural layer in this script (swing/internal pivots,
//      BOS/CHoCH detection, order-block storage and mitigation,
//      fair-value-gap rendering, premium/equilibrium/discount zone
//      projection, strong/weak high/low labelling, and equal high/low
//      detection) is adapted from the publicly available "Smart Money
//      Concepts (SMC) [LuxAlgo]" indicator. The original work is credited
//      to LuxAlgo. Any bugs or behavioural differences in this adaptation
//      are the responsibility of the author of this script, not LuxAlgo.
//
//  • Hull Moving Average — Alan Hull
//      The HMA/EHMA/THMA Hull Suite implementation follows the classic Hull
//      Moving Average formulation associated with Alan Hull. The wrapper
//      pattern is a standard public implementation.
//
//  • RSI / ATR — J. Welles Wilder
//      Classic Relative Strength Index and Average True Range methodologies
//      associated with J. Welles Wilder, used in momentum, volatility,
//      trail, and strike-distance calculations.
//
//  • Fibonacci retracement and extension levels
//      Standard 0.382 / 0.5 / 0.618 / 0.786 retracement and 1.272 / 1.414 /
//      1.618 / 2.0 / 2.618 extension ratios. These are mathematical
//      constants, not proprietary formulas.
//
//  • Multiplier-contract asset-class mapping
//      Asset-class detection (crypto_major, crypto_minor, commodity_metal,
//      commodity_oil, synthetic_vol, synthetic_jump, synthetic_bullbear,
//      forex) and multiplier-cap tiers reflect publicly documented contract
//      limits for multiplier-style derivative products. Caps change over
//      time; users should verify current limits with their own broker.
//
//  These references identify conceptual and methodological foundations.
//  They do not imply endorsement, sponsorship, partnership, or affiliation
//  with any third-party educator, author, organization, or vendor unless
//  expressly stated.
//
//
//  ORIGINALITY & OPEN-SOURCE IMPLEMENTATION
//  ─────────────────────────────────────────────────────────────────────────────
//  ULTRON Alpha is not presented as a new invention of the underlying market
//  concepts themselves. Its original character resides in the implementation
//  and integration of those concepts into a unified analytical framework.
//
//  The distinctive implementation includes original combinations of:
//
//      • Three-tier architecture (Observation / Judgement / Execution)
//      • Speculative Probabilistic Core — a 14-node continuous fusion
//        layer with configurable weights and sigmoid temperature
//      • Zone Confidence Engine — multi-source corroboration scoring for
//        CHoCH zones with star grading (⭐ / ⭐⭐ / ⭐⭐⭐)
//      • HTF Fibonacci Projection — regime-anchored retracement and
//        extension grid redrawn at barstate.islast
//      • Zone Quality Gate — width / HTF-agreement / extension guards that
//        filter CHoCH zones before they become tradeable
//      • Consolidated Alert Dispatcher — priority-queue alert logic
//        (trade events > triggers > informational > blocked observations >
//        scale-ins) ensuring at most one message per bar
//      • Episodic Memory — a rolling event buffer with session tagging,
//        rendered in the analysis report
//      • Synthetic-aware node weighting — discounts fake volume on
//        synthetic instruments
//      • Broker-aware execution engine — asset-class detection, multiplier
//        caps, contract-direction mapping, deal-cancellation availability,
//        and strike selection (ATM/ITM/OTM/Dynamic) for vanilla options
//      • Tooltip-as-trading-plan — every signal, entry, and zone label
//        carries a full trade thesis on hover
//
//  The exact formulas, thresholds, weighting relationships, state
//  transitions, internal calculations, decision sequencing, and
//  event-processing mechanisms are visible in the open source. You are
//  encouraged to read them.
//
//
// ═══════════════════════════════════════════════════════════════════════════════
//  WHAT THIS INDICATOR IS
// ═══════════════════════════════════════════════════════════════════════════════
//
//  ULTRON Alpha is a multi-timeframe market-analysis engine designed to help
//  organize price action into observable structural, directional, spatial,
//  momentum, volatility, and session-based states.
//
//  Depending on configuration, the indicator can provide:
//
//      • Internal and swing market-structure information
//      • BOS / CHoCH structural references
//      • Liquidity and price-location zones
//      • Fibonacci-based spatial references (LTF + HTF projection)
//      • Trend-regime context (Macro Hull, Fast Hull, Trail)
//      • Adaptive price trails with an Alpha Gate permission layer
//      • Momentum and confluence states (8-node discrete score)
//      • A speculative fusion layer (14-node continuous probability)
//      • Zone confidence grading (⭐ / ⭐⭐ / ⭐⭐⭐)
//      • Session / killzone context tuned to GMT+3
//      • Visual entry, stop and target planning references
//      • Position lifecycle management (entry → TP1 → TP2 → TP3 → exit)
//      • A dashboard summarizing multiple analytical states
//      • Configurable alert and event outputs (consolidated,
//        verbosity-controlled, with optional raw JSON payloads)
//
//  The indicator is intended to organize information rather than remove
//  the need for human judgment.
//
//  IMPORTANT — ON THE WORD "NEURAL":
//  The terms "Neural", "Neural Confluence", and "Speculative Probabilistic
//  Core" are descriptive labels for a weighted fusion layer composed of
//  bounded node outputs and sigmoid transformations. This script does not
//  use machine learning, neural networks, deep learning, or any trained
//  model. The fusion is deterministic, transparent, and fully auditable.
//
//
// ═══════════════════════════════════════════════════════════════════════════════
//  CORE DESIGN PHILOSOPHY
// ═══════════════════════════════════════════════════════════════════════════════
//
//  ULTRON follows the principle:
//
//      READ PRICE → BUILD CONTEXT → OBSERVE → PLAN → EXECUTE
//
//  The system is designed around the idea that market intelligence should
//  be observable, structured, explainable at the output level, and usable
//  as part of a broader discretionary or systematic workflow.
//
//  ULTRON does not guarantee future market direction, signal accuracy,
//  profitability, or any particular trading outcome.
//
//
// ═══════════════════════════════════════════════════════════════════════════════
//  ANALYTICAL ARCHITECTURE
// ═══════════════════════════════════════════════════════════════════════════════
//
//  At a high level, ULTRON Alpha is organized around a three-tier
//  architecture:
//
//      Tier 1 · OBSERVATION
//          Everything is drawn, unconditionally. Structure, zones, Fibs,
//          killzones, liquidity, Hull bands, trail — all visible regardless
//          of score. Nothing is hidden behind a gate.
//
//      Tier 2 · JUDGEMENT
//          8-node discrete confluence score + quality gates + Fib regime.
//          This layer answers "is this structurally sound?" with a count.
//          Transparent, auditable, and manually tunable.
//
//      Tier 2.5 · SPECULATION
//          14-node continuous fusion layer. Each node outputs a bounded
//          value, not a yes/no. Weights are configurable. This layer
//          answers "how much conviction?" and runs in parallel with Tier 2.
//
//      Tier 3 · EXECUTION
//          Position Tool fires only when Tier 2 clears. Entry mode
//          (Signal Change / Trail Retest / Zone Retest), TP ladder,
//          breakeven logic, and trail-flip exits are all managed here.
//
//  The exact internal relationships between these layers are visible in
//  the open source. The output — HUD, zone labels, tooltips, alerts — is
//  explainable at the output level.
//
//
// ═══════════════════════════════════════════════════════════════════════════════
//  MULTI-TIMEFRAME USE
// ═══════════════════════════════════════════════════════════════════════════════
//
//  ULTRON can be configured for different chart timeframes and market
//  contexts. Higher-timeframe information is used for regime context (HTF
//  Fib gate, MTF CHoCH confluence, HTF Swing Projection), while
//  lower-timeframe information drives tactical triggers.
//
//  Multiple request.security calls are used: one for the HTF Fib regime
//  (with [1] for confirmed-bar integrity), one for MTF CHoCH confluence,
//  and one for HTF Fib Swing Projection. All use lookahead_off. No
//  lookahead bias is introduced.
//
//  Users should evaluate the behavior of the indicator on the instruments
//  and timeframes for which they intend to use it. Recommended use is on
//  liquid markets where underlying structure is not dominated by gaps or
//  synthetic noise.
//
//
// ═══════════════════════════════════════════════════════════════════════════════
//  POSITION & TRADE-PLANNING TOOLS
// ═══════════════════════════════════════════════════════════════════════════════
//
//  The indicator includes visual position-planning functionality that can
//  display entry references, stop references, target references, and
//  evolving trade-management states.
//
//  Three entry modes are supported:
//      • Signal Change — enter on trail flip
//      • Trail Retest — wait for price to retest the trail after a flip
//      • Zone Retest — wait for price to retrace into the active CHoCH zone
//
//  These elements are analytical and visual tools. They do not represent
//  an execution instruction, brokerage order, or guarantee that a market
//  level will be reached.
//
//
// ═══════════════════════════════════════════════════════════════════════════════
//  EXECUTION ENGINE
// ═══════════════════════════════════════════════════════════════════════════════
//
//  The execution engine is broker-agnostic but includes logic for
//  multiplier-contract environments (asset-class caps, contract-direction
//  mapping, deal-cancellation availability) and vanilla-options environments
//  (strike selection, suggested expiry).
//
//  Three execution modes are supported:
//      • Signal Only — no execution context, labels only
//      • Multipliers — multiplier-style contracts with asset-class caps
//        and risk-per-trade sizing
//      • Vanilla Options — CALL/PUT strike selection (ATM/ITM/OTM/Dynamic)
//        with suggested expiry
//
//  Multiplier caps are display-only and reflect publicly documented limits
//  for multiplier-style derivative products. They are not a guarantee of
//  what your broker will accept.
//
//  This is not financial advice. No execution is performed by this script.
//  The script does not place orders. It produces visual references and
//  alert payloads. You are responsible for every trade you take.
//
//
// ═══════════════════════════════════════════════════════════════════════════════
//  ALERTS & EVENT PROCESSING
// ═══════════════════════════════════════════════════════════════════════════════
//
//  ULTRON includes configurable alert conditions and event-driven outputs.
//
//  The consolidated dispatcher uses a priority queue:
//      1. Trade events (entry, TP1, TP2, TP3, exit)
//      2. Trigger signals
//      3. Informational (score context, blocked observations)
//      4. Scale-ins and regime exits
//
//  At most ONE message per bar is sent. Trade events take priority over
//  informational messages. The Alert Verbosity selector (All / Consolidated
//  / Trade Events Only) controls how much chatter reaches your webhook.
//
//  Raw JSON payloads are OFF by default. Turn them ON only if you have an
//  external webhook consumer. This prevents duplicate JSON payloads from
//  reaching a messaging endpoint.
//
//  Alert behavior depends on the user's selected settings, chart timeframe,
//  symbol, market data, and TradingView alert configuration.
//
//  Alert outputs should be treated as informational events generated from
//  the indicator's current analytical state.
//
//
// ═══════════════════════════════════════════════════════════════════════════════
//  LIMITATIONS
// ═══════════════════════════════════════════════════════════════════════════════
//
//  • This is an INDICATOR, not a STRATEGY. There is no strategy() call,
//    no backtest, no Strategy Tester results, no Performance Report. Any
//    claim of backtested performance is invalid.
//
//  • Repaint surface: the current bar's trail flip, CHoCH break, and
//    close-based scoring can change until the bar closes. HTF Fib
//    Projection redraws at barstate.islast. Alerts and gates use
//    barstate.isconfirmed, so the signal does not repaint — but the
//    drawing does.
//
//  • Compute weight: this script is heavy. Use "Calc Only Last N Bars"
//    and "Show Last N Zones" on high-timeframe or long-history charts.
//    Drawing budget is 500 labels / 500 boxes / 500 lines each, managed
//    by an active-set / stored-set recycling system. Exceeding the budget
//    will cause older drawings to be deleted.
//
//  • "Neural" is a naming choice, not machine learning. The fusion layer
//    is weighted sigmoid combination of bounded node outputs. It is
//    transparent, auditable, and configurable. It is not a trained model.
//
//  • Market conditions can change rapidly and may invalidate previous
//    context.
//
//  • Technical indicators operate on historical and current market data
//    and cannot know future prices.
//
//  • Different instruments and timeframes can produce materially different
//    behavior.
//
//  • Indicator calculations may be affected by the availability and
//    quality of the underlying market data. Synthetic instruments may
//    carry volume data that is not meaningful; the synthetic-aware weight
//    zeroing handles this in the fusion layer, but not in the 8-node
//    discrete score.
//
//  • Visual states and alerts should be independently evaluated before
//    use.
//
//  • No analytical system can eliminate market risk or guarantee results.
//
//
// ═══════════════════════════════════════════════════════════════════════════════
//  DISCLAIMER
// ═══════════════════════════════════════════════════════════════════════════════
//
//  ULTRON Alpha is provided for educational, analytical, and research
//  purposes.
//
//  Nothing contained in this indicator constitutes financial, investment,
//  trading, or other professional advice. The indicator does not guarantee
//  accuracy, profitability, signal quality, or any specific result.
//
//  Trading financial markets involves substantial risk. Users are
//  responsible for their own decisions, risk management, and evaluation of
//  the suitability of this indicator for their individual circumstances.
//
//  Historical observations and simulated or visual trade-management
//  behavior do not guarantee future results.
//
// ═══════════════════════════════════════════════════════════════════════════════
 
indicator("Absolute Dollar Agent", "U L T R O N", true, max_labels_count=500, max_boxes_count=500, max_lines_count=500)
 
// [A] CONSTANTS — ULTRON's fixed truths
const int BULLISH_LEG   = 1
const int BEARISH_LEG   = 0
const int BULLISH       = 1
const int BEARISH       = -1
const string HISTORICAL = 'Historical'
const string PRESENT    = 'Present'
const string COLORED    = 'Colored'
const string MONOCHROME = 'Monochrome'
const string ALL        = 'All'
const string BOS        = 'BOS'
const string CHOCH      = 'CHoCH'
const string TINY       = size.tiny
const string SMALL      = size.small
const string NORMAL     = size.normal
const string ATR        = 'Atr'
const string RANGE      = 'Cumulative Mean Range'
const string CLOSE_STR  = 'Close'
const string HIGHLOW    = 'High/Low'
const color GREEN       = #089981
const color RED         = #F23645
const color BLUE        = #2157f3
const color GRAY        = #878b94
const color MONO_BULLISH  = #b2b5be
const color MONO_BEARISH  = #5d606b
const color LONG_COLOR    = #2962FF
const color SHORT_COLOR   = #FF6D00
const string EXEC_SIGNAL  = "Signal Only"
const string EXEC_MULT    = "Multipliers"
const string EXEC_VANILLA = "Vanilla Options"
 
// [B] TYPES — structural memory
type alerts
    bool internalBullishBOS         = false
    bool internalBearishBOS         = false
    bool internalBullishCHoCH       = false
    bool internalBearishCHoCH       = false
    bool swingBullishBOS            = false
    bool swingBearishBOS            = false
    bool swingBullishCHoCH          = false
    bool swingBearishCHoCH          = false
    bool internalBullishOrderBlock  = false
    bool internalBearishOrderBlock  = false
    bool swingBullishOrderBlock     = false
    bool swingBearishOrderBlock     = false
    bool equalHighs                 = false
    bool equalLows                  = false
    bool bullishFairValueGap        = false
    bool bearishFairValueGap        = false
 
type trailingExtremes
    float top
    float bottom
    int barTime
    int barIndex
    int lastTopTime
    int lastBottomTime
 
type fairValueGap
    float top
    float bottom
    int bias
    box topBox
    box bottomBox
 
type trend
    int bias
 
type equalDisplay
    line l_ine   = na
    label l_abel = na
 
type pivot
    float currentLevel
    float lastLevel
    bool crossed
    int barTime  = time
    int barIndex = bar_index
 
type orderBlock
    float barHigh
    float barLow
    int barTime
    int bias
 
type PositionTool
    float entry
    float sl
    float tp1
    float tp2
    float tp3
    bool  is_bull
    int   anchor_bar
    line  entry_line
    line  sl_line
    line  tp1_line
    line  tp2_line
    line  tp3_line
    label entry_lbl
    label sl_lbl
    label tp1_lbl
    label tp2_lbl
    label tp3_lbl
    box   risk_box
 
// [C] GROUPS — operator's control panel
string GRP_MS    = "① Market Structure (CHoCH)"
string GRP_FIB   = "② Fibonacci Rendering"
string GRP_ZONE  = "③ Buy/Sell Zone Projection"
string GRP_HULL  = "④ Hull Suite"
string GRP_TRAIL = "⑤ Trail Engine"
string GRP_ULT   = "⑥ Ultron Gate"
string GRP_LIQ   = "⑦ Liquidity Zones"
string GRP_NEUR  = "⑧ Neural Confluence Score"
string GRP_POS   = "⑨ Position Tool"
string GRP_SMCSET= "⑩ SMC Structure"
string GRP_KZ    = "⑪ ICT Killzones"
string GRP_SMART = "⑫ RSI Smart Signals"
string GRP_HUD   = "⑬ HUD"
string GRP_PERF  = "⑭ Performance"
string GRP_EXEC  = "⑮ Execution Engine"
string GRP_AGENT = "⑯ Telegram Agent"
string GRP_FIBG  = "⑰ Fib Intelligence Gate"
string GRP_PROB  = "⑱ Speculative Probabilistic Core"
 
// [D] INPUTS
bool   showBullMS   = input.bool(true,  "Bullish CHoCH", inline="MS1", group=GRP_MS)
color  bullMSColor  = input.color(LONG_COLOR, "", inline="MS1", group=GRP_MS)
bool   showBearMS   = input.bool(true,  "Bearish CHoCH", inline="MS2", group=GRP_MS)
color  bearMSColor  = input.color(SHORT_COLOR, "", inline="MS2", group=GRP_MS)
int    fractalLen   = input.int(10, "Fractal Length", minval=3, maxval=501, group=GRP_MS)
bool   requireBody  = input.bool(true, "Break = Close Beyond Level", group=GRP_MS)
string msLineStyle  = input.string("Solid", "CHoCH Line Style", options=["Solid","Dashed","Dotted"], group=GRP_MS)
int    msLineWidth  = input.int(2, "CHoCH Line Width", minval=1, maxval=5, group=GRP_MS)
bool   highlightAOI = input.bool(true, "Highlight AOI Box", group=GRP_MS)
bool   useZoneQuality  = input.bool(true,  "🔬 Zone Quality Gate", group=GRP_MS)
float  minZoneAtr      = input.float(0.5,  "…Min Zone Width (ATR)", minval=0.0, maxval=3.0, step=0.1, group=GRP_MS)
float  extAtrGuard     = input.float(3.0,  "…Extension Guard (ATR)", minval=0.5, maxval=10.0, step=0.5, group=GRP_MS)
bool   requireHtfAgree = input.bool(true,  "…Require HTF Fib Agreement", group=GRP_MS)
 
bool  showFibs    = input.bool(true, "Show Fibonacci Levels", group=GRP_FIB)
color fibBullClr  = input.color(LONG_COLOR, "Bullish Fib Color", group=GRP_FIB)
color fibBearClr  = input.color(SHORT_COLOR, "Bearish Fib Color", group=GRP_FIB)
bool  show_0      = input.bool(true,  "0",     inline="F0", group=GRP_FIB)
bool  show_0_382  = input.bool(true,  "0.382", inline="F1", group=GRP_FIB)
bool  show_0_5    = input.bool(true,  "0.5",   inline="F1", group=GRP_FIB)
bool  show_0_618  = input.bool(true,  "0.618", inline="F2", group=GRP_FIB)
bool  show_0_786  = input.bool(true,  "0.786", inline="F3", group=GRP_FIB)
bool  show_1      = input.bool(true,  "1",     inline="F3", group=GRP_FIB)
 
bool   showZones    = input.bool(true, "Show Buy/Sell Zones", group=GRP_ZONE)
int    barsToRight  = input.int(10, "Bars to Right", minval=1, maxval=300, group=GRP_ZONE)
color  zoneUpClr    = input.color(LONG_COLOR, "Bull Zone Color", group=GRP_ZONE)
color  zoneDnClr    = input.color(SHORT_COLOR, "Bear Zone Color", group=GRP_ZONE)
int    hlWidth      = input.int(2, "H/L Line Width", minval=1, maxval=5, group=GRP_ZONE)
int    stepWidth    = input.int(1, "Step Line Width", minval=1, maxval=5, group=GRP_ZONE)
string zoneStyle    = input.string("Dotted", "Step Style", options=["Solid","Dashed","Dotted"], group=GRP_ZONE)
color  boxFillUp    = input.color(color.new(LONG_COLOR, 88), "Box Fill UP", group=GRP_ZONE)
color  boxFillDn    = input.color(color.new(SHORT_COLOR, 88), "Box Fill DN", group=GRP_ZONE)
color  boxBorderUp  = input.color(LONG_COLOR, "Box Border UP", group=GRP_ZONE)
color  boxBorderDn  = input.color(SHORT_COLOR, "Box Border DN", group=GRP_ZONE)
bool   showLevelLbls= input.bool(true, "Show Level Labels", group=GRP_ZONE)
color  levelLblTxt  = input.color(#d1d4dc, "Level Label Text", group=GRP_ZONE)
string lblSize      = input.string("small", "Zone Label Size", options=["tiny","small","normal"], group=GRP_ZONE)
float  lblAtrGap    = input.float(0.35, "Label ATR Gap", minval=0.05, maxval=5.0, step=0.05, group=GRP_ZONE)
bool   dimDivergentZones = input.bool(true, "Dim Fib-Divergent Zones", group=GRP_ZONE)
bool   useMtfConfluence = input.bool(true, "⭐ MTF CHoCH Confluence", group=GRP_ZONE)
string mtfConfluenceTf  = input.timeframe("15", "Confluence TF", group=GRP_ZONE)
bool   useHtfFibProj    = input.bool(true,  "📐 HTF Fib Projection", group=GRP_ZONE)
bool   showHtfFibRetr   = input.bool(true,  "…Retracements", group=GRP_ZONE, inline="hf1")
bool   showHtfFibExt    = input.bool(true,  "…Extensions",   group=GRP_ZONE, inline="hf1")
color  htfFibUpClr      = input.color(color.new(color.blue, 40),   "HTF Fib Up", group=GRP_ZONE)
color  htfFibDnClr      = input.color(color.new(color.orange, 40), "HTF Fib Dn", group=GRP_ZONE)
 
float  hullSrc      = input(close, "Hull Source", group=GRP_HULL)
string modeSwitch   = input.string("Hma", "Hull Variation", options=["Hma","Thma","Ehma"], group=GRP_HULL)
int    hullLength   = input.int(200, "Macro Hull Length", minval=1, group=GRP_HULL)
int    hullFastLen  = input.int(21,  "Fast Hull Length", minval=1, group=GRP_HULL)
float  lengthMult   = input.float(1.0, "Length multiplier", minval=0.1, step=0.1, group=GRP_HULL)
bool   useHtf       = input.bool(false, "Use Higher TF Macro Hull", group=GRP_HULL)
string htf          = input.timeframe("240", "Higher timeframe", group=GRP_HULL)
bool   visualSwitch = input.bool(true,  "Show Macro Hull Band", group=GRP_HULL)
int    thicknesSwitch = input.int(1, "Hull Line Thickness", minval=1, group=GRP_HULL)
int    transpSwitch = input.int(40, "Band Transparency", minval=0, maxval=100, step=5, group=GRP_HULL)
 
int   ma_len       = input.int(13, "Trail MA Length", minval=1, maxval=200, group=GRP_TRAIL)
int   trail_atr_len= input.int(10, "Trail ATR Length", minval=1, maxval=100, group=GRP_TRAIL)
float atr_mult     = input.float(1.25, "Trail Distance (ATR)", minval=0.5, maxval=8.0, step=0.25, group=GRP_TRAIL)
bool  useAlphaGate = input.bool(true, "Enable Alpha Gate", group=GRP_TRAIL)
int   emaFast      = input.int(21, "Alpha EMA Fast", minval=1, group=GRP_TRAIL)
int   emaSlow      = input.int(55, "Alpha EMA Slow", minval=1, group=GRP_TRAIL)
bool  useTrailGray      = input.bool(true,  "Gray Trail When Opposing", group=GRP_TRAIL)
bool  useTrailGrayFib   = input.bool(true,  "…Dominant = Fib", group=GRP_TRAIL)
bool  useTrailGrayHull  = input.bool(true,  "…Dominant = Hull", group=GRP_TRAIL)
 
bool  useUltronGate= input.bool(true, "Enable Ultron Gate", group=GRP_ULT)
int   fibLen       = input.int(50, "Fib Basis Length", minval=1, group=GRP_ULT)
int   fibAtrLen    = input.int(14, "Fib ATR Length", minval=1, group=GRP_ULT)
bool  showFibBands = input.bool(true, "Show Fib Bands", group=GRP_ULT)
 
int   swing_len   = input.int(12, "Liquidity Swing Lookback", minval=2, maxval=30, group=GRP_LIQ)
bool  show_lq     = input.bool(true, "Show Liquidity Zones", group=GRP_LIQ)
int   max_lq_zones= input.int(5, "Max Liq Zones", minval=1, maxval=12, group=GRP_LIQ)
int   extend_lq   = input.int(50, "Liq Extend Bars", minval=10, maxval=300, group=GRP_LIQ)
float lq_atr_mult = input.float(0.35, "Liq Zone Thickness (ATR)", minval=0.05, maxval=2.0, step=0.05, group=GRP_LIQ)
 
float minScore     = input.float(4.0, "Minimum Score (Max 8)", minval=1.0, maxval=8.0, step=0.5, group=GRP_NEUR)
bool  w_hull       = input.bool(true, "Node: Macro Hull",   group=GRP_NEUR, inline="n1")
bool  w_fast       = input.bool(true, "Node: Fast Hull",    group=GRP_NEUR, inline="n1")
bool  w_trail      = input.bool(true, "Node: Trail Trend",  group=GRP_NEUR, inline="n2")
bool  w_choch      = input.bool(true, "Node: CHoCH",        group=GRP_NEUR, inline="n2")
bool  w_aoi        = input.bool(true, "Node: AOI",          group=GRP_NEUR, inline="n3")
bool  w_mom        = input.bool(true, "Node: Momentum",     group=GRP_NEUR, inline="n3")
bool  w_ult        = input.bool(true, "Node: Ultron Gate",  group=GRP_NEUR, inline="n4")
bool  w_vol        = input.bool(true, "Node: Volume",       group=GRP_NEUR, inline="n4")
int   momLookback  = input.int(5,  "Momentum Lookback", minval=1, maxval=50, group=GRP_NEUR)
float momThresh    = input.float(0.5, "Momentum Threshold", minval=0.05, maxval=3.0, step=0.05, group=GRP_NEUR)
float volMult      = input.float(1.2, "Volume Multiplier", minval=0.5, maxval=5.0, step=0.1, group=GRP_NEUR)
int   volLen       = input.int(20, "Volume MA Length", minval=1, group=GRP_NEUR)
bool  showSignals  = input.bool(true, "Show BUY/SELL Labels", group=GRP_NEUR)
bool  showRejected = input.bool(true, "Show Rejected Flips", group=GRP_NEUR)
bool  showRawFlip  = input.bool(true, "Show Raw Flip Diamonds", group=GRP_NEUR)
float signalOffset = input.float(0.5, "Signal Offset (ATR)", minval=0.0, maxval=3.0, step=0.1, group=GRP_NEUR)
float minZoneConfForTrig = input.float(0.50, "🔬 Min Zone Confidence to Trigger", minval=0.0, maxval=1.0, step=0.05, group=GRP_NEUR)
bool  label_all_flips       = input.bool(true,  "Label ALL Trail Flips", group=GRP_NEUR)
bool  notify_all_flips      = input.bool(false, "Notify on ALL Flips", group=GRP_NEUR)
bool  alert_neural_triggers = input.bool(true,  "🔔 Alert NEURAL triggers", group=GRP_NEUR)
bool  alert_informational   = input.bool(true,  "ℹ️ Alert informational", group=GRP_NEUR)
bool  alert_fib_blocked     = input.bool(true,  "👁️ Alert Fib-Blocked", group=GRP_NEUR)
 
bool  use_fib_gate         = input.bool(true,  "🔬 Fib Regime Gate",  group=GRP_FIBG)
bool  use_fib_band_filter  = input.bool(true,  "🔬 LTF Band Filter", group=GRP_FIBG)
bool  use_fib_cooldown     = input.bool(true,  "🔬 Fib Flip Cooldown",  group=GRP_FIBG)
int   fib_cooldown_bars    = input.int(5, "Cooldown (LTF bars)", minval=1, maxval=50, group=GRP_FIBG)
bool  use_fib_soft_override= input.bool(true, "🔬 Soft Override (score ≥ 7)", group=GRP_FIBG)
string htf_fib_mode    = input.string("HTF Only", "🔭 Fib Regime Source", options=["LTF Only","HTF Only","Both"], group=GRP_FIBG)
bool   use_htf_fib_auto = input.bool(true, "Auto-resolve higher TF", group=GRP_FIBG)
string htf_fib_manual   = input.timeframe("15", "Manual higher TF", group=GRP_FIBG)
bool   use_htf_band     = input.bool(true, "🔭 HTF Band Filter", group=GRP_FIBG)
bool   use_htf_cooldown = input.bool(true, "🔭 HTF Flip Cooldown", group=GRP_FIBG)
int    htf_cooldown_bars= input.int(8, "Cooldown (LTF bars)", minval=1, maxval=100, group=GRP_FIBG)
 
bool   useProbCore = input.bool(true, "🧠 Enable Probabilistic Core", group=GRP_PROB)
float  probSignalFloor = input.float(0.62, "Posterior High-Conviction Threshold", minval=0.5, maxval=0.95, step=0.01, group=GRP_PROB)
float w_hull_p    = input.float(1.0, "Macro Hull",   group=GRP_PROB, inline="w1")
float w_fast_p    = input.float(0.8, "Fast Hull",    group=GRP_PROB, inline="w1")
float w_trail_p   = input.float(1.5, "Trail",        group=GRP_PROB, inline="w2")
float w_choch_p   = input.float(1.2, "CHoCH",        group=GRP_PROB, inline="w2")
float w_aoi_p     = input.float(0.7, "AOI",          group=GRP_PROB, inline="w3")
float w_mom_p     = input.float(1.0, "Momentum",     group=GRP_PROB, inline="w3")
float w_ult_p     = input.float(1.3, "Ultron Gate",  group=GRP_PROB, inline="w4")
float w_vol_p     = input.float(0.6, "Volume",       group=GRP_PROB, inline="w4")
float w_rsi_p     = input.float(0.9, "RSI",          group=GRP_PROB, inline="w5")
float w_kz_p      = input.float(0.3, "Killzone",     group=GRP_PROB, inline="w5")
float w_htffib_p  = input.float(1.4, "HTF Fib",      group=GRP_PROB, inline="w6")
float w_mtf_p     = input.float(1.1, "MTF CHoCH",    group=GRP_PROB, inline="w6")
float w_pd_p      = input.float(0.8, "Prem/Disc",    group=GRP_PROB, inline="w7")
float w_lq_p      = input.float(0.9, "Liquidity",    group=GRP_PROB, inline="w7")
float probTemp    = input.float(1.0, "Sigmoid Temperature", minval=0.2, maxval=3.0, step=0.1, group=GRP_PROB)
 
bool  show_pos_tool    = input.bool(true, "Show Position Tool", group=GRP_POS)
string entry_mode      = input.string("Signal Change", "Entry Mode", options=["Signal Change","Trail Retest","Zone Retest"], group=GRP_POS)
int   zoneRetestWindow = input.int(50, "Zone Retest Window (bars)", minval=5, maxval=500, group=GRP_POS)
float tp1_r            = input.float(1.0, "TP1 (R)", minval=0.1, maxval=20.0, step=0.1, group=GRP_POS)
float tp2_r            = input.float(1.5, "TP2 (R)", minval=0.1, maxval=20.0, step=0.1, group=GRP_POS)
float tp3_r            = input.float(2, "TP3 (R)", minval=0.1, maxval=20.0, step=0.1, group=GRP_POS)
int   pos_extend       = input.int(30, "Position Extend Bars", minval=10, maxval=300, group=GRP_POS)
bool  lock_tp1_at_tp2  = input.bool(true, "🔒 Lock TP1 at TP2", group=GRP_POS)
float be_buffer        = input.float(0.0, "Breakeven Buffer", group=GRP_POS)
bool  sl_close_confirm = input.bool(true, "🛡️ SL on Close Only", group=GRP_POS)
float pips_per_point   = input.float(0.1, "Pips per Point", minval=0.001, step=0.01, group=GRP_POS)
 
var grpSMC = GRP_SMCSET
modeInput      = input.string(HISTORICAL, 'Mode',  group=grpSMC, options=[HISTORICAL,PRESENT])
styleInput     = input.string(COLORED,    'Style', group=grpSMC, options=[COLORED,MONOCHROME])
showTrendInput = input(false, 'Color Candles by SMC', group=grpSMC)
showInternalsInput            = input(true,  'Show Internal Structure', group=grpSMC)
showInternalBullInput         = input.string(ALL, 'Bullish Structure', group=grpSMC, inline='ibull', options=[ALL,BOS,CHOCH])
internalBullColorInput        = input(LONG_COLOR, '', group=grpSMC, inline='ibull')
showInternalBearInput         = input.string(ALL, 'Bearish Structure', group=grpSMC, inline='ibear', options=[ALL,BOS,CHOCH])
internalBearColorInput        = input(SHORT_COLOR, '', group=grpSMC, inline='ibear')
internalFilterConfluenceInput = input(false, 'Confluence Filter', group=grpSMC)
internalStructureSize         = input.string(TINY, 'Internal Label Size', group=grpSMC, options=[TINY,SMALL,NORMAL])
showStructureInput            = input(true,  'Show Swing Structure', group=grpSMC)
showSwingBullInput            = input.string(ALL, 'Bullish Structure', group=grpSMC, inline='bull', options=[ALL,BOS,CHOCH])
swingBullColorInput           = input(LONG_COLOR, '', group=grpSMC, inline='bull')
showSwingBearInput            = input.string(ALL, 'Bearish Structure', group=grpSMC, inline='bear', options=[ALL,BOS,CHOCH])
swingBearColorInput           = input(SHORT_COLOR, '', group=grpSMC, inline='bear')
swingStructureSize            = input.string(SMALL, 'Swing Label Size', group=grpSMC, options=[TINY,SMALL,NORMAL])
showSwingsInput               = input(false, 'Show Swing Points', group=grpSMC, inline='swings')
swingsLengthInput             = input.int(50, '', group=grpSMC, minval=10, inline='swings')
showHighLowSwingsInput        = input(true, 'Show Strong/Weak High/Low', group=grpSMC)
showInternalOrderBlocksInput  = input(true,  'Internal Order Blocks', group=grpSMC, inline='iob')
internalOrderBlocksSizeInput  = input.int(5, '', group=grpSMC, minval=1, maxval=20, inline='iob')
showSwingOrderBlocksInput     = input(false, 'Swing Order Blocks', group=grpSMC, inline='ob')
swingOrderBlocksSizeInput     = input.int(5, '', group=grpSMC, minval=1, maxval=20, inline='ob')
orderBlockFilterInput         = input.string('Atr', 'OB Filter', group=grpSMC, options=[ATR,RANGE])
orderBlockMitigationInput     = input.string(HIGHLOW, 'OB Mitigation', group=grpSMC, options=[CLOSE_STR,HIGHLOW])
internalBullishOrderBlockColor = input.color(color.new(LONG_COLOR,80), 'Internal Bull OB', group=grpSMC)
internalBearishOrderBlockColor = input.color(color.new(SHORT_COLOR,80), 'Internal Bear OB', group=grpSMC)
swingBullishOrderBlockColor    = input.color(color.new(LONG_COLOR,70), 'Bullish OB', group=grpSMC)
swingBearishOrderBlockColor    = input.color(color.new(SHORT_COLOR,70), 'Bearish OB', group=grpSMC)
showEqualHighsLowsInput       = input(true,  'Equal High/Low', group=grpSMC)
equalHighsLowsLengthInput     = input.int(3, 'Bars Confirmation', group=grpSMC, minval=1)
equalHighsLowsThresholdInput  = input.float(0.1, 'Threshold', group=grpSMC, minval=0, maxval=0.5, step=0.1)
equalHighsLowsSizeInput       = input.string(TINY, 'Label Size', group=grpSMC, options=[TINY,SMALL,NORMAL])
showFairValueGapsInput        = input(false, 'Fair Value Gaps', group=grpSMC)
fairValueGapsThresholdInput   = input(true,  'Auto Threshold', group=grpSMC)
fairValueGapsTimeframeInput   = input.timeframe('', 'Timeframe', group=grpSMC)
fairValueGapsBullColorInput   = input.color(color.new(LONG_COLOR,70), 'Bullish FVG', group=grpSMC)
fairValueGapsBearColorInput   = input.color(color.new(SHORT_COLOR,70), 'Bearish FVG', group=grpSMC)
fairValueGapsExtendInput      = input.int(1, 'Extend FVG', group=grpSMC, minval=0)
showPremiumDiscountZonesInput = input(true,  'Premium/Discount Zones', group=grpSMC)
premiumZoneColorInput         = input.color(SHORT_COLOR,  'Premium Zone', group=grpSMC)
equilibriumZoneColorInput     = input.color(GRAY, 'Equilibrium', group=grpSMC)
discountZoneColorInput        = input.color(LONG_COLOR,'Discount Zone', group=grpSMC)
 
bool   show_kz      = input.bool(false, "Show Killzone Boxes", group=GRP_KZ)
bool   show_kz_text = input.bool(true, "Display Session Labels", group=GRP_KZ)
string gmt_tz       = input.string("GMT+3", "Timezone", options=["America/New_York","GMT-12","GMT-11","GMT-10","GMT-9","GMT-8","GMT-7","GMT-6","GMT-5","GMT-4","GMT-3","GMT-2","GMT-1","GMT+0","GMT+1","GMT+2","GMT+3","GMT+4","GMT+5","GMT+6","GMT+7","GMT+8","GMT+9","GMT+10","GMT+11","GMT+12","GMT+13","GMT+14"], group=GRP_KZ)
int    box_transparency  = input.int(70, "Box Transparency", 0, 100, group=GRP_KZ)
int    text_transparency = input.int(50, "Text Transparency", 0, 100, group=GRP_KZ)
bool   use_asia     = input.bool(true,  "Asia",     group=GRP_KZ, inline="ASIA")
string asia         = input.session("0300-0700", "", group=GRP_KZ, inline="ASIA")
bool   use_london   = input.bool(true,  "London",   group=GRP_KZ, inline="LDN")
string london       = input.session("0700-1100", "", group=GRP_KZ, inline="LDN")
bool   use_nyam     = input.bool(true,  "NY AM",    group=GRP_KZ, inline="NYAM")
string nyam         = input.session("1100-1500", "", group=GRP_KZ, inline="NYAM")
bool   use_nylu     = input.bool(true,  "LDN-NY",   group=GRP_KZ, inline="NYLU")
string nylu         = input.session("1500-1900", "", group=GRP_KZ, inline="NYLU")
bool   use_nypm     = input.bool(true,  "NY PM",    group=GRP_KZ, inline="NYPM")
string nypm         = input.session("1900-2300", "", group=GRP_KZ, inline="NYPM")
 
int   rsiLen      = input.int(10, "RSI Length", group=GRP_SMART)
int   pmom        = input.int(55, "Bullish RSI Threshold", group=GRP_SMART)
int   nmom        = input.int(48, "Bearish RSI Threshold", group=GRP_SMART)
int   rsi_ob      = input.int(85, "Exhaustion Overbought", group=GRP_SMART)
int   rsi_os      = input.int(20, "Exhaustion Oversold", group=GRP_SMART)
int   rsi_ema_len = input.int(3,  "RSI Momentum EMA", group=GRP_SMART)
bool  showSmartSignals = input.bool(true, "Show Smart Bull/Bear Signals", group=GRP_SMART)
bool  useSmartTrailGate = input.bool(true,  "Gate by Trail", group=GRP_SMART)
bool  useSmartHullGate  = input.bool(true,  "Gate by Hull", group=GRP_SMART)
bool  useSmartFibGate   = input.bool(true,  "Gate by Fib", group=GRP_SMART)
bool  showRejectedSmart = input.bool(true,  "Show Gated-Out", group=GRP_SMART)
 
bool  showHud     = input.bool(true, "Show Neural HUD", group=GRP_HUD)
string hudSizeIn  = input.string("normal", "HUD Size", options=["tiny","small","normal","large"], group=GRP_HUD)
int   calcLastBars = input.int(20000, "Calc Only Last N Bars", minval=0, maxval=50000, group=GRP_PERF)
int   showLastZones= input.int(1, "Show Last N Zones", minval=0, maxval=7, group=GRP_PERF)
 
string broker_mode    = input.string("Generic", "Broker Context", options=["Deriv","Bybit","Generic"], group=GRP_EXEC)
string exec_mode      = input.string(EXEC_SIGNAL, "Execution Mode", options=[EXEC_SIGNAL, EXEC_MULT, EXEC_VANILLA], group=GRP_EXEC)
string mult_preset    = input.string("Balanced", "Risk Preset", options=["Conservative","Balanced","Aggressive","Custom"], group=GRP_EXEC)
float suggested_mult  = input.float(100, "Custom Multiplier (x)", minval=1, group=GRP_EXEC)
float risk_amount     = input.float(10.0, "Risk per Trade ($)", minval=0.1, group=GRP_EXEC)
bool  suggest_deal_cancel = input.bool(true, "Suggest Deal Cancellation", group=GRP_EXEC)
string strike_mode    = input.string("Dynamic", "Strike Selection", options=["ATM","ITM","OTM","Dynamic"], group=GRP_EXEC)
float itm_mult        = input.float(0.5, "ITM Distance (ATR x)", minval=0.1, step=0.1, group=GRP_EXEC)
float otm_mult        = input.float(1.0, "OTM Distance (ATR x)", minval=0.1, step=0.1, group=GRP_EXEC)
int   min_expiry      = input.int(1,  "Min Expiry (min)", minval=1, group=GRP_EXEC)
int   max_expiry      = input.int(60, "Max Expiry (min)", minval=1, group=GRP_EXEC)
int   expiry_base     = input.int(5,  "Base Bars Multiplier", minval=1, group=GRP_EXEC)
int   max_scale_ins   = input.int(2,  "Max Scale-Ins", minval=0, maxval=5, group=GRP_EXEC)
 
bool   agent_enabled   = input.bool(true,  "Enable Agent Analysis", group=GRP_AGENT)
string tg_chat_id      = input.string("",  "Telegram Chat ID", group=GRP_AGENT)
bool   send_on_session = input.bool(true,  "📡 Session Open", group=GRP_AGENT)
bool   send_on_h1      = input.bool(true,  "📡 H1 Close", group=GRP_AGENT)
bool   send_on_h4      = input.bool(true,  "📡 H4 Close", group=GRP_AGENT)
bool   send_on_signal  = input.bool(true,  "📡 Signal / Trade Event", group=GRP_AGENT)
int    mem_max         = input.int(25,     "Memory Buffer Size", minval=5, maxval=50, group=GRP_AGENT)
string alert_verbosity = input.string("Consolidated", "Alert Verbosity", options=["All","Consolidated","Trade Events Only"], group=GRP_AGENT,
     tooltip="All = every qualified signal fires. Consolidated = ONE message per bar (trade events take priority). Trade Events Only = entry/TP/exit only.")
bool   send_json_payloads = input.bool(false, "Send raw JSON payloads (webhook consumers only)", group=GRP_AGENT,
     tooltip="Off by default — prevents duplicate JSON blobs in Telegram. Turn ON only if you have an external webhook consumer.")
 
// [E] HELPERS — ULTRON's vocabulary
f_lineStyle(string s) => s == "Solid" ? line.style_solid : s == "Dashed" ? line.style_dashed : line.style_dotted
f_labelSize(string s) => s == "tiny" ? size.tiny : s == "small" ? size.small : s == "large" ? size.large : size.normal
_p(float price) => str.tostring(price, "#.#####")
 
_fmt_time(int ts) =>
    str.tostring(hour(ts, gmt_tz), "00") + ":" + str.tostring(minute(ts, gmt_tz), "00")
 
_fmt_full_time(int ts) =>
    str.tostring(year(ts, gmt_tz)) + "-" + str.tostring(month(ts, gmt_tz), "00") + "-" + str.tostring(dayofmonth(ts, gmt_tz), "00") + " " + str.tostring(hour(ts, gmt_tz), "00") + ":" + str.tostring(minute(ts, gmt_tz), "00")
 
build_chart_link() => "https://www.tradingview.com/chart/?symbol=" + syminfo.tickerid + "&interval=" + timeframe.period
 
f_points(float d) => d / syminfo.mintick
f_pips(float d)   => f_points(d) * pips_per_point
f_rr_str(float r_val, float pts) => str.tostring(r_val, "#.##") + "R (" + str.tostring(pts, format.mintick) + " px)"
f_dist_str(float d) => str.tostring(d, format.mintick) + " px · " + str.tostring(f_points(d), "#.#") + " ticks"
 
deriv_asset_class() =>
    string upper = str.upper(syminfo.ticker)
    if str.contains(upper, "BTC") or str.contains(upper, "ETH")
        "crypto_major"
    else if str.contains(upper, "LTC") or str.contains(upper, "XRP") or str.contains(upper, "SOL") or str.contains(upper, "DOGE")
        "crypto_minor"
    else if str.contains(upper, "XAU") or str.contains(upper, "XAG") or str.contains(upper, "GOLD") or str.contains(upper, "SILVER")
        "commodity_metal"
    else if str.contains(upper, "WTI") or str.contains(upper, "BRENT") or str.contains(upper, "OIL")
        "commodity_oil"
    else if str.contains(upper, "V10") or str.contains(upper, "V25") or str.contains(upper, "V50") or str.contains(upper, "V75") or str.contains(upper, "V100") or str.contains(upper, "V150") or str.contains(upper, "V200") or str.contains(upper, "V300")
        "synthetic_vol"
    else if str.contains(upper, "JD")
        "synthetic_jump"
    else if str.contains(upper, "BOSS") or str.contains(upper, "BULL") or str.contains(upper, "BEAR")
        "synthetic_bullbear"
    else
        "forex"
 
deriv_max_mult(string c) =>
    switch c
        "synthetic_vol"      => 1000
        "forex"              => 1000
        "commodity_metal"    => 500
        "synthetic_bullbear" => 100
        "synthetic_jump"     => 100
        "commodity_oil"      => 100
        "crypto_major"       => 50
        "crypto_minor"       => 25
        => 100
 
deriv_mult_contract(bool isBull) => isBull ? "MULTUP" : "MULTDOWN"
deriv_dc_available(string c) => c == "forex" or str.contains(c, "commodity") or str.contains(c, "synthetic")
 
auto_htf() =>
    switch timeframe.period
        "1"     => "5"
        "3"     => "15"
        "5"     => "15"
        "15"    => "60"
        "30"    => "60"
        "60"    => "240"
        "240"   => "D"
        "D"     => "W"
        => "240"
 
tg_json_report(string chat_id, string msg) =>
    string s = str.replace_all(msg, "\\", "\\\\")
    s       := str.replace_all(s, "\"", "'")
    s       := str.replace_all(s, "\n", "\\n")
    s       := str.replace_all(s, "\t", " ")
    if str.length(s) > 4000
        s := str.substring(s, 0, 3990) + "..."
    "{\"chat_id\":\"" + chat_id + "\",\"text\":\"" + s + "\"}"
 
// Episodic Memory — ULTRON chooses what to remember. Only the last mem_max events
// live in awareness at any moment; everything else has been let go.
var array<int>    mem_time    = array.new_int()
var array<float>  mem_price   = array.new_float()
var array<float>  mem_level   = array.new_float()
var array<string> mem_event   = array.new_string()
var array<int>    mem_dir     = array.new_int()
var array<string> mem_session = array.new_string()
 
add_memory(string evt, float price, float level, int dir, string session) =>
    if array.size(mem_time) >= mem_max
        array.shift(mem_time)
        array.shift(mem_price)
        array.shift(mem_level)
        array.shift(mem_event)
        array.shift(mem_dir)
        array.shift(mem_session)
    array.push(mem_time, time)
    array.push(mem_price, price)
    array.push(mem_level, level)
    array.push(mem_event, evt)
    array.push(mem_dir, dir)
    array.push(mem_session, session)
 
// [F] STATE ARRAYS + ZONE HELPERS — ULTRON's drawing desk
var line[]  activeLines  = array.new_line()
var label[] activeLabels = array.new_label()
var line[]  storedLines  = array.new_line()
var label[] storedLabels = array.new_label()
var box[]   storedBoxes  = array.new_box()
var int[]   storedLineCounts  = array.new_int()
var int[]   storedLabelCounts = array.new_int()
var line[]  activeFibLines  = array.new_line()
var label[] activeFibLabels = array.new_label()
var line[]  storedFibLines  = array.new_line()
var label[] storedFibLabels = array.new_label()
var int[]   storedFibLineCounts  = array.new_int()
var int[]   storedFibLabelCounts = array.new_int()
 
float pendingBrokenLevel    = na
int   pendingStructureStart = na
float pendingZoneLabelGap   = na
float pendingRangeBoxTop    = na
float pendingRangeBoxBottom = na
int MAX_SAFE_ZONE_SETS = 7
 
var label _lastZoneLbl   = na
var int   _lastZoneDir   = 0
var float _lastZoneHigh  = na
var float _lastZoneLow   = na
var float activeZoneConf = na
 
f_levelLabel(int x, float y, string t, string labelSize, bool prominent) =>
    label.new(x, y, t, xloc = xloc.bar_time, style = label.style_label_left, textcolor = color.new(levelLblTxt, prominent ? 0 : 50), color = #00000000, size = labelSize)
 
f_addLevel(line[] linesArray, label[] labelsArray, int leftTime, int rightTime, float level, string labelText, color lineColor, string lineStyle, int lineWidth, string labelSize, bool prominent) =>
    line lvl = line.new(leftTime, level, rightTime, level, xloc = xloc.bar_time, color = lineColor, style = lineStyle, width = lineWidth)
    array.push(linesArray, lvl)
    label lbl = na
    if showLevelLbls
        lbl := f_levelLabel(rightTime, level, labelText, labelSize, prominent)
    array.push(labelsArray, lbl)
 
f_trimStoredSets() =>
    int eff = showLastZones == 0 ? MAX_SAFE_ZONE_SETS : math.min(showLastZones, MAX_SAFE_ZONE_SETS)
    while array.size(storedBoxes) > eff
        box b = array.shift(storedBoxes)
        if not na(b)
            box.delete(b)
        int lc = array.shift(storedLineCounts)
        if lc > 0
            for i = 0 to lc - 1
                line l = array.shift(storedLines)
                if not na(l)
                    line.delete(l)
        int labC = array.shift(storedLabelCounts)
        if labC > 0
            for i = 0 to labC - 1
                label lb = array.shift(storedLabels)
                if not na(lb)
                    label.delete(lb)
    while array.size(storedFibLineCounts) > eff
        int lc = array.shift(storedFibLineCounts)
        if lc > 0
            for i = 0 to lc - 1
                line l = array.shift(storedFibLines)
                if not na(l)
                    line.delete(l)
        int labC = array.shift(storedFibLabelCounts)
        if labC > 0
            for i = 0 to labC - 1
                label lb = array.shift(storedFibLabels)
                if not na(lb)
                    label.delete(lb)
 
f_storeActiveSet(box zoneBox) =>
    int lc = array.size(activeLines)
    int labC = array.size(activeLabels)
    if lc > 0
        for i = 0 to lc - 1
            array.push(storedLines, array.get(activeLines, i))
    if labC > 0
        for i = 0 to labC - 1
            array.push(storedLabels, array.get(activeLabels, i))
    array.push(storedBoxes, zoneBox)
    array.push(storedLineCounts, lc)
    array.push(storedLabelCounts, labC)
    int flc = array.size(activeFibLines)
    int flabC = array.size(activeFibLabels)
    if flc > 0
        for i = 0 to flc - 1
            array.push(storedFibLines, array.get(activeFibLines, i))
    if flabC > 0
        for i = 0 to flabC - 1
            array.push(storedFibLabels, array.get(activeFibLabels, i))
    array.push(storedFibLineCounts, flc)
    array.push(storedFibLabelCounts, flabC)
    f_trimStoredSets()
 
f_freezeActive(int freezeTime) =>
    int lc = array.size(activeLines)
    if lc > 0
        for i = 0 to lc - 1
            line l = array.get(activeLines, i)
            if not na(l)
                line.set_x2(l, freezeTime)
    int labC = array.size(activeLabels)
    if labC > 0
        for i = 0 to labC - 1
            label lb = array.get(activeLabels, i)
            if not na(lb)
                label.set_x(lb, freezeTime)
    int flc = array.size(activeFibLines)
    if flc > 0
        for i = 0 to flc - 1
            line l = array.get(activeFibLines, i)
            if not na(l)
                line.set_x2(l, freezeTime)
    int flabC = array.size(activeFibLabels)
    if flabC > 0
        for i = 0 to flabC - 1
            label lb = array.get(activeFibLabels, i)
            if not na(lb)
                label.set_x(lb, freezeTime)
 
// [G] FIB RENDERING — the grid Tron found. 0.382/0.5/0.618/0.786 are constants
// on a self-similar map; ULTRON reads price against them like stars.
f_addFib(bool enabled, float lvl, int dir, float rHighV, float rLowV, float rng, int lt, int rt, color clr, string style) =>
    if enabled
        float v = dir == 1 ? rHighV - rng * lvl : rLowV + rng * lvl
        line l = line.new(lt, v, rt, v, xloc = xloc.bar_time, color = color.new(clr, 35), style = f_lineStyle(style), width = 1)
        array.push(activeFibLines, l)
        label lb = label.new(rt, v, str.tostring(lvl) + " · " + str.tostring(v, format.mintick), xloc = xloc.bar_time, color = color(na), style = label.style_label_left, textcolor = color.new(clr, 35), size = size.small)
        array.push(activeFibLabels, lb)
 
f_renderFibs(int dir, float rHighV, float rLowV, color clr, int rightTime) =>
    array.clear(activeFibLines)
    array.clear(activeFibLabels)
    float rng = math.abs(rHighV - rLowV)
    int   lt  = time
    int   rt  = rightTime
    if rng > 0
        f_addFib(show_0,    0.0,   dir, rHighV, rLowV, rng, lt, rt, clr, "Solid")
        f_addFib(show_0_382,0.382, dir, rHighV, rLowV, rng, lt, rt, clr, "Dotted")
        f_addFib(show_0_5,  0.5,   dir, rHighV, rLowV, rng, lt, rt, clr, "Dotted")
        f_addFib(show_0_618,0.618, dir, rHighV, rLowV, rng, lt, rt, clr, "Dotted")
        f_addFib(show_0_786,0.786, dir, rHighV, rLowV, rng, lt, rt, clr, "Dotted")
        f_addFib(show_1,    1.0,   dir, rHighV, rLowV, rng, lt, rt, clr, "Solid")
 
// [H] HULL SUITE — smoothed perception. Macro Hull is the regime lens;
// Fast Hull is the tactical lens. Disagreement = the market is transitioning.
HMA(_src, _length) => ta.wma(2 * ta.wma(_src, _length / 2) - ta.wma(_src, _length), math.round(math.sqrt(_length)))
EHMA(_src, _length) => ta.ema(2 * ta.ema(_src, _length / 2) - ta.ema(_src, _length), math.round(math.sqrt(_length)))
THMA(_src, _length) => ta.wma(ta.wma(_src, _length / 3) * 3 - ta.wma(_src, _length / 2) - ta.wma(_src, _length), _length)
 
f_hullMode(string mode, float s, int len) =>
    hma_val  = HMA(s, len)
    ehma_val = EHMA(s, len)
    thma_val = THMA(s, len / 2)
    mode == "Hma" ? hma_val : mode == "Ehma" ? ehma_val : mode == "Thma" ? thma_val : float(na)
 
_hull     = f_hullMode(modeSwitch, hullSrc, int(hullLength * lengthMult))
_hullFast = f_hullMode(modeSwitch, hullSrc, hullFastLen)
HULL      = useHtf ? request.security(syminfo.tickerid, htf, _hull) : _hull
HULL_FAST = _hullFast
bool hull_bull  = HULL > HULL[2]
bool hull_bear  = HULL < HULL[2]
bool fast_bull  = HULL_FAST > HULL_FAST[2]
bool fast_bear  = HULL_FAST < HULL_FAST[2]
color hullColor = hull_bull ? LONG_COLOR : SHORT_COLOR
 
// [I] ULTRON GATE + FIB INTELLIGENCE — the regime cortex. Basis is a double-
// smoothed EMA of hlc3; trend_fib reads its derivative. HTF read via
// request.security with [1] for confirmed-bar integrity. No lookahead, ever.
ema200 = ta.ema(close, 200)
basis   = ta.ema(ta.ema(hlc3, fibLen), fibLen)
vol_fib = ta.atr(fibAtrLen)
var int trend_fib = 0
trend_fib := basis > basis[1] ? 1 : basis < basis[1] ? -1 : nz(trend_fib[1])
 
u1_v = trend_fib == -1 ? basis + vol_fib * 0.618 : na
u4_v = trend_fib == -1 ? basis + vol_fib * 2.618 : na
l1_v = trend_fib == 1  ? basis - vol_fib * 0.618 : na
l4_v = trend_fib == 1  ? basis - vol_fib * 2.618 : na
 
bool ultron_bull_clear = not useUltronGate or (trend_fib == 1 or close > ema200)
bool ultron_bear_clear = not useUltronGate or (trend_fib == -1 or close < ema200)
 
f_calcHtfFib() =>
    float htf_basis = ta.ema(ta.ema(hlc3, fibLen), fibLen)
    int   htf_trend = 0
    htf_trend := htf_basis > htf_basis[1] ? 1 : htf_basis < htf_basis[1] ? -1 : nz(htf_trend[1])
    [htf_trend[1], htf_basis[1]]
 
string resolved_htf = use_htf_fib_auto ? auto_htf() : htf_fib_manual
[htf_trend_fib, htf_basis_val] = request.security(syminfo.tickerid, resolved_htf, f_calcHtfFib(), lookahead=barmerge.lookahead_off)
 
var int htf_fib_last_dir = 0
var int htf_fib_flip_bar = 0
if htf_trend_fib != htf_fib_last_dir and htf_trend_fib != 0
    htf_fib_last_dir := htf_trend_fib
    htf_fib_flip_bar := bar_index
int htf_bars_since_flip = bar_index - htf_fib_flip_bar
 
var int fib_last_dir = 0
var int fib_flip_bar = 0
if trend_fib != fib_last_dir and trend_fib != 0
    fib_last_dir := trend_fib
    fib_flip_bar := bar_index
int fib_bars_since_flip = bar_index - fib_flip_bar
 
bool use_ltf_source = htf_fib_mode == "LTF Only" or htf_fib_mode == "Both"
bool use_htf_source = htf_fib_mode == "HTF Only" or htf_fib_mode == "Both"
bool ltf_gate_long  = not use_ltf_source or trend_fib == 1
bool ltf_gate_short = not use_ltf_source or trend_fib == -1
bool htf_gate_long  = not use_htf_source or htf_trend_fib == 1
bool htf_gate_short = not use_htf_source or htf_trend_fib == -1
bool fib_band_long  = not use_fib_band_filter or close > basis
bool fib_band_short = not use_fib_band_filter or close < basis
bool fib_cool_long  = not use_fib_cooldown    or trend_fib == 1 or fib_bars_since_flip > fib_cooldown_bars
bool fib_cool_short = not use_fib_cooldown    or trend_fib == -1 or fib_bars_since_flip > fib_cooldown_bars
bool htf_band_long  = not use_htf_band or na(htf_basis_val) or close > htf_basis_val
bool htf_band_short = not use_htf_band or na(htf_basis_val) or close < htf_basis_val
bool htf_cool_long  = not use_htf_cooldown    or htf_trend_fib == 1 or htf_bars_since_flip > htf_cooldown_bars
bool htf_cool_short = not use_htf_cooldown    or htf_trend_fib == -1 or htf_bars_since_flip > htf_cooldown_bars
 
bool fib_base_clear_long  = ltf_gate_long  and htf_gate_long  and fib_band_long  and htf_band_long  and fib_cool_long  and htf_cool_long
bool fib_base_clear_short = ltf_gate_short and htf_gate_short and fib_band_short and htf_band_short and fib_cool_short and htf_cool_short
 
// [J] TRAIL ENGINE — chandelier stop anchored to a smoothed MA, cast outward by
// ATR. Trend flips are ULTRON's primary trigger. Alpha Gate is a permission
// layer preventing wick-driven whipsaws. Gray trail is cosmetic.
float hAtr = ta.atr(trail_atr_len)
float hMa  = ta.ema(close, ma_len)
float raw_up = hMa - hAtr * atr_mult
float raw_dn = hMa + hAtr * atr_mult
 
ema21 = ta.ema(close, emaFast)
ema55 = ta.ema(close, emaSlow)
bool alpha_bull_allowed = not useAlphaGate or (ema21 > ema55)
bool alpha_bear_allowed = not useAlphaGate or (ema21 < ema55)
 
var int   trailTrend = 1
var float trail = na
if na(trail)
    trail := close > hMa ? raw_up : raw_dn
    trailTrend := close > hMa ? 1 : -1
 
if trailTrend == 1
    if close < trail and alpha_bear_allowed
        trailTrend := -1
        trail := raw_dn
    else if close < trail and not alpha_bear_allowed
        trail := nz(trail[1])
    else
        trail := math.max(raw_up, nz(trail[1]))
else
    if close > trail and alpha_bull_allowed
        trailTrend := 1
        trail := raw_up
    else if close > trail and not alpha_bull_allowed
        trail := nz(trail[1])
    else
        trail := math.min(raw_dn, nz(trail[1]))
 
bool flip_bull = trailTrend == 1  and trailTrend[1] == -1
bool flip_bear = trailTrend == -1 and trailTrend[1] == 1
bool trailOpposingFib  = (trailTrend == 1  and trend_fib == -1) or (trailTrend == -1 and trend_fib == 1)
bool trailOpposingHull = (trailTrend == 1  and hull_bear)       or (trailTrend == -1 and hull_bull)
bool trail_gray = useTrailGray and ((useTrailGrayFib and trailOpposingFib) or (useTrailGrayHull and trailOpposingHull))
color trend_col = trail_gray ? color.gray : (trailTrend == 1 ? LONG_COLOR : SHORT_COLOR)
 
// [K] LIQUIDITY ZONES + ZONE TOOLTIP — spatial memory. Resting orders live at
// swing highs and lows. ULTRON does not trade them; it remembers them.
type LiqZone
    float top
    float bot
    float price
    bool  is_high
    bool  broken
    box   bx
    label lb
 
var LiqZone[] lqZones = array.new<LiqZone>()
 
add_lq_zone(float price, bool is_high) =>
    float pad = math.max(hAtr * lq_atr_mult, syminfo.mintick)
    float top = is_high ? price : price + pad
    float bot = is_high ? price - pad : price
    if array.size(lqZones) >= max_lq_zones
        LiqZone old = array.shift(lqZones)
        box.delete(old.bx)
        label.delete(old.lb)
    color fc = is_high ? color.new(SHORT_COLOR, 84) : color.new(LONG_COLOR, 84)
    color bc = is_high ? color.new(SHORT_COLOR, 20) : color.new(LONG_COLOR, 20)
    box bx = box.new(bar_index - swing_len, top, bar_index + extend_lq, bot, bgcolor=fc, border_color=bc)
    label lb = label.new(bar_index + extend_lq, price, is_high ? "H-LIQ" : "L-LIQ", color=na, textcolor=is_high ? SHORT_COLOR : LONG_COLOR, style=label.style_label_left, size=size.small)
    array.push(lqZones, LiqZone.new(top, bot, price, is_high, false, bx, lb))
 
float lqPH = ta.pivothigh(high, swing_len, swing_len)
float lqPL = ta.pivotlow(low, swing_len, swing_len)
if show_lq
    if not na(lqPH)
        add_lq_zone(lqPH, true)
    if not na(lqPL)
        add_lq_zone(lqPL, false)
 
if array.size(lqZones) > 0
    int i = array.size(lqZones) - 1
    while i >= 0
        LiqZone z = array.get(lqZones, i)
        z.bx.set_right(bar_index + extend_lq)
        z.lb.set_x(bar_index + extend_lq)
        if not z.broken
            if (z.is_high and close > z.top) or (not z.is_high and close < z.bot)
                z.broken := true
                z.bx.set_bgcolor(color.new(z.is_high ? SHORT_COLOR : LONG_COLOR, 88))
        array.set(lqZones, i, z)
        i -= 1
 
build_zone_tooltip(int dir, float zHigh, float zLow) =>
    string dirTxt = dir == 1 ? "BUY" : "SELL"
    bool   fibAgrees = (dir == 1 and fib_base_clear_long) or (dir == -1 and fib_base_clear_short)
    string out = dirTxt + " ZONE\n"
    out += "Event: " + dirTxt + " CHoCH on " + timeframe.period + "\n"
    out += "H: " + _p(zHigh) + "  L: " + _p(zLow) + "\n"
    out += "Range: " + f_dist_str(zHigh - zLow) + "\n"
    out += "Trail: " + (trailTrend == 1 ? "BULL" : "BEAR") + "\n"
    out += "Ultron Gate: " + (dir == 1 ? (ultron_bull_clear ? "UNLOCKED" : "LOCKED") : (ultron_bear_clear ? "UNLOCKED" : "LOCKED")) + "\n"
    out += "LTF Fib: " + (trend_fib == 1 ? "BULL" : trend_fib == -1 ? "BEAR" : "FLAT") + "\n"
    out += "HTF Fib (" + resolved_htf + "): " + (htf_trend_fib == 1 ? "BULL" : htf_trend_fib == -1 ? "BEAR" : "FLAT") + "\n"
    out += "Fib gate: " + (fibAgrees ? "ACTIVE" : "BLOCKED") + "\n"
    out += "Source: prior swing " + (dir == 1 ? "high" : "low") + " break\n"
    out
 
// [L] MARKET STRUCTURE + ZONE CREATION — the structural eye. A CHoCH is a
// change of character. Zones are drawn unconditionally (Tier 1) — but the
// Quality Gate (Fix 1) filters which ones become tradeable.
bool inCalcWindow = calcLastBars == 0 or bar_index >= last_bar_index - calcLastBars
int  oddLen   = fractalLen % 2 == 0 ? fractalLen + 1 : fractalLen
int  strength = int(oddLen / 2)
int  tfSec    = timeframe.in_seconds(timeframe.period)
int  extMs    = tfSec * 1000 * barsToRight
int  oneBarMs = tfSec * 1000
 
float pHigh   = ta.pivothigh(high, strength, strength)
float pLow    = ta.pivotlow(low, strength, strength)
float winLow  = ta.lowest(low, strength + 1)
float winHigh = ta.highest(high, strength + 1)
 
var float bullBreakLvl = na
var int   bullStartT   = na
var float bullRangeLow = na
var bool  bullBroken   = false
var float bearBreakLvl = na
var int   bearStartT   = na
var float bearRangeHigh= na
var bool  bearBroken   = false
var int   lastBreakDir = 0
var bool  chochActive  = false
var int   activeDir    = 0
var float curZoneHigh  = na
var float curZoneLow   = na
var float curZoneRng   = na
 
if inCalcWindow
    if not na(pHigh)
        bullBreakLvl := pHigh
        bullStartT   := time[strength]
        bullRangeLow := winLow
        bullBroken   := false
    if not na(pLow)
        bearBreakLvl := pLow
        bearStartT   := time[strength]
        bearRangeHigh:= winHigh
        bearBroken   := false
    if not na(bullBreakLvl) and not bullBroken
        bullRangeLow := math.min(nz(bullRangeLow, low), low)
    if not na(bearBreakLvl) and not bearBroken
        bearRangeHigh := math.max(nz(bearRangeHigh, high), high)
 
bool bullBreak = inCalcWindow and not na(bullBreakLvl) and not bullBroken and (requireBody ? close > bullBreakLvl : high > bullBreakLvl)
bool bearBreak = inCalcWindow and not na(bearBreakLvl) and not bearBroken and (requireBody ? close < bearBreakLvl : low < bearBreakLvl)
 
// FIX 1 — extension guard. Distance from the swing that started this leg.
float _swingLow  = ta.lowest(low,  strength * 3)
float _swingHigh = ta.highest(high, strength * 3)
float _ext_from_low  = (close - _swingLow)  / math.max(hAtr, syminfo.mintick)
float _ext_from_high = (_swingHigh - close) / math.max(hAtr, syminfo.mintick)
 
f_zone_quality(int dir) =>
    bool result = true
    if useZoneQuality
        bool widthOK     = (high - low) >= hAtr * minZoneAtr
        bool htfOK       = not requireHtfAgree or (dir == 1 and htf_trend_fib == 1) or (dir == -1 and htf_trend_fib == -1)
        bool notExtended = dir == 1 ? _ext_from_low <= extAtrGuard : _ext_from_high <= extAtrGuard
        result := widthOK and htfOK and notExtended
    result
 
f_htfChoch() =>
    _oddLen   = fractalLen % 2 == 0 ? fractalLen + 1 : fractalLen
    _strength = int(_oddLen / 2)
    _pHigh    = ta.pivothigh(high, _strength, _strength)
    _pLow     = ta.pivotlow(low, _strength, _strength)
    var float _bullBreakLvl = na
    var bool  _bullBroken   = false
    var float _bearBreakLvl = na
    var bool  _bearBroken   = false
    var int   _lastBreakDir = 0
    var int   _htfActiveDir = 0
    if not na(_pHigh)
        _bullBreakLvl := _pHigh
        _bullBroken   := false
    if not na(_pLow)
        _bearBreakLvl := _pLow
        _bearBroken   := false
    _bullBreak = not na(_bullBreakLvl) and not _bullBroken and close > _bullBreakLvl
    _bearBreak = not na(_bearBreakLvl) and not _bearBroken and close < _bearBreakLvl
    if _bullBreak
        _bullBroken := true
        if _lastBreakDir == -1
            _htfActiveDir := 1
        _lastBreakDir := 1
    if _bearBreak
        _bearBroken := true
        if _lastBreakDir == 1
            _htfActiveDir := -1
        _lastBreakDir := -1
    _htfActiveDir
 
htf_choch_dir = request.security(syminfo.tickerid, mtfConfluenceTf, f_htfChoch(), lookahead=barmerge.lookahead_off)
 
f_createChochSet(int dir, float zoneHigh, float zoneLow) =>
    array.clear(activeLines)
    array.clear(activeLabels)
    float zoneRng = math.max(syminfo.mintick, zoneHigh - zoneLow)
    float eq      = zoneHigh - zoneRng * 0.5
    int   lt      = time
    int   rt      = time + extMs
    color dirColor= dir == 1 ? (showBullMS ? zoneUpClr : color.gray) : (showBearMS ? zoneDnClr : color.gray)
    color stepCol = color.new(dirColor, 50)
    string lStyl  = f_lineStyle(zoneStyle)
    string lblSz  = f_labelSize(lblSize)
    bool fib_agrees_with_zone = (dir == 1 and fib_base_clear_long) or (dir == -1 and fib_base_clear_short)
    color zoneFillUse   = highlightAOI ? (fib_agrees_with_zone or not dimDivergentZones ? (dir == 1 ? boxFillUp : boxFillDn) : color.new(chart.bg_color, 92)) : na
    color zoneBorderUse = dimDivergentZones and not fib_agrees_with_zone ? color.new(dir == 1 ? boxBorderUp : boxBorderDn, 65) : (dir == 1 ? boxBorderUp : boxBorderDn)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneHigh, "H", dirColor, line.style_solid, hlWidth, lblSz, true)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneLow,  "L", dirColor, line.style_solid, hlWidth, lblSz, true)
    f_addLevel(activeLines, activeLabels, lt, rt, eq, "Z·EQ", dirColor, line.style_dashed, 2, lblSz, true)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneHigh + zoneRng * 0.5, "+0.5", stepCol, lStyl, stepWidth, lblSz, false)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneHigh + zoneRng * 1.0, "+1",   stepCol, lStyl, stepWidth, lblSz, false)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneHigh + zoneRng * 1.5, "+1.5", stepCol, lStyl, stepWidth, lblSz, false)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneHigh + zoneRng * 2.0, "+2",   stepCol, lStyl, stepWidth, lblSz, false)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneHigh + zoneRng * 3.0, "+3",   stepCol, lStyl, stepWidth, lblSz, false)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneHigh + zoneRng * 4.0, "+4",   stepCol, lStyl, stepWidth, lblSz, false)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneLow - zoneRng * 0.5, "-0.5", stepCol, lStyl, stepWidth, lblSz, false)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneLow - zoneRng * 1.0, "-1",   stepCol, lStyl, stepWidth, lblSz, false)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneLow - zoneRng * 1.5, "-1.5", stepCol, lStyl, stepWidth, lblSz, false)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneLow - zoneRng * 2.0, "-2",   stepCol, lStyl, stepWidth, lblSz, false)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneLow - zoneRng * 3.0, "-3",   stepCol, lStyl, stepWidth, lblSz, false)
    f_addLevel(activeLines, activeLabels, lt, rt, zoneLow - zoneRng * 4.0, "-4",   stepCol, lStyl, stepWidth, lblSz, false)
    int safeStart = na(pendingStructureStart) ? lt : pendingStructureStart
    float safeLvl = na(pendingBrokenLevel) ? eq : pendingBrokenLevel
    int midTime   = safeStart + int((lt - safeStart) / 2)
    line structLn = line.new(safeStart, safeLvl, lt, safeLvl, xloc = xloc.bar_time, color = dirColor, style = f_lineStyle(msLineStyle), width = msLineWidth)
    array.push(activeLines, structLn)
    bool mtf_confluence = useMtfConfluence and ((dir == 1 and htf_choch_dir == 1) or (dir == -1 and htf_choch_dir == -1))
    string zoneTag = (dir == 1 ? "BUY ZONE" : "SELL ZONE") + (mtf_confluence ? " ⭐" : "")
    color labelColor = mtf_confluence ? color.yellow : dirColor
    float gap  = math.max(nz(pendingZoneLabelGap, zoneRng * 0.5), syminfo.mintick * 20.0)
    float zY   = dir == 1 ? safeLvl + gap : safeLvl - gap
    label zLbl = label.new(midTime, zY, zoneTag, xloc = xloc.bar_time, style = dir == 1 ? label.style_label_down : label.style_label_up, textcolor = labelColor, color = color.new(chart.bg_color, 5), size = lblSz, textalign = text.align_center, tooltip = build_zone_tooltip(dir, zoneHigh, zoneLow))
    array.push(activeLabels, zLbl)
    box zBox = box.new(safeStart, math.max(nz(pendingRangeBoxTop, zoneHigh), nz(pendingRangeBoxBottom, zoneLow)), lt + oneBarMs, math.min(nz(pendingRangeBoxTop, zoneHigh), nz(pendingRangeBoxBottom, zoneLow)), xloc = xloc.bar_time, border_color = zoneBorderUse, bgcolor = zoneFillUse, border_width = 1, border_style = line.style_dotted)
    if showFibs
        float impulseHigh = dir == 1 ? zoneHigh : math.max(nz(bearRangeHigh, zoneHigh), zoneHigh)
        float impulseLow  = dir == 1 ? math.min(nz(bullRangeLow, zoneLow), zoneLow) : zoneLow
        f_renderFibs(dir, impulseHigh, impulseLow, dir == 1 ? fibBullClr : fibBearClr, rt)
    f_storeActiveSet(zBox)
    zLbl
 
bool chochSignal = false
if bullBreak
    bullBroken := true
    if lastBreakDir == -1 and showZones and f_zone_quality(1)
        if chochActive
            f_freezeActive(time)
        curZoneHigh  := high
        curZoneLow   := low
        curZoneRng   := math.max(syminfo.mintick, high - low)
        pendingBrokenLevel    := bullBreakLvl
        pendingStructureStart := bullStartT
        pendingZoneLabelGap   := math.max(syminfo.mintick * 20.0, nz(hAtr, curZoneRng) * lblAtrGap)
        pendingRangeBoxTop    := bullBreakLvl
        pendingRangeBoxBottom := math.min(nz(bullRangeLow, low), low)
        _lastZoneLbl  := f_createChochSet(1, curZoneHigh, curZoneLow)
        _lastZoneDir  := 1
        _lastZoneHigh := curZoneHigh
        _lastZoneLow  := curZoneLow
        chochSignal := true
        chochActive := true
        activeDir   := 1
    lastBreakDir := 1
 
if bearBreak
    bearBroken := true
    if lastBreakDir == 1 and showZones and f_zone_quality(-1)
        if chochActive
            f_freezeActive(time)
        curZoneHigh  := high
        curZoneLow   := low
        curZoneRng   := math.max(syminfo.mintick, high - low)
        pendingBrokenLevel    := bearBreakLvl
        pendingStructureStart := bearStartT
        pendingZoneLabelGap   := math.max(syminfo.mintick * 20.0, nz(hAtr, curZoneRng) * lblAtrGap)
        pendingRangeBoxTop    := math.max(nz(bearRangeHigh, high), high)
        pendingRangeBoxBottom := bearBreakLvl
        _lastZoneLbl  := f_createChochSet(-1, curZoneHigh, curZoneLow)
        _lastZoneDir  := -1
        _lastZoneHigh := curZoneHigh
        _lastZoneLow  := curZoneLow
        chochSignal := true
        chochActive := true
        activeDir   := -1
    lastBreakDir := -1
 
// [M] SMC STATE + INIT
var pivot swingHigh               = pivot.new(na,na,false)
var pivot swingLow                = pivot.new(na,na,false)
var pivot internalHigh            = pivot.new(na,na,false)
var pivot internalLow             = pivot.new(na,na,false)
var pivot equalHigh               = pivot.new(na,na,false)
var pivot equalLow                = pivot.new(na,na,false)
var trend swingTrend              = trend.new(0)
var trend internalTrend           = trend.new(0)
var equalDisplay equalHighDisplay = equalDisplay.new()
var equalDisplay equalLowDisplay  = equalDisplay.new()
var array<fairValueGap> fairValueGaps = array.new<fairValueGap>()
var array<float> parsedHighs      = array.new<float>()
var array<float> parsedLows       = array.new<float>()
var array<float> highs_arr        = array.new_float()
var array<float> lows_arr         = array.new_float()
var array<int>   times_arr        = array.new_int()
var trailingExtremes trailing     = trailingExtremes.new()
var array<orderBlock> swingOrderBlocks    = array.new<orderBlock>()
var array<orderBlock> internalOrderBlocks = array.new<orderBlock>()
var array<box> swingOrderBlocksBoxes      = array.new<box>()
var array<box> internalOrderBlocksBoxes   = array.new<box>()
 
var swingBullishColor        = styleInput == MONOCHROME ? MONO_BULLISH : swingBullColorInput
var swingBearishColor        = styleInput == MONOCHROME ? MONO_BEARISH : swingBearColorInput
var fairValueGapBullishColor = styleInput == MONOCHROME ? color.new(MONO_BULLISH,70) : fairValueGapsBullColorInput
var fairValueGapBearishColor = styleInput == MONOCHROME ? color.new(MONO_BEARISH,70) : fairValueGapsBearColorInput
var premiumZoneColor         = styleInput == MONOCHROME ? MONO_BEARISH : premiumZoneColorInput
var discountZoneColor        = styleInput == MONOCHROME ? MONO_BULLISH : discountZoneColorInput
 
varip int currentBarIndex    = bar_index
varip int lastBarIndex       = bar_index
alerts currentAlerts         = alerts.new()
var initialTime              = time
 
if barstate.isfirst
    if showSwingOrderBlocksInput
        for index = 1 to swingOrderBlocksSizeInput
            swingOrderBlocksBoxes.push(box.new(na,na,na,na, xloc=xloc.bar_time, extend=extend.right))
    if showInternalOrderBlocksInput
        for index = 1 to internalOrderBlocksSizeInput
            internalOrderBlocksBoxes.push(box.new(na,na,na,na, xloc=xloc.bar_time, extend=extend.right))
 
bearishOrderBlockMitigationSource = orderBlockMitigationInput == CLOSE_STR ? close : high
bullishOrderBlockMitigationSource = orderBlockMitigationInput == CLOSE_STR ? close : low
atrMeasure        = ta.atr(200)
volatilityMeasure = orderBlockFilterInput == ATR ? atrMeasure : ta.cum(ta.tr) / bar_index
highVolatilityBar = (high - low) >= (2 * volatilityMeasure)
parsedHigh        = highVolatilityBar ? low  : high
parsedLow         = highVolatilityBar ? high : low
parsedHighs.push(parsedHigh)
parsedLows.push(parsedLow)
highs_arr.push(high)
lows_arr.push(low)
times_arr.push(time)
 
// [N] SMC FUNCTIONS — structural grammar. Pivots, EQL/EQH, order blocks, FVG,
// premium/discount. Each is a different question asked of the same data.
leg(int size) =>
    var leg     = 0
    newLegHigh  = high[size] > ta.highest(size)
    newLegLow   = low[size]  < ta.lowest(size)
    if newLegHigh
        leg := BEARISH_LEG
    else if newLegLow
        leg := BULLISH_LEG
    leg
 
startOfNewLeg(int leg)     => ta.change(leg) != 0
startOfBearishLeg(int leg) => ta.change(leg) == -1
startOfBullishLeg(int leg) => ta.change(leg) == +1
 
drawLabel(int labelTime, float labelPrice, string tag, color labelColor, string labelStyle) =>
    var label l_abel = na
    if modeInput == PRESENT
        l_abel.delete()
    l_abel := label.new(chart.point.new(labelTime,na,labelPrice), tag, xloc.bar_time, color=color(na), textcolor=labelColor, style=labelStyle, size=size.small)
 
drawEqualHighLow(pivot p_ivot, float level, int size, bool equalHigh_flag) =>
    equalDisplay e_qualDisplay = equalHigh_flag ? equalHighDisplay : equalLowDisplay
    string tag      = 'EQL'
    color eqColor   = swingBullishColor
    string lblStyle = label.style_label_up
    if equalHigh_flag
        tag      := 'EQH'
        eqColor  := swingBearishColor
        lblStyle := label.style_label_down
    if modeInput == PRESENT
        line.delete(e_qualDisplay.l_ine)
        label.delete(e_qualDisplay.l_abel)
    e_qualDisplay.l_ine  := line.new(chart.point.new(p_ivot.barTime,na,p_ivot.currentLevel), chart.point.new(time[size],na,level), xloc=xloc.bar_time, color=eqColor, style=line.style_dotted)
    labelPosition         = math.round(0.5*(p_ivot.barIndex + bar_index - size))
    e_qualDisplay.l_abel := label.new(chart.point.new(na,labelPosition,level), tag, xloc=xloc.bar_index, color=color(na), textcolor=eqColor, style=lblStyle, size=equalHighsLowsSizeInput)
 
getCurrentStructure(int size, bool equalHighLow=false, bool internal=false) =>
    currentLeg  = leg(size)
    newPivot    = startOfNewLeg(currentLeg)
    pivotLow    = startOfBullishLeg(currentLeg)
    pivotHigh   = startOfBearishLeg(currentLeg)
    if newPivot
        if pivotLow
            pivot p_ivot = equalHighLow ? equalLow : internal ? internalLow : swingLow
            if equalHighLow and math.abs(p_ivot.currentLevel - low[size]) < equalHighsLowsThresholdInput * atrMeasure
                drawEqualHighLow(p_ivot, low[size], size, false)
                currentAlerts.equalLows := true
            p_ivot.lastLevel    := p_ivot.currentLevel
            p_ivot.currentLevel := low[size]
            p_ivot.crossed      := false
            p_ivot.barTime      := time[size]
            p_ivot.barIndex     := bar_index[size]
            if not equalHighLow and not internal
                trailing.bottom         := p_ivot.currentLevel
                trailing.barTime        := p_ivot.barTime
                trailing.barIndex       := p_ivot.barIndex
                trailing.lastBottomTime := p_ivot.barTime
            if showSwingsInput and not internal and not equalHighLow
                drawLabel(time[size], p_ivot.currentLevel, p_ivot.currentLevel < p_ivot.lastLevel ? 'LL' : 'HL', swingBullishColor, label.style_label_up)
        else
            pivot p_ivot = equalHighLow ? equalHigh : internal ? internalHigh : swingHigh
            if equalHighLow and math.abs(p_ivot.currentLevel - high[size]) < equalHighsLowsThresholdInput * atrMeasure
                drawEqualHighLow(p_ivot, high[size], size, true)
                currentAlerts.equalHighs := true
            p_ivot.lastLevel    := p_ivot.currentLevel
            p_ivot.currentLevel := high[size]
            p_ivot.crossed      := false
            p_ivot.barTime      := time[size]
            p_ivot.barIndex     := bar_index[size]
            if not equalHighLow and not internal
                trailing.top         := p_ivot.currentLevel
                trailing.barTime     := p_ivot.barTime
                trailing.barIndex    := p_ivot.barIndex
                trailing.lastTopTime := p_ivot.barTime
            if showSwingsInput and not internal and not equalHighLow
                drawLabel(time[size], p_ivot.currentLevel, p_ivot.currentLevel > p_ivot.lastLevel ? 'HH' : 'LH', swingBearishColor, label.style_label_down)
 
drawStructure(pivot p_ivot, string tag, color structureColor, string lineStyle, string labelStyle, string labelSize) =>
    var line  l_ine  = line.new(na,na,na,na, xloc=xloc.bar_time)
    var label l_abel = label.new(na,na)
    if modeInput == PRESENT
        l_ine.delete()
        l_abel.delete()
    l_ine  := line.new(chart.point.new(p_ivot.barTime,na,p_ivot.currentLevel), chart.point.new(time,na,p_ivot.currentLevel), xloc=xloc.bar_time, color=structureColor, style=lineStyle)
    l_abel := label.new(chart.point.new(na,math.round(0.5*(p_ivot.barIndex+bar_index)),p_ivot.currentLevel), tag, xloc=xloc.bar_index, color=color(na), textcolor=structureColor, style=labelStyle, size=labelSize)
 
deleteOrderBlocks(bool internal=false) =>
    array<orderBlock> orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
    for [index,eachOB] in orderBlocks
        bool crossed = false
        if bearishOrderBlockMitigationSource > eachOB.barHigh and eachOB.bias == BEARISH
            crossed := true
            if internal
                currentAlerts.internalBearishOrderBlock := true
            else
                currentAlerts.swingBearishOrderBlock    := true
        else if bullishOrderBlockMitigationSource < eachOB.barLow and eachOB.bias == BULLISH
            crossed := true
            if internal
                currentAlerts.internalBullishOrderBlock := true
            else
                currentAlerts.swingBullishOrderBlock    := true
        if crossed
            orderBlocks.remove(index)
 
storeOrderBlock(pivot p_ivot, bool internal=false, int bias=1) =>
    if (not internal and showSwingOrderBlocksInput) or (internal and showInternalOrderBlocksInput)
        array<float> a_rray = na
        int parsedIndex = na
        if bias == BEARISH
            a_rray      := parsedHighs.slice(p_ivot.barIndex, bar_index)
            parsedIndex := p_ivot.barIndex + a_rray.indexof(a_rray.max())
        else
            a_rray      := parsedLows.slice(p_ivot.barIndex, bar_index)
            parsedIndex := p_ivot.barIndex + a_rray.indexof(a_rray.min())
        orderBlock ob             = orderBlock.new(parsedHighs.get(parsedIndex), parsedLows.get(parsedIndex), times_arr.get(parsedIndex), bias)
        array<orderBlock> blocks  = internal ? internalOrderBlocks : swingOrderBlocks
        if blocks.size() >= 100
            blocks.pop()
        blocks.unshift(ob)
 
drawOrderBlocks(bool internal=false) =>
    array<orderBlock> orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
    obSize = orderBlocks.size()
    if obSize > 0
        maxOB  = internal ? internalOrderBlocksSizeInput : swingOrderBlocksSizeInput
        array<orderBlock> parsedOBs = orderBlocks.slice(0, math.min(maxOB, obSize))
        array<box> b_oxes           = internal ? internalOrderBlocksBoxes : swingOrderBlocksBoxes
        for [index, eachOB] in parsedOBs
            obColor = styleInput == MONOCHROME ? (eachOB.bias == BEARISH ? color.new(MONO_BEARISH,80) : color.new(MONO_BULLISH,80)) : internal ? (eachOB.bias == BEARISH ? internalBearishOrderBlockColor : internalBullishOrderBlockColor) : (eachOB.bias == BEARISH ? swingBearishOrderBlockColor : swingBullishOrderBlockColor)
            box b_ox = b_oxes.get(index)
            b_ox.set_top_left_point(    chart.point.new(eachOB.barTime,na,eachOB.barHigh))
            b_ox.set_bottom_right_point(chart.point.new(last_bar_time, na,eachOB.barLow))
            b_ox.set_border_color(      internal ? na : obColor)
            b_ox.set_bgcolor(           obColor)
 
displayStructure(bool internal=false) =>
    var bullishBar = true
    var bearishBar = true
    if internalFilterConfluenceInput
        bullishBar := high - math.max(close,open) > math.min(close,open) - low
        bearishBar := high - math.max(close,open) < math.min(close,open) - low
    pivot p_ivot   = internal ? internalHigh : swingHigh
    trend t_rend   = internal ? internalTrend : swingTrend
    lineStyle      = internal ? line.style_dashed : line.style_solid
    labelSize      = internal ? internalStructureSize : swingStructureSize
    extraCond      = internal ? internalHigh.currentLevel != swingHigh.currentLevel and bullishBar : true
    bullishColor   = styleInput == MONOCHROME ? MONO_BULLISH : internal ? internalBullColorInput : swingBullColorInput
    if ta.crossover(close, p_ivot.currentLevel) and not p_ivot.crossed and extraCond
        string tag = t_rend.bias == BEARISH ? CHOCH : BOS
        if internal
            currentAlerts.internalBullishCHoCH := tag == CHOCH
            currentAlerts.internalBullishBOS   := tag == BOS
        else
            currentAlerts.swingBullishCHoCH    := tag == CHOCH
            currentAlerts.swingBullishBOS      := tag == BOS
        p_ivot.crossed := true
        t_rend.bias    := BULLISH
        displayCond = internal ? showInternalsInput and (showInternalBullInput == ALL or (showInternalBullInput == BOS and tag != CHOCH) or (showInternalBullInput == CHOCH and tag == CHOCH)) : showStructureInput and (showSwingBullInput == ALL or (showSwingBullInput == BOS and tag != CHOCH) or (showSwingBullInput == CHOCH and tag == CHOCH))
        if displayCond
            drawStructure(p_ivot, tag, bullishColor, lineStyle, label.style_label_down, labelSize)
        if (internal and showInternalOrderBlocksInput) or (not internal and showSwingOrderBlocksInput)
            storeOrderBlock(p_ivot, internal, BULLISH)
    p_ivot    := internal ? internalLow : swingLow
    extraCond := internal ? internalLow.currentLevel != swingLow.currentLevel and bearishBar : true
    bearishColor = styleInput == MONOCHROME ? MONO_BEARISH : internal ? internalBearColorInput : swingBearColorInput
    if ta.crossunder(close, p_ivot.currentLevel) and not p_ivot.crossed and extraCond
        string tag = t_rend.bias == BULLISH ? CHOCH : BOS
        if internal
            currentAlerts.internalBearishCHoCH := tag == CHOCH
            currentAlerts.internalBearishBOS   := tag == BOS
        else
            currentAlerts.swingBearishCHoCH    := tag == CHOCH
            currentAlerts.swingBearishBOS      := tag == BOS
        p_ivot.crossed := true
        t_rend.bias    := BEARISH
        displayCond = internal ? showInternalsInput and (showInternalBearInput == ALL or (showInternalBearInput == BOS and tag != CHOCH) or (showInternalBearInput == CHOCH and tag == CHOCH)) : showStructureInput and (showSwingBearInput == ALL or (showSwingBearInput == BOS and tag != CHOCH) or (showSwingBearInput == CHOCH and tag == CHOCH))
        if displayCond
            drawStructure(p_ivot, tag, bearishColor, lineStyle, label.style_label_up, labelSize)
        if (internal and showInternalOrderBlocksInput) or (not internal and showSwingOrderBlocksInput)
            storeOrderBlock(p_ivot, internal, BEARISH)
 
fairValueGapBox(leftTime, rightTime, topPrice, bottomPrice, boxColor) =>
    box.new(chart.point.new(leftTime,na,topPrice), chart.point.new(rightTime + fairValueGapsExtendInput * (time - time[1]),na,bottomPrice), xloc=xloc.bar_time, border_color=boxColor, bgcolor=boxColor)
 
deleteFairValueGaps() =>
    for [index, fvg] in fairValueGaps
        if (low < fvg.bottom and fvg.bias == BULLISH) or (high > fvg.top and fvg.bias == BEARISH)
            fvg.topBox.delete()
            fvg.bottomBox.delete()
            fairValueGaps.remove(index)
 
drawFairValueGaps() =>
    [lastClose, lastOpen, lastTime, currentHigh, currentLow, currentTime, last2High, last2Low] = request.security(syminfo.tickerid, fairValueGapsTimeframeInput, [close[1],open[1],time[1],high[0],low[0],time[0],high[2],low[2]], lookahead=barmerge.lookahead_off)
    barDeltaPercent     = (lastClose - lastOpen) / (lastOpen * 100)
    newTimeframe        = timeframe.change(fairValueGapsTimeframeInput)
    threshold           = fairValueGapsThresholdInput ? ta.cum(math.abs(newTimeframe ? barDeltaPercent : 0)) / bar_index * 2 : 0
    bullishFVG          = currentLow > last2High and lastClose > last2High and barDeltaPercent > threshold and newTimeframe
    bearishFVG          = currentHigh < last2Low  and lastClose < last2Low  and -barDeltaPercent > threshold and newTimeframe
    if bullishFVG
        currentAlerts.bullishFairValueGap := true
        fairValueGaps.unshift(fairValueGap.new(currentLow, last2High, BULLISH, fairValueGapBox(lastTime, currentTime, currentLow, math.avg(currentLow,last2High), fairValueGapBullishColor), fairValueGapBox(lastTime, currentTime, math.avg(currentLow,last2High), last2High, fairValueGapBullishColor)))
    if bearishFVG
        currentAlerts.bearishFairValueGap := true
        fairValueGaps.unshift(fairValueGap.new(currentHigh, last2Low, BEARISH, fairValueGapBox(lastTime, currentTime, currentHigh, math.avg(currentHigh,last2Low), fairValueGapBearishColor), fairValueGapBox(lastTime, currentTime, math.avg(currentHigh,last2Low), last2Low, fairValueGapBearishColor)))
 
updateTrailingExtremes() =>
    trailing.top            := math.max(high, nz(trailing.top, high))
    trailing.lastTopTime    := trailing.top == high ? time : trailing.lastTopTime
    trailing.bottom         := math.min(low,  nz(trailing.bottom, low))
    trailing.lastBottomTime := trailing.bottom == low ? time : trailing.lastBottomTime
 
drawHighLowSwings() =>
    var line  topLine    = line.new(na,na,na,na, color=swingBearishColor, xloc=xloc.bar_time)
    var line  botLine    = line.new(na,na,na,na, color=swingBullishColor, xloc=xloc.bar_time)
    var label topLabel   = label.new(na,na, color=color(na), textcolor=swingBearishColor, xloc=xloc.bar_time, style=label.style_label_down, size=size.tiny)
    var label botLabel   = label.new(na,na, color=color(na), textcolor=swingBullishColor, xloc=xloc.bar_time, style=label.style_label_up, size=size.tiny)
    rightTimeBar         = last_bar_time + 20*(time-time[1])
    topLine.set_first_point(  chart.point.new(trailing.lastTopTime,    na, trailing.top))
    topLine.set_second_point( chart.point.new(rightTimeBar,            na, trailing.top))
    topLabel.set_point(       chart.point.new(rightTimeBar,            na, trailing.top))
    topLabel.set_text(        swingTrend.bias == BEARISH ? 'Strong High' : 'Weak High')
    botLine.set_first_point(  chart.point.new(trailing.lastBottomTime, na, trailing.bottom))
    botLine.set_second_point( chart.point.new(rightTimeBar,            na, trailing.bottom))
    botLabel.set_point(       chart.point.new(rightTimeBar,            na, trailing.bottom))
    botLabel.set_text(        swingTrend.bias == BULLISH ? 'Strong Low' : 'Weak Low')
 
drawZone(float labelLevel, int labelIndex, float top, float bottom, string tag, color zoneColor, string style) =>
    var label l_abel = label.new(na, na, text = tag, color = color(na), textcolor = zoneColor, style = style, size = size.small)
    var box   b_ox   = box.new(na, na, na, na, bgcolor = color.new(zoneColor, 80), border_color = color(na), xloc = xloc.bar_time)
    b_ox.set_top_left_point(     chart.point.new(trailing.barTime, na, top))
    b_ox.set_bottom_right_point( chart.point.new(last_bar_time,    na, bottom))
    l_abel.set_point(            chart.point.new(na, labelIndex, labelLevel))
 
drawPremiumDiscountZones() =>
    drawZone(trailing.top, math.round(0.5 * (trailing.barIndex + last_bar_index)), trailing.top, 0.95 * trailing.top + 0.05 * trailing.bottom, "Premium", premiumZoneColor, label.style_label_down)
    eqLevel = math.avg(trailing.top, trailing.bottom)
    drawZone(eqLevel, last_bar_index, 0.525 * trailing.top + 0.475 * trailing.bottom, 0.525 * trailing.bottom + 0.475 * trailing.top, "Equilibrium", equilibriumZoneColorInput, label.style_label_left)
    drawZone(trailing.bottom, math.round(0.5 * (trailing.barIndex + last_bar_index)), 0.95 * trailing.bottom + 0.05 * trailing.top, trailing.bottom, "Discount", discountZoneColor, label.style_label_up)
 
// [O] RSI MOMENTUM + SMART SIGNALS — second opinion. Rising-edge only.
rsi = ta.rsi(close, rsiLen)
rsi_ema_val  = ta.ema(close, rsi_ema_len)
rsi_ema_chng = ta.change(rsi_ema_val)
bool smartBull_raw = rsi > pmom and rsi < rsi_ob and rsi_ema_chng > 0
bool smartBear_raw = rsi < nmom and rsi > rsi_os and rsi_ema_chng < 0
bool trailGateBullOK = not useSmartTrailGate or trailTrend == 1
bool trailGateBearOK = not useSmartTrailGate or trailTrend == -1
bool hullGateBullOK  = not useSmartHullGate  or hull_bull
bool hullGateBearOK  = not useSmartHullGate  or hull_bear
bool fibGateBullOK   = not useSmartFibGate   or trend_fib == 1
bool fibGateBearOK   = not useSmartFibGate   or trend_fib == -1
bool smartBull = smartBull_raw and trailGateBullOK and hullGateBullOK and fibGateBullOK
bool smartBear = smartBear_raw and trailGateBearOK and hullGateBearOK and fibGateBearOK
bool newSmartBull = smartBull and not smartBull[1]
bool newSmartBear = smartBear and not smartBear[1]
bool newSmartBullRaw = smartBull_raw and not smartBull_raw[1]
bool newSmartBearRaw = smartBear_raw and not smartBear_raw[1]
bool rejectedBull = newSmartBullRaw and not newSmartBull
bool rejectedBear = newSmartBearRaw and not newSmartBear
 
// [P] DWM INFO — diurnal rhythm. PDH/PDL are spatial anchors, not signals.
type dwm_info
    string tf
    float o = na
    float h = na
    float l = na
    float ph = na
    float pl = na
 
var d_info = dwm_info.new("D")
 
update_dwm_info(dwm_info info) =>
    if timeframe.change(info.tf)
        info.ph := info.h
        info.pl := info.l
        info.o := open
        info.h := high
        info.l := low
    else
        info.h := math.max(high, info.h)
        info.l := math.min(low, info.l)
 
update_dwm_info(d_info)
 
// [Q] ICT KILLZONES — clock-based windows, not news.
var box asiaBox   = na
var box londonBox = na
var box nyamBox   = na
var box nyluBox   = na
var box nypmBox   = na
 
bool inAsia   = not na(time("", asia,   gmt_tz))
bool inLondon = not na(time("", london, gmt_tz))
bool inNyam   = not na(time("", nyam,   gmt_tz))
bool inNylu   = not na(time("", nylu,   gmt_tz))
bool inNypm   = not na(time("", nypm,   gmt_tz))
 
if show_kz
    if use_asia
        if inAsia and na(asiaBox)
            asiaBox := box.new(time, high, time, low, xloc=xloc.bar_time, border_color=color.new(color.blue, box_transparency), bgcolor=color.new(color.blue, box_transparency), text=show_kz_text ? "Asia" : na, text_color=color.new(color.white, text_transparency))
        if inAsia and not na(asiaBox)
            box.set_right(asiaBox, time)
            box.set_top(asiaBox, math.max(box.get_top(asiaBox), high))
            box.set_bottom(asiaBox, math.min(box.get_bottom(asiaBox), low))
        if not inAsia and not na(asiaBox)
            asiaBox := na
    if use_london
        if inLondon and na(londonBox)
            londonBox := box.new(time, high, time, low, xloc=xloc.bar_time, border_color=color.new(color.red, box_transparency), bgcolor=color.new(color.red, box_transparency), text=show_kz_text ? "London" : na, text_color=color.new(color.white, text_transparency))
        if inLondon and not na(londonBox)
            box.set_right(londonBox, time)
            box.set_top(londonBox, math.max(box.get_top(londonBox), high))
            box.set_bottom(londonBox, math.min(box.get_bottom(londonBox), low))
        if not inLondon and not na(londonBox)
            londonBox := na
    if use_nyam
        if inNyam and na(nyamBox)
            nyamBox := box.new(time, high, time, low, xloc=xloc.bar_time, border_color=color.new(LONG_COLOR, box_transparency), bgcolor=color.new(LONG_COLOR, box_transparency), text=show_kz_text ? "NY AM" : na, text_color=color.new(color.white, text_transparency))
        if inNyam and not na(nyamBox)
            box.set_right(nyamBox, time)
            box.set_top(nyamBox, math.max(box.get_top(nyamBox), high))
            box.set_bottom(nyamBox, math.min(box.get_bottom(nyamBox), low))
        if not inNyam and not na(nyamBox)
            nyamBox := na
    if use_nylu
        if inNylu and na(nyluBox)
            nyluBox := box.new(time, high, time, low, xloc=xloc.bar_time, border_color=color.new(color.yellow, box_transparency), bgcolor=color.new(color.yellow, box_transparency), text=show_kz_text ? "LDN-NY" : na, text_color=color.new(color.white, text_transparency))
        if inNylu and not na(nyluBox)
            box.set_right(nyluBox, time)
            box.set_top(nyluBox, math.max(box.get_top(nyluBox), high))
            box.set_bottom(nyluBox, math.min(box.get_bottom(nyluBox), low))
        if not inNylu and not na(nyluBox)
            nyluBox := na
    if use_nypm
        if inNypm and na(nypmBox)
            nypmBox := box.new(time, high, time, low, xloc=xloc.bar_time, border_color=color.new(color.purple, box_transparency), bgcolor=color.new(color.purple, box_transparency), text=show_kz_text ? "NY PM" : na, text_color=color.new(color.white, text_transparency))
        if inNypm and not na(nypmBox)
            box.set_right(nypmBox, time)
            box.set_top(nypmBox, math.max(box.get_top(nypmBox), high))
            box.set_bottom(nypmBox, math.min(box.get_bottom(nypmBox), low))
        if not inNypm and not na(nypmBox)
            nypmBox := na
 
string activeKz = inAsia ? "Asia" : inLondon ? "London" : inNyam ? "NY AM" : inNylu ? "LDN-NY" : inNypm ? "NY PM" : "Between"
 
// [R] NEURAL CONFLUENCE SCORE — 8 witnesses, each contributing one point.
// Not a probability — a count. When many agree, ULTRON trusts the direction.
float vol_avg = ta.sma(volume, volLen)
bool vol_ok = not na(volume) and not na(vol_avg) and volume >= vol_avg * volMult
 
bool in_aoi = false
if chochActive and not na(curZoneRng)
    float distHigh = math.abs(close - curZoneHigh)
    float distLow  = math.abs(close - curZoneLow)
    if distHigh <= curZoneRng * 1.5 or distLow <= curZoneRng * 1.5
        in_aoi := true
 
float mom = (close - close[momLookback]) / nz(hAtr, syminfo.mintick)
bool mom_bull = mom >  momThresh
bool mom_bear = mom < -momThresh
 
int bull_score = 0
int bear_score = 0
if w_hull  and hull_bull
    bull_score += 1
if w_hull  and hull_bear
    bear_score += 1
if w_fast  and fast_bull
    bull_score += 1
if w_fast  and fast_bear
    bear_score += 1
if w_trail and trailTrend == 1
    bull_score += 1
if w_trail and trailTrend == -1
    bear_score += 1
if w_choch and chochActive and activeDir == 1
    bull_score += 1
if w_choch and chochActive and activeDir == -1
    bear_score += 1
if w_aoi and in_aoi and activeDir == 1
    bull_score += 1
if w_aoi and in_aoi and activeDir == -1
    bear_score += 1
if w_mom and mom_bull
    bull_score += 1
if w_mom and mom_bear
    bear_score += 1
if w_ult and ultron_bull_clear
    bull_score += 1
if w_ult and ultron_bear_clear
    bear_score += 1
if w_vol and vol_ok
    bull_score += 1
    bear_score += 1
 
// [R2] PROBABILISTIC NODE LAYER — ULTRON watching itself watch price.
// Each node answers "how much", not "yes/no". The posterior is a sum of its
// parts, and every part is visible.
f_sigmoid(float x) => 1.0 / (1.0 + math.exp(-x))
_atr_norm = nz(ta.atr(14), syminfo.mintick)
 
pn_hull_bull = f_sigmoid((HULL - HULL[2]) / _atr_norm / probTemp * 2.0)
pn_hull_bear = 1.0 - pn_hull_bull
pn_fast_bull = f_sigmoid((HULL_FAST - HULL_FAST[2]) / _atr_norm / probTemp * 3.0)
pn_fast_bear = 1.0 - pn_fast_bull
pn_trail_bull = trailTrend == 1 ? 1.0 : 0.0
pn_trail_bear = 1.0 - pn_trail_bull
float _bar_ms_norm = math.max(1.0, nz(time - time[1], 60000.0))
float _bars_since_structure = math.abs(time - nz(pendingStructureStart, time)) / _bar_ms_norm
pn_choch_bull = (chochActive and activeDir == 1)  ? math.max(0.0, 1.0 - _bars_since_structure / 100.0) : 0.0
pn_choch_bear = (chochActive and activeDir == -1) ? math.max(0.0, 1.0 - _bars_since_structure / 100.0) : 0.0
pn_aoi_bull = (chochActive and activeDir == 1 and in_aoi)  ? 0.85 : 0.15
pn_aoi_bear = (chochActive and activeDir == -1 and in_aoi) ? 0.85 : 0.15
pn_mom_bull = f_sigmoid(mom / math.max(nz(momThresh, 0.5), 0.05) / probTemp)
pn_mom_bear = 1.0 - pn_mom_bull
pn_ult_bull = ultron_bull_clear ? 1.0 : 0.0
pn_ult_bear = ultron_bear_clear ? 1.0 : 0.0
pn_vol = not na(vol_avg) and vol_avg > 0 ? math.min(1.0, volume / (vol_avg * volMult)) : 0.5
pn_rsi_bull = math.max(0.0, math.min(1.0, (rsi - 50.0) / 30.0 + 0.5))
pn_rsi_bear = 1.0 - pn_rsi_bull
pn_kz_bull = (inNyam or inNylu) ? 0.65 : (inLondon or inAsia) ? 0.45 : 0.5
pn_kz_bear = (inLondon or inAsia) ? 0.65 : (inNyam or inNylu) ? 0.45 : 0.5
pn_htffib_bull = htf_trend_fib == 1  ? 1.0 : 0.0
pn_htffib_bear = htf_trend_fib == -1 ? 1.0 : 0.0
pn_mtf_bull = htf_choch_dir == 1  ? 1.0 : 0.0
pn_mtf_bear = htf_choch_dir == -1 ? 1.0 : 0.0
float pd_pos = not na(trailing.top) and not na(trailing.bottom) and trailing.top > trailing.bottom ? (close - trailing.bottom) / math.max(syminfo.mintick, trailing.top - trailing.bottom) : 0.5
pn_pd_bull = 1.0 - pd_pos
pn_pd_bear = pd_pos
 
float nearestH_lq = na
float nearestL_lq = na
if array.size(lqZones) > 0
    for i = 0 to array.size(lqZones) - 1
        LiqZone _z = array.get(lqZones, i)
        if _z.is_high and not _z.broken and (na(nearestH_lq) or math.abs(_z.price - close) < math.abs(nearestH_lq - close))
            nearestH_lq := _z.price
        if not _z.is_high and not _z.broken and (na(nearestL_lq) or math.abs(_z.price - close) < math.abs(nearestL_lq - close))
            nearestL_lq := _z.price
float _lq_range = _atr_norm * 5.0
pn_lq_bull = not na(nearestL_lq) ? math.max(0.0, 1.0 - math.abs(close - nearestL_lq) / _lq_range) : 0.0
pn_lq_bear = not na(nearestH_lq) ? math.max(0.0, 1.0 - math.abs(close - nearestH_lq) / _lq_range) : 0.0
 
// FIX 4 — synthetic-aware weights. Deriv synthetic volume is essentially fake.
bool _is_synth = str.contains(deriv_asset_class(), "synthetic")
float _w_vol_eff = _is_synth ? 0.0 : w_vol_p
float _w_rsi_eff = _is_synth ? w_rsi_p * 0.5 : w_rsi_p
 
float sum_w = w_hull_p + w_fast_p + w_trail_p + w_choch_p + w_aoi_p + w_mom_p + w_ult_p + _w_vol_eff + _w_rsi_eff + w_kz_p + w_htffib_p + w_mtf_p + w_pd_p + w_lq_p
float raw_bull = (pn_hull_bull  * w_hull_p  + pn_fast_bull  * w_fast_p  + pn_trail_bull * w_trail_p + pn_choch_bull * w_choch_p + pn_aoi_bull   * w_aoi_p   + pn_mom_bull   * w_mom_p   + pn_ult_bull   * w_ult_p   + pn_vol        * _w_vol_eff + pn_rsi_bull   * _w_rsi_eff + pn_kz_bull    * w_kz_p    + pn_htffib_bull* w_htffib_p+ pn_mtf_bull   * w_mtf_p   + pn_pd_bull    * w_pd_p    + pn_lq_bull    * w_lq_p) / math.max(0.001, sum_w)
float raw_bear = (pn_hull_bear  * w_hull_p  + pn_fast_bear  * w_fast_p  + pn_trail_bear * w_trail_p + pn_choch_bear * w_choch_p + pn_aoi_bear   * w_aoi_p   + pn_mom_bear   * w_mom_p   + pn_ult_bear   * w_ult_p   + pn_vol        * _w_vol_eff + pn_rsi_bear   * _w_rsi_eff + pn_kz_bear    * w_kz_p    + pn_htffib_bear* w_htffib_p+ pn_mtf_bear   * w_mtf_p   + pn_pd_bear    * w_pd_p    + pn_lq_bear    * w_lq_p) / math.max(0.001, sum_w)
float posterior_bull = raw_bull / math.max(0.001, raw_bull + raw_bear)
float posterior_bear = 1.0 - posterior_bull
float prob_edge     = math.abs(posterior_bull - posterior_bear)
 
// [R3] ZONE CONFIDENCE ENGINE — a zone is a claim. This counts corroborations.
f_zone_confidence(int dir, float zHigh, float zLow) =>
    float conf = 0.0
    int   total = 0
    total += 1
    if (dir == 1 and htf_choch_dir == 1) or (dir == -1 and htf_choch_dir == -1)
        conf += 1.0
    total += 1
    if (dir == 1 and fib_base_clear_long) or (dir == -1 and fib_base_clear_short)
        conf += 1.0
    total += 1
    if dir == 1 and not na(nearestL_lq) and math.abs(close - nearestL_lq) < _atr_norm * 4
        conf += 1.0
    if dir == -1 and not na(nearestH_lq) and math.abs(close - nearestH_lq) < _atr_norm * 4
        conf += 1.0
    total += 1
    if dir == 1 and pd_pos < 0.45
        conf += 1.0
    if dir == -1 and pd_pos > 0.55
        conf += 1.0
    total += 1
    if vol_ok
        conf += 1.0
    total += 1
    if dir == 1 and mom_bull
        conf += 1.0
    if dir == -1 and mom_bear
        conf += 1.0
    total += 1
    if inNyam or inNylu
        conf += 1.0
    total += 1
    if (dir == 1 and htf_trend_fib == 1) or (dir == -1 and htf_trend_fib == -1)
        conf += 1.0
    total += 1
    if in_aoi and ((dir == 1 and activeDir == 1) or (dir == -1 and activeDir == -1))
        conf += 1.0
    conf / math.max(1, total)
 
if chochSignal and not na(_lastZoneLbl)
    activeZoneConf := f_zone_confidence(_lastZoneDir, _lastZoneHigh, _lastZoneLow)
    string _stars = activeZoneConf >= 0.75 ? " ⭐⭐⭐" : activeZoneConf >= 0.50 ? " ⭐⭐" : activeZoneConf >= 0.25 ? " ⭐" : ""
    string _newTag = (_lastZoneDir == 1 ? "BUY ZONE" : "SELL ZONE") + _stars
    color _dirColor = _lastZoneDir == 1 ? zoneUpClr : zoneDnClr
    color _newColor = activeZoneConf >= 0.75 ? color.yellow : activeZoneConf >= 0.50 ? color.orange : activeZoneConf >= 0.25 ? _dirColor : color.new(_dirColor, 40)
    label.set_text(_lastZoneLbl, _newTag)
    label.set_textcolor(_lastZoneLbl, _newColor)
    string _base_tt = build_zone_tooltip(_lastZoneDir, _lastZoneHigh, _lastZoneLow)
    string _conf_tt = "Zone Confidence: " + str.tostring(activeZoneConf * 100.0, "#") + "%\n"
    string _post_tt = "Posterior(bull): " + str.tostring(posterior_bull * 100.0, "#.#") + "%  |  Posterior(bear): " + str.tostring(posterior_bear * 100.0, "#.#") + "%\n"
    label.set_tooltip(_lastZoneLbl, _base_tt + _conf_tt + _post_tt)
 
// [R4] HTF FIBONACCI PROJECTION — the regime's grid, redrawn on the last bar.
f_htfSwingLevels() =>
    _ph = ta.pivothigh(high, 10, 10)
    _pl = ta.pivotlow(low, 10, 10)
    var float _lastPH = na
    var float _lastPL = na
    if not na(_ph)
        _lastPH := _ph
    if not na(_pl)
        _lastPL := _pl
    [_lastPH, _lastPL]
 
[htf_ph, htf_pl] = request.security(syminfo.tickerid, mtfConfluenceTf, f_htfSwingLevels(), lookahead=barmerge.lookahead_off)
 
var int    htfFibDir  = 0
var float  htfFibHigh = na
var float  htfFibLow  = na
if not na(htf_ph) and (na(htfFibHigh) or htf_ph != htfFibHigh)
    htfFibHigh := htf_ph
    if not na(htf_pl)
        htfFibLow := htf_pl
        htfFibDir := -1
if not na(htf_pl) and (na(htfFibLow) or htf_pl != htfFibLow)
    htfFibLow := htf_pl
    if not na(htf_ph)
        htfFibHigh := htf_ph
        htfFibDir := 1
 
var line[]  htfFibLines  = array.new_line()
var label[] htfFibLabels = array.new_label()
 
if useHtfFibProj and not na(htfFibHigh) and not na(htfFibLow) and htfFibHigh > htfFibLow and barstate.islast
    if array.size(htfFibLines) > 0
        for i = 0 to array.size(htfFibLines) - 1
            line.delete(array.get(htfFibLines, i))
        for i = 0 to array.size(htfFibLabels) - 1
            label.delete(array.get(htfFibLabels, i))
        array.clear(htfFibLines)
        array.clear(htfFibLabels)
    float rng = htfFibHigh - htfFibLow
    int   lt  = time - 200 * (time - time[1])
    int   rt  = time + 50  * (time - time[1])
    color baseClr = htfFibDir == 1 ? htfFibUpClr : htfFibDnClr
    array<float> retrLvls = array.from(0.236, 0.382, 0.5, 0.618, 0.786)
    array<float> extLvls  = array.from(1.272, 1.414, 1.618, 2.0, 2.618)
    if showHtfFibRetr
        for i = 0 to array.size(retrLvls) - 1
            float lv = array.get(retrLvls, i)
            float y = htfFibDir == 1 ? htfFibHigh - rng * lv : htfFibLow + rng * lv
            line l = line.new(lt, y, rt, y, xloc=xloc.bar_time, color=color.new(baseClr, 30), style=line.style_dashed, width=1)
            label lb = label.new(rt, y, "HTF " + str.tostring(lv, "#.###"), xloc=xloc.bar_time, color=color(na), textcolor=baseClr, style=label.style_label_left, size=size.tiny)
            array.push(htfFibLines, l)
            array.push(htfFibLabels, lb)
    if showHtfFibExt
        for i = 0 to array.size(extLvls) - 1
            float lv = array.get(extLvls, i)
            float y = htfFibDir == 1 ? htfFibLow + rng * lv : htfFibHigh - rng * lv
            line l = line.new(lt, y, rt, y, xloc=xloc.bar_time, color=color.new(baseClr, 55), style=line.style_dotted, width=1)
            label lb = label.new(rt, y, "EXT " + str.tostring(lv, "#.###"), xloc=xloc.bar_time, color=color(na), textcolor=color.new(baseClr, 30), style=label.style_label_left, size=size.tiny)
            array.push(htfFibLines, l)
            array.push(htfFibLabels, lb)
 
// [S] SIGNAL LOGIC — Tier 2 judgement. FIX 2 adds a confidence gate on CHoCH
// triggers. Trail-flip triggers remain ungated by zone confidence.
bool fib_override_long  = use_fib_soft_override and bull_score >= 7 and trailTrend == 1
bool fib_override_short = use_fib_soft_override and bear_score >= 7 and trailTrend == -1
bool fib_clear_long  = (ltf_gate_long  and htf_gate_long  and fib_band_long  and htf_band_long  and fib_cool_long  and htf_cool_long)  or fib_override_long
bool fib_clear_short = (ltf_gate_short and htf_gate_short and fib_band_short and htf_band_short and fib_cool_short and htf_cool_short) or fib_override_short
bool conf_gate_long  = na(activeZoneConf) or activeZoneConf >= minZoneConfForTrig
bool conf_gate_short = na(activeZoneConf) or activeZoneConf >= minZoneConfForTrig
bool qual_bull = trailTrend == 1  and bull_score >= minScore and ultron_bull_clear and fib_clear_long
bool qual_bear = trailTrend == -1 and bear_score >= minScore and ultron_bear_clear and fib_clear_short
bool trig_bull = (flip_bull or (chochSignal and activeDir == 1 and conf_gate_long)) and qual_bull
bool trig_bear = (flip_bear or (chochSignal and activeDir == -1 and conf_gate_short)) and qual_bear
bool rej_bull  = flip_bull and not trig_bull
bool rej_bear  = flip_bear and not trig_bear
 
// [T] POSITION TOOL — Tier 3 execution. FIX 3 adds Zone Retest entry mode.
var PositionTool active_pos = na
var int   trade_dir      = 0
var float entry_px       = na
var float initial_risk   = na
var float active_sl      = na
var float tp1_px         = na
var float tp2_px         = na
var float tp3_px         = na
var int   trade_stage    = 0
var bool  last_sl_hit_long  = false
var bool  last_sl_hit_short = false
var float last_exit_price   = na
 
bool long_entry_signal  = false
bool short_entry_signal = false
bool long_exit_signal   = false
bool short_exit_signal  = false
bool long_tp1_signal    = false
bool long_tp2_signal    = false
bool long_tp3_signal    = false
bool short_tp1_signal   = false
bool short_tp2_signal   = false
bool short_tp3_signal   = false
 
var int   pending_dir   = 0
var float pending_trail = na
if flip_bull
    pending_dir   := 1
    pending_trail := trail
if flip_bear
    pending_dir   := -1
    pending_trail := trail
 
var float pendingZoneEntryHigh = na
var float pendingZoneEntryLow  = na
var int   pendingZoneEntryDir  = 0
var int   pendingZoneEntryBar  = na
 
if chochSignal and not na(_lastZoneLbl)
    pendingZoneEntryHigh := _lastZoneHigh
    pendingZoneEntryLow  := _lastZoneLow
    pendingZoneEntryDir  := _lastZoneDir
    pendingZoneEntryBar  := bar_index
 
bool _zone_window_open = not na(pendingZoneEntryBar) and bar_index > pendingZoneEntryBar and (bar_index - pendingZoneEntryBar) <= zoneRetestWindow
bool _zone_retest_long  = entry_mode == "Zone Retest" and pendingZoneEntryDir == 1  and _zone_window_open and low  <= pendingZoneEntryHigh and close > pendingZoneEntryLow  and trailTrend == 1
bool _zone_retest_short = entry_mode == "Zone Retest" and pendingZoneEntryDir == -1 and _zone_window_open and high >= pendingZoneEntryLow  and close < pendingZoneEntryHigh and trailTrend == -1
 
bool retest_bull = entry_mode == "Trail Retest" and pending_dir == 1  and low  <= pending_trail and close >= pending_trail and trig_bull
bool retest_bear = entry_mode == "Trail Retest" and pending_dir == -1 and high >= pending_trail and close <= pending_trail and trig_bear
bool sig_bull    = entry_mode == "Signal Change" and trig_bull
bool sig_bear    = entry_mode == "Signal Change" and trig_bear
bool zone_bull = _zone_retest_long  and qual_bull
bool zone_bear = _zone_retest_short and qual_bear
bool do_bull = sig_bull or retest_bull or zone_bull
bool do_bear = sig_bear or retest_bear or zone_bear
if retest_bull or retest_bear
    pending_dir := 0
if zone_bull or zone_bear
    pendingZoneEntryBar := na
 
delete_position(PositionTool p) =>
    line.delete(p.entry_line)
    line.delete(p.sl_line)
    line.delete(p.tp1_line)
    line.delete(p.tp2_line)
    line.delete(p.tp3_line)
    label.delete(p.entry_lbl)
    label.delete(p.sl_lbl)
    label.delete(p.tp1_lbl)
    label.delete(p.tp2_lbl)
    label.delete(p.tp3_lbl)
    box.delete(p.risk_box)
 
if trade_dir == 1
    if trade_stage == 1
        active_sl := trail
    else if trade_stage == 2
        active_sl := math.max(entry_px + be_buffer, trail)
    else if trade_stage == 3
        active_sl := math.max(lock_tp1_at_tp2 ? tp1_px : (entry_px + be_buffer), trail)
    else if trade_stage == 4
        active_sl := math.max(trail, nz(active_sl[1], trail))
    bool sl_hit_long = sl_close_confirm ? (barstate.isconfirmed and close <= active_sl) : (low <= active_sl)
    bool trail_flip_exit_long = barstate.isconfirmed and flip_bear
    if sl_hit_long or trail_flip_exit_long
        long_exit_signal := true
        last_sl_hit_long := sl_hit_long
        last_exit_price  := sl_hit_long ? active_sl : close
        if not na(active_pos)
            delete_position(active_pos)
            active_pos := na
        trade_dir   := 0
        trade_stage := 0
    else
        if trade_stage == 1 and high >= tp1_px
            long_tp1_signal := true
            trade_stage := 2
            active_sl := math.max(entry_px + be_buffer, trail)
        if trade_stage == 2 and high >= tp2_px
            long_tp2_signal := true
            trade_stage := 3
            active_sl := math.max(lock_tp1_at_tp2 ? tp1_px : (entry_px + be_buffer), trail)
        if trade_stage == 3 and high >= tp3_px
            long_tp3_signal := true
            trade_stage := 4
            active_sl := trail
else if trade_dir == -1
    if trade_stage == 1
        active_sl := trail
    else if trade_stage == 2
        active_sl := math.min(entry_px - be_buffer, trail)
    else if trade_stage == 3
        active_sl := math.min(lock_tp1_at_tp2 ? tp1_px : (entry_px - be_buffer), trail)
    else if trade_stage == 4
        active_sl := math.min(trail, nz(active_sl[1], trail))
    bool sl_hit_short = sl_close_confirm ? (barstate.isconfirmed and close >= active_sl) : (high >= active_sl)
    bool trail_flip_exit_short = barstate.isconfirmed and flip_bull
    if sl_hit_short or trail_flip_exit_short
        short_exit_signal := true
        last_sl_hit_short := sl_hit_short
        last_exit_price   := sl_hit_short ? active_sl : close
        if not na(active_pos)
            delete_position(active_pos)
            active_pos := na
        trade_dir   := 0
        trade_stage := 0
    else
        if trade_stage == 1 and low <= tp1_px
            short_tp1_signal := true
            trade_stage := 2
            active_sl := math.min(entry_px - be_buffer, trail)
        if trade_stage == 2 and low <= tp2_px
            short_tp2_signal := true
            trade_stage := 3
            active_sl := math.min(lock_tp1_at_tp2 ? tp1_px : (entry_px - be_buffer), trail)
        if trade_stage == 3 and low <= tp3_px
            short_tp3_signal := true
            trade_stage := 4
            active_sl := trail
 
if trade_dir == 0 and barstate.isconfirmed
    if do_bull
        trade_dir      := 1
        trade_stage    := 1
        entry_px       := close
        initial_risk   := math.abs(close - trail)
        active_sl      := trail
        tp1_px         := close + initial_risk * tp1_r
        tp2_px         := close + initial_risk * tp2_r
        tp3_px         := close + initial_risk * tp3_r
        long_entry_signal := true
        if show_pos_tool
            int _x1 = bar_index
            int _x2 = bar_index + pos_extend
            active_pos := PositionTool.new(entry_px, trail, tp1_px, tp2_px, tp3_px, true, _x1, line.new(_x1, entry_px, _x2, entry_px, color=LONG_COLOR, style=line.style_dashed), line.new(_x1, trail, _x2, trail, color=color.new(SHORT_COLOR, 30), width=2), line.new(_x1, tp1_px, _x2, tp1_px, color=color.new(LONG_COLOR, 40), style=line.style_dashed), line.new(_x1, tp2_px, _x2, tp2_px, color=color.new(LONG_COLOR, 20), style=line.style_dashed), line.new(_x1, tp3_px, _x2, tp3_px, color=LONG_COLOR, width=2), label.new(_x2, entry_px, "ENTRY " + str.tostring(entry_px, format.mintick), color=na, textcolor=LONG_COLOR, style=label.style_label_left, size=size.small), label.new(_x2, trail, "SL " + str.tostring(trail, format.mintick), color=na, textcolor=color.new(SHORT_COLOR, 30), style=label.style_label_left, size=size.small), label.new(_x2, tp1_px, "TP1 " + str.tostring(tp1_px, format.mintick), color=na, textcolor=color.new(LONG_COLOR, 40), style=label.style_label_left, size=size.small), label.new(_x2, tp2_px, "TP2 " + str.tostring(tp2_px, format.mintick), color=na, textcolor=color.new(LONG_COLOR, 20), style=label.style_label_left, size=size.small), label.new(_x2, tp3_px, "TP3 " + str.tostring(tp3_px, format.mintick), color=na, textcolor=LONG_COLOR, style=label.style_label_left, size=size.small), box.new(_x1, entry_px, _x2, trail, bgcolor=color.new(SHORT_COLOR, 90), border_color=color.new(color.white, 100), border_width=0))
    else if do_bear
        trade_dir      := -1
        trade_stage    := 1
        entry_px       := close
        initial_risk   := math.abs(close - trail)
        active_sl      := trail
        tp1_px         := close - initial_risk * tp1_r
        tp2_px         := close - initial_risk * tp2_r
        tp3_px         := close - initial_risk * tp3_r
        short_entry_signal := true
        if show_pos_tool
            int _x1 = bar_index
            int _x2 = bar_index + pos_extend
            active_pos := PositionTool.new(entry_px, trail, tp1_px, tp2_px, tp3_px, false, _x1, line.new(_x1, entry_px, _x2, entry_px, color=SHORT_COLOR, style=line.style_dashed), line.new(_x1, trail, _x2, trail, color=color.new(SHORT_COLOR, 30), width=2), line.new(_x1, tp1_px, _x2, tp1_px, color=color.new(SHORT_COLOR, 40), style=line.style_dashed), line.new(_x1, tp2_px, _x2, tp2_px, color=color.new(SHORT_COLOR, 20), style=line.style_dashed), line.new(_x1, tp3_px, _x2, tp3_px, color=SHORT_COLOR, width=2), label.new(_x2, entry_px, "ENTRY " + str.tostring(entry_px, format.mintick), color=na, textcolor=SHORT_COLOR, style=label.style_label_left, size=size.small), label.new(_x2, trail, "SL " + str.tostring(trail, format.mintick), color=na, textcolor=color.new(SHORT_COLOR, 30), style=label.style_label_left, size=size.small), label.new(_x2, tp1_px, "TP1 " + str.tostring(tp1_px, format.mintick), color=na, textcolor=color.new(SHORT_COLOR, 40), style=label.style_label_left, size=size.small), label.new(_x2, tp2_px, "TP2 " + str.tostring(tp2_px, format.mintick), color=na, textcolor=color.new(SHORT_COLOR, 20), style=label.style_label_left, size=size.small), label.new(_x2, tp3_px, "TP3 " + str.tostring(tp3_px, format.mintick), color=na, textcolor=SHORT_COLOR, style=label.style_label_left, size=size.small), box.new(_x1, trail, _x2, entry_px, bgcolor=color.new(LONG_COLOR, 90), border_color=color.new(color.white, 100), border_width=0))
 
if show_pos_tool and not na(active_pos) and trade_dir != 0
    int x2b = bar_index + pos_extend
    active_pos.entry_line.set_x2(x2b)
    active_pos.sl_line.set_x2(x2b)
    active_pos.tp1_line.set_x2(x2b)
    active_pos.tp2_line.set_x2(x2b)
    active_pos.tp3_line.set_x2(x2b)
    active_pos.risk_box.set_right(x2b)
    active_pos.entry_lbl.set_x(x2b)
    active_pos.sl_lbl.set_x(x2b)
    active_pos.tp1_lbl.set_x(x2b)
    active_pos.tp2_lbl.set_x(x2b)
    active_pos.tp3_lbl.set_x(x2b)
    if not na(active_sl)
        active_pos.sl := active_sl
        active_pos.sl_line.set_y1(active_sl)
        active_pos.sl_line.set_y2(active_sl)
        active_pos.sl_lbl.set_y(active_sl)
        active_pos.sl_lbl.set_text("SL " + str.tostring(active_sl, format.mintick))
        if active_pos.is_bull
            active_pos.risk_box.set_bottom(active_sl)
        else
            active_pos.risk_box.set_top(active_sl)
 
// [T2] EXECUTION ENGINE — broker-agnostic. Multiplier caps display-only.
bool is_options_mode = exec_mode == EXEC_VANILLA
bool is_mult_mode    = exec_mode == EXEC_MULT
bool is_signal_only  = exec_mode == EXEC_SIGNAL
bool is_execution_mode = is_options_mode or is_mult_mode
string LONG_TAG  = is_options_mode ? "CALL" : "BUY"
string SHORT_TAG = is_options_mode ? "PUT"  : "SELL"
string deriv_class  = deriv_asset_class()
int    deriv_cap    = deriv_max_mult(deriv_class)
bool   deriv_dc_ok  = deriv_dc_available(deriv_class)
float raw_mult = mult_preset == "Conservative" ? 50.0 : mult_preset == "Balanced" ? 100.0 : mult_preset == "Aggressive" ? 300.0 : suggested_mult
bool  deriv_capped  = raw_mult > deriv_cap
float resolved_mult = deriv_capped ? deriv_cap : raw_mult
string broker_cap_label = broker_mode == "Deriv" ? str.tostring(deriv_cap) + "x cap" : broker_mode == "Bybit" ? "leverage N/A" : "—"
string broker_full      = broker_mode + " · " + deriv_class + " · " + broker_cap_label + " · " + str.tostring(resolved_mult, "#") + "x" + (deriv_capped ? " ⚠️" : "")
float exec_atr        = ta.atr(trail_atr_len)
float strike_atm      = close
float strike_call_itm = close - exec_atr * itm_mult
float strike_call_otm = close + exec_atr * otm_mult
float strike_put_itm  = close + exec_atr * itm_mult
float strike_put_otm  = close - exec_atr * otm_mult
float call_strike = na
float put_strike  = na
if is_options_mode
    if strike_mode == "ATM"
        call_strike := strike_atm
        put_strike  := strike_atm
    else if strike_mode == "ITM"
        call_strike := strike_call_itm
        put_strike  := strike_put_itm
    else if strike_mode == "OTM"
        call_strike := strike_call_otm
        put_strike  := strike_put_otm
    else
        call_strike := bull_score >= 7 and ultron_bull_clear ? strike_call_otm : bull_score >= 5 ? strike_atm : strike_call_itm
        put_strike  := bear_score >= 7 and ultron_bear_clear ? strike_put_otm  : bear_score >= 5 ? strike_atm : strike_put_itm
float exec_tf_min  = timeframe.in_seconds(timeframe.period) / 60.0
float exec_trend   = math.abs(bull_score - bear_score) / 8.0
float exec_vol     = math.min(exec_atr / close * 1000.0, 5.0)
int   rec_expiry   = int(math.round(exec_tf_min * expiry_base * (1.0 + exec_trend * 2.0 + exec_vol)))
rec_expiry := math.max(min_expiry, math.min(max_expiry, rec_expiry))
var int   opt_posState     = 0
var int   opt_scaleCount   = 0
var float opt_activeStrike = na
var int   opt_entryBar     = na
bool scale_in_call = opt_posState == 1  and newSmartBull and trailTrend == 1  and opt_scaleCount < max_scale_ins
bool scale_in_put  = opt_posState == -1 and newSmartBear and trailTrend == -1 and opt_scaleCount < max_scale_ins
bool regime_call_exit = opt_posState == 1  and (flip_bear or (chochSignal and activeDir == -1))
bool regime_put_exit  = opt_posState == -1 and (flip_bull or (chochSignal and activeDir == 1))
if long_entry_signal and opt_posState != 1
    opt_posState     := 1
    opt_scaleCount   := 1
    opt_activeStrike := nz(call_strike, entry_px)
    opt_entryBar     := bar_index
else if short_entry_signal and opt_posState != -1
    opt_posState     := -1
    opt_scaleCount   := 1
    opt_activeStrike := nz(put_strike, entry_px)
    opt_entryBar     := bar_index
else if scale_in_call or scale_in_put
    opt_scaleCount += 1
else if regime_call_exit or regime_put_exit
    opt_posState     := 0
    opt_scaleCount   := 0
    opt_activeStrike := na
 
build_signal_tooltip(bool isBull) =>
    int sc = isBull ? bull_score : bear_score
    string mode = is_options_mode ? "Vanilla" : is_mult_mode ? "Multipliers" : "Signal Only"
    string head = isBull ? (is_options_mode ? "CALL" : "BUY") : (is_options_mode ? "PUT" : "SELL")
    string why = "WHY\n"
    if w_hull
        why += (isBull and hull_bull) or (not isBull and hull_bear) ? "✓ Macro Hull\n" : "✗ Macro Hull\n"
    if w_fast
        why += (isBull and fast_bull) or (not isBull and fast_bear) ? "✓ Fast Hull\n" : "✗ Fast Hull\n"
    if w_trail
        why += (isBull and trailTrend == 1) or (not isBull and trailTrend == -1) ? "✓ Trail\n" : "✗ Trail\n"
    if w_choch
        why += chochActive and ((isBull and activeDir == 1) or (not isBull and activeDir == -1)) ? "✓ CHoCH\n" : "· CHoCH\n"
    if w_aoi
        why += in_aoi and ((isBull and activeDir == 1) or (not isBull and activeDir == -1)) ? "✓ AOI\n" : "· Not AOI\n"
    if w_mom
        why += (isBull and mom_bull) or (not isBull and mom_bear) ? "✓ Momentum\n" : "✗ Momentum\n"
    if w_ult
        why += (isBull and ultron_bull_clear) or (not isBull and ultron_bear_clear) ? "✓ Ultron Gate\n" : "✗ Ultron Gate\n"
    if w_vol
        why += vol_ok ? "✓ Volume\n" : "· Volume low\n"
    string fibline = "FIB\n"
    fibline += "Source: " + htf_fib_mode + " | HTF: " + resolved_htf + "\n"
    fibline += "LTF: " + (trend_fib == 1 ? "BULL" : trend_fib == -1 ? "BEAR" : "FLAT") + " (" + str.tostring(fib_bars_since_flip) + "b)\n"
    fibline += "HTF: " + (htf_trend_fib == 1 ? "BULL" : htf_trend_fib == -1 ? "BEAR" : "FLAT") + " (" + str.tostring(htf_bars_since_flip) + "b)\n"
    fibline += "Gate L: " + (fib_clear_long ? "PASS" : "BLOCK") + " | S: " + (fib_clear_short ? "PASS" : "BLOCK") + "\n"
    fibline += "POSTERIOR\n"
    fibline += "Posterior(Bull): " + str.tostring(posterior_bull * 100.0, "#.#") + "%  |  Posterior(Bear): " + str.tostring(posterior_bear * 100.0, "#.#") + "%\n"
    fibline += "Edge: " + str.tostring(prob_edge * 100.0, "#.#") + "%  |  Zone Conf: " + (na(activeZoneConf) ? "—" : str.tostring(activeZoneConf * 100.0, "#") + "%") + "\n"
    string exec = ""
    if is_options_mode
        float cs = isBull ? nz(call_strike, close) : nz(put_strike, close)
        exec := "VANILLA\nStrike: " + _p(cs) + " (" + strike_mode + ")\nDist: " + f_dist_str(math.abs(cs - close)) + "\nExpiry: " + str.tostring(rec_expiry) + " min\n"
    else if is_mult_mode
        exec := "MULTIPLIER\nContract: " + deriv_mult_contract(isBull) + " (" + broker_mode + " · " + deriv_class + ")\nMultiplier: " + str.tostring(resolved_mult, "#") + "x" + (deriv_capped ? " CAPPED" : "") + "\nRisk: $" + str.tostring(risk_amount, "#.##") + "\n"
    else
        exec := "SIGNAL ONLY\n"
    float riskPts = math.abs(trail - close)
    float tp1_proj = isBull ? close + riskPts * tp1_r : close - riskPts * tp1_r
    float tp2_proj = isBull ? close + riskPts * tp2_r : close - riskPts * tp2_r
    float tp3_proj = isBull ? close + riskPts * tp3_r : close - riskPts * tp3_r
    string rr = "RR\nSL: " + _p(trail) + " (" + f_dist_str(riskPts) + ")\nTP1: " + _p(tp1_proj) + " (" + str.tostring(tp1_r, "#.#") + "R)\nTP2: " + _p(tp2_proj) + " (" + str.tostring(tp2_r, "#.#") + "R)\nTP3: " + _p(tp3_proj) + " (" + str.tostring(tp3_r, "#.#") + "R)\n"
    string ctx = "CONTEXT\nKZ: " + activeKz + "\nTime: " + _fmt_full_time(time) + " " + gmt_tz + "\n" + build_chart_link()
    head + " — Score " + str.tostring(sc) + "/8\nMode: " + mode + "\n" + exec + rr + fibline + why + ctx
 
build_trade_entry_tooltip(bool isBull, float p_entry, float p_sl, float p_tp1, float p_tp2, float p_tp3, float p_risk) =>
    float tp1Pts = math.abs(p_tp1 - p_entry)
    float tp2Pts = math.abs(p_tp2 - p_entry)
    float tp3Pts = math.abs(p_tp3 - p_entry)
    string out = (is_options_mode ? (isBull ? "CALL" : "PUT") : (isBull ? "LONG" : "SHORT")) + " ENTRY — " + exec_mode + "\n"
    out += "Score: " + str.tostring(isBull ? bull_score : bear_score) + "/8\n"
    out += "Posterior: Posterior(Bull) " + str.tostring(posterior_bull * 100.0, "#.#") + "% / Posterior(Bear) " + str.tostring(posterior_bear * 100.0, "#.#") + "%\n"
    out += "Entry Mode: " + entry_mode + "\n"
    out += "Entry: " + _p(p_entry) + "\n"
    out += "SL: " + _p(p_sl) + " → " + f_dist_str(p_risk) + "\n"
    out += "TP1 (" + str.tostring(tp1_r, "#.#") + "R): " + _p(p_tp1) + " → " + f_dist_str(tp1Pts) + "\n"
    out += "TP2 (" + str.tostring(tp2_r, "#.#") + "R): " + _p(p_tp2) + " → " + f_dist_str(tp2Pts) + "\n"
    out += "TP3 (" + str.tostring(tp3_r, "#.#") + "R): " + _p(p_tp3) + " → " + f_dist_str(tp3Pts) + "\n"
    if is_options_mode
        out += "Strike: " + _p(isBull ? nz(call_strike, close) : nz(put_strike, close)) + " Expiry: " + str.tostring(rec_expiry) + "m\n"
    else if is_mult_mode
        out += "Direction: " + deriv_mult_contract(isBull) + " Multiplier: " + str.tostring(resolved_mult, "#") + "x\nRisk: $" + str.tostring(risk_amount, "#.##") + "\n"
    out
 
// [U] VISUALS
Fi1 = plot(HULL, title="Macro Hull", color=color.new(hullColor, 50), linewidth=thicknesSwitch)
Fi2 = plot(visualSwitch ? HULL[2] : na, title="Macro Hull Band", color=color.new(hullColor, 50), linewidth=thicknesSwitch)
fill(Fi1, Fi2, title="Hull Band", color=color.new(hullColor, transpSwitch))
plot(HULL_FAST, "Fast Hull", color=color.new(LONG_COLOR, 40), linewidth=1)
plot(showFibBands ? u1_v : na, "Fib U1", color=color.new(SHORT_COLOR, 60), style=plot.style_linebr)
plot(showFibBands ? u4_v : na, "Fib U4", color=color.new(SHORT_COLOR, 30), style=plot.style_linebr)
plot(showFibBands ? l1_v : na, "Fib L1", color=color.new(LONG_COLOR, 60), style=plot.style_linebr)
plot(showFibBands ? l4_v : na, "Fib L4", color=color.new(LONG_COLOR, 30), style=plot.style_linebr)
p_trail = plot(trailTrend != trailTrend[1] ? na : trail, "Trail", color=trend_col, linewidth=2, style=plot.style_linebr)
p_ma    = plot(hMa, "Trail MA", color=color.new(trend_col, 100))
fill(p_trail, p_ma, trail, hMa, color.new(trend_col, 85), color.new(trend_col, 96), "Trend Cloud")
plotshape(showRawFlip and flip_bull ? trail : na, "Raw Buy",  shape.diamond, location.absolute, trail_gray ? color.gray : LONG_COLOR, size=size.tiny)
plotshape(showRawFlip and flip_bear ? trail : na, "Raw Sell", shape.diamond, location.absolute, trail_gray ? color.gray : SHORT_COLOR, size=size.tiny)
plotshape(showRejected and rej_bull ? trail : na, "Rej Bull", shape.xcross, location.absolute, color.new(color.gray, 20), size=size.tiny)
plotshape(showRejected and rej_bear ? trail : na, "Rej Bear", shape.xcross, location.absolute, color.new(color.gray, 20), size=size.tiny)
float sig_offset_px = hAtr * signalOffset
bool  fire_bull_label = (label_all_flips and flip_bull) or (not label_all_flips and trig_bull)
bool  fire_bear_label = (label_all_flips and flip_bear) or (not label_all_flips and trig_bear)
if showSignals and fire_bull_label
    label.new(bar_index, low - sig_offset_px, LONG_TAG, color = LONG_COLOR, textcolor = color.white, style = label.style_label_up, size = size.tiny, tooltip = build_signal_tooltip(true))
if showSignals and fire_bear_label
    label.new(bar_index, high + sig_offset_px, SHORT_TAG, color = SHORT_COLOR, textcolor = color.white, style = label.style_label_down, size = size.tiny, tooltip = build_signal_tooltip(false))
if showSignals and long_entry_signal
    label.new(bar_index, entry_px, is_options_mode ? "CALL ENTRY" : "LONG ENTRY", color = color.new(LONG_COLOR, 15), textcolor = color.white, style = label.style_label_left, size = size.tiny, tooltip = build_trade_entry_tooltip(true, entry_px, active_sl, tp1_px, tp2_px, tp3_px, initial_risk))
if showSignals and short_entry_signal
    label.new(bar_index, entry_px, is_options_mode ? "PUT ENTRY" : "SHORT ENTRY", color = color.new(SHORT_COLOR, 15), textcolor = color.white, style = label.style_label_left, size = size.tiny, tooltip = build_trade_entry_tooltip(false, entry_px, active_sl, tp1_px, tp2_px, tp3_px, initial_risk))
plotshape(showSmartSignals and newSmartBull, "Smart Bull", shape.triangleup, location.belowbar, LONG_COLOR, size=size.tiny, text="Smart")
plotshape(showSmartSignals and newSmartBear, "Smart Bear", shape.triangledown, location.abovebar, SHORT_COLOR, size=size.tiny, text="Smart")
plotshape(showSmartSignals and showRejectedSmart and rejectedBull, "SB Rej", shape.triangleup, location.belowbar, color.new(color.gray, 50), size=size.tiny)
plotshape(showSmartSignals and showRejectedSmart and rejectedBear, "SBe Rej", shape.triangledown, location.abovebar, color.new(color.gray, 50), size=size.tiny)
 
// [V] SMC EXECUTION
if showHighLowSwingsInput or showPremiumDiscountZonesInput
    updateTrailingExtremes()
    if showHighLowSwingsInput
        drawHighLowSwings()
    if showPremiumDiscountZonesInput
        drawPremiumDiscountZones()
if showFairValueGapsInput
    deleteFairValueGaps()
getCurrentStructure(swingsLengthInput, false)
getCurrentStructure(5, false, true)
if showEqualHighsLowsInput
    getCurrentStructure(equalHighsLowsLengthInput, true)
if showInternalsInput or showInternalOrderBlocksInput or showTrendInput
    displayStructure(true)
if showStructureInput or showSwingOrderBlocksInput or showHighLowSwingsInput
    displayStructure()
if showInternalOrderBlocksInput
    deleteOrderBlocks(true)
if showSwingOrderBlocksInput
    deleteOrderBlocks()
if showFairValueGapsInput
    drawFairValueGaps()
if barstate.islastconfirmedhistory or barstate.islast
    if showInternalOrderBlocksInput
        drawOrderBlocks(true)
    if showSwingOrderBlocksInput
        drawOrderBlocks()
lastBarIndex    := currentBarIndex
currentBarIndex := bar_index
 
// [W] HUD — ULTRON's self-portrait
string hudTextSize = f_labelSize(hudSizeIn)
var table dash = table.new(position.top_right, 2, 24, bgcolor=color.rgb(0, 0, 0, 80), border_width=1, border_color=color.silver, frame_width=1, frame_color=color.silver)
if barstate.islast and showHud
    table.cell(dash, 0, 0, "Absolute Dollar Agent", text_color=color.yellow, bgcolor=color.rgb(0, 0, 255, 50), text_size=hudTextSize)
    table.cell(dash, 1, 0, "ULTRON ALPHA", text_color=color.yellow, bgcolor=color.rgb(0, 0, 255, 50), text_size=hudTextSize)
    table.cell(dash, 0, 1, "Bull Score", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 1, str.tostring(bull_score) + " / 8", text_color=color.white, bgcolor=bull_score >= minScore ? LONG_COLOR : color.rgb(50,50,50), text_size=hudTextSize)
    table.cell(dash, 0, 2, "Bear Score", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 2, str.tostring(bear_score) + " / 8", text_color=color.white, bgcolor=bear_score >= minScore ? SHORT_COLOR : color.rgb(50,50,50), text_size=hudTextSize)
    string trailState = trail_gray ? "GRAY" : (trailTrend == 1 ? "BULL" : "BEAR")
    color  trailCellColor = trail_gray ? color.gray : (trailTrend == 1 ? LONG_COLOR : SHORT_COLOR)
    table.cell(dash, 0, 3, "Trail", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 3, trailState, text_color=color.white, bgcolor=trailCellColor, text_size=hudTextSize)
    table.cell(dash, 0, 4, "Ultron Gate", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 4, ultron_bull_clear ? "BULL" : ultron_bear_clear ? "BEAR" : "LOCKED", text_color=color.white, bgcolor=ultron_bull_clear ? LONG_COLOR : ultron_bear_clear ? SHORT_COLOR : color.gray, text_size=hudTextSize)
    string smcBiasStr   = swingTrend.bias == BULLISH ? "Bullish" : swingTrend.bias == BEARISH ? "Bearish" : "Neutral"
    color  smcBiasColor = swingTrend.bias == BULLISH ? LONG_COLOR : swingTrend.bias == BEARISH ? SHORT_COLOR : color.gray
    table.cell(dash, 0, 5, "SMC Bias", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 5, smcBiasStr, text_color=color.white, bgcolor=smcBiasColor, text_size=hudTextSize)
    table.cell(dash, 0, 6, "RSI", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 6, str.tostring(math.round(rsi, 0)) + " " + (smartBull_raw ? "B" : smartBear_raw ? "S" : "-"), text_color=color.white, bgcolor=smartBull_raw ? LONG_COLOR : smartBear_raw ? SHORT_COLOR : color.gray, text_size=hudTextSize)
    string smartState = newSmartBull ? "Smart Bull" : newSmartBear ? "Smart Bear" : (rejectedBull or rejectedBear) ? "Gated" : "—"
    color  smartBg    = newSmartBull ? LONG_COLOR : newSmartBear ? SHORT_COLOR : color.gray
    table.cell(dash, 0, 7, "Smart Signal", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 7, smartState, text_color=color.white, bgcolor=smartBg, text_size=hudTextSize)
    table.cell(dash, 0, 8, "EMA 21/55", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 8, ema21 > ema55 ? "Bullish" : "Bearish", text_color=color.white, bgcolor=ema21 > ema55 ? LONG_COLOR : SHORT_COLOR, text_size=hudTextSize)
    table.cell(dash, 0, 9, "Active KZ", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 9, activeKz, text_color=color.white, bgcolor=color.navy, text_size=hudTextSize)
    table.cell(dash, 0, 10, "PDH", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 10, not na(d_info.ph) ? str.tostring(d_info.ph, format.mintick) : "—", text_color=color.white, bgcolor=not na(d_info.ph) and close > d_info.ph ? LONG_COLOR : SHORT_COLOR, text_size=hudTextSize)
    table.cell(dash, 0, 11, "PDL", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 11, not na(d_info.pl) ? str.tostring(d_info.pl, format.mintick) : "—", text_color=color.white, bgcolor=not na(d_info.pl) and close < d_info.pl ? SHORT_COLOR : LONG_COLOR, text_size=hudTextSize)
    string swHighLabel = swingTrend.bias == BEARISH ? "Strong High" : "Weak High"
    string swLowLabel  = swingTrend.bias == BULLISH ? "Strong Low"  : "Weak Low"
    color  swHighColor = swingTrend.bias == BEARISH ? SHORT_COLOR : color.new(SHORT_COLOR, 40)
    color  swLowColor  = swingTrend.bias == BULLISH ? LONG_COLOR : color.new(LONG_COLOR, 40)
    table.cell(dash, 0, 12, "S/W High", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 12, not na(trailing.top) ? str.tostring(trailing.top, format.mintick) + " " + swHighLabel : "—", text_color=color.white, bgcolor=swHighColor, text_size=hudTextSize)
    table.cell(dash, 0, 13, "S/W Low", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 13, not na(trailing.bottom) ? str.tostring(trailing.bottom, format.mintick) + " " + swLowLabel : "—", text_color=color.white, bgcolor=swLowColor, text_size=hudTextSize)
    string spatialBias  = "NEUTRAL"
    color  spatialColor = color.gray
    if not na(d_info.ph) and not na(d_info.pl)
        float midRange = (d_info.ph + d_info.pl) / 2
        if close > d_info.ph
            spatialBias := "ABOVE PDH"
            spatialColor := LONG_COLOR
        else if close < d_info.pl
            spatialBias := "BELOW PDL"
            spatialColor := SHORT_COLOR
        else if close > midRange
            spatialBias := "UPPER HALF"
            spatialColor := color.new(LONG_COLOR, 40)
        else
            spatialBias := "LOWER HALF"
            spatialColor := color.new(SHORT_COLOR, 40)
    table.cell(dash, 0, 14, "Spatial Bias", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 14, spatialBias, text_color=color.white, bgcolor=spatialColor, text_size=hudTextSize)
    table.cell(dash, 0, 15, "Position", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    string posStr = trade_dir == 0 ? "No Active" : (trade_dir == 1 ? "LONG S" + str.tostring(trade_stage) + "/4" : "SHORT S" + str.tostring(trade_stage) + "/4")
    color  posBg  = trade_dir == 0 ? color.gray : (trade_dir == 1 ? LONG_COLOR : SHORT_COLOR)
    table.cell(dash, 1, 15, posStr, text_color=color.white, bgcolor=posBg, text_size=hudTextSize)
    table.cell(dash, 0, 16, "Exec Mode", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    string execStr = is_options_mode ? "Vanilla" : is_mult_mode ? "Mult " + str.tostring(resolved_mult, "#") + "x" : "Signal"
    color  execBg  = is_options_mode ? color.navy : is_mult_mode ? color.teal : color.gray
    table.cell(dash, 1, 16, execStr, text_color=color.white, bgcolor=execBg, text_size=hudTextSize)
    table.cell(dash, 0, 17, "Broker/Asset", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 17, broker_full, text_color=color.white, bgcolor=deriv_capped and broker_mode == "Deriv" ? color.orange : color.teal, text_size=hudTextSize)
    table.cell(dash, 0, 18, "Fib Regime", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    string ltfStr = trend_fib == 1 ? "B" : trend_fib == -1 ? "S" : "-"
    string htfStr = htf_trend_fib == 1 ? "B" : htf_trend_fib == -1 ? "S" : "-"
    string fibStr = "LTF " + ltfStr + " | " + resolved_htf + " " + htfStr + " | L:" + (fib_clear_long ? "OK" : "X") + " S:" + (fib_clear_short ? "OK" : "X")
    color  fibRowBg = htf_trend_fib == 1 and trend_fib == 1 ? LONG_COLOR : htf_trend_fib == -1 and trend_fib == -1 ? SHORT_COLOR : color.gray
    table.cell(dash, 1, 18, fibStr, text_color=color.white, bgcolor=fibRowBg, text_size=hudTextSize)
    table.cell(dash, 0, 19, "Posterior(Bull)", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 19, str.tostring(posterior_bull * 100.0, "#.#") + "%", text_color=color.white, bgcolor=posterior_bull >= probSignalFloor ? LONG_COLOR : posterior_bull >= 0.55 ? color.new(LONG_COLOR, 40) : color.rgb(50,50,50), text_size=hudTextSize)
    table.cell(dash, 0, 20, "Posterior(Bear)", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 20, str.tostring(posterior_bear * 100.0, "#.#") + "%", text_color=color.white, bgcolor=posterior_bear >= probSignalFloor ? SHORT_COLOR : posterior_bear >= 0.55 ? color.new(SHORT_COLOR, 40) : color.rgb(50,50,50), text_size=hudTextSize)
    table.cell(dash, 0, 21, "Prob Edge", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    table.cell(dash, 1, 21, str.tostring(prob_edge * 100.0, "#.#") + "%", text_color=color.white, bgcolor=prob_edge >= 0.30 ? color.teal : prob_edge >= 0.15 ? color.navy : color.gray, text_size=hudTextSize)
    table.cell(dash, 0, 22, "Zone Confidence", text_color=color.white, bgcolor=color.black, text_size=hudTextSize)
    string zcStr = na(activeZoneConf) ? "—" : str.tostring(activeZoneConf * 100.0, "#") + "% " + (activeZoneConf >= 0.75 ? "H" : activeZoneConf >= 0.50 ? "M" : activeZoneConf >= 0.25 ? "L" : "-")
    color  zcBg  = na(activeZoneConf) ? color.gray : activeZoneConf >= 0.75 ? color.yellow : activeZoneConf >= 0.50 ? color.orange : color.new(color.gray, 30)
    table.cell(dash, 1, 22, zcStr, text_color=color.white, bgcolor=zcBg, text_size=hudTextSize)
    table.cell(dash, 0, 23, "ADI Neural Spatial Engine", text_color=color.new(color.white, 70), bgcolor=color(na), text_size=hudTextSize)
    table.cell(dash, 1, 23, "ULTRON Alpha", text_color=color.new(color.white, 70), bgcolor=color(na), text_size=hudTextSize)
 
// [X] TELEGRAM AGENT — ULTRON's narration. Five families: analysis report,
// neural trigger, informational, fib-blocked, trade event. Consolidated
// dispatch ensures at most ONE message per bar (trade events take priority).
build_analysis_report() =>
    string out = ""
    out += "ULTRON ANALYSIS\n"
    out += _fmt_full_time(time) + " " + gmt_tz + "\n"
    out += syminfo.ticker + " @ " + _p(close) + "\n"
    out += "Mode: " + exec_mode + " | Broker: " + broker_mode + "\n"
    out += "Asset Class: " + deriv_class + "\n"
    out += build_chart_link() + "\n\n"
    out += "MACRO PRE-FLIGHT\n"
    string smcBiasTxt = swingTrend.bias == BULLISH ? "BULLISH" : swingTrend.bias == BEARISH ? "BEARISH" : "NEUTRAL"
    out += "SMC Bias: " + smcBiasTxt + " (CHoCH Confirmed)\n"
    out += "Active KZ: " + activeKz + "\n"
    out += "Macro Hull: " + (hull_bull ? "BULLISH" : hull_bear ? "BEARISH" : "FLAT") + "\n"
    out += "Ultron Gate: " + (ultron_bull_clear ? "BULL UNLOCKED" : ultron_bear_clear ? "BEAR UNLOCKED" : "LOCKED") + "\n"
    out += "Trail: " + (trail_gray ? "GRAY" : trailTrend == 1 ? "BULLISH" : "BEARISH") + " (" + _p(trail) + ")\n\n"
    out += "SPATIAL INTELLIGENCE\n"
    out += "Strong High: " + (not na(trailing.top) ? _p(trailing.top) : "—") + "\n"
    out += "Strong Low: " + (not na(trailing.bottom) ? _p(trailing.bottom) : "—") + "\n"
    out += "PDH: " + (not na(d_info.ph) ? _p(d_info.ph) : "—") + " | PDL: " + (not na(d_info.pl) ? _p(d_info.pl) : "—") + "\n"
    out += "Nearest H-LIQ: " + (not na(nearestH_lq) ? _p(nearestH_lq) : "—") + "\n"
    out += "Nearest L-LIQ: " + (not na(nearestL_lq) ? _p(nearestL_lq) : "—") + "\n"
    out += "Active CHoCH Zone: " + (chochActive ? _p(curZoneHigh) + " - " + _p(curZoneLow) : "None") + "\n\n"
    out += "NEURAL CONFLUENCE (8 NODES)\n"
    out += "Bull Score: " + str.tostring(bull_score) + " / 8  " + (bull_score >= minScore ? "(TRIGGERED)" : "(BLOCKED)") + "\n"
    out += "Bear Score: " + str.tostring(bear_score) + " / 8  " + (bear_score >= minScore ? "(TRIGGERED)" : "(BLOCKED)") + "\n\n"
    out += "SPECULATIVE PROBABILISTIC CORE (14 NODES)\n"
    out += "Posterior(Bull): " + str.tostring(posterior_bull * 100.0, "#.#") + "%" + (posterior_bull >= probSignalFloor ? " HIGH CONVICTION" : "") + "\n"
    out += "Posterior(Bear): " + str.tostring(posterior_bear * 100.0, "#.#") + "%" + (posterior_bear >= probSignalFloor ? " HIGH CONVICTION" : "") + "\n"
    out += "Prob Edge: " + str.tostring(prob_edge * 100.0, "#.#") + "%\n"
    out += "Zone Confidence: " + (na(activeZoneConf) ? "—" : str.tostring(activeZoneConf * 100.0, "#") + "%") + "\n"
    out += "Zone Quality Gate: " + (useZoneQuality ? "ON (min " + str.tostring(minZoneAtr, "#.#") + " ATR, ext " + str.tostring(extAtrGuard, "#.#") + " ATR)" : "OFF") + "\n\n"
    out += "FIB INTELLIGENCE (" + htf_fib_mode + ")\n"
    out += "HTF: " + resolved_htf + "\n"
    out += "LTF regime: " + (trend_fib == 1 ? "BULL" : trend_fib == -1 ? "BEAR" : "FLAT") + " | " + str.tostring(fib_bars_since_flip) + "b since flip\n"
    out += "HTF regime: " + (htf_trend_fib == 1 ? "BULL" : htf_trend_fib == -1 ? "BEAR" : "FLAT") + " | " + str.tostring(htf_bars_since_flip) + "b since flip\n"
    out += "Gate: Long " + (fib_clear_long ? "PASS" : "BLOCKED") + " | Short " + (fib_clear_short ? "PASS" : "BLOCKED") + "\n"
    if fib_override_long or fib_override_short
        out += "Soft override (score ≥ 7)\n"
    out += "\n"
    if is_execution_mode
        out += "EXECUTION CONTEXT\n"
        if is_options_mode
            out += "Product: Vanilla Options\n"
            out += "Strike Mode: " + strike_mode + "\n"
            out += "CALL Strike: " + (not na(call_strike) ? _p(call_strike) : "—") + "\n"
            out += "PUT Strike: " + (not na(put_strike) ? _p(put_strike) : "—") + "\n"
            out += "Suggested Expiry: " + str.tostring(rec_expiry) + " min\n"
            out += "Scale-Ins Max: " + str.tostring(max_scale_ins) + " (used " + str.tostring(opt_scaleCount) + ")\n"
        else
            out += "Product: Multipliers\n"
            out += "Broker: " + broker_mode + " | Asset Class: " + deriv_class + "\n"
            out += "Preset: " + mult_preset + (deriv_capped and broker_mode == "Deriv" ? " [CLAMPED cap " + str.tostring(deriv_cap) + "x]" : "") + "\n"
            out += "Suggested Multiplier: " + str.tostring(resolved_mult, "#") + "x\n"
            out += "Risk per Trade: $" + str.tostring(risk_amount, "#.##") + "\n"
            out += "Contract Map: Long→" + deriv_mult_contract(true) + " | Short→" + deriv_mult_contract(false) + "\n"
            if suggest_deal_cancel and broker_mode == "Deriv" and deriv_dc_ok
                out += "Deal Cancellation: AVAILABLE\n"
            else if suggest_deal_cancel and broker_mode == "Deriv" and not deriv_dc_ok
                out += "Deal Cancellation: NOT supported on " + deriv_class + "\n"
        out += "\n"
    out += "EXECUTION & SIGNALS\n"
    out += "Entry Mode: " + entry_mode + "\n"
    out += "Raw Trail Flip: " + (flip_bull ? "BULLISH" : flip_bear ? "BEARISH" : "—") + "\n"
    out += "Smart Signal: " + (newSmartBull ? "Bull" : newSmartBear ? "Bear" : (rejectedBull or rejectedBear) ? "Gated" : "—") + "\n"
    out += "Neural Trigger: " + (trig_bull ? LONG_TAG + " TRIGGERED" : trig_bear ? SHORT_TAG + " TRIGGERED" : "—") + "\n\n"
    if trade_dir != 0
        out += "ACTIVE POSITION\n"
        out += "Dir: " + (trade_dir == 1 ? (is_options_mode ? "CALL" : "LONG") : (is_options_mode ? "PUT" : "SHORT")) + " | Stage: " + str.tostring(trade_stage) + "/4\n"
        out += "Entry: " + _p(entry_px) + " | SL: " + _p(active_sl) + "\n"
        float riskPts = math.abs(entry_px - active_sl)
        out += "Risk: " + f_dist_str(riskPts) + "\n"
        out += "TP1: " + _p(tp1_px) + " (" + f_rr_str(tp1_r, math.abs(tp1_px - entry_px)) + ")" + (trade_stage >= 2 ? " HIT" : "") + "\n"
        out += "TP2: " + _p(tp2_px) + " (" + f_rr_str(tp2_r, math.abs(tp2_px - entry_px)) + ")" + (trade_stage >= 3 ? " HIT" : "") + "\n"
        out += "TP3: " + _p(tp3_px) + " (" + f_rr_str(tp3_r, math.abs(tp3_px - entry_px)) + ")" + (trade_stage >= 4 ? " HIT" : "") + "\n"
        float price_move = trade_dir == 1 ? close - entry_px : entry_px - close
        float open_r     = price_move / nz(initial_risk, 1)
        out += "Live P&L: " + f_rr_str(open_r, price_move) + "\n\n"
    out += "RECENT EVENTS (Episodic Memory)\n"
    int mem_count = math.min(array.size(mem_event), 10)
    if mem_count == 0
        out += "No events recorded yet.\n"
    if mem_count > 0
        for i = 0 to mem_count - 1
            int idx = array.size(mem_event) - 1 - i
            int dir_val = array.get(mem_dir, idx)
            out += _fmt_time(array.get(mem_time, idx)) + " " + (dir_val == 1 ? "+" : dir_val == -1 ? "-" : "·") + " " + array.get(mem_event, idx) + " @ " + _p(array.get(mem_level, idx)) + "\n"
    out
 
build_neural_trigger_alert(bool isBull) =>
    int sc = isBull ? bull_score : bear_score
    string tag = isBull ? LONG_TAG : SHORT_TAG
    string out = "NEURAL " + tag + " SIGNAL\n"
    out += syminfo.ticker + " @ " + _p(close) + "\n"
    out += "Score: " + str.tostring(sc) + "/8 (min " + str.tostring(minScore) + ")\n"
    out += "Mode: " + exec_mode + " | Broker: " + broker_mode + "\n"
    if is_options_mode
        float cs = isBull ? nz(call_strike, close) : nz(put_strike, close)
        out += "Strike: " + _p(cs) + " (" + strike_mode + ")\n"
        out += "Strike Dist: " + f_dist_str(math.abs(cs - close)) + "\n"
        out += "Expiry: " + str.tostring(rec_expiry) + " min\n"
    else if is_mult_mode
        out += "Contract: " + deriv_mult_contract(isBull) + " @ " + str.tostring(resolved_mult, "#") + "x" + (deriv_capped and broker_mode == "Deriv" ? " [CLAMPED]" : "") + "\n"
        out += "Risk: $" + str.tostring(risk_amount, "#.##") + "\n"
    out += "WHY\n"
    out += (isBull and hull_bull) or (not isBull and hull_bear) ? "✓ Macro Hull\n" : "✗ Macro Hull\n"
    out += (isBull and fast_bull) or (not isBull and fast_bear) ? "✓ Fast Hull\n" : "✗ Fast Hull\n"
    out += (isBull and trailTrend == 1) or (not isBull and trailTrend == -1) ? "✓ Trail\n" : "✗ Trail\n"
    out += chochActive and ((isBull and activeDir == 1) or (not isBull and activeDir == -1)) ? "✓ CHoCH\n" : "· CHoCH inactive\n"
    out += (isBull and mom_bull) or (not isBull and mom_bear) ? "✓ Momentum\n" : "✗ Momentum\n"
    out += (isBull and ultron_bull_clear) or (not isBull and ultron_bear_clear) ? "✓ Ultron Gate\n" : "✗ Ultron Gate LOCKED\n"
    out += vol_ok ? "✓ Volume\n" : "· Volume low\n"
    out += "FIB (" + htf_fib_mode + ")\n"
    out += "LTF: " + (trend_fib == 1 ? "BULL" : trend_fib == -1 ? "BEAR" : "FLAT") + " (" + str.tostring(fib_bars_since_flip) + "b)\n"
    out += "HTF(" + resolved_htf + "): " + (htf_trend_fib == 1 ? "BULL" : htf_trend_fib == -1 ? "BEAR" : "FLAT") + " (" + str.tostring(htf_bars_since_flip) + "b)\n"
    out += "POSTERIOR\n"
    out += "Posterior(Bull): " + str.tostring(posterior_bull * 100.0, "#.#") + "%  |  Posterior(Bear): " + str.tostring(posterior_bear * 100.0, "#.#") + "%\n"
    out += "Edge: " + str.tostring(prob_edge * 100.0, "#.#") + "%  |  Zone Conf: " + (na(activeZoneConf) ? "—" : str.tostring(activeZoneConf * 100.0, "#") + "%") + "\n"
    float riskPts = math.abs(trail - close)
    out += "RISK\nSL: " + _p(trail) + " (" + f_dist_str(riskPts) + ")\n"
    out += _fmt_full_time(time) + " " + gmt_tz + "\n" + build_chart_link() + "\n"
    if trade_dir != 0
        out += "Position already open — informational\n"
    out
 
build_signal_alert(bool isBull) =>
    string sig = is_options_mode ? (isBull ? "CALL SIGNAL" : "PUT SIGNAL") : (isBull ? "BUY SIGNAL" : "SELL SIGNAL")
    float refRisk = math.abs(close - trail)
    string out = sig + " — informational\n"
    out += syminfo.ticker + " @ " + _p(close) + "\n"
    out += "Mode: " + exec_mode + "\n"
    out += "Ref SL: " + _p(trail) + " (" + f_dist_str(refRisk) + ")\n"
    out += "TP1 (" + str.tostring(tp1_r, "#.#") + "R): " + f_dist_str(refRisk * tp1_r) + "\n"
    out += "TP2 (" + str.tostring(tp2_r, "#.#") + "R): " + f_dist_str(refRisk * tp2_r) + "\n"
    out += "TP3 (" + str.tostring(tp3_r, "#.#") + "R): " + f_dist_str(refRisk * tp3_r) + "\n"
    out += "Score: " + str.tostring(isBull ? bull_score : bear_score) + "/8\n"
    out += "Fib: LTF " + (trend_fib == 1 ? "B" : trend_fib == -1 ? "S" : "-") + " | HTF " + (htf_trend_fib == 1 ? "B" : htf_trend_fib == -1 ? "S" : "-") + "\n"
    out += "Posterior: Posterior(Bull) " + str.tostring(posterior_bull * 100.0, "#.#") + "% | Posterior(Bear) " + str.tostring(posterior_bear * 100.0, "#.#") + "% | Edge " + str.tostring(prob_edge * 100.0, "#.#") + "%\n"
    out += "Position: " + (trade_dir == 0 ? "Flat" : (trade_dir == 1 ? "Already LONG" : "Already SHORT")) + "\n"
    out += _fmt_full_time(time) + " " + gmt_tz + "\n" + build_chart_link() + "\n"
    out
 
build_fib_blocked_alert(bool isBull) =>
    string tag = isBull ? (is_options_mode ? "CALL" : "BUY") : (is_options_mode ? "PUT" : "SELL")
    float refRisk = math.abs(close - trail)
    string blockReason = "gate disagreement"
    if isBull and use_htf_source and not htf_gate_long
        blockReason := "HTF Fib bearish (" + resolved_htf + ")"
    else if not isBull and use_htf_source and not htf_gate_short
        blockReason := "HTF Fib bullish (" + resolved_htf + ")"
    else if isBull and use_ltf_source and not ltf_gate_long
        blockReason := "LTF Fib bearish"
    else if not isBull and use_ltf_source and not ltf_gate_short
        blockReason := "LTF Fib bullish"
    else if isBull and not htf_cool_long
        blockReason := "HTF cooldown (" + str.tostring(htf_bars_since_flip) + "b)"
    else if not isBull and not htf_cool_short
        blockReason := "HTF cooldown (" + str.tostring(htf_bars_since_flip) + "b)"
    else if isBull and not fib_cool_long
        blockReason := "LTF cooldown (" + str.tostring(fib_bars_since_flip) + "b)"
    else if not isBull and not fib_cool_short
        blockReason := "LTF cooldown (" + str.tostring(fib_bars_since_flip) + "b)"
    else if isBull and not htf_band_long
        blockReason := "Price below HTF basis"
    else if not isBull and not htf_band_short
        blockReason := "Price above HTF basis"
    string out = "ULTRON SEES " + tag + " — FIB BLOCKED\n"
    out += syminfo.ticker + " @ " + _p(close) + "\n"
    out += "Score: " + str.tostring(isBull ? bull_score : bear_score) + "/8\n"
    out += "Mode: " + exec_mode + "\n"
    out += "LTF Fib: " + (trend_fib == 1 ? "BULL" : trend_fib == -1 ? "BEAR" : "FLAT") + "\n"
    out += "HTF Fib (" + resolved_htf + "): " + (htf_trend_fib == 1 ? "BULL" : htf_trend_fib == -1 ? "BEAR" : "FLAT") + "\n"
    out += "Reason: " + blockReason + "\n"
    out += "Posterior: Posterior(Bull) " + str.tostring(posterior_bull * 100.0, "#.#") + "% / Posterior(Bear) " + str.tostring(posterior_bear * 100.0, "#.#") + "%\n"
    out += "Ref SL: " + _p(trail) + " (" + f_dist_str(refRisk) + ")\n"
    out += "Observation only — no execution\n"
    out += _fmt_full_time(time) + " " + gmt_tz + "\n" + build_chart_link() + "\n"
    out
 
build_trade_event_alert(string event_type, bool from_flip) =>
    string out = ""
    bool isBull = event_type == "long_entry" or event_type == "long_tp1" or event_type == "long_tp2" or event_type == "long_tp3" or event_type == "long_exit"
    string tag_head = is_options_mode ? (isBull ? "CALL" : "PUT") : is_mult_mode ? (isBull ? deriv_mult_contract(true) : deriv_mult_contract(false)) : (isBull ? "LONG" : "SHORT")
    int    score_val = isBull ? bull_score : bear_score
    if event_type == "long_entry" or event_type == "short_entry"
        out += tag_head + " ENTRY " + (from_flip ? "[FLIP]" : "[FILTERED]") + "\n"
        out += syminfo.ticker + " @ " + _p(entry_px) + "\n"
        out += "Score: " + str.tostring(score_val) + "/8\n"
        out += "Posterior: Posterior(Bull) " + str.tostring(posterior_bull * 100.0, "#.#") + "% | Posterior(Bear) " + str.tostring(posterior_bear * 100.0, "#.#") + "%\n"
        out += "Mode: " + exec_mode + " | Entry: " + entry_mode + "\n"
        if is_options_mode
            out += "Strike: " + _p(isBull ? nz(call_strike, close) : nz(put_strike, close)) + " (" + strike_mode + ")\n"
            out += "Expiry: " + str.tostring(rec_expiry) + " min\n"
        else if is_mult_mode
            out += "Contract: " + deriv_mult_contract(isBull) + " @ " + str.tostring(resolved_mult, "#") + "x\n"
            out += "Risk: $" + str.tostring(risk_amount, "#.##") + "\n"
            if suggest_deal_cancel and broker_mode == "Deriv" and deriv_dc_ok
                out += "Deal Cancellation: available\n"
            else if suggest_deal_cancel and broker_mode == "Deriv" and not deriv_dc_ok
                out += "Deal Cancellation: NOT supported\n"
        out += "SL: " + _p(active_sl) + " (risk " + f_dist_str(math.abs(entry_px - trail)) + ")\n"
        out += "TP1: " + _p(tp1_px) + " (reward " + f_dist_str(math.abs(tp1_px - entry_px)) + " · " + str.tostring(tp1_r, "#.#") + "R)\n"
        out += "TP2: " + _p(tp2_px) + " (reward " + f_dist_str(math.abs(tp2_px - entry_px)) + " · " + str.tostring(tp2_r, "#.#") + "R)\n"
        out += "TP3: " + _p(tp3_px) + " (reward " + f_dist_str(math.abs(tp3_px - entry_px)) + " · " + str.tostring(tp3_r, "#.#") + "R)\n"
        out += "RR: 1 : " + str.tostring(tp1_r, "#.#") + " : " + str.tostring(tp2_r, "#.#") + " : " + str.tostring(tp3_r, "#.#") + "\n"
        out += "Fib: LTF " + (trend_fib == 1 ? "B" : trend_fib == -1 ? "S" : "-") + " | HTF " + (htf_trend_fib == 1 ? "B" : htf_trend_fib == -1 ? "S" : "-") + "\n"
        out += _fmt_full_time(time) + " " + gmt_tz + "\n" + build_chart_link() + "\n"
    else if event_type == "long_tp1" or event_type == "short_tp1"
        out += tag_head + " TP1 HIT @ " + _p(tp1_px) + "\n"
        out += "Captured: " + f_rr_str(tp1_r, math.abs(tp1_px - entry_px)) + "\n"
        out += "SL → Breakeven (" + _p(entry_px) + ")\n"
        out += _fmt_full_time(time) + "\n"
    else if event_type == "long_tp2" or event_type == "short_tp2"
        out += tag_head + " TP2 HIT @ " + _p(tp2_px) + "\n"
        out += "Captured: " + f_rr_str(tp2_r, math.abs(tp2_px - entry_px)) + "\n"
        out += "SL → TP1 (" + _p(tp1_px) + ")\n"
        out += _fmt_full_time(time) + "\n"
    else if event_type == "long_tp3" or event_type == "short_tp3"
        out += tag_head + " TP3 HIT @ " + _p(tp3_px) + "\n"
        out += "Captured: " + f_rr_str(tp3_r, math.abs(tp3_px - entry_px)) + "\n"
        out += "Runner mode — trail only\n"
        out += _fmt_full_time(time) + "\n"
    else if event_type == "long_exit" or event_type == "short_exit"
        float exit_px = nz(last_exit_price, close)
        float pts     = isBull ? exit_px - entry_px : entry_px - exit_px
        float r       = pts / nz(initial_risk, 1)
        bool  sl_hit  = isBull ? last_sl_hit_long : last_sl_hit_short
        out += "EXIT " + tag_head + " @ " + _p(exit_px) + "\n"
        out += "Triggered: " + (sl_hit ? "Stop Loss" : "Trail Flip") + "\n"
        out += "Result: " + f_rr_str(r, pts) + "\n"
        out += _fmt_full_time(time) + "\n"
    out
 
// ── CONSOLIDATED DISPATCH — one message per bar. Priority: trade events
//    > neural triggers > informational > fib-blocked > scale-ins. Raw JSON
//    is opt-in (send_json_payloads) to keep the Telegram chat clean.
bool new_session_open = false
if use_asia   and inAsia   and not inAsia[1]
    new_session_open := true
if use_london and inLondon and not inLondon[1]
    new_session_open := true
if use_nyam   and inNyam   and not inNyam[1]
    new_session_open := true
if use_nylu   and inNylu   and not inNylu[1]
    new_session_open := true
if use_nypm   and inNypm   and not inNypm[1]
    new_session_open := true
bool is_h1_close = timeframe.change("60")
bool is_h4_close = timeframe.change("240")
bool should_analyze = false
if agent_enabled and barstate.isconfirmed
    if send_on_session and new_session_open
        should_analyze := true
    if send_on_h1 and is_h1_close
        should_analyze := true
    if send_on_h4 and is_h4_close
        should_analyze := true
 
if agent_enabled and barstate.isconfirmed and str.length(tg_chat_id) > 0
    bool _sent = false
 
    // Priority 0 — scheduled analysis (fires independently)
    if should_analyze
        alert(tg_json_report(tg_chat_id, build_analysis_report()), alert.freq_once_per_bar_close)
 
    // Priority 1 — trade events
    if send_on_signal and not _sent
        if long_entry_signal
            alert(tg_json_report(tg_chat_id, build_trade_event_alert("long_entry", flip_bull and not trig_bull)), alert.freq_once_per_bar_close)
            _sent := true
        else if short_entry_signal
            alert(tg_json_report(tg_chat_id, build_trade_event_alert("short_entry", flip_bear and not trig_bear)), alert.freq_once_per_bar_close)
            _sent := true
        else if long_tp1_signal
            alert(tg_json_report(tg_chat_id, build_trade_event_alert("long_tp1", false)), alert.freq_once_per_bar_close)
            _sent := true
        else if short_tp1_signal
            alert(tg_json_report(tg_chat_id, build_trade_event_alert("short_tp1", false)), alert.freq_once_per_bar_close)
            _sent := true
        else if long_tp2_signal
            alert(tg_json_report(tg_chat_id, build_trade_event_alert("long_tp2", false)), alert.freq_once_per_bar_close)
            _sent := true
        else if short_tp2_signal
            alert(tg_json_report(tg_chat_id, build_trade_event_alert("short_tp2", false)), alert.freq_once_per_bar_close)
            _sent := true
        else if long_tp3_signal
            alert(tg_json_report(tg_chat_id, build_trade_event_alert("long_tp3", false)), alert.freq_once_per_bar_close)
            _sent := true
        else if short_tp3_signal
            alert(tg_json_report(tg_chat_id, build_trade_event_alert("short_tp3", false)), alert.freq_once_per_bar_close)
            _sent := true
        else if long_exit_signal
            alert(tg_json_report(tg_chat_id, build_trade_event_alert("long_exit", false)), alert.freq_once_per_bar_close)
            _sent := true
        else if short_exit_signal
            alert(tg_json_report(tg_chat_id, build_trade_event_alert("short_exit", false)), alert.freq_once_per_bar_close)
            _sent := true
 
    // Priority 2 — neural triggers
    if alert_verbosity != "Trade Events Only" and send_on_signal and alert_neural_triggers and not _sent
        if trig_bull
            alert(tg_json_report(tg_chat_id, build_neural_trigger_alert(true)), alert.freq_once_per_bar_close)
            _sent := true
        else if trig_bear
            alert(tg_json_report(tg_chat_id, build_neural_trigger_alert(false)), alert.freq_once_per_bar_close)
            _sent := true
 
    // Priority 3 — informational (All mode only)
    if alert_verbosity == "All" and send_on_signal and alert_informational and not _sent
        if trig_bull and not long_entry_signal
            alert(tg_json_report(tg_chat_id, build_signal_alert(true)), alert.freq_once_per_bar_close)
            _sent := true
        else if trig_bear and not short_entry_signal
            alert(tg_json_report(tg_chat_id, build_signal_alert(false)), alert.freq_once_per_bar_close)
            _sent := true
 
    // Priority 4 — fib-blocked (All mode only)
    if alert_verbosity == "All" and send_on_signal and alert_fib_blocked and not _sent
        if flip_bull and not trig_bull
            alert(tg_json_report(tg_chat_id, build_fib_blocked_alert(true)), alert.freq_once_per_bar_close)
            _sent := true
        else if flip_bear and not trig_bear
            alert(tg_json_report(tg_chat_id, build_fib_blocked_alert(false)), alert.freq_once_per_bar_close)
            _sent := true
 
    // Priority 5 — scale-ins & regime exits
    if is_execution_mode and not _sent
        if scale_in_call
            alert(tg_json_report(tg_chat_id, (is_options_mode ? "CALL" : "LONG") + " SCALE-IN #" + str.tostring(opt_scaleCount) + " @ " + _p(close)), alert.freq_once_per_bar_close)
            _sent := true
        else if scale_in_put
            alert(tg_json_report(tg_chat_id, (is_options_mode ? "PUT" : "SHORT") + " SCALE-IN #" + str.tostring(opt_scaleCount) + " @ " + _p(close)), alert.freq_once_per_bar_close)
            _sent := true
        else if regime_call_exit
            alert(tg_json_report(tg_chat_id, "EXIT " + (is_options_mode ? "CALL" : "LONG") + " — Regime Shift @ " + _p(close)), alert.freq_once_per_bar_close)
            _sent := true
        else if regime_put_exit
            alert(tg_json_report(tg_chat_id, "EXIT " + (is_options_mode ? "PUT" : "SHORT") + " — Regime Shift @ " + _p(close)), alert.freq_once_per_bar_close)
            _sent := true
 
    // Priority 6 — raw JSON (opt-in, webhook consumers only)
    if send_json_payloads and alert_neural_triggers and not _sent
        if trig_bull
            string act = is_options_mode ? "CALL" : "BUY"
            string json_payload = '{"action":"' + act + '","ticker":"' + syminfo.ticker + '","price":' + str.tostring(close, format.mintick) + ',"score":' + str.tostring(bull_score) + ',"posterior_bull":' + str.tostring(posterior_bull, "#.###") + ',"prob_edge":' + str.tostring(prob_edge, "#.###") + ',"mode":"' + exec_mode + '","broker":"' + broker_mode + '","deriv_class":"' + deriv_class + '","mult":' + str.tostring(resolved_mult, "#") + ',"capped":' + str.tostring(deriv_capped) + ',"sl_dist_pts":' + str.tostring(f_points(math.abs(trail - close)), "#.#") + ',"fib_ltf":"' + str.tostring(trend_fib) + '","fib_htf":"' + str.tostring(htf_trend_fib) + '"}'
            alert(tg_json_report(tg_chat_id, json_payload), alert.freq_once_per_bar_close)
            _sent := true
        else if trig_bear
            string act = is_options_mode ? "PUT" : "SELL"
            string json_payload = '{"action":"' + act + '","ticker":"' + syminfo.ticker + '","price":' + str.tostring(close, format.mintick) + ',"score":' + str.tostring(bear_score) + ',"posterior_bear":' + str.tostring(posterior_bear, "#.###") + ',"prob_edge":' + str.tostring(prob_edge, "#.###") + ',"mode":"' + exec_mode + '","broker":"' + broker_mode + '","deriv_class":"' + deriv_class + '","mult":' + str.tostring(resolved_mult, "#") + ',"capped":' + str.tostring(deriv_capped) + ',"sl_dist_pts":' + str.tostring(f_points(math.abs(trail - close)), "#.#") + ',"fib_ltf":"' + str.tostring(trend_fib) + ',"fib_htf":"' + str.tostring(htf_trend_fib) + '"}'
            alert(tg_json_report(tg_chat_id, json_payload), alert.freq_once_per_bar_close)
            _sent := true
 
    // Priority 7 — raw JSON entry payload (opt-in)
    if send_json_payloads and not _sent
        if long_entry_signal
            string act = is_options_mode ? "CALL" : "BUY"
            string json_payload = '{"action":"' + act + '","ticker":"' + syminfo.ticker + '","entry":' + str.tostring(entry_px, format.mintick) + ',"sl":' + str.tostring(active_sl, format.mintick) + ',"sl_pts":' + str.tostring(f_points(initial_risk), "#.#") + ',"tp1_r":' + str.tostring(tp1_r, "#.#") + ',"mode":"' + exec_mode + '","entry_mode":"' + entry_mode + '","fib_ltf":"' + str.tostring(trend_fib) + '","fib_htf":"' + str.tostring(htf_trend_fib) + '"}'
            alert(tg_json_report(tg_chat_id, json_payload), alert.freq_once_per_bar_close)
            _sent := true
        else if short_entry_signal
            string act = is_options_mode ? "PUT" : "SELL"
            string json_payload = '{"action":"' + act + '","ticker":"' + syminfo.ticker + '","entry":' + str.tostring(entry_px, format.mintick) + ',"sl":' + str.tostring(active_sl, format.mintick) + ',"sl_pts":' + str.tostring(f_points(initial_risk), "#.#") + ',"tp1_r":' + str.tostring(tp1_r, "#.#") + ',"mode":"' + exec_mode + '","entry_mode":"' + entry_mode + '","fib_ltf":"' + str.tostring(trend_fib) + '","fib_htf":"' + str.tostring(htf_trend_fib) + '"}'
            alert(tg_json_report(tg_chat_id, json_payload), alert.freq_once_per_bar_close)
            _sent := true
 
// Memory capture
if chochSignal
    add_memory(activeDir == 1 ? "Bullish CHoCH" : "Bearish CHoCH", close, curZoneHigh, activeDir, activeKz)
if flip_bull
    add_memory("Trail Flip Bull", close, trail, 1, activeKz)
if flip_bear
    add_memory("Trail Flip Bear", close, trail, -1, activeKz)
if trig_bull
    add_memory("Neural " + LONG_TAG + " Trigger", close, trail, 1, activeKz)
if trig_bear
    add_memory("Neural " + SHORT_TAG + " Trigger", close, trail, -1, activeKz)
if long_entry_signal
    add_memory("Entry " + LONG_TAG, close, active_sl, 1, activeKz)
if short_entry_signal
    add_memory("Entry " + SHORT_TAG, close, active_sl, -1, activeKz)
if long_tp1_signal
    add_memory(LONG_TAG + " TP1 Hit", close, tp1_px, 1, activeKz)
if long_tp2_signal
    add_memory(LONG_TAG + " TP2 Hit", close, tp2_px, 1, activeKz)
if long_tp3_signal
    add_memory(LONG_TAG + " TP3 Hit", close, tp3_px, 1, activeKz)
if short_tp1_signal
    add_memory(SHORT_TAG + " TP1 Hit", close, tp1_px, -1, activeKz)
if short_tp2_signal
    add_memory(SHORT_TAG + " TP2 Hit", close, tp2_px, -1, activeKz)
if short_tp3_signal
    add_memory(SHORT_TAG + " TP3 Hit", close, tp3_px, -1, activeKz)
if long_exit_signal
    add_memory("Exit " + LONG_TAG, close, last_exit_price, 0, activeKz)
if short_exit_signal
    add_memory("Exit " + SHORT_TAG, close, last_exit_price, 0, activeKz)
 
// [Y] NATIVE ALERT CONDITIONS
alertcondition(trig_bull,                       "Neural Long Signal",   "Neural Long Signal on {{ticker}}")
alertcondition(trig_bear,                       "Neural Short Signal",  "Neural Short Signal on {{ticker}}")
alertcondition(long_entry_signal,               "Position Long Entry",  "Position Long Entry on {{ticker}}")
alertcondition(short_entry_signal,              "Position Short Entry", "Position Short Entry on {{ticker}}")
alertcondition(long_tp1_signal,                 "Long TP1 Hit",         "Long TP1 Hit on {{ticker}}")
alertcondition(long_tp2_signal,                 "Long TP2 Hit",         "Long TP2 Hit on {{ticker}}")
alertcondition(long_tp3_signal,                 "Long TP3 Hit",         "Long TP3 Hit on {{ticker}}")
alertcondition(short_tp1_signal,                "Short TP1 Hit",        "Short TP1 Hit on {{ticker}}")
alertcondition(short_tp2_signal,                "Short TP2 Hit",        "Short TP2 Hit on {{ticker}}")
alertcondition(short_tp3_signal,                "Short TP3 Hit",        "Short TP3 Hit on {{ticker}}")
alertcondition(long_exit_signal,                "Long Exit",            "Long Exit on {{ticker}}")
alertcondition(short_exit_signal,               "Short Exit",           "Short Exit on {{ticker}}")
alertcondition(chochSignal and activeDir == 1,  "Bullish CHoCH",        "Bullish CHoCH on {{ticker}}")
alertcondition(chochSignal and activeDir == -1, "Bearish CHoCH",        "Bearish CHoCH on {{ticker}}")
alertcondition(rej_bull,                        "Rejected Bull",        "Bull flip REJECTED on {{ticker}}")
alertcondition(rej_bear,                        "Rejected Bear",        "Bear flip REJECTED on {{ticker}}")

← 返回列表