SMC BUYER & SELLER LIQUIDITY PROFILE PRO

Michael_Fx_Trader · study · 1342 行 · 点赞 459 · TradingView 原页

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

Pine Script

// ====================================================================================================
//  SMC BUYER & SELLER LIQUIDITY PROFILE PRO   [short title: BSLP PRO]
//  Version 1.0.0  |  Pine Script v6  |  Release date: 2026-10-22
// ====================================================================================================
//
//  AUTHOR / PUBLISHER / RIGHTS
//  ---------------------------
//  Author ............ Michael_Fx_Trader
//  Publisher ......... Michael_Fx_Trader
//  Rights holder ..... Michael_Fx_Trader
//  Copyright ......... (c) 2026 Michael_Fx_Trader. All rights reserved.
//  Verification ID ... BSLP-PRO-MFT-1.0.0-20261022
//
//  ORIGINALITY DECLARATION AND AUTHOR VERIFICATION
//  -----------------------------------------------
//  I, Michael_Fx_Trader, declare the following about this script:
//    1. ORIGINAL IMPLEMENTATION. This script is an original implementation. Its volume-allocation
//       engine, buyer/seller estimation, profile-guided pivot refinement, evidence scoring, level
//       lifecycle manager, liquidity-sweep / structure / FVG logic, multi-timeframe confluence,
//       drawing layer, dashboard and alert system were written for this project from scratch.
//    2. NOT COPIED. No source code was copied, forked, translated, or adapted from any other
//       TradingView script (open-source, protected, or invite-only), from any library, or from any
//       third-party repository. No external libraries are imported.
//    3. GENERIC CONCEPTS ONLY. The script uses widely known, non-proprietary market concepts
//       (volume profile, point of control, swing pivots, ATR, liquidity sweeps, market structure,
//       fair value gaps). Concepts are public knowledge; only this specific code is claimed.
//    4. VISUAL REFERENCE. A chart screenshot was used only as a visual design target (layout and
//       colour scheme). No code or data was taken from the tool that produced that screenshot.
//    5. OWNERSHIP. Michael_Fx_Trader is the sole author, publisher and rights holder. No
//       third party holds any rights to this script.
//    6. DEVELOPMENT NOTE. The code was drafted with AI assistance (Claude, by Anthropic) under the
//       author's direction, and was reviewed, adopted and published by the author, who takes full
//       responsibility for it.
//    7. HOW TO VERIFY. Authorship is verifiable through the TradingView publishing account
//       "Michael_Fx_Trader" and the Verification ID above, which is also embedded as the SIGNATURE
//       constant below and shown as a tooltip on the dashboard title.
//
//  Redistribution, resale, re-publication, or removal of this header without written permission
//  of the author is not permitted.
//
//  IMPORTANT DISCLOSURES
//  ---------------------
//  * Educational / analytical tool only. Not financial advice. No profit or accuracy guarantee.
//  * Buyer/seller volume shown here is ESTIMATED from candle data (close location / direction).
//    It is NOT actual bid volume, ask volume, aggressive buying/selling, or institutional order
//    flow. On OANDA XAUUSD and most forex/CFD symbols, "volume" is TICK volume.
//  * The 0-100 score is a relative technical-strength rating produced by this model. It is NOT a
//    probability of profit, an expected return, or a guarantee of a price reaction.
//  * Support / resistance levels are potential reaction areas, not guaranteed turning points.
//  * Swing pivots are confirmed only after the right-side bars close (default: 5 bars = 20 hours on
//    the 4H chart). Levels are drawn from the original pivot candle but were NOT known at that time.
//  * The rolling profile (POC and row widths) naturally changes as the rolling window moves. This
//    is normal profile evolution. Accepted level prices/scores are NOT rewritten with future data.
//
//  METHOD SUMMARY (details in the tooltips of every input)
//  -------------------------------------------------------
//  Rolling profile : last N bars -> price range split into rows -> each candle's volume is
//                    distributed over overlapping rows in proportion to the overlap (sum of
//                    allocations == candle volume). Buy share per candle comes from close location
//                    within the range (optionally blended with candle direction).
//  POC             : first row holding the maximum total volume of the active window.
//  Pivot refinement: at pivot CONFIRMATION a profile is rebuilt from the window that ENDS at the
//                    confirmation bar (no future bars). Candidate rows within an ATR radius are
//                    scored on node strength, local prominence, directional share and proximity.
//                    The best row above the thresholds pulls the final level toward it by the
//                    profile-influence factor (bounded by the search radius).
//  Score (0-100)   : 45% profile evidence, 15% absorption-like proxy, 15% relative pivot volume,
//                    15% wick rejection, 10% SMC confirmation; unavailable components are removed
//                    and the rest renormalised. A small, capped MTF bonus is added afterwards.
//  Lifecycle       : support invalidated by a CONFIRMED close below (level - buffer*ATR); resistance
//                    by a confirmed close above (level + buffer*ATR). Optional wick mode.
//
//  NON-REPAINTING NOTES
//  --------------------
//  All level / structure / sweep / alert logic runs only on confirmed bars (barstate.isconfirmed).
//  Higher-timeframe data uses expression[1] with lookahead_on (completed HTF bars only).
//  The chart drawings are rebuilt on the last bar from the stored state arrays.
//  This script has NOT been platform-compiled or runtime-tested by the author of this file;
//  review historical and real-time behaviour yourself before relying on it.
// ====================================================================================================
//@version=6
indicator(title = "SMC BUYER & SELLER LIQUIDITY PROFILE PRO", shorttitle = "BSLP PRO", overlay = true, max_bars_back = 1500, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
 
// ====================================================================================================
// 1. CONSTANTS (developer-tunable, intentionally NOT user inputs)
// ====================================================================================================
const string SIGNATURE   = "BSLP PRO v1.0.0 | Author & Publisher: Michael_Fx_Trader | (c) 2026 | Verification ID BSLP-PRO-MFT-1.0.0-20261022 | Original implementation"
 
// Profile-evidence weights (sum = 1.0)
const float  W_STR       = 0.40   // relative node strength
const float  W_PROM      = 0.25   // local prominence
const float  W_DIR       = 0.10   // directional (estimated buyer/seller) share
const float  W_PROX      = 0.25   // proximity to the raw pivot
 
// Composite score weights (renormalised over available components)
const float  WS_PROF     = 0.45
const float  WS_ABS      = 0.15
const float  WS_RV       = 0.15
const float  WS_WICK     = 0.15
const float  WS_SMC      = 0.10
 
const int    MIN_HIST_BARS = 60     // minimum bars required to build a trustworthy profile
const float  MIN_VOL_Q     = 0.60   // minimum share of bars with usable volume
const int    MIN_NZ_ROWS   = 8      // minimum number of non-empty rows in a profile
const int    POOL_MAX_AGE  = 400    // liquidity pools older than this many bars are dropped
 
// ====================================================================================================
// 2. INPUTS
// ====================================================================================================
const string G_MAIN = "1. Main Profile Settings"
const string G_BSD  = "2. Buyer/Seller Distribution"
const string G_PIV  = "3. Pivot Detection"
const string G_LVL  = "4. Profile-Confirmed Levels"
const string G_SMC  = "5. Smart Money Concepts"
const string G_SWP  = "6. Liquidity Sweeps"
const string G_MTF  = "7. Multi-Timeframe Confirmation"
const string G_SCR  = "8. Level Scoring"
const string G_ALR  = "9. Alerts"
const string G_DSH  = "10. Dashboard"
const string G_VIS  = "11. Visual Style"
const string G_TP   = "12. Trade Planning (optional, OFF by default)"
 
// ---- 1. Main profile ----
bool   showProfile  = input.bool(true, "Show Rolling Volume Profile", group = G_MAIN, tooltip = "Draws the large horizontal volume profile on the right side of the chart. It is rebuilt on the last bar from the rolling lookback window. Turning it off also removes the POC, node markers and level-row outlines. NOTE: increase the chart's right margin (Chart Settings > Scales > Right margin) so the profile is visible.")
int    profLookback = input.int(600, "Profile Lookback (bars)", minval = 50, maxval = 1000, group = G_MAIN, tooltip = "Number of most recent bars used for the rolling profile. Higher = broader, steadier profile but slower to react. Lower = more local profile. Lower this on low timeframes.")
int    profRows     = input.int(72, "Profile Rows", minval = 10, maxval = 120, group = G_MAIN, tooltip = "Number of horizontal price rows. More rows = finer detail but thinner rows and more drawing objects (each row uses up to 2 boxes). Also used when profiles are rebuilt for pivot evaluation.")
int    profWidth    = input.int(58, "Profile Width (bars)", minval = 10, maxval = 200, group = G_MAIN, tooltip = "Width of the widest (POC) row, measured in chart bars to the right of the profile start.")
int    profOffset   = input.int(8, "Profile Offset (bars)", minval = 0, maxval = 100, group = G_MAIN, tooltip = "Horizontal gap between the latest candle and the start of the profile.")
string profView     = input.string("Buyer / Seller (estimated)", "Profile Display", options = ["Buyer / Seller (estimated)", "Total Volume"], group = G_MAIN, tooltip = "Show the two ESTIMATED components (buyer share / seller share) or only the total volume per row.")
bool   showPOC      = input.bool(true, "Show POC Outline, Line and Label", group = G_MAIN, tooltip = "Orange outline on the Point of Control row (the row with the highest estimated volume in the active window), a horizontal guide line and a price label.")
int    pocLineBars  = input.int(20, "POC Guide Start (bars before last bar)", minval = 0, maxval = 300, group = G_MAIN, tooltip = "How far to the left the POC guide line starts, measured from the latest bar.")
bool   showHVN      = input.bool(false, "Show High-Volume Nodes (HVN)", group = G_MAIN, tooltip = "Marks significant local volume peaks (other than the POC). Adjacent qualifying rows are merged into one zone. A node must be a local maximum, hold at least 45% of the POC volume, and exceed nearby valleys by the prominence threshold.")
bool   showLVN      = input.bool(false, "Show Low-Volume Nodes (LVN)", group = G_MAIN, tooltip = "Marks meaningful local volume valleys (thin-volume areas between two heavier areas). Rows with no data are ignored and the profile must have adequate volume quality.")
float  nodePromThr  = input.float(0.12, "Node Prominence Threshold", minval = 0.02, maxval = 0.60, step = 0.01, group = G_MAIN, tooltip = "Minimum volume difference (as a fraction of POC volume) between a node and its surrounding valleys/peaks. Higher = fewer, cleaner nodes.")
 
// ---- 2. Buyer / Seller distribution ----
string allocModel   = input.string("Close Location", "Buyer/Seller Allocation Model", options = ["Close Location", "Close Location + Candle Direction", "Candle Direction"], group = G_BSD, tooltip = "ESTIMATION METHOD (not real order flow). 'Close Location': buy share = (close - low) / (high - low). 'Close Location + Candle Direction': 70% close location + 30% candle direction. 'Candle Direction': bullish = 100% buy, bearish = 0%, doji = 50%. On forex/CFDs such as OANDA XAUUSD the volume is TICK volume, and these splits are estimates, NOT actual bid/ask volume.")
color  buyCol       = input.color(#1FA384, "Estimated Buyer Volume Color", group = G_BSD)
color  sellCol      = input.color(#4B50B8, "Estimated Seller Volume Color", group = G_BSD)
color  totCol       = input.color(#7A8CA5, "Total Volume Color", group = G_BSD)
int    profTransp   = input.int(30, "Profile Transparency", minval = 0, maxval = 95, group = G_BSD, tooltip = "Higher = more transparent profile boxes.")
bool   reduceDir    = input.bool(true, "Reduce Directional Weight When Volume Quality Is Low", group = G_BSD, tooltip = "When some bars have missing/zero volume, the buyer/seller contribution to pivot evidence is pulled toward neutral (50%) in proportion to the share of usable-volume bars.")
 
// ---- 3. Pivot detection ----
int    pivLeft      = input.int(5, "Pivot Left Bars", minval = 1, maxval = 50, group = G_PIV, tooltip = "Bars to the left that must be lower (swing high) / higher (swing low).")
int    pivRight     = input.int(5, "Pivot Right Bars (confirmation delay)", minval = 1, maxval = 50, group = G_PIV, tooltip = "Bars to the right that must close before a pivot is confirmed. The pivot is only KNOWN this many bars after it happened (5 bars on 4H = 20 hours). Larger = fewer, more reliable pivots but later confirmation.")
int    atrLen       = input.int(14, "ATR Period", minval = 1, maxval = 200, group = G_PIV, tooltip = "ATR length used to normalise the search radius, merge tolerance, invalidation buffer and sweep thresholds.")
int    maxEvalBars  = input.int(5000, "Max History To Evaluate (bars)", minval = 500, maxval = 20000, group = G_PIV, tooltip = "Pivots older than this many bars (counted back from the last bar) are not evaluated. Protects execution time on very long histories.")
bool   useSess      = input.bool(false, "Require Pivot Candle Inside Session", group = G_PIV, tooltip = "Optional session filter: ignore pivots whose candle falls outside the session below (useful when volume quality differs strongly by session).")
string sessStr      = input.session("0000-2400", "Session", group = G_PIV)
 
// ---- 4. Profile-confirmed levels ----
int    pivProfBars  = input.int(300, "Pivot Evaluation Profile Lookback (bars)", minval = 100, maxval = 1000, group = G_LVL, tooltip = "Window (ending at the pivot's CONFIRMATION bar) used to rebuild the historical profile for each pivot. Bounded on purpose for performance. No future bars are used.")
float  searchRad    = input.float(1.20, "Level Search Radius (ATR)", minval = 0.1, maxval = 5.0, step = 0.05, group = G_LVL, tooltip = "Profile nodes are searched within this ATR distance of the raw pivot (never less than one profile row). Larger = more freedom to snap to nodes, but weaker link to the original pivot.")
float  minNodeStr   = input.float(0.08, "Min Profile-Node Strength", minval = 0.0, maxval = 1.0, step = 0.01, group = G_LVL, tooltip = "Minimum node volume relative to the strongest row of that profile (0-1).")
float  minEvidence  = input.float(0.22, "Min Profile Evidence", minval = 0.0, maxval = 1.0, step = 0.01, group = G_LVL, tooltip = "Minimum normalised profile-evidence (0-1) made of node strength 40%, prominence 25%, estimated directional share 10% and proximity 25%.")
int    minScore     = input.int(35, "Min Final Score (0-100)", minval = 0, maxval = 100, group = G_LVL, tooltip = "Levels below this composite score are rejected.")
int    maxLevels    = input.int(20, "Max Active Levels", minval = 1, maxval = 40, group = G_LVL, tooltip = "When exceeded, the weakest active level (lowest score, oldest first on ties) is removed.")
float  mergeDist    = input.float(0.16, "Duplicate-Level Merge Distance (ATR)", minval = 0.0, maxval = 2.0, step = 0.01, group = G_LVL, tooltip = "Same-side levels closer than this are treated as duplicates. A new level replaces them only if its score is strictly higher than the best overlapping one; otherwise it is discarded. Supports and resistances are never merged with each other.")
float  influence    = input.float(0.60, "Profile Influence Factor", minval = 0.0, maxval = 1.0, step = 0.05, group = G_LVL, tooltip = "0 = keep the raw pivot price, 1 = move fully to the selected profile node. Final = raw + factor * (node - raw). Always bounded by the search radius.")
bool   allowRaw     = input.bool(false, "Allow Raw-Pivot Fallback", group = G_LVL, tooltip = "OFF (recommended): pivots without a qualifying profile node are rejected. ON: such pivots may be kept at their raw price; the profile component is then excluded from the score and the level is flagged 'raw fallback' in its tooltip.")
float  breakBuf     = input.float(0.10, "Invalidation Buffer (ATR)", minval = 0.0, maxval = 2.0, step = 0.01, group = G_LVL, tooltip = "A support is invalidated when a CONFIRMED close is below level - buffer*ATR; a resistance when a confirmed close is above level + buffer*ATR.")
bool   wickInval    = input.bool(false, "Wick-Based Invalidation (advanced)", group = G_LVL, tooltip = "OFF (default): confirmed closes only. ON: a wick beyond the buffer also invalidates the level.")
bool   keepHist     = input.bool(false, "Keep Invalidated Levels (history)", group = G_LVL, tooltip = "Keeps a limited record of broken levels, drawn thin, dotted and faded.")
int    histMax      = input.int(8, "Max Invalidated Levels Kept", minval = 1, maxval = 40, group = G_LVL)
 
// ---- 5. Smart Money Concepts ----
bool   smcOn        = input.bool(true, "Enable SMC Engine (calculation)", group = G_SMC, tooltip = "Calculates liquidity pools, structure breaks (BOS/MSS) and fair value gaps on confirmed bars. Needed for the SMC component of the level score and for SMC alerts. Visibility is controlled separately below.")
bool   showPools    = input.bool(false, "Show Liquidity Pools", group = G_SMC, tooltip = "Draws active buy-side (above swing highs) and sell-side (below swing lows) liquidity pools. Equal-ish highs/lows within the cluster tolerance are merged.")
float  poolTol      = input.float(0.25, "Pool Cluster Tolerance (ATR)", minval = 0.0, maxval = 2.0, step = 0.05, group = G_SMC)
int    poolMax      = input.int(8, "Max Pools Per Side", minval = 1, maxval = 20, group = G_SMC)
bool   showStruct   = input.bool(false, "Show BOS / MSS Labels", group = G_SMC, tooltip = "BOS = break of the last swing in the direction of the existing structure state. MSS = break against the previous structure state (e.g. bullish break while the state was bearish). First break from an undefined state is labelled BOS. Breaks need a confirmed CLOSE beyond the swing.")
bool   showFvg      = input.bool(false, "Show Fair Value Gaps", group = G_SMC, tooltip = "Three-candle imbalance: bullish when low[0] > high[2], bearish when high[0] < low[2]. Removed when a close trades fully through the gap.")
float  fvgMin       = input.float(0.10, "Min FVG Size (ATR)", minval = 0.0, maxval = 3.0, step = 0.05, group = G_SMC)
int    fvgMax       = input.int(8, "Max FVGs Kept", minval = 1, maxval = 30, group = G_SMC)
int    smcMaxMarks  = input.int(40, "Max SMC Markers Kept", minval = 5, maxval = 100, group = G_SMC)
 
// ---- 6. Liquidity sweeps ----
bool   sweepOn      = input.bool(true, "Enable Liquidity Sweep Detection", group = G_SWP, tooltip = "Bearish sweep: price trades above a buy-side liquidity pool, then a candle CLOSES back below it. Bullish sweep: price trades below a sell-side pool, then a candle closes back above. A plain breakout that keeps closing beyond the pool is NOT a sweep.")
bool   showSweeps   = input.bool(true, "Show Sweep Markers", group = G_SWP)
float  sweepTol     = input.float(0.02, "Sweep Penetration (ATR)", minval = 0.0, maxval = 2.0, step = 0.01, group = G_SWP, tooltip = "Minimum distance beyond the pool that counts as a breach.")
int    sweepDelay   = input.int(3, "Max Confirmation Delay (bars)", minval = 0, maxval = 20, group = G_SWP, tooltip = "Maximum bars allowed between the breach and the closing reclaim. 0 = the same candle must breach and close back.")
float  sweepMinRej  = input.float(0.30, "Min Rejection Strength (ATR)", minval = 0.0, maxval = 5.0, step = 0.05, group = G_SWP, tooltip = "Required distance between the sweep extreme and the reclaiming close, in ATR.")
 
// ---- 7. Multi-timeframe ----
bool   mtfOn        = input.bool(true, "Enable MTF Confluence", group = G_MTF, tooltip = "Compares each candidate level with CONFIRMED swing highs/lows of higher timeframes (completed HTF bars only: expression[1] + lookahead_on). Timeframes not higher than the chart are ignored. If HTF data is unavailable the chart keeps working without the bonus.")
bool   useTf1       = input.bool(true, "Use Timeframe 1", group = G_MTF, inline = "t1")
string tf1          = input.timeframe("D", "TF", group = G_MTF, inline = "t1")
bool   useTf2       = input.bool(true, "Use Timeframe 2", group = G_MTF, inline = "t2")
string tf2          = input.timeframe("W", "TF", group = G_MTF, inline = "t2")
bool   useTf3       = input.bool(false, "Use Timeframe 3", group = G_MTF, inline = "t3")
string tf3          = input.timeframe("60", "TF", group = G_MTF, inline = "t3")
int    htfPivLen    = input.int(3, "HTF Pivot Length", minval = 1, maxval = 20, group = G_MTF, tooltip = "Left/right bars for HTF swing detection (confirmed on completed HTF bars).")
float  mtfTol       = input.float(0.50, "MTF Match Tolerance (ATR)", minval = 0.05, maxval = 3.0, step = 0.05, group = G_MTF)
float  mtfMax       = input.float(6.0, "Max MTF Score Bonus (points)", minval = 0.0, maxval = 15.0, step = 0.5, group = G_MTF, tooltip = "Capped bonus added to the 0-100 score. At most two matching timeframes count (they are correlated), so the bonus can never grow without limit.")
 
// ---- 8. Level scoring ----
bool   rvOn         = input.bool(true, "Use Relative Pivot Volume", group = G_SCR)
int    volLen       = input.int(20, "Relative Volume Baseline (bars)", minval = 5, maxval = 200, group = G_SCR, tooltip = "Pivot-candle volume is divided by its SMA of this length. The ratio is capped at 3x so one extreme candle cannot dominate.")
bool   wickOn       = input.bool(true, "Use Wick Rejection", group = G_SCR)
bool   absOn        = input.bool(true, "Use Absorption-Like Proxy", group = G_SCR, tooltip = "Looks around the pivot for candles with elevated volume but a small real body. This is only an absorption-LIKE proxy from candle data; it cannot confirm real institutional absorption.")
int    absWin       = input.int(3, "Absorption Window (bars around pivot)", minval = 1, maxval = 10, group = G_SCR, tooltip = "Limited to the pivot-right length because only bars up to the confirmation bar are known.")
bool   smcInScore   = input.bool(true, "Use SMC Confirmation In Score", group = G_SCR, tooltip = "Adds sweep / structure / FVG evidence found around the pivot (needs the SMC engine).")
bool   volFilterOn  = input.bool(false, "Volatility Condition Filter (status)", group = G_SCR, tooltip = "Shows 'Compressed / Normal / Expanded' (ATR vs its 100-bar average) in the dashboard.")
bool   volAdjust    = input.bool(false, "Raise Evidence Threshold In Expanded Volatility", group = G_SCR, tooltip = "If the filter is on and ATR is above 1.35x its average, the minimum profile evidence is raised by 0.05. The score formula itself is never altered.")
 
// ---- 9. Alerts ----
bool   useDynAlerts = input.bool(false, "Send Dynamic alert() Messages", group = G_ALR, tooltip = "Adds alert() calls with detailed text (event, symbol, timeframe, price, score, reason). When using the separate alertcondition entries from the alert dialog, keep this OFF to avoid duplicate notifications. Events fire only on confirmed bars.")
int    highScoreThr = input.int(70, "High-Score Level Threshold", minval = 1, maxval = 100, group = G_ALR)
 
// ---- 10. Dashboard ----
bool   dashOn       = input.bool(true, "Show Dashboard", group = G_DSH)
string dashPos      = input.string("Bottom Left", "Position", options = ["Top Left", "Top Right", "Bottom Left", "Bottom Right"], group = G_DSH)
string dashSize     = input.string("Small", "Text Size", options = ["Tiny", "Small", "Normal"], group = G_DSH)
string dashTheme    = input.string("Dark", "Theme", options = ["Dark", "Light"], group = G_DSH)
 
// ---- 11. Visual style ----
color  supCol       = input.color(#2ECC71, "Support Color", group = G_VIS)
color  resCol       = input.color(#E53935, "Resistance Color", group = G_VIS)
color  goldCol      = input.color(#FFC107, "Confirmed Pivot Core Color", group = G_VIS)
color  rawCol       = input.color(#8A8F98, "Raw Pivot Marker Color", group = G_VIS)
color  pocCol       = input.color(#FF9800, "POC Color", group = G_VIS)
string lineStyleIn  = input.string("Solid", "Level Line Style", options = ["Solid", "Dashed", "Dotted"], group = G_VIS)
bool   showLevels   = input.bool(true, "Show Level Lines", group = G_VIS)
bool   showMarkers  = input.bool(true, "Show Historical Pivot Markers", group = G_VIS, tooltip = "Layered circle at each ACCEPTED pivot: rings by score (<50: 1, 50-65: 2, 66-81: 3, 82+: 4), gold core. Rejected pivots get no marker.")
bool   showMarkScore = input.bool(true, "Show Score Inside Marker", group = G_VIS)
bool   showRaw      = input.bool(true, "Show Raw Pivot Marker", group = G_VIS, tooltip = "Subtle grey circle at the ORIGINAL raw pivot price (a reference point, not the final level).")
bool   showGuide    = input.bool(true, "Show Dotted Relocation Guide", group = G_VIS, tooltip = "Dotted vertical connector between the raw pivot price and the final level price at the pivot's historical time. It only shows the adjustment, not a price path.")
bool   showEdgeDots = input.bool(true, "Show Right-Edge Dots", group = G_VIS)
bool   showEdgeScore = input.bool(true, "Show Right-Edge Score Labels", group = G_VIS)
bool   showRowOutline = input.bool(true, "Outline Profile Rows Of Active Levels", group = G_VIS, tooltip = "Outlines the profile row containing each active level (green support / red resistance). If several levels share a row, the highest score wins; the others are listed in that level's label tooltip.")
int    dotOff       = input.int(2, "Right-Edge Dot Offset (bars)", minval = 0, maxval = 20, group = G_VIS)
string dotSizeIn    = input.string("Normal", "Right-Edge Dot Size", options = ["Tiny", "Small", "Normal", "Large"], group = G_VIS)
string scoreSizeIn  = input.string("Tiny", "Right-Edge Score Text Size", options = ["Tiny", "Small", "Normal"], group = G_VIS)
string coreSizeIn   = input.string("Tiny", "Marker Score Text Size", options = ["Tiny", "Small", "Normal"], group = G_VIS, tooltip = "Pine label sizes are fixed in pixels and do not scale with chart zoom. Adjust here if the number inside the marker looks cramped.")
 
// ---- 12. Trade planning (optional) ----
bool   tpOn         = input.bool(false, "ENABLE Trade-Planning Annotations (master switch)", group = G_TP, tooltip = "OFF by default. When ON, an OBSERVATION zone is drawn when price reacts at an active level (rejection wick, sweep or structure break). These are reference annotations, NOT trade recommendations. Targets are risk/reward references, not predictions, and the nearest opposite level is never assumed to be the target.")
int    tpMinScore   = input.int(50, "Min Level Score For Observation", minval = 0, maxval = 100, group = G_TP)
float  tpTouch      = input.float(0.25, "Touch Tolerance (ATR)", minval = 0.0, maxval = 2.0, step = 0.05, group = G_TP)
float  tpInv        = input.float(0.50, "Invalidation Reference Beyond Level (ATR)", minval = 0.1, maxval = 5.0, step = 0.05, group = G_TP)
float  tpRR1        = input.float(1.5, "Reference R:R 1", minval = 0.5, maxval = 10.0, step = 0.5, group = G_TP)
float  tpRR2        = input.float(2.5, "Reference R:R 2", minval = 0.5, maxval = 10.0, step = 0.5, group = G_TP)
int    tpCooldown   = input.int(12, "Cooldown Per Level (bars)", minval = 1, maxval = 200, group = G_TP)
 
// ====================================================================================================
// 3. TYPES
// ====================================================================================================
type Level
    bool   isSup
    int    pivBar
    int    confBar
    int    pivTime
    int    confTime
    float  rawPrice
    float  nodePrice
    float  price
    float  score
    float  profEv
    float  nodeStr
    float  wickS
    float  rvS
    float  absS
    float  smcS
    float  mtfB
    bool   guided
    int    endBar
    int    lastPlan = -1000000
 
type Pool
    float  price
    int    bar
    int    cnt
    int    breachBar
    float  ext
 
type Fvg
    float  top
    float  bot
    int    bar
    bool   bull
 
type Mk
    int    kind      // 1 bull sweep, 2 bear sweep, 3 bull BOS, 4 bear BOS, 5 bull MSS, 6 bear MSS
    int    x0
    int    x
    float  y
    string txt
    string tip
 
// ====================================================================================================
// 4. PER-BAR SERIES AND PERSISTENT STATE
// ====================================================================================================
float atrV    = ta.atr(atrLen)
float atrBase = ta.sma(atrV, 100)
float volSma  = ta.sma(volume, volLen)
bool  inSess  = not na(time(timeframe.period, sessStr))
float ph      = ta.pivothigh(high, pivLeft, pivRight)
float pl      = ta.pivotlow(low, pivLeft, pivRight)
 
var array<Level> lvls      = array.new<Level>()
var array<Level> hist      = array.new<Level>()
var array<Pool>  buyPools  = array.new<Pool>()
var array<Pool>  sellPools = array.new<Pool>()
var array<Fvg>   fvgs      = array.new<Fvg>()
var array<Mk>    marks     = array.new<Mk>()
 
var array<float> pTot = array.new<float>(profRows, 0.0)
var array<float> pBuy = array.new<float>(profRows, 0.0)
var array<float> mTot = array.new<float>(profRows, 0.0)
var array<float> mBuy = array.new<float>(profRows, 0.0)
 
var array<line>  dLines  = array.new<line>()
var array<label> dLabels = array.new<label>()
var array<box>   dBoxes  = array.new<box>()
 
var int   lastBullSweep = -1000000
var int   lastBearSweep = -1000000
var int   lastBullBreak = -1000000
var int   lastBearBreak = -1000000
var int   lastBullFvg   = -1000000
var int   lastBearFvg   = -1000000
var int   trend         = 0
var float lastSH        = na
var float lastSL        = na
var int   lastSHbar     = na
var int   lastSLbar     = na
var bool  shBroken      = false
var bool  slBroken      = false
 
var string lastSweepTxt = "None yet"
var int    lastSweepBar = na
 
var bool  planOn    = false
var int   planSide  = 0
var int   planBar   = na
var float planEntry = na
var float planInv   = na
var float planT1    = na
var float planT2    = na
 
// ---- per-bar event flags (reset on every bar) ----
bool   evNewSup    = false
bool   evNewRes    = false
bool   evSupBreak  = false
bool   evResBreak  = false
bool   evBullSweep = false
bool   evBearSweep = false
bool   evBullBreak = false
bool   evBearBreak = false
bool   evHighScore = false
string msgNewSup    = ""
string msgNewRes    = ""
string msgSupBreak  = ""
string msgResBreak  = ""
string msgBullSweep = ""
string msgBearSweep = ""
string msgBullBreak = ""
string msgBearBreak = ""
string msgHighScore = ""
 
// ---- higher-timeframe confirmed references ----
f_tf_ok(string tf) =>
    timeframe.in_seconds(tf) > timeframe.in_seconds(timeframe.period)
 
f_htf() =>
    float hph = ta.pivothigh(high, htfPivLen, htfPivLen)
    float hpl = ta.pivotlow(low, htfPivLen, htfPivLen)
    var float lastPH = na
    var float lastPL = na
    var int   hdir   = 0
    if not na(hph)
        lastPH := hph
    if not na(hpl)
        lastPL := hpl
    if not na(lastPH) and close > lastPH
        hdir := 1
    else if not na(lastPL) and close < lastPL
        hdir := -1
    [lastPH[1], lastPL[1], hdir[1]]
 
bool  v1ok = mtfOn and useTf1 and f_tf_ok(tf1)
bool  v2ok = mtfOn and useTf2 and f_tf_ok(tf2)
bool  v3ok = mtfOn and useTf3 and f_tf_ok(tf3)
float h1 = na
float l1 = na
int   d1 = na
float h2 = na
float l2 = na
int   d2 = na
float h3 = na
float l3 = na
int   d3 = na
if v1ok
    [a1, b1, c1] = request.security(syminfo.tickerid, tf1, f_htf(), lookahead = barmerge.lookahead_on)
    h1 := a1
    l1 := b1
    d1 := c1
if v2ok
    [a2, b2, c2] = request.security(syminfo.tickerid, tf2, f_htf(), lookahead = barmerge.lookahead_on)
    h2 := a2
    l2 := b2
    d2 := c2
if v3ok
    [a3, b3, c3] = request.security(syminfo.tickerid, tf3, f_htf(), lookahead = barmerge.lookahead_on)
    h3 := a3
    l3 := b3
    d3 := c3
 
// ====================================================================================================
// 5. HELPER FUNCTIONS
// ====================================================================================================
f_clamp(float x, float lo, float hi) =>
    math.max(lo, math.min(hi, x))
 
f_clamp01(float x) =>
    math.max(0.0, math.min(1.0, x))
 
f_size(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Large"  => size.large
        "Huge"   => size.huge
        => size.normal
 
f_lstyle(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
        "Top Right"    => position.top_right
        "Bottom Right" => position.bottom_right
        => position.bottom_left
 
f_px(float x) =>
    na(x) ? "n/a" : str.tostring(x, format.mintick)
 
f_n2(float x) =>
    na(x) ? "n/a" : str.tostring(x, "0.00")
 
f_msg(string typ, float px, float sc, string why) =>
    typ + " | " + syminfo.ticker + " " + timeframe.period + " | price " + str.tostring(px, format.mintick) + (na(sc) ? "" : " | score " + str.tostring(sc, "#")) + " | " + why
 
// price range of the last nBars bars (high/low extremes)
f_range(int nBars) =>
    float lo = 1.0e18
    float hi = -1.0e18
    if nBars > 0
        for i = 0 to nBars - 1
            float h = high[i]
            float l = low[i]
            if not na(h) and not na(l)
                hi := math.max(hi, h)
                lo := math.min(lo, l)
    [lo, hi]
 
// estimated buyer share (0..1) of one candle
f_buy_frac(float o, float h, float l, float c, string model) =>
    float rng = h - l
    float clv = rng > 0 ? (c - l) / rng : 0.5
    float dr = c > o ? 1.0 : c < o ? 0.0 : 0.5
    float r = switch model
        "Candle Direction" => dr
        "Close Location + Candle Direction" => 0.7 * clv + 0.3 * dr
        => clv
    f_clamp01(r)
 
// Builds a profile over the last nBars bars into tot[] / buy[]; returns the number of bars with usable volume.
// Each candle's volume is split over the rows it overlaps, proportionally to the overlap (sum == candle volume).
f_build(array<float> tot, array<float> buy, int nBars, float lo, float rs, int rows) =>
    int validBars = 0
    if nBars > 0 and rs > 0
        for i = 0 to nBars - 1
            float h = high[i]
            float l = low[i]
            float v = volume[i]
            if not na(h) and not na(l) and not na(v) and v > 0
                validBars += 1
                float o = open[i]
                float c = close[i]
                float rng = h - l
                float bf = f_buy_frac(o, h, l, c, allocModel)
                if rng <= 0
                    int r0 = int(f_clamp(math.floor((c - lo) / rs), 0, rows - 1))
                    array.set(tot, r0, array.get(tot, r0) + v)
                    array.set(buy, r0, array.get(buy, r0) + v * bf)
                else
                    int r1 = int(f_clamp(math.floor((l - lo) / rs), 0, rows - 1))
                    int r2 = int(f_clamp(math.floor((h - lo) / rs), 0, rows - 1))
                    for r = r1 to r2
                        float rb = lo + r * rs
                        float ov = math.min(h, rb + rs) - math.max(l, rb)
                        if ov > 0
                            float part = v * ov / rng
                            array.set(tot, r, array.get(tot, r) + part)
                            array.set(buy, r, array.get(buy, r) + part * bf)
    validBars
 
// Profile-guided node search for one pivot, using ONLY bars up to the current (confirmation) bar.
f_eval_profile(bool isSup, float pivPrice, float atrNow, int w) =>
    bool  ok    = false
    float nodeP = na
    float nodeS = na
    float promV = na
    float dirV  = na
    float proxV = na
    float ev    = na
    float q     = na
    int nBars = math.min(w, bar_index + 1)
    if nBars >= MIN_HIST_BARS
        [lo, hi] = f_range(nBars)
        if hi > lo
            float rs = math.max((hi - lo) / profRows, syminfo.mintick)
            array.fill(pTot, 0.0)
            array.fill(pBuy, 0.0)
            int vb = f_build(pTot, pBuy, nBars, lo, rs, profRows)
            q := vb / float(nBars)
            float mx = array.max(pTot)
            int nz = 0
            for v in pTot
                if v > 0
                    nz += 1
            if q >= MIN_VOL_Q and mx > 0 and nz >= MIN_NZ_ROWS
                float rad = math.max(searchRad * atrNow, rs)
                int rLo = int(f_clamp(math.floor((pivPrice - rad - lo) / rs), 0, profRows - 1))
                int rHi = int(f_clamp(math.floor((pivPrice + rad - lo) / rs), 0, profRows - 1))
                float bestEv = -1.0
                for r = rLo to rHi
                    float vr = array.get(pTot, r)
                    float strength = vr / mx
                    if vr > 0 and strength >= minNodeStr
                        float cen = lo + (r + 0.5) * rs
                        float dist = math.abs(cen - pivPrice)
                        if dist <= rad
                            float sumN = 0.0
                            int cntN = 0
                            for k = -3 to 3
                                if k != 0
                                    int rr = r + k
                                    if rr >= 0 and rr < profRows
                                        sumN += array.get(pTot, rr)
                                        cntN += 1
                            float meanN = cntN > 0 ? sumN / cntN : vr
                            float prom = f_clamp01((vr - meanN) / (0.5 * mx))
                            float shr = array.get(pBuy, r) / vr
                            float dRaw = isSup ? shr : 1.0 - shr
                            float dAdj = reduceDir ? 0.5 + (dRaw - 0.5) * q : dRaw
                            float prx = 1.0 - dist / rad
                            float e = W_STR * strength + W_PROM * prom + W_DIR * dAdj + W_PROX * prx
                            if e > bestEv
                                bestEv := e
                                nodeP := cen
                                nodeS := strength
                                promV := prom
                                dirV := dAdj
                                proxV := prx
                ok := bestEv >= 0
                ev := bestEv >= 0 ? bestEv : na
    [ok, nodeP, nodeS, promV, dirV, proxV, ev, q]
 
// SMC evidence around a pivot (0..1) or na when nothing applicable is enabled
f_smc_score(bool isSup, int pb) =>
    float num = 0.0
    float den = 0.0
    if sweepOn
        den += 0.5
        bool hit = isSup ? lastBullSweep >= pb - pivRight : lastBearSweep >= pb - pivRight
        num += hit ? 0.5 : 0.0
    den += 0.3
    bool hit2 = isSup ? lastBullBreak >= pb : lastBearBreak >= pb
    num += hit2 ? 0.3 : 0.0
    den += 0.2
    bool hit3 = isSup ? lastBullFvg >= pb - 1 : lastBearFvg >= pb - 1
    num += hit3 ? 0.2 : 0.0
    den > 0 ? num / den : na
 
f_mtf_one(bool isSup, float price, float tol, float hRef, float lRef, int hd) =>
    float r = 0.0
    float ref = isSup ? lRef : hRef
    if not na(ref) and math.abs(ref - price) <= tol
        r := 0.7
        if hd == (isSup ? 1 : -1)
            r += 0.3
    r
 
f_mtf_bonus(bool isSup, float price, float atrNow) =>
    float tol = mtfTol * atrNow
    float tot = 0.0
    if v1ok
        tot += f_mtf_one(isSup, price, tol, h1, l1, d1)
    if v2ok
        tot += f_mtf_one(isSup, price, tol, h2, l2, d2)
    if v3ok
        tot += f_mtf_one(isSup, price, tol, h3, l3, d3)
    mtfMax * math.min(tot, 2.0) / 2.0
 
f_composite(float ev, float ab, float rv, float wk, float sm) =>
    float num = 0.0
    float den = 0.0
    if not na(ev)
        num += WS_PROF * ev
        den += WS_PROF
    if not na(ab)
        num += WS_ABS * ab
        den += WS_ABS
    if not na(rv)
        num += WS_RV * rv
        den += WS_RV
    if not na(wk)
        num += WS_WICK * wk
        den += WS_WICK
    if not na(sm)
        num += WS_SMC * sm
        den += WS_SMC
    den > 0 ? num / den : na
 
f_tip(Level L) =>
    string t = (L.isSup ? "SUPPORT" : "RESISTANCE") + " | Score " + str.tostring(L.score, "#") + "/100"
    t += "\n(relative technical-strength rating - NOT a probability, NOT a guarantee)"
    t += "\nRaw pivot: " + f_px(L.rawPrice) + "  @ " + str.format_time(L.pivTime, "yyyy-MM-dd HH:mm", syminfo.timezone)
    t += "\nConfirmed: " + str.format_time(L.confTime, "yyyy-MM-dd HH:mm", syminfo.timezone) + "  (" + str.tostring(L.confBar - L.pivBar) + " bars after the pivot)"
    t += "\nSelected profile node: " + (L.guided ? f_px(L.nodePrice) : "none (raw fallback)")
    t += "\nFinal level: " + f_px(L.price)
    t += "\nProfile evidence: " + f_n2(L.profEv) + "  | node strength: " + f_n2(L.nodeStr)
    t += "\nWick rejection: " + f_n2(L.wickS) + "  | rel. volume: " + f_n2(L.rvS)
    t += "\nAbsorption-like proxy: " + f_n2(L.absS) + "  | SMC: " + f_n2(L.smcS)
    t += "\nMTF bonus: +" + str.tostring(L.mtfB, "0.0") + " pts"
    t += "\nVolume is estimated from candles (tick volume on forex/CFD)."
    t
 
// ---- the full evaluation of one confirmed pivot; returns the accepted Level or na ----
f_try_level(bool isSup, float rawP) =>
    Level res = na
    float atrNow = atrV
    int   R = pivRight
    bool  ok = not na(atrNow) and atrNow > 0 and not na(rawP) and bar_index >= R + 1
    if ok and useSess
        ok := inSess[R]
    float effEv = minEvidence
    if ok and volFilterOn and volAdjust and not na(atrBase) and atrBase > 0 and atrNow / atrBase > 1.35
        effEv := math.min(1.0, minEvidence + 0.05)
    float nodeP = na
    float nodeS = na
    float ev = na
    bool  guided = false
    float finalP = rawP
    float sc = na
    float wk = na
    float rv = na
    float ab = na
    float sm = na
    float mtfB = 0.0
    // ---- 1. profile refinement ----
    if ok
        [okP, nP, nS, pr, dr, px, e, q] = f_eval_profile(isSup, rawP, atrNow, pivProfBars)
        if okP and not na(e) and e >= effEv and nS >= minNodeStr
            guided := true
            nodeP := nP
            nodeS := nS
            ev := e
            finalP := rawP + influence * (nP - rawP)
        else if not allowRaw
            ok := false
    // ---- 2. candle evidence ----
    if ok
        float hP = high[R]
        float lP = low[R]
        float oP = open[R]
        float cP = close[R]
        float vP = volume[R]
        float rngP = hP - lP
        if wickOn and rngP > 0
            float wickLen = isSup ? math.min(oP, cP) - lP : hP - math.max(oP, cP)
            wk := f_clamp01((wickLen / rngP - 0.10) / 0.50)
            bool dirOk = isSup ? cP >= oP : cP <= oP
            wk := dirOk ? wk : wk * 0.85
        if rvOn
            float base = volSma[R]
            if not na(vP) and vP > 0 and not na(base) and base > 0
                rv := f_clamp01((math.min(vP / base, 3.0) - 0.5) / 1.5)
        if absOn
            int wa = math.min(absWin, R)
            float best = 0.0
            int used = 0
            for k = R - wa to R + wa
                float vk = volume[k]
                float bk = volSma[k]
                float rk = high[k] - low[k]
                if not na(vk) and vk > 0 and not na(bk) and bk > 0 and not na(rk) and rk > 0
                    used += 1
                    float bodyR = math.abs(close[k] - open[k]) / rk
                    float clv = (close[k] - low[k]) / rk
                    bool ctx = isSup ? clv >= 0.4 : clv <= 0.6
                    float s = f_clamp01(vk / bk - 1.0) * f_clamp01(1.0 - bodyR / 0.5) * (ctx ? 1.0 : 0.5)
                    best := math.max(best, s)
            if used >= 3
                ab := best
        if smcOn and smcInScore
            sm := f_smc_score(isSup, bar_index - R)
        float comp = f_composite(guided ? ev : na, ab, rv, wk, sm)
        if mtfOn
            mtfB := f_mtf_bonus(isSup, finalP, atrNow)
        sc := na(comp) ? na : f_clamp(comp * 100.0 + mtfB, 0.0, 100.0)
        ok := not na(sc) and sc >= minScore
    // ---- 3. reject levels that were already broken between pivot and confirmation ----
    if ok
        float buf = breakBuf * atrNow
        for i = 0 to R - 1
            if isSup
                if (wickInval ? low[i] : close[i]) < finalP - buf
                    ok := false
            else
                if (wickInval ? high[i] : close[i]) > finalP + buf
                    ok := false
    // ---- 4. same-side merge / replacement rule and level cap ----
    if ok
        float tolM = mergeDist * atrNow
        array<int> ov = array.new<int>()
        float maxOld = -1.0
        for [i, o] in lvls
            if o.isSup == isSup and math.abs(o.price - finalP) <= tolM
                array.push(ov, i)
                maxOld := math.max(maxOld, o.score)
        int nov = array.size(ov)
        if nov > 0 and sc <= maxOld
            ok := false
        else if nov > 0
            for j = nov - 1 to 0
                array.remove(lvls, array.get(ov, j))
    if ok
        if array.size(lvls) >= maxLevels
            int wi = 0
            float ws = 1.0e9
            int wb = 0
            for [i, o] in lvls
                if o.score < ws or (o.score == ws and o.pivBar < wb)
                    ws := o.score
                    wi := i
                    wb := o.pivBar
            if sc > ws
                array.remove(lvls, wi)
            else
                ok := false
    if ok
        res := Level.new(isSup = isSup, pivBar = bar_index - R, confBar = bar_index, pivTime = time[R], confTime = time, rawPrice = rawP, nodePrice = nodeP, price = finalP, score = sc, profEv = ev, nodeStr = nodeS, wickS = wk, rvS = rv, absS = ab, smcS = sm, mtfB = mtfB, guided = guided)
        array.push(lvls, res)
    res
 
f_add_mark(int kind, int x0, int x, float y, string txt, string tip) =>
    array.push(marks, Mk.new(kind = kind, x0 = x0, x = x, y = y, txt = txt, tip = tip))
    if array.size(marks) > smcMaxMarks
        array.shift(marks)
    true
 
f_near_level(bool wantSup, float price, float atrNow) =>
    bool r = false
    for o in lvls
        if o.isSup == wantSup and math.abs(o.price - price) <= 0.5 * atrNow
            r := true
    r
 
f_near_htf(bool useLow, float price, float atrNow) =>
    float tol = mtfTol * atrNow
    float a = useLow ? l1 : h1
    float b = useLow ? l2 : h2
    float c = useLow ? l3 : h3
    (v1ok and not na(a) and math.abs(a - price) <= tol) or (v2ok and not na(b) and math.abs(b - price) <= tol) or (v3ok and not na(c) and math.abs(c - price) <= tol)
 
// ---- drawing helpers (every object is tracked so it can be deleted on the next refresh) ----
f_line(int x1, float y1, int x2, float y2, color c, string stl, int w) =>
    array.push(dLines, line.new(x1, y1, x2, y2, xloc = xloc.bar_index, color = c, style = stl, width = w))
    true
 
f_lab(int x, float y, string txt, string stl, color bg, color tc, string sz, string tip) =>
    array.push(dLabels, label.new(x, y, txt, xloc = xloc.bar_index, yloc = yloc.price, color = bg, style = stl, textcolor = tc, size = sz, tooltip = tip))
    true
 
f_box(int l, float t, int r, float b, color bord, color bg, int bw) =>
    if r > l
        array.push(dBoxes, box.new(l, t, r, b, border_color = bord, border_width = bw, xloc = xloc.bar_index, bgcolor = bg))
    true
 
f_clear() =>
    for ln in dLines
        line.delete(ln)
    array.clear(dLines)
    for lb in dLabels
        label.delete(lb)
    array.clear(dLabels)
    for bx in dBoxes
        box.delete(bx)
    array.clear(dBoxes)
    true
 
// ====================================================================================================
// 6. CONFIRMED-BAR LOGIC (level lifecycle, SMC engine, new pivots, trade-planning observation)
// ====================================================================================================
if barstate.isconfirmed and not na(atrV) and atrV > 0
    float a = atrV
 
    // ---- 6.1 level invalidation (confirmed closes by default) ----
    int nLv = array.size(lvls)
    if nLv > 0
        for i = nLv - 1 to 0
            Level o = array.get(lvls, i)
            if bar_index > o.confBar
                float buf = breakBuf * a
                bool brk = false
                if o.isSup
                    brk := (wickInval ? low : close) < o.price - buf
                else
                    brk := (wickInval ? high : close) > o.price + buf
                if brk
                    array.remove(lvls, i)
                    if o.isSup
                        evSupBreak := true
                        msgSupBreak := f_msg("SUPPORT BROKEN", o.price, o.score, "confirmed close below support minus buffer")
                    else
                        evResBreak := true
                        msgResBreak := f_msg("RESISTANCE BROKEN", o.price, o.score, "confirmed close above resistance plus buffer")
                    if keepHist
                        o.endBar := bar_index
                        array.push(hist, o)
                        if array.size(hist) > histMax
                            array.shift(hist)
 
    // ---- 6.2 SMC engine ----
    if smcOn
        // sweeps of buy-side liquidity (bearish sweep)
        int nb = array.size(buyPools)
        if nb > 0 and sweepOn
            for i = nb - 1 to 0
                Pool p = array.get(buyPools, i)
                bool rm = false
                if bar_index - p.bar > POOL_MAX_AGE
                    rm := true
                else
                    if na(p.breachBar)
                        if high > p.price + sweepTol * a
                            p.breachBar := bar_index
                            p.ext := high
                    else
                        p.ext := math.max(p.ext, high)
                    if not na(p.breachBar)
                        if close < p.price
                            float rej = (p.ext - close) / a
                            int dly = bar_index - p.breachBar
                            if dly <= sweepDelay and rej >= sweepMinRej
                                bool nearL = f_near_level(false, p.price, a)
                                bool nearH = f_near_htf(false, p.price, a)
                                evBearSweep := true
                                lastBearSweep := bar_index
                                lastSweepBar := bar_index
                                lastSweepTxt := "Bearish (BSL) @ " + f_px(p.price)
                                string why = "BSL swept: reclaim close after " + str.tostring(dly) + " bar(s), rejection " + str.tostring(rej, "0.00") + " ATR" + (nearL ? ", near active resistance" : "") + (nearH ? ", near HTF swing high" : "")
                                msgBearSweep := f_msg("BEARISH LIQUIDITY SWEEP", p.price, na, why)
                                f_add_mark(2, bar_index, bar_index, p.ext, "BSL" + (nearL or nearH ? " +" : ""), "Bearish liquidity sweep (buy-side liquidity taken).\n" + why + "\nA sweep is context, not a trade signal.")
                            rm := true
                        else if bar_index - p.breachBar >= sweepDelay
                            rm := true
                if rm
                    array.remove(buyPools, i)
        // sweeps of sell-side liquidity (bullish sweep)
        int ns = array.size(sellPools)
        if ns > 0 and sweepOn
            for i = ns - 1 to 0
                Pool p = array.get(sellPools, i)
                bool rm = false
                if bar_index - p.bar > POOL_MAX_AGE
                    rm := true
                else
                    if na(p.breachBar)
                        if low < p.price - sweepTol * a
                            p.breachBar := bar_index
                            p.ext := low
                    else
                        p.ext := math.min(p.ext, low)
                    if not na(p.breachBar)
                        if close > p.price
                            float rej = (close - p.ext) / a
                            int dly = bar_index - p.breachBar
                            if dly <= sweepDelay and rej >= sweepMinRej
                                bool nearL = f_near_level(true, p.price, a)
                                bool nearH = f_near_htf(true, p.price, a)
                                evBullSweep := true
                                lastBullSweep := bar_index
                                lastSweepBar := bar_index
                                lastSweepTxt := "Bullish (SSL) @ " + f_px(p.price)
                                string why = "SSL swept: reclaim close after " + str.tostring(dly) + " bar(s), rejection " + str.tostring(rej, "0.00") + " ATR" + (nearL ? ", near active support" : "") + (nearH ? ", near HTF swing low" : "")
                                msgBullSweep := f_msg("BULLISH LIQUIDITY SWEEP", p.price, na, why)
                                f_add_mark(1, bar_index, bar_index, p.ext, "SSL" + (nearL or nearH ? " +" : ""), "Bullish liquidity sweep (sell-side liquidity taken).\n" + why + "\nA sweep is context, not a trade signal.")
                            rm := true
                        else if bar_index - p.breachBar >= sweepDelay
                            rm := true
                if rm
                    array.remove(sellPools, i)
 
        // structure breaks (confirmed close beyond the last confirmed swing)
        if not na(lastSH) and not shBroken and close > lastSH
            shBroken := true
            string typ = trend == -1 ? "MSS" : "BOS"
            string why = "Bullish " + typ + ": close above swing high " + f_px(lastSH) + " (previous state: " + (trend == 1 ? "bullish" : trend == -1 ? "bearish" : "undefined") + ")"
            trend := 1
            lastBullBreak := bar_index
            evBullBreak := true
            msgBullBreak := f_msg("BULLISH STRUCTURE BREAK (" + typ + ")", lastSH, na, why)
            f_add_mark(typ == "MSS" ? 5 : 3, lastSHbar, bar_index, lastSH, typ, why)
        if not na(lastSL) and not slBroken and close < lastSL
            slBroken := true
            string typ = trend == 1 ? "MSS" : "BOS"
            string why = "Bearish " + typ + ": close below swing low " + f_px(lastSL) + " (previous state: " + (trend == 1 ? "bullish" : trend == -1 ? "bearish" : "undefined") + ")"
            trend := -1
            lastBearBreak := bar_index
            evBearBreak := true
            msgBearBreak := f_msg("BEARISH STRUCTURE BREAK (" + typ + ")", lastSL, na, why)
            f_add_mark(typ == "MSS" ? 6 : 4, lastSLbar, bar_index, lastSL, typ, why)
 
        // fair value gaps: mitigation first, then detection
        int nf = array.size(fvgs)
        if nf > 0
            for i = nf - 1 to 0
                Fvg g = array.get(fvgs, i)
                if (g.bull and close < g.bot) or (not g.bull and close > g.top)
                    array.remove(fvgs, i)
        if bar_index >= 2
            if low > high[2] and low - high[2] >= fvgMin * a
                array.push(fvgs, Fvg.new(top = low, bot = high[2], bar = bar_index - 2, bull = true))
                lastBullFvg := bar_index
            else if high < low[2] and low[2] - high >= fvgMin * a
                array.push(fvgs, Fvg.new(top = low[2], bot = high, bar = bar_index - 2, bull = false))
                lastBearFvg := bar_index
            if array.size(fvgs) > fvgMax
                array.shift(fvgs)
 
        // swings and liquidity pools (new swing confirmed on this bar)
        if not na(ph)
            lastSH := ph
            lastSHbar := bar_index - pivRight
            shBroken := false
            bool merged = false
            for p in buyPools
                if not merged and na(p.breachBar) and math.abs(p.price - ph) <= poolTol * a
                    p.price := math.max(p.price, ph)
                    p.cnt := p.cnt + 1
                    merged := true
            if not merged
                array.push(buyPools, Pool.new(price = ph, bar = bar_index - pivRight, cnt = 1))
                if array.size(buyPools) > poolMax
                    array.shift(buyPools)
        if not na(pl)
            lastSL := pl
            lastSLbar := bar_index - pivRight
            slBroken := false
            bool merged = false
            for p in sellPools
                if not merged and na(p.breachBar) and math.abs(p.price - pl) <= poolTol * a
                    p.price := math.min(p.price, pl)
                    p.cnt := p.cnt + 1
                    merged := true
            if not merged
                array.push(sellPools, Pool.new(price = pl, bar = bar_index - pivRight, cnt = 1))
                if array.size(sellPools) > poolMax
                    array.shift(sellPools)
 
    // ---- 6.3 new confirmed pivots -> candidate levels ----
    bool inRecent = bar_index >= last_bar_index - maxEvalBars
    if inRecent and not na(pl)
        Level nl = f_try_level(true, pl)
        if not na(nl)
            evNewSup := true
            msgNewSup := f_msg("NEW PROFILE-GUIDED SUPPORT", nl.price, nl.score, "pivot confirmed " + str.tostring(pivRight) + " bars after the swing low; " + (nl.guided ? "profile node " + f_px(nl.nodePrice) : "raw fallback"))
            if nl.score >= highScoreThr
                evHighScore := true
                msgHighScore := f_msg("HIGH-SCORE SUPPORT", nl.price, nl.score, "score at or above " + str.tostring(highScoreThr))
    if inRecent and not na(ph)
        Level nl = f_try_level(false, ph)
        if not na(nl)
            evNewRes := true
            msgNewRes := f_msg("NEW PROFILE-GUIDED RESISTANCE", nl.price, nl.score, "pivot confirmed " + str.tostring(pivRight) + " bars after the swing high; " + (nl.guided ? "profile node " + f_px(nl.nodePrice) : "raw fallback"))
            if nl.score >= highScoreThr
                evHighScore := true
                msgHighScore := f_msg("HIGH-SCORE RESISTANCE", nl.price, nl.score, "score at or above " + str.tostring(highScoreThr))
 
    // ---- 6.4 optional observation zones (disabled by default) ----
    if tpOn
        if planOn
            if (planSide == 1 and close < planInv) or (planSide == -1 and close > planInv) or bar_index - planBar > 80
                planOn := false
        float rngB = high - low
        for o in lvls
            if bar_index - o.lastPlan > tpCooldown and o.score >= tpMinScore
                if o.isSup
                    float lw = rngB > 0 ? (math.min(open, close) - low) / rngB : 0.0
                    bool touched = low <= o.price + tpTouch * a and close > o.price
                    bool conf = (close > open and lw >= 0.40) or (bar_index - lastBullSweep <= 3) or (bar_index - lastBullBreak <= 3)
                    if touched and conf
                        o.lastPlan := bar_index
                        planOn := true
                        planSide := 1
                        planBar := bar_index
                        planEntry := close
                        planInv := o.price - tpInv * a
                        planT1 := planEntry + tpRR1 * (planEntry - planInv)
                        planT2 := planEntry + tpRR2 * (planEntry - planInv)
                else
                    float uw = rngB > 0 ? (high - math.max(open, close)) / rngB : 0.0
                    bool touched = high >= o.price - tpTouch * a and close < o.price
                    bool conf = (close < open and uw >= 0.40) or (bar_index - lastBearSweep <= 3) or (bar_index - lastBearBreak <= 3)
                    if touched and conf
                        o.lastPlan := bar_index
                        planOn := true
                        planSide := -1
                        planBar := bar_index
                        planEntry := close
                        planInv := o.price + tpInv * a
                        planT1 := planEntry - tpRR1 * (planInv - planEntry)
                        planT2 := planEntry - tpRR2 * (planInv - planEntry)
 
// ====================================================================================================
// 7. ALERTS
// ====================================================================================================
if useDynAlerts
    if evNewSup
        alert(msgNewSup, alert.freq_once_per_bar_close)
    if evNewRes
        alert(msgNewRes, alert.freq_once_per_bar_close)
    if evSupBreak
        alert(msgSupBreak, alert.freq_once_per_bar_close)
    if evResBreak
        alert(msgResBreak, alert.freq_once_per_bar_close)
    if evBullSweep
        alert(msgBullSweep, alert.freq_once_per_bar_close)
    if evBearSweep
        alert(msgBearSweep, alert.freq_once_per_bar_close)
    if evBullBreak
        alert(msgBullBreak, alert.freq_once_per_bar_close)
    if evBearBreak
        alert(msgBearBreak, alert.freq_once_per_bar_close)
    if evHighScore
        alert(msgHighScore, alert.freq_once_per_bar_close)
 
alertcondition(evNewSup, "BSLP: New profile-guided support confirmed", "BSLP PRO: new profile-guided SUPPORT confirmed on {{ticker}} {{interval}} (close {{close}}). Open the level tooltip for score and evidence.")
alertcondition(evNewRes, "BSLP: New profile-guided resistance confirmed", "BSLP PRO: new profile-guided RESISTANCE confirmed on {{ticker}} {{interval}} (close {{close}}). Open the level tooltip for score and evidence.")
alertcondition(evSupBreak, "BSLP: Support break confirmed", "BSLP PRO: SUPPORT broken (confirmed close beyond level minus ATR buffer) on {{ticker}} {{interval}} (close {{close}}).")
alertcondition(evResBreak, "BSLP: Resistance break confirmed", "BSLP PRO: RESISTANCE broken (confirmed close beyond level plus ATR buffer) on {{ticker}} {{interval}} (close {{close}}).")
alertcondition(evBullSweep, "BSLP: Bullish liquidity sweep", "BSLP PRO: bullish liquidity sweep (sell-side pool swept, closing reclaim) on {{ticker}} {{interval}} (close {{close}}).")
alertcondition(evBearSweep, "BSLP: Bearish liquidity sweep", "BSLP PRO: bearish liquidity sweep (buy-side pool swept, closing reclaim) on {{ticker}} {{interval}} (close {{close}}).")
alertcondition(evBullBreak, "BSLP: Bullish market structure break", "BSLP PRO: bullish structure break (BOS or MSS) on {{ticker}} {{interval}} (close {{close}}).")
alertcondition(evBearBreak, "BSLP: Bearish market structure break", "BSLP PRO: bearish structure break (BOS or MSS) on {{ticker}} {{interval}} (close {{close}}).")
alertcondition(evHighScore, "BSLP: High-score level confirmed", "BSLP PRO: new HIGH-SCORE level confirmed on {{ticker}} {{interval}} (close {{close}}).")
 
// ====================================================================================================
// 8. DASHBOARD OBJECT
// ====================================================================================================
color dBg   = dashTheme == "Light" ? color.new(#F2F4F8, 6) : color.new(#10131A, 8)
color dTxt  = dashTheme == "Light" ? #1B2330 : #D5DAE3
color dDim  = dashTheme == "Light" ? #5C6675 : #8A93A3
color dBord = dashTheme == "Light" ? color.new(#9AA3B2, 40) : color.new(#3A4252, 40)
var table dash = dashOn ? table.new(f_pos(dashPos), 2, 14, bgcolor = dBg, border_width = 1, border_color = dBord, frame_width = 1, frame_color = dBord) : na
 
f_cell(int r, string a, string b, color bc) =>
    table.cell(dash, 0, r, a, text_color = dDim, bgcolor = dBg, text_halign = text.align_left, text_size = f_size(dashSize))
    table.cell(dash, 1, r, b, text_color = bc, bgcolor = dBg, text_halign = text.align_right, text_size = f_size(dashSize))
    true
 
// ====================================================================================================
// 9. RENDERING (rebuilt on the last bar only; objects are deleted before being recreated)
// ====================================================================================================
if barstate.islast
    f_clear()
    int xl = bar_index + profOffset
    int xr = xl + profWidth
    string lstl = f_lstyle(lineStyleIn)
 
    // ---- 9.1 rolling profile calculation ----
    int  nB = math.min(profLookback, bar_index + 1)
    [lo0, hi0] = f_range(nB)
    bool  profOk = false
    float rs0 = na
    float mx0 = na
    int   pocRow = -1
    float volQ = na
    if hi0 > lo0 and (showProfile or dashOn)
        rs0 := math.max((hi0 - lo0) / profRows, syminfo.mintick)
        array.fill(mTot, 0.0)
        array.fill(mBuy, 0.0)
        int vb = f_build(mTot, mBuy, nB, lo0, rs0, profRows)
        volQ := vb / float(nB)
        mx0 := array.max(mTot)
        if vb > 0 and mx0 > 0
            profOk := true
            pocRow := array.indexof(mTot, mx0)
 
    // ---- 9.2 which level owns which profile row (highest score wins, deterministic) ----
    int nL = array.size(lvls)
    array<string> extra = array.new<string>(nL, "")
    array<int> owner = array.new<int>(profRows, -1)
    if nL > 0 and profOk
        array<float> keys = array.new<float>()
        for q0 in lvls
            array.push(keys, q0.score - q0.pivBar * 1.0e-7)
        array<int> ord = array.sort_indices(keys, order.descending)
        for idx in ord
            Level L2 = array.get(lvls, idx)
            int rr = int(math.floor((L2.price - lo0) / rs0))
            if rr >= 0 and rr < profRows
                int ow = array.get(owner, rr)
                if ow == -1
                    array.set(owner, rr, idx)
                else
                    array.set(extra, ow, array.get(extra, ow) + "\nAlso in this profile row: " + (L2.isSup ? "support " : "resistance ") + f_px(L2.price) + " (score " + str.tostring(L2.score, "#") + ")")
 
    // ---- 9.3 profile boxes ----
    if showProfile and profOk
        float gap = rs0 * 0.07
        for r = 0 to profRows - 1
            float tv = array.get(mTot, r)
            if tv > 0
                int wB = math.max(1, int(math.round(tv / mx0 * profWidth)))
                float rb = lo0 + r * rs0
                if profView == "Total Volume"
                    f_box(xl, rb + rs0 - gap, xl + wB, rb + gap, color(na), color.new(totCol, profTransp), 1)
                else
                    float bsh = array.get(mBuy, r) / tv
                    int wBuy = int(math.round(wB * bsh))
                    f_box(xl, rb + rs0 - gap, xl + wBuy, rb + gap, color(na), color.new(buyCol, profTransp), 1)
                    f_box(xl + wBuy, rb + rs0 - gap, xl + wB, rb + gap, color(na), color.new(sellCol, profTransp), 1)
 
    // ---- 9.4 outlines of rows that contain active levels ----
    if showProfile and profOk and showRowOutline
        for r = 0 to profRows - 1
            int ow = array.get(owner, r)
            if ow != -1
                Level L3 = array.get(lvls, ow)
                float tv = array.get(mTot, r)
                int wO = math.max(3, int(math.round(tv / mx0 * profWidth)))
                f_box(xl, lo0 + (r + 1) * rs0, xl + wO, lo0 + r * rs0, L3.isSup ? supCol : resCol, color(na), 1)
 
    // ---- 9.5 POC ----
    float pocPrice = na
    if profOk
        pocPrice := lo0 + (pocRow + 0.5) * rs0
        if showPOC
            float rbP = lo0 + pocRow * rs0
            f_box(xl, rbP + rs0, xl + profWidth, rbP, pocCol, color(na), 2)
            f_line(math.max(0, bar_index - pocLineBars), pocPrice, xr, pocPrice, pocCol, line.style_solid, 1)
            f_lab(xr + 1, pocPrice, "POC " + f_px(pocPrice), label.style_label_left, color.new(#000000, 35), pocCol, size.tiny, "Rolling Point of Control: the row with the highest ESTIMATED total volume in the last " + str.tostring(nB) + " bars. It moves as the window rolls; accepted pivot levels do not move with it.")
 
    // ---- 9.6 high / low volume nodes ----
    if profOk and (showHVN or showLVN)
        int kk = math.max(2, int(profRows / 18))
        int rN = kk
        int hvnShown = 0
        while rN <= profRows - 1 - kk
            float v = array.get(mTot, rN)
            float maxL = 0.0
            float maxR = 0.0
            float minL = 1.0e18
            float minR = 1.0e18
            float maxL2 = 0.0
            float maxR2 = 0.0
            float minL2 = 1.0e18
            float minR2 = 1.0e18
            for d = 1 to 2 * kk
                int il = rN - d
                int ir = rN + d
                if il >= 0
                    float vl = array.get(mTot, il)
                    maxL2 := math.max(maxL2, vl)
                    minL2 := math.min(minL2, vl)
                    if d <= kk
                        maxL := math.max(maxL, vl)
                        minL := math.min(minL, vl)
                if ir < profRows
                    float vr = array.get(mTot, ir)
                    maxR2 := math.max(maxR2, vr)
                    minR2 := math.min(minR2, vr)
                    if d <= kk
                        maxR := math.max(maxR, vr)
                        minR := math.min(minR, vr)
            int nextR = rN + 1
            bool isPeak = v > maxL and v >= maxR and v / mx0 >= 0.45 and (v - math.min(minL2, minR2)) >= nodePromThr * mx0
            if showHVN and isPeak and rN != pocRow and hvnShown < 6
                int zLo = rN
                int zHi = rN
                while zLo > 0 and array.get(mTot, zLo - 1) >= 0.8 * v
                    zLo -= 1
                while zHi < profRows - 1 and array.get(mTot, zHi + 1) >= 0.8 * v
                    zHi += 1
                if pocRow < zLo or pocRow > zHi
                    f_box(xr + 2, lo0 + (zHi + 1) * rs0, xr + 4, lo0 + zLo * rs0, color(na), color.new(buyCol, 35), 1)
                    f_lab(xr + 5, lo0 + (rN + 0.5) * rs0, "HVN", label.style_label_left, color.new(#000000, 100), color.new(buyCol, 0), size.tiny, "High-volume node zone (estimated volume). A potential area of interest, not a guaranteed reaction.")
                    hvnShown += 1
                nextR := zHi + 1
            bool isValley = v > 0 and v < minL and v <= minR and v / mx0 <= 0.35 and (math.min(maxL2, maxR2) - v) >= nodePromThr * mx0 and volQ >= 0.8
            if showLVN and isValley
                f_line(xr + 2, lo0 + (rN + 0.5) * rs0, xr + 4, lo0 + (rN + 0.5) * rs0, color.new(rawCol, 20), line.style_dashed, 2)
                f_lab(xr + 5, lo0 + (rN + 0.5) * rs0, "LVN", label.style_label_left, color.new(#000000, 100), rawCol, size.tiny, "Low-volume node: a thin-volume valley between heavier areas (estimated volume).")
            rN := math.max(nextR, rN + 1)
 
    // ---- 9.6b fair value gaps and liquidity pools ----
    if smcOn and showFvg
        for g in fvgs
            f_box(g.bar, g.top, bar_index + 3, g.bot, color(na), color.new(g.bull ? supCol : resCol, 85), 1)
    if smcOn and showPools
        for p in buyPools
            f_line(p.bar, p.price, bar_index, p.price, color.new(resCol, 45), line.style_dotted, 1)
            f_lab(bar_index + 1, p.price, "BSL" + (p.cnt > 1 ? " x" + str.tostring(p.cnt) : ""), label.style_label_left, color.new(#000000, 100), color.new(resCol, 20), size.tiny, "Buy-side liquidity pool above swing high(s).")
        for p in sellPools
            f_line(p.bar, p.price, bar_index, p.price, color.new(supCol, 45), line.style_dotted, 1)
            f_lab(bar_index + 1, p.price, "SSL" + (p.cnt > 1 ? " x" + str.tostring(p.cnt) : ""), label.style_label_left, color.new(#000000, 100), color.new(supCol, 20), size.tiny, "Sell-side liquidity pool below swing low(s).")
 
    // ---- 9.7 SMC markers ----
    for m in marks
        if m.kind <= 2
            if showSweeps
                bool bullM = m.kind == 1
                f_lab(m.x, m.y, m.txt, bullM ? label.style_label_up : label.style_label_down, color.new(bullM ? supCol : resCol, 30), color.white, size.tiny, m.tip)
        else if showStruct
            bool bullS = m.kind == 3 or m.kind == 5
            color cs = bullS ? supCol : resCol
            f_line(m.x0, m.y, m.x, m.y, color.new(cs, 35), line.style_dashed, 1)
            f_lab(int(math.round((m.x0 + m.x) / 2.0)), m.y, m.txt, bullS ? label.style_label_down : label.style_label_up, color.new(#000000, 100), cs, size.tiny, m.tip)
 
    // ---- 9.8 invalidated level history ----
    if keepHist
        for hlv in hist
            color hc = hlv.isSup ? supCol : resCol
            f_line(hlv.pivBar, hlv.price, hlv.endBar, hlv.price, color.new(hc, 78), line.style_dotted, 1)
            f_lab(hlv.endBar, hlv.price, "x", label.style_label_center, color.new(#000000, 100), color.new(hc, 40), size.tiny, "Invalidated " + (hlv.isSup ? "support " : "resistance ") + f_px(hlv.price) + " (score was " + str.tostring(hlv.score, "#") + ")")
 
    // ---- 9.9 active levels ----
    if nL > 0
        array<float> prices = array.new<float>()
        for q1 in lvls
            array.push(prices, q1.price)
        array<int> byPrice = array.sort_indices(prices)
        float prevP = na
        int shiftN = 0
        float atrD = na(atrV) ? syminfo.mintick * 10 : atrV
        for k in byPrice
            Level L = array.get(lvls, k)
            if not na(prevP) and math.abs(L.price - prevP) < 0.30 * atrD
                shiftN := (shiftN + 1) % 3
            else
                shiftN := 0
            prevP := L.price
            color c = L.isSup ? supCol : resCol
            int trn = int(f_clamp(85.0 - L.score * 0.85, 8.0, 80.0))
            int lw = L.score >= 85 ? 4 : L.score >= 70 ? 3 : L.score >= 50 ? 2 : 1
            int xe = bar_index + dotOff + shiftN * 2
            string tipL = f_tip(L) + array.get(extra, k)
 
            if showLevels
                f_line(L.pivBar, L.price, xe, L.price, color.new(c, trn), lstl, lw)
            if showEdgeDots
                f_lab(xe, L.price, "", label.style_circle, c, c, f_size(dotSizeIn), tipL)
            if showEdgeScore
                f_lab(xl, L.price, str.tostring(L.score, "#"), label.style_label_right, color.new(#000000, 100), c, f_size(scoreSizeIn), tipL)
            if showMarkers
                if showRaw and math.abs(L.rawPrice - L.price) > syminfo.mintick * 0.5
                    f_lab(L.pivBar, L.rawPrice, "", label.style_circle, color.new(rawCol, 35), rawCol, size.tiny, "Raw pivot " + f_px(L.rawPrice) + " (reference point only)")
                if showGuide and math.abs(L.rawPrice - L.price) > syminfo.mintick * 0.5
                    f_line(L.pivBar, L.rawPrice, L.pivBar, L.price, color.new(rawCol, 25), line.style_dotted, 1)
                int rings = L.score >= 82 ? 4 : L.score >= 66 ? 3 : L.score >= 50 ? 2 : 1
                if rings >= 2
                    f_lab(L.pivBar, L.price, "", label.style_circle, color.new(c, 84), c, size.huge, tipL)
                f_lab(L.pivBar, L.price, "", label.style_circle, color.new(c, rings == 1 ? 66 : 72), c, size.large, tipL)
                if rings >= 3
                    f_lab(L.pivBar, L.price, "", label.style_circle, color.new(c, 56), c, size.normal, tipL)
                if rings >= 4
                    f_lab(L.pivBar, L.price, "", label.style_circle, color.new(c, 44), c, size.small, tipL)
                f_lab(L.pivBar, L.price, showMarkScore ? str.tostring(L.score, "#") : "", label.style_circle, L.guided ? goldCol : color.new(rawCol, 10), #000000, f_size(coreSizeIn), tipL)
 
    // ---- 9.10 optional observation zone ----
    if tpOn and planOn
        int xp = bar_index + 6
        string pc = planSide == 1 ? "Bullish" : "Bearish"
        f_line(planBar, planEntry, xp, planEntry, color.new(goldCol, 10), line.style_dashed, 1)
        f_line(planBar, planInv, xp, planInv, color.new(planSide == 1 ? resCol : supCol, 10), line.style_dashed, 1)
        f_line(planBar, planT1, xp, planT1, color.new(planSide == 1 ? supCol : resCol, 30), line.style_dotted, 1)
        f_line(planBar, planT2, xp, planT2, color.new(planSide == 1 ? supCol : resCol, 30), line.style_dotted, 1)
        f_lab(xp, planEntry, pc + " observation ref " + f_px(planEntry), label.style_label_left, color.new(#000000, 100), goldCol, size.tiny, "OBSERVATION reference only - not a trade recommendation.")
        f_lab(xp, planInv, "invalidation ref " + f_px(planInv), label.style_label_left, color.new(#000000, 100), rawCol, size.tiny, "ATR-based invalidation reference.")
        f_lab(xp, planT1, str.tostring(tpRR1, "0.0") + "R ref " + f_px(planT1), label.style_label_left, color.new(#000000, 100), rawCol, size.tiny, "Risk/reward reference, not a prediction.")
        f_lab(xp, planT2, str.tostring(tpRR2, "0.0") + "R ref " + f_px(planT2), label.style_label_left, color.new(#000000, 100), rawCol, size.tiny, "Risk/reward reference, not a prediction.")
 
    // ---- 9.11 dashboard ----
    if dashOn
        float nearSup = na
        float nearRes = na
        float strongS = -1.0
        float strongP = na
        bool  strongIsSup = true
        for o in lvls
            if o.isSup and o.price <= close and (na(nearSup) or o.price > nearSup)
                nearSup := o.price
            if not o.isSup and o.price >= close and (na(nearRes) or o.price < nearRes)
                nearRes := o.price
            if o.score > strongS
                strongS := o.score
                strongP := o.price
                strongIsSup := o.isSup
        bool atrOk = not na(atrV) and atrV > 0
        string supTxt = na(nearSup) ? "n/a" : f_px(nearSup) + (atrOk ? "  (" + str.tostring((close - nearSup) / atrV, "0.0") + " ATR)" : "")
        string resTxt = na(nearRes) ? "n/a" : f_px(nearRes) + (atrOk ? "  (" + str.tostring((nearRes - close) / atrV, "0.0") + " ATR)" : "")
        string strTxt = strongS < 0 ? "n/a" : (strongIsSup ? "S " : "R ") + f_px(strongP) + "  score " + str.tostring(strongS, "#")
        string biasTxt = not smcOn ? "SMC off" : trend == 1 ? "Bullish structure" : trend == -1 ? "Bearish structure" : "Undefined"
        string swpTxt = not sweepOn ? "off" : na(lastSweepBar) ? "None yet" : lastSweepTxt + "  (" + str.tostring(bar_index - lastSweepBar) + " bars ago)"
        string bsTxt = "n/a"
        if profOk
            float bPoc = array.get(mBuy, pocRow) / array.get(mTot, pocRow)
            bsTxt := str.tostring(bPoc * 100, "0") + "% buy / " + str.tostring((1.0 - bPoc) * 100, "0") + "% sell (est.)"
        string vqTxt = profOk ? "OK (" + str.tostring(volQ * 100, "0") + "% bars)" : "Unavailable"
        string mcTxt = "off"
        if volFilterOn
            if atrOk and not na(atrBase) and atrBase > 0
                float rat = atrV / atrBase
                mcTxt := rat < 0.75 ? "Compressed" : rat > 1.35 ? "Expanded" : "Normal"
            else
                mcTxt := "n/a"
        table.cell(dash, 0, 0, "BSLP PRO", text_color = dTxt, bgcolor = dBg, text_halign = text.align_left, text_size = f_size(dashSize), tooltip = SIGNATURE)
        table.cell(dash, 1, 0, "estimates only", text_color = dDim, bgcolor = dBg, text_halign = text.align_right, text_size = f_size(dashSize), tooltip = SIGNATURE)
        f_cell(1, "Symbol", syminfo.ticker, dTxt)
        f_cell(2, "Timeframe", timeframe.period, dTxt)
        f_cell(3, "Price", f_px(close), dTxt)
        f_cell(4, "Rolling POC", profOk ? f_px(pocPrice) : "n/a", pocCol)
        f_cell(5, "Nearest support", supTxt, supCol)
        f_cell(6, "Nearest resistance", resTxt, resCol)
        f_cell(7, "Strongest level", strTxt, strongIsSup ? supCol : resCol)
        f_cell(8, "Structure bias", biasTxt, dTxt)
        f_cell(9, "Last sweep", swpTxt, dTxt)
        f_cell(10, "Buy/sell @ POC", bsTxt, dTxt)
        f_cell(11, "Volume data", vqTxt, dTxt)
        f_cell(12, "Volatility", mcTxt, dTxt)
        table.cell(dash, 0, 13, "Context only - not a forecast", text_color = dDim, bgcolor = dBg, text_halign = text.align_left, text_size = f_size(dashSize))
        table.cell(dash, 1, 13, "", bgcolor = dBg)

← 返回列表