MSNR Key Levels Pro [Abusuhil]

abusuhil · study · 941 行 · 点赞 520 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Abusuhil
//
// MSNR Key Levels Pro — Malaysian Support & Resistance (levels and context only, no trade signals)
// • Levels come from candle BODIES (close of candle 1 = open of candle 2), never from wicks.
// • Higher timeframes are rebuilt from the chart's own closed bars: no request.security,
//   no lookahead, no repaint. Every state change happens on a confirmed bar.
// • Every rule the source books disagree on is a separate setting; two methods are never mixed.
 
//@version=6
indicator("MSNR Key Levels Pro [Abusuhil]", shorttitle = "MSNR Pro", overlay = true, max_lines_count = 500, max_labels_count = 500)
 
// ───────────────────────────── Constants ─────────────────────────────
string LANG_EN = "English"
string LANG_AR = "العربية"
 
string TF_ONE   = "One higher timeframe"
string TF_THREE = "Three layers: D1 > H4 > H1 (Trading Secret)"
 
string GAP_ALL   = "All same-colour pairs (Trading Secret)"
string GAP_MOM   = "Momentum candle only (Alchemist 2.00)"
string GAP_CLEAN = "Clean gap, no long tail (ZakFX)"
 
string FR_WICK = "Wick touch = unfresh (Flipper / ZakFX)"
string FR_BODY = "Body close only (Alchemist 2.00 p.26)"
 
string ST_BRK = "Rejection + breakout one layer below (EMS Trinity)"
string ST_REJ = "Rejection only"
 
string LQ_NONE = "Off"
string LQ_CE   = "50% of tail - CE (Sataya / Alchemist 2.00)"
string LQ_TAIL = "Tail extreme - liquidity (ZakFX)"
 
string FIB_KEY    = "MSNR key-level clusters (.618 / .786)"
string FIB_SNIPER = "Sweep extension (-0.21 / 1.47 / 2.56)"
string FIB_PULL   = "Pullback projection (1.618 / 2.618)"
string FA_WICK = "Wicks"
string FA_BODY = "Bodies (line chart)"
 
int MAX_LEVELS = 180
int ATR_LEN    = 14
 
// ───────────────────────────── Inputs ─────────────────────────────
string G_GEN = "General"
string langIn = input.string(LANG_EN, "Language / اللغة", options = [LANG_EN, LANG_AR], group = G_GEN)
 
string G_LV = "Levels - chart timeframe"
bool showAV   = input.bool(true, "A / V levels", group = G_LV, inline = "l1")
bool showGap  = input.bool(true, "Gap (OCL)", group = G_LV, inline = "l1")
bool showFlip = input.bool(true, "RBS / SBR", group = G_LV, inline = "l2")
bool showQml  = input.bool(true, "QML", group = G_LV, inline = "l2")
int  pivLen   = input.int(2, "Turn strength (line-chart pivot)", minval = 1, maxval = 20, group = G_LV, tooltip = "1 = every turn of the closing line, exactly as the books draw it (busy). Higher = only stronger turns.\n1 = كل انعطاف في خط الإغلاق كما في الكتب. الأعلى = انعطافات أقوى فقط.")
 
string G_HTF = "Higher timeframes"
bool   useHtf     = input.bool(true, "Use higher timeframes", group = G_HTF)
string tfMode     = input.string(TF_ONE, "Timeframe system", options = [TF_ONE, TF_THREE], group = G_HTF, tooltip = "One higher timeframe: chart + one layer above it.\nThree layers: chart = entry layer, middle = validation layer, top = key-zone layer (MSNR Trading Secret p.29-34: D1 marks the zone, H4 validates, H1 enters).\nBoth are built from the chart's own bars, so they never repaint.\nنظام فريم أعلى واحد، أو ثلاث طبقات كما في Trading Secret. كلاهما بلا إعادة رسم.")
string htfIn1     = input.timeframe("", "Layer 2 timeframe (Chart = Auto)", group = G_HTF, tooltip = "Auto follows the pairs in MSNR Trading Secret: 5m>30m, 15m>1H, 30m>2H, 1H>4H, 4H>D, D>W.")
string htfIn2     = input.timeframe("", "Layer 3 timeframe (Chart = Auto)", group = G_HTF, tooltip = "Used only in the three-layer system. Auto = one step above layer 2 (1H chart: 4H then D).")
bool   showHtfAV  = input.bool(true, "HTF A / V", group = G_HTF, inline = "h1")
bool   showHtfGap = input.bool(true, "HTF Gap (OCL)", group = G_HTF, inline = "h1")
int    htfPiv     = input.int(2, "HTF turn strength", minval = 1, maxval = 10, group = G_HTF)
 
string G_GAP = "Gap (OCL) selection - authors differ"
string gapMode = input.string(GAP_MOM, "Which gaps count", options = [GAP_ALL, GAP_MOM, GAP_CLEAN], group = G_GAP)
float  gapMom  = input.float(1.0, "Momentum: min body (x ATR)", minval = 0.1, step = 0.1, group = G_GAP)
float  gapTail = input.float(0.25, "Clean: max tail (x body)", minval = 0.0, step = 0.05, group = G_GAP)
 
string G_FR = "Freshness - authors differ"
string freshRule   = input.string(FR_WICK, "What makes a level unfresh", options = [FR_WICK, FR_BODY], group = G_FR)
int    spendN      = input.int(0, "Hide a level after N touches (0 = never)", minval = 0, maxval = 10, group = G_FR, tooltip = "1 = a level is used once only (MSNR PDF, Flipper). 2 = Alchemist 2.00. 0 keeps touched levels on the chart as unfresh.\nA body break still flips a hidden level and makes it fresh again.")
int    maxFlips    = input.int(2, "Max role flips (RBS/SBR)", minval = 0, maxval = 10, group = G_FR, tooltip = "How many times a body break may flip a level and make it fresh again. Flipper: unlimited (use 10). ZakFX: a level price chops through is dropped (use 1). 0 = a broken level is deleted.")
bool   showUnfresh = input.bool(true, "Show unfresh levels (dashed)", group = G_FR)
 
string G_BR = "Break and retest"
bool   showMarks = input.bool(true, "Mark the break and the first retest", group = G_BR, tooltip = "For a flipped level (RBS / SBR): the old role is drawn faded up to the breaking candle, a cross marks the body break, and RT marks the first wick retest.\nيُرسم الدور القديم باهتاً حتى شمعة الكسر، وعلامة × للكسر و RT لأول إعادة اختبار.")
string lqLine    = input.string(LQ_NONE, "Liquidity line behind fresh A / V", options = [LQ_NONE, LQ_CE, LQ_TAIL], group = G_BR, tooltip = "Optional second line in the wick of the turn: its midpoint (candle equilibrium) or its tip.")
 
string G_QM = "QML"
int   qmLen    = input.int(5, "Structure pivot length", minval = 2, maxval = 30, group = G_QM)
float qmExcess = input.float(0.0, "Max head excess (x shoulder height, 0 = off)", minval = 0.0, step = 0.1, group = G_QM, tooltip = "Nora Bystra: the head should break the left shoulder only a little. 0 disables this filter.")
bool  qmHtf    = input.bool(false, "Head must tap an HTF level (Trading Secret)", group = G_QM)
 
string G_ST = "Storyline (higher-timeframe context)"
bool   stlOn        = input.bool(true, "Track storyline", group = G_ST)
string stlMode      = input.string(ST_BRK, "Storyline starts on", options = [ST_BRK, ST_REJ], group = G_ST, tooltip = "EMS Trinity: the top layer rejects one of its own fresh levels, then the layer below closes through its last classic A / V.\nOne higher timeframe: top = layer 2, breakout on the chart. Three layers: top = layer 3, breakout on layer 2.")
bool   showStl      = input.bool(true, "Show storyline target line", group = G_ST)
bool   showStlMarks = input.bool(false, "Show storyline direction changes on chart", group = G_ST)
 
string G_FIB = "Fibonacci (optional confluence)"
bool   fibOn     = input.bool(false, "Show fibonacci on last swing leg", group = G_FIB)
string fibPreset = input.string(FIB_KEY, "Preset", options = [FIB_KEY, FIB_SNIPER, FIB_PULL], group = G_FIB)
string fibAnchor = input.string(FA_WICK, "Anchor on", options = [FA_WICK, FA_BODY], group = G_FIB)
 
string G_STY = "Style"
color  colRes    = input.color(#F23645, "Resistance", group = G_STY, inline = "c1")
color  colSup    = input.color(#089981, "Support", group = G_STY, inline = "c1")
color  colQml    = input.color(#9C27B0, "QML", group = G_STY, inline = "c1")
int    maxSide   = input.int(6, "Max fresh levels each side of price", minval = 1, maxval = 40, group = G_STY)
int    maxSideU  = input.int(3, "Max unfresh levels each side of price", minval = 0, maxval = 40, group = G_STY)
int    extBars   = input.int(8, "Extend lines right (bars)", minval = 2, maxval = 100, group = G_STY)
bool   showLbl   = input.bool(true, "Level labels", group = G_STY)
string lblSizeIn = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = G_STY)
bool   showDash  = input.bool(true, "Dashboard", group = G_STY)
string dashPosIn = input.string("Top right", "Dashboard position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = G_STY)
 
// ───────────────────────────── Derived settings ─────────────────────────────
bool isAr     = langIn == LANG_AR
bool wickMode = freshRule == FR_WICK
 
f_t(string en, string ar) =>
    isAr ? ar : en
 
// Next layer up, following the timeframe pairs printed in MSNR Trading Secret p.36
f_autoFrom(int s) =>
    string r = "M"
    if s <= 60
        r := "15"
    else if s <= 300
        r := "30"
    else if s <= 900
        r := "60"
    else if s <= 1800
        r := "120"
    else if s <= 3600
        r := "240"
    else if s <= 14400
        r := "D"
    else if s <= 86400
        r := "W"
    r
 
f_tfStr(string tf) =>
    string r = tf
    bool named = str.contains(tf, "D") or str.contains(tf, "W") or str.contains(tf, "M") or str.contains(tf, "S")
    if not named
        int m = int(str.tonumber(tf))
        if m >= 60 and m % 60 == 0
            r := str.tostring(int(m / 60)) + "H"
        else
            r := str.tostring(m) + "m"
    r
 
string rawTf1 = htfIn1 == "" ? f_autoFrom(timeframe.in_seconds()) : htfIn1
string rawTf2 = htfIn2 == "" ? f_autoFrom(timeframe.in_seconds(rawTf1)) : htfIn2
int    cSec   = timeframe.in_seconds()
bool   ok1    = timeframe.in_seconds(rawTf1) > cSec
bool   ok2    = tfMode == TF_THREE and timeframe.in_seconds(rawTf2) > cSec
// A manual layer that is not above the chart timeframe is skipped; the remaining one becomes layer 2.
string tf1   = ok1 ? rawTf1 : rawTf2
string tf2   = rawTf2
bool   htfOK = useHtf and (ok1 or ok2)
bool   three = htfOK and ok1 and ok2 and timeframe.in_seconds(rawTf2) > timeframe.in_seconds(rawTf1)
string lbl1  = f_tfStr(tf1)
string lbl2  = f_tfStr(tf2)
// Storyline layers: the top layer gives the level and the rejection, the layer below gives the breakout.
int topSlot = three ? 2 : 1
int brkSlot = topSlot - 1
 
// ───────────────────────────── Global series (all ta.* calls live here) ─────────────────────────────
float atr     = ta.atr(ATR_LEN)
float phC     = ta.pivothigh(close, pivLen, pivLen)
float plC     = ta.pivotlow(close, pivLen, pivLen)
float sphC    = ta.pivothigh(close, qmLen, qmLen)
float splC    = ta.pivotlow(close, qmLen, qmLen)
float sphW    = ta.pivothigh(high, qmLen, qmLen)
float splW    = ta.pivotlow(low, qmLen, qmLen)
bool  chg1    = timeframe.change(tf1)
bool  chg2    = timeframe.change(tf2)
int   closeT1 = time_close(tf1)
int   closeT2 = time_close(tf2)
 
// ───────────────────────────── Objects ─────────────────────────────
// kind: 1 = classic A/V, 2 = gap (OCL), 3 = QML   |   role: 1 = resistance, -1 = support
// slot: 0 = chart timeframe, 1 = layer 2, 2 = layer 3
type Level
    float price
    float tail
    int   t0
    int   kind
    int   role
    int   slot
    int   uses
    int   flips
    bool  touching
    int   usesPrev
    int   tBrk
    int   tRet
 
// One higher-timeframe candle under construction plus the history of closed ones
type Htf
    float o
    float h
    float l
    float c
    int   t
    array<float> os
    array<float> hs
    array<float> ls
    array<float> cs
    array<int>   ts
    int   lastBrk
 
var array<Level> levels = array.new<Level>()
var Htf H1 = Htf.new(na, na, na, na, na, array.new<float>(), array.new<float>(), array.new<float>(), array.new<float>(), array.new<int>(), 0)
var Htf H2 = Htf.new(na, na, na, na, na, array.new<float>(), array.new<float>(), array.new<float>(), array.new<float>(), array.new<int>(), 0)
 
f_add(float price, float tail, int t0, int kind, int role, int slot, int uses0) =>
    bool dup = false
    float tol = nz(atr) * 0.02
    if levels.size() > 0
        for i = levels.size() - 1 to 0
            Level x = levels.get(i)
            if x.slot == slot and x.role == role and math.abs(x.price - price) <= tol
                dup := true
                if kind == 3
                    x.kind  := 3
                    x.flips := 0
                    x.uses  := uses0
                    x.tail  := tail
                    x.tBrk  := na
                    x.tRet  := na
                break
    if not dup
        levels.push(Level.new(price, tail, t0, kind, role, slot, uses0, 0, false, uses0, na, na))
        if levels.size() > MAX_LEVELS
            int rm = -1
            for i = 0 to levels.size() - 1
                Level x = levels.get(i)
                if x.slot == 0 and x.uses > 0
                    rm := i
                    break
            if rm < 0
                for i = 0 to levels.size() - 1
                    Level x = levels.get(i)
                    if x.slot == 0
                        rm := i
                        break
            if rm < 0
                rm := 0
            levels.remove(rm)
    not dup
 
f_name(Level lv) =>
    string n = ""
    if lv.kind == 3
        n := "QML"
    else if lv.flips > 0
        n := lv.role == 1 ? "SBR" : "RBS"
    else if lv.kind == 2
        n := "GAP"
    else
        n := lv.role == 1 ? "A" : "V"
    string pre = ""
    if lv.slot == 1
        pre := lbl1 + " "
    else if lv.slot == 2
        pre := lbl2 + " "
    pre + n
 
f_isFresh(Level lv) =>
    wickMode ? lv.uses == 0 : true
 
f_isSpent(Level lv) =>
    spendN > 0 and lv.uses >= spendN
 
// Was the level still fresh when the current candle of its own timeframe opened?
f_wasFresh(Level lv) =>
    bool r = wickMode ? lv.usesPrev == 0 : true
    if spendN > 0 and lv.usesPrev >= spendN
        r := false
    r
 
f_flip(Level lv, int newRole) =>
    lv.role := newRole
    lv.flips += 1
    lv.uses := 0
    lv.touching := false
    lv.tail := na
    lv.tBrk := time
    lv.tRet := na
 
f_gapOK(float o1, float h1, float l1, float c1, float o2, float h2, float l2, float c2, int dir, float a) =>
    bool ok = true
    float b1 = math.abs(c1 - o1)
    float b2 = math.abs(c2 - o2)
    if gapMode == GAP_MOM
        ok := math.max(b1, b2) >= gapMom * nz(a)
    else if gapMode == GAP_CLEAN
        // No long tail across the junction: candle 1's closing-side wick and candle 2's opening-side wick.
        float w1 = dir == 1 ? h1 - c1 : c1 - l1
        float w2 = dir == 1 ? o2 - l2 : h2 - o2
        ok := w1 <= gapTail * b1 and w2 <= gapTail * b2
    ok
 
// Nearest level of a layer in a direction (dir 1 = resistance above px, -1 = support below px).
f_next(int slot, int dir, float px) =>
    float best = na
    if levels.size() > 0
        for i = 0 to levels.size() - 1
            Level x = levels.get(i)
            if x.slot == slot and x.role == dir
                if dir == 1 and x.price > px
                    if na(best) or x.price < best
                        best := x.price
                if dir == -1 and x.price < px
                    if na(best) or x.price > best
                        best := x.price
    best
 
// Most recent unbroken classic A / V of a layer on the far side of px: the breakout line of the storyline.
f_lastClassic(int slot, int role, float px) =>
    float r = na
    if levels.size() > 0
        for i = levels.size() - 1 to 0
            Level x = levels.get(i)
            if x.slot == slot and x.kind == 1 and x.flips == 0 and x.role == role
                bool side = role == -1 ? x.price < px : x.price > px
                if side
                    r := x.price
                    break
    r
 
// Feeds one chart bar into a higher-timeframe layer. When a candle of that layer closes it:
// flips the layer's levels on a body close, records wick rejections of levels that were fresh,
// and creates the layer's new A / V and gap levels.
// Returns [closed, broke, formed, breakDir, rejectDir].
f_htf(Htf s, int slot, bool chg, int closeT) =>
    bool closed = false
    bool broke = false
    bool formed = false
    int brkDir = 0
    int rejDir = 0
    for q = 0 to 1
        bool doClose = false
        if q == 0
            // A new period started and the previous candle was not closed by time: close it now.
            if chg and not na(s.o)
                doClose := true
        else
            if na(s.o)
                s.o := open
                s.h := high
                s.l := low
                s.t := time
            else
                s.h := math.max(s.h, high)
                s.l := math.min(s.l, low)
            s.c := close
            if not na(closeT) and time_close >= closeT
                doClose := true
        if doClose
            closed := true
            s.os.push(s.o)
            s.hs.push(s.h)
            s.ls.push(s.l)
            s.cs.push(s.c)
            s.ts.push(s.t)
            if s.cs.size() > 60
                s.os.shift()
                s.hs.shift()
                s.ls.shift()
                s.cs.shift()
                s.ts.shift()
            int n = s.cs.size()
            // Body breaks and wick rejections of this layer's levels
            if levels.size() > 0
                for i = levels.size() - 1 to 0
                    Level lv = levels.get(i)
                    if lv.slot == slot
                        bool wf = f_wasFresh(lv)
                        if lv.role == 1
                            if s.c > lv.price
                                f_flip(lv, -1)
                                broke := true
                                s.lastBrk := 1
                                if wf
                                    brkDir := 1
                                if lv.flips > maxFlips
                                    levels.remove(i)
                            else if s.h >= lv.price and wf
                                rejDir := -1
                        else
                            if s.c < lv.price
                                f_flip(lv, 1)
                                broke := true
                                s.lastBrk := -1
                                if wf
                                    brkDir := -1
                                if lv.flips > maxFlips
                                    levels.remove(i)
                            else if s.l <= lv.price and wf
                                rejDir := 1
            // New A / V on this layer's closing line
            if n >= 2 * htfPiv + 1
                int c0 = n - 1 - htfPiv
                float pc = s.cs.get(c0)
                bool isA = true
                bool isV = true
                for j = 1 to htfPiv
                    float lft = s.cs.get(c0 - j)
                    float rgt = s.cs.get(c0 + j)
                    if not (pc >= lft and pc > rgt)
                        isA := false
                    if not (pc <= lft and pc < rgt)
                        isV := false
                if isA
                    int u = 0
                    if c0 + 2 <= n - 1
                        for k = c0 + 2 to n - 1
                            if s.hs.get(k) >= pc
                                u := 1
                    if f_add(pc, math.max(s.hs.get(c0), s.hs.get(c0 + 1)), s.ts.get(c0), 1, 1, slot, u)
                        formed := true
                if isV
                    int u = 0
                    if c0 + 2 <= n - 1
                        for k = c0 + 2 to n - 1
                            if s.ls.get(k) <= pc
                                u := 1
                    if f_add(pc, math.min(s.ls.get(c0), s.ls.get(c0 + 1)), s.ts.get(c0), 1, -1, slot, u)
                        formed := true
            // New gap (OCL): two closed candles of the same colour
            if n >= 2
                float o1 = s.os.get(n - 2)
                float h1 = s.hs.get(n - 2)
                float l1 = s.ls.get(n - 2)
                float c1 = s.cs.get(n - 2)
                // Average range of this layer's last candles (the chart ATR would be too small here)
                float hAtr = 0.0
                int cntA = math.min(n, ATR_LEN)
                for k = n - cntA to n - 1
                    hAtr += s.hs.get(k) - s.ls.get(k)
                hAtr := hAtr / cntA
                if c1 > o1 and s.c > s.o
                    if f_gapOK(o1, h1, l1, c1, s.o, s.h, s.l, s.c, 1, hAtr)
                        if f_add(c1, s.l, s.t, 2, -1, slot, 0)
                            formed := true
                if c1 < o1 and s.c < s.o
                    if f_gapOK(o1, h1, l1, c1, s.o, s.h, s.l, s.c, -1, hAtr)
                        if f_add(c1, s.h, s.t, 2, 1, slot, 0)
                            formed := true
            // Snapshot of use counts: tells the next candle of this layer which levels were fresh at its open
            if levels.size() > 0
                for i = 0 to levels.size() - 1
                    Level x = levels.get(i)
                    if x.slot == slot
                        x.usesPrev := x.uses
            s.o := na
    [closed, broke, formed, brkDir, rejDir]
 
// ───────────────────────────── Persistent state ─────────────────────────────
// Storyline
var int   stDir     = 0
var float stTarget  = na
var int   pendDir   = 0
var float pendRef   = na
var int   stShown   = 0
 
// QML tracking (close-based structure pivots)
var float qHiP = na
var float qHiTail = na
var int   qHiT = na
var int   qHiBar = na
var float qLoP = na
var float qLoTail = na
var int   qLoT = na
var int   qLoBar = na
var float qbLS = na
var float qbTail = na
var int   qbT = na
var float qbNeck = na
var float qbHead = na
var float qsLS = na
var float qsTail = na
var int   qsT = na
var float qsNeck = na
var float qsHead = na
 
// Fibonacci leg anchors
var float fHiP = na
var int   fHiT = na
var float fLoP = na
var int   fLoT = na
 
// Per-bar events (used by the alerts)
bool evNew = false
bool evFreshTouch = false
bool evBreak = false
bool evStl = false
 
// ───────────────────────────── Engine (confirmed bars only) ─────────────────────────────
if barstate.isconfirmed
    // 1) Wick touches on every layer; body breaks and role flips on the chart layer --------
    if levels.size() > 0
        for i = levels.size() - 1 to 0
            Level lv = levels.get(i)
            float P = lv.price
            bool brk = false
            bool tch = false
            if lv.role == 1
                brk := lv.slot == 0 and close > P
                tch := high >= P
            else
                brk := lv.slot == 0 and close < P
                tch := low <= P
            if brk
                f_flip(lv, -lv.role)
                evBreak := true
                if lv.flips > maxFlips
                    levels.remove(i)
            else if tch
                if not lv.touching
                    if lv.uses == 0
                        evFreshTouch := true
                    if lv.flips > 0 and na(lv.tRet)
                        lv.tRet := time
                    lv.uses += 1
                lv.touching := true
            else
                lv.touching := false
 
    // 2) Higher-timeframe layers, rebuilt from chart bars ---------------------------------
    bool closed1 = false
    bool closedTop = false
    int  topBrk = 0
    int  topRej = 0
    if htfOK
        [c1x, b1x, n1x, bd1, rd1] = f_htf(H1, 1, chg1, closeT1)
        closed1 := c1x
        if b1x
            evBreak := true
        if n1x
            evNew := true
        if not three
            closedTop := c1x
            topBrk := bd1
            topRej := rd1
    if three
        [c2x, b2x, n2x, bd2, rd2] = f_htf(H2, 2, chg2, closeT2)
        closedTop := c2x
        topBrk := bd2
        topRej := rd2
        if b2x
            evBreak := true
        if n2x
            evNew := true
 
    // 3) New chart-timeframe A / V levels (turns of the closing line) ----------------------
    if not na(phC)
        float pA = close[pivLen]
        int uA = 0
        if pivLen >= 2
            for k = pivLen - 2 to 0
                if high[k] >= pA
                    uA := 1
        if f_add(pA, math.max(high[pivLen], high[pivLen - 1]), time[pivLen], 1, 1, 0, uA)
            evNew := true
    if not na(plC)
        float pV = close[pivLen]
        int uV = 0
        if pivLen >= 2
            for k = pivLen - 2 to 0
                if low[k] <= pV
                    uV := 1
        if f_add(pV, math.min(low[pivLen], low[pivLen - 1]), time[pivLen], 1, -1, 0, uV)
            evNew := true
 
    // 4) New chart-timeframe gap (OCL) ----------------------------------------------------
    if showGap and bar_index > 0
        if close[1] > open[1] and close > open
            if f_gapOK(open[1], high[1], low[1], close[1], open, high, low, close, 1, atr)
                if f_add(close[1], low, time, 2, -1, 0, 0)
                    evNew := true
        if close[1] < open[1] and close < open
            if f_gapOK(open[1], high[1], low[1], close[1], open, high, low, close, -1, atr)
                if f_add(close[1], high, time, 2, 1, 0, 0)
                    evNew := true
 
    // 5) QML: left shoulder, head, then a body close through the neckline -----------------
    if showQml
        if not na(sphC)
            float hp = close[qmLen]
            float ht = math.max(high[qmLen], high[qmLen - 1])
            // Bearish QM candidate: H (left shoulder) -> L (neck) -> HH (head)
            if not na(qHiP) and not na(qLoP) and qLoBar > qHiBar and hp > qHiP and qLoP < qHiP
                bool okQ = true
                if qmExcess > 0
                    okQ := (hp - qHiP) <= qmExcess * (qHiP - qLoP)
                if qmHtf
                    bool tap = false
                    if levels.size() > 0
                        for i = 0 to levels.size() - 1
                            Level x = levels.get(i)
                            if x.slot >= 1 and x.price >= qHiP and x.price <= ht
                                tap := true
                    okQ := okQ and tap
                if okQ
                    qbLS := qHiP
                    qbTail := qHiTail
                    qbT := qHiT
                    qbNeck := qLoP
                    qbHead := hp
            qHiP := hp
            qHiTail := ht
            qHiT := time[qmLen]
            qHiBar := bar_index - qmLen
        if not na(splC)
            float lp = close[qmLen]
            float lt = math.min(low[qmLen], low[qmLen - 1])
            // Bullish QM candidate: L (left shoulder) -> H (neck) -> LL (head)
            if not na(qLoP) and not na(qHiP) and qHiBar > qLoBar and lp < qLoP and qHiP > qLoP
                bool okQ = true
                if qmExcess > 0
                    okQ := (qLoP - lp) <= qmExcess * (qHiP - qLoP)
                if qmHtf
                    bool tap = false
                    if levels.size() > 0
                        for i = 0 to levels.size() - 1
                            Level x = levels.get(i)
                            if x.slot >= 1 and x.price <= qLoP and x.price >= lt
                                tap := true
                    okQ := okQ and tap
                if okQ
                    qsLS := qLoP
                    qsTail := qLoTail
                    qsT := qLoT
                    qsNeck := qHiP
                    qsHead := lp
            qLoP := lp
            qLoTail := lt
            qLoT := time[qmLen]
            qLoBar := bar_index - qmLen
        if not na(qbLS)
            if close < qbNeck
                if f_add(qbLS, qbTail, qbT, 3, 1, 0, 0)
                    evNew := true
                qbLS := na
            else if close > qbHead
                qbLS := na
        if not na(qsLS)
            if close > qsNeck
                if f_add(qsLS, qsTail, qsT, 3, -1, 0, 0)
                    evNew := true
                qsLS := na
            else if close < qsHead
                qsLS := na
 
    // 6) Fibonacci leg anchors ------------------------------------------------------------
    if fibAnchor == FA_WICK
        if not na(sphW)
            fHiP := sphW
            fHiT := time[qmLen]
        if not na(splW)
            fLoP := splW
            fLoT := time[qmLen]
    else
        if not na(sphC)
            fHiP := sphC
            fHiT := time[qmLen]
        if not na(splC)
            fLoP := splC
            fLoT := time[qmLen]
 
    // 7) Storyline ------------------------------------------------------------------------
    if stlOn and htfOK
        // 7a) Events on the top layer's closed candle
        if closedTop
            if topBrk != 0
                // A fresh top-layer level was broken by a body: price is expected at the next one.
                stDir := topBrk
                stTarget := f_next(topSlot, topBrk, close)
                pendDir := 0
                pendRef := na
                evStl := true
            else if topRej != 0
                if stlMode == ST_REJ
                    stDir := topRej
                    stTarget := f_next(topSlot, topRej, close)
                    pendDir := 0
                    pendRef := na
                    evStl := true
                else
                    pendDir := topRej
                    pendRef := f_lastClassic(brkSlot, -topRej, close)
        // 7b) Breakout confirmation on the layer below the top
        bool brkBar = brkSlot == 0 ? true : closed1
        if pendDir != 0 and brkBar and not evStl
            if na(pendRef)
                pendRef := f_lastClassic(brkSlot, -pendDir, close)
            if not na(pendRef)
                bool conf = pendDir == -1 ? close < pendRef : close > pendRef
                if conf
                    stDir := pendDir
                    stTarget := f_next(topSlot, pendDir, close)
                    pendDir := 0
                    pendRef := na
                    evStl := true
        // 7c) Target reached: the storyline is complete
        if stDir != 0 and not na(stTarget) and not evStl
            bool reached = stDir == 1 ? high >= stTarget : low <= stTarget
            if reached
                stDir := 0
                stTarget := na
 
    if evStl and showStlMarks and stDir != 0 and stDir != stShown
        stShown := stDir
        if stDir == 1
            label.new(bar_index, low, "STL ▲", style = label.style_label_up, color = color.new(colSup, 70), textcolor = colSup, size = size.tiny, yloc = yloc.belowbar)
        else
            label.new(bar_index, high, "STL ▼", style = label.style_label_down, color = color.new(colRes, 70), textcolor = colRes, size = size.tiny, yloc = yloc.abovebar)
 
// ───────────────────────────── Drawing (last bar, from stored state) ─────────────────────────────
var array<line>  drawnLines  = array.new<line>()
var array<label> drawnLabels = array.new<label>()
var table dash = na
 
f_visible(Level lv) =>
    bool ok = false
    if lv.kind == 3
        ok := showQml
    else if lv.flips > 0
        ok := showFlip
    else if lv.kind == 2
        ok := lv.slot >= 1 ? showHtfGap : showGap
    else
        ok := lv.slot >= 1 ? showHtfAV : showAV
    if lv.slot == 1 and not htfOK
        ok := false
    if lv.slot == 2 and not three
        ok := false
    if not showUnfresh and not f_isFresh(lv)
        ok := false
    if f_isSpent(lv)
        ok := false
    ok
 
string lblSize = switch lblSizeIn
    "Tiny" => size.tiny
    "Normal" => size.normal
    => size.small
 
if barstate.islast
    if drawnLines.size() > 0
        for i = drawnLines.size() - 1 to 0
            line.delete(drawnLines.get(i))
        drawnLines.clear()
    if drawnLabels.size() > 0
        for i = drawnLabels.size() - 1 to 0
            label.delete(drawnLabels.get(i))
        drawnLabels.clear()
 
    int barMs = timeframe.in_seconds() * 1000
    int xR = time + extBars * barMs
    float nearR = na
    float nearS = na
    string nearRn = ""
    string nearSn = ""
    int cntR = 0
    int cntS = 0
 
    // Distance ranking: fresh and unfresh levels each get their own quota per side of price
    array<float> dUp = array.new<float>()
    array<float> dDn = array.new<float>()
    array<float> uUp = array.new<float>()
    array<float> uDn = array.new<float>()
    if levels.size() > 0
        for i = 0 to levels.size() - 1
            Level lv = levels.get(i)
            if f_visible(lv)
                bool frs = f_isFresh(lv)
                if lv.price >= close
                    if frs
                        dUp.push(lv.price - close)
                    else
                        uUp.push(lv.price - close)
                else
                    if frs
                        dDn.push(close - lv.price)
                    else
                        uDn.push(close - lv.price)
                if frs
                    if lv.role == 1 and lv.price >= close
                        cntR += 1
                        if na(nearR) or lv.price < nearR
                            nearR := lv.price
                            nearRn := f_name(lv)
                    if lv.role == -1 and lv.price <= close
                        cntS += 1
                        if na(nearS) or lv.price > nearS
                            nearS := lv.price
                            nearSn := f_name(lv)
    dUp.sort()
    dDn.sort()
    uUp.sort()
    uDn.sort()
    float limUp = dUp.size() > maxSide ? dUp.get(maxSide - 1) : 1e18
    float limDn = dDn.size() > maxSide ? dDn.get(maxSide - 1) : 1e18
    float limUpU = -1.0
    float limDnU = -1.0
    if maxSideU > 0
        limUpU := uUp.size() > maxSideU ? uUp.get(maxSideU - 1) : 1e18
        limDnU := uDn.size() > maxSideU ? uDn.get(maxSideU - 1) : 1e18
 
    if levels.size() > 0
        for i = 0 to levels.size() - 1
            Level lv = levels.get(i)
            if f_visible(lv)
                float dist = math.abs(lv.price - close)
                bool fresh = f_isFresh(lv)
                bool inRange = false
                if fresh
                    inRange := lv.price >= close ? dist <= limUp : dist <= limDn
                else
                    inRange := lv.price >= close ? dist <= limUpU : dist <= limDnU
                if inRange
                    color base = lv.role == 1 ? colRes : colSup
                    if lv.kind == 3
                        base := colQml
                    color c = fresh ? base : color.new(base, 45)
                    string stl = fresh ? line.style_solid : line.style_dashed
                    if lv.kind == 2 and fresh
                        stl := line.style_dotted
                    int w = lv.slot + 1
                    int xFrom = lv.t0
                    // Break and retest: old role faded up to the breaking candle, then the new role
                    if showMarks and lv.flips > 0 and not na(lv.tBrk) and lv.kind != 3
                        color oldC = lv.role == 1 ? colSup : colRes
                        drawnLines.push(line.new(lv.t0, lv.price, lv.tBrk, lv.price, xloc = xloc.bar_time, color = color.new(oldC, 65), style = line.style_dotted, width = 1))
                        drawnLabels.push(label.new(lv.tBrk, lv.price, "✕", xloc = xloc.bar_time, style = label.style_none, textcolor = base, size = size.small))
                        xFrom := lv.tBrk
                        if not na(lv.tRet)
                            drawnLabels.push(label.new(lv.tRet, lv.price, "RT", xloc = xloc.bar_time, style = lv.role == 1 ? label.style_label_down : label.style_label_up, color = color.new(base, 75), textcolor = base, size = size.tiny))
                    drawnLines.push(line.new(xFrom, lv.price, xR, lv.price, xloc = xloc.bar_time, color = c, style = stl, width = w))
                    if lqLine != LQ_NONE and not na(lv.tail) and fresh and lv.kind == 1
                        float tp = lqLine == LQ_CE ? lv.price + 0.5 * (lv.tail - lv.price) : lv.tail
                        drawnLines.push(line.new(lv.t0, tp, xR, tp, xloc = xloc.bar_time, color = color.new(base, 60), style = line.style_dotted, width = 1))
                    if showLbl
                        string txt = f_name(lv)
                        if not fresh
                            txt := txt + " ×" + str.tostring(lv.uses)
                        drawnLabels.push(label.new(xR, lv.price, txt, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(base, 100), textcolor = c, size = lblSize))
 
    // Storyline target
    if stlOn and showStl and htfOK and stDir != 0 and not na(stTarget)
        color sc = stDir == 1 ? colSup : colRes
        drawnLines.push(line.new(time, stTarget, xR, stTarget, xloc = xloc.bar_time, color = color.new(sc, 30), style = line.style_dotted, width = 2))
        drawnLabels.push(label.new(time, stTarget, f_t("STL target", "هدف الستوري لاين"), xloc = xloc.bar_time, style = stDir == 1 ? label.style_label_down : label.style_label_up, color = color.new(sc, 80), textcolor = sc, size = size.tiny))
 
    // Fibonacci on the last swing leg (1 = leg origin, 0 = leg end)
    if fibOn and not na(fHiP) and not na(fLoP)
        array<float> fl = array.from(0.0, 0.109, 0.127, 0.145, 0.214, 0.232, 0.25, 0.618, 0.636, 0.654, 0.786, 0.804, 0.822, 1.0)
        if fibPreset == FIB_SNIPER
            fl := array.from(0.0, 1.0, -0.21, -0.255, -0.29, 1.47, 1.55, 2.56, 2.64)
        else if fibPreset == FIB_PULL
            fl := array.from(0.0, 1.0, 1.618, 1.68, 1.78, 2.618, 2.68, 2.77)
        bool upLeg = fHiT > fLoT
        float p1 = upLeg ? fLoP : fHiP
        float p0 = upLeg ? fHiP : fLoP
        int tA = upLeg ? fLoT : fHiT
        int tB = upLeg ? fHiT : fLoT
        color fc = color.new(color.orange, 25)
        drawnLines.push(line.new(tA, p1, tB, p0, xloc = xloc.bar_time, color = color.new(color.orange, 55), style = line.style_dashed, width = 1))
        for i = 0 to fl.size() - 1
            float lvl = fl.get(i)
            float py = p0 + lvl * (p1 - p0)
            drawnLines.push(line.new(tB, py, xR, py, xloc = xloc.bar_time, color = fc, style = line.style_dotted, width = 1))
            drawnLabels.push(label.new(tB, py, str.tostring(lvl), xloc = xloc.bar_time, style = label.style_label_right, color = color.new(color.orange, 100), textcolor = fc, size = size.tiny))
 
    // Dashboard
    if showDash
        string pos = switch dashPosIn
            "Top left" => position.top_left
            "Bottom right" => position.bottom_right
            "Bottom left" => position.bottom_left
            => position.top_right
        if na(dash)
            dash := table.new(pos, 2, 8, bgcolor = color.new(#131722, 15), border_color = color.new(color.gray, 70), border_width = 1, frame_color = color.new(color.gray, 60), frame_width = 1)
        table.clear(dash, 0, 0, 1, 7)
        color tc = color.new(color.white, 10)
        color mc = color.new(color.gray, 0)
        string tfs = f_tfStr(timeframe.period)
        if htfOK
            tfs := tfs + " › " + lbl1
        if three
            tfs := tfs + " › " + lbl2
        int r = 0
        table.cell(dash, 0, r, "MSNR Pro", text_color = color.white, text_size = size.small, text_halign = text.align_left)
        table.cell(dash, 1, r, tfs, text_color = mc, text_size = size.small, text_halign = text.align_right)
        r += 1
        string stTxt = f_t("Neutral", "محايد")
        color stCol = mc
        if not htfOK or not stlOn
            stTxt := "—"
        else if stDir == 1
            stTxt := f_t("Bullish ▲", "صاعد ▲")
            stCol := colSup
        else if stDir == -1
            stTxt := f_t("Bearish ▼", "هابط ▼")
            stCol := colRes
        else if pendDir != 0
            stTxt := pendDir == 1 ? f_t("Waiting breakout ▲", "بانتظار الاختراق ▲") : f_t("Waiting breakout ▼", "بانتظار الاختراق ▼")
        table.cell(dash, 0, r, f_t("Storyline", "الستوري لاين"), text_color = tc, text_size = size.small, text_halign = text.align_left)
        table.cell(dash, 1, r, stTxt, text_color = stCol, text_size = size.small, text_halign = text.align_right)
        r += 1
        if three
            // Middle layer: direction of its latest body break, and whether it agrees with the storyline
            string mTxt = "—"
            color mCol = mc
            if H1.lastBrk == 1
                mTxt := f_t("Broke up ▲", "كسر للأعلى ▲")
                mCol := colSup
            else if H1.lastBrk == -1
                mTxt := f_t("Broke down ▼", "كسر للأسفل ▼")
                mCol := colRes
            table.cell(dash, 0, r, f_t("Validation layer", "طبقة التأكيد"), text_color = tc, text_size = size.small, text_halign = text.align_left)
            table.cell(dash, 1, r, mTxt, text_color = mCol, text_size = size.small, text_halign = text.align_right)
            r += 1
            string aTxt = "—"
            color aCol = mc
            if stDir != 0 and H1.lastBrk != 0
                if stDir == H1.lastBrk
                    aTxt := f_t("Aligned ✓", "متوافقة ✓")
                    aCol := stDir == 1 ? colSup : colRes
                else
                    aTxt := f_t("Not aligned ✕", "غير متوافقة ✕")
            table.cell(dash, 0, r, f_t("Layers", "الطبقات"), text_color = tc, text_size = size.small, text_halign = text.align_left)
            table.cell(dash, 1, r, aTxt, text_color = aCol, text_size = size.small, text_halign = text.align_right)
            r += 1
        table.cell(dash, 0, r, f_t("Fresh resistance", "مقاومة طازجة"), text_color = tc, text_size = size.small, text_halign = text.align_left)
        table.cell(dash, 1, r, na(nearR) ? "—" : nearRn + "  " + str.tostring(nearR, format.mintick), text_color = colRes, text_size = size.small, text_halign = text.align_right)
        r += 1
        table.cell(dash, 0, r, f_t("Fresh support", "دعم طازج"), text_color = tc, text_size = size.small, text_halign = text.align_left)
        table.cell(dash, 1, r, na(nearS) ? "—" : nearSn + "  " + str.tostring(nearS, format.mintick), text_color = colSup, text_size = size.small, text_halign = text.align_right)
        r += 1
        table.cell(dash, 0, r, f_t("Fresh above / below", "طازج فوق / تحت"), text_color = tc, text_size = size.small, text_halign = text.align_left)
        table.cell(dash, 1, r, str.tostring(cntR) + " / " + str.tostring(cntS), text_color = mc, text_size = size.small, text_halign = text.align_right)
 
// ───────────────────────────── Alerts (levels only) ─────────────────────────────
alertcondition(evNew, "New level formed", "MSNR Pro: a new level formed on {{ticker}} {{interval}}")
alertcondition(evFreshTouch, "Fresh level touched", "MSNR Pro: a fresh level was touched on {{ticker}} {{interval}} at {{close}}")
alertcondition(evBreak, "Level broken (RBS / SBR)", "MSNR Pro: a level was broken by a body close and flipped on {{ticker}} {{interval}}")

← 返回列表