Structure Adaptive Trend [AlgoNorth]

AlgoNorth · study · 556 行 · 点赞 1,142 · TradingView 原页

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

Pine Script

// This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
// https://creativecommons.org/licenses/by-nc-sa/4.0/
// © AlgoNorth
//@version=6
indicator("Structure Adaptive Trend [AlgoNorth]", overlay = true, max_labels_count = 500, max_lines_count = 500)
 
// ───────────────────────── Inputs ─────────────────────────
grpS      = "Structure"
swingLen  = input.int(3, "Swing length", minval = 1, maxval = 20, group = grpS, tooltip = "Bars on each side that confirm a swing high or low. A swing is only used once it is confirmed, so nothing changes after a bar has closed.")
 
grpL      = "Trend line"
fastLen   = input.int(6, "Fast length (after a BOS)", minval = 2, group = grpL, tooltip = "The speed the line heads toward after a BOS or CHoCH closes. The line eases toward it rather than jumping, so it only gets part of the way before easing back: with the defaults it reaches about half the slow length. More bars to ease back lets it get closer.")
slowLen   = input.int(30, "Slow length (settled)", minval = 3, group = grpL, tooltip = "The length the line eases back to while price pulls back or ranges. Always kept above the fast length.")
easeBars  = input.int(8, "Bars to ease back", minval = 1, group = grpL, tooltip = "How many bars the line's target speed takes to slow from the fast length back to the slow length.")
smoothLen = input.int(5, "Line smoothing", minval = 1, group = grpL, tooltip = "Extra smoothing on the drawn line so it stays one clean curve. 1 = off.")
 
grpV       = "Visuals"
bullCol    = input.color(#00E676, "Bullish", inline = "c", group = grpV)
bearCol    = input.color(#FF1744, "Bearish", inline = "c", group = grpV)
crossCol   = input.color(#787B86, "Crossed (no CHoCH)", group = grpV, tooltip = "Used when price is across the line (tether columns) or across the CHoCH level on the open bar (panel state) without a CHoCH. Also the line colour before the first break, and the colour of the first swings on the chart, which have nothing before them to compare against.")
showTether = input.bool(true, "Tether columns", group = grpV, tooltip = "A column from each candle to the trend line, brightest at the candle and fading to the line.")
colourBars = input.bool(false, "Colour candles by side", group = grpV)
 
grpM    = "Swing map"
showMap = input.bool(true, "Swing map (right of the last bar)", group = grpM, tooltip = "The last swings drawn at their real prices to the right of the live bar, labelled HH / HL / LH / LL. The first node starts with ••• to show the structure carries on to the left, off the map. A dashed leg runs from the last confirmed swing to the live price, ending where the next swing will appear once it confirms. The shaded zone runs between the two levels the structure is watching: a close through the trend-side level extends the trend (next BOS), a close through the other flips structure (CHoCH).")
mapLen  = input.int(3, "Structure scale (swing length)", minval = 1, maxval = 50, group = grpM, tooltip = "Bars on each side that confirm a swing for the map. Match the line's swing length and the map shows the same structure as the line. Raise it to track bigger swings and the larger trend: the map, its zone and the panel then run on that bigger structure, while the line, tether and CHoCH tags stay on the line's swing length.")
mapN    = input.int(8, "Swings shown", minval = 4, maxval = 12, group = grpM)
mapGap  = input.int(8, "Gap from the last bar (bars)", minval = 2, maxval = 100, group = grpM)
mapStep = input.int(4, "Space between swings (bars)", minval = 2, maxval = 20, group = grpM)
 
grpT     = "BOS / CHoCH"
showCh   = input.bool(true, "CHoCH tags on the chart", group = grpT, tooltip = "The most recent 120 are kept. Older ones are removed whole, so no ring, stem or tag is ever left on its own.")
tagGap   = input.float(0.5, "CHoCH tag gap past the candles (ATR)", minval = 0.2, step = 0.1, group = grpT, tooltip = "The tag clears the CHoCH candle and the candles next to it by this much, and always sits past the start of the stem.")
wickGap  = input.float(0.15, "Gap between wick and stem (ATR)", minval = 0.0, step = 0.05, group = grpT, tooltip = "Small space between the wick tip and the start of the dotted stem, so the two can't be confused.")
showFail = input.bool(true, "Failed-break levels", group = grpT, tooltip = "A BOS fails when price closes back through the broken level soon after. Marked with a dashed level, drawn on the close of the bar that reclaimed it. The most recent 100 are kept.")
failBars = input.int(3, "Failed if reclaimed within (bars)", minval = 1, maxval = 20, group = grpT, tooltip = "Bars after the BOS close in which a close back through the broken level counts as a failed break. The panel's BOS held rate uses the same window.")
 
grpP      = "Panel"
showPanel = input.bool(true, "Structure panel", group = grpP, tooltip = "Reads the live price against the map structure's two levels and shows how this chart's past structure has behaved. All counts are taken on closed bars only, on the map's structure scale.")
panelPos  = input.string("Top right", "Position", options = ["Top right", "Middle right", "Bottom right", "Top left", "Bottom left"], group = grpP)
panelTxt  = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = grpP)
 
slowLenSafe = math.max(slowLen, fastLen + 1)
tagOff      = math.max(tagGap, wickGap + 0.1)   // the tag always sits past the start of the stem
fg          = chart.fg_color
noCol       = color.new(color.black, 100)
 
// Drawing budget inside the 500 label / 500 line limits. A CHoCH tag uses 3 labels + 1 line, a failed break
// 1 label + 1 line, the swing map up to 18 labels + 26 lines. Old marks are removed whole, never in parts.
keepCh   = 120
keepFail = 100
 
// ───────────────────────── Structure (the line's scale) ─────────────────────────
atr = ta.atr(14)
ph  = ta.pivothigh(high, swingLen, swingLen)
pl  = ta.pivotlow(low, swingLen, swingLen)
 
var float lhP    = na
var int   lhBar  = na
var bool  lhUsed = true
var float llP    = na
var int   llBar  = na
var bool  llUsed = true
var int   dir    = 0
var float ln     = na
var float tl     = na
var int   since  = 1000
var float lenNow = slowLenSafe
 
// Last BOS, watched for a failed break
var bool  bOpen = false
var int   bDir  = 0
var int   bBar  = na
var int   bPiv  = na
var float bLvl  = na
 
int evt     = 0   // 1 BOS up · -1 BOS down · 2 CHoCH up · -2 CHoCH down
int failEvt = 0   // 1 failed bullish BOS · -1 failed bearish BOS
 
// All state changes happen on bar close only, so nothing repaints
if barstate.isconfirmed
    if not na(ph)
        lhP    := ph
        lhBar  := bar_index - swingLen
        lhUsed := false
    if not na(pl)
        llP    := pl
        llBar  := bar_index - swingLen
        llUsed := false
 
    // Failed break: the last BOS level is closed back through within failBars bars
    if bOpen and bar_index - bBar <= failBars
        if (bDir == 1 and close < bLvl) or (bDir == -1 and close > bLvl)
            failEvt := bDir
            bOpen   := false
    else if bOpen
        bOpen := false
 
    breakUp = not lhUsed and close > lhP
    breakDn = not llUsed and close < llP
 
    if dir == 1
        if breakDn
            llUsed := true
            dir    := -1
            evt    := -2
        else if breakUp
            lhUsed := true
            evt    := 1
    else if dir == -1
        if breakUp
            lhUsed := true
            dir    := 1
            evt    := 2
        else if breakDn
            llUsed := true
            evt    := -1
    else
        if breakUp
            lhUsed := true
            dir    := 1
            evt    := 1
        else if breakDn
            llUsed := true
            dir    := -1
            evt    := -1
 
    if math.abs(evt) == 1
        bOpen := true
        bDir  := evt
        bBar  := bar_index
        bLvl  := evt == 1 ? lhP : llP
        bPiv  := evt == 1 ? lhBar : llBar
 
    since  := evt != 0 ? 0 : since + 1
    // Target speed jumps on a BOS/CHoCH; the line's actual speed closes 35% of the gap to it each bar, so no kinks
    target  = fastLen + (slowLenSafe - fastLen) * math.min(1.0, float(since) / easeBars)
    lenNow := lenNow + 0.35 * (target - lenNow)
    ln     := na(ln) ? close : ln + 2.0 / (lenNow + 1.0) * (close - ln)
    tl     := na(tl) ? ln : tl + 2.0 / (smoothLen + 1.0) * (ln - tl)
 
sideCol = dir > 0 ? bullCol : dir < 0 ? bearCol : crossCol
 
// ───────────────────────── Map structure (its own scale) ─────────────────────────
// The same break rules as the line's structure, run on swings of the map's own length, so the map can
// track bigger swings than the line. With the two lengths equal it is the same structure as the line.
// Every confirmed swing is kept in order and labelled against the previous swing of the same kind.
var array<float>  swP = array.new<float>()
var array<bool>   swH = array.new<bool>()
var array<string> swT = array.new<string>()
 
addSwing(float p, bool isHi) =>
    string t = isHi ? "H" : "L"
    n = swP.size()
    if n > 0
        for j = n - 1 to 0
            if swH.get(j) == isHi
                // a swing only counts as a new extreme when it goes past the last one: equal highs read LH, equal lows HL
                t := isHi ? (p > swP.get(j) ? "HH" : "LH") : (p < swP.get(j) ? "LL" : "HL")
                break
    swP.push(p)
    swH.push(isHi)
    swT.push(t)
    if swP.size() > 40
        swP.shift()
        swH.shift()
        swT.shift()
 
mph = ta.pivothigh(high, mapLen, mapLen)
mpl = ta.pivotlow(low, mapLen, mapLen)
 
var float mHiP    = na
var bool  mHiUsed = true
var float mLoP    = na
var bool  mLoUsed = true
var int   mDir    = 0
 
// Panel stats, counted on closed bars only
var int   mbOpen   = 0      // side of the BOS being watched for a failed break, 0 = none
var int   mbBar    = na
var float mbLvl    = na
var int   bosN     = 0      // BOS resolved (held or failed)
var int   bosHeld  = 0
var bool  chPend   = false  // last CHoCH still waiting for its first BOS
var int   chN      = 0
var int   chHit    = 0
var int   curBos   = 0      // BOS in the current trend
var int   trBar    = na     // bar the current trend began
var bool  trFromCh = false  // current trend began with a CHoCH (the first trend on the chart did not)
var float sumBos   = 0.0
var float sumBars  = 0.0
var int   nTr      = 0
 
int mEvt = 0   // 1 BOS up · -1 BOS down · 2 CHoCH up · -2 CHoCH down · 3 / -3 first break on the chart
 
if barstate.isconfirmed
    if not na(mph)
        mHiP    := mph
        mHiUsed := false
        addSwing(mph, true)
    if not na(mpl)
        mLoP    := mpl
        mLoUsed := false
        addSwing(mpl, false)
 
    // The watched BOS fails on a close back through its level within failBars bars, otherwise it held
    if mbOpen != 0
        if (mbOpen == 1 and close < mbLvl) or (mbOpen == -1 and close > mbLvl)
            bosN   += 1
            mbOpen := 0
        else if bar_index - mbBar >= failBars
            bosN    += 1
            bosHeld += 1
            mbOpen  := 0
 
    mUp = not mHiUsed and close > mHiP
    mDn = not mLoUsed and close < mLoP
    if mDir == 1
        if mDn
            mLoUsed := true
            mDir    := -1
            mEvt    := -2
        else if mUp
            mHiUsed := true
            mEvt    := 1
    else if mDir == -1
        if mUp
            mHiUsed := true
            mDir    := 1
            mEvt    := 2
        else if mDn
            mLoUsed := true
            mEvt    := -1
    else
        if mUp
            mHiUsed := true
            mDir    := 1
            mEvt    := 3
        else if mDn
            mLoUsed := true
            mDir    := -1
            mEvt    := -3
 
    if math.abs(mEvt) == 1
        // a new BOS before the last one's window ran out: the last one held
        if mbOpen != 0
            bosN    += 1
            bosHeld += 1
        mbOpen := mEvt
        mbBar  := bar_index
        mbLvl  := mEvt == 1 ? mHiP : mLoP
        curBos += 1
        if chPend
            chN    += 1
            chHit  += 1
            chPend := false
    else if math.abs(mEvt) == 2
        if chPend
            chN += 1
        chPend := true
        if trFromCh
            sumBos  += curBos
            sumBars += bar_index - trBar
            nTr     += 1
        curBos   := 0
        trBar    := bar_index
        trFromCh := true
    else if math.abs(mEvt) == 3
        curBos := 0
        trBar  := bar_index
 
mapCol = mDir > 0 ? bullCol : mDir < 0 ? bearCol : crossCol
zTop   = mHiUsed ? na : mHiP    // live high level: next BOS in an uptrend, CHoCH in a downtrend
zBot   = mLoUsed ? na : mLoP    // live low level: CHoCH in an uptrend, next BOS in a downtrend
 
// ───────────────────────── Tether columns ─────────────────────────
// One column per candle from the body edge nearest the line to the line. Seven nested layers start at
// the candle and reach part-way to the line, so the column is brightest at the candle and fades to the line.
// Columns are drawn on both sides of the line; grey when price is across the line without a CHoCH.
// A body that straddles the line has no edge, so nothing is drawn for it.
bodyHi  = math.max(open, close)
bodyLo  = math.min(open, close)
above   = bodyLo > tl
below   = bodyHi < tl
edge    = above ? bodyLo : below ? bodyHi : na
onSide  = (dir > 0 and above) or (dir < 0 and below)
tCol    = showTether and dir != 0 ? color.new(onSide ? sideCol : crossCol, 84) : noCol
 
layerTo(float f) =>
    edge + (tl - edge) * f
 
l1 = layerTo(1.00)
l2 = layerTo(0.86)
l3 = layerTo(0.72)
l4 = layerTo(0.58)
l5 = layerTo(0.44)
l6 = layerTo(0.30)
l7 = layerTo(0.16)
 
plotcandle(edge, math.max(edge, l1), math.min(edge, l1), l1, "Tether 1", tCol, wickcolor = noCol, bordercolor = noCol, display = display.pane)
plotcandle(edge, math.max(edge, l2), math.min(edge, l2), l2, "Tether 2", tCol, wickcolor = noCol, bordercolor = noCol, display = display.pane)
plotcandle(edge, math.max(edge, l3), math.min(edge, l3), l3, "Tether 3", tCol, wickcolor = noCol, bordercolor = noCol, display = display.pane)
plotcandle(edge, math.max(edge, l4), math.min(edge, l4), l4, "Tether 4", tCol, wickcolor = noCol, bordercolor = noCol, display = display.pane)
plotcandle(edge, math.max(edge, l5), math.min(edge, l5), l5, "Tether 5", tCol, wickcolor = noCol, bordercolor = noCol, display = display.pane)
plotcandle(edge, math.max(edge, l6), math.min(edge, l6), l6, "Tether 6", tCol, wickcolor = noCol, bordercolor = noCol, display = display.pane)
plotcandle(edge, math.max(edge, l7), math.min(edge, l7), l7, "Tether 7", tCol, wickcolor = noCol, bordercolor = noCol, display = display.pane)
 
// ───────────────────────── Trend line ─────────────────────────
plot(tl, "Glow", color.new(sideCol, 86), 10, display = display.pane)
plot(tl, "Line", sideCol, 4)
plot(tl, "Core", color.new(fg, 35), 1, display = display.pane)
 
// ───────────────────────── Candles ─────────────────────────
barcolor(colourBars and dir != 0 ? sideCol : na)
 
// ───────────────────────── Failed-break level ─────────────────────────
// Dashed level at the broken price, from just before the break to the bar that closed back through it
var array<line>  fbLns  = array.new<line>()
var array<label> fbLbls = array.new<label>()
 
if showFail and failEvt != 0
    fc = failEvt == 1 ? bullCol : bearCol
    x0 = math.max(bPiv, bBar - 10)
    fbLns.push(line.new(x0, bLvl, bar_index, bLvl, xloc = xloc.bar_index, color = fc, width = 1, style = line.style_dashed))
    fbLbls.push(label.new(x0, bLvl, "failed break", xloc = xloc.bar_index, style = label.style_label_right, color = noCol, textcolor = fc, size = size.small))
    if fbLns.size() > keepFail
        fbLns.shift().delete()
        fbLbls.shift().delete()
 
// ───────────────────────── CHoCH tags ─────────────────────────
// Ring + dot on the line. The dotted stem is 1px (same as a wick) so it sits on the candle's centre
// line, starts a small gap past the wick tip, and runs out to the tag's pointer. The tag clears the
// CHoCH candle and the 2 candles either side.
lo3 = ta.lowest(low, 3)
hi3 = ta.highest(high, 3)
 
var label        chTag  = na
var line         chStem = na
var int          chBar  = na
var bool         chUp   = false
var float        chExt  = na
var float        chAtr  = na
var array<label> chLbls = array.new<label>()
var array<line>  chLns  = array.new<line>()
 
if showCh and math.abs(evt) == 2
    chUp  := evt > 0
    chBar := bar_index
    chExt := chUp ? lo3 : hi3
    chAtr := atr
    yTag   = chUp ? chExt - tagOff * chAtr : chExt + tagOff * chAtr
    yStart = chUp ? low - wickGap * chAtr : high + wickGap * chAtr
    chLbls.push(label.new(bar_index, tl, "◯", style = label.style_none, textcolor = color.new(fg, 55), size = size.large))
    chLbls.push(label.new(bar_index, tl, "●", style = label.style_none, textcolor = fg, size = size.normal))
    chStem := line.new(bar_index, yStart, bar_index, yTag, xloc = xloc.bar_index, color = fg, width = 1, style = line.style_dotted)
    chTag  := label.new(bar_index, yTag, chUp ? "▲ CHoCH" : "▼ CHoCH", xloc = xloc.bar_index, color = fg, textcolor = chart.bg_color, style = chUp ? label.style_label_up : label.style_label_down, size = size.small, text_formatting = text.format_bold)
    chLns.push(chStem)
    chLbls.push(chTag)
    // keep the most recent CHoCH tags; an older one goes as a whole (ring, dot, stem and tag together)
    if chLns.size() > keepCh
        chLns.shift().delete()
        for j = 1 to 3
            chLbls.shift().delete()
else if showCh and barstate.isconfirmed and not na(chBar) and bar_index - chBar <= 2
    // The 2 candles after the CHoCH can still reach the tag, so push it further out if they do
    chExt := chUp ? math.min(chExt, low) : math.max(chExt, high)
    yTag   = chUp ? chExt - tagOff * chAtr : chExt + tagOff * chAtr
    chStem.set_y2(yTag)
    chTag.set_y(yTag)
 
// ───────────────────────── Swing map · hold zone ─────────────────────────
// Drawn to the right of the live bar, redrawn on the last bar only, from the map structure's confirmed swings.
// Each swing sits at its real price; time between swings is squeezed to an even spacing. The first node is
// prefixed with ••• to show the structure carries on to the left, off the map.
// The zone spans the two live levels of the map structure: the trend-side level (close through it = next BOS) and
// the opposite level (close through it = CHoCH), each with its price tagged at the right end. A dotted line carries
// the live price across to a NOW tag whose pointer sits exactly on it, and a dashed forming leg runs from the last
// confirmed swing to the live price, ending where the next node will appear. Both are live and redrawn every tick.
var array<line>  mLines = array.new<line>()
var array<label> mLbls  = array.new<label>()
var box          mBox   = na
 
swCol(string t) =>
    t == "HH" or t == "HL" ? bullCol : t == "LH" or t == "LL" ? bearCol : crossCol
 
px(float v) =>
    str.tostring(v, format.mintick)
 
if barstate.islast
    for l in mLines
        l.delete()
    mLines.clear()
    for lb in mLbls
        lb.delete()
    mLbls.clear()
    mBox.delete()
    total = swP.size()
    if showMap and total >= 2 and mDir != 0
        cnt = math.min(mapN, total)
        s0  = total - cnt
        x0  = bar_index + mapGap
        xR  = x0 + cnt * mapStep
        int xHi = na     // x of the last swing high on the map
        int xLo = na     // x of the last swing low on the map
        // legs (glow + core), coloured by the swing they lead into
        for k = 0 to cnt - 1
            i = s0 + k
            p = swP.get(i)
            x = x0 + k * mapStep
            if swH.get(i)
                xHi := x
            else
                xLo := x
            if k > 0
                c = swCol(swT.get(i))
                mLines.push(line.new(x - mapStep, swP.get(i - 1), x, p, xloc = xloc.bar_index, color = color.new(c, 85), width = 7))
                mLines.push(line.new(x - mapStep, swP.get(i - 1), x, p, xloc = xloc.bar_index, color = c, width = 2))
        // hold zone between the two live levels, starting at the node of the level it marks
        int zL = na
        if not na(zTop) and not na(xHi)
            zL := xHi - 1
        if not na(zBot) and not na(xLo)
            zL := na(zL) ? xLo - 1 : math.min(zL, xLo - 1)
        zL := nz(zL, x0 - 1)
        zMid = int((zL + xR) / 2)
        if not na(zTop) and not na(zBot)
            mBox := box.new(zL, zTop, xR, zBot, xloc = xloc.bar_index, bgcolor = color.new(mapCol, 90), border_color = noCol, border_width = 0)
        if not na(zTop)
            mLines.push(line.new(zL, zTop, xR, zTop, xloc = xloc.bar_index, color = bullCol, width = 1, style = line.style_dashed))
            mLbls.push(label.new(zMid, zTop + 0.45 * atr, mDir == 1 ? "close above → next BOS" : "close above → CHoCH", xloc = xloc.bar_index, style = label.style_none, textcolor = bullCol, size = size.normal, text_formatting = text.format_bold))
            mLbls.push(label.new(xR + 1, zTop, px(zTop), xloc = xloc.bar_index, style = label.style_label_left, color = bullCol, textcolor = color.black, size = size.normal, text_formatting = text.format_bold))
        if not na(zBot)
            mLines.push(line.new(zL, zBot, xR, zBot, xloc = xloc.bar_index, color = bearCol, width = 1, style = line.style_dashed))
            mLbls.push(label.new(zMid, zBot - 0.45 * atr, mDir == 1 ? "close below → CHoCH" : "close below → next BOS", xloc = xloc.bar_index, style = label.style_none, textcolor = bearCol, size = size.normal, text_formatting = text.format_bold))
            mLbls.push(label.new(xR + 1, zBot, px(zBot), xloc = xloc.bar_index, style = label.style_label_left, color = bearCol, textcolor = color.black, size = size.normal, text_formatting = text.format_bold))
        // live price carried across to the map, ending in a NOW tag whose pointer sits exactly on it
        mLines.push(line.new(bar_index, close, xR + 1, close, xloc = xloc.bar_index, color = color.new(fg, 60), width = 1, style = line.style_dotted))
        mLbls.push(label.new(xR + 1, close, "NOW", xloc = xloc.bar_index, style = label.style_label_left, color = fg, textcolor = chart.bg_color, size = size.small, text_formatting = text.format_bold))
        // forming leg: dashed, from the last confirmed swing to the live price, ending where the next node will appear
        mLines.push(line.new(xR - mapStep, swP.get(total - 1), xR, close, xloc = xloc.bar_index, color = fg, width = 2, style = line.style_dashed))
        // small dot where the forming leg meets the NOW line (a shape, not a text glyph, so it sits exactly on the price)
        mLbls.push(label.new(xR, close, "", xloc = xloc.bar_index, style = label.style_circle, color = fg, size = 5))
        // swing nodes (drawn after the legs so they sit on top); the first carries ••• when there is structure off the map
        for k = 0 to cnt - 1
            i = s0 + k
            t = swT.get(i)
            mLbls.push(label.new(x0 + k * mapStep, swP.get(i), k == 0 and s0 > 0 ? "••• " + t : t, xloc = xloc.bar_index, style = label.style_label_center, color = swCol(t), textcolor = color.black, size = size.small, text_formatting = text.format_bold))
 
// ───────────────────────── Structure panel ─────────────────────────
// State: where the live price sits against the map structure's two levels, and what would change that read.
// Levels: each live level with its distance from the live price in ATR(14).
// Stats: how this chart's past structure behaved on the map's scale, counted on closed bars only.
pSize = panelTxt == "Tiny" ? size.tiny : panelTxt == "Normal" ? size.normal : size.small
vSize = panelTxt == "Tiny" ? size.normal : panelTxt == "Normal" ? size.huge : size.large
pPos  = panelPos == "Top left" ? position.top_left : panelPos == "Bottom left" ? position.bottom_left : panelPos == "Middle right" ? position.middle_right : panelPos == "Bottom right" ? position.bottom_right : position.top_right
 
var table panel = showPanel ? table.new(pPos, 2, 11, bgcolor = chart.bg_color, frame_color = color.new(fg, 70), frame_width = 1, border_color = color.new(fg, 85), border_width = 1) : na
 
// merged rows: header, settings, state, watch, last bar
if barstate.isfirst and showPanel
    for r = 0 to 10
        table.cell(panel, 0, r, "")
        table.cell(panel, 1, r, "")
    for r in array.from(0, 1, 2, 3, 10)
        table.merge_cells(panel, 0, r, 1, r)
 
// name of a level for the state: its label when it has one, otherwise a plain name
lvlName(string t, bool isHi) =>
    na(t) or t == "H" or t == "L" ? (isHi ? "LAST HIGH" : "LAST LOW") : t
 
// label of the most recent swing high or low
lastTag(bool isHi) =>
    string t = na
    n = swP.size()
    if n > 0
        for j = n - 1 to 0
            if swH.get(j) == isHi
                t := swT.get(j)
                break
    t
 
// a level with its distance from the live price in ATR
lvlTxt(float v) =>
    px(v) + " · " + str.tostring(math.abs(close - v) / atr, "#.##") + " ATR " + (v > close ? "above" : "below")
 
pct(int hit, int n) =>
    n > 0 ? str.tostring(100.0 * hit / n, "#") + "% · n " + str.tostring(n) : "not enough history"
 
rowL(int r, string t, string tip) =>
    table.cell(panel, 0, r, t, text_color = fg, text_halign = text.align_left, text_size = pSize, tooltip = tip)
 
rowR(int r, string t, color c) =>
    table.cell(panel, 1, r, t, text_color = c, text_halign = text.align_right, text_size = pSize)
 
if barstate.islast and showPanel
    string verdict = "NO STRUCTURE YET"
    string subTxt  = "waiting for the first close through a swing"
    color  vCol    = crossCol
    string chTxt   = "—"
    string bosTxt  = "—"
    color  chCol   = fg
    color  bosCol  = fg
    if mDir != 0
        up        = mDir == 1
        holdLine  = up ? zBot : zTop     // CHoCH level
        bosLine   = up ? zTop : zBot     // next BOS level
        noHold    = na(holdLine)
        extending = na(bosLine)
        atRisk    = not noHold and (up ? close < holdLine : close > holdLine)
        pastBos   = not extending and (up ? close > bosLine : close < bosLine)
        trendSw   = up ? "high" : "low"     // the swing that sets the next BOS level
        holdSw    = up ? "low" : "high"     // the swing that sets the CHoCH level
        sideTxt   = up ? "above" : "below"
        gapTxt    = noHold ? "" : px(math.abs(close - holdLine))
        vCol := mapCol
        if atRisk
            verdict := (up ? "BELOW THE " : "ABOVE THE ") + lvlName(lastTag(not up), not up) + " · a close here = CHoCH"
            subTxt  := "a candle close " + (up ? "below " : "above ") + px(holdLine) + " confirms the CHoCH"
            vCol    := crossCol
        else if extending
            verdict := up ? "NEW HIGH FORMING" : "NEW LOW FORMING"
            subTxt  := "the next swing " + trendSw + " sets the BOS level · shown once the " + trendSw + " is confirmed" + (noHold ? "" : " · " + gapTxt + " " + sideTxt + " the CHoCH level")
        else if pastBos
            verdict := (up ? "ABOVE THE " : "BELOW THE ") + lvlName(lastTag(up), up) + " · a close here = BOS"
            subTxt  := "a candle close " + sideTxt + " " + px(bosLine) + " confirms the BOS"
        else if noHold
            verdict := up ? "SWING LOW FORMING" : "SWING HIGH FORMING"
            subTxt  := "the next swing " + holdSw + " sets the CHoCH level · shown once the " + holdSw + " is confirmed"
        else
            verdict := "HOLDING " + (up ? "ABOVE" : "BELOW") + " THE " + lvlName(lastTag(not up), not up)
            subTxt  := "trend is safe while price closes " + sideTxt + " the CHoCH level · " + gapTxt + " " + sideTxt + " it"
        chTxt  := noHold ? "no swing " + holdSw + " yet" : lvlTxt(holdLine)
        chCol  := up ? bearCol : bullCol
        bosTxt := extending ? "set by the next swing " + trendSw : lvlTxt(bosLine)
        bosCol := up ? bullCol : bearCol
 
    trTxt  = na(trBar) ? "—" : str.tostring(curBos) + " BOS · " + str.tostring(bar_index - trBar) + " bars"
    avgTxt = nTr > 0 ? str.tostring(sumBos / nTr, "#.#") + " BOS · " + str.tostring(sumBars / nTr, "#") + " bars · n " + str.tostring(nTr) : "not enough history"
 
    table.cell(panel, 0, 0, "Structure Adaptive Trend [AlgoNorth] · swing map", bgcolor = mapCol, text_color = color.black, text_halign = text.align_left, text_size = pSize, text_formatting = text.format_bold)
    table.cell(panel, 0, 1, "line swing " + str.tostring(swingLen) + " · map scale " + str.tostring(mapLen) + " · fast " + str.tostring(fastLen) + " → slow " + str.tostring(slowLenSafe) + " · failed ≤ " + str.tostring(failBars) + " bars", text_color = fg, text_halign = text.align_left, text_size = pSize)
    table.cell(panel, 0, 2, verdict, text_color = vCol, text_halign = text.align_left, text_size = vSize, text_formatting = text.format_bold)
    table.cell(panel, 0, 3, subTxt, text_color = fg, text_halign = text.align_left, text_size = pSize)
    rowL(4, "CHoCH level", "The level a candle close must break to flip structure, with its distance from the live price in ATR(14).")
    rowR(4, chTxt, chCol)
    rowL(5, "BOS level", "The level a candle close must break for the next BOS, with its distance from the live price in ATR(14). After a BOS there is no level until the next swing confirms.")
    rowR(5, bosTxt, bosCol)
    rowL(6, "This trend", "BOS made so far in the current trend, and bars since it began.")
    rowR(6, trTxt, fg)
    rowL(7, "Avg trend", "Average BOS count and length in bars of past trends on this chart, CHoCH to CHoCH. n = trends counted.")
    rowR(7, avgTxt, fg)
    rowL(8, "BOS held", "Share of past BOS not closed back through their broken level within the failed-break window. n = BOS counted.")
    rowR(8, pct(bosHeld, bosN), fg)
    rowL(9, "CHoCH → BOS", "Share of past CHoCHs that went on to make at least one BOS in the new direction before the next CHoCH. n = CHoCHs counted.")
    rowR(9, pct(chHit, chN), fg)
    table.cell(panel, 0, 10, "Last bar " + str.format_time(time, "yyyy-MM-dd HH:mm", syminfo.timezone) + " exchange time · " + str.tostring(bar_index + 1) + " bars", text_color = fg, text_halign = text.align_left, text_size = pSize)

← 返回列表