Support & Resistance Zones with Volume Profile and Anchor Levels

TonyANT · study · 1289 行 · 点赞 73 · TradingView 原页

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

Pine Script

// =============================================================================
// SUPPORT & RESISTANCE ZONES WITH VOLUME PROFILE AND ANCHOR LEVELS
// Detects support and resistance zones from pivots or a Donchian channel (auto-selected by ADX),
// tracks touches, sweeps, traded volume and breakouts per zone, and summarises POC / VAH / VAL
// and previous day / week / month highs and lows in a compact dashboard.
// =============================================================================
 
//@version=6
indicator(title            = "Support & Resistance Zones with Volume Profile and Anchor Levels",
          shorttitle       = "S&R Zones",
          overlay          = true,
          max_bars_back    = 5000,
          max_lines_count  = 500,
          max_boxes_count  = 500,
          max_labels_count = 500)
 
// =============================================================================
// CONSTANTS & TYPES
// Default colors, option strings and the zone record. Colors here are only
// defaults: every user-facing color is exposed through input.color below.
// =============================================================================
 
BULL_COLOR    = #089981
BEAR_COLOR    = #f23645
NONE_COLOR    = #00000000
 
// Info table structural defaults.
TXT_COLOR     = #e6e6e6
HDR_BG_COLOR  = #1e222d
BORDER_COLOR  = color.new(#000000, 70)
ROW_1_COLOR   = color.new(#262b36, 30)
ROW_2_COLOR   = color.new(#1a1d24, 30)
ACCENT_ORANGE = color.new(#ffa726, 0)
ACCENT_GREY   = color.new(#8a8f98, 0)
 
TOP_RIGHT     = 'Top Right'
BOTTOM_RIGHT  = 'Bottom Right'
BOTTOM_LEFT   = 'Bottom Left'
 
TINY          = 'Tiny'
SMALL         = 'Small'
NORMAL        = 'Normal'
LARGE         = 'Large'
HUGE          = 'Huge'
 
METHOD_PIVOTS   = 'Pivots'
METHOD_DONCHIAN = 'Donchian'
 
OVERLAP_NONE       = 'None'
OVERLAP_MERGE      = 'Merge Overlapping'
OVERLAP_HIDE_OLD   = 'Hide Overlapping (Oldest Precedence)'
OVERLAP_HIDE_YOUNG = 'Hide Overlapping (Youngest Precedence)'
 
// Bars by which active zones are extended to the right of the current bar.
EXT_BARS      = 25
 
// Calendar lengths used to choose the higher-timeframe access pattern.
DAY_SECS      = 86400
WEEK_SECS     = DAY_SECS * 7
MONTH_SECS    = DAY_SECS * 30
 
type level
    float top
    float btm
    float base_price
    int   start_bar
    int   start_time
    int   mitigation_bar
    int   mitigation_time
    bool  is_support
    bool  is_mitigated
    bool  is_user_hidden
    int   entries
    int   strength
    int   sweeps
    float traded_volume
    line  line_id
    box   box_id
    line  ext_line_id
    box   ext_box_id
    label stats_label
 
// =============================================================================
// GROUP 1 — DETECTION
// =============================================================================
 
G_DETECT = 'Detection'
 
auto_method    = input.bool(true, 'Auto-detect Method (ADX-based)', group = G_DETECT,
     tooltip = 'ON (default): switches between Pivots and Donchian according to trend strength.\n- ADX >= threshold: Donchian (trending market, channel breakouts).\n- ADX < threshold: Pivots (range-bound market, reversals).\nOFF: the method selected in Manual Method is always used.')
 
adx_len        = input.int(14, 'ADX Length (for Auto)', minval = 5, maxval = 50, group = G_DETECT,
     tooltip = 'Length of the DMI / ADX calculation used by the auto-detect switch. 14 is the standard setting. Shorter values react faster to regime changes but switch methods more often; longer values give a more stable regime reading.')
 
adx_threshold  = input.float(25.0, 'ADX Threshold (Donchian when >=)', minval = 10, maxval = 50, group = G_DETECT,
     tooltip = 'ADX level at which the auto-detect switch selects Donchian. 25 is the conventional boundary for a trending market. Lower values switch to Donchian more often; higher values require a stronger trend.')
 
manual_method  = input.string(METHOD_PIVOTS, 'Manual Method (when Auto is OFF)', options = [METHOD_PIVOTS, METHOD_DONCHIAN], group = G_DETECT,
     tooltip = 'Detection method used when Auto-detect is disabled. Pivots suit range-bound markets and mark swing reversals; Donchian suits trending markets and marks the extreme before each channel direction change.')
 
sensitivity    = input.float(10.0, 'Swing Sensitivity (lookback bars)', minval = 1, group = G_DETECT,
     tooltip = 'Lookback window for both Pivots and Donchian. Smaller values detect more, shorter-term swings; larger values keep only structural swings. Typical: 5-10 for intraday, 10-20 for swing charts.')
 
// =============================================================================
// GROUP 2 — ZONE SIZING
// =============================================================================
 
G_SIZE = 'Zone Sizing'
 
display_type   = input.string('Zones', 'Display Style', options = ['Levels', 'Zones'], group = G_SIZE,
     tooltip = 'Zones: support and resistance are drawn as price areas with an ATR-based depth, which reflects that a level is traded as a zone rather than a single price.\nLevels: plain horizontal lines at the pivot price.')
 
atr_period     = input.int(200, 'ATR Period', minval = 1, group = G_SIZE,
     tooltip = 'Length of the ATR used for zone depth and for the secondary-level match radius. 200 reflects average volatility over a wide window and keeps zone depth stable.')
 
atr_mult       = input.float(0.5, 'Zone Depth (ATR Mult)', minval = 0.0, group = G_SIZE,
     tooltip = 'Zone depth as a multiple of ATR, measured from the pivot price. Smaller values give narrow zones that are broken more easily; larger values give wide zones that capture more touches.')
 
// =============================================================================
// GROUP 3 — FILTERING & VISIBILITY
// =============================================================================
 
G_FILTER = 'Filtering & Visibility'
 
overlap_mode   = input.string(OVERLAP_HIDE_OLD, 'Overlap Handling', options = [OVERLAP_NONE, OVERLAP_MERGE, OVERLAP_HIDE_OLD, OVERLAP_HIDE_YOUNG], group = G_FILTER,
     tooltip = 'Treatment of overlapping zones of the same type:\n- None: all zones are shown, even when they overlap.\n- Merge: overlapping zones are combined into one wider zone.\n- Hide Oldest Precedence: the existing zone is kept and the new one is skipped (default).\n- Hide Youngest Precedence: the new zone is kept and the existing one is hidden.')
 
max_levels     = input.int(10, 'Max Active (Unmitigated)', minval = 1, maxval = 50, group = G_FILTER,
     tooltip = 'Maximum number of active (unbroken) zones displayed on the chart. The oldest zones beyond this limit are hidden. 10 balances coverage against chart clarity.')
 
show_broken    = input.bool(false, 'Show Broken S&R', group = G_FILTER,
     tooltip = 'Keep broken (mitigated) zones on the chart. OFF removes a zone as soon as it is broken for a cleaner chart; ON keeps it as a historical level, useful for polarity-flip analysis.')
 
pre_mit_lookback = input.int(5000, 'Pre-mitigation Lookback (bars)', minval = 0, maxval = 5000, group = G_FILTER,
     tooltip = 'When a zone is created with a start bar in the past (mainly with Donchian), the history since that bar is replayed and the zone is marked as broken immediately if a close has already crossed it. Prevents stale active zones. 0 disables the check.')
 
extend_active  = input.bool(true, 'Extend Active S&R', group = G_FILTER,
     tooltip = 'Extend active zones to the right of the current bar so their projection into the future is visible. The E / S / SW / V / D statistics label is placed at the end of this extension.')
 
label_spacing  = input.int(0, 'Label Spacing (bars)', minval = 0, maxval = 50, group = G_FILTER,
     tooltip = 'Horizontal offset, in bars, between the statistics labels of consecutive active zones, so labels of nearby zones do not overlap. 0 keeps every label at the end of the extension. Typical: 5-15 when several zones sit close to each other.')
 
// =============================================================================
// GROUP 4 — MINIMUM REQUIREMENTS
// =============================================================================
 
G_MIN = 'Minimum Requirements'
 
min_entries    = input.int(0, 'Min Price Entries', minval = 0, group = G_MIN,
     tooltip = 'Minimum number of touches required to display a zone. 0 shows all zones; higher values keep only tested zones.')
 
min_strength   = input.int(0, 'Min Overall Strength', minval = 0, group = G_MIN,
     tooltip = 'Minimum zone strength, where Strength = entries + sweeps x 2. A sweep carries more weight than a plain touch and is therefore doubled. 0 disables the filter; 3-5 removes weak zones.')
 
min_sweeps     = input.int(0, 'Min Sweeps', minval = 0, group = G_MIN,
     tooltip = 'Minimum number of sweeps (stop runs through the zone edge with a close back inside) required to display a zone. 1 or more keeps only zones where liquidity has already been taken.')
 
min_volume     = input.float(0, 'Min Traded Volume', minval = 0, group = G_MIN,
     tooltip = 'Minimum volume accumulated inside the zone. Removes zones that price has not revisited. On crypto, values of roughly 100K-1M are a practical starting point.')
 
min_duration   = input.int(0, 'Min Duration (Bars)', minval = 0, group = G_MIN,
     tooltip = 'Minimum zone age in bars. Newly created zones stay hidden until they reach this age. 0 shows zones immediately.')
 
// =============================================================================
// GROUP 5 — STYLE
// =============================================================================
 
G_STYLE = 'Style'
 
show_swing_marks = input.bool(false, 'Show Swing Markers', group = G_STYLE,
     tooltip = 'Triangles above swing highs and below swing lows that created a zone. Off by default for a cleaner chart.')
 
show_sweeps    = input.bool(false, 'Highlight Sweeps', group = G_STYLE,
     tooltip = 'Mark each sweep with a dot at the wick extreme (wick beyond the zone edge with a close back inside). Useful to verify the detection visually, at the cost of extra chart markers.')
 
show_breakouts = input.bool(false, 'Highlight Breakouts', group = G_STYLE,
     tooltip = 'Mark each breakout with a cross on the bar whose close moved beyond the zone boundary. Useful for visual verification.')
 
// =============================================================================
// GROUP 6 — VOLUME PROFILE
// =============================================================================
 
G_POC = 'Volume Profile'
 
poc_enable     = input.bool(true, 'Show POC in Dashboard', group = G_POC,
     tooltip = 'Point of Control: the price with the highest traded volume within the window. Usually the strongest single reference level. Shown in the dashboard together with VAH / VAL and the percentage distance from the current price.')
 
poc_length     = input.int(150, 'POC Lookback (bars)', minval = 20, group = G_POC,
     tooltip = 'Window for the volume profile calculation. 150 bars is a common profile window. A shorter window gives a POC that reflects recent activity; a longer window gives a more structural POC.')
 
poc_buckets    = input.int(24, 'POC Resolution (buckets)', minval = 10, maxval = 100, group = G_POC,
     tooltip = 'Number of price buckets in the volume histogram. 24 is a common resolution. More buckets give a more precise POC but more sensitivity to noise; fewer buckets give a coarser but more stable result.')
 
// =============================================================================
// GROUP 7 — PREVIOUS DAY / WEEK / MONTH
// =============================================================================
 
G_ANCH = 'Previous Day / Week / Month'
 
show_pd        = input.bool(true, 'Prev Day H/L in Dashboard', group = G_ANCH,
     tooltip = 'Previous day high and low. Key intraday reference levels, widely traded from the session open.')
 
show_pw        = input.bool(true, 'Prev Week H/L in Dashboard', group = G_ANCH,
     tooltip = 'Previous week high and low. Swing reference levels for medium-term trading.')
 
show_pm        = input.bool(false, 'Prev Month H/L in Dashboard', group = G_ANCH,
     tooltip = 'Previous month high and low. Long-term reference levels for swing and position trading.')
 
// =============================================================================
// GROUP 8 — SECONDARY LEVELS
// =============================================================================
 
G_SEC = 'Secondary Levels'
 
show_sec       = input.bool(true, 'Show Secondary Levels (dashed)', group = G_SEC,
     tooltip = 'Additional levels derived from pivot clustering within a price corridor. Drawn as dashed lines only when they do not coincide with an active zone (within Match Radius x ATR). Available on 1H and higher timeframes.')
 
sec_pivot_len  = input.int(10, 'Pivot Period', minval = 1, group = G_SEC,
     tooltip = 'Number of bars on each side required to confirm a pivot used for secondary levels. Smaller values include minor swings; larger values keep only major swings. Typical: 5-15.')
 
sec_lookback   = input.int(284, 'Lookback (bars)', minval = 50, maxval = 500, group = G_SEC,
     tooltip = 'Number of bars scanned for pivots. Also defines the high-low range from which the corridor width is derived. Larger values add older levels at the cost of more calculation per bar.')
 
sec_min_touches = input.int(2, 'Min Pivots per Level', minval = 1, group = G_SEC,
     tooltip = 'Minimum number of pivots that must fall inside the corridor around a pivot for it to qualify as a secondary level. Higher values keep only repeatedly tested prices.')
 
sec_channel_pct = input.int(10, 'Corridor Width %', minval = 1, maxval = 50, group = G_SEC,
     tooltip = 'Corridor half-width as a percentage of the lookback high-low range. Pivots within this distance of each other are counted as one level. Smaller values give more, tighter levels; larger values merge nearby pivots.')
 
sec_color      = input.color(color.new(color.gray, 30), 'Line Color', group = G_SEC,
     tooltip = 'Color of the dashed secondary level lines. A neutral tone keeps them visually subordinate to the main zones.')
 
sec_match_mult = input.float(0.5, 'Match Radius (ATR Mult)', minval = 0.1, step = 0.1, group = G_SEC,
     tooltip = 'A secondary level within Match Radius x ATR of an active zone is treated as a duplicate of that zone and is not drawn. Larger values suppress more secondary levels.')
 
// =============================================================================
// GROUP 9 — INFO TABLE
// =============================================================================
 
G_DASH = 'Info Table'
 
show_dash      = input.bool(true, 'Show Dashboard', group = G_DASH,
     tooltip = 'Show or hide the dashboard table in the chart corner.')
 
dash_loc       = input.string(TOP_RIGHT, 'Position', options = [TOP_RIGHT, BOTTOM_RIGHT, BOTTOM_LEFT], group = G_DASH,
     tooltip = 'Chart corner where the dashboard is anchored.')
 
dash_text_size = input.string(SMALL, 'Size', options = [TINY, SMALL, NORMAL, LARGE, HUGE], group = G_DASH,
     tooltip = 'Text size of the dashboard cells. Tiny maximises chart space; Large and Huge suit presentations and recordings.')
 
// =============================================================================
// GROUP 10 — COLORS
// =============================================================================
 
G_COL = 'Colors'
 
sup_color      = input.color(BULL_COLOR, 'Support Color', group = G_COL,
     tooltip = 'Color of support zones (formed at swing lows). Applied once the zone has accumulated traded volume (V > 0); untested zones are drawn in white.')
 
res_color      = input.color(BEAR_COLOR, 'Resistance Color', group = G_COL,
     tooltip = 'Color of resistance zones (formed at swing highs). Applied once the zone has accumulated traded volume (V > 0); untested zones are drawn in white.')
 
c_anchor_above = input.color(BULL_COLOR, 'Anchor: Price Above Level', group = G_COL,
     tooltip = 'Dashboard label color of a previous day / week / month level when the current close is above it (the level acts as support).')
 
c_anchor_below = input.color(BEAR_COLOR, 'Anchor: Price Below Level', group = G_COL,
     tooltip = 'Dashboard label color of a previous day / week / month level when the current close is below it (the level acts as resistance).')
 
c_poc          = input.color(ACCENT_ORANGE, 'POC Marker', group = G_COL,
     tooltip = 'Color of the POC label and the method status line in the dashboard.')
 
c_va           = input.color(ACCENT_GREY, 'Value Area / Section Marker', group = G_COL,
     tooltip = 'Color of the VAH / VAL labels and the Daily / Weekly / Monthly section captions in the dashboard.')
 
c_txt          = input.color(TXT_COLOR, 'Table Text', group = G_COL,
     tooltip = 'Primary text color of the dashboard.')
 
c_hdr          = input.color(HDR_BG_COLOR, 'Table Header Background', group = G_COL,
     tooltip = 'Background of the dashboard header rows and section captions.')
 
c_row1         = input.color(ROW_1_COLOR, 'Table Row Background (even)', group = G_COL,
     tooltip = 'Background of even dashboard rows (zebra striping).')
 
c_row2         = input.color(ROW_2_COLOR, 'Table Row Background (odd)', group = G_COL,
     tooltip = 'Background of odd dashboard rows (zebra striping).')
 
// =============================================================================
// GLOBAL SERIES CALCULATIONS
// All ta.* series functions are evaluated here on every bar. Calling them only
// when a method is active would leave gaps in their history and produce
// misplaced pivots after an Auto-mode switch.
// =============================================================================
 
int   sens_int      = math.max(1, int(sensitivity))
float global_atr    = ta.atr(atr_period)
float cum_range     = ta.cum(math.abs(high - low))
float donch_highest = ta.highest(high, sens_int)
float donch_lowest  = ta.lowest(low, sens_int)
int   bar_ms        = timeframe.in_seconds() * 1000
 
// ADX drives the auto-detect switch. ta.dmi returns [+DI, -DI, ADX].
[_, _, adx_value] = ta.dmi(adx_len, adx_len)
 
string effective_method = auto_method
     ? (adx_value >= adx_threshold ? METHOD_DONCHIAN : METHOD_PIVOTS)
     : manual_method
 
// Volume profile window bounds (kept global to avoid CW10003).
float poc_win_high = ta.highest(high, poc_length)
float poc_win_low  = ta.lowest(low,  poc_length)
 
float global_ph = ta.pivothigh(sens_int, sens_int)
float global_pl = ta.pivotlow(sens_int, sens_int)
 
// Secondary levels run only on 1H and higher: on lower timeframes the pivot
// clustering produces mostly local noise.
bool  sec_tf_ok   = timeframe.in_seconds() >= 3600
float sec_ph      = ta.pivothigh(sec_pivot_len, sec_pivot_len)
float sec_pl      = ta.pivotlow(sec_pivot_len, sec_pivot_len)
float sec_prd_hi  = ta.highest(sec_lookback)
float sec_prd_lo  = ta.lowest(sec_lookback)
float sec_cwidth  = (sec_prd_hi - sec_prd_lo) * sec_channel_pct / 100
 
// =============================================================================
// PREVIOUS DAY / WEEK / MONTH HIGHS AND LOWS
// When the chart timeframe is at or below the period, the standard
// lookahead_on + [1] pattern returns the last completed period. When the chart
// timeframe exceeds the period, that pattern snaps to the end of the higher
// bar, so the value is rebuilt from request.security_lower_tf arrays plus a
// carry of the last element from the previous chart bar.
// =============================================================================
 
[std_pdh, std_pdl] = request.security(syminfo.tickerid, 'D', [high[1], low[1]], lookahead = barmerge.lookahead_on)
[std_pwh, std_pwl] = request.security(syminfo.tickerid, 'W', [high[1], low[1]], lookahead = barmerge.lookahead_on)
[std_pmh, std_pml] = request.security(syminfo.tickerid, 'M', [high[1], low[1]], lookahead = barmerge.lookahead_on)
 
// ignore_invalid_timeframe prevents a runtime error when the chart timeframe is
// at or below the requested one; the arrays are then empty and unused.
d_hi_arr = request.security_lower_tf(syminfo.tickerid, 'D', high, ignore_invalid_timeframe = true)
d_lo_arr = request.security_lower_tf(syminfo.tickerid, 'D', low,  ignore_invalid_timeframe = true)
w_hi_arr = request.security_lower_tf(syminfo.tickerid, 'W', high, ignore_invalid_timeframe = true)
w_lo_arr = request.security_lower_tf(syminfo.tickerid, 'W', low,  ignore_invalid_timeframe = true)
m_hi_arr = request.security_lower_tf(syminfo.tickerid, 'M', high, ignore_invalid_timeframe = true)
m_lo_arr = request.security_lower_tf(syminfo.tickerid, 'M', low,  ignore_invalid_timeframe = true)
 
// Carry: last element of the previous chart bar's array. Needed when the
// current chart bar holds a single element, so the previous period lies in
// the previous chart bar.
var float d_carry_h = na
var float d_carry_l = na
var float w_carry_h = na
var float w_carry_l = na
var float m_carry_h = na
var float m_carry_l = na
 
f_prev_from_lower(array<float> arr, float carry) =>
    float result = carry
    if not na(arr)
        int sz = arr.size()
        if sz >= 2
            result := arr.get(sz - 2)
    result
 
f_last_from_lower(array<float> arr) =>
    float result = na
    if not na(arr)
        int sz = arr.size()
        if sz > 0
            result := arr.get(sz - 1)
    result
 
// Volume share of a candle segment [y21, y22] that falls into bucket [y11, y12].
// Volume is distributed in proportion to the overlap of the two ranges;
// height is the segment size (body, upper wick or lower wick) used for normalisation.
f_get_vol(float y11, float y12, float y21, float y22, float height, float vol) =>
    float a = math.max(math.min(y11, y12), math.min(y21, y22))
    float b = math.min(math.max(y11, y12), math.max(y21, y22))
    float overlap = math.max(b - a, 0)
    height > 0 ? nz(overlap * vol / height) : 0.0
 
prev_d_lo_h = f_prev_from_lower(d_hi_arr, d_carry_h)
prev_d_lo_l = f_prev_from_lower(d_lo_arr, d_carry_l)
prev_w_lo_h = f_prev_from_lower(w_hi_arr, w_carry_h)
prev_w_lo_l = f_prev_from_lower(w_lo_arr, w_carry_l)
prev_m_lo_h = f_prev_from_lower(m_hi_arr, m_carry_h)
prev_m_lo_l = f_prev_from_lower(m_lo_arr, m_carry_l)
 
float d_last_h = f_last_from_lower(d_hi_arr)
float d_last_l = f_last_from_lower(d_lo_arr)
float w_last_h = f_last_from_lower(w_hi_arr)
float w_last_l = f_last_from_lower(w_lo_arr)
float m_last_h = f_last_from_lower(m_hi_arr)
float m_last_l = f_last_from_lower(m_lo_arr)
if not na(d_last_h)
    d_carry_h := d_last_h
if not na(d_last_l)
    d_carry_l := d_last_l
if not na(w_last_h)
    w_carry_h := w_last_h
if not na(w_last_l)
    w_carry_l := w_last_l
if not na(m_last_h)
    m_carry_h := m_last_h
if not na(m_last_l)
    m_carry_l := m_last_l
 
int chart_tf_sec = timeframe.in_seconds()
 
float prev_d_high = chart_tf_sec <= DAY_SECS   ? std_pdh : prev_d_lo_h
float prev_d_low  = chart_tf_sec <= DAY_SECS   ? std_pdl : prev_d_lo_l
float prev_w_high = chart_tf_sec <= WEEK_SECS  ? std_pwh : prev_w_lo_h
float prev_w_low  = chart_tf_sec <= WEEK_SECS  ? std_pwl : prev_w_lo_l
float prev_m_high = chart_tf_sec <= MONTH_SECS ? std_pmh : prev_m_lo_h
float prev_m_low  = chart_tf_sec <= MONTH_SECS ? std_pml : prev_m_lo_l
 
// =============================================================================
// HELPER FUNCTIONS
// ATR with a cumulative-range fallback for the first bars, compact volume
// formatting, and dashboard cell / row helpers.
// =============================================================================
 
f_get_atr() =>
    float res = global_atr
    if na(res)
        res := cum_range / (bar_index + 1)
    res
 
f_format_val(float val) =>
    if val >= 1000000000
        str.format("{0,number,#.#}B", val / 1000000000)
    else if val >= 1000000
        str.format("{0,number,#.#}M", val / 1000000)
    else if val >= 1000
        str.format("{0,number,#.#}K", val / 1000)
    else
        str.tostring(val, "#.#")
 
var dash_position = switch dash_loc
    TOP_RIGHT    => position.top_right
    BOTTOM_RIGHT => position.bottom_right
    BOTTOM_LEFT  => position.bottom_left
 
var dash_size = switch dash_text_size
    TINY   => size.tiny
    SMALL  => size.small
    NORMAL => size.normal
    LARGE  => size.large
    HUGE   => size.huge
 
f_cell(table t_able, int column, int row, string data, color txt_color = #FFFFFF, align = text.align_right, color background = na, float height = 0, string tooltip = '') =>
    t_able.cell(column, row, data, text_color = txt_color, text_size = dash_size, text_halign = align, bgcolor = background, height = height, tooltip = tooltip)
 
// Zebra striping for the variable-length rows of the dashboard.
f_row_bg(int row) =>
    row % 2 == 0 ? c_row1 : c_row2
 
// =============================================================================
// ZONE DETECTION
// Produces at most one new support pivot (pl) and one new resistance pivot (ph)
// per bar from the active method, and keeps running statistics for the dashboard.
// =============================================================================
 
var level[] levels_array = array.new<level>()
float current_atr = f_get_atr()
 
float ph = na
float pl = na
int ph_bar = na
int pl_bar = na
 
var int   total_sup_count  = 0
var int   total_res_count  = 0
var int   sup_mitigated    = 0
var int   res_mitigated    = 0
var int   sup_duration     = 0
var int   res_duration     = 0
var int   sup_sweeps_count = 0
var int   res_sweeps_count = 0
var float sup_cum_volume   = 0.0
var float res_cum_volume   = 0.0
 
// Instruments without volume (some indices and FX feeds) report 0 or na, which
// makes the volume profile meaningless. Once any volume is seen the flag stays
// true; the dashboard uses it to blank POC / VAH / VAL otherwise.
var bool has_volume = false
if nz(volume) > 0
    has_volume := true
 
// Method 1: Pivots.
if effective_method == METHOD_PIVOTS
    ph := global_ph
    pl := global_pl
    if not na(ph)
        ph_bar := bar_index - sens_int
    if not na(pl)
        pl_bar := bar_index - sens_int
 
// Method 2: Donchian (alternating extremes).
// The channel state is updated on every bar regardless of the active method.
// If it were frozen while Pivots is active, returning to Donchian in Auto mode
// would emit pivots at stale prices. Pivots are emitted only while Donchian is active.
var int   donch_os      = 0
var float donch_val     = na
var int   donch_val_loc = na
 
donch_os := donch_highest > donch_highest[1] ? 1 : donch_lowest < donch_lowest[1] ? -1 : donch_os
 
// Snapshot before the update: the tracked extreme of the finished leg is the pivot price.
float donch_val_snap     = donch_val
int   donch_val_loc_snap = donch_val_loc
 
if donch_os != donch_os[1]
    // Direction changed: restart the tracked extreme on the current bar.
    if donch_os == 1
        donch_val := high
        donch_val_loc := bar_index
    else
        donch_val := low
        donch_val_loc := bar_index
else
    // Same direction: move the extreme if the current bar exceeds it.
    if donch_os == 1
        if high >= nz(donch_val, -1.0e10)
            donch_val := high
            donch_val_loc := bar_index
    else if donch_os == -1
        if low <= nz(donch_val, 1.0e10)
            donch_val := low
            donch_val_loc := bar_index
 
if effective_method == METHOD_DONCHIAN and donch_os != donch_os[1]
    if donch_os == 1
        pl := donch_val_snap
        pl_bar := donch_val_loc_snap
    else
        ph := donch_val_snap
        ph_bar := donch_val_loc_snap
 
if show_swing_marks
    if not na(ph)
        label.new(time[bar_index - ph_bar], ph, "▼", xloc = xloc.bar_time, color = NONE_COLOR, textcolor = res_color, style = label.style_label_center, size = size.small)
    if not na(pl)
        label.new(time[bar_index - pl_bar], pl, "▲", xloc = xloc.bar_time, color = NONE_COLOR, textcolor = sup_color, style = label.style_label_center, size = size.small)
 
// =============================================================================
// ZONE CREATION & OVERLAP HANDLING
// A new zone is checked against active zones of the same type and is skipped,
// merged, or hides the older zone according to Overlap Handling. Zones created
// with a start bar in the past are replayed against history so that zones
// already broken by a close are not shown as active.
// =============================================================================
 
f_handle_structure(float top, float btm, float base, int start, bool is_sup) =>
    bool should_add = true
    if levels_array.size() > 0
        for i = levels_array.size() - 1 to 0
            level l = levels_array.get(i)
            if not l.is_mitigated and not l.is_user_hidden and l.is_support == is_sup
                bool overlaps = math.max(btm, l.btm) < math.min(top, l.top)
                if overlaps
                    if overlap_mode == OVERLAP_HIDE_OLD
                        should_add := false
                        break
                    else if overlap_mode == OVERLAP_HIDE_YOUNG
                        l.is_user_hidden := true
                    else if overlap_mode == OVERLAP_MERGE
                        l.top := math.max(l.top, top)
                        l.btm := math.min(l.btm, btm)
                        should_add := false
                        break
    if should_add
        level new_l = level.new(top, btm, base, start, time[bar_index - start], 0, 0, is_sup, false, false, 0, 0, 0, 0.0, na, na, na, na, na)
        levels_array.unshift(new_l)
        true
    else
        false
 
// Returns bars-ago of the first close beyond the zone since its start bar,
// or na if the zone has not been broken.
f_check_pre_mit(level l, int start, bool is_sup) =>
    int pre_mit_bars_ago = na
    if pre_mit_lookback > 0
        int bars_back = bar_index - start
        int max_scan = math.min(bars_back, pre_mit_lookback)
        if max_scan > 1
            for k = max_scan to 1
                if is_sup
                    if close[k] < l.btm
                        pre_mit_bars_ago := k
                        break
                else
                    if close[k] > l.top
                        pre_mit_bars_ago := k
                        break
    if not na(pre_mit_bars_ago)
        l.is_mitigated := true
        l.mitigation_bar := bar_index - pre_mit_bars_ago
        l.mitigation_time := time[pre_mit_bars_ago]
    pre_mit_bars_ago
 
if not na(ph)
    if f_handle_structure(ph, ph - current_atr * atr_mult, ph, ph_bar, false)
        total_res_count += 1
        // unshift() placed the new zone at index 0.
        int pre_ago_r = f_check_pre_mit(levels_array.first(), ph_bar, false)
        if not na(pre_ago_r)
            res_mitigated += 1
            res_duration += (bar_index - pre_ago_r - ph_bar)
if not na(pl)
    if f_handle_structure(pl + current_atr * atr_mult, pl, pl, pl_bar, true)
        total_sup_count += 1
        int pre_ago_s = f_check_pre_mit(levels_array.first(), pl_bar, true)
        if not na(pre_ago_s)
            sup_mitigated += 1
            sup_duration += (bar_index - pre_ago_s - pl_bar)
 
// =============================================================================
// MITIGATION, STATISTICS & ZONE RENDERING
// For every stored zone: detect a close beyond the boundary, accumulate
// touches, sweeps and traded volume, apply the minimum-requirement filters,
// then create, update or delete its drawings. Zones without traded volume
// are drawn in white to mark them as untested.
// =============================================================================
 
if levels_array.size() > 100
    levels_array.pop()
 
int active_sup_count = 0
int active_res_count = 0
int active_total = 0
 
if levels_array.size() > 0
    for i = 0 to levels_array.size() - 1
        level l = levels_array.get(i)
        if not l.is_mitigated
            if l.is_support
                if close < l.btm
                    l.is_mitigated := true
                    l.mitigation_bar := bar_index
                    l.mitigation_time := time
                    sup_mitigated += 1
                    sup_duration += (l.mitigation_bar - l.start_bar)
                    sup_cum_volume += l.traded_volume
                    if show_breakouts
                        label.new(time, low, "×", xloc = xloc.bar_time, color = NONE_COLOR, textcolor = sup_color, style = label.style_label_center, size = size.tiny)
            else
                if close > l.top
                    l.is_mitigated := true
                    l.mitigation_bar := bar_index
                    l.mitigation_time := time
                    res_mitigated += 1
                    res_duration += (l.mitigation_bar - l.start_bar)
                    res_cum_volume += l.traded_volume
                    if show_breakouts
                        label.new(time, high, "×", xloc = xloc.bar_time, color = NONE_COLOR, textcolor = res_color, style = label.style_label_center, size = size.tiny)
 
            if not l.is_mitigated
                if high >= l.btm and low <= l.top
                    l.traded_volume += volume
                if l.is_support
                    if low <= l.top and close >= l.btm
                        l.entries += 1
                    // Support sweep: wick below the zone bottom, close back above it.
                    // Measured by close only, so fast V-shaped reversals are included.
                    if low < l.btm and close >= l.btm
                        l.sweeps += 1
                        sup_sweeps_count += 1
                        if show_sweeps
                            label.new(time, low, "●", xloc = xloc.bar_time, color = NONE_COLOR, textcolor = sup_color, style = label.style_label_center, size = size.small)
                else
                    if high >= l.btm and close <= l.top
                        l.entries += 1
                    // Resistance sweep: wick above the zone top, close back below it.
                    if high > l.top and close <= l.top
                        l.sweeps += 1
                        res_sweeps_count += 1
                        if show_sweeps
                            label.new(time, high, "●", xloc = xloc.bar_time, color = NONE_COLOR, textcolor = res_color, style = label.style_label_center, size = size.small)
 
                // A sweep outweighs a plain touch, hence the double weight.
                l.strength := l.entries + l.sweeps * 2
 
        int cur_d = l.is_mitigated ? l.mitigation_bar - l.start_bar : bar_index - l.start_bar
        bool meets = l.entries >= min_entries and l.strength >= min_strength and l.sweeps >= min_sweeps and l.traded_volume >= min_volume and cur_d >= min_duration and not l.is_user_hidden
        bool show = false
        if meets
            if not l.is_mitigated and active_total < max_levels
                show := true
                active_total += 1
                if l.is_support
                    active_sup_count += 1
                else
                    active_res_count += 1
            else if l.is_mitigated and show_broken
                show := true
 
        if show
            int end_t = l.is_mitigated ? l.mitigation_time : time
            // Guard against zero-width drawings when the zone ends on its start bar.
            if end_t <= l.start_time
                end_t := l.start_time + bar_ms
            color c = l.traded_volume == 0 ? color.white : (l.is_support ? sup_color : res_color)
            float avg_y = (l.top + l.btm) / 2
 
            if na(l.line_id)
                l.line_id := line.new(l.start_time, l.base_price, end_t, l.base_price, xloc = xloc.bar_time, color = c)
            else
                l.line_id.set_xy1(l.start_time, l.base_price)
                l.line_id.set_xy2(end_t, l.base_price)
                // Recolor on every bar: a zone created untested must switch from
                // white to its type color once volume accumulates.
                l.line_id.set_color(c)
 
            if display_type == 'Zones'
                if na(l.box_id)
                    l.box_id := box.new(l.start_time, l.top, end_t, l.btm, xloc = xloc.bar_time, border_color = NONE_COLOR, bgcolor = color.new(c, 85))
                else
                    l.box_id.set_left(l.start_time)
                    l.box_id.set_top(l.top)
                    l.box_id.set_right(end_t)
                    l.box_id.set_bottom(l.btm)
                    l.box_id.set_bgcolor(color.new(c, 85))
            else
                if not na(l.box_id)
                    l.box_id.delete()
                    l.box_id := na
 
            // Right-side extension is anchored by time so it reaches past the last bar.
            if not l.is_mitigated and extend_active
                int end_ext = time + EXT_BARS * bar_ms
                if na(l.ext_line_id)
                    l.ext_line_id := line.new(time, l.base_price, end_ext, l.base_price, xloc = xloc.bar_time, color = c)
                else
                    l.ext_line_id.set_xy1(time, l.base_price)
                    l.ext_line_id.set_xy2(end_ext, l.base_price)
                    l.ext_line_id.set_color(c)
 
                if display_type == 'Zones'
                    if na(l.ext_box_id)
                        l.ext_box_id := box.new(time, l.top, end_ext, l.btm, xloc = xloc.bar_time, border_color = NONE_COLOR, bgcolor = color.new(c, 85))
                    else
                        l.ext_box_id.set_left(time)
                        l.ext_box_id.set_top(l.top)
                        l.ext_box_id.set_right(end_ext)
                        l.ext_box_id.set_bottom(l.btm)
                        l.ext_box_id.set_bgcolor(color.new(c, 85))
                else
                    if not na(l.ext_box_id)
                        l.ext_box_id.delete()
                        l.ext_box_id := na
 
                // Each active zone gets its own horizontal slot to avoid label collisions.
                int slot = active_total - 1
                int label_x = end_ext + slot * label_spacing * bar_ms
                string price_range = str.format("[{0}-{1}]",
                     str.tostring(math.round_to_mintick(l.btm)),
                     str.tostring(math.round_to_mintick(l.top)))
                string txt = str.format("{0} | E:{1} | S:{2} | SW:{3} | V:{4} | D:{5}",
                     price_range, l.entries, l.strength, l.sweeps, f_format_val(l.traded_volume), cur_d)
                if na(l.stats_label)
                    l.stats_label := label.new(label_x, avg_y, txt, xloc = xloc.bar_time, color = NONE_COLOR, textcolor = c, style = label.style_label_left, size = size.tiny)
                else
                    l.stats_label.set_xy(label_x, avg_y)
                    l.stats_label.set_text(txt)
                    l.stats_label.set_textcolor(c)
            else
                if not na(l.ext_line_id)
                    l.ext_line_id.delete()
                    l.ext_line_id := na
                if not na(l.ext_box_id)
                    l.ext_box_id.delete()
                    l.ext_box_id := na
                if not na(l.stats_label)
                    l.stats_label.delete()
                    l.stats_label := na
        else
            if not na(l.line_id)
                l.line_id.delete()
                l.line_id := na
            if not na(l.box_id)
                l.box_id.delete()
                l.box_id := na
            if not na(l.ext_line_id)
                l.ext_line_id.delete()
                l.ext_line_id := na
            if not na(l.ext_box_id)
                l.ext_box_id.delete()
                l.ext_box_id := na
            if not na(l.stats_label)
                l.stats_label.delete()
                l.stats_label := na
 
// =============================================================================
// SECONDARY LEVELS
// Pivot prices that gather at least Min Pivots per Level pivots inside a
// corridor of Corridor Width % of the lookback range. They are context only:
// no mitigation, touches, sweeps or volume are tracked, and they are never
// stored in levels_array. A level within Match Radius x ATR of an active zone
// is treated as a duplicate and is not drawn.
// =============================================================================
 
var sec_levels    = array.new<float>(21, na)
var ln_sec        = array.new<line>(21, na)
sec_available     = array.new<bool>(41, true)
 
if show_sec and sec_tf_ok and (not na(sec_ph) or not na(sec_pl)) and sec_cwidth > 0
    for i = 0 to 20
        array.set(sec_levels, i, na)
    for i = 0 to 40
        array.set(sec_available, i, true)
 
    int sec_pivot_count = 0
    for x = 0 to sec_lookback
        if na(close[x])
            break
        float ph_x = sec_ph[x]
        float pl_x = sec_pl[x]
        if not na(ph_x) or not na(pl_x)
            sec_pivot_count += 1
            if sec_pivot_count > 40
                break
            if array.get(sec_available, sec_pivot_count)
                float pivot_price = not na(ph_x) ? high[x + sec_pivot_len] : low[x + sec_pivot_len]
                float upper_bound = pivot_price + sec_cwidth
                float lower_bound = pivot_price - sec_cwidth
                sec_tmp = array.new<bool>(41, true)
                int cnt = 0
                int touch_count = 0
                for xx = 0 to sec_lookback
                    if na(close[xx])
                        break
                    float ph_xx = sec_ph[xx]
                    float pl_xx = sec_pl[xx]
                    if not na(ph_xx) or not na(pl_xx)
                        bool changed = false
                        cnt += 1
                        if cnt > 40
                            break
                        if array.get(sec_available, cnt)
                            if not na(ph_xx)
                                float h_piv = high[xx + sec_pivot_len]
                                if h_piv <= upper_bound and h_piv >= lower_bound
                                    touch_count += 1
                                    changed := true
                            if not na(pl_xx)
                                float l_piv = low[xx + sec_pivot_len]
                                if l_piv <= upper_bound and l_piv >= lower_bound
                                    touch_count += 1
                                    changed := true
                        if changed and cnt < 41
                            array.set(sec_tmp, cnt, false)
 
                if touch_count >= sec_min_touches
                    for g = 0 to 40
                        if not array.get(sec_tmp, g)
                            array.set(sec_available, g, false)
                    if sec_pivot_count < 21
                        array.set(sec_levels, sec_pivot_count, pivot_price)
 
// Redraw on every bar: delete previous lines, draw only non-duplicate levels.
float sec_match_tol = current_atr * sec_match_mult
for i = 0 to 20
    line old_line = array.get(ln_sec, i)
    if not na(old_line)
        line.delete(old_line)
        array.set(ln_sec, i, na)
 
    if not (show_sec and sec_tf_ok)
        continue
    float lvl = array.get(sec_levels, i)
    if na(lvl)
        continue
 
    bool overlaps_active = false
    if levels_array.size() > 0
        for k = 0 to levels_array.size() - 1
            level zone = levels_array.get(k)
            if not zone.is_mitigated and not zone.is_user_hidden
                if lvl >= zone.btm - sec_match_tol and lvl <= zone.top + sec_match_tol
                    overlaps_active := true
                    break
 
    if not overlaps_active
        array.set(ln_sec, i, line.new(time - bar_ms, lvl, time, lvl, xloc = xloc.bar_time, color = sec_color, width = 1, style = line.style_dashed, extend = extend.both))
 
// =============================================================================
// VOLUME PROFILE (POC / VAH / VAL)
// Classic volume profile over the last POC Lookback bars. Each candle's volume
// is spread across buckets in proportion to the overlap of its body, upper
// wick and lower wick with each bucket; wicks are weighted x2 relative to the
// body and the parts sum to the full candle volume. Calculation only: the
// values are shown in the dashboard, nothing is drawn on the chart.
// =============================================================================
 
var float poc_price = na
var float vah_price = na
var float val_price = na
 
if poc_enable and barstate.islast
    float win_high = poc_win_high
    float win_low  = poc_win_low
    float b_size   = (win_high - win_low) / poc_buckets
    // Without volume the profile is meaningless (max volume 0 pins POC to the
    // first bucket), so values stay na and the dashboard shows a dash.
    if b_size > 0 and has_volume
        // Bucket boundaries: win_low, win_low + b_size, ..., win_high (poc_buckets + 1 points).
        var float[] vp_levels  = array.new<float>(poc_buckets + 1, 0.0)
        var float[] vp_buckets = array.new<float>(poc_buckets, 0.0)
        for x = 0 to poc_buckets
            array.set(vp_levels, x, win_low + b_size * x)
        for x = 0 to poc_buckets - 1
            array.set(vp_buckets, x, 0.0)
 
        for i = 0 to poc_length - 1
            float c = close[i]
            float o = open[i]
            float h = high[i]
            float l = low[i]
            float v = nz(volume[i], 0.0)
            float body_top    = math.max(c, o)
            float body_bot    = math.min(c, o)
            float top_wick    = h - body_top
            float bottom_wick = body_bot - l
            float body        = body_top - body_bot
            // Weights: body x1, upper wick x2, lower wick x2.
            float denom       = 2 * top_wick + 2 * bottom_wick + body
            if denom > 0 and v > 0
                float body_vol        = body * v / denom
                float top_wick_vol    = 2 * top_wick * v / denom
                float bottom_wick_vol = 2 * bottom_wick * v / denom
                for x = 0 to poc_buckets - 1
                    float lo = array.get(vp_levels, x)
                    float hi = array.get(vp_levels, x + 1)
                    float add = 0.0
                    if body > 0
                        add := add + f_get_vol(lo, hi, body_bot, body_top, body, body_vol)
                    if top_wick > 0
                        add := add + f_get_vol(lo, hi, body_top, h, top_wick, top_wick_vol)
                    if bottom_wick > 0
                        add := add + f_get_vol(lo, hi, body_bot, l, bottom_wick, bottom_wick_vol)
                    if add > 0
                        array.set(vp_buckets, x, array.get(vp_buckets, x) + add)
 
        int max_idx = 0
        float max_vol = array.get(vp_buckets, 0)
        for i = 1 to poc_buckets - 1
            float v = array.get(vp_buckets, i)
            if v > max_vol
                max_vol := v
                max_idx := i
        // POC is the midpoint of the highest-volume bucket.
        poc_price := win_low + (max_idx + 0.5) * b_size
 
        // Value Area: expand from the POC, each step adding the larger of the
        // two neighbouring buckets, until at least 70% of total volume is covered.
        float total_vol = 0.0
        for i = 0 to poc_buckets - 1
            total_vol := total_vol + array.get(vp_buckets, i)
        if total_vol > 0
            float target_vol = total_vol * 0.70
            float va_vol     = array.get(vp_buckets, max_idx)
            int   up_idx     = max_idx
            int   down_idx   = max_idx
            while va_vol < target_vol and (up_idx < poc_buckets - 1 or down_idx > 0)
                float up_cand   = up_idx   < poc_buckets - 1 ? array.get(vp_buckets, up_idx + 1)   : -1.0
                float down_cand = down_idx > 0               ? array.get(vp_buckets, down_idx - 1) : -1.0
                if up_cand >= down_cand and up_idx < poc_buckets - 1
                    up_idx := up_idx + 1
                    va_vol := va_vol + up_cand
                else if down_idx > 0
                    down_idx := down_idx - 1
                    va_vol := va_vol + down_cand
                else
                    break
            vah_price := win_low + (up_idx + 1) * b_size
            val_price := win_low + down_idx * b_size
        else
            vah_price := na
            val_price := na
 
// =============================================================================
// DASHBOARD TOOLTIPS
// Explanatory texts shown when hovering the (i) markers in the dashboard.
// =============================================================================
 
f_pct(float lvl_price) =>
    pct = (lvl_price - close) / close * 100
    sign = pct >= 0 ? "+" : ""
    sign + str.tostring(pct, "#.##") + "%"
 
// Above the level: the level acts as support. Below: resistance or broken support.
f_anchor_col(float lvl_price) =>
    close > lvl_price ? c_anchor_above : c_anchor_below
 
tt_dash = "S&R Zones - three level types:\n" +
   "1) Active support / resistance zones (green / red / white on the chart) from Pivots or Donchian, depth = N x ATR.\n" +
   "   Auto method: ADX >= threshold selects Donchian, ADX < threshold selects Pivots.\n" +
   "2) Volume profile (POC, VAH, VAL): where volume traded within the window.\n" +
   "3) Anchor levels (PDH/PDL, PWH/PWL, PMH/PML): extremes of previous periods.\n" +
   "\n" +
   "Secondary levels are drawn on the chart as dashed grey lines. They do not duplicate active zones (Match Radius x ATR filter) and are not listed in the dashboard.\n" +
   "\n" +
   "ACTIVE ZONE COLORS:\n" +
   "Green - Support: zone below price that has absorbed selling. Volume accumulated, confirmed support.\n" +
   "Red - Resistance: zone above price that has absorbed buying. Confirmed resistance.\n" +
   "White - untested (V = 0): price has not returned to the zone yet. A weaker candidate until volume accumulates.\n" +
   "White switches to green / red automatically as traded volume accumulates.\n" +
   "\n" +
   "Breakout: a close beyond the zone boundary marks the zone as mitigated (hidden, or kept if Show Broken S&R is on)."
 
tt_active = "ACTIVE / TOTAL zones detected over the loaded history.\n" +
   "Active = not broken (no close beyond the boundary yet). Shown as zones on the chart.\n" +
   "Total = cumulative count of all zones detected.\n" +
   "Use it to check whether active zones currently exist near price."
 
tt_mitig = "Share of all detected zones that have been BROKEN.\n" +
   "High (>80%): zones on this instrument are weak and break often.\n" +
   "Low (<50%): zones are robust and price respects them.\n" +
   "Over a long history values near 90% are normal. Most useful for comparing instruments."
 
tt_sweeps = "Total Sweeps - number of wick sweeps (stop runs).\n" +
   "Support: low traded BELOW the zone bottom, close returned above it.\n" +
   "Resistance: high traded ABOVE the zone top, close returned below it.\n" +
   "Both slow sweeps (close inside the zone) and fast sweeps (close far on the other side of the wick) are counted.\n" +
   "A higher count indicates more active liquidity collection around the zones."
 
tt_method = "Current zone detection method and ADX (trend strength).\n" +
   "Auto mode: the method is selected by ADX.\n" +
   "- ADX >= threshold (default 25): Donchian (trending market).\n" +
   "- ADX < threshold: Pivots (range-bound market).\n" +
   "Manual mode (Auto OFF in settings): the method is fixed and ADX is informational only.\n" +
   "Higher ADX means a stronger trend. ADX < 20: weak or no trend. ADX 25-40: normal trend. ADX > 50: extreme."
 
tt_zone_legend = "ZONE STATISTICS LEGEND (shown to the right of each active zone on the chart):\n" +
   "[price-price] = zone range (lower and upper boundary).\n" +
   "E (Entries) - number of touches: price reached the zone and the close stayed inside or on the correct side. Higher E means a more tested zone.\n" +
   "S (Strength) - E + SW x 2. A sweep outweighs a plain touch and is therefore doubled. Used by the Min Strength filter.\n" +
   "SW (Sweeps) - number of sweeps: the wick moved beyond the level and the close returned.\n" +
   "V (Volume) - total volume traded INSIDE the zone over its lifetime.\n" +
   "D (Duration) - zone age in bars (or its lifetime until it was broken)."
 
tt_vol_profile = "VOLUME PROFILE - where the MOST VOLUME traded over the last " + str.tostring(poc_length) + " bars of the CURRENT timeframe.\n" +
   "The window high-low range is split into " + str.tostring(poc_buckets) + " buckets. Each candle's volume is distributed across buckets proportionally (classic volume profile).\n" +
   "\n" +
   "COMPONENTS:\n" +
   "POC (Point of Control) - bucket with the highest volume. The main price magnet that price revisits most often.\n" +
   "VAH (Value Area High) - upper boundary of the area containing 70% of volume. Price above VAH = overvalued.\n" +
   "VAL (Value Area Low) - lower boundary of the 70% area. Price below VAL = undervalued.\n" +
   "\n" +
   "TRADING CONTEXT:\n" +
   "Between VAL and VAH the market is in balance, suited to mean-reversion strategies.\n" +
   "A breakout of VAH / VAL on volume signals the start of a new trend (the new valuation is accepted).\n" +
   "\n" +
   "Distance (+/-): the level is above / below the current price."
 
tt_anchor = "ANCHOR LEVELS - highs and lows of previous periods.\n" +
   "These are actual high / low prices (not volume-based) that large participants reference at the start of a new session.\n" +
   "\n" +
   "COMPONENTS:\n" +
   "PDH/PDL = Previous Day High/Low - extremes of the previous day. Key intraday references.\n" +
   "PWH/PWL = Previous Week High/Low - extremes of the previous week. Swing horizon.\n" +
   "PMH/PML = Previous Month High/Low - extremes of the previous month. Long-term horizon.\n" +
   "\n" +
   "COLOR CODING:\n" +
   "Green - price is ABOVE the level (support below holds).\n" +
   "Red - price is BELOW the level (broken support or resistance above).\n" +
   "\n" +
   "Distance (+/-): the level is above / below the current price."
 
tt_poc = "POC (Point of Control) - the price level with the HIGHEST VOLUME.\n" +
   "\n" +
   "WINDOW:\n" +
   "The last " + str.tostring(poc_length) + " bars of the CURRENT timeframe, which covers a different time span on each timeframe:\n" +
   "- 1H: about 8 days, 4H: about 33 days, 1D: about 10 months, 1W: about 4 years.\n" +
   "The window high-low range is split into " + str.tostring(poc_buckets) + " buckets. POC = center of the bucket with the highest accumulated volume.\n" +
   "\n" +
   "SIGNIFICANCE:\n" +
   "The most heavily traded level: most transactions passed through it. It acts as a strong price magnet that price frequently revisits.\n" +
   "\n" +
   "COLOR: always orange - the main volume reference, regardless of price position."
 
tt_vah = "VAH (Value Area High) - UPPER BOUNDARY OF THE FAIR VALUE AREA.\n" +
   "\n" +
   "DEFINITION:\n" +
   "Value Area = range around the POC containing 70% of total volume over the " + str.tostring(poc_length) + "-bar window.\n" +
   "Algorithm: start at the POC and expand in both directions, each step adding the higher-volume bucket, until 70% is reached.\n" +
   "\n" +
   "SIGNIFICANCE:\n" +
   "Price above VAH = overvalued relative to the fair value area. Candidate for mean reversion back to the POC.\n" +
   "A breakout above VAH on high volume with acceptance = start of a new uptrend (the higher valuation becomes the norm).\n" +
   "\n" +
   "COLOR: grey - a boundary of the accepted value area, not a directional signal."
 
tt_val = "VAL (Value Area Low) - LOWER BOUNDARY OF THE FAIR VALUE AREA.\n" +
   "\n" +
   "DEFINITION:\n" +
   "Symmetric to VAH. 70% of volume over the " + str.tostring(poc_length) + "-bar window traded between VAL and VAH.\n" +
   "\n" +
   "SIGNIFICANCE:\n" +
   "Price below VAL = undervalued. Candidate for mean reversion up to the POC.\n" +
   "A breakdown below VAL on volume with acceptance = start of a downtrend (a new lower valuation).\n" +
   "\n" +
   "COLOR: grey - a boundary of the accepted value area, not a directional signal."
 
tt_pdh = "Previous Day High - HIGH OF THE PREVIOUS DAY.\n" +
   "A common reference for trading at the start of a new session.\n" +
   "A breakout above PDH is a bullish signal. A rejection from PDH means resistance held.\n" +
   "\n" +
   "COLOR:\n" +
   "Green - price is ABOVE the level (PDH acts as support below).\n" +
   "Red - price is BELOW the level (PDH acts as resistance above)."
 
tt_pdl = "Previous Day Low - LOW OF THE PREVIOUS DAY.\n" +
   "Often acts as strong support during the current session.\n" +
   "A break below PDL is a bearish signal. A bounce from PDL means support held.\n" +
   "\n" +
   "COLOR:\n" +
   "Green - price is ABOVE the level (PDL holds as support).\n" +
   "Red - price is BELOW the level (PDL broken, weakness)."
 
tt_pwh = "Previous Week High - HIGH OF THE PREVIOUS WEEK.\n" +
   "A higher-order reference than PDH, relevant on the swing horizon.\n" +
   "A breakout above PWH often starts a larger upward move.\n" +
   "\n" +
   "COLOR:\n" +
   "Green - price is ABOVE (PWH acts as swing support).\n" +
   "Red - price is BELOW (PWH acts as swing resistance)."
 
tt_pwl = "Previous Week Low - LOW OF THE PREVIOUS WEEK.\n" +
   "Swing support. A break below it is a significant bearish signal.\n" +
   "\n" +
   "COLOR:\n" +
   "Green - price is ABOVE the level (swing support holds).\n" +
   "Red - price is BELOW (broken, bearish signal)."
 
tt_pmh = "Previous Month High - HIGH OF THE PREVIOUS MONTH.\n" +
   "A long-term reference for swing and position trading.\n" +
   "\n" +
   "COLOR:\n" +
   "Green - price is ABOVE (macro support).\n" +
   "Red - price is BELOW (macro resistance)."
 
tt_pml = "Previous Month Low - LOW OF THE PREVIOUS MONTH.\n" +
   "Long-term support. A break below it indicates a significant trend change.\n" +
   "\n" +
   "COLOR:\n" +
   "Green - price is ABOVE the level (macro support holds).\n" +
   "Red - price is BELOW (broken, significant trend change)."
 
// =============================================================================
// DASHBOARD
// Rendered on the last bar only. Cells are wiped before every refill so rows
// that are toggled off do not leave stale content. POC / VAH / VAL rows stay
// in place on instruments without volume and show a dash, so the table layout
// does not shift.
// =============================================================================
 
if show_dash and barstate.islast
    var table t = table.new(dash_position, 4, 22, c_hdr, BORDER_COLOR, 1, BORDER_COLOR, 1)
    table.clear(t, 0, 0, 3, 21)
 
    t.merge_cells(0, 0, 3, 0)
    f_cell(t, 0, 0, 'S&R Zones · Dashboard ⓘ', c_txt, text.align_center, background = c_hdr, tooltip = tt_dash)
 
    string method_txt = 'Method: ' + effective_method + (auto_method ? ' (Auto, ADX=' + str.tostring(adx_value, '#.#') + ')' : ' (Manual)')
    t.merge_cells(0, 1, 3, 1)
    f_cell(t, 0, 1, method_txt + ' ⓘ', c_poc, text.align_center, background = c_row2, tooltip = tt_method)
 
    f_cell(t, 0, 2, '',           c_txt, text.align_left,   background = c_hdr)
    f_cell(t, 1, 2, 'Support',    c_txt, text.align_center, background = c_hdr)
    f_cell(t, 2, 2, 'Resistance', c_txt, text.align_center, background = c_hdr)
    f_cell(t, 3, 2, 'Total',      c_txt, text.align_center, background = c_hdr)
 
    f_cell(t, 0, 3, 'Active / Total ⓘ', c_txt, text.align_left, background = c_row1, tooltip = tt_active)
    f_cell(t, 1, 3, str.format("{0} / {1}", active_sup_count, total_sup_count), c_txt, background = c_row1)
    f_cell(t, 2, 3, str.format("{0} / {1}", active_res_count, total_res_count), c_txt, background = c_row1)
    f_cell(t, 3, 3, str.format("{0} / {1}", active_total, total_sup_count + total_res_count), c_txt, background = c_row1)
 
    f_cell(t, 0, 4, 'Mitigated % ⓘ', c_txt, text.align_left, background = c_row2, tooltip = tt_mitig)
    f_cell(t, 1, 4, str.format("{0,number,#.#}%", sup_mitigated * 100 / math.max(1, total_sup_count)), c_txt, background = c_row2)
    f_cell(t, 2, 4, str.format("{0,number,#.#}%", res_mitigated * 100 / math.max(1, total_res_count)), c_txt, background = c_row2)
    f_cell(t, 3, 4, str.format("{0,number,#.#}%", (sup_mitigated + res_mitigated) * 100 / math.max(1, total_sup_count + total_res_count)), c_txt, background = c_row2)
 
    f_cell(t, 0, 5, 'Total Sweeps ⓘ', c_txt, text.align_left, background = c_row1, tooltip = tt_sweeps)
    f_cell(t, 1, 5, str.tostring(sup_sweeps_count), c_txt, background = c_row1)
    f_cell(t, 2, 5, str.tostring(res_sweeps_count), c_txt, background = c_row1)
    f_cell(t, 3, 5, str.tostring(sup_sweeps_count + res_sweeps_count), c_txt, background = c_row1)
 
    int r = 6
    t.merge_cells(0, r, 3, r)
    f_cell(t, 0, r, 'Volume Profile  ·  Price  ·  Distance ⓘ', c_txt, text.align_center, background = c_hdr, tooltip = tt_vol_profile)
    r += 1
    if poc_enable
        color bg = f_row_bg(r)
        string poc_price_txt = has_volume and not na(poc_price) ? str.tostring(math.round_to_mintick(poc_price)) : '—'
        string poc_dist_txt  = has_volume and not na(poc_price) ? f_pct(poc_price) : '—'
        f_cell(t, 0, r, '● POC', c_poc, text.align_left, background = bg, tooltip = tt_poc)
        f_cell(t, 1, r, poc_price_txt, c_txt, text.align_center, background = bg)
        t.merge_cells(1, r, 2, r)
        f_cell(t, 3, r, poc_dist_txt, c_txt, text.align_right, background = bg)
        r += 1
    if poc_enable
        color bg = f_row_bg(r)
        string vah_price_txt = has_volume and not na(vah_price) ? str.tostring(math.round_to_mintick(vah_price)) : '—'
        string vah_dist_txt  = has_volume and not na(vah_price) ? f_pct(vah_price) : '—'
        f_cell(t, 0, r, '● VAH', c_va, text.align_left, background = bg, tooltip = tt_vah)
        f_cell(t, 1, r, vah_price_txt, c_txt, text.align_center, background = bg)
        t.merge_cells(1, r, 2, r)
        f_cell(t, 3, r, vah_dist_txt, c_txt, text.align_right, background = bg)
        r += 1
    if poc_enable
        color bg = f_row_bg(r)
        string val_price_txt = has_volume and not na(val_price) ? str.tostring(math.round_to_mintick(val_price)) : '—'
        string val_dist_txt  = has_volume and not na(val_price) ? f_pct(val_price) : '—'
        f_cell(t, 0, r, '● VAL', c_va, text.align_left, background = bg, tooltip = tt_val)
        f_cell(t, 1, r, val_price_txt, c_txt, text.align_center, background = bg)
        t.merge_cells(1, r, 2, r)
        f_cell(t, 3, r, val_dist_txt, c_txt, text.align_right, background = bg)
        r += 1
 
    t.merge_cells(0, r, 3, r)
    f_cell(t, 0, r, 'Anchor Levels  ·  Price  ·  Distance ⓘ', c_txt, text.align_center, background = c_hdr, tooltip = tt_anchor)
    r += 1
 
    if show_pd and (not na(prev_d_high) or not na(prev_d_low))
        t.merge_cells(0, r, 3, r)
        f_cell(t, 0, r, '— Daily —', c_va, text.align_center, background = c_hdr)
        r += 1
    if show_pd and not na(prev_d_high)
        color bg = f_row_bg(r)
        color c  = f_anchor_col(prev_d_high)
        f_cell(t, 0, r, '● PDH', c, text.align_left, background = bg, tooltip = tt_pdh)
        f_cell(t, 1, r, str.tostring(math.round_to_mintick(prev_d_high)), c_txt, text.align_center, background = bg)
        t.merge_cells(1, r, 2, r)
        f_cell(t, 3, r, f_pct(prev_d_high), c_txt, text.align_right, background = bg)
        r += 1
    if show_pd and not na(prev_d_low)
        color bg = f_row_bg(r)
        color c  = f_anchor_col(prev_d_low)
        f_cell(t, 0, r, '● PDL', c, text.align_left, background = bg, tooltip = tt_pdl)
        f_cell(t, 1, r, str.tostring(math.round_to_mintick(prev_d_low)), c_txt, text.align_center, background = bg)
        t.merge_cells(1, r, 2, r)
        f_cell(t, 3, r, f_pct(prev_d_low), c_txt, text.align_right, background = bg)
        r += 1
 
    if show_pw and (not na(prev_w_high) or not na(prev_w_low))
        t.merge_cells(0, r, 3, r)
        f_cell(t, 0, r, '— Weekly —', c_va, text.align_center, background = c_hdr)
        r += 1
    if show_pw and not na(prev_w_high)
        color bg = f_row_bg(r)
        color c  = f_anchor_col(prev_w_high)
        f_cell(t, 0, r, '● PWH', c, text.align_left, background = bg, tooltip = tt_pwh)
        f_cell(t, 1, r, str.tostring(math.round_to_mintick(prev_w_high)), c_txt, text.align_center, background = bg)
        t.merge_cells(1, r, 2, r)
        f_cell(t, 3, r, f_pct(prev_w_high), c_txt, text.align_right, background = bg)
        r += 1
    if show_pw and not na(prev_w_low)
        color bg = f_row_bg(r)
        color c  = f_anchor_col(prev_w_low)
        f_cell(t, 0, r, '● PWL', c, text.align_left, background = bg, tooltip = tt_pwl)
        f_cell(t, 1, r, str.tostring(math.round_to_mintick(prev_w_low)), c_txt, text.align_center, background = bg)
        t.merge_cells(1, r, 2, r)
        f_cell(t, 3, r, f_pct(prev_w_low), c_txt, text.align_right, background = bg)
        r += 1
 
    if show_pm and (not na(prev_m_high) or not na(prev_m_low))
        t.merge_cells(0, r, 3, r)
        f_cell(t, 0, r, '— Monthly —', c_va, text.align_center, background = c_hdr)
        r += 1
    if show_pm and not na(prev_m_high)
        color bg = f_row_bg(r)
        color c  = f_anchor_col(prev_m_high)
        f_cell(t, 0, r, '● PMH', c, text.align_left, background = bg, tooltip = tt_pmh)
        f_cell(t, 1, r, str.tostring(math.round_to_mintick(prev_m_high)), c_txt, text.align_center, background = bg)
        t.merge_cells(1, r, 2, r)
        f_cell(t, 3, r, f_pct(prev_m_high), c_txt, text.align_right, background = bg)
        r += 1
    if show_pm and not na(prev_m_low)
        color bg = f_row_bg(r)
        color c  = f_anchor_col(prev_m_low)
        f_cell(t, 0, r, '● PML', c, text.align_left, background = bg, tooltip = tt_pml)
        f_cell(t, 1, r, str.tostring(math.round_to_mintick(prev_m_low)), c_txt, text.align_center, background = bg)
        t.merge_cells(1, r, 2, r)
        f_cell(t, 3, r, f_pct(prev_m_low), c_txt, text.align_right, background = bg)
        r += 1
 
    t.merge_cells(0, r, 3, r)
    f_cell(t, 0, r, 'Zone Stats Legend:  E · S · SW · V · D ⓘ', c_txt, text.align_center, background = c_row2, tooltip = tt_zone_legend)

← 返回列表