MSS / Automated Projections / SwingHL

strades55 · study · 655 行 · 点赞 43 · TradingView 原页

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

Pine Script

//@version=6
// ============================================================================
//  SHANE — MSS / AUTOMATED PROJECTIONS / SWING H-L                [indicator]
// ----------------------------------------------------------------------------
//  Standalone extraction of three subsystems from the "QT Shane [AMD-X]"
//  strategy: (1) swing pivot dots, (2) Market Structure Shift detection with
//  labels, (3) the trailing Standard-Deviation projection engine.
//
//  HOW IT WORKS
//    1. Swing pivots are marked with dots (ta.pivothigh / ta.pivotlow).
//    2. An MSS fires on the first CLOSE that flips structure against the
//       prevailing direction (reversal / CHoCH only — continuation breaks
//       update state silently and are not labelled).
//    3. On each MSS an SD projection is anchored: the 1.0 leg is the origin
//       swing of the move, the 0.0 anchor is the MSS impulse close. The 0.0
//       anchor TRAILS with each successive same-direction candle close and the
//       whole level set re-prices with it. It LOCKS the moment the first
//       opposing candle prints.
//
//  PROJECTION MODES
//    Standard : keeps the last N *effective draws* on the chart (default 3)
//               plus the live one, so recent context stays visible.
//    Manual   : deletes the prior projection on every new MSS, so exactly ONE
//               projection is ever on screen — clean hand-trading view.
//
//  MULTI-TF DIRECTION  (added in v3)
//    The exact same state machine is re-run, DRAW-FREE, inside
//    request.security() for three configurable timeframes (default 4H / 1H /
//    15m). Those calls return STATE ONLY — nothing is plotted off-chart — and
//    the info panel reports, per timeframe, which way that timeframe's CURRENT
//    SD projection points and whether its 0.0 anchor is still trailing or has
//    locked. A fourth row reports the chart timeframe itself, and an alignment
//    row tallies how many of the higher timeframes agree with chart structure.
//
//    Direction == structure here by construction: a projection is only ever
//    re-anchored on a REVERSAL MSS, so the projection direction flips if and
//    only if the structural direction flips.
//
//  POSITION SIZING  (added in v4)
//    A stop level (default 0.9) is drawn as a dashed line on every projection.
//    When the projection LOCKS (levels are final) the 0.1, 0.25 and 0.5 entry
//    labels are stamped with the number of contracts of the chart's product
//    that risk a fixed $ amount (default $250) between that entry and the stop:
//        contracts = risk$ / ( |entry − stop| × syminfo.pointvalue )
//    Point value comes from the symbol itself (MNQ = $2/pt, NQ = $20/pt,
//    MES = $5/pt, ES = $50/pt …), so the same settings work on any contract.
//    If even one contract exceeds the risk, the label shows 0 and the cost of
//    a single contract so you can decide for yourself.
//
//  v5: level labels one size bigger (adjustable), labels sit 10 bars past the
//      current bar instead of 60, and a 0.5 entry is sized alongside 0.1/0.25.
//
//  Visual only — no orders, no alerts-to-broker, no sweep/confluence engine.
// ============================================================================
indicator("Shane - MSS / Automated Projections / SwingHL",
     shorttitle="Shane MSS/Proj/SwingHL", overlay=true,
     max_lines_count=500, max_labels_count=500, max_boxes_count=500)
 
// ============================================================================
//  INPUTS
// ============================================================================
// ---- PROJECTION MODE --------------------------------------------------------
gMD = "▸ PROJECTION MODE"
projMode = input.string("Standard (last 3 draws)", "Mode",
     options=["Standard (last 3 draws)", "Manual (current only)"], group=gMD,
     tooltip="Standard = keep the last N completed projections on the chart (default 3) in addition to the live one.\nManual = only the CURRENT projection is ever drawn; the prior one is deleted the moment a new MSS fires.")
histKeep = input.int(3, "Standard: previous draws to keep", minval=1, maxval=10, group=gMD,
     tooltip="Only used in Standard mode. 3 = the three previous effective draws stay visible behind the live projection.")
 
// ---- SWING HIGH / LOW -------------------------------------------------------
gSW = "▸ SWING HIGH / LOW"
swLen   = input.int(3, "Swing pivot strength (bars each side)", minval=1, maxval=50, group=gSW,
     tooltip="Same pivot the MSS is measured from. Higher = only larger swings; lower = more sensitive.")
showDots= input.bool(true, "Show swing dots", group=gSW)
cDotHi  = input.color(color.green, "Swing-high dot", inline="dc", group=gSW)
cDotLo  = input.color(color.red,   "Swing-low dot",  inline="dc", group=gSW)
dotSize = input.int(3, "Dot size", minval=1, maxval=6, group=gSW)
 
// ---- MSS (candle closure required) -----------------------------------------
gMS = "▸ MARKET STRUCTURE SHIFT (MSS)"
showMSS  = input.bool(true, "Show MSS lines/labels", group=gMS)
mssKeep  = input.int(6, "Keep last N MSS drawings", minval=1, maxval=40, group=gMS)
mssLblSz = input.string("Small", "MSS label size", options=["Tiny","Small","Normal","Large"], group=gMS)
cUp      = input.color(#00C853, "Bullish MSS", inline="mc", group=gMS)
cDn      = input.color(#FF5252, "Bearish MSS", inline="mc", group=gMS)
 
// ---- PROJECTION SETTINGS ----------------------------------------------------
gPR = "▸ SD PROJECTION"
showProj     = input.bool(true, "Draw SD projection on each MSS", group=gPR)
projRight    = input.int(10, "Extend right / label offset (bars past current bar)", minval=1, maxval=400, group=gPR,
     tooltip="How far past the current bar the live projection's lines run and where its price labels sit. Lower = labels closer to price.")
extendActive = input.bool(true, "Keep the CURRENT projection extending with price", group=gPR,
     tooltip="ON = the live projection's right edge trails the current bar (+ the extend value above) until it is replaced. Retired projections keep the width they had when they were superseded.")
projLbls     = input.bool(true, "Show projection level labels", group=gPR)
projLblSz    = input.string("Normal", "Level label size", options=["Tiny","Small","Normal","Large"], group=gPR)
projBox      = input.bool(true, "Shade 0.25–0.75 entry range", group=gPR)
dimHistory   = input.bool(true, "Dim retired projections (Standard mode)", group=gPR,
     tooltip="Fades the colour of a projection once a new MSS supersedes it, so the live draw stands out.")
histTransp   = input.int(55, "…dim amount (0–90)", minval=0, maxval=90, group=gPR)
 
gPC = "▸ SD PROJECTION · COLOURS"
cSDblue   = input.color(#42A5F5, "0.25 / 0.75  (entry)",  group=gPC)
cSDorange = input.color(#FF9800, "0.1  (Entry 1)",        group=gPC)
cSDcyan   = input.color(#26C6DA, "-0.5  (breakeven)",     group=gPC)
cSDltgrn  = input.color(#A5D6A7, "0.5 / -2 / -2.5",       group=gPC)
cSDgreen  = input.color(#00C853, "-3.5 / -4",             group=gPC)
cSDtan    = input.color(#F5D6A0, "-1 / -1.5",             group=gPC)
cSDgray   = input.color(#B0BEC5, "0 / -1.25",             group=gPC)
 
// ---- POSITION SIZING --------------------------------------------------------
gSZ = "▸ POSITION SIZING"
sizeOn    = input.bool(true, "Show contract size on entry labels", group=gSZ,
     tooltip="Appends the number of contracts of the chart's product that risk the $ amount below between the entry level and the stop level. Point value is read from the symbol (MNQ = $2/pt, NQ = $20/pt, etc.).")
riskUSD   = input.float(250, "Risk per trade ($)", minval=1, step=25, group=gSZ)
stopLvl   = input.float(0.9, "Stop level", minval=0.3, maxval=2.0, step=0.05, group=gSZ,
     tooltip="Projection level used as the stop for sizing. 0.9 = 90% of the way back toward the 1.0 origin swing.")
showStop  = input.bool(true, "Draw the stop level on the projection", group=gSZ)
cStop     = input.color(#FF1744, "Stop level colour", group=gSZ)
sizeE1    = input.bool(true, "Size 0.1",  inline="se", group=gSZ)
sizeE2    = input.bool(true, "Size 0.25", inline="se", group=gSZ)
sizeE3    = input.bool(true, "Size 0.5",  inline="se", group=gSZ)
sizeRound = input.string("Down (never exceed risk)", "Rounding",
     options=["Down (never exceed risk)", "Nearest"], group=gSZ,
     tooltip="Down = the size never risks more than the $ amount (can be 0 on wide stops).\nNearest = rounds to the closest whole contract, so actual risk can be above or below the $ amount. The label always shows the real $ risk at the size shown.")
sizeLive  = input.bool(false, "Also show while the anchor is still trailing", group=gSZ,
     tooltip="OFF = sizes appear only once the projection locks and the levels are final.\nON = sizes are shown immediately and update as the 0.0 anchor trails.")
 
// ---- INFO PANEL -------------------------------------------------------------
gDB = "▸ INFO PANEL"
showDash = input.bool(true, "Show info panel", group=gDB)
dbPos    = input.string("Top Right", "Position", options=["Top Right","Top Left","Bottom Right","Bottom Left"], group=gDB)
 
// ---- MULTI-TF DIRECTION -----------------------------------------------------
gTF = "▸ MULTI-TF DIRECTION"
showMTF     = input.bool(true,  "Show multi-timeframe direction block", group=gTF,
     tooltip="Adds one row per timeframe to the info panel showing which way that timeframe's CURRENT SD projection points. State only — nothing from these timeframes is ever drawn on the chart.")
mtfA        = input.timeframe("240", "Timeframe 1", group=gTF)
mtfB        = input.timeframe("60",  "Timeframe 2", group=gTF)
mtfC        = input.timeframe("15",  "Timeframe 3", group=gTF)
mtfChart    = input.bool(true,  "Include a row for the chart timeframe", group=gTF)
mtfHideLo   = input.bool(true,  "Hide rows for timeframes below the chart TF", group=gTF,
     tooltip="request.security() can only hand back the LAST completed sub-bar of a lower timeframe, so a 15m row read from a 1H chart is stale by construction. Leave ON unless you know why you want it OFF.")
mtfConf     = input.bool(false, "Read the last CLOSED bar of each timeframe", group=gTF,
     tooltip="OFF (default) = live: a row flips the moment the higher-timeframe candle closes through structure, which on an unfinished HTF bar can flip back. ON = only fully closed higher-timeframe bars are reported: never flickers, always one bar late.")
mtfShowLock = input.bool(true,  "Append anchor state (trailing / locked)", group=gTF)
mtfAlign    = input.bool(true,  "Show alignment row", group=gTF)
mtfSwLen    = input.int(0, "Pivot strength for the MTF rows (0 = same as chart)", minval=0, maxval=50, group=gTF,
     tooltip="0 = use the chart's swing pivot strength on every timeframe. Raise it to make the higher-timeframe reads structurally coarser than the chart.")
 
// mode flags
isManual    = projMode == "Manual (current only)"
projKeepEff = isManual ? 0 : histKeep      // Manual keeps zero history = one draw
mtfLen      = mtfSwLen == 0 ? swLen : mtfSwLen
 
// sizing flags
prodName    = syminfo.root != "" ? syminfo.root : syminfo.ticker
roundDown   = sizeRound == "Down (never exceed risk)"
 
f_lblSize(_s) => _s == "Tiny" ? size.tiny : _s == "Small" ? size.small : _s == "Normal" ? size.normal : size.large
 
// ============================================================================
//  SWING PIVOTS
// ============================================================================
ph = ta.pivothigh(swLen, swLen)
pl = ta.pivotlow(swLen, swLen)
 
var float lastPH   = na
var int   lastPHt  = na
var bool  phBroken = true
var float lastPL   = na
var int   lastPLt  = na
var bool  plBroken = true
var float legHigh  = na          // highest swing high of the current up-leg (bearish origin)
var float legLow   = na          // lowest  swing low  of the current down-leg (bullish origin)
var float runHigh  = na          // running fallback when no pivot exists yet
var float runLow   = na
 
if not na(ph)
    lastPH   := ph
    lastPHt  := time[swLen]
    phBroken := false
    legHigh  := na(legHigh) ? ph : math.max(legHigh, ph)
if not na(pl)
    lastPL   := pl
    lastPLt  := time[swLen]
    plBroken := false
    legLow   := na(legLow) ? pl : math.min(legLow, pl)
runHigh := na(runHigh) ? high : math.max(runHigh, high)
runLow  := na(runLow)  ? low  : math.min(runLow,  low)
 
plot(showDots and not na(ph) ? high[swLen] : na, "Swing High", style=plot.style_circles, linewidth=dotSize, color=cDotHi, offset=-swLen)
plot(showDots and not na(pl) ? low[swLen]  : na, "Swing Low",  style=plot.style_circles, linewidth=dotSize, color=cDotLo, offset=-swLen)
 
// ============================================================================
//  MSS  (reversal-only, close-confirmed)
// ============================================================================
var int     msDir    = 0
var string  msLast   = "—"
var line[]  msLines  = array.new_line()
var label[] msLabels = array.new_label()
 
f_prune_l(_a, _m) =>
    while array.size(_a) > _m
        line.delete(array.shift(_a))
f_prune_lb(_a, _m) =>
    while array.size(_a) > _m
        label.delete(array.shift(_a))
 
brkUp = not na(lastPH) and not phBroken and close > lastPH
brkDn = not na(lastPL) and not plBroken and close < lastPL
mssUp = brkUp and msDir <= 0      // bullish reversal
mssDn = brkDn and msDir >= 0      // bearish reversal
 
f_drawMSS(_lvl, _t1, _up) =>
    col = _up ? cUp : cDn
    ln = line.new(_t1, _lvl, time, _lvl, xloc=xloc.bar_time, color=col, width=1, style=line.style_dotted)
    array.push(msLines, ln)
    lb = label.new(time, _up ? low : high, _up ? "MSS ▲" : "MSS ▼", xloc=xloc.bar_time, yloc=yloc.price,
         style=_up ? label.style_label_up : label.style_label_down, textcolor=color.white, color=col, size=f_lblSize(mssLblSz))
    array.push(msLabels, lb)
 
// ============================================================================
//  SD PROJECTION  (0.0 anchor trails the impulse, locks on first opposing candle)
// ============================================================================
type Proj
    bool  bull
    float p0            // 0.0 anchor (MSS impulse close, trails until lock)
    float swing         // 1.0 origin swing
    bool  locked        // locked once the first opposing candle prints
    int   bidx          // bar_index the projection was created on
    line[]  lines
    label[] labels
    box     bx
 
// Full Shane SD set (matches the Fib-tool levels/colours). The 1.0 origin is the
// internal anchor and is not drawn (unchecked in the Fib tool). The stop level
// (default 0.9) is prepended once on the first bar when it is switched on, so
// the line/label index ↔ level index mapping is fixed before anything is drawn.
var float[] projLevels = array.from(0.75, 0.5, 0.25, 0.1, 0.0, -0.5, -1.0, -1.25, -1.5, -2.0, -2.5, -3.5, -4.0)
if barstate.isfirst and showStop and not array.includes(projLevels, stopLvl)
    array.unshift(projLevels, stopLvl)
 
var Proj    active   = na                 // the live setup
var Proj[]  projHist = array.new<Proj>()  // retired setups, newest last
 
f_projColor(_n) => (showStop and _n == stopLvl) ? cStop : _n == 0.1 ? cSDorange : (_n == 0.25 or _n == 0.75) ? cSDblue : _n == -0.5 ? cSDcyan : (_n == 0.5 or _n == -2.0 or _n == -2.5) ? cSDltgrn : (_n == -3.5 or _n == -4.0) ? cSDgreen : (_n == -1.0 or _n == -1.5) ? cSDtan : cSDgray
 
f_delProj(_p) =>
    if not na(_p)
        if array.size(_p.lines) > 0
            for i = 0 to array.size(_p.lines) - 1
                line.delete(array.get(_p.lines, i))
        if array.size(_p.labels) > 0
            for i = 0 to array.size(_p.labels) - 1
                label.delete(array.get(_p.labels, i))
        if not na(_p.bx)
            box.delete(_p.bx)
 
f_price(_p, _n) => _p.p0 + _n * (_p.swing - _p.p0)
 
// ---- position sizing --------------------------------------------------------
f_isEntry(_n) => (_n == 0.1 and sizeE1) or (_n == 0.25 and sizeE2) or (_n == 0.5 and sizeE3)
 
// contracts of the chart's product that risk `riskUSD` from level _n to the stop
f_sizeTxt(_p, _n) =>
    entry = math.round_to_mintick(f_price(_p, _n))
    stop  = math.round_to_mintick(f_price(_p, stopLvl))
    perCt = math.abs(entry - stop) * syminfo.pointvalue
    string s = ""
    if perCt > 0
        raw = riskUSD / perCt
        qty = roundDown ? math.floor(raw) : math.round(raw)
        s := qty >= 1 ? "  ·  " + str.tostring(qty) + " " + prodName + "  ($" + str.tostring(qty * perCt, "#,##0") + ")" : "  ·  0 " + prodName + "  (1 = $" + str.tostring(perCt, "#,##0") + ")"
    s
 
// label text for one level: price, plus STOP tag / contract size where relevant
f_lvlText(_p, _n) =>
    px = f_price(_p, _n)
    string t = str.tostring(_n, "0.##") + "  " + str.tostring(px, format.mintick)
    if showStop and _n == stopLvl
        t := str.tostring(_n, "0.##") + "  STOP  " + str.tostring(px, format.mintick)
    else if sizeOn and f_isEntry(_n) and (_p.locked or sizeLive)
        t := t + f_sizeTxt(_p, _n)
    t
 
f_drawProj(_p) =>
    x1 = _p.bidx
    x2 = bar_index + projRight
    for i = 0 to array.size(projLevels) - 1
        n      = array.get(projLevels, i)
        p      = f_price(_p, n)
        col    = f_projColor(n)
        isStop = showStop and n == stopLvl
        ln = line.new(x1, p, x2, p, xloc=xloc.bar_index, color=col, width=isStop ? 2 : 1,
             style=isStop ? line.style_dashed : line.style_solid)
        array.push(_p.lines, ln)
        if projLbls
            lb = label.new(x2, p, f_lvlText(_p, n), xloc=xloc.bar_index,
                 style=label.style_none, textcolor=col, size=f_lblSize(projLblSz), textalign=text.align_left)
            array.push(_p.labels, lb)
    if projBox
        p25 = f_price(_p, 0.25)
        p75 = f_price(_p, 0.75)
        _p.bx := box.new(x1, math.max(p25, p75), x2, math.min(p25, p75), xloc=xloc.bar_index,
             border_color=color.new(cSDblue, 70), bgcolor=color.new(cSDblue, 90))
 
// re-price every level (used while the 0.0 anchor is still trailing, and once
// more at the moment of lock to stamp the contract sizes onto the labels)
f_reprice(_p) =>
    if array.size(_p.lines) > 0
        for i = 0 to array.size(_p.lines) - 1
            n = array.get(projLevels, i)
            p = f_price(_p, n)
            ln = array.get(_p.lines, i)
            line.set_y1(ln, p)
            line.set_y2(ln, p)
            if projLbls and array.size(_p.labels) > i
                lb = array.get(_p.labels, i)
                label.set_y(lb, p)
                label.set_text(lb, f_lvlText(_p, n))
    if not na(_p.bx)
        p25 = f_price(_p, 0.25)
        p75 = f_price(_p, 0.75)
        box.set_top(_p.bx, math.max(p25, p75))
        box.set_bottom(_p.bx, math.min(p25, p75))
 
// trail the right edge of the live projection with price
f_extend(_p) =>
    x2 = bar_index + projRight
    if array.size(_p.lines) > 0
        for i = 0 to array.size(_p.lines) - 1
            line.set_x2(array.get(_p.lines, i), x2)
            if projLbls and array.size(_p.labels) > i
                label.set_x(array.get(_p.labels, i), x2)
    if not na(_p.bx)
        box.set_right(_p.bx, x2)
 
// fade a projection once it has been superseded
f_dimProj(_p) =>
    if not na(_p)
        if array.size(_p.lines) > 0
            for i = 0 to array.size(_p.lines) - 1
                n = array.get(projLevels, i)
                line.set_color(array.get(_p.lines, i), color.new(f_projColor(n), histTransp))
                if projLbls and array.size(_p.labels) > i
                    label.set_textcolor(array.get(_p.labels, i), color.new(f_projColor(n), histTransp))
        if not na(_p.bx)
            box.set_border_color(_p.bx, color.new(cSDblue, 90))
            box.set_bgcolor(_p.bx, color.new(cSDblue, 96))
 
// ---- anchor trailing / lock -------------------------------------------------
// NOTE: Pine's `and` does not reliably short-circuit, so UDT field access must be
// nested under a `not na(active)` guard rather than chained with `and`.
lockedNow = false
if not na(active)
    if not active.locked and bar_index > active.bidx
        if active.bull
            if close > open
                active.p0 := close
                if showProj
                    f_reprice(active)
            else if close < open
                active.locked := true
                lockedNow     := true
                if showProj
                    f_reprice(active)      // levels are final → stamp contract sizes
        else
            if close < open
                active.p0 := close
                if showProj
                    f_reprice(active)
            else if close > open
                active.locked := true
                lockedNow     := true
                if showProj
                    f_reprice(active)      // levels are final → stamp contract sizes
 
// ============================================================================
//  MSS EVENT HANDLING + PROJECTION CREATION
// ============================================================================
newProjBull = false
newProjBear = false
 
if mssUp
    if showMSS
        f_drawMSS(lastPH, lastPHt, true)
    // retire the previous setup
    if not na(active)
        if dimHistory and not isManual
            f_dimProj(active)
        array.push(projHist, active)
    origLow = not na(legLow) ? legLow : runLow
    p = Proj.new(true, close, origLow, false, bar_index, array.new_line(), array.new_label(), na)
    active := p
    if showProj
        f_drawProj(active)
    newProjBull := true
    msLast      := "MSS ▲ Bull"
    phBroken    := true
    msDir       := 1
    legHigh     := na
    runHigh     := high
else if brkUp
    phBroken := true
    msDir    := 1
 
if mssDn
    if showMSS
        f_drawMSS(lastPL, lastPLt, false)
    if not na(active)
        if dimHistory and not isManual
            f_dimProj(active)
        array.push(projHist, active)
    origHigh = not na(legHigh) ? legHigh : runHigh
    p2 = Proj.new(false, close, origHigh, false, bar_index, array.new_line(), array.new_label(), na)
    active := p2
    if showProj
        f_drawProj(active)
    newProjBear := true
    msLast      := "MSS ▼ Bear"
    plBroken    := true
    msDir       := -1
    legLow      := na
    runLow      := low
else if brkDn
    plBroken := true
    msDir    := -1
 
// keep the live projection extending with price
if extendActive and showProj and not na(active) and not (newProjBull or newProjBear)
    f_extend(active)
 
// prune history: Standard keeps `histKeep`, Manual keeps 0 (single draw on screen)
while array.size(projHist) > projKeepEff
    f_delProj(array.shift(projHist))
 
// prune MSS drawings
f_prune_l(msLines, mssKeep)
f_prune_lb(msLabels, mssKeep)
 
// ============================================================================
//  MULTI-TIMEFRAME DIRECTION ENGINE
// ----------------------------------------------------------------------------
//  f_mtfState() is a HEADLESS clone of everything above: same pivots, same
//  reversal-only MSS rule, same trailing-anchor / lock rule. It creates no
//  lines, labels or boxes — which is exactly what makes it safe to run inside
//  request.security() once per timeframe.
//
//  A projection is only ever re-anchored on a REVERSAL MSS, so on any given
//  timeframe the projection direction and the structure direction are the same
//  number. That number is what the panel prints:
//     +1  that timeframe's live projection is a LONG projection
//     -1  ... a SHORT projection
//      0  that timeframe has not printed its first MSS yet
//
//  Returned tuple: [dir, hasProjection, locked]
//  The 1.0 origin swing and the 0.0 anchor price are deliberately NOT tracked
//  here — direction and lock state are all the panel consumes, and every field
//  left out is one less thing to keep in sync with the on-chart engine.
// ============================================================================
f_mtfState() =>
    var float _lastPH   = na
    var bool  _phBroken = true
    var float _lastPL   = na
    var bool  _plBroken = true
    var int   _msDir    = 0
    var bool  _hasProj  = false
    var bool  _pBull    = false
    var bool  _locked   = false
    var int   _pBar     = na
 
    // state as it stood at the close of the PREVIOUS bar of this timeframe,
    // captured before anything below can mutate it — this is what the
    // "read the last CLOSED bar" option hands back
    _prevDir  = _msDir
    _prevHas  = _hasProj ? 1 : 0
    _prevLock = _locked  ? 1 : 0
 
    _ph = ta.pivothigh(mtfLen, mtfLen)
    _pl = ta.pivotlow(mtfLen, mtfLen)
    if not na(_ph)
        _lastPH   := _ph
        _phBroken := false
    if not na(_pl)
        _lastPL   := _pl
        _plBroken := false
 
    _brkUp = not na(_lastPH) and not _phBroken and close > _lastPH
    _brkDn = not na(_lastPL) and not _plBroken and close < _lastPL
    _mssUp = _brkUp and _msDir <= 0
    _mssDn = _brkDn and _msDir >= 0
 
    // --- anchor trailing / lock (identical rule to the on-chart engine:
    //     a same-direction close trails the 0.0 anchor, the first opposing
    //     candle locks it; the MSS bar itself is excluded) -------------------
    if _hasProj and not _locked and bar_index > nz(_pBar, bar_index)
        if _pBull
            if close < open
                _locked := true
        else
            if close > open
                _locked := true
 
    // --- MSS events (reversal only, close-confirmed) ----------------------
    if _mssUp
        _pBull    := true
        _locked   := false
        _hasProj  := true
        _pBar     := bar_index
        _phBroken := true
        _msDir    := 1
    else if _brkUp
        _phBroken := true
        _msDir    := 1
 
    if _mssDn
        _pBull    := false
        _locked   := false
        _hasProj  := true
        _pBar     := bar_index
        _plBroken := true
        _msDir    := -1
    else if _brkDn
        _plBroken := true
        _msDir    := -1
 
    // NB: the "last closed bar" values must be taken in the REQUESTED timeframe's
    // own context. Stepping back on the security RESULT would only walk one
    // CHART bar, which on a 5m chart reading 4H is not the same thing at all.
    [mtfConf ? _prevDir : _msDir, mtfConf ? _prevHas : (_hasProj ? 1 : 0), mtfConf ? _prevLock : (_locked ? 1 : 0)]
 
// ---- one security call per configured timeframe -----------------------------
[dirA, hasA, lockA] = request.security(syminfo.tickerid, mtfA, f_mtfState(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
[dirB, hasB, lockB] = request.security(syminfo.tickerid, mtfB, f_mtfState(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
[dirC, hasC, lockC] = request.security(syminfo.tickerid, mtfC, f_mtfState(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
 
// ---- chart-timeframe state, read straight off the live projection object ----
// NOTE: same caveat as the anchor-trailing block above — UDT field access must
// sit inside a `not na(active)` guard, never inside a ternary, because Pine
// evaluates both branches of `?:` and would fault on the undefined object.
int hasChart  = 0
int lockChart = 0
if not na(active)
    hasChart  := 1
    lockChart := active.locked ? 1 : 0
 
// ---- which rows are shown ---------------------------------------------------
tfSecs  = timeframe.in_seconds(timeframe.period)
rowA    = showMTF and (not mtfHideLo or timeframe.in_seconds(mtfA) >= tfSecs)
rowB    = showMTF and (not mtfHideLo or timeframe.in_seconds(mtfB) >= tfSecs)
rowC    = showMTF and (not mtfHideLo or timeframe.in_seconds(mtfC) >= tfSecs)
rowX    = showMTF and mtfChart
 
// ---- alignment tally (how many enabled HTFs agree with chart structure) -----
alignTot  = (rowA ? 1 : 0) + (rowB ? 1 : 0) + (rowC ? 1 : 0)
alignN    = (rowA and msDir != 0 and dirA == msDir ? 1 : 0) + (rowB and msDir != 0 and dirB == msDir ? 1 : 0) + (rowC and msDir != 0 and dirC == msDir ? 1 : 0)
alignFull = alignTot > 0 and msDir != 0 and alignN == alignTot
mtfFlip   = dirA != nz(dirA[1], dirA) or dirB != nz(dirB[1], dirB) or dirC != nz(dirC[1], dirC)
 
// ---- row indices (rows collapse when a timeframe is hidden) -----------------
iHdr = 6
iA   = iHdr + 1
iB   = iA + (rowA ? 1 : 0)
iC   = iB + (rowB ? 1 : 0)
iX   = iC + (rowC ? 1 : 0)
iAl  = iX + (rowX ? 1 : 0)
 
// ---- formatting -------------------------------------------------------------
f_tfLbl(_tf) =>
    _s = timeframe.in_seconds(_tf)
    _s < 60 ? str.tostring(_s) + "s" : _s >= 86400 ? str.tostring(_s / 86400.0, "0.##") + "D" : _s >= 3600 ? str.tostring(_s / 3600.0, "0.##") + "H" : str.tostring(_s / 60.0, "0.##") + "m"
 
f_dirTxt(_d, _has, _lock) =>
    string _t = _d == 1 ? "▲  LONG projection" : _d == -1 ? "▼  SHORT projection" : "—"
    if _has == 0 or _d == 0
        _t := "no MSS yet"
    else if mtfShowLock
        _t := _t + (_lock == 1 ? "  ·  locked" : "  ·  trailing")
    _t
 
f_dirCol(_d, _has) => (_has == 0 or _d == 0) ? color.new(color.gray, 30) : _d == 1 ? color.new(#00C853, 20) : color.new(#FF5252, 20)
 
lblA = f_tfLbl(mtfA)
lblB = f_tfLbl(mtfB)
lblC = f_tfLbl(mtfC)
lblX = f_tfLbl(timeframe.period) + "  chart"
 
// ============================================================================
//  INFO PANEL
// ============================================================================
f_pos(_p) => _p == "Top Right" ? position.top_right : _p == "Top Left" ? position.top_left : _p == "Bottom Right" ? position.bottom_right : position.bottom_left
 
// one multi-timeframe direction row: timeframe label | direction of its projection
f_mtfRow(_t, _r, _lbl, _d, _has, _lock) =>
    table.cell(_t, 0, _r, _lbl, text_color=color.white, bgcolor=#37474F, text_size=size.small, text_halign=text.align_left)
    table.cell(_t, 1, _r, f_dirTxt(_d, _has, _lock), text_color=color.white, bgcolor=f_dirCol(_d, _has), text_size=size.small, text_halign=text.align_left)
 
var table db = na
if showDash and barstate.islast
    if not na(db)
        table.delete(db)
    nRows = 6 + (showMTF ? 1 + (rowA ? 1 : 0) + (rowB ? 1 : 0) + (rowC ? 1 : 0) + (rowX ? 1 : 0) + (mtfAlign ? 1 : 0) : 0)
    db := table.new(f_pos(dbPos), 2, nRows, border_width=1, frame_color=color.gray, frame_width=1)
    dirTxt  = na(active) ? "—" : (active.bull ? "LONG projection" : "SHORT projection")
    dirCol  = na(active) ? color.new(color.gray, 25) : (active.bull ? color.new(#00C853, 20) : color.new(#FF5252, 20))
    lockTxt = na(active) ? "—" : (active.locked ? "LOCKED" : "trailing…")
    lockCol = na(active) ? color.new(color.gray, 25) : (active.locked ? color.new(#5C6BC0, 15) : color.new(#FFB300, 15))
    legPts  = na(active) ? na : math.abs(active.swing - active.p0)
    legTxt  = na(legPts) ? "—" : str.tostring(legPts, format.mintick) + " pts (0 → 1.0)"
    modeTxt = isManual ? "MANUAL · current only" : "STANDARD · last " + str.tostring(histKeep) + " draws"
    modeCol = isManual ? color.new(#FFB300, 15) : color.new(#455A64, 0)
    drawsTxt= str.tostring(array.size(projHist)) + " retained" + (na(active) ? "" : " + 1 live")
 
    table.cell(db, 0, 0, "SHANE · MSS / PROJ / SWING", text_color=color.white, bgcolor=#263238, text_size=size.small)
    table.cell(db, 1, 0, timeframe.period, text_color=color.white, bgcolor=#263238, text_size=size.small)
    table.cell(db, 0, 1, "Mode", text_color=color.white, bgcolor=#37474F, text_size=size.small)
    table.cell(db, 1, 1, modeTxt, text_color=color.white, bgcolor=modeCol, text_size=size.small)
    table.cell(db, 0, 2, "Structure", text_color=color.white, bgcolor=#37474F, text_size=size.small)
    table.cell(db, 1, 2, msLast, text_color=color.white, bgcolor=msDir == 1 ? color.new(#00C853, 25) : msDir == -1 ? color.new(#FF5252, 25) : color.new(color.gray, 25), text_size=size.small)
    table.cell(db, 0, 3, "Projection", text_color=color.white, bgcolor=#37474F, text_size=size.small)
    table.cell(db, 1, 3, dirTxt, text_color=color.white, bgcolor=dirCol, text_size=size.small)
    table.cell(db, 0, 4, "Anchor state", text_color=color.white, bgcolor=#37474F, text_size=size.small)
    table.cell(db, 1, 4, lockTxt, text_color=color.white, bgcolor=lockCol, text_size=size.small)
    table.cell(db, 0, 5, "Leg / draws", text_color=color.white, bgcolor=#37474F, text_size=size.small)
    table.cell(db, 1, 5, legTxt + "  ·  " + drawsTxt, text_color=color.white, bgcolor=#455A64, text_size=size.small)
 
    // ---- MULTI-TF DIRECTION BLOCK -------------------------------------------
    if showMTF
        table.cell(db, 0, iHdr, "DIRECTION" + (mtfConf ? "  · closed" : "  · live"), text_color=color.white, bgcolor=#1A237E, text_size=size.small, text_halign=text.align_left)
        table.cell(db, 1, iHdr, "CURRENT PROJECTION", text_color=color.white, bgcolor=#1A237E, text_size=size.small, text_halign=text.align_left)
        if rowA
            f_mtfRow(db, iA, lblA, dirA, hasA, lockA)
        if rowB
            f_mtfRow(db, iB, lblB, dirB, hasB, lockB)
        if rowC
            f_mtfRow(db, iC, lblC, dirC, hasC, lockC)
        if rowX
            f_mtfRow(db, iX, lblX, msDir, hasChart, lockChart)
        if mtfAlign
            aTxt = alignTot == 0 ? "—" : str.tostring(alignN) + " / " + str.tostring(alignTot) + (alignFull ? (msDir == 1 ? "  ALIGNED LONG" : "  ALIGNED SHORT") : "  mixed")
            aCol = alignTot == 0 ? color.new(color.gray, 30) : alignFull ? (msDir == 1 ? color.new(#00C853, 10) : color.new(#FF5252, 10)) : color.new(#FFB300, 20)
            table.cell(db, 0, iAl, "Alignment", text_color=color.white, bgcolor=#37474F, text_size=size.small, text_halign=text.align_left)
            table.cell(db, 1, iAl, aTxt, text_color=color.white, bgcolor=aCol, text_size=size.small, text_halign=text.align_left)
 
// ============================================================================
//  ALERTS
// ============================================================================
alertcondition(mssUp, "Bullish MSS", "Shane: Bullish MSS (close broke swing high).")
alertcondition(mssDn, "Bearish MSS", "Shane: Bearish MSS (close broke swing low).")
alertcondition(newProjBull or newProjBear, "New projection", "Shane: new SD projection created off MSS.")
alertcondition(lockedNow, "Projection locked", "Shane: SD projection locked (first opposing candle) — levels are final.")
alertcondition(mtfFlip, "MTF direction flip",
     "Shane: a higher-timeframe projection just flipped direction.")
alertcondition(alignFull and not alignFull[1], "MTF direction aligned",
     "Shane: every enabled higher timeframe now agrees with chart structure.")

← 返回列表