StormCore | HTF Price Magnet Matrix MTF v1.8

StormCore · study · 433 行 · 点赞 340 · TradingView 原页

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

Pine Script

//@version=6
// @author Andy Storm | AI-StormCore
indicator(
     title               = "StormCore | HTF Price Magnet Matrix MTF v1.8", 
     shorttitle          = "SC | Magnet Matrix MTF v1.8", 
     overlay             = true, 
     max_boxes_count     = 500, 
     max_lines_count     = 500, 
     max_labels_count    = 500,
     dynamic_requests    = false
 )
 
// ============================================================================
// 1. MODULE MASTER SWITCHES (TOP-LEVEL TOGGLES)
// ============================================================================
string GRP_TOGGLES = "━━━ 1. MODULE MASTER SWITCHES (TOGGLES) ━━━"
 
bool   en_fvg      = input.bool(true,  "Enable HTF Fair Value Gaps (FVG)",       group = GRP_TOGGLES, tooltip = "Отображает институциональные ценовые дисбалансы (Imbalance / FVG) старших таймфреймов.")
bool   en_liq      = input.bool(true,  "Enable HTF Liquidity Pools (EQH / EQL)", group = GRP_TOGGLES, tooltip = "Отображает пулы ликвидности (равные вершины Equal Highs и равные впадины Equal Lows) старших ТФ.")
bool   en_npoc     = input.bool(true,  "Enable HTF Naked POC (Volume Magnets)",  group = GRP_TOGGLES, tooltip = "Отображает нетестированные уровни максимального объема (Point of Control / VWAP-anchor) закрытых периодов.")
bool   en_gap      = input.bool(true,  "Enable HTF Session / Weekend Gaps",      group = GRP_TOGGLES, tooltip = "Отображает ценовые разрывы между закрытием и открытием свечей старшего ТФ.")
 
bool   en_htf1     = input.bool(true,  "Enable Slot 1: 4H Timeframe",            group = GRP_TOGGLES, tooltip = "Включает расчет и отрисовку магнитов с первого старшего ТФ (по умолчанию 4 часа).")
bool   en_htf2     = input.bool(true,  "Enable Slot 2: 1D Timeframe",            group = GRP_TOGGLES, tooltip = "Включает расчет и отрисовку магнитов со второго старшего ТФ (по умолчанию 1 день).")
bool   en_htf3     = input.bool(true,  "Enable Slot 3: 1W Timeframe",            group = GRP_TOGGLES, tooltip = "Включает расчет и отрисовку магнитов с третьего старшего ТФ (по умолчанию 1 неделя).")
bool   en_htf4     = input.bool(true,  "Enable Slot 4: 1M Timeframe",            group = GRP_TOGGLES, tooltip = "Включает расчет и отрисовку макро-магнитов с четвертого старшего ТФ (по умолчанию 1 месяц).")
bool   en_dash     = input.bool(true,  "Enable StormCore Telemetry Dashboard",   group = GRP_TOGGLES, tooltip = "Отображает информационную панель со статистикой активных магнитов и ближайшими целями.")
 
// ============================================================================
// 2. MITIGATION & ANTI-CLUTTER ENGINE
// ============================================================================
string GRP_ENGINE  = "━━━ 2. MITIGATION & ANTI-CLUTTER ENGINE ━━━"
 
string mit_mode    = input.string("StormCore 50% Equilibrium (CE)", "Mitigation (Removal) Mode", 
                     options = ["StormCore Touch (First Contact)", "StormCore 50% Equilibrium (CE)", "StormCore Full Fill (100% Mitigation)"], 
                     group   = GRP_ENGINE, 
                     tooltip = "Критерий автоматического удаления отработанной зоны с графика:\n• Touch — касание ближней границы.\n• 50% CE — достижение середины зоны.\n• Full Fill — полное перекрытие зоны.")
 
string zone_scope  = input.string("Smart Proximity (Nearest Only)", "Zone Display Scope", 
                     options = ["Smart Proximity (Nearest Only)", "Full Historical Scope (All Unmitigated)"], 
                     group   = GRP_ENGINE, 
                     tooltip = "• Smart Proximity — отображает только ближайшие к текущей цене зоны (сохраняет график чистым).\n• Full Historical Scope — отображает абсолютно все нетронутые зоны за всю историю актива по всему графику.")
 
int    max_magnets = input.int(16,   "Max Nearest Active Magnets (Anti-Clutter)", minval = 2, maxval = 60, group = GRP_ENGINE, tooltip = "Ограничивает количество одновременно отображаемых на экране ближайших к цене магнитов для сохранения чистоты графика (актуально для Smart Proximity режима).")
float  max_dist_pct= input.float(25.0,"Max Proximity Distance (% from Price)",    minval = 1.0, maxval = 200.0, step = 1.0, group = GRP_ENGINE, tooltip = "Скрывает магниты дальше указанного процента от цены в режиме Smart Proximity.")
int    right_offset= input.int(12,   "Right Projection Offset (Bars)",            minval = 2, maxval = 50, group = GRP_ENGINE, tooltip = "Отступ правого края зон и меток вправо от текущей свечи.")
bool   show_ce_line= input.bool(true,"Show 50% Equilibrium (CE) Line in Boxes",   group = GRP_ENGINE, tooltip = "Отрисовывает пунктирную линию 50% внутри диапазонных магнитов (FVG и Gaps).")
 
// ============================================================================
// 3. HTF TIMEFRAME CONFIGURATION
// ============================================================================
string GRP_HTF     = "━━━ 3. HTF TIMEFRAME CONFIG ━━━"
 
string tf_1        = input.timeframe("240", "HTF Slot 1 (Default: 4H)", group = GRP_HTF, tooltip = "Первый старший таймфрейм (рекомендуется 240 = 4 часа).")
string tf_2        = input.timeframe("D",   "HTF Slot 2 (Default: 1D)", group = GRP_HTF, tooltip = "Второй старший таймфрейм (рекомендуется D = 1 день).")
string tf_3        = input.timeframe("W",   "HTF Slot 3 (Default: 1W)", group = GRP_HTF, tooltip = "Третий старший таймфрейм (рекомендуется W = 1 неделя).")
string tf_4        = input.timeframe("M",   "HTF Slot 4 (Default: 1M)", group = GRP_HTF, tooltip = "Четвертый старший таймфрейм (рекомендуется M = 1 месяц).")
 
// ============================================================================
// 4. MAGNET SENSITIVITY & ATR FILTERS
// ============================================================================
string GRP_FILTER  = "━━━ 4. MAGNET SENSITIVITY & ATR FILTERS ━━━"
 
int    atr_len     = input.int(14,    "HTF ATR Period",                        minval = 5, maxval = 50, group = GRP_FILTER, tooltip = "Период ATR на старшем ТФ для фильтрации силы магнитов.")
float  fvg_min_atr = input.float(0.25,"FVG Minimum Height (x HTF ATR)",        minval = 0.05, maxval = 3.0, step = 0.05, group = GRP_FILTER, tooltip = "Минимальная ширина FVG в единицах ATR старшего ТФ. Отсекает мелкие незначимые имбалансы.")
int    liq_piv_len = input.int(3,     "EQH / EQL Pivot Lookback (HTF Bars)",   minval = 2, maxval = 15, group = GRP_FILTER, tooltip = "Количество свечей старшего ТФ слева и справа для формирования структурного экстремума.")
float  liq_tol_atr = input.float(0.15,"EQH / EQL Tolerance (x HTF ATR)",       minval = 0.02, maxval = 0.5, step = 0.01, group = GRP_FILTER, tooltip = "Максимальное расхождение между двумя пиками/впадинами (в долях ATR старшего ТФ) для признания их пулом ликвидности EQH/EQL.")
float  gap_min_atr = input.float(0.15,"Session/Weekend Gap Min Size (x ATR)",  minval = 0.05, maxval = 2.0, step = 0.05, group = GRP_FILTER, tooltip = "Минимальный размер разрыва между закрытием и открытием свечей старшего ТФ.")
 
// ============================================================================
// 5. STORMCORE VISUAL THEME & DASHBOARD
// ============================================================================
string GRP_VISUAL  = "━━━ 5. STORMCORE VISUAL THEME ━━━"
 
color  col_fvg_bull= input.color(color.new(#00E676, 82), "Bullish FVG (Lower Magnet) Fill",  group = GRP_VISUAL, tooltip = "Цвет заливки бычьего имбаланса (магнит поддержки внизу).")
color  col_fvg_bear= input.color(color.new(#FF5252, 82), "Bearish FVG (Upper Magnet) Fill",  group = GRP_VISUAL, tooltip = "Цвет заливки медвежьего имбаланса (магнит сопротивления вверху).")
color  col_liq_bull= input.color(color.new(#00B0FF, 15), "EQL Liquidity Pool Color",         group = GRP_VISUAL, tooltip = "Цвет уровня ликвидности под равными минимумами (EQL).")
color  col_liq_bear= input.color(color.new(#FF9100, 15), "EQH Liquidity Pool Color",         group = GRP_VISUAL, tooltip = "Цвет уровня ликвидности над равными максимумами (EQH).")
color  col_npoc    = input.color(color.new(#E040FB, 15), "Naked POC Volume Magnet Color",    group = GRP_VISUAL, tooltip = "Цвет нетестированного уровня максимального объема (nPOC).")
color  col_gap     = input.color(color.new(#FFD740, 80), "HTF Gap Magnet Fill",              group = GRP_VISUAL, tooltip = "Цвет заливки ценового гэпа старшего ТФ.")
string dash_pos    = input.string("StormCore Top Right", "Dashboard Position", 
                     options = ["StormCore Top Right", "StormCore Bottom Right", "StormCore Bottom Left", "StormCore Top Left"], 
                     group   = GRP_VISUAL, tooltip = "Позиция информационной панели на графике.")
string dash_scale  = input.string("Normal", "Dashboard Scale / Size", 
                     options = ["Small", "Normal", "Large", "Huge"], 
                     group   = GRP_VISUAL, tooltip = "Масштаб (размер шрифта и ячеек) информационной панели дашборда.")
string label_scale = input.string("Auto / Small", "Labels Font Scale / Size", 
                     options = ["Auto / Small", "Normal", "Large", "Huge"], 
                     group   = GRP_VISUAL, tooltip = "Масштаб шрифта текстовых меток магнитов на графике.")
 
// ============================================================================
// UDT (USER-DEFINED TYPES) & GLOBAL METHODS (PINE SCRIPT V6)
// ============================================================================
 
type MagnetZone
    string tf_name
    string m_type
    float  top
    float  bottom
    float  mid
    int    start_bar
    bool   is_bull
    bool   is_line
    color  base_col
    box    z_box
    line   z_line
    label  z_lbl
 
type HTFDataPacket
    bool   is_new_bar
    float  atr_val
    bool   fvg_bull_ok
    float  fvg_bull_top
    float  fvg_bull_bot
    bool   fvg_bear_ok
    float  fvg_bear_top
    float  fvg_bear_bot
    bool   eqh_ok
    float  eqh_lvl
    bool   eql_ok
    float  eql_lvl
    bool   npoc_ok
    float  npoc_lvl
    bool   gap_ok
    float  gap_top
    float  gap_bot
    bool   gap_is_bull
 
// Метод полной очистки графических примитивов магнита
method destroy_visuals(MagnetZone this) =>
    if not na(this.z_box)
        this.z_box.delete()
        this.z_box := na
    if not na(this.z_line)
        this.z_line.delete()
        this.z_line := na
    if not na(this.z_lbl)
        this.z_lbl.delete()
        this.z_lbl := na
    true
 
// Метод проверки отработки (Mitigation) зоны по текущим ценам High / Low
method is_mitigated(MagnetZone this, string mode) =>
    bool mitigated = false
    if bar_index > this.start_bar
        if this.is_line
            mitigated := (high >= this.mid and low <= this.mid) or (this.is_bull and low <= this.mid) or (not this.is_bull and high >= this.mid)
        else
            if this.is_bull
                float target = mode == "StormCore Touch (First Contact)" ? this.top : mode == "StormCore 50% Equilibrium (CE)" ? this.mid : this.bottom
                mitigated := low <= target
            else
                float target = mode == "StormCore Touch (First Contact)" ? this.bottom : mode == "StormCore 50% Equilibrium (CE)" ? this.mid : this.top
                mitigated := high >= target
    mitigated
 
// Метод отрисовки / обновления видимого магнита без окантовки (border_color = na)
method render_magnet(MagnetZone this, bool is_visible, int r_offset, bool show_ce, string lbl_sz_mode) =>
    if not is_visible
        this.destroy_visuals()
    else
        int right_x = bar_index + r_offset
        color text_col = color.new(color.white, 5)
        string lbl_text = str.format("🧲 {0} {1} [{2}]", this.tf_name, this.m_type, str.tostring(this.mid, format.mintick))
        
        string resolved_lbl_sz = lbl_sz_mode == "Normal" ? size.normal : lbl_sz_mode == "Large" ? size.large : lbl_sz_mode == "Huge" ? size.huge : size.small
 
        if this.is_line
            if na(this.z_line)
                this.z_line := line.new(this.start_bar, this.mid, right_x, this.mid, color = this.base_col, style = line.style_dashed, width = 2)
            else
                this.z_line.set_x2(right_x)
                this.z_line.set_y1(this.mid)
                this.z_line.set_y2(this.mid)
        else
            // Убираем окантовку блоков (border_color = na), оставляя только чистую заливку (bgcolor = this.base_col)
            if na(this.z_box)
                this.z_box := box.new(this.start_bar, this.top, right_x, this.bottom, border_color = na, border_width = 1, bgcolor = this.base_col)
            else
                this.z_box.set_right(right_x)
                this.z_box.set_top(this.top)
                this.z_box.set_bottom(this.bottom)
            
            if show_ce
                if na(this.z_line)
                    this.z_line := line.new(this.start_bar, this.mid, right_x, this.mid, color = color.new(this.base_col, 25), style = line.style_dotted, width = 1)
                else
                    this.z_line.set_x2(right_x)
                    this.z_line.set_y1(this.mid)
                    this.z_line.set_y2(this.mid)
            else if not na(this.z_line)
                this.z_line.delete()
                this.z_line := na
 
        if na(this.z_lbl)
            this.z_lbl := label.new(right_x, this.mid, lbl_text, color = color.new(#131722, 15), textcolor = text_col, style = label.style_label_left, size = resolved_lbl_sz)
        else
            this.z_lbl.set_x(right_x)
            this.z_lbl.set_y(this.mid)
            this.z_lbl.set_text(lbl_text)
            this.z_lbl.set_size(resolved_lbl_sz)
    true
 
// Функция расчета кандидатов магнитов на закрытых барах старшего ТФ (Zero-Repainting с индексом [1])
f_calc_htf_candidates(int atr_p, float fvg_mult, int piv_len, float eq_tol, float gap_mult) =>
    float atr = ta.atr(atr_p)[1]
    
    // 1. HTF FVG (Fair Value Gap) на закрытых свечах
    float b_fvg_top = low[1]
    float b_fvg_bot = high[3]
    bool  b_fvg     = (b_fvg_top - b_fvg_bot) >= (atr * fvg_mult) and close[2] > open[2]
    
    float s_fvg_top = low[3]
    float s_fvg_bot = high[1]
    bool  s_fvg     = (s_fvg_top - s_fvg_bot) >= (atr * fvg_mult) and close[2] < open[2]
    
    // 2. HTF EQH / EQL (Пулы ликвидности по пивотам)
    float ph = ta.pivothigh(high, piv_len, piv_len)[1]
    float pl = ta.pivotlow(low, piv_len, piv_len)[1]
    
    var float prev_ph = na
    var float prev_pl = na
    bool  eqh_found   = false
    float eqh_val     = na
    bool  eql_found   = false
    float eql_val     = na
    
    if not na(ph)
        if not na(prev_ph) and math.abs(ph - prev_ph) <= (atr * eq_tol)
            eqh_found := true
            eqh_val   := math.max(ph, prev_ph)
        prev_ph := ph
        
    if not na(pl)
        if not na(prev_pl) and math.abs(pl - prev_pl) <= (atr * eq_tol)
            eql_found := true
            eql_val   := math.min(pl, prev_pl)
        prev_pl := pl
 
    // 3. HTF Naked Volume POC
    float vol_ma   = ta.sma(volume, 10)[1]
    bool  npoc_ok  = volume[1] > vol_ma * 1.15
    float npoc_val = hlc3[1]
 
    // 4. HTF Session / Weekend Gap
    float gap_size = math.abs(open[1] - close[2])
    bool  gap_ok   = gap_size >= (atr * gap_mult)
    float gap_t    = math.max(open[1], close[2])
    float gap_b    = math.min(open[1], close[2])
    bool  gap_bull = open[1] > close[2]
 
    [bar_index[1], atr, b_fvg, b_fvg_top, b_fvg_bot, s_fvg, s_fvg_top, s_fvg_bot, eqh_found, eqh_val, eql_found, eql_val, npoc_ok, npoc_val, gap_ok, gap_t, gap_b, gap_bull]
 
// Безопасный MTF-запрос через request.security без ошибок индексации
f_fetch_htf(string tf, int atr_p, float fvg_mult, int piv_len, float eq_tol, float gap_mult) =>
    [h_idx, h_atr, bf_ok, bf_t, bf_b, sf_ok, sf_t, sf_b, eqh_ok, eqh_v, eql_ok, eql_v, np_ok, np_v, g_ok, g_t, g_b, g_bull] = request.security(
         syminfo.tickerid, 
         tf, 
         f_calc_htf_candidates(atr_p, fvg_mult, piv_len, eq_tol, gap_mult), 
         barmerge.gaps_off, 
         barmerge.lookahead_on
     )
    var int last_h_idx = -1
    bool is_new = not na(h_idx) and h_idx != last_h_idx
    if is_new
        last_h_idx := h_idx
    HTFDataPacket.new(is_new, h_atr, bf_ok, bf_t, bf_b, sf_ok, sf_t, sf_b, eqh_ok, eqh_v, eql_ok, eql_v, np_ok, np_v, g_ok, g_t, g_b, g_bull)
 
// Метод регистрации новых магнитов из пакета HTF в единый массив
method register_htf_magnets(
     array<MagnetZone> pool, 
     HTFDataPacket     pkt, 
     bool              tf_enabled, 
     string            tf_str, 
     string            tf_Tag,
     bool              use_fvg, 
     bool              use_liq, 
     bool              use_npoc, 
     bool              use_gap,
     color             c_fvg_b,
     color             c_fvg_s,
     color             c_liq_b,
     color             c_liq_s,
     color             c_npoc,
     color             c_gap
 ) =>
    bool valid_tf = timeframe.in_seconds(tf_str) >= timeframe.in_seconds(timeframe.period)
    if tf_enabled and valid_tf and pkt.is_new_bar
        if use_fvg and pkt.fvg_bull_ok and low > pkt.fvg_bull_top
            float mid_v = (pkt.fvg_bull_top + pkt.fvg_bull_bot) * 0.5
            pool.push(MagnetZone.new(tf_Tag, "Bull FVG", pkt.fvg_bull_top, pkt.fvg_bull_bot, mid_v, bar_index, true, false, c_fvg_b, na, na, na))
        if use_fvg and pkt.fvg_bear_ok and high < pkt.fvg_bear_bot
            float mid_v = (pkt.fvg_bear_top + pkt.fvg_bear_bot) * 0.5
            pool.push(MagnetZone.new(tf_Tag, "Bear FVG", pkt.fvg_bear_top, pkt.fvg_bear_bot, mid_v, bar_index, false, false, c_fvg_s, na, na, na))
        if use_liq and pkt.eqh_ok and high < pkt.eqh_lvl
            pool.push(MagnetZone.new(tf_Tag, "EQH Pool", pkt.eqh_lvl, pkt.eqh_lvl, pkt.eqh_lvl, bar_index, false, true, c_liq_s, na, na, na))
        if use_liq and pkt.eql_ok and low > pkt.eql_lvl
            pool.push(MagnetZone.new(tf_Tag, "EQL Pool", pkt.eql_lvl, pkt.eql_lvl, pkt.eql_lvl, bar_index, true, true, c_liq_b, na, na, na))
        if use_npoc and pkt.npoc_ok and (low > pkt.npoc_lvl or high < pkt.npoc_lvl)
            bool is_b = close > pkt.npoc_lvl
            pool.push(MagnetZone.new(tf_Tag, "nPOC", pkt.npoc_lvl, pkt.npoc_lvl, pkt.npoc_lvl, bar_index, is_b, true, c_npoc, na, na, na))
        if use_gap and pkt.gap_ok and (low > pkt.gap_top or high < pkt.gap_bot)
            float mid_g = (pkt.gap_top + pkt.gap_bot) * 0.5
            pool.push(MagnetZone.new(tf_Tag, "HTF Gap", pkt.gap_top, pkt.gap_bot, mid_g, bar_index, pkt.gap_is_bull, false, c_gap, na, na, na))
    true
 
// ============================================================================
// GLOBAL EXECUTION & DATA COLLECTION ("CALCULATE ALWAYS")
// ============================================================================
 
var array<MagnetZone> magnet_pool = array.new<MagnetZone>()
var int total_mitigated_count     = 0
 
HTFDataPacket pkt_1 = f_fetch_htf(tf_1, atr_len, fvg_min_atr, liq_piv_len, liq_tol_atr, gap_min_atr)
HTFDataPacket pkt_2 = f_fetch_htf(tf_2, atr_len, fvg_min_atr, liq_piv_len, liq_tol_atr, gap_min_atr)
HTFDataPacket pkt_3 = f_fetch_htf(tf_3, atr_len, fvg_min_atr, liq_piv_len, liq_tol_atr, gap_min_atr)
HTFDataPacket pkt_4 = f_fetch_htf(tf_4, atr_len, fvg_min_atr, liq_piv_len, liq_tol_atr, gap_min_atr)
 
magnet_pool.register_htf_magnets(pkt_1, en_htf1, tf_1, "4H", en_fvg, en_liq, en_npoc, en_gap, col_fvg_bull, col_fvg_bear, col_liq_bull, col_liq_bear, col_npoc, col_gap)
magnet_pool.register_htf_magnets(pkt_2, en_htf2, tf_2, "1D", en_fvg, en_liq, en_npoc, en_gap, col_fvg_bull, col_fvg_bear, col_liq_bull, col_liq_bear, col_npoc, col_gap)
magnet_pool.register_htf_magnets(pkt_3, en_htf3, tf_3, "1W", en_fvg, en_liq, en_npoc, en_gap, col_fvg_bull, col_fvg_bear, col_liq_bull, col_liq_bear, col_npoc, col_gap)
magnet_pool.register_htf_magnets(pkt_4, en_htf4, tf_4, "1M", en_fvg, en_liq, en_npoc, en_gap, col_fvg_bull, col_fvg_bear, col_liq_bull, col_liq_bear, col_npoc, col_gap)
 
// ============================================================================
// MITIGATION & ANTI-CLUTTER ENGINE PROCESSING
// ============================================================================
 
bool mitigated_this_bar = false
 
if magnet_pool.size() > 0
    for i = magnet_pool.size() - 1 to 0
        MagnetZone mz = magnet_pool.get(i)
        if mz.is_mitigated(mit_mode)
            mz.destroy_visuals()
            magnet_pool.remove(i)
            total_mitigated_count += 1
            mitigated_this_bar    := true
 
while magnet_pool.size() > 300
    MagnetZone oldest = magnet_pool.shift()
    oldest.destroy_visuals()
 
float nearest_up_lvl  = na
string nearest_up_txt = "None"
float nearest_dn_lvl  = na
string nearest_dn_txt = "None"
int   visible_count   = 0
 
if barstate.islast and magnet_pool.size() > 0
    array<float> dist_arr = array.new<float>()
    for i = 0 to magnet_pool.size() - 1
        MagnetZone mz = magnet_pool.get(i)
        float dist_pct = math.abs(mz.mid - close) / close * 100.0
        dist_arr.push(dist_pct)
        
        if mz.mid > close and (na(nearest_up_lvl) or mz.mid < nearest_up_lvl)
            nearest_up_lvl := mz.mid
            nearest_up_txt := mz.tf_name + " " + mz.m_type
        if mz.mid < close and (na(nearest_dn_lvl) or mz.mid > nearest_dn_lvl)
            nearest_dn_lvl := mz.mid
            nearest_dn_txt := mz.tf_name + " " + mz.m_type
 
    array<float> sorted_dist = dist_arr.copy()
    sorted_dist.sort(order.ascending)
    int   cutoff_idx = math.min(max_magnets - 1, sorted_dist.size() - 1)
    float cutoff_val = sorted_dist.get(cutoff_idx)
 
    for i = 0 to magnet_pool.size() - 1
        MagnetZone mz  = magnet_pool.get(i)
        float d_pct    = dist_arr.get(i)
        
        bool show_now = false
        if zone_scope == "Full Historical Scope (All Unmitigated)"
            show_now := true
            visible_count += 1
        else
            show_now := d_pct <= cutoff_val and d_pct <= max_dist_pct and visible_count < max_magnets
            if show_now
                visible_count += 1
                
        mz.render_magnet(show_now, right_offset, show_ce_line, label_scale)
 
// ============================================================================
// STORMCORE TELEMETRY DASHBOARD & GLOBAL PLOTS
// ============================================================================
 
var table sc_dash = na
if barstate.islast
    if not en_dash
        if not na(sc_dash)
            sc_dash.delete()
            sc_dash := na
    else
        string pos_str = dash_pos == "StormCore Top Right" ? position.top_right : dash_pos == "StormCore Bottom Right" ? position.bottom_right : dash_pos == "StormCore Bottom Left" ? position.bottom_left : position.top_left
        if na(sc_dash)
            sc_dash := table.new(pos_str, 2, 7, bgcolor = color.new(#0D1117, 10), border_color = color.new(#30363D, 20), border_width = 1, frame_color = color.new(#58A6FF, 30), frame_width = 1)
        
        string sz_choice = dash_scale == "Small" ? size.small : dash_scale == "Large" ? size.large : dash_scale == "Huge" ? size.huge : size.normal
 
        color c_head = color.new(#161B22, 0)
        color c_txt  = color.new(#E6EDF3, 0)
        color c_acc  = color.new(#58A6FF, 0)
        
        sc_dash.cell(0, 0, "⚡ SC | MAGNET MATRIX v1.8", text_color = c_acc, bgcolor = c_head, text_size = sz_choice)
        sc_dash.cell(1, 0, "MTF ZERO-REPAINT",          text_color = color.new(#3FB950, 0), bgcolor = c_head, text_size = sz_choice)
        
        sc_dash.cell(0, 1, "Mitigation Mode",           text_color = c_txt, text_size = sz_choice, text_halign = text.align_left)
        sc_dash.cell(1, 1, str.replace(mit_mode, "StormCore ", ""), text_color = c_acc, text_size = sz_choice, text_halign = text.align_right)
        
        sc_dash.cell(0, 2, "Visible / Memory Magnets",  text_color = c_txt, text_size = sz_choice, text_halign = text.align_left)
        sc_dash.cell(1, 2, str.tostring(visible_count) + " / " + str.tostring(magnet_pool.size()), text_color = c_txt, text_size = sz_choice, text_halign = text.align_right)
        
        sc_dash.cell(0, 3, "Mitigated (Cleared) Zones", text_color = c_txt, text_size = sz_choice, text_halign = text.align_left)
        sc_dash.cell(1, 3, str.tostring(total_mitigated_count), text_color = color.new(#A371F7, 0), text_size = sz_choice, text_halign = text.align_right)
        
        string up_str = na(nearest_up_lvl) ? "None" : nearest_up_txt + " @ " + str.tostring(nearest_up_lvl, format.mintick)
        sc_dash.cell(0, 4, "🔼 Upper Magnet",           text_color = color.new(#FF7B72, 0), text_size = sz_choice, text_halign = text.align_left)
        sc_dash.cell(1, 4, up_str,                      text_color = color.new(#FF7B72, 0), text_size = sz_choice, text_halign = text.align_right)
        
        string dn_str = na(nearest_dn_lvl) ? "None" : nearest_dn_txt + " @ " + str.tostring(nearest_dn_lvl, format.mintick)
        sc_dash.cell(0, 5, "🔽 Lower Magnet",           text_color = color.new(#3FB950, 0), text_size = sz_choice, text_halign = text.align_left)
        sc_dash.cell(1, 5, dn_str,                      text_color = color.new(#3FB950, 0), text_size = sz_choice, text_halign = text.align_right)
 
        string htf_active = (en_htf1 ? "4H " : "") + (en_htf2 ? "1D " : "") + (en_htf3 ? "1W " : "") + (en_htf4 ? "1M" : "")
        sc_dash.cell(0, 6, "Active HTF Slots",          text_color = c_txt, text_size = sz_choice, text_halign = text.align_left)
        sc_dash.cell(1, 6, htf_active,                  text_color = c_acc, text_size = sz_choice, text_halign = text.align_right)
 
// Глобальные невидимые линии ближайших магнитов для использования в стандартных алертах и окне данных TradingView
plot(nearest_up_lvl, title = "SC Nearest Upper Magnet", color = color.new(#FF5252, 100), display = display.data_window)
plot(nearest_dn_lvl, title = "SC Nearest Lower Magnet", color = color.new(#00E676, 100), display = display.data_window)
 
// Глобальные условия оповещений (Alertconditions)
alertcondition(mitigated_this_bar, title = "StormCore: HTF Magnet Mitigated (Reached)", message = "SC | Magnet Matrix MTF: Цена достигла и отработала ценовой магнит старшего ТФ на {{ticker}} ({{interval}}).")

← 返回列表