Market Structure Lab [Indicatr]

Indicatr · study · 741 行 · 点赞 17 · TradingView 原页

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

Pine Script

//@version=6
// ════════════════════════════════════════════════════════════════════════════════════
// Market Structure Lab [Indicatr]
// Market structure drawn by fixed rules, plus a lab dashboard that measures how that
// structure actually behaved on the chart you are looking at.
// One dashboard view per lesson of the "Market Structure by Rule" series.
// Educational measuring tool. We measure, we don't claim. No signals, no entries,
// no stops, no targets.
// © Indicatr · indicator.trading · Mozilla Public License 2.0
// ════════════════════════════════════════════════════════════════════════════════════
indicator("Market Structure Lab [Indicatr]", "MSL", overlay = true, max_bars_back = 1000, max_boxes_count = 100, max_lines_count = 200, max_labels_count = 500, behind_chart = false)
 
 
// ════════════════════════════════════════════════════════════════════════════════════
// 1  INPUTS
// ════════════════════════════════════════════════════════════════════════════════════
 
G_VIEW = "Lesson"
i_view = input.string("Overview", "Dashboard view", options = ["Overview", "1 · Swings", "2 · BOS vs CHoCH", "3 · Protected level", "4 · Liquidity sweeps", "5 · Fair value gaps", "6 · Higher timeframe", "7 · Your rule set"], group = G_VIEW, tooltip = "Overview shows one key figure per topic.\n\nEach lesson view shows the figures of one part of the series \"Market Structure by Rule\" and draws only what that lesson needs on the chart.")
 
G_ST = "1 · Structure"
i_swing   = input.int(10, "Swing length", minval = 2, maxval = 100, group = G_ST, tooltip = "A swing high is a high with this many lower highs on each side (a swing low the other way round). It is confirmed this many bars after it formed and is never moved afterwards.\n\nSmall values follow the internal structure, large values the main structure.")
i_confirm = input.string("Close", "Break confirmed by", options = ["Close", "Wick"], group = G_ST, tooltip = "Close: a candle has to close beyond the swing level to break it. A wick beyond the level that closes back inside is marked as a liquidity sweep.\n\nWick: trading through the level is enough.\n\nThe dashboard always measures both, so you can compare them on your chart.")
i_htf     = input.timeframe("", "Higher timeframe (Chart = auto)", group = G_ST, tooltip = "Used in lesson 6 and in your rule set. \"Chart\" = automatic: up to 15m → 1h, up to 1h → 4h, up to 4h → 1D, 1D → 1W, above → 1M.\n\nThe higher timeframe structure is taken from the last closed higher timeframe bar, so it never repaints.")
 
G_VIS = "2 · Chart"
i_showSw   = input.bool(true, "Swing labels (HH, HL, LH, LL)", group = G_VIS)
i_showBrk  = input.bool(true, "BOS / CHoCH lines and labels", group = G_VIS)
i_brkKeep  = input.int(10, "Breaks kept on chart", minval = 1, maxval = 50, group = G_VIS)
i_showProt = input.bool(true, "Protected level with structure band", group = G_VIS, tooltip = "In an up structure the last confirmed swing low, in a down structure the last confirmed swing high. The structure is wrong once price closes beyond it.")
i_showLiq  = input.bool(true, "Open swing levels", group = G_VIS, tooltip = "The current unbroken swing high and swing low, extended to the right. The next break or sweep happens at one of them.")
i_showSwp  = input.bool(true, "Liquidity sweeps", group = G_VIS)
i_showFvg  = input.bool(true, "Fair value gaps", group = G_VIS)
i_fvgKeep  = input.int(3, "Open gaps shown per side", minval = 1, maxval = 10, group = G_VIS)
i_barCol   = input.bool(false, "Colour candles by structure", group = G_VIS)
i_colBull  = input.color(#089981, "Up", inline = "cols", group = G_VIS)
i_colBear  = input.color(#f23645, "Down", inline = "cols", group = G_VIS)
i_colSwp   = input.color(#ff9800, "Sweep", inline = "cols", group = G_VIS)
 
G_LAB = "3 · Lab rules"
i_failBars = input.int(5, "Back through the level within (bars)", minval = 1, maxval = 50, group = G_LAB, tooltip = "Lesson 2. A break counts as failed when a candle closes back on the other side of the broken level within this many bars, the break candle included.")
i_wideAtr  = input.float(3.0, "Wide protected level from (× ATR)", minval = 0.5, maxval = 20.0, step = 0.5, group = G_LAB, tooltip = "Lesson 3. Breaks whose protected level is at least this far from the close are counted as wide.")
i_swpAtr   = input.float(1.0, "Sweep reversal distance (× ATR)", minval = 0.25, maxval = 5.0, step = 0.25, group = G_LAB, tooltip = "Lesson 4. A sweep counts as reversed when price moves this far back from the swept level before it trades beyond the sweep wick.")
i_swpBars  = input.int(30, "Sweep horizon (bars)", minval = 5, maxval = 300, group = G_LAB)
i_fvgMin   = input.float(0.25, "Minimum gap size (× ATR)", minval = 0.0, maxval = 3.0, step = 0.05, group = G_LAB, tooltip = "Lesson 5.")
i_fvgBars  = input.int(50, "Gap horizon (bars)", minval = 5, maxval = 500, group = G_LAB, tooltip = "A gap is checked for this many bars after it formed. Touched: price trades back into the gap. Filled: price trades through the whole gap.")
i_evBars   = input.int(5000, "Measured bars", minval = 200, group = G_LAB, tooltip = "Only events that started inside the last this many bars are counted.")
 
G_RULE = "4 · Your rule set (lesson 7)"
i_rType = input.string("BOS + CHoCH", "Breaks that count", options = ["BOS + CHoCH", "BOS only", "CHoCH only"], group = G_RULE)
i_rHtf  = input.bool(false, "Only with the higher timeframe structure", group = G_RULE)
i_rMax  = input.float(0.0, "Protected level at most (× ATR, 0 = off)", minval = 0.0, maxval = 20.0, step = 0.5, group = G_RULE, tooltip = "A setup is a break that passes all rules you set here. It is not an entry. The dashboard counts how many breaks pass and what came after them.")
 
G_DB = "5 · Dashboard"
i_dbShow = input.bool(true, "Show dashboard", group = G_DB)
i_theme  = input.string("Auto", "Theme", options = ["Auto", "Light", "Dark"], group = G_DB, tooltip = "Auto follows the chart background.")
i_dbPos  = input.string("Top right", "Position", options = ["Top right", "Top left", "Bottom right", "Bottom left", "Middle right", "Middle left"], group = G_DB)
i_dbSize = input.string("Large", "Text size", options = ["Tiny", "Small", "Normal", "Large"], group = G_DB)
 
 
// ════════════════════════════════════════════════════════════════════════════════════
// 2  THEME AND HELPERS
// ════════════════════════════════════════════════════════════════════════════════════
 
float bgLum = (0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color)) / 255.0
bool DARK = i_theme == "Dark" or (i_theme == "Auto" and bgLum < 0.5)
 
color C_BG     = DARK ? #1e1e28 : #ffffff
color C_TOP    = DARK ? #2a2e39 : #131722
color C_TOP2   = DARK ? #252a37 : #f0f3fa
color C_TOPTX2 = DARK ? #e9e9f0 : #131722
color C_SECT   = DARK ? #24243a : #f8f9fd
color C_BORDER = DARK ? #34344a : #e6e8ef
color C_FRAME  = DARK ? #4a4a60 : #d1d4dc
color C_TXT    = DARK ? #e9e9f0 : #131722
color C_DIM    = DARK ? #9a9cab : #787b86
color C_BARC   = DARK ? #5b8cff : #2962ff
color C_BAR0   = DARK ? #3a3a50 : #dde2ea
color C_TOPSUB = DARK ? #9598a1 : #9598a1
color C_WARN   = #ff9800
color C_NONE   = color.new(color.white, 100)
color C_BULL   = i_colBull
color C_BEAR   = i_colBear
 
f_size(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Normal" => size.normal
        "Large"  => size.large
        => size.small
 
f_sizeUp(string s) =>
    switch s
        "Tiny"   => size.small
        "Small"  => size.normal
        => size.large
 
f_sizeDown(string s) =>
    switch s
        "Large"  => size.normal
        "Normal" => size.small
        => size.tiny
 
f_pos(string s) =>
    switch s
        "Top left"     => position.top_left
        "Bottom right" => position.bottom_right
        "Bottom left"  => position.bottom_left
        "Middle right" => position.middle_right
        "Middle left"  => position.middle_left
        => position.top_right
 
f_share(int a, int n) => n > 0 ? 100.0 * a / n : na
f_pctTxt(float p) => na(p) ? "–" : str.tostring(p, "#") + "%"
f_tfTxt(string tf) =>
    int sec = timeframe.in_seconds(tf)
    string s = sec < 3600 ? str.tostring(math.round(sec / 60)) + "m" : sec < 86400 ? str.tostring(math.round(sec / 3600)) + "h" : sec < 604800 ? str.tostring(math.round(sec / 86400)) + "D" : sec < 2419200 ? str.tostring(math.round(sec / 604800)) + "W" : str.tostring(math.round(sec / 2628000)) + "M"
    s
 
int V = switch i_view
    "1 · Swings"           => 1
    "2 · BOS vs CHoCH"     => 2
    "3 · Protected level"  => 3
    "4 · Liquidity sweeps" => 4
    "5 · Fair value gaps"  => 5
    "6 · Higher timeframe" => 6
    "7 · Your rule set"    => 7
    => 0
 
 
// ════════════════════════════════════════════════════════════════════════════════════
// 3  STRUCTURE ENGINE
// ════════════════════════════════════════════════════════════════════════════════════
// A swing high is confirmed `len` bars after it formed. The latest confirmed swing high and
// swing low are the open levels. A close (or wick) beyond one of them is a break: a BOS when it
// goes with the current structure, a CHoCH when it is the first break against it. Each level
// can be broken only once. Nothing is redrawn after the bar closes.
 
f_engine(simple int len, bool wick) =>
    var float opH    = na
    var int   opHBar = na
    var float opL    = na
    var int   opLBar = na
    var float swH    = na
    var float swL    = na
    var int   trend  = 0
    float ph = ta.pivothigh(high, len, len)
    float pl = ta.pivotlow(low, len, len)
    if not na(ph)
        opH    := ph
        opHBar := bar_index - len
        swH    := ph
    if not na(pl)
        opL    := pl
        opLBar := bar_index - len
        swL    := pl
    bool upX = not na(opH) and (wick ? high : close) > opH
    bool dnX = not na(opL) and (wick ? low : close) < opL
    if upX and dnX
        upX := close >= open
        dnX := not upX
    bool  bCh  = false
    float bLvl = na
    int   bBar = na
    if upX
        bCh   := trend != 1
        bLvl  := opH
        bBar  := opHBar
        trend := 1
        opH   := na
    if dnX
        bCh   := trend != -1
        bLvl  := opL
        bBar  := opLBar
        trend := -1
        opL   := na
    [trend, swH, swL, opH, opHBar, opL, opLBar, upX, dnX, bCh, bLvl, bBar, ph, pl]
 
bool WICK  = i_confirm == "Wick"
float atr14 = ta.atr(14)
bool inWin = bar_index >= last_bar_index - i_evBars
 
// Next break after a break: was it in the same direction? Counts only breaks inside the window.
f_stats(bool up, bool dn, bool ch) =>
    var int  pDir   = 0
    var bool pCh    = false
    var bool pIn    = false
    var int  nBrk   = 0
    var int  nBos   = 0
    var int  bosBos = 0
    var int  nCh    = 0
    var int  chBos  = 0
    var int  lBar   = na
    var bool lCh    = false
    var int  lDir   = 0
    if up or dn
        int d = up ? 1 : -1
        if inWin
            nBrk += 1
        if pDir != 0 and pIn
            if pCh
                nCh   += 1
                chBos += d == pDir ? 1 : 0
            else
                nBos   += 1
                bosBos += d == pDir ? 1 : 0
        pDir := d
        pCh  := ch
        pIn  := inWin
        lBar := bar_index
        lCh  := ch
        lDir := d
    [nBrk, nBos, bosBos, nCh, chBos, lBar, lCh, lDir]
 
// main engine (as chosen), close and wick engines for lesson 2, three swing lengths for lesson 1
[trend, swH, swL, opH, opHBar, opL, opLBar, bUp, bDn, bCh, bLvl, bBar, ph, pl] = f_engine(i_swing, WICK)
[cTrend, cSwH, cSwL, cOpH, cOpHBar, cOpL, cOpLBar, cUp, cDn, cCh, cLvl, cBar, cPh, cPl] = f_engine(i_swing, false)
[wTrend, wSwH, wSwL, wOpH, wOpHBar, wOpL, wOpLBar, wUp, wDn, wCh, wLvl, wBar, wPh, wPl] = f_engine(i_swing, true)
[t5, sh5, sl5, oh5, ohb5, ol5, olb5, u5, d5, c5, lv5, bb5, ph5, pl5] = f_engine(5, false)
[t10, sh10, sl10, oh10, ohb10, ol10, olb10, u10, d10, c10, lv10, bb10, ph10, pl10] = f_engine(10, false)
[t20, sh20, sl20, oh20, ohb20, ol20, olb20, u20, d20, c20, lv20, bb20, ph20, pl20] = f_engine(20, false)
 
[mBrk, mBos, mBosBos, mCh, mChBos, mLBar, mLCh, mLDir] = f_stats(bUp, bDn, bCh)
[yBrk, yBos, yBosBos, yCh, yChBos, yLBar, yLCh, yLDir] = f_stats(cUp, cDn, cCh)
[s5Brk, s5Bos, s5BosBos, s5Ch, s5ChBos, s5LBar, s5LCh, s5LDir] = f_stats(u5, d5, c5)
[s10Brk, s10Bos, s10BosBos, s10Ch, s10ChBos, s10LBar, s10LCh, s10LDir] = f_stats(u10, d10, c10)
[s20Brk, s20Bos, s20BosBos, s20Ch, s20ChBos, s20LBar, s20LCh, s20LDir] = f_stats(u20, d20, c20)
 
// higher timeframe structure, taken from the last closed higher timeframe bar
int TF_SEC = timeframe.in_seconds()
string HTF_AUTO = TF_SEC <= 900 ? "60" : TF_SEC <= 3600 ? "240" : TF_SEC <= 14400 ? "D" : TF_SEC <= 86400 ? "W" : "M"
string HTF = i_htf == "" ? HTF_AUTO : i_htf
bool HTF_OK = timeframe.in_seconds(HTF) > TF_SEC
 
f_htfTrend() =>
    [ht, hsh, hsl, hoh, hohb, hol, holb, hu, hd, hc, hlv, hbb, hph, hpl] = f_engine(i_swing, false)
    ht[1]
 
int htfRaw = request.security(syminfo.tickerid, HTF, f_htfTrend(), lookahead = barmerge.lookahead_on)
int htfT = HTF_OK and not na(htfRaw) ? htfRaw : 0
 
 
// ════════════════════════════════════════════════════════════════════════════════════
// 4  LAB: WHAT HAPPENED AFTER EACH EVENT
// ════════════════════════════════════════════════════════════════════════════════════
 
// 4.1  per break of the main engine: protected distance, higher timeframe, your rule set
var int   nDist    = 0
var float sumDist  = 0.0
var int   nWide    = 0
var int   nHtfBrk  = 0     // breaks in the window with a known higher timeframe structure
var int   nWith    = 0
var int   withCont = 0
var int   nAgainst = 0
var int   agCont   = 0
var int   nSetup   = 0     // breaks in the window that pass your rules
var float sumSetupDist = 0.0
var int   nSetupRes = 0
var int   setupCont = 0
var int   pDir2    = 0
var bool  pIn2     = false
var int   pAlign   = 0     // 1 with, -1 against, 0 unknown
var bool  pSetup   = false
 
bool  isSetup = false
float protAtBrk = na
if bUp or bDn
    int d = bUp ? 1 : -1
    // resolve the previous break
    if pDir2 != 0 and pIn2
        bool same = d == pDir2
        if pAlign == 1
            nWith    += 1
            withCont += same ? 1 : 0
        else if pAlign == -1
            nAgainst += 1
            agCont   += same ? 1 : 0
        if pSetup
            nSetupRes += 1
            setupCont += same ? 1 : 0
    // this break
    protAtBrk := bUp ? swL : swH
    float dist = na(protAtBrk) ? na : math.abs(close - protAtBrk) / atr14
    int align = htfT == 0 ? 0 : htfT == d ? 1 : -1
    bool typeOk = i_rType == "BOS + CHoCH" or (i_rType == "BOS only" ? not bCh : bCh)
    bool htfOk  = not i_rHtf or align == 1
    bool distOk = i_rMax == 0 or (not na(dist) and dist <= i_rMax)
    isSetup := typeOk and htfOk and distOk
    if inWin
        if not na(dist)
            nDist   += 1
            sumDist += dist
            nWide   += dist >= i_wideAtr ? 1 : 0
        if align != 0
            nHtfBrk += 1
        if isSetup
            nSetup += 1
            sumSetupDist += na(dist) ? 0.0 : dist
    pDir2  := d
    pIn2   := inWin
    pAlign := align
    pSetup := isSetup
 
// 4.2  failed breaks: close back through the broken level within N bars (close and wick engine)
type Brk
    int   dir
    float lvl
    int   bar
 
var array<Brk> pendC = array.new<Brk>()
var array<Brk> pendW = array.new<Brk>()
var int nFailC = 0
var int failC  = 0
var int nFailW = 0
var int failW  = 0
 
if (cUp or cDn) and inWin
    pendC.push(Brk.new(cUp ? 1 : -1, cLvl, bar_index))
if (wUp or wDn) and inWin
    pendW.push(Brk.new(wUp ? 1 : -1, wLvl, bar_index))
 
if pendC.size() > 0
    for i = pendC.size() - 1 to 0
        Brk bk = pendC.get(i)
        bool back = bk.dir == 1 ? close < bk.lvl : close > bk.lvl
        if back or bar_index - bk.bar >= i_failBars - 1
            nFailC += 1
            failC  += back ? 1 : 0
            pendC.remove(i)
 
if pendW.size() > 0
    for i = pendW.size() - 1 to 0
        Brk bk = pendW.get(i)
        bool back = bk.dir == 1 ? close < bk.lvl : close > bk.lvl
        if back or bar_index - bk.bar >= i_failBars - 1
            nFailW += 1
            failW  += back ? 1 : 0
            pendW.remove(i)
 
// 4.3  liquidity sweeps (close engine): a wick beyond an open swing level that closes back inside
type Swp
    int   dir      // 1 = swept a high, -1 = swept a low
    float lvl
    float ext      // sweep wick extreme
    float dist     // reversal distance in price
    int   bar
    bool  counted
 
var array<Swp> pendS = array.new<Swp>()
var float sweptH = na
var float sweptL = na
var int nSwp   = 0
var int swpRev = 0
var int swpRun = 0
bool swpUp = not na(cOpH) and high > cOpH and close <= cOpH and (na(sweptH) or cOpH != sweptH)
bool swpDn = not na(cOpL) and low < cOpL and close >= cOpL and (na(sweptL) or cOpL != sweptL)
if swpUp
    sweptH := cOpH
    pendS.push(Swp.new(1, cOpH, high, i_swpAtr * atr14, bar_index, inWin))
if swpDn
    sweptL := cOpL
    pendS.push(Swp.new(-1, cOpL, low, i_swpAtr * atr14, bar_index, inWin))
 
if pendS.size() > 0
    for j = pendS.size() - 1 to 0
        Swp s = pendS.get(j)
        bool done = false
        if bar_index > s.bar
            bool ran = s.dir == 1 ? high > s.ext : low < s.ext
            bool rev = s.dir == 1 ? low <= s.lvl - s.dist : high >= s.lvl + s.dist
            if ran
                done := true
                if s.counted
                    nSwp   += 1
                    swpRun += 1
            else if rev
                done := true
                if s.counted
                    nSwp   += 1
                    swpRev += 1
            else if bar_index - s.bar >= i_swpBars
                done := true
                if s.counted
                    nSwp += 1
        if done
            pendS.remove(j)
 
// 4.4  fair value gaps: touched / filled within the horizon
type Gap
    int   dir      // 1 = bullish gap (below price), -1 = bearish gap
    float top
    float bot
    int   bar
    bool  counted
    bool  touched = false
    box   bx
 
bool SHOW_FVG = i_showFvg and (V == 0 or V == 5)
bool SHOW_SWP = i_showSwp and not WICK and (V == 0 or V == 4)
bool SHOW_LIQ = i_showLiq and (V == 0 or V == 4)
 
var array<Gap> gaps = array.new<Gap>()
var int nGap   = 0
var int gapTch = 0
var int gapFil = 0
var int gapBarsSum = 0
 
bool gUp = low > high[2] and low - high[2] >= i_fvgMin * atr14
bool gDn = high < low[2] and low[2] - high >= i_fvgMin * atr14
 
if gaps.size() > 0
    for k = gaps.size() - 1 to 0
        Gap g = gaps.get(k)
        bool filled = g.dir == 1 ? low <= g.bot : high >= g.top
        bool touch  = g.dir == 1 ? low <= g.top : high >= g.bot
        if touch
            g.touched := true
        int age = bar_index - g.bar
        if filled or age >= i_fvgBars
            if g.counted
                nGap   += 1
                gapTch += g.touched ? 1 : 0
                if filled
                    gapFil += 1
                    gapBarsSum += age
            if not na(g.bx)
                g.bx.delete()
            gaps.remove(k)
        else if not na(g.bx)
            g.bx.set_right(bar_index + 5)
            if g.dir == 1 and low < g.bx.get_top()
                g.bx.set_top(math.max(low, g.bot))
            if g.dir == -1 and high > g.bx.get_bottom()
                g.bx.set_bottom(math.min(high, g.top))
 
if gUp or gDn
    float top = gUp ? low : low[2]
    float bot = gUp ? high[2] : high
    int gd = gUp ? 1 : -1
    box b = na
    if SHOW_FVG
        color gc = gd == 1 ? C_BULL : C_BEAR
        b := box.new(bar_index - 2, top, bar_index + 5, bot, border_color = color.new(gc, 78), bgcolor = color.new(gc, 88), border_width = 1, text = "FVG", text_size = size.tiny, text_color = color.new(gc, 45), text_halign = text.align_right, text_valign = text.align_center)
    gaps.push(Gap.new(gd, top, bot, bar_index, inWin, false, b))
    int seen = 0
    for m = gaps.size() - 1 to 0
        Gap g2 = gaps.get(m)
        if g2.dir == gd and not na(g2.bx)
            seen += 1
            if seen > i_fvgKeep
                g2.bx.delete()
                g2.bx := na
 
 
// ════════════════════════════════════════════════════════════════════════════════════
// 5  CHART
// ════════════════════════════════════════════════════════════════════════════════════
 
color C_SWLBL = DARK ? #b2b5be : #5d606b
 
// 5.1  swing labels
var float prevPh = na
var float prevPl = na
if not na(ph)
    if i_showSw
        label.new(bar_index - i_swing, ph, na(prevPh) ? "SH" : ph > prevPh ? "HH" : "LH", color = C_NONE, textcolor = C_SWLBL, style = label.style_label_down, size = size.tiny)
    prevPh := ph
if not na(pl)
    if i_showSw
        label.new(bar_index - i_swing, pl, na(prevPl) ? "SL" : pl > prevPl ? "HL" : "LL", color = C_NONE, textcolor = C_SWLBL, style = label.style_label_up, size = size.tiny)
    prevPl := pl
 
// 5.2  BOS / CHoCH (in lesson 7, breaks that pass your rules carry a check mark)
var array<line>  brkLn = array.new<line>()
var array<label> brkLb = array.new<label>()
if i_showBrk and (bUp or bDn)
    color bc = bUp ? C_BULL : C_BEAR
    string txt = (bCh ? "CHoCH" : "BOS") + (V == 7 and isSetup ? " ✓" : "")
    line ln = line.new(bBar, bLvl, bar_index, bLvl, color = color.new(bc, bCh ? 0 : 25), width = bCh ? 2 : 1, style = bCh ? line.style_solid : line.style_dashed)
    label lb = label.new(int(math.round((bBar + bar_index) / 2)), bLvl, txt, color = bCh ? bc : C_NONE, textcolor = bCh ? color.white : bc, style = bUp ? label.style_label_down : label.style_label_up, size = size.small)
    brkLn.push(ln)
    brkLb.push(lb)
    if brkLn.size() > i_brkKeep
        brkLn.shift().delete()
        brkLb.shift().delete()
 
// 5.3  protected level: glow and a band that fades from the level towards price
float protP = trend == 1 ? swL : trend == -1 ? swH : na
color protC = trend == 1 ? C_BULL : C_BEAR
bool protJump = protP != protP[1] or trend != trend[1]
float protD = i_showProt and not protJump ? protP : na
plot(protD, "Protected level glow wide", color = color.new(protC, 90), linewidth = 14, style = plot.style_linebr, editable = false, display = display.pane)
plot(protD, "Protected level glow", color = color.new(protC, 75), linewidth = 7, style = plot.style_linebr, editable = false, display = display.pane)
pProt = plot(protD, "Protected level", color = protC, linewidth = 2, style = plot.style_linebr, display = display.all - display.price_scale)
float bandEdge = na(protD) ? na : trend == 1 ? math.min(close, protD + 1.5 * atr14) : math.max(close, protD - 1.5 * atr14)
pEdge = plot(bandEdge, "Band edge", color = na, display = display.none, editable = false)
fill(pProt, pEdge, protD, bandEdge, color.new(protC, 70), color.new(protC, 100), title = "Structure band")
var label protLb = na
if barstate.islast and i_showProt
    protLb.delete()
    if not na(protP)
        protLb := label.new(bar_index + 3, protP, trend == 1 ? "Protected low" : "Protected high", color = protC, textcolor = color.white, style = label.style_label_left, size = size.small)
 
// 5.4  open swing levels
var line  liqH  = na
var line  liqL  = na
var label liqHL = na
var label liqLL = na
color C_LIQ = DARK ? #787b86 : #9598a1
if barstate.islast
    liqH.delete()
    liqL.delete()
    liqHL.delete()
    liqLL.delete()
    if SHOW_LIQ
        if not na(opH)
            liqH := line.new(opHBar, opH, bar_index + 8, opH, color = C_LIQ, style = line.style_dotted, width = 1)
            if na(protP) or opH != protP or not i_showProt
                liqHL := label.new(bar_index + 8, opH, "Open swing high", color = C_NONE, textcolor = C_LIQ, style = label.style_label_left, size = size.small)
        if not na(opL)
            liqL := line.new(opLBar, opL, bar_index + 8, opL, color = C_LIQ, style = line.style_dotted, width = 1)
            if na(protP) or opL != protP or not i_showProt
                liqLL := label.new(bar_index + 8, opL, "Open swing low", color = C_NONE, textcolor = C_LIQ, style = label.style_label_left, size = size.small)
 
// 5.5  sweeps (close confirmation only)
var array<label> swpLb = array.new<label>()
if SHOW_SWP
    if swpUp
        swpLb.push(label.new(bar_index, high, "✕ sweep", color = C_NONE, textcolor = i_colSwp, style = label.style_label_down, size = size.small, tooltip = "Liquidity sweep: the wick traded beyond the open swing high and the candle closed back below it."))
    if swpDn
        swpLb.push(label.new(bar_index, low, "✕ sweep", color = C_NONE, textcolor = i_colSwp, style = label.style_label_up, size = size.small, tooltip = "Liquidity sweep: the wick traded beyond the open swing low and the candle closed back above it."))
    while swpLb.size() > 20
        swpLb.shift().delete()
 
// 5.6  candles and higher timeframe background (lesson 6)
barcolor(i_barCol ? (trend == 1 ? C_BULL : trend == -1 ? C_BEAR : na) : na)
bgcolor(V == 6 and htfT != 0 ? color.new(htfT == 1 ? C_BULL : C_BEAR, 94) : na, title = "Higher timeframe structure (lesson 6)")
 
 
// ════════════════════════════════════════════════════════════════════════════════════
// 6  DASHBOARD
// ════════════════════════════════════════════════════════════════════════════════════
// 23 columns: label (0), 20 score boxes (1-20), value (21), n (22)
 
var table db = table.new(f_pos(i_dbPos), 23, 40, bgcolor = C_BG, frame_color = C_FRAME, frame_width = 1, border_color = C_BG, border_width = 2)
 
// one text over the columns c0..c1
f_span(table t, int c0, int c1, int r, string txt, color tc, color bg, string sz, string ha, bool bold) =>
    t.cell(c0, r, txt, text_color = tc, bgcolor = bg, text_size = sz, text_halign = ha, text_formatting = bold ? text.format_bold : text.format_none)
    if c1 > c0
        for c = c0 + 1 to c1
            t.cell(c, r, "", bgcolor = bg)
        t.merge_cells(c0, r, c1, r)
 
f_full(table t, int r, string txt, color tc, color bg, string sz, bool bold) =>
    f_span(t, 0, 22, r, txt, tc, bg, sz, text.align_left, bold)
    r + 1
 
f_sect(table t, int r, string txt, bool showN, string szS) =>
    f_span(t, 0, 21, r, txt, C_DIM, C_SECT, szS, text.align_left, true)
    t.cell(22, r, showN ? "n" : "", text_color = C_DIM, bgcolor = C_SECT, text_size = szS, text_halign = text.align_right)
    r + 1
 
// score box colour: red → orange → green from box 1 to box 20
f_boxCol(int i) =>
    switch i
        1 => #f23645
        2 => #f34341
        3 => #f4513d
        4 => #f55f3a
        5 => #f76d37
        6 => #f87a33
        7 => #fa882f
        8 => #fc952b
        9 => #fea128
        10 => #fcad28
        11 => #f5b72a
        12 => #e9be2f
        13 => #d6c036
        14 => #c0c13c
        15 => #a4be43
        16 => #88ba4b
        17 => #68b458
        18 => #48ae65
        19 => #28a373
        => #089981
 
// a measured share: label, a 10 segment bar, the share and the number of cases
f_pRow(table t, int r, string lbl, float p, int n, string sz, string szS) =>
    t.cell(0, r, lbl, bgcolor = C_BG, text_color = C_TXT, text_size = sz, text_halign = text.align_left)
    int k = na(p) ? 0 : int(math.round(p / 5.0))
    for i = 1 to 20
        t.cell(i, r, "", bgcolor = i <= k ? f_boxCol(i) : C_BAR0, width = 0.38)
    t.cell(21, r, f_pctTxt(p), bgcolor = C_BG, text_color = C_TXT, text_size = sz, text_halign = text.align_right, text_formatting = text.format_bold)
    t.cell(22, r, str.tostring(n), bgcolor = C_BG, text_color = n < 20 ? C_WARN : C_DIM, text_size = szS, text_halign = text.align_right)
    r + 1
 
// a plain value
f_vRow(table t, int r, string lbl, string val, color vc, string sz) =>
    t.cell(0, r, lbl, bgcolor = C_BG, text_color = C_TXT, text_size = sz, text_halign = text.align_left)
    f_span(t, 1, 21, r, val, vc, C_BG, sz, text.align_right, true)
    t.cell(22, r, "", bgcolor = C_BG)
    r + 1
 
f_brkTxt(int lBar, bool lCh, int lDir) =>
    na(lBar) ? "–" : (lCh ? "CHoCH " : "BOS ") + (lDir == 1 ? "▲ " : "▼ ") + str.tostring(bar_index - lBar) + " bars ago"
 
// lesson 1: one row per swing length
f_swRow(table t, int r, string lbl, int nBrk, int nBos, int bb, int nCh, int cb, int lBar, bool lCh, int lDir, bool mine, string sz, string szS) =>
    t.cell(0, r, lbl, bgcolor = C_BG, text_color = C_TXT, text_size = sz, text_halign = text.align_left, text_formatting = mine ? text.format_bold : text.format_none)
    f_span(t, 1, 8, r, str.tostring(nBrk), C_TXT, C_BG, sz, text.align_right, false)
    f_span(t, 9, 20, r, f_pctTxt(f_share(bb, nBos)) + "  ·  " + f_pctTxt(f_share(cb, nCh)), C_TXT, C_BG, sz, text.align_right, false)
    f_span(t, 21, 22, r, na(lBar) ? "–" : (lCh ? "CHoCH " : "BOS ") + (lDir == 1 ? "▲ " : "▼ ") + str.tostring(bar_index - lBar), lDir == 1 ? C_BULL : lDir == -1 ? C_BEAR : C_DIM, C_BG, sz, text.align_right, true)
    r + 1
 
if barstate.islast and i_dbShow
    table.clear(db, 0, 0, 22, 39)
    sz  = f_size(i_dbSize)
    szS = f_sizeDown(i_dbSize)
    szL = f_sizeUp(i_dbSize)
    int r = 0
 
    // header
    f_span(db, 0, 20, r, "Market Structure Lab", color.white, C_TOP, szL, text.align_left, true)
    f_span(db, 21, 22, r, syminfo.ticker + " · " + f_tfTxt(timeframe.period), C_TOPSUB, C_TOP, sz, text.align_right, true)
    r += 1
    r := f_full(db, r, "We measure. We don't claim.", C_TOPSUB, C_TOP, szS, false)
 
    string ttl = switch V
        1 => "Lesson 1 · Swings"
        2 => "Lesson 2 · BOS vs CHoCH"
        3 => "Lesson 3 · Protected level"
        4 => "Lesson 4 · Liquidity sweeps"
        5 => "Lesson 5 · Fair value gaps"
        6 => "Lesson 6 · Higher timeframe"
        7 => "Lesson 7 · Your rule set"
        => "Overview"
    string q = switch V
        1 => "How many breaks does each swing length see on this chart?"
        2 => "What came after a break? Does a close hold better than a wick?"
        3 => "How far away is the level that proves the structure wrong?"
        4 => "After a wick through a swing level, what came first?"
        5 => "How often were gaps touched and filled?"
        6 => "Did breaks with the higher timeframe follow through more often?"
        7 => "How many breaks pass your rules, and what came after them?"
        => "One figure per lesson. Pick a lesson view in the settings."
    r := f_full(db, r, ttl, C_TOPTX2, C_TOP2, sz, true)
    r := f_full(db, r, q, C_DIM, C_TOP2, szS, false)
 
    // now (all views)
    string stTxt = trend == 1 ? "Up" : trend == -1 ? "Down" : "Not set yet"
    color  stCol = trend == 1 ? C_BULL : trend == -1 ? C_BEAR : C_DIM
    r := f_sect(db, r, "NOW", false, szS)
    r := f_vRow(db, r, "Structure", stTxt, stCol, sz)
    r := f_vRow(db, r, "Last break", f_brkTxt(mLBar, mLCh, mLDir), mLDir == 1 ? C_BULL : mLDir == -1 ? C_BEAR : C_DIM, sz)
    if not na(protP)
        r := f_vRow(db, r, trend == 1 ? "Protected low" : "Protected high", str.tostring(math.abs(close - protP) / atr14, "#.0") + " ATR away", C_TXT, sz)
    if V == 0 or V == 6 or V == 7
        string hTxt = not HTF_OK ? "pick a higher timeframe" : htfT == 1 ? "Up" : htfT == -1 ? "Down" : "Not set yet"
        r := f_vRow(db, r, "Higher timeframe (" + f_tfTxt(HTF) + ")", hTxt, htfT == 1 ? C_BULL : htfT == -1 ? C_BEAR : C_DIM, sz)
 
    float pBosBos = f_share(mBosBos, mBos)
    float pChBos  = f_share(mChBos, mCh)
    float pCont   = f_share(mBosBos + mChBos, mBos + mCh)
 
    if V == 0
        r := f_sect(db, r, "ONE FIGURE PER LESSON", true, szS)
        r := f_vRow(db, r, "1 · Breaks with swing " + str.tostring(i_swing), str.tostring(mBrk), C_TXT, sz)
        r := f_pRow(db, r, "2 · BOS followed by another BOS", pBosBos, mBos, sz, szS)
        r := f_pRow(db, r, "2 · Close breaks back through", f_share(failC, nFailC), nFailC, sz, szS)
        r := f_pRow(db, r, "3 · Protected level ≥ " + str.tostring(i_wideAtr, "#.#") + " ATR away", f_share(nWide, nDist), nDist, sz, szS)
        r := f_pRow(db, r, "4 · Sweeps that moved back first", f_share(swpRev, nSwp), nSwp, sz, szS)
        r := f_pRow(db, r, "5 · Gaps filled within " + str.tostring(i_fvgBars) + " bars", f_share(gapFil, nGap), nGap, sz, szS)
        r := f_pRow(db, r, "6 · With HTF, followed through", f_share(withCont, nWith), nWith, sz, szS)
        r := f_pRow(db, r, "7 · Your setups, followed through", f_share(setupCont, nSetupRes), nSetupRes, sz, szS)
 
    if V == 1
        db.cell(0, r, "SWING", text_color = C_DIM, bgcolor = C_SECT, text_size = szS, text_halign = text.align_left, text_formatting = text.format_bold)
        f_span(db, 1, 8, r, "BREAKS", C_DIM, C_SECT, szS, text.align_right, true)
        f_span(db, 9, 20, r, "BOS→BOS  ·  CHoCH→BOS", C_DIM, C_SECT, szS, text.align_right, true)
        f_span(db, 21, 22, r, "LAST BREAK · BARS AGO", C_DIM, C_SECT, szS, text.align_right, true)
        r += 1
        r := f_swRow(db, r, "5", s5Brk, s5Bos, s5BosBos, s5Ch, s5ChBos, s5LBar, s5LCh, s5LDir, i_swing == 5, sz, szS)
        r := f_swRow(db, r, "10", s10Brk, s10Bos, s10BosBos, s10Ch, s10ChBos, s10LBar, s10LCh, s10LDir, i_swing == 10, sz, szS)
        r := f_swRow(db, r, "20", s20Brk, s20Bos, s20BosBos, s20Ch, s20ChBos, s20LBar, s20LCh, s20LDir, i_swing == 20, sz, szS)
        if i_swing != 5 and i_swing != 10 and i_swing != 20
            r := f_swRow(db, r, str.tostring(i_swing) + " (yours)", yBrk, yBos, yBosBos, yCh, yChBos, yLBar, yLCh, yLDir, true, sz, szS)
        r := f_full(db, r, "All rows confirm breaks on the close. Same candles, different definition.", C_DIM, C_BG, szS, false)
 
    if V == 2
        r := f_sect(db, r, "WHAT CAME AFTER A BREAK", true, szS)
        r := f_pRow(db, r, "BOS followed by another BOS", pBosBos, mBos, sz, szS)
        r := f_pRow(db, r, "CHoCH confirmed by a BOS", pChBos, mCh, sz, szS)
        r := f_sect(db, r, "BACK THROUGH THE LEVEL WITHIN " + str.tostring(i_failBars) + " BARS", true, szS)
        r := f_pRow(db, r, "Breaks on the close", f_share(failC, nFailC), nFailC, sz, szS)
        r := f_pRow(db, r, "Breaks on the wick", f_share(failW, nFailW), nFailW, sz, szS)
        r := f_full(db, r, "Switch \"Break confirmed by\" to see both versions on the chart.", C_DIM, C_BG, szS, false)
 
    if V == 3
        r := f_sect(db, r, "AT EACH BREAK", true, szS)
        r := f_vRow(db, r, "Average distance to the protected level", nDist > 0 ? str.tostring(sumDist / nDist, "#.0") + " ATR" : "–", C_TXT, sz)
        r := f_pRow(db, r, "At least " + str.tostring(i_wideAtr, "#.#") + " ATR away", f_share(nWide, nDist), nDist, sz, szS)
        r := f_sect(db, r, "AFTERWARDS", true, szS)
        r := f_pRow(db, r, "Next break in the same direction", pCont, mBos + mCh, sz, szS)
        r := f_full(db, r, "The distance is what a stop beyond the protected level would have needed.", C_DIM, C_BG, szS, false)
 
    if V == 4
        r := f_sect(db, r, "AFTER A SWEEP, WHAT CAME FIRST", true, szS)
        r := f_pRow(db, r, "Moved " + str.tostring(i_swpAtr, "#.##") + " ATR back", f_share(swpRev, nSwp), nSwp, sz, szS)
        r := f_pRow(db, r, "Traded beyond the sweep wick", f_share(swpRun, nSwp), nSwp, sz, szS)
        if nSwp - swpRev - swpRun > 0
            r := f_pRow(db, r, "Neither within " + str.tostring(i_swpBars) + " bars", f_share(nSwp - swpRev - swpRun, nSwp), nSwp, sz, szS)
        if WICK
            r := f_full(db, r, "Sweeps are drawn with close confirmation only. The figures always use close.", C_WARN, C_BG, szS, false)
 
    if V == 5
        r := f_sect(db, r, "GAPS ≥ " + str.tostring(i_fvgMin, "#.##") + " ATR, WITHIN " + str.tostring(i_fvgBars) + " BARS", true, szS)
        r := f_pRow(db, r, "Touched", f_share(gapTch, nGap), nGap, sz, szS)
        r := f_pRow(db, r, "Filled completely", f_share(gapFil, nGap), nGap, sz, szS)
        r := f_vRow(db, r, "Average bars until filled", gapFil > 0 ? str.tostring(gapBarsSum / gapFil, "#") : "–", C_TXT, sz)
 
    if V == 6
        r := f_sect(db, r, "NEXT BREAK IN THE SAME DIRECTION", true, szS)
        r := f_pRow(db, r, "Breaks with the " + f_tfTxt(HTF) + " structure", f_share(withCont, nWith), nWith, sz, szS)
        r := f_pRow(db, r, "Breaks against the " + f_tfTxt(HTF) + " structure", f_share(agCont, nAgainst), nAgainst, sz, szS)
        r := f_full(db, r, not HTF_OK ? "Choose a higher timeframe than the chart in the settings." : "Background: " + f_tfTxt(HTF) + " structure from the last closed " + f_tfTxt(HTF) + " bar.", not HTF_OK ? C_WARN : C_DIM, C_BG, szS, false)
 
    if V == 7
        string rules = i_rType + (i_rHtf ? " · with " + f_tfTxt(HTF) : "") + (i_rMax > 0 ? " · protected ≤ " + str.tostring(i_rMax, "#.#") + " ATR" : "")
        r := f_sect(db, r, "YOUR RULES", false, szS)
        r := f_full(db, r, "Swing " + str.tostring(i_swing) + " · " + str.lower(i_confirm) + " · " + rules, C_TXT, C_BG, sz, true)
        r := f_sect(db, r, "MEASURED", true, szS)
        r := f_pRow(db, r, "Breaks that pass your rules", f_share(nSetup, mBrk), mBrk, sz, szS)
        r := f_pRow(db, r, "Then a break in the same direction", f_share(setupCont, nSetupRes), nSetupRes, sz, szS)
        r := f_pRow(db, r, "All breaks, for comparison", pCont, mBos + mCh, sz, szS)
        r := f_vRow(db, r, "Average distance to protected level", nSetup > 0 ? str.tostring(sumSetupDist / nSetup, "#.0") + " ATR" : "–", C_TXT, sz)
        r := f_full(db, r, "A setup is a break that passes your rules (✓ on the chart). It is not an entry.", C_DIM, C_BG, szS, false)
 
    // footer
    r := f_full(db, r, "Swing " + str.tostring(i_swing) + " · " + str.lower(i_confirm) + " · last " + str.tostring(math.min(i_evBars, last_bar_index + 1)) + " bars · n in orange: fewer than 20 cases", C_DIM, C_SECT, szS, false)
    r := f_full(db, r, "Past behaviour on this chart. Not a forecast, not a signal.", C_DIM, C_SECT, szS, false)

← 返回列表