Apex Order Block & Liquidity Engine [AOBLE]

Michael_Fx_Trader · study · 1574 行 · 点赞 317 · TradingView 原页

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

Pine Script

//@version=6
// =====================================================================================================
//  APEX ORDER BLOCK & LIQUIDITY ENGINE [AOBLE]
// =====================================================================================================
//
//  ORIGINAL WORK DECLARATION AND AUTHOR VERIFICATION
//  -----------------------------------------------------------------------------------------------------
//  Script name ........ Apex Order Block & Liquidity Engine [AOBLE]
//  Short title ........ AOBLE
//  Language ........... Pine Script v6
//  Version ............ 1.0 (26 October 2026)
//  Author ............. Michael_Fx_Trader
//  Publisher .......... Michael_Fx_Trader
//  Rights holder ...... Michael_Fx_Trader
//  Copyright .......... (c) 2026 Michael_Fx_Trader. All rights reserved.
//
//  DECLARATION
//  1. This indicator is an ORIGINAL work. Its source code, detection rules, state machines, data
//     structures, scoring/validation logic and drawing logic were written from scratch for this script.
//  2. No source code was copied, translated, or adapted from any other TradingView script (open-source,
//     protected or invite-only), from any library, or from any third-party indicator.
//  3. Terms such as order block, breaker block, BOS, CHoCH, MSS, buy-side / sell-side liquidity, fair
//     value gap and premium / discount are general market-analysis concepts used by many traders. Only
//     the concepts are shared; the implementation in this file is the author's own.
//  4. The author named above is the sole author, publisher and holder of all rights to this script.
//  5. The script is not affiliated with, endorsed by, or derived from any other author or brand.
//
//  VERIFICATION AND CLARIFICATION
//  -----------------------------------------------------------------------------------------------------
//  - Author verification : "Michael_Fx_Trader" is the declared author and publisher of this source.
//  - Originality         : Every module (structure, order blocks, breakers, liquidity, FVG, dealing range,
//                          multi-timeframe, trade planning, volume, dashboard, alerts) is implemented here
//                          with the author's own logic and parameters.
//  - Purpose             : Educational / analytical chart annotation. This is an INDICATOR, not an order
//                          execution system. Nothing displayed is financial advice, and no accuracy or
//                          profitability is claimed or guaranteed. Past behaviour does not predict results.
//
//  HOW THE ENGINES WORK (SUMMARY)
//  -----------------------------------------------------------------------------------------------------
//  Order blocks : A structure break (swing or internal) must occur together with a displacement candle
//                 (body >= ATR multiple). The origin is the last opposite-colour candle (or a small
//                 cluster) before the break. Bullish OB = last bearish candle before bullish displacement;
//                 bearish OB = last bullish candle before bearish displacement. Boundaries are selectable
//                 (full range, body, hybrid). States: fresh -> partially mitigated (price entered) ->
//                 fully mitigated (distal edge tagged) -> invalidated (break by close or wick).
//  Breakers     : An invalidated order block is tracked and re-classified in the opposite direction
//                 (bullish OB broken down = bearish breaker; bearish OB broken up = bullish breaker).
//                 Retests are highlighted; failed or expired breakers are removed.
//  BOS/CHoCH/MSS: Based on confirmed pivots. A close through the last unbroken pivot in the trend direction
//                 is BOS. A close against the trend is CHoCH, upgraded to MSS when it also shows
//                 displacement (and the optional volume filter, if enabled).
//  Liquidity    : Confirmed pivot highs / lows are clustered (equal highs / lows) inside an ATR or tick
//                 tolerance. A level becomes visible after the minimum number of touches. Trading through
//                 a level is a SWEEP (wick back inside) or a TAKEN level (close beyond). A sweep alone is
//                 never a trade signal.
//  FVG          : Three-candle imbalance with a minimum size. Partial fills shrink the zone; a full fill
//                 removes or fades it.
//  Trade plan   : Optional. Trigger (liquidity sweep and/or order block touch) + confirmation (MSS/CHoCH or
//                 displacement) + optional FVG / volume / discount-premium filters. Entry, stop and five
//                 targets are frozen when the setup is confirmed.
//
//  NON-REPAINTING AND CONFIRMATION DELAYS
//  -----------------------------------------------------------------------------------------------------
//  - Pivots need N bars on the right side before they are known. Everything built from a pivot (structure
//    lines, liquidity levels, dealing range) is created on the bar where the pivot is CONFIRMED, never
//    earlier. Structure lines are drawn back to the pivot bar for readability; that is a drawing
//    convention, the information only existed from the confirmation bar onward.
//  - Order blocks are created on the bar that confirms the structure break. The box starts at the origin
//    candle, but the zone only became known on the break bar.
//  - With "Confirmed-Bar Logic" enabled (default) all engines evaluate on closed bars only. Disabling it
//    allows intrabar evaluation, which can change before the candle closes.
//  - Multi-timeframe data uses request.security() with lookahead_on on a [1]-shifted expression, which
//    exposes only the last CLOSED higher-timeframe bar. Zones appear one higher-timeframe bar later.
//  - The optional "Developing Preview" is visibly marked as unconfirmed and disappears on bar close.
//  - Volume is exchange/broker tick or traded volume. It is NOT verified institutional order flow. When a
//    symbol has no volume data, volume filters are bypassed and the dashboard shows N/A.
//
//  INSTALLATION
//  -----------------------------------------------------------------------------------------------------
//  1. Open TradingView and a chart (for example XAUUSD).  2. Open the Pine Editor (bottom panel).
//  3. Delete the default code and paste this entire file.  4. Click "Save", then "Add to chart".
//  5. Open the indicator settings (gear icon) and adjust the 15 input groups as needed.
//  6. Right-click the indicator > "Add alert" to create alerts from the declared alert conditions.
// =====================================================================================================
 
indicator(title="Apex Order Block & Liquidity Engine [AOBLE]", shorttitle="AOBLE", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500, max_bars_back=500)
 
// =====================================================================================================
// 0. CONSTANTS AND TYPES
// =====================================================================================================
 
// Event slots. Detection code sets a slot to 1 on the bar where the event happens (used by alerts and logic).
const int E_BULL_OB    = 0
const int E_BEAR_OB    = 1
const int E_BULL_BR    = 2
const int E_BEAR_BR    = 3
const int E_BULL_BOS   = 4
const int E_BEAR_BOS   = 5
const int E_BULL_MSS   = 6
const int E_BEAR_MSS   = 7
const int E_BSL_SWEEP  = 8
const int E_SSL_SWEEP  = 9
const int E_BULL_FVG   = 10
const int E_BEAR_FVG   = 11
const int E_BUY        = 12
const int E_SELL       = 13
const int E_ENTRY      = 14
const int E_SL         = 15
const int E_TP         = 16
const int E_BULL_TOUCH = 17
const int E_BEAR_TOUCH = 18
const int E_NEW_BSL    = 19
const int E_NEW_SSL    = 20
const int NEV          = 21
 
// Generic zone: order block (kind 0), breaker (1), fair value gap (2), higher-timeframe order block (3)
type Zone
    float top
    float bot
    int   originBar
    int   dir
    int   state
    int   kind
    int   bornBar
    bool  retested
    box   bx
    box   gx
    line  mid
    label lb
 
// Liquidity level (local or higher timeframe)
type Liq
    float price
    int   touches
    int   lastBar
    int   firstBar
    bool  isBSL
    bool  shown
    bool  swept
    bool  htf
    line  ln
    label lb
 
// Market structure state
type Struct
    int   trend = 0
    float hPrice
    int   hBar
    bool  hOpen = false
    float lPrice
    int   lBar
    bool  lOpen = false
 
// Trade setup (entry, stop and five targets)
type Setup
    int          dir
    int          state
    int          bar0
    float        entry
    float        sl
    array<float> tps
    int          tpHit
    array<line>  lns
    array<label> lbs
 
// =====================================================================================================
// 1. INPUTS
// =====================================================================================================
 
const string G_GEN  = "1. General Settings"
const string G_MS   = "2. Market Structure"
const string G_BULL = "3. Bullish Order Blocks"
const string G_BEAR = "4. Bearish Order Blocks"
const string G_BRK  = "5. Breaker Blocks"
const string G_LIQ  = "6. Liquidity Detection"
const string G_FVG  = "7. Fair Value Gaps"
const string G_PD   = "8. Premium and Discount"
const string G_MTF  = "9. Multi-Timeframe Analysis"
const string G_TRD  = "10. Entry and Exit Planning"
const string G_VOL  = "11. Volume Confirmation"
const string G_DSH  = "12. Dashboard"
const string G_VIS  = "13. Visual Theme"
const string G_ALR  = "14. Alerts"
const string G_PRF  = "15. Performance and Object Management"
 
// ---- 1. General
int    atrLen        = input.int(14, "ATR Length", minval=1, group=G_GEN, tooltip="ATR period used for displacement, tolerance, gap size and stop calculations.")
bool   confirmedOnly = input.bool(true, "Confirmed-Bar Logic (Recommended)", group=G_GEN, tooltip="When enabled, all engines evaluate on closed bars only (non-repainting). When disabled, logic also runs on every tick of the live bar and may change before the candle closes.")
string lblMode       = input.string("Zone Start", "Zone Label Placement", options=["Zone Start", "Right Edge", "Hidden"], group=G_GEN, tooltip="Where order block, breaker, FVG and higher-timeframe zone labels are shown.")
string zoneTxtSize   = input.string("Small", "Zone Label Text Size", options=["Tiny", "Small", "Normal", "Large"], group=G_GEN, tooltip="Text size for zone, liquidity and trade-plan labels.")
int    rightPad      = input.int(6, "Right-Edge Label Offset (Bars)", minval=0, maxval=60, group=G_GEN, tooltip="Distance of right-edge labels from the latest bar.")
 
// ---- 2. Market structure
bool   showStructure  = input.bool(true, "Display BOS / CHoCH / MSS", group=G_MS, tooltip="Master switch for structure lines and labels. Structure is still tracked internally when hidden.")
bool   showSwingStruct = input.bool(true, "Show Swing Structure", group=G_MS)
int    swingLen       = input.int(5, "Swing Pivot Length", minval=2, group=G_MS, tooltip="Bars on each side required to confirm a swing pivot.")
string swingStyle     = input.string("Solid", "Swing Line Style", options=["Solid", "Dashed", "Dotted"], group=G_MS)
string swingSize      = input.string("Small", "Swing Label Size", options=["Tiny", "Small", "Normal", "Large"], group=G_MS)
bool   showIntStruct  = input.bool(true, "Show Internal Structure", group=G_MS)
int    intLen         = input.int(3, "Internal Pivot Length", minval=1, group=G_MS, tooltip="Bars on each side required to confirm an internal pivot.")
string intStyle       = input.string("Dashed", "Internal Line Style", options=["Solid", "Dashed", "Dotted"], group=G_MS)
string intSize        = input.string("Tiny", "Internal Label Size", options=["Tiny", "Small", "Normal", "Large"], group=G_MS)
float  dispMult       = input.float(1.0, "MSS / Setup Displacement (ATR multiple)", minval=0.1, step=0.1, group=G_MS, tooltip="A reversal break with a candle body of at least this ATR multiple (within 3 bars) is labelled MSS instead of CHoCH. Also used as the displacement test for trade setups.")
 
// ---- 3. Bullish order blocks (also holds shared order block search settings)
bool   showBullOB   = input.bool(true, "Display Bullish Order Blocks", group=G_BULL)
int    maxBullOB    = input.int(10, "Maximum Bullish Order Blocks", minval=1, maxval=50, group=G_BULL)
string bullBoundary = input.string("Full Candle Range", "Bullish Boundary Mode", options=["Full Candle Range", "Candle Body", "Hybrid"], group=G_BULL, tooltip="Full range = high to low. Body = open to close. Hybrid = body plus a percentage of the wick.")
int    bullHybrid   = input.int(50, "Bullish Hybrid Wick Inclusion (%)", minval=0, maxval=100, group=G_BULL)
float  bullDisp     = input.float(1.0, "Minimum Bullish Displacement (ATR multiple)", minval=0.1, step=0.1, group=G_BULL, tooltip="Strongest bullish candle body (current or previous 2 bars) must be at least this multiple of ATR for an order block to qualify.")
string lblBullOB    = input.string("BULLISH ORDER BLOCK", "Bullish Label Text", group=G_BULL)
string obSource     = input.string("Swing", "Order Block Source (Both Directions)", options=["Swing", "Internal", "Both"], group=G_BULL, tooltip="Which structure breaks may create order blocks.")
int    obScan       = input.int(10, "Origin Candle Search Bars (Both Directions)", minval=1, maxval=40, group=G_BULL, tooltip="Maximum number of bars searched backward from the break for the origin candle.")
bool   useCluster   = input.bool(false, "Use Candle Cluster (Both Directions)", group=G_BULL, tooltip="Merge consecutive opposite-colour candles into one zone.")
int    clusterMax   = input.int(3, "Maximum Cluster Candles", minval=2, maxval=6, group=G_BULL)
 
// ---- 4. Bearish order blocks
bool   showBearOB   = input.bool(true, "Display Bearish Order Blocks", group=G_BEAR)
int    maxBearOB    = input.int(10, "Maximum Bearish Order Blocks", minval=1, maxval=50, group=G_BEAR)
string bearBoundary = input.string("Full Candle Range", "Bearish Boundary Mode", options=["Full Candle Range", "Candle Body", "Hybrid"], group=G_BEAR)
int    bearHybrid   = input.int(50, "Bearish Hybrid Wick Inclusion (%)", minval=0, maxval=100, group=G_BEAR)
float  bearDisp     = input.float(1.0, "Minimum Bearish Displacement (ATR multiple)", minval=0.1, step=0.1, group=G_BEAR, tooltip="Strongest bearish candle body (current or previous 2 bars) must be at least this multiple of ATR for an order block to qualify.")
string lblBearOB    = input.string("BEARISH ORDER BLOCK", "Bearish Label Text", group=G_BEAR)
 
// ---- 5. Breaker blocks
bool   showBreakers = input.bool(true, "Display Breaker Blocks", group=G_BRK, tooltip="An invalidated order block is re-classified as a breaker in the opposite direction.")
string brkInvalid   = input.string("Candle Close", "Invalidation Rule", options=["Candle Close", "Wick"], group=G_BRK, tooltip="Candle Close = a bar must close beyond the distal edge. Wick = a wick beyond the distal edge is enough.")
float  brkStrength  = input.float(0.1, "Minimum Breakout Strength (ATR multiple)", minval=0.0, step=0.05, group=G_BRK, tooltip="Distance beyond the distal edge required to count as a break.")
int    maxBreakers  = input.int(6, "Maximum Breakers Per Direction", minval=1, maxval=30, group=G_BRK)
bool   brkRetest    = input.bool(true, "Highlight Breaker Retests", group=G_BRK)
bool   keepGhost    = input.bool(true, "Keep Broken Order Block History", group=G_BRK, tooltip="Leave a faded, frozen box where the original order block was broken.")
int    brkExpire    = input.int(400, "Breaker Expiry (Bars)", minval=20, group=G_BRK, tooltip="Breakers older than this are removed automatically.")
string obMitMode    = input.string("Keep Faded", "Fully Mitigated Order Blocks", options=["Keep Faded", "Remove"], group=G_BRK, tooltip="What happens when price tags the far edge of an order block without breaking it.")
 
// ---- 6. Liquidity
bool   showLiq        = input.bool(true, "Display Liquidity", group=G_LIQ)
int    liqLen         = input.int(5, "Liquidity Pivot Length", minval=2, group=G_LIQ)
string liqTolMode     = input.string("ATR", "Equal Level Tolerance Mode", options=["ATR", "Ticks"], group=G_LIQ)
float  liqTolAtr      = input.float(0.15, "Tolerance (ATR multiple)", minval=0.0, step=0.01, group=G_LIQ)
int    liqTolTicks    = input.int(30, "Tolerance (Ticks)", minval=0, group=G_LIQ)
int    liqMinTouches  = input.int(2, "Minimum Touches", minval=1, maxval=6, group=G_LIQ, tooltip="1 = every confirmed swing is a liquidity level. 2 or more = only equal highs / equal lows.")
int    liqMinSep      = input.int(5, "Minimum Separation Between Swings (Bars)", minval=1, group=G_LIQ)
int    maxLiq         = input.int(15, "Maximum Active Liquidity Levels", minval=2, maxval=60, group=G_LIQ)
bool   showSweepLbl   = input.bool(true, "Show Sweep Labels", group=G_LIQ)
bool   delConsumed    = input.bool(false, "Delete Consumed Levels", group=G_LIQ, tooltip="Remove the line when a level is swept. Otherwise it is kept as a faded dotted line.")
int    liqWidth       = input.int(1, "Liquidity Line Width", minval=1, maxval=4, group=G_LIQ)
string liqStyle       = input.string("Dashed", "Liquidity Line Style", options=["Solid", "Dashed", "Dotted"], group=G_LIQ)
 
// ---- 7. Fair value gaps
bool   showFVG    = input.bool(true, "Display Fair Value Gaps", group=G_FVG)
string fvgMode    = input.string("ATR", "Minimum Gap Mode", options=["ATR", "Ticks"], group=G_FVG)
float  fvgMinAtr  = input.float(0.2, "Minimum Gap (ATR multiple)", minval=0.0, step=0.05, group=G_FVG, tooltip="Set to 0 to display every gap.")
int    fvgMinTicks = input.int(20, "Minimum Gap (Ticks)", minval=0, group=G_FVG)
int    maxFvg     = input.int(10, "Maximum FVGs Per Direction", minval=1, maxval=50, group=G_FVG)
bool   fvgMid     = input.bool(true, "Show Midpoint (Consequent Encroachment)", group=G_FVG)
string fvgOnFill  = input.string("Fade", "When Fully Filled", options=["Fade", "Remove"], group=G_FVG)
bool   fvgLabel   = input.bool(false, "Show FVG Labels", group=G_FVG)
 
// ---- 8. Premium / discount
bool   showPD      = input.bool(true, "Display Premium / Discount", group=G_PD, tooltip="Dealing range from the latest confirmed swing high and swing low. Premium / discount are context only, not guaranteed sell / buy areas.")
string pdSource    = input.string("Swing", "Dealing Range Source", options=["Swing", "Internal"], group=G_PD, tooltip="Uses the swing or internal pivot sensitivity set in Market Structure.")
bool   showRangeHL = input.bool(true, "Show Range High / Low / Equilibrium Lines", group=G_PD)
int    pdTransp    = input.int(92, "Zone Transparency", minval=50, maxval=99, group=G_PD)
 
// ---- 9. Multi-timeframe
bool   showMTF = input.bool(false, "Enable Multi-Timeframe Confluence", group=G_MTF, tooltip="Optional. Uses confirmed higher-timeframe data only. Disable to reduce execution cost.")
bool   mtfOB   = input.bool(true, "Show Higher-Timeframe Order Blocks", group=G_MTF)
bool   mtfLiq  = input.bool(true, "Show Higher-Timeframe Liquidity", group=G_MTF)
int    maxMTF  = input.int(10, "Maximum Higher-Timeframe Objects (Each Type)", minval=1, maxval=40, group=G_MTF)
bool   mtfOn1  = input.bool(false, "Timeframe 1", inline="t1", group=G_MTF)
string mtfTf1  = input.timeframe("15", "", inline="t1", group=G_MTF)
bool   mtfOn2  = input.bool(true, "Timeframe 2", inline="t2", group=G_MTF)
string mtfTf2  = input.timeframe("60", "", inline="t2", group=G_MTF)
bool   mtfOn3  = input.bool(true, "Timeframe 3", inline="t3", group=G_MTF)
string mtfTf3  = input.timeframe("240", "", inline="t3", group=G_MTF)
bool   mtfOn4  = input.bool(true, "Timeframe 4", inline="t4", group=G_MTF)
string mtfTf4  = input.timeframe("D", "", inline="t4", group=G_MTF)
bool   mtfOn5  = input.bool(false, "Timeframe 5", inline="t5", group=G_MTF)
string mtfTf5  = input.timeframe("W", "", inline="t5", group=G_MTF)
 
// ---- 10. Entry and exit planning
bool   showSetups   = input.bool(true, "Enable Trade Planning", group=G_TRD, tooltip="Analytical reference only. This indicator does not execute orders.")
string entryMethod  = input.string("Confirmation Close", "Entry Method", options=["Confirmation Close", "Order Block Retest", "FVG Retest", "User Price"], group=G_TRD, tooltip="Retest and user-price entries wait (pending) until price reaches the entry. If no suitable zone exists the confirmation close is used.")
float  userEntry    = input.float(0.0, "User Entry Price", minval=0.0, group=G_TRD, tooltip="Used only with the User Price method. The price is limited to the pullback side of the current close.")
string slMode       = input.string("Beyond Swing", "Stop Loss Mode", options=["Beyond Swing", "Beyond Order Block", "ATR"], group=G_TRD)
float  slBuf        = input.float(0.2, "Stop Safety Buffer (ATR multiple)", minval=0.0, step=0.05, group=G_TRD)
float  slAtrMult    = input.float(1.5, "ATR Stop Distance (ATR multiple)", minval=0.2, step=0.1, group=G_TRD)
float  maxRiskAtr   = input.float(6.0, "Maximum Risk (ATR multiple)", minval=1.0, step=0.5, group=G_TRD, tooltip="If a structural stop is farther than this, the ATR stop is used instead.")
string tpMode       = input.string("Risk Reward", "Target Mode", options=["Risk Reward", "Structure & Liquidity"], group=G_TRD, tooltip="Structure & Liquidity uses nearby liquidity pools, opposing order blocks and swing levels, then fills the rest with the reward multiples below.")
float  rr1          = input.float(1.0, "Target 1 (R multiple)", minval=0.1, step=0.1, group=G_TRD)
float  rr2          = input.float(2.0, "Target 2 (R multiple)", minval=0.1, step=0.1, group=G_TRD)
float  rr3          = input.float(3.0, "Target 3 (R multiple)", minval=0.1, step=0.1, group=G_TRD)
float  rr4          = input.float(4.0, "Target 4 (R multiple)", minval=0.1, step=0.1, group=G_TRD)
float  rr5          = input.float(5.0, "Target 5 (R multiple)", minval=0.1, step=0.1, group=G_TRD)
string trigMode     = input.string("Sweep or OB Touch", "Setup Trigger", options=["Sweep or OB Touch", "Sweep Only", "OB Touch Only"], group=G_TRD, tooltip="Sweep = liquidity swept with a close back inside. OB Touch = first touch of an order block.")
string confMode     = input.string("MSS/CHoCH or Displacement", "Setup Confirmation", options=["MSS/CHoCH or Displacement", "MSS/CHoCH Only"], group=G_TRD)
bool   reqFvg       = input.bool(false, "Require Recent FVG", group=G_TRD)
bool   pdFilter     = input.bool(false, "Longs in Discount / Shorts in Premium Only", group=G_TRD)
int    setupWin     = input.int(20, "Trigger-to-Confirmation Window (Bars)", minval=1, group=G_TRD)
int    cooldown     = input.int(10, "Cooldown Bars Between Setups", minval=0, group=G_TRD)
int    pendExpire   = input.int(30, "Pending Entry Expiry (Bars)", minval=1, group=G_TRD)
bool   dynSetup     = input.bool(false, "Dynamic Update While Pending", group=G_TRD, tooltip="Off (default): entry, stop and targets are frozen at confirmation. On: a pending (not yet filled) setup is recalculated each bar. Filled setups are never changed.")
int    maxSetups    = input.int(3, "Setups Kept On Chart", minval=1, maxval=10, group=G_TRD)
bool   setupMarker  = input.bool(true, "Show Setup Marker Label", group=G_TRD)
 
// ---- 11. Volume
int    volLen          = input.int(20, "Volume Lookback", minval=2, group=G_VOL)
float  volThr          = input.float(1.5, "Relative Volume Threshold", minval=0.5, step=0.1, group=G_VOL, tooltip="Volume divided by its moving average. Volume is not verified institutional order flow.")
bool   volOBFilter     = input.bool(false, "Require Volume Spike For Order Blocks", group=G_VOL)
bool   volMSSFilter    = input.bool(false, "Require Volume Spike For MSS", group=G_VOL)
bool   volSetupFilter  = input.bool(false, "Require Volume Spike For Setups", group=G_VOL)
 
// ---- 12. Dashboard
bool   showDash    = input.bool(true, "Display Dashboard", group=G_DSH)
string dashPos     = input.string("Top Right", "Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=G_DSH)
string dashSize    = input.string("Small", "Text Size", options=["Tiny", "Small", "Normal", "Large"], group=G_DSH)
bool   dashCompact = input.bool(false, "Compact Mode", group=G_DSH)
color  dashTxtIn   = input.color(#FFFFFF, "Custom Text Color", group=G_DSH, tooltip="Used when Custom Colors is enabled in Visual Theme.")
color  dashBgIn    = input.color(color.new(#0B0E14, 15), "Custom Background Color", group=G_DSH)
 
// ---- 13. Visual theme
string themeSel    = input.string("Professional Dark", "Theme", options=["Professional Dark", "Professional Light", "Neon", "Minimal"], group=G_VIS)
bool   useCustom   = input.bool(false, "Use Custom Colors Below", group=G_VIS, tooltip="When off, colors come from the selected theme.")
color  iBullOB     = input.color(#00E676, "Bullish Order Block", group=G_VIS)
color  iBearOB     = input.color(#FF1744, "Bearish Order Block", group=G_VIS)
color  iBullBr     = input.color(#00BFA5, "Bullish Breaker", group=G_VIS)
color  iBearBr     = input.color(#C2185B, "Bearish Breaker", group=G_VIS)
color  iBSL        = input.color(#FF5252, "Buy-Side Liquidity", group=G_VIS)
color  iSSL        = input.color(#FF9800, "Sell-Side Liquidity", group=G_VIS)
color  iBullMSS    = input.color(#00E676, "Bullish Structure", group=G_VIS)
color  iBearMSS    = input.color(#FF1744, "Bearish Structure", group=G_VIS)
color  iBullFVG    = input.color(#26C6DA, "Bullish FVG", group=G_VIS)
color  iBearFVG    = input.color(#FF9100, "Bearish FVG", group=G_VIS)
color  iEq         = input.color(#FFD600, "Equilibrium", group=G_VIS)
color  iEntry      = input.color(#FFFFFF, "Entry Line", group=G_VIS)
color  iSL         = input.color(#FF1744, "Stop Loss", group=G_VIS)
color  iTP         = input.color(#00E5A0, "Targets", group=G_VIS)
color  iText       = input.color(#FFFFFF, "Zone Text", group=G_VIS)
int    fillTransp  = input.int(85, "Zone Fill Transparency", minval=40, maxval=98, group=G_VIS)
bool   showBorder  = input.bool(true, "Show Zone Borders", group=G_VIS)
int    lineW       = input.int(1, "Line Width", minval=1, maxval=4, group=G_VIS)
bool   showMid     = input.bool(false, "Show Zone Midpoint Lines (Order Blocks / Breakers)", group=G_VIS)
bool   glowOn      = input.bool(false, "Layered Glow Effect", group=G_VIS, tooltip="Adds a thick, very transparent outline behind order blocks and breakers.")
int    glowTransp  = input.int(90, "Glow Transparency", minval=60, maxval=99, group=G_VIS)
 
// ---- 14. Alerts
bool   alertOnTouch = input.bool(true, "Raise 'Price Entered Zone' Alert Events", group=G_ALR, tooltip="Zone detected, price entering a zone, liquidity sweep and confirmed setup are separate alert conditions. Create alerts from the chart alert dialog.")
 
// ---- 15. Performance
bool   recentOnly = input.bool(false, "Display Recent Zones Only", group=G_PRF)
int    recentBars = input.int(1500, "Recent Window (Bars)", minval=100, group=G_PRF)
int    maxGhosts  = input.int(15, "Maximum Faded / Swept History Objects", minval=0, maxval=60, group=G_PRF)
bool   devPreview = input.bool(false, "Developing Order Block Preview (Unconfirmed)", group=G_PRF, tooltip="Shows a dashed preview on the live bar when a structure break and displacement are forming. It is NOT confirmed and disappears on bar close. Only active with Confirmed-Bar Logic on.")
 
// =====================================================================================================
// 2. THEME AND HELPERS
// =====================================================================================================
 
int themeIdx = switch themeSel
    "Professional Dark"  => 0
    "Professional Light" => 1
    "Neon"               => 2
    => 3
 
f_pick(color dk, color lt, color nn, color mn) =>
    themeIdx == 0 ? dk : themeIdx == 1 ? lt : themeIdx == 2 ? nn : mn
 
color cBullOB  = useCustom ? iBullOB  : f_pick(#00E676, #00963F, #39FF14, #5C9E7A)
color cBearOB  = useCustom ? iBearOB  : f_pick(#FF1744, #D50000, #FF0055, #B5655F)
color cBullBr  = useCustom ? iBullBr  : f_pick(#00BFA5, #00796B, #00FFD0, #4F9E96)
color cBearBr  = useCustom ? iBearBr  : f_pick(#C2185B, #880E4F, #FF2DAA, #9E5873)
color cBSL     = useCustom ? iBSL     : f_pick(#FF5252, #E53935, #FF4D6D, #A06060)
color cSSL     = useCustom ? iSSL     : f_pick(#FF9800, #EF6C00, #FFB300, #B08A55)
color cBullMSS = useCustom ? iBullMSS : f_pick(#00E676, #00A152, #00FF9C, #6FAF8A)
color cBearMSS = useCustom ? iBearMSS : f_pick(#FF1744, #D50000, #FF3D71, #B5655F)
color cBullFVG = useCustom ? iBullFVG : f_pick(#26C6DA, #00ACC1, #00E5FF, #7FB8C0)
color cBearFVG = useCustom ? iBearFVG : f_pick(#FF9100, #EF6C00, #FF6D00, #C09A6A)
color cEq      = useCustom ? iEq      : f_pick(#FFD600, #F9A825, #FFEA00, #C8B560)
color cEntry   = useCustom ? iEntry   : f_pick(#FFFFFF, #1A1A1A, #FFFFFF, #8A8A8A)
color cSL      = useCustom ? iSL      : f_pick(#FF1744, #D50000, #FF3D71, #B5655F)
color cTP      = useCustom ? iTP      : f_pick(#00E5A0, #00796B, #00FFB2, #5FA58F)
color cText    = useCustom ? iText    : f_pick(#FFFFFF, #111111, #FFFFFF, #D0D0D0)
color dTxt     = useCustom ? dashTxtIn : f_pick(#FFFFFF, #111111, #FFFFFF, #D0D0D0)
color dBg      = useCustom ? dashBgIn  : f_pick(color.new(#0B0E14, 15), color.new(#FFFFFF, 10), color.new(#05010F, 10), color.new(#2B2F36, 25))
 
f_size(string s) =>
    switch s
        "Tiny"  => size.tiny
        "Small" => size.small
        "Large" => size.large
        => size.normal
 
f_style(string s) =>
    switch s
        "Dashed" => line.style_dashed
        "Dotted" => line.style_dotted
        => line.style_solid
 
f_pos(string s) =>
    switch s
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
f_tfStyle(int idx) =>
    switch idx
        0 => line.style_dotted
        1 => line.style_dashed
        2 => line.style_solid
        3 => line.style_dashed
        => line.style_dotted
 
f_tfLabel(string tf) =>
    string r = tf
    if tf == "D" or tf == "1D"
        r := "D1"
    else if tf == "W" or tf == "1W"
        r := "W1"
    else if tf == "M" or tf == "1M"
        r := "MN1"
    else
        float m = str.tonumber(tf)
        if not na(m)
            if m < 60
                r := "M" + str.tostring(m, "#")
            else if m % 60 == 0
                r := "H" + str.tostring(m / 60, "#")
            else
                r := tf + "m"
    r
 
// =====================================================================================================
// 3. CORE SERIES (computed on every bar)
// =====================================================================================================
 
float atrV = ta.atr(atrLen)
 
float phSwing = ta.pivothigh(high, swingLen, swingLen)
float plSwing = ta.pivotlow(low, swingLen, swingLen)
float phInt   = ta.pivothigh(high, intLen, intLen)
float plInt   = ta.pivotlow(low, intLen, intLen)
float phLiq   = ta.pivothigh(high, liqLen, liqLen)
float plLiq   = ta.pivotlow(low, liqLen, liqLen)
 
float bullBody3 = ta.highest(close - open, 3)
float bearBody3 = ta.highest(open - close, 3)
 
float volMa      = ta.sma(volume, volLen)
bool  volAvail   = nz(volMa) > 0
float relVol     = volAvail ? volume / volMa : na
float relVolMax3 = ta.highest(nz(relVol), 3)
bool  volSpike   = volAvail and nz(relVol) >= volThr
 
float fvgMinSz   = fvgMode == "ATR" ? fvgMinAtr * nz(atrV) : fvgMinTicks * syminfo.mintick
bool  bullFvgNow = low > high[2] and (low - high[2]) >= fvgMinSz
bool  bearFvgNow = high < low[2] and (low[2] - high) >= fvgMinSz
 
float wBull = bullBoundary == "Full Candle Range" ? 1.0 : bullBoundary == "Candle Body" ? 0.0 : bullHybrid / 100.0
float wBear = bearBoundary == "Full Candle Range" ? 1.0 : bearBoundary == "Candle Body" ? 0.0 : bearHybrid / 100.0
 
// Evaluate engines on closed bars only (default) or on every tick
bool go = confirmedOnly ? barstate.isconfirmed : true
 
string dSize = f_size(dashSize)
 
// =====================================================================================================
// 4. PERSISTENT COLLECTIONS AND STATE
// =====================================================================================================
 
var array<Zone>  obs    = array.new<Zone>()
var array<Zone>  brs    = array.new<Zone>()
var array<Zone>  fvgs   = array.new<Zone>()
var array<Zone>  mtfZ   = array.new<Zone>()
var array<Liq>   liqs   = array.new<Liq>()
var array<box>   ghosts = array.new<box>()
var array<line>  sweptLines = array.new<line>()
var array<Setup> setups = array.new<Setup>()
 
var Struct sSwing = Struct.new()
var Struct sInt   = Struct.new()
var Setup  cur    = na
 
var array<int>    ev       = array.new<int>(NEV, 0)
var array<int>    sweepLog = array.new<int>(2, -1)      // [0] last BSL sweep with rejection, [1] last SSL sweep with rejection
var array<int>    trigLog  = array.new<int>(4, -1)      // [0] bull OB first touch, [1] bear OB first touch, [2] bull FVG, [3] bear FVG
var array<float>  brkLog   = array.new<float>(2, na)    // [0] bar of last swing break, [1] its price (duplicate-label guard)
var array<string> txtLog   = array.new<string>(1, "None")
var array<int>    mtfSeen  = array.new<int>(20, 0)
var array<float>  trigPx   = array.new<float>(4, na)    // [0] bull OB top, [1] bull OB bot, [2] bear OB top, [3] bear OB bot (last touched)
 
var int usedBullTrig = -1
var int usedBearTrig = -1
var int lastSetupBar = -100000
 
ev.fill(0)
 
// =====================================================================================================
// 5. ZONE DRAWING HELPERS
// =====================================================================================================
 
f_zCol(int kind, int dir, int state) =>
    color base = switch kind
        0 => dir == 1 ? cBullOB : cBearOB
        1 => dir == 1 ? cBullBr : cBearBr
        2 => dir == 1 ? cBullFVG : cBearFVG
        => dir == 1 ? cBullOB : cBearOB
    int ft = kind == 3 ? math.min(fillTransp + 6, 98) : fillTransp
    if state == 1
        ft := math.min(ft + 4, 98)
    else if state == 2
        ft := 94
    int bt = state == 2 ? 55 : 0
    [color.new(base, bt), color.new(base, ft), base]
 
f_makeZone(int kind, int dir, float t, float b, int left, string txt, bool withMid, int origin) =>
    [bd, bg, base] = f_zCol(kind, dir, 0)
    box gx = na
    if glowOn and kind != 3
        gx := box.new(left, t, bar_index, b, border_color=color.new(base, glowTransp), border_width=lineW + 4, bgcolor=na, extend=extend.right)
    string bTxt = lblMode == "Zone Start" ? txt : ""
    box bx = box.new(left, t, bar_index, b, border_color=showBorder ? bd : color.new(bd, 100), border_width=lineW, border_style=line.style_solid, extend=extend.right, bgcolor=bg, text=bTxt, text_size=f_size(zoneTxtSize), text_color=cText, text_halign=text.align_left, text_valign=text.align_center)
    line md = na
    if withMid
        float m = (t + b) / 2
        md := line.new(left, m, bar_index, m, extend=extend.right, color=color.new(base, 30), style=line.style_dotted, width=1)
    label lb = na
    if lblMode == "Right Edge" and txt != ""
        lb := label.new(bar_index, (t + b) / 2, txt, style=label.style_label_left, color=color.new(base, 100), textcolor=base, size=f_size(zoneTxtSize))
    Zone.new(top=t, bot=b, originBar=origin, dir=dir, state=0, kind=kind, bornBar=bar_index, retested=false, bx=bx, gx=gx, mid=md, lb=lb)
 
f_zStyle(Zone z) =>
    [bd, bg, base] = f_zCol(z.kind, z.dir, z.state)
    box.set_bgcolor(z.bx, bg)
    box.set_border_color(z.bx, showBorder ? bd : color.new(bd, 100))
    box.set_border_style(z.bx, z.state == 2 ? line.style_dotted : line.style_solid)
    if not na(z.gx)
        box.set_border_color(z.gx, z.state == 2 ? color.new(base, 100) : color.new(base, glowTransp))
    if not na(z.mid)
        line.set_color(z.mid, color.new(base, z.state == 2 ? 80 : 30))
 
f_endZone(Zone z, int endBar) =>
    box.set_extend(z.bx, extend.none)
    box.set_right(z.bx, endBar)
    if not na(z.gx)
        box.set_extend(z.gx, extend.none)
        box.set_right(z.gx, endBar)
    if not na(z.mid)
        line.set_extend(z.mid, extend.none)
        line.set_x2(z.mid, endBar)
 
f_delZone(Zone z) =>
    if not na(z.bx)
        box.delete(z.bx)
    if not na(z.gx)
        box.delete(z.gx)
    if not na(z.mid)
        line.delete(z.mid)
    if not na(z.lb)
        label.delete(z.lb)
 
// Remove the oldest zones of a direction (dir 0 = every zone in the array) until the limit is respected
f_trim(array<Zone> arr, int dir, int maxN) =>
    int cnt = 0
    for z in arr
        if dir == 0 or z.dir == dir
            cnt += 1
    while cnt > maxN
        int idx = -1
        for i = 0 to arr.size() - 1
            Zone zz = arr.get(i)
            if dir == 0 or zz.dir == dir
                idx := i
                break
        if idx < 0
            break
        f_delZone(arr.get(idx))
        arr.remove(idx)
        cnt -= 1
 
f_pushGhost(box b) =>
    ghosts.push(b)
    while ghosts.size() > maxGhosts
        box.delete(ghosts.shift())
 
// =====================================================================================================
// 6. ORDER BLOCK ENGINE
// =====================================================================================================
 
// Pure search: last opposite-colour candle (optionally a cluster) before the break. Returns [found, top, bottom, originBar, leftBar]
f_findOB(bool bull, int maxK, float wFrac) =>
    bool found = false
    float zt = na
    float zb = na
    int originIdx = na
    int leftIdx = na
    int k0 = 1
    int lim = math.max(maxK, 1)
    for k = 1 to lim
        bool opp = bull ? close[k] < open[k] : close[k] > open[k]
        if opp
            found := true
            k0 := k
            break
    if found
        float hi = high[k0]
        float lo = low[k0]
        float bTop = bull ? open[k0] : close[k0]
        float bBot = bull ? close[k0] : open[k0]
        int kEarliest = k0
        if useCluster
            int j = k0 + 1
            int cnt = 1
            while cnt < clusterMax and j <= bar_index
                bool opp2 = bull ? close[j] < open[j] : close[j] > open[j]
                if not opp2
                    break
                hi := math.max(hi, high[j])
                lo := math.min(lo, low[j])
                bTop := math.max(bTop, bull ? open[j] : close[j])
                bBot := math.min(bBot, bull ? close[j] : open[j])
                kEarliest := j
                j += 1
                cnt += 1
        zt := bTop + (hi - bTop) * wFrac
        zb := bBot - (bBot - lo) * wFrac
        originIdx := bar_index - k0
        leftIdx := bar_index - kEarliest
    [found, zt, zb, originIdx, leftIdx]
 
f_addOB(bool bull, float t, float b, int idx, int left) =>
    int d = bull ? 1 : -1
    float tt = t
    float bb = b
    if tt - bb < syminfo.mintick
        tt := bb + syminfo.mintick
    bool dup = false
    for z in obs
        if z.dir == d and not dup
            if z.originBar == idx
                dup := true
            else if z.state < 2
                float ov = math.min(z.top, tt) - math.max(z.bot, bb)
                float h = math.min(z.top - z.bot, tt - bb)
                if ov > 0.5 * h
                    dup := true
    if not dup
        Zone nzone = f_makeZone(0, d, tt, bb, left, bull ? lblBullOB : lblBearOB, showMid, idx)
        obs.push(nzone)
        f_trim(obs, d, bull ? maxBullOB : maxBearOB)
        ev.set(bull ? E_BULL_OB : E_BEAR_OB, 1)
 
f_tryOB(bool bull, int pivBar, bool obAllowed) =>
    bool en = bull ? showBullOB : showBearOB
    if en and obAllowed and not na(atrV)
        float body3 = bull ? bullBody3 : bearBody3
        float dmul = bull ? bullDisp : bearDisp
        bool volOk = not volOBFilter or not volAvail or relVolMax3 >= volThr
        if body3 >= dmul * atrV and volOk
            float w = bull ? wBull : wBear
            int span = math.max(bar_index - pivBar, 1)
            [fnd, zTop, zBot, oIdx, oLeft] = f_findOB(bull, math.min(obScan, span), w)
            if fnd
                f_addOB(bull, zTop, zBot, oIdx, oLeft)
 
// Called when an order block is invalidated: archive the original and optionally create the opposite-direction breaker
f_breakOB(Zone z) =>
    bool wasBull = z.dir == 1
    if keepGhost and maxGhosts > 0
        f_endZone(z, bar_index)
        box.set_bgcolor(z.bx, color.new(color.gray, 94))
        box.set_border_color(z.bx, color.new(color.gray, 60))
        box.set_border_style(z.bx, line.style_dotted)
        box.set_text(z.bx, "")
        if not na(z.gx)
            box.delete(z.gx)
        if not na(z.mid)
            line.delete(z.mid)
        if not na(z.lb)
            label.delete(z.lb)
        f_pushGhost(z.bx)
    else
        f_delZone(z)
    if showBreakers
        int nd = wasBull ? -1 : 1
        Zone bz = f_makeZone(1, nd, z.top, z.bot, bar_index, wasBull ? "BEARISH BREAKER BLOCK" : "BULLISH BREAKER BLOCK", showMid, z.originBar)
        brs.push(bz)
        f_trim(brs, nd, maxBreakers)
        ev.set(wasBull ? E_BEAR_BR : E_BULL_BR, 1)
 
f_manageOB() =>
    int n = obs.size()
    if n > 0
        for i = n - 1 to 0
            Zone z = obs.get(i)
            bool rm = false
            if recentOnly and bar_index - z.originBar > recentBars
                f_delZone(z)
                rm := true
            else if bar_index > z.bornBar
                bool bull = z.dir == 1
                bool entered = bull ? low <= z.top : high >= z.bot
                bool tagged = bull ? low <= z.bot : high >= z.top
                float refPx = brkInvalid == "Wick" ? (bull ? low : high) : close
                float strength = brkStrength * nz(atrV)
                bool inv = bull ? refPx < z.bot - strength : refPx > z.top + strength
                if inv
                    f_breakOB(z)
                    rm := true
                else
                    int oldState = z.state
                    if z.state == 0 and entered
                        z.state := 1
                        if bull
                            ev.set(E_BULL_TOUCH, alertOnTouch ? 1 : 0)
                            trigLog.set(0, bar_index)
                            trigPx.set(0, z.top)
                            trigPx.set(1, z.bot)
                        else
                            ev.set(E_BEAR_TOUCH, alertOnTouch ? 1 : 0)
                            trigLog.set(1, bar_index)
                            trigPx.set(2, z.top)
                            trigPx.set(3, z.bot)
                    if z.state < 2 and tagged
                        z.state := 2
                    if z.state != oldState
                        if z.state == 2 and obMitMode == "Remove"
                            f_delZone(z)
                            rm := true
                        else
                            f_zStyle(z)
            if rm
                obs.remove(i)
 
f_manageBR() =>
    int n = brs.size()
    if n > 0
        for i = n - 1 to 0
            Zone z = brs.get(i)
            bool rm = false
            if (recentOnly and bar_index - z.originBar > recentBars) or bar_index - z.bornBar > brkExpire
                f_delZone(z)
                rm := true
            else if bar_index > z.bornBar
                bool bear = z.dir == -1
                float refPx = brkInvalid == "Wick" ? (bear ? high : low) : close
                float strength = brkStrength * nz(atrV)
                bool dead = bear ? refPx > z.top + strength : refPx < z.bot - strength
                if dead
                    f_delZone(z)
                    rm := true
                else if brkRetest and not z.retested
                    bool retest = bear ? high >= z.bot : low <= z.top
                    if retest
                        z.retested := true
                        [bd, bg, base] = f_zCol(1, z.dir, 0)
                        box.set_bgcolor(z.bx, color.new(base, math.max(fillTransp - 25, 40)))
                        box.set_border_width(z.bx, lineW + 1)
                        if lblMode == "Zone Start"
                            box.set_text(z.bx, (bear ? "BEARISH BREAKER BLOCK" : "BULLISH BREAKER BLOCK") + " (RETEST)")
            if rm
                brs.remove(i)
 
// =====================================================================================================
// 7. MARKET STRUCTURE ENGINE (BOS / CHoCH / MSS)
// =====================================================================================================
 
f_struct(Struct s, float ph, float pl, bool isInt) =>
    int pLen = isInt ? intLen : swingLen
    if not na(ph)
        s.hPrice := ph
        s.hBar := bar_index - pLen
        s.hOpen := true
    if not na(pl)
        s.lPrice := pl
        s.lBar := bar_index - pLen
        s.lOpen := true
    bool showIt = showStructure and (isInt ? showIntStruct : showSwingStruct)
    string stl = isInt ? intStyle : swingStyle
    string szs = isInt ? intSize : swingSize
    bool obAllowed = obSource == "Both" or (obSource == "Swing" and not isInt) or (obSource == "Internal" and isInt)
    bool volMss = not volMSSFilter or not volAvail or relVolMax3 >= volThr
 
    // Bullish break: close above the last unbroken pivot high
    if s.hOpen and close > s.hPrice
        bool rev = s.trend == -1
        bool strong = not na(atrV) and bullBody3 >= dispMult * atrV and volMss
        string nm = rev ? (strong ? "BULLISH MSS" : "BULLISH CHoCH") : "BOS"
        float lvl = s.hPrice
        int x0 = s.hBar
        s.hOpen := false
        s.trend := 1
        bool dup = isInt and brkLog.get(0) == bar_index and math.abs(brkLog.get(1) - lvl) < syminfo.mintick * 2
        if not dup
            ev.set(rev ? E_BULL_MSS : E_BULL_BOS, 1)
            txtLog.set(0, nm + " @ " + str.tostring(lvl, format.mintick))
            if not isInt
                brkLog.set(0, float(bar_index))
                brkLog.set(1, lvl)
            if showIt
                line.new(x0, lvl, bar_index, lvl, color=cBullMSS, style=f_style(stl), width=lineW)
                int xm = int(math.round(x0 + (bar_index - x0) / 2.0))
                label.new(xm, lvl, nm, style=label.style_label_down, color=color.new(cBullMSS, 100), textcolor=cBullMSS, size=f_size(szs))
        f_tryOB(true, x0, obAllowed)
 
    // Bearish break: close below the last unbroken pivot low
    if s.lOpen and close < s.lPrice
        bool rev = s.trend == 1
        bool strong = not na(atrV) and bearBody3 >= dispMult * atrV and volMss
        string nm = rev ? (strong ? "BEARISH MSS" : "BEARISH CHoCH") : "BOS"
        float lvl = s.lPrice
        int x0 = s.lBar
        s.lOpen := false
        s.trend := -1
        bool dup = isInt and brkLog.get(0) == bar_index and math.abs(brkLog.get(1) - lvl) < syminfo.mintick * 2
        if not dup
            ev.set(rev ? E_BEAR_MSS : E_BEAR_BOS, 1)
            txtLog.set(0, nm + " @ " + str.tostring(lvl, format.mintick))
            if not isInt
                brkLog.set(0, float(bar_index))
                brkLog.set(1, lvl)
            if showIt
                line.new(x0, lvl, bar_index, lvl, color=cBearMSS, style=f_style(stl), width=lineW)
                int xm = int(math.round(x0 + (bar_index - x0) / 2.0))
                label.new(xm, lvl, nm, style=label.style_label_up, color=color.new(cBearMSS, 100), textcolor=cBearMSS, size=f_size(szs))
        f_tryOB(false, x0, obAllowed)
 
// =====================================================================================================
// 8. LIQUIDITY ENGINE
// =====================================================================================================
 
f_trimLiq() =>
    int localShown = 0
    int htfCnt = 0
    for l in liqs
        if l.htf
            htfCnt += 1
        else if l.shown
            localShown += 1
    while localShown > maxLiq
        int idx = -1
        for i = 0 to liqs.size() - 1
            Liq q = liqs.get(i)
            if not q.htf and q.shown
                idx := i
                break
        if idx < 0
            break
        Liq old = liqs.get(idx)
        if not na(old.ln)
            line.delete(old.ln)
        if not na(old.lb)
            label.delete(old.lb)
        liqs.remove(idx)
        localShown -= 1
    while htfCnt > maxMTF * 2
        int idx = -1
        for i = 0 to liqs.size() - 1
            Liq q = liqs.get(i)
            if q.htf
                idx := i
                break
        if idx < 0
            break
        Liq old = liqs.get(idx)
        if not na(old.ln)
            line.delete(old.ln)
        if not na(old.lb)
            label.delete(old.lb)
        liqs.remove(idx)
        htfCnt -= 1
 
f_liqPivot(float pv, bool isBSL) =>
    int pbar = bar_index - liqLen
    float tol = liqTolMode == "ATR" ? liqTolAtr * nz(atrV) : liqTolTicks * syminfo.mintick
    Liq hit = na
    for l in liqs
        if na(hit) and not l.htf and l.isBSL == isBSL and not l.swept and math.abs(l.price - pv) <= tol
            hit := l
    if na(hit)
        Liq nl = Liq.new(price=pv, touches=1, lastBar=pbar, firstBar=pbar, isBSL=isBSL, shown=false, swept=false, htf=false)
        liqs.push(nl)
        hit := nl
    else if pbar - hit.lastBar >= liqMinSep
        hit.touches += 1
        hit.lastBar := pbar
        hit.price := isBSL ? math.max(hit.price, pv) : math.min(hit.price, pv)
    if hit.touches >= liqMinTouches
        string txt = (isBSL ? "BUY-SIDE LIQUIDITY" : "SELL-SIDE LIQUIDITY") + (hit.touches > 1 ? " (EQ x" + str.tostring(hit.touches) + ")" : "")
        color c = isBSL ? cBSL : cSSL
        if not hit.shown
            hit.shown := true
            ev.set(isBSL ? E_NEW_BSL : E_NEW_SSL, 1)
            if showLiq
                hit.ln := line.new(hit.firstBar, hit.price, bar_index, hit.price, extend=extend.right, color=c, style=f_style(liqStyle), width=liqWidth)
                hit.lb := label.new(bar_index, hit.price, txt, style=label.style_label_left, color=color.new(c, 100), textcolor=c, size=f_size(zoneTxtSize))
        else
            if not na(hit.ln)
                line.set_y1(hit.ln, hit.price)
                line.set_y2(hit.ln, hit.price)
            if not na(hit.lb)
                label.set_y(hit.lb, hit.price)
                label.set_text(hit.lb, txt)
    f_trimLiq()
 
f_manageLiq() =>
    int n = liqs.size()
    if n > 0
        for i = n - 1 to 0
            Liq l = liqs.get(i)
            bool rm = false
            color c = l.isBSL ? cBSL : cSSL
            if not l.shown
                if bar_index - l.lastBar > 500
                    rm := true
            else if recentOnly and not l.htf and bar_index - l.firstBar > recentBars
                if not na(l.ln)
                    line.delete(l.ln)
                if not na(l.lb)
                    label.delete(l.lb)
                rm := true
            else if not l.swept and bar_index > l.firstBar
                bool crossed = l.isBSL ? high > l.price : low < l.price
                if crossed
                    l.swept := true
                    bool rej = l.isBSL ? close <= l.price : close >= l.price
                    if not l.htf
                        ev.set(l.isBSL ? E_BSL_SWEEP : E_SSL_SWEEP, 1)
                        if rej
                            sweepLog.set(l.isBSL ? 0 : 1, bar_index)
                        if showSweepLbl and showLiq
                            label.new(bar_index, l.isBSL ? high : low, (l.isBSL ? "BSL " : "SSL ") + (rej ? "SWEEP" : "TAKEN"), style=l.isBSL ? label.style_label_down : label.style_label_up, color=color.new(c, 100), textcolor=c, size=f_size(zoneTxtSize))
                    if not na(l.lb)
                        label.delete(l.lb)
                    if not na(l.ln)
                        if delConsumed or l.htf
                            line.delete(l.ln)
                        else
                            line.set_extend(l.ln, extend.none)
                            line.set_x2(l.ln, bar_index)
                            line.set_style(l.ln, line.style_dotted)
                            line.set_color(l.ln, color.new(c, 65))
                            sweptLines.push(l.ln)
                            while sweptLines.size() > maxGhosts
                                line.delete(sweptLines.shift())
                    rm := true
            if rm
                liqs.remove(i)
 
// =====================================================================================================
// 9. FAIR VALUE GAP ENGINE
// =====================================================================================================
 
f_addFVG(bool bull) =>
    int d = bull ? 1 : -1
    float t = bull ? low : low[2]
    float b = bull ? high[2] : high
    string txt = fvgLabel ? (bull ? "BULLISH FVG" : "BEARISH FVG") : ""
    Zone zn = f_makeZone(2, d, t, b, bar_index - 2, txt, fvgMid, bar_index - 2)
    fvgs.push(zn)
    f_trim(fvgs, d, maxFvg)
    ev.set(bull ? E_BULL_FVG : E_BEAR_FVG, 1)
    trigLog.set(bull ? 2 : 3, bar_index)
 
f_manageFVG() =>
    int n = fvgs.size()
    if n > 0
        for i = n - 1 to 0
            Zone z = fvgs.get(i)
            bool rm = recentOnly and bar_index - z.originBar > recentBars
            if rm
                f_delZone(z)
            else if bar_index > z.bornBar and z.state < 2
                bool filled = false
                if z.dir == 1
                    if low < z.top
                        z.top := math.max(low, z.bot)
                        box.set_top(z.bx, z.top)
                        if z.state == 0
                            z.state := 1
                    filled := low <= z.bot
                else
                    if high > z.bot
                        z.bot := math.min(high, z.top)
                        box.set_bottom(z.bx, z.bot)
                        if z.state == 0
                            z.state := 1
                    filled := high >= z.top
                if not na(z.mid)
                    float m = (z.top + z.bot) / 2
                    line.set_y1(z.mid, m)
                    line.set_y2(z.mid, m)
                if filled
                    z.state := 2
                    if fvgOnFill == "Remove"
                        f_delZone(z)
                        rm := true
                    else
                        f_endZone(z, bar_index)
                        f_zStyle(z)
            if rm
                fvgs.remove(i)
 
// =====================================================================================================
// 10. MULTI-TIMEFRAME ENGINE
// =====================================================================================================
 
// Runs in the higher-timeframe context. Every returned value is shifted by one bar so only CLOSED
// higher-timeframe bars are exposed (no future leakage with lookahead_on).
f_htf() =>
    float a = ta.atr(atrLen)
    float ph = ta.pivothigh(high, swingLen, swingLen)
    float pl = ta.pivotlow(low, swingLen, swingLen)
    float up3 = ta.highest(close - open, 3)
    float dn3 = ta.highest(open - close, 3)
    var float lH = na
    var float lL = na
    var bool oH = false
    var bool oL = false
    if not na(ph)
        lH := ph
        oH := true
    if not na(pl)
        lL := pl
        oL := true
    float bT = na
    float bB = na
    int bTm = na
    float sT = na
    float sB = na
    int sTm = na
    float bslP = na
    int bslT = na
    float sslP = na
    int sslT = na
    if not na(ph)
        bslP := ph
        bslT := time[swingLen]
    if not na(pl)
        sslP := pl
        sslT := time[swingLen]
    if oH and close > lH
        oH := false
        if not na(a) and up3 >= dispMult * a
            for k = 1 to 12
                if close[k] < open[k]
                    bT := high[k]
                    bB := low[k]
                    bTm := time[k]
                    break
    if oL and close < lL
        oL := false
        if not na(a) and dn3 >= dispMult * a
            for k = 1 to 12
                if close[k] > open[k]
                    sT := high[k]
                    sB := low[k]
                    sTm := time[k]
                    break
    [bT[1], bB[1], bTm[1], sT[1], sB[1], sTm[1], bslP[1], bslT[1], sslP[1], sslT[1]]
 
f_addMtfZone(int dir, float t, float b, int tm, string txt, int idx) =>
    [bd, bg, base] = f_zCol(3, dir, 0)
    box bx = box.new(left=tm, top=t, right=time, bottom=b, xloc=xloc.bar_time, extend=extend.right, border_color=showBorder ? bd : color.new(bd, 100), border_width=lineW, border_style=f_tfStyle(idx), bgcolor=bg, text=lblMode == "Zone Start" ? txt : "", text_size=f_size(zoneTxtSize), text_color=cText, text_halign=text.align_left, text_valign=text.align_center)
    label lb = na
    if lblMode == "Right Edge"
        lb := label.new(bar_index, (t + b) / 2, txt, style=label.style_label_left, color=color.new(base, 100), textcolor=base, size=f_size(zoneTxtSize))
    Zone zn = Zone.new(top=t, bot=b, originBar=bar_index, dir=dir, state=0, kind=3, bornBar=bar_index, retested=false, bx=bx, lb=lb)
    mtfZ.push(zn)
    f_trim(mtfZ, 0, maxMTF * 2)
 
f_addMtfLiq(bool isBSL, float p, int tm, string txt, int idx) =>
    color c = isBSL ? cBSL : cSSL
    Liq nl = Liq.new(price=p, touches=1, lastBar=bar_index, firstBar=bar_index, isBSL=isBSL, shown=true, swept=false, htf=true)
    nl.ln := line.new(tm, p, time, p, xloc=xloc.bar_time, extend=extend.right, color=c, style=f_tfStyle(idx), width=liqWidth)
    nl.lb := label.new(bar_index, p, txt, style=label.style_label_left, color=color.new(c, 100), textcolor=c, size=f_size(zoneTxtSize))
    liqs.push(nl)
    f_trimLiq()
 
f_mtf(int idx, string tf, bool active, float rBT, float rBB, int rBTm, float rST, float rSB, int rSTm, float rBslP, int rBslT, float rSslP, int rSslT) =>
    if active and go
        string tfl = f_tfLabel(tf)
        if mtfOB
            if not na(rBTm) and rBTm != mtfSeen.get(idx * 4)
                mtfSeen.set(idx * 4, rBTm)
                f_addMtfZone(1, rBT, rBB, rBTm, tfl + " BULLISH OB", idx)
            if not na(rSTm) and rSTm != mtfSeen.get(idx * 4 + 1)
                mtfSeen.set(idx * 4 + 1, rSTm)
                f_addMtfZone(-1, rST, rSB, rSTm, tfl + " BEARISH OB", idx)
        if mtfLiq
            if not na(rBslT) and rBslT != mtfSeen.get(idx * 4 + 2)
                mtfSeen.set(idx * 4 + 2, rBslT)
                f_addMtfLiq(true, rBslP, rBslT, tfl + " BUY-SIDE LIQUIDITY", idx)
            if not na(rSslT) and rSslT != mtfSeen.get(idx * 4 + 3)
                mtfSeen.set(idx * 4 + 3, rSslT)
                f_addMtfLiq(false, rSslP, rSslT, tfl + " SELL-SIDE LIQUIDITY", idx)
 
f_manageMTFZ() =>
    int n = mtfZ.size()
    if n > 0
        for i = n - 1 to 0
            Zone z = mtfZ.get(i)
            bool dead = bar_index > z.bornBar and ((z.dir == 1 and close < z.bot) or (z.dir == -1 and close > z.top))
            if dead
                f_delZone(z)
                mtfZ.remove(i)
 
// =====================================================================================================
// 11. TRADE PLANNING ENGINE
// =====================================================================================================
 
// Nearest usable zone of a direction relative to a reference price. Returns [top, bottom]
f_nearZone(array<Zone> arr, int dir, float refPx) =>
    float bt = na
    float bb = na
    float bestD = 1e18
    for z in arr
        if z.dir == dir and z.state < 2
            float d = 1e18
            if dir == 1
                if z.bot < refPx
                    d := z.top <= refPx ? refPx - z.top : 0.0
            else
                if z.top > refPx
                    d := z.bot >= refPx ? z.bot - refPx : 0.0
            if d < bestD
                bestD := d
                bt := z.top
                bb := z.bot
    [bt, bb]
 
f_targets(int dir, float entry, float risk) =>
    array<float> out = array.new<float>()
    bool lng = dir == 1
    if tpMode == "Structure & Liquidity"
        array<float> cands = array.new<float>()
        for l in liqs
            if not l.htf and l.shown and not l.swept
                if lng and l.isBSL and l.price > entry
                    cands.push(l.price)
                else if not lng and not l.isBSL and l.price < entry
                    cands.push(l.price)
        for z in obs
            if z.state < 2
                if lng and z.dir == -1 and z.bot > entry
                    cands.push(z.bot)
                else if not lng and z.dir == 1 and z.top < entry
                    cands.push(z.top)
        float sw = lng ? sSwing.hPrice : sSwing.lPrice
        if not na(sw) and (lng ? sw > entry : sw < entry)
            cands.push(sw)
        if lng
            cands.sort(order.ascending)
        else
            cands.sort(order.descending)
        float lastV = entry
        for v in cands
            if out.size() < 5
                bool okStep = lng ? v >= lastV + 0.5 * risk : v <= lastV - 0.5 * risk
                if okStep
                    out.push(v)
                    lastV := v
    array<float> rrs = array.from(rr1, rr2, rr3, rr4, rr5)
    while out.size() < 5
        int i = out.size()
        float lastV2 = i > 0 ? out.last() : entry
        float cand = lng ? entry + risk * rrs.get(i) : entry - risk * rrs.get(i)
        float px = lng ? math.max(cand, lastV2 + 0.5 * risk) : math.min(cand, lastV2 - 0.5 * risk)
        out.push(px)
    out
 
// Build (but do not draw) a plan: entry, stop and five targets
f_plan(int dir) =>
    bool lng = dir == 1
    float a = nz(atrV, 1.0)
    float c = close
    [obT, obB] = f_nearZone(obs, dir, c)
    [fvT, fvB] = f_nearZone(fvgs, dir, c)
    float entry = c
    if entryMethod == "Order Block Retest" and not na(obT)
        entry := lng ? math.min(obT, c) : math.max(obB, c)
    else if entryMethod == "FVG Retest" and not na(fvT)
        float fm = (fvT + fvB) / 2
        entry := lng ? math.min(fm, c) : math.max(fm, c)
    else if entryMethod == "User Price" and userEntry > 0
        entry := lng ? math.min(userEntry, c) : math.max(userEntry, c)
    float base = na
    if slMode == "Beyond Swing"
        float sw = lng ? sSwing.lPrice : sSwing.hPrice
        if not na(sw) and (lng ? sw < entry : sw > entry)
            base := sw
    else if slMode == "Beyond Order Block"
        float zb = lng ? obB : obT
        if not na(zb) and (lng ? zb < entry : zb > entry)
            base := zb
    float sl = lng ? entry - slAtrMult * a : entry + slAtrMult * a
    if not na(base)
        float sb = lng ? base - slBuf * a : base + slBuf * a
        if math.abs(entry - sb) <= maxRiskAtr * a
            sl := sb
    float risk = math.abs(entry - sl)
    if risk < 0.3 * a
        risk := 0.3 * a
        sl := lng ? entry - risk : entry + risk
    array<float> tps = f_targets(dir, entry, risk)
    Setup.new(dir=dir, state=0, bar0=bar_index, entry=entry, sl=sl, tps=tps, tpHit=0, lns=array.new<line>(), lbs=array.new<label>())
 
f_setupTxt(Setup s, int i) =>
    float px = i == 0 ? s.entry : i == 1 ? s.sl : s.tps.get(i - 2)
    string nm = i == 0 ? (s.dir == 1 ? "BUY ENTRY" : "SELL ENTRY") : i == 1 ? "STOP LOSS" : "TARGET " + str.tostring(i - 1)
    nm + " " + str.tostring(px, format.mintick)
 
f_setupPx(Setup s, int i) =>
    i == 0 ? s.entry : i == 1 ? s.sl : s.tps.get(i - 2)
 
f_drawSetup(Setup s) =>
    for i = 0 to 6
        color c = i == 0 ? cEntry : i == 1 ? cSL : cTP
        float px = f_setupPx(s, i)
        string st = (i == 0 and s.state == 0) ? line.style_dashed : line.style_solid
        s.lns.push(line.new(s.bar0, px, bar_index + 1, px, extend=extend.right, color=c, style=st, width=lineW))
        s.lbs.push(label.new(bar_index, px, f_setupTxt(s, i), style=label.style_label_left, color=color.new(c, 100), textcolor=c, size=f_size(zoneTxtSize)))
 
f_refreshSetup(Setup s) =>
    for i = 0 to 6
        float px = f_setupPx(s, i)
        line.set_y1(s.lns.get(i), px)
        line.set_y2(s.lns.get(i), px)
        label.set_y(s.lbs.get(i), px)
        label.set_text(s.lbs.get(i), f_setupTxt(s, i))
 
f_closeSetup(Setup s) =>
    for ln in s.lns
        line.set_extend(ln, extend.none)
        line.set_x2(ln, bar_index)
    for lb in s.lbs
        label.set_x(lb, bar_index)
 
f_delSetup(Setup s) =>
    for ln in s.lns
        line.delete(ln)
    for lb in s.lbs
        label.delete(lb)
 
f_trackSetup(Setup s) =>
    bool lng = s.dir == 1
    if bar_index > s.bar0
        if s.state == 0
            bool filled = lng ? low <= s.entry : high >= s.entry
            bool dead = lng ? close < s.sl : close > s.sl
            if dead or bar_index - s.bar0 > pendExpire
                s.state := 2
                label.set_text(s.lbs.get(0), f_setupTxt(s, 0) + " [CANCELLED]")
                f_closeSetup(s)
            else if filled
                s.state := 1
                ev.set(E_ENTRY, 1)
                label.set_text(s.lbs.get(0), f_setupTxt(s, 0) + " [FILLED]")
                line.set_style(s.lns.get(0), line.style_solid)
            else if dynSetup
                Setup np = f_plan(s.dir)
                s.entry := np.entry
                s.sl := np.sl
                s.tps := np.tps
                f_refreshSetup(s)
        if s.state == 1
            bool slHit = lng ? low <= s.sl : high >= s.sl
            if slHit
                s.state := 2
                ev.set(E_SL, 1)
                label.set_text(s.lbs.get(1), f_setupTxt(s, 1) + " [HIT]")
                f_closeSetup(s)
            else
                while s.tpHit < 5 and (lng ? high >= s.tps.get(s.tpHit) : low <= s.tps.get(s.tpHit))
                    label.set_text(s.lbs.get(2 + s.tpHit), f_setupTxt(s, 2 + s.tpHit) + " [HIT]")
                    s.tpHit += 1
                    ev.set(E_TP, 1)
                if s.tpHit >= 5
                    s.state := 2
                    f_closeSetup(s)
 
// =====================================================================================================
// 12. DASHBOARD HELPERS
// =====================================================================================================
 
var table dash = showDash ? table.new(f_pos(dashPos), 2, 12, bgcolor=dBg, frame_color=color.new(color.gray, 50), frame_width=1, border_width=1, border_color=color.new(color.gray, 75)) : na
 
f_dashRow(int r, string k, string v, color vc) =>
    table.cell(dash, 0, r, k, text_color=dTxt, text_halign=text.align_left, text_size=dSize, bgcolor=dBg)
    table.cell(dash, 1, r, v, text_color=vc, text_halign=text.align_left, text_size=dSize, bgcolor=dBg)
 
f_nearOBTxt(int dir) =>
    float bt = na
    float bb = na
    float bestD = 1e18
    for z in obs
        if z.dir == dir and z.state < 2
            float d = close > z.top ? close - z.top : close < z.bot ? z.bot - close : 0.0
            if d < bestD
                bestD := d
                bt := z.top
                bb := z.bot
    na(bt) ? "-" : str.tostring(bb, format.mintick) + " - " + str.tostring(bt, format.mintick)
 
f_nearLiqTxt(bool bsl) =>
    float best = na
    for l in liqs
        if not l.htf and l.shown and not l.swept and l.isBSL == bsl
            bool ok = bsl ? l.price > close : l.price < close
            if ok
                if na(best) or (bsl ? l.price < best : l.price > best)
                    best := l.price
    na(best) ? "-" : str.tostring(best, format.mintick)
 
f_trendTxt(int t) =>
    t == 1 ? "BULLISH" : t == -1 ? "BEARISH" : "NEUTRAL"
 
// =====================================================================================================
// 13. MAIN EXECUTION
// =====================================================================================================
 
if go
    f_manageOB()
    f_manageBR()
    f_manageFVG()
    f_manageMTFZ()
 
    f_struct(sSwing, phSwing, plSwing, false)
    f_struct(sInt, phInt, plInt, true)
 
    if not na(phLiq)
        f_liqPivot(phLiq, true)
    if not na(plLiq)
        f_liqPivot(plLiq, false)
    f_manageLiq()
 
    if showFVG
        if bullFvgNow
            f_addFVG(true)
        if bearFvgNow
            f_addFVG(false)
 
// Higher-timeframe data: requests are made unconditionally (consistent execution). A disabled slot
// requests the chart timeframe itself (no extra data) and is ignored.
bool mtfA1 = showMTF and mtfOn1 and timeframe.in_seconds(mtfTf1) > timeframe.in_seconds(timeframe.period)
bool mtfA2 = showMTF and mtfOn2 and timeframe.in_seconds(mtfTf2) > timeframe.in_seconds(timeframe.period)
bool mtfA3 = showMTF and mtfOn3 and timeframe.in_seconds(mtfTf3) > timeframe.in_seconds(timeframe.period)
bool mtfA4 = showMTF and mtfOn4 and timeframe.in_seconds(mtfTf4) > timeframe.in_seconds(timeframe.period)
bool mtfA5 = showMTF and mtfOn5 and timeframe.in_seconds(mtfTf5) > timeframe.in_seconds(timeframe.period)
 
[a1BT, a1BB, a1BTm, a1ST, a1SB, a1STm, a1BslP, a1BslT, a1SslP, a1SslT] = request.security(syminfo.tickerid, mtfA1 ? mtfTf1 : timeframe.period, f_htf(), lookahead=barmerge.lookahead_on)
[a2BT, a2BB, a2BTm, a2ST, a2SB, a2STm, a2BslP, a2BslT, a2SslP, a2SslT] = request.security(syminfo.tickerid, mtfA2 ? mtfTf2 : timeframe.period, f_htf(), lookahead=barmerge.lookahead_on)
[a3BT, a3BB, a3BTm, a3ST, a3SB, a3STm, a3BslP, a3BslT, a3SslP, a3SslT] = request.security(syminfo.tickerid, mtfA3 ? mtfTf3 : timeframe.period, f_htf(), lookahead=barmerge.lookahead_on)
[a4BT, a4BB, a4BTm, a4ST, a4SB, a4STm, a4BslP, a4BslT, a4SslP, a4SslT] = request.security(syminfo.tickerid, mtfA4 ? mtfTf4 : timeframe.period, f_htf(), lookahead=barmerge.lookahead_on)
[a5BT, a5BB, a5BTm, a5ST, a5SB, a5STm, a5BslP, a5BslT, a5SslP, a5SslT] = request.security(syminfo.tickerid, mtfA5 ? mtfTf5 : timeframe.period, f_htf(), lookahead=barmerge.lookahead_on)
 
f_mtf(0, mtfTf1, mtfA1, a1BT, a1BB, a1BTm, a1ST, a1SB, a1STm, a1BslP, a1BslT, a1SslP, a1SslT)
f_mtf(1, mtfTf2, mtfA2, a2BT, a2BB, a2BTm, a2ST, a2SB, a2STm, a2BslP, a2BslT, a2SslP, a2SslT)
f_mtf(2, mtfTf3, mtfA3, a3BT, a3BB, a3BTm, a3ST, a3SB, a3STm, a3BslP, a3BslT, a3SslP, a3SslT)
f_mtf(3, mtfTf4, mtfA4, a4BT, a4BB, a4BTm, a4ST, a4SB, a4STm, a4BslP, a4BslT, a4SslP, a4SslT)
f_mtf(4, mtfTf5, mtfA5, a5BT, a5BB, a5BTm, a5ST, a5SB, a5STm, a5BslP, a5BslT, a5SslP, a5SslT)
 
// ---- Trade planning ----
if go and showSetups and not na(atrV)
    if not na(cur)
        if cur.state < 2
            f_trackSetup(cur)
 
    bool coolOk = bar_index - lastSetupBar >= cooldown
    bool free = true
    if not na(cur)
        free := cur.state == 2
    if free and coolOk
        float eqMid = (not na(sSwing.hPrice) and not na(sSwing.lPrice)) ? (sSwing.hPrice + sSwing.lPrice) / 2 : na
        bool volOkS = not volSetupFilter or not volAvail or relVolMax3 >= volThr
 
        // Long setup
        int tbL = -1
        if trigMode != "OB Touch Only" and sweepLog.get(1) >= 0 and bar_index - sweepLog.get(1) <= setupWin
            tbL := math.max(tbL, sweepLog.get(1))
        if trigMode != "Sweep Only" and trigLog.get(0) >= 0 and bar_index - trigLog.get(0) <= setupWin
            tbL := math.max(tbL, trigLog.get(0))
        bool bullDispNow = close > open and (close - open) >= dispMult * atrV
        bool confL = ev.get(E_BULL_MSS) == 1 or (confMode == "MSS/CHoCH or Displacement" and bullDispNow)
        bool fvgL = not reqFvg or (trigLog.get(2) >= 0 and bar_index - trigLog.get(2) <= setupWin)
        bool pdL = not pdFilter or na(eqMid) or close < eqMid
        if tbL > usedBullTrig and tbL >= 0 and confL and fvgL and pdL and volOkS
            Setup s = f_plan(1)
            s.state := s.entry == close ? 1 : 0
            f_drawSetup(s)
            setups.push(s)
            while setups.size() > maxSetups
                f_delSetup(setups.shift())
            cur := s
            lastSetupBar := bar_index
            usedBullTrig := tbL
            ev.set(E_BUY, 1)
            if setupMarker
                label.new(bar_index, low, "BUY SETUP", yloc=yloc.belowbar, style=label.style_label_up, color=color.new(cBullMSS, 20), textcolor=color.white, size=size.small)
        else
            // Short setup
            int tbS = -1
            if trigMode != "OB Touch Only" and sweepLog.get(0) >= 0 and bar_index - sweepLog.get(0) <= setupWin
                tbS := math.max(tbS, sweepLog.get(0))
            if trigMode != "Sweep Only" and trigLog.get(1) >= 0 and bar_index - trigLog.get(1) <= setupWin
                tbS := math.max(tbS, trigLog.get(1))
            bool bearDispNow = close < open and (open - close) >= dispMult * atrV
            bool confS = ev.get(E_BEAR_MSS) == 1 or (confMode == "MSS/CHoCH or Displacement" and bearDispNow)
            bool fvgS = not reqFvg or (trigLog.get(3) >= 0 and bar_index - trigLog.get(3) <= setupWin)
            bool pdS = not pdFilter or na(eqMid) or close > eqMid
            if tbS > usedBearTrig and tbS >= 0 and confS and fvgS and pdS and volOkS
                Setup s = f_plan(-1)
                s.state := s.entry == close ? 1 : 0
                f_drawSetup(s)
                setups.push(s)
                while setups.size() > maxSetups
                    f_delSetup(setups.shift())
                cur := s
                lastSetupBar := bar_index
                usedBearTrig := tbS
                ev.set(E_SELL, 1)
                if setupMarker
                    label.new(bar_index, high, "SELL SETUP", yloc=yloc.abovebar, style=label.style_label_down, color=color.new(cBearMSS, 20), textcolor=color.white, size=size.small)
 
// =====================================================================================================
// 14. LAST-BAR DRAWING (right-edge labels, dealing range, dashboard, developing preview)
// =====================================================================================================
 
var box   pdPrem = na
var box   pdDisc = na
var line  pdHiL  = na
var line  pdEqL  = na
var line  pdLoL  = na
var label pdHiT  = na
var label pdEqT  = na
var label pdLoT  = na
var box   devBox = na
 
if barstate.islast
    // Right-edge labels follow the latest bar
    int xr = bar_index + rightPad
    for l in liqs
        if not na(l.lb)
            label.set_x(l.lb, xr)
    for z in obs
        if not na(z.lb)
            label.set_x(z.lb, xr)
    for z in brs
        if not na(z.lb)
            label.set_x(z.lb, xr)
    for z in mtfZ
        if not na(z.lb)
            label.set_x(z.lb, xr)
    for s in setups
        if s.state < 2
            for lb in s.lbs
                label.set_x(lb, xr)
 
    // Premium / discount dealing range
    if showPD
        Struct ps = pdSource == "Swing" ? sSwing : sInt
        if not na(ps.hPrice) and not na(ps.lPrice) and ps.hPrice > ps.lPrice
            float hi = ps.hPrice
            float lo = ps.lPrice
            float eq = (hi + lo) / 2
            int x0 = math.min(ps.hBar, ps.lBar)
            if na(pdPrem)
                pdPrem := box.new(x0, hi, bar_index, eq, border_color=na, bgcolor=color.new(cBearOB, pdTransp), extend=extend.right, text="PREMIUM", text_size=f_size(zoneTxtSize), text_color=color.new(cBearOB, 40), text_halign=text.align_left, text_valign=text.align_top)
                pdDisc := box.new(x0, eq, bar_index, lo, border_color=na, bgcolor=color.new(cBullOB, pdTransp), extend=extend.right, text="DISCOUNT", text_size=f_size(zoneTxtSize), text_color=color.new(cBullOB, 40), text_halign=text.align_left, text_valign=text.align_bottom)
                if showRangeHL
                    pdHiL := line.new(x0, hi, bar_index, hi, extend=extend.right, color=color.new(cText, 60), style=line.style_dotted)
                    pdEqL := line.new(x0, eq, bar_index, eq, extend=extend.right, color=cEq, style=line.style_dashed)
                    pdLoL := line.new(x0, lo, bar_index, lo, extend=extend.right, color=color.new(cText, 60), style=line.style_dotted)
                    pdHiT := label.new(xr, hi, "RANGE HIGH (100%)", style=label.style_label_left, color=color.new(cText, 100), textcolor=color.new(cText, 20), size=f_size(zoneTxtSize))
                    pdEqT := label.new(xr, eq, "EQUILIBRIUM (50%)", style=label.style_label_left, color=color.new(cEq, 100), textcolor=cEq, size=f_size(zoneTxtSize))
                    pdLoT := label.new(xr, lo, "RANGE LOW (0%)", style=label.style_label_left, color=color.new(cText, 100), textcolor=color.new(cText, 20), size=f_size(zoneTxtSize))
            else
                box.set_lefttop(pdPrem, x0, hi)
                box.set_rightbottom(pdPrem, bar_index, eq)
                box.set_lefttop(pdDisc, x0, eq)
                box.set_rightbottom(pdDisc, bar_index, lo)
                if showRangeHL and not na(pdHiL)
                    line.set_xy1(pdHiL, x0, hi)
                    line.set_xy2(pdHiL, bar_index, hi)
                    line.set_xy1(pdEqL, x0, eq)
                    line.set_xy2(pdEqL, bar_index, eq)
                    line.set_xy1(pdLoL, x0, lo)
                    line.set_xy2(pdLoL, bar_index, lo)
                    label.set_xy(pdHiT, xr, hi)
                    label.set_xy(pdEqT, xr, eq)
                    label.set_xy(pdLoT, xr, lo)
 
    // Developing (unconfirmed) order block preview
    if not na(devBox)
        box.delete(devBox)
        devBox := na
    if devPreview and confirmedOnly and not barstate.isconfirmed and not na(atrV)
        if showBullOB and sSwing.hOpen and close > sSwing.hPrice and bullBody3 >= bullDisp * atrV
            [fnd1, t1, b1, i1, l1] = f_findOB(true, math.min(obScan, math.max(bar_index - sSwing.hBar, 1)), wBull)
            if fnd1
                devBox := box.new(l1, t1, bar_index, b1, border_color=cBullOB, border_style=line.style_dashed, bgcolor=color.new(cBullOB, 92), extend=extend.right, text="DEVELOPING BULLISH OB (UNCONFIRMED)", text_size=f_size(zoneTxtSize), text_color=cText, text_halign=text.align_left, text_valign=text.align_center)
        else if showBearOB and sSwing.lOpen and close < sSwing.lPrice and bearBody3 >= bearDisp * atrV
            [fnd2, t2, b2, i2, l2] = f_findOB(false, math.min(obScan, math.max(bar_index - sSwing.lBar, 1)), wBear)
            if fnd2
                devBox := box.new(l2, t2, bar_index, b2, border_color=cBearOB, border_style=line.style_dashed, bgcolor=color.new(cBearOB, 92), extend=extend.right, text="DEVELOPING BEARISH OB (UNCONFIRMED)", text_size=f_size(zoneTxtSize), text_color=cText, text_halign=text.align_left, text_valign=text.align_center)
 
    // Dashboard
    if showDash
        string setTxt = "None"
        color setCol = dTxt
        if not na(cur)
            if cur.state < 2
                setTxt := (cur.dir == 1 ? "BUY" : "SELL") + (cur.state == 0 ? " pending @ " : " active @ ") + str.tostring(cur.entry, format.mintick) + " | TP " + str.tostring(cur.tpHit) + "/5"
                setCol := cur.dir == 1 ? cBullMSS : cBearMSS
        string volTxt = volAvail ? str.tostring(nz(relVol), "#.##") + "x" + (volSpike ? " (SPIKE)" : "") : "N/A (no volume data)"
        string mtfTxt = "Off"
        if showMTF
            mtfTxt := (mtfOn1 ? f_tfLabel(mtfTf1) + " " : "") + (mtfOn2 ? f_tfLabel(mtfTf2) + " " : "") + (mtfOn3 ? f_tfLabel(mtfTf3) + " " : "") + (mtfOn4 ? f_tfLabel(mtfTf4) + " " : "") + (mtfOn5 ? f_tfLabel(mtfTf5) : "")
        color biasCol = sSwing.trend == 1 ? cBullMSS : sSwing.trend == -1 ? cBearMSS : dTxt
        color intCol  = sInt.trend == 1 ? cBullMSS : sInt.trend == -1 ? cBearMSS : dTxt
        int r = 0
        f_dashRow(r, "AOBLE", syminfo.ticker + " " + timeframe.period, dTxt)
        r += 1
        f_dashRow(r, "Structural Bias", f_trendTxt(sSwing.trend), biasCol)
        r += 1
        if not dashCompact
            f_dashRow(r, "Internal Structure", f_trendTxt(sInt.trend), intCol)
            r += 1
        f_dashRow(r, "Last BOS / MSS", txtLog.get(0), dTxt)
        r += 1
        if not dashCompact
            f_dashRow(r, "Nearest Bullish OB", f_nearOBTxt(1), cBullOB)
            r += 1
            f_dashRow(r, "Nearest Bearish OB", f_nearOBTxt(-1), cBearOB)
            r += 1
            f_dashRow(r, "Nearest Buy-Side Liq.", f_nearLiqTxt(true), cBSL)
            r += 1
            f_dashRow(r, "Nearest Sell-Side Liq.", f_nearLiqTxt(false), cSSL)
            r += 1
        f_dashRow(r, "Active Setup", setTxt, setCol)
        r += 1
        f_dashRow(r, "Relative Volume", volTxt, dTxt)
        r += 1
        if not dashCompact
            f_dashRow(r, "HTF Confluence", mtfTxt, dTxt)
            r += 1
 
// =====================================================================================================
// 15. ALERT CONDITIONS
// =====================================================================================================
// Each condition fires only on the bar where the event occurs. Detection, price entering a zone,
// liquidity sweeps and confirmed setups are separate conditions.
 
alertcondition(ev.get(E_BULL_OB) == 1,    "AOBLE: New Bullish Order Block",     "AOBLE: bullish order block detected on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_BEAR_OB) == 1,    "AOBLE: New Bearish Order Block",     "AOBLE: bearish order block detected on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_BULL_TOUCH) == 1, "AOBLE: Price Entered Bullish OB",    "AOBLE: price entered a bullish order block on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_BEAR_TOUCH) == 1, "AOBLE: Price Entered Bearish OB",    "AOBLE: price entered a bearish order block on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_BULL_BR) == 1,    "AOBLE: Bullish Breaker Confirmed",   "AOBLE: bullish breaker block confirmed on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_BEAR_BR) == 1,    "AOBLE: Bearish Breaker Confirmed",   "AOBLE: bearish breaker block confirmed on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_BULL_BOS) == 1,   "AOBLE: Bullish BOS",                 "AOBLE: bullish break of structure on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_BEAR_BOS) == 1,   "AOBLE: Bearish BOS",                 "AOBLE: bearish break of structure on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_BULL_MSS) == 1,   "AOBLE: Bullish MSS / CHoCH",         "AOBLE: bullish MSS / CHoCH on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_BEAR_MSS) == 1,   "AOBLE: Bearish MSS / CHoCH",         "AOBLE: bearish MSS / CHoCH on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_NEW_BSL) == 1,    "AOBLE: New Buy-Side Liquidity Pool", "AOBLE: new buy-side liquidity pool on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_NEW_SSL) == 1,    "AOBLE: New Sell-Side Liquidity Pool", "AOBLE: new sell-side liquidity pool on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_BSL_SWEEP) == 1,  "AOBLE: Buy-Side Liquidity Sweep",    "AOBLE: buy-side liquidity traded through on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_SSL_SWEEP) == 1,  "AOBLE: Sell-Side Liquidity Sweep",   "AOBLE: sell-side liquidity traded through on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_BULL_FVG) == 1,   "AOBLE: Bullish FVG Created",         "AOBLE: bullish fair value gap on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_BEAR_FVG) == 1,   "AOBLE: Bearish FVG Created",         "AOBLE: bearish fair value gap on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_BUY) == 1,        "AOBLE: Confirmed BUY Setup",         "AOBLE: confirmed BUY setup on {{ticker}} ({{interval}}) - analytical reference only")
alertcondition(ev.get(E_SELL) == 1,       "AOBLE: Confirmed SELL Setup",        "AOBLE: confirmed SELL setup on {{ticker}} ({{interval}}) - analytical reference only")
alertcondition(ev.get(E_ENTRY) == 1,      "AOBLE: Pending Entry Filled",        "AOBLE: pending setup entry was reached on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_SL) == 1,         "AOBLE: Stop Loss Hit",               "AOBLE: setup stop loss reached on {{ticker}} ({{interval}})")
alertcondition(ev.get(E_TP) == 1,         "AOBLE: Target Reached",              "AOBLE: setup target reached on {{ticker}} ({{interval}})")

← 返回列表