Strong Magnet Zones | ProjectSyndicate

ProjectSyndicate · study · 894 行 · 点赞 1,407 · TradingView 原页

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

Pine Script

//@version=6
indicator("Strong Magnet Zones", "Strong Magnet Zones", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500, max_bars_back=5000)
 
grpB = "1 · Build"
lockTf   = input.timeframe("30", "Build zones on timeframe", group=grpB, tooltip="Stop pools AND supply/demand bases are built from this timeframe, so every chart at or below it (1m, 5m, 15m, 30m) shows the same zones. Charts above it use their own timeframe. Leave empty to always use the chart timeframe.")
pivLen   = input.int(5, "Swing length", minval=2, maxval=30, group=grpB, tooltip="A swing high/low needs this many bars on each side. Stops sit just beyond these swings.")
mergeTol = input.float(0.30, "Merge tolerance (× ATR)", minval=0.05, step=0.05, group=grpB, tooltip="A new pool or base that comes within this distance of a same-side zone merges into it (equal highs/lows stack heat; a pool inside a base becomes a confluence zone).")
useVol   = input.bool(true, "Weight by volume at the swing", group=grpB)
useRound = input.bool(true, "Boost zones holding a round number", group=grpB)
roundStp = input.float(0.0, "Round number step (0 = auto)", minval=0.0, group=grpB)
 
grpZ = "2 · Zone height (universal)"
heightMode = input.string("ATR Based", "Height method", options=["ATR Based", "Fixed Percentage"], group=grpZ, tooltip="Every zone — stop pool, base or merged — gets the SAME thickness, centered on its level (swing price, or base midpoint).")
heightATR  = input.float(0.6, "Zone height (ATR mult)", minval=0.05, maxval=10.0, step=0.05, group=grpZ)
heightPct  = input.float(0.30, "Zone height (% of price)", minval=0.01, maxval=5.0, step=0.05, group=grpZ)
atrLen     = input.int(200, "ATR length (build TF)", minval=1, maxval=500, group=grpZ)
 
grpS = "3 · Supply / demand bases"
minBase      = input.int(1, "Min base candles", minval=1, group=grpS)
maxBase      = input.int(5, "Max base candles", minval=1, maxval=20, group=grpS)
baseThresh   = input.float(0.65, "Max base body/range ratio", minval=0.1, maxval=0.95, step=0.05, group=grpS)
legOutThresh = input.float(0.55, "Min leg-out body/range ratio", minval=0.3, maxval=0.95, step=0.05, group=grpS)
legOutMult   = input.float(1.4, "Leg-out range vs base average (×)", minval=1.0, step=0.1, group=grpS)
depCandles   = input.int(1, "Sustained departure candles", minval=1, maxval=5, group=grpS)
 
grpH = "4 · Heat & lifecycle"
halfLife = input.int(150, "Heat half-life (bars of build TF)", minval=10, maxval=2000, group=grpH)
touchAdd = input.float(0.3, "Heat added per touch without sweep", minval=0.0, step=0.1, group=grpH)
maxLv    = input.int(60, "Max active zones", minval=10, maxval=200, group=grpH)
maxDist  = input.float(16.0, "Show zones within (× ATR of price)", minval=2.0, step=0.5, group=grpH)
minShow  = input.float(4.0, "Hide zones scoring below (0–10)", minval=0.0, maxval=10.0, step=0.5, group=grpH)
hotPct   = input.int(60, "Hot zone = heat ≥", minval=10, maxval=100, group=grpH)
workRR   = input.float(1.0, "WORKED = price travels (× zone height) after a test", minval=0.5, maxval=5.0, step=0.5, group=grpH)
revBars  = input.int(10, "Sweep → reversal window (bars)", minval=2, maxval=100, group=grpH)
revAtr   = input.float(0.5, "Reversal = close back beyond zone by (× ATR)", minval=0.1, step=0.1, group=grpH)
keepRes  = input.int(30, "Resolved zones kept on chart", minval=0, maxval=150, group=grpH)
 
grpG = "5 · Signals & tickets"
showSig  = input.bool(true, "Signals", group=grpG)
sigMode  = input.string("Trend or turning", "Trend gate (Laguerre, not drawn)", options=["Trend aligned", "Trend or turning", "Any"], group=grpG, tooltip="An invisible Ehlers Laguerre fast/slow filter gates signals. Trend aligned: BUY only when fast > slow AND rising. Trend or turning: either. Any: no gate. Nothing is plotted.")
lagLen   = input.int(20, "Laguerre period", minval=5, group=grpG)
sigWin   = input.int(8, "Reclaim within (bars after a sweep)", minval=1, maxval=50, group=grpG)
minScore = input.float(6.0, "Min signal score (0–10)", minval=0.0, maxval=10.0, step=0.5, group=grpG)
coolBars = input.int(10, "Cooldown after a ticket closes (bars)", minval=0, maxval=200, group=grpG)
showTk   = input.bool(true, "Draw R-tickets (entry / SL / TP)", group=grpG)
slPad    = input.float(0.15, "SL pad beyond the sweep extreme (× ATR)", minval=0.0, step=0.05, group=grpG)
maxRisk  = input.float(2.0, "Max risk (× ATR)", minval=0.3, step=0.1, group=grpG)
minRisk  = input.float(0.4, "Min risk (× ATR)", minval=0.1, step=0.1, group=grpG)
defRR    = input.float(2.0, "Default target (R) when no magnet fits", minval=0.5, step=0.5, group=grpG)
maxRR    = input.float(5.0, "Max target distance (R)", minval=1.0, step=0.5, group=grpG)
maxHold  = input.int(60, "Ticket timeout (bars)", minval=5, maxval=500, group=grpG)
keepTk   = input.int(12, "Tickets kept on chart", minval=1, maxval=60, group=grpG)
 
grpV = "6 · Visuals"
showZ     = input.bool(true, "Magnet zones", group=grpV)
maxSide   = input.int(5, "Max live zones shown per side", minval=1, maxval=30, group=grpV, tooltip="Only the best-scoring live zones in view are drawn, per side. Keeps the chart readable.")
showLbl   = input.bool(true, "Labels inside zones", group=grpV)
lblMax    = input.int(4, "Max labels (best live zones)", minval=1, maxval=20, group=grpV)
lblMin    = input.float(5.0, "Label zones scoring ≥", minval=0.0, maxval=10.0, step=0.5, group=grpV)
lblRes    = input.bool(true, "Brief labels on resolved zones", group=grpV, tooltip="Resolved zones are greyed out and carry a short label: score · outcome (WORKED ✔ / ⚡ REVERSED ✔ / ⚡ CONTINUED ✘).")
lblSize   = input.string("Normal", "Label size", options=["Tiny", "Small", "Normal", "Large"], group=grpV)
showEdge  = input.bool(false, "Proximal (solid) / distal (dashed) edge lines", group=grpV)
showSwept = input.bool(true, "Show resolved zones (greyed out)", group=grpV)
resBars   = input.int(400, "Resolved band max length (bars)", minval=20, maxval=3000, group=grpV)
showProf  = input.bool(true, "Heat profile on the right", group=grpV)
profBins  = input.int(40, "Profile rows", minval=10, maxval=80, group=grpV)
profWidth = input.int(12, "Profile width (bars)", minval=5, maxval=100, group=grpV)
extRight  = input.int(3, "Extend zones right (bars)", minval=0, maxval=50, group=grpV)
showMag   = input.bool(true, "Magnets (hottest zone above / below)", group=grpV)
showSwpL  = input.bool(true, "Sweep marks ⚡ (solid = reversed · faded = continued)", group=grpV)
hotCandle = input.bool(true, "Glow candles inside hot zones", group=grpV)
 
grpK = "7 · Style"
cBull     = input.color(#21c997, "Magnet Zone Bulls tone", group=grpK)
cBear     = input.color(#cc24e2, "Magnet Zone Bears tone", group=grpK)
cSwept    = input.color(#B2B5BE, "Swept / resolved zone", group=grpK)
fillTransp= input.int(84, "Zone transparency", minval=50, maxval=96, group=grpK)
showBord  = input.bool(true, "Show zone borders", group=grpK)
bordTransp= input.int(35, "Border transparency", minval=0, maxval=100, group=grpK)
cTp     = input.color(#4caf50, "Ticket TP", group=grpK)
cSl     = input.color(#e53935, "Ticket SL", group=grpK)
 
type MZ
    float lvl
    float top
    float bot
    int   side
    float w
    int   born
    int   bornT
    int   stacks = 0
    bool  sd = false
    float imp = 0.0
    float bod = 0.0
    float vf = 1.0
    bool  rnd = false
    int   tests = 0
    bool  inLast = false
    int   addB = na
    int   state = 0
    int   revRes = 0
    int   endBar = na
    float score = 0.0
    float hpEnd = 0.0
    box   bx = na
    line  pLn = na
    line  dLn = na
    label tag = na
 
type Tk
    int   dir
    float entry
    float sl
    float tp
    int   born
    float r
    line  eLn
    line  sLn
    line  tLn
    box   rBox
    box   pBox
    label sig
    label out = na
    int   state = 0
 
int    chSec  = timeframe.in_seconds()
int    lkSec  = lockTf == "" ? chSec : timeframe.in_seconds(lockTf)
string effTf  = lkSec > chSec ? lockTf : timeframe.period
int    effSec = math.max(lkSec, chSec)
float  tfMult = float(effSec) / chSec
 
f_sdDetect() =>
    int   dirO = 0
    float zTop = na
    float zBot = na
    float imp  = 0.0
    float bod  = 0.0
    float vf   = 1.0
    int   st   = na
    float va   = ta.sma(nz(volume), 50)
    int   lo   = depCandles
    if bar_index >= maxBase + lo + 5
        float rngL = high[lo] - low[lo]
        float bdyL = math.abs(close[lo] - open[lo])
        if rngL > 0 and bdyL / rngL >= legOutThresh
            bool bull = close[lo] > open[lo]
            int  bc = 0
            int  sb = lo + 1
            for i = 0 to maxBase - 1
                float r = high[sb + i] - low[sb + i]
                float b = math.abs(close[sb + i] - open[sb + i])
                if r > 0 and b / r <= baseThresh
                    bc += 1
                else
                    break
            bool inside = high[sb] <= high[sb + 1] and low[sb] >= low[sb + 1]
            if bc >= minBase and not inside
                float bh = high[sb]
                float bl = low[sb]
                float sum = 0.0
                for b2 = 0 to bc - 1
                    bh := math.max(bh, high[sb + b2])
                    bl := math.min(bl, low[sb + b2])
                    sum += high[sb + b2] - low[sb + b2]
                float avg = sum / bc
                float zh = bh - bl
                if zh > 0 and zh < rngL and rngL >= avg * legOutMult
                    bool ok = true
                    for dep = 1 to depCandles
                        int d = lo - dep
                        if d >= 0
                            if bull ? (close[d] <= bh or low[d] <= bh) : (close[d] >= bl or high[d] >= bl)
                                ok := false
                    if ok and (bull ? close[lo] > bh : close[lo] < bl)
                        dirO := bull ? 1 : -1
                        zTop := bh
                        zBot := bl
                        imp  := rngL / avg
                        bod  := bdyL / rngL
                        vf   := va[lo] > 0 ? math.min(math.max(nz(volume[lo]) / va[lo], 0.5), 3.0) : 1.0
                        st   := time[sb + bc - 1]
    [dirO, zTop, zBot, imp, bod, vf, st]
 
f_src() =>
    float a   = ta.atr(14)
    float a2  = ta.atr(atrLen)
    float va  = ta.sma(nz(volume), 50)
    float vfx = va[pivLen] > 0 ? math.min(math.max(nz(volume[pivLen]) / va[pivLen], 0.5), 3.0) : 1.0
    float p1  = ta.pivothigh(high, pivLen, pivLen)
    float p2  = ta.pivotlow(low, pivLen, pivLen)
    int   tp  = time[pivLen]
    [sdD, sdT, sdB, sdI, sdBo, sdV, sdS] = f_sdDetect()
    [p1[1], p2[1], tp[1], a[1], a2[1], vfx[1], high[1], low[1], sdD[1], sdT[1], sdB[1], sdI[1], sdBo[1], sdV[1], sdS[1]]
[ph, pl, pivT, atrL, atrNL, vfL, hiL, loL, sdDir, sdTop, sdBot, sdImp, sdBod, sdVf, sdStartT] = request.security(syminfo.tickerid, effTf, f_src(), lookahead=barmerge.lookahead_on)
bool  tfCh   = timeframe.change(effTf)
bool  newL   = effTf == timeframe.period ? true : tfCh
float atr    = atrL
float atrN   = math.max(nz(atrNL, atr), syminfo.mintick)
float zoneH  = heightMode == "ATR Based" ? atrN * heightATR : close * (heightPct / 100.0)
bool  conf   = barstate.isconfirmed
bool  hasVol = ta.cum(nz(volume)) > 0
 
f_idxAt(int t) =>
    int k = 0
    while k < 4900 and bar_index - k > 0 and time[k] > t
        k += 1
    bar_index - k
 
var array<MZ> act = array.new<MZ>()
var array<MZ> res = array.new<MZ>()
 
f_step() =>
    float s = roundStp
    if s <= 0
        s := math.pow(10, math.floor(math.log10(math.max(close, 1e-10))) - 2) * 2.5
    s
f_heat(MZ z) =>
    float age = (time - z.bornT) / (effSec * 1000.0)
    z.w * math.pow(0.5, age / halfLife)
f_clamp(float v, float lo, float hi) =>
    math.max(lo, math.min(hi, v))
f_prox(MZ z) =>
    z.side == 1 ? z.top : z.bot
f_dist(MZ z) =>
    z.side == 1 ? z.bot : z.top
f_hasRound(float top, float bot) =>
    float st = f_step()
    float r = math.round((top + bot) / 2 / st) * st
    r >= bot and r <= top
f_setBounds(MZ z) =>
    z.top := z.lvl + zoneH / 2
    z.bot := z.lvl - zoneH / 2
f_stars(float sc) =>
    sc >= 8 ? "★★★★" : sc >= 6.5 ? "★★★" : sc >= 5 ? "★★" : sc >= 3 ? "★" : "·"
f_tier(float sc) =>
    sc >= 8 ? "ELITE" : sc >= 6.5 ? "STRONG" : sc >= 5 ? "MODERATE" : sc >= 3 ? "WEAK" : "FORMING"
 
f_score(MZ z, float mx) =>
    float hp = mx > 0 ? math.sqrt(math.max(f_heat(z), 0) / mx) : 0.0
    float pts = 4.0 * hp
    pts += math.min(1.5, z.stacks * 0.5)
    if z.sd
        pts += f_clamp((z.imp - 1.0) * 1.5, 0.0, 2.0) + f_clamp((z.bod - 0.5) * 3.0, 0.0, 1.0)
    pts += f_clamp((z.vf - 1.0), 0.0, 1.0)
    pts += z.sd and z.stacks > 0 ? 1.5 : 0.0
    pts += z.rnd ? 0.5 : 0.0
    pts += z.state == 0 and z.tests == 0 ? 0.5 : 0.0
    f_clamp(pts, 0.0, 10.0)
 
f_add(float lvl, int side, float wNew, int bornBar, int bornT, bool isSD, float imp, float bod, float vf) =>
    float tol = math.max(mergeTol * atr, zoneH / 2)
    int hit = -1
    float best = tol
    if act.size() > 0
        for i = 0 to act.size() - 1
            MZ z = act.get(i)
            float d = math.abs(z.lvl - lvl)
            if z.side == side and d <= best
                best := d
                hit := i
    if hit >= 0
        MZ z = act.get(hit)
        float cur = f_heat(z)
        float tw = cur + wNew
        z.lvl := (z.lvl * cur + lvl * wNew) / tw
        f_setBounds(z)
        z.w := tw + (isSD ? 0.0 : wNew * 0.5)
        z.born := math.min(z.born, bornBar)
        z.bornT := math.max(z.bornT, bornT)
        z.addB := bar_index
        if isSD
            z.sd := true
            z.imp := math.max(z.imp, imp)
            z.bod := math.max(z.bod, bod)
            z.vf := math.max(z.vf, vf)
        else
            z.stacks += 1
            z.vf := math.max(z.vf, vf)
        z.rnd := useRound and f_hasRound(z.top, z.bot)
    else
        MZ nz1 = MZ.new(lvl, lvl + zoneH / 2, lvl - zoneH / 2, side, wNew, bornBar, bornT)
        nz1.rnd := useRound and f_hasRound(nz1.top, nz1.bot)
        if nz1.rnd
            nz1.w := nz1.w * 1.3
        if isSD
            nz1.sd := true
            nz1.imp := imp
            nz1.bod := bod
            nz1.vf := vf
        else
            nz1.stacks := 1
            nz1.vf := vf
        nz1.addB := bar_index
        act.push(nz1)
    hit
 
if conf and newL and not na(atr) and atr > 0 and zoneH > 0
    if not na(pivT)
        float vf = useVol and hasVol ? nz(vfL, 1.0) : 1.0
        int bi = na(ph) and na(pl) ? na : f_idxAt(pivT)
        if not na(ph)
            f_add(ph, -1, vf, bi, pivT, false, 0.0, 0.0, vf)
        if not na(pl)
            f_add(pl, 1, vf, bi, pivT, false, 0.0, 0.0, vf)
    if nz(sdDir) != 0 and not na(sdTop) and not na(sdBot) and not na(sdStartT)
        float wSD = 1.0 + f_clamp((sdImp - 1.0) * 0.5, 0.0, 1.0)
        f_add((sdTop + sdBot) / 2, sdDir, wSD, f_idxAt(sdStartT), sdStartT, true, sdImp, sdBod, useVol and hasVol ? sdVf : 1.0)
 
float maxH = 0.0
if act.size() > 0
    for i = 0 to act.size() - 1
        maxH := math.max(maxH, f_heat(act.get(i)))
 
var array<label> swLbls = array.new<label>()
var int nRev   = 0
var int nRevOk = 0
bool  sweepBull = false
bool  sweepBear = false
bool  workEv    = false
bool  testEv    = false
float swBullHp  = 0.0
float swBearHp  = 0.0
float swBullP   = na
float swBearP   = na
float swBullSc  = 0.0
float swBearSc  = 0.0
string hotMsg = ""
 
f_zName(MZ z) =>
    z.side == 1 ? "MAGNET ZONE BULLS" : "MAGNET ZONE BEARS"
f_zCol(MZ z) =>
    z.side == 1 ? cBull : cBear
f_zSize() =>
    lblSize == "Tiny" ? size.tiny : lblSize == "Normal" ? size.normal : lblSize == "Large" ? size.large : size.small
 
f_zText(MZ z, float hp) =>
    float hpx = z.state == 0 ? hp : z.hpEnd
    string t = f_stars(z.score) + " " + str.tostring(z.score, "0.0") + "/10 " + f_tier(z.score) + " · heat " + str.tostring(hpx, "0")
    if z.stacks > 1
        t += " · ×" + str.tostring(z.stacks)
    if z.sd
        t += " · S/D " + str.tostring(z.imp, "0.0") + "×"
    if z.sd and z.stacks > 0
        t += " · CONF"
    if z.vf > 1.05
        t += " · vol " + str.tostring(z.vf, "0.0") + "×"
    if z.rnd
        t += " · ◎"
    t += z.state == 1 ? " · WORKED ✔" : z.state == 2 ? (z.revRes == 1 ? " · SWEPT → REVERSED ✔" : z.revRes == -1 ? " · SWEPT → CONTINUED ✘" : " · SWEPT") : z.tests == 0 ? " · FRESH" : " · R:" + str.tostring(z.tests)
    t
 
f_zBrief(MZ z) =>
    str.tostring(z.score, "0.0") + (z.state == 1 ? " · WORKED ✔" : z.revRes == 1 ? " · ⚡ REVERSED ✔" : z.revRes == -1 ? " · ⚡ CONTINUED ✘" : " · ⚡ SWEPT")
 
f_zDel(MZ z) =>
    if not na(z.bx)
        z.bx.delete()
    if not na(z.pLn)
        z.pLn.delete()
    if not na(z.dLn)
        z.dLn.delete()
    if not na(z.tag)
        z.tag.delete()
    true
 
f_zFreeze(MZ z, color c, int alpha) =>
    int xl = math.max(z.born, bar_index - resBars)
    if na(z.bx)
        z.bx := box.new(xl, z.top, bar_index, z.bot, border_color=color(na), bgcolor=color.new(c, alpha))
    else
        z.bx.set_lefttop(xl, z.top)
        z.bx.set_rightbottom(bar_index, z.bot)
        z.bx.set_bgcolor(color.new(c, alpha))
        z.bx.set_border_color(color(na))
    if not na(z.pLn)
        z.pLn.delete()
        z.pLn := na
    if not na(z.dLn)
        z.dLn.delete()
        z.dLn := na
    if lblRes and showLbl
        if na(z.tag)
            z.tag := label.new(bar_index, (z.top + z.bot) / 2, f_zBrief(z), style=label.style_label_right, color=color.new(c, 100), textcolor=color.new(cSwept, 20), size=size.tiny)
        else
            z.tag.set_x(bar_index)
            z.tag.set_text(f_zBrief(z))
            z.tag.set_textcolor(color.new(cSwept, 20))
            z.tag.set_size(size.tiny)
    else if not na(z.tag)
        label old = z.tag
        z.tag := na
        old.delete()
    true
 
if conf and act.size() > 0 and not na(atr)
    for i = act.size() - 1 to 0
        MZ z = act.get(i)
        if zoneH > 0
            f_setBounds(z)
        if z.born < bar_index
            float hp = maxH > 0 ? 100 * math.sqrt(f_heat(z) / maxH) : 0
            bool swept  = z.side == 1 ? low < z.bot - 0.05 * atr : high > z.top + 0.05 * atr
            bool inZone = high >= z.bot and low <= z.top
            bool touchH = newL and not na(hiL) and z.addB != bar_index and (z.side == 1 ? loL <= z.top : hiL >= z.bot)
            bool worked = z.tests > 0 and (z.side == 1 ? high >= z.top + (z.top - z.bot) * workRR : low <= z.bot - (z.top - z.bot) * workRR)
            if swept
                z.state := 2
                z.endBar := bar_index
                z.hpEnd := hp
                z.score := f_score(z, maxH)
                if hp >= hotPct
                    hotMsg += (z.side == 1 ? "BULLS " : "BEARS ") + str.tostring(f_prox(z), format.mintick) + " (heat " + str.tostring(hp, "0") + ")  "
                if z.side == 1
                    sweepBull := true
                    if hp > swBullHp
                        swBullHp := hp
                        swBullP := z.top
                        swBullSc := z.score
                else
                    sweepBear := true
                    if hp > swBearHp
                        swBearHp := hp
                        swBearP := z.bot
                        swBearSc := z.score
                if showSwpL and hp >= hotPct
                    bool up = z.side == -1
                    label sl = label.new(bar_index, up ? high : low, "⚡", yloc=up ? yloc.abovebar : yloc.belowbar, style=label.style_none, textcolor=up ? cBear : cBull, size=size.normal, tooltip=f_zName(z) + " swept · " + str.tostring(f_prox(z), format.mintick) + " · heat " + str.tostring(hp, "0") + " · outcome pending")
                    swLbls.push(sl)
                    while swLbls.size() > 24
                        swLbls.shift().delete()
                f_zFreeze(z, cSwept, 84)
                act.remove(i)
                res.push(z)
            else if worked
                z.state := 1
                z.endBar := bar_index
                z.hpEnd := hp
                z.score := f_score(z, maxH)
                workEv := true
                f_zFreeze(z, cSwept, 80)
                act.remove(i)
                res.push(z)
            else
                if inZone and not z.inLast
                    z.tests += 1
                    testEv := true
                if touchH
                    z.w := f_heat(z) + touchAdd
                    z.bornT := time
                z.inLast := inZone
    while act.size() > maxLv
        int ci = 0
        float ch = 1e30
        for j = 0 to act.size() - 1
            float h = f_heat(act.get(j))
            if h < ch
                ch := h
                ci := j
        MZ d = act.remove(ci)
        f_zDel(d)
 
if conf and res.size() > 0 and not na(atr)
    for i = 0 to res.size() - 1
        MZ z = res.get(i)
        if z.state == 2 and z.revRes == 0
            bool ok  = bar_index > z.endBar and (z.side == 1 ? close >= z.top + revAtr * atr : close <= z.bot - revAtr * atr)
            bool out = bar_index - z.endBar >= revBars * tfMult
            if ok or out
                z.revRes := ok ? 1 : -1
                nRev += 1
                nRevOk += ok ? 1 : 0
                if not na(z.tag)
                    z.tag.set_text(f_zBrief(z))
                if swLbls.size() > 0
                    for k = swLbls.size() - 1 to 0
                        label sl = swLbls.get(k)
                        if sl.get_x() == z.endBar
                            color sc = f_zCol(z)
                            sl.set_textcolor(ok ? sc : color.new(sc, 65))
                            sl.set_tooltip(f_zName(z) + " swept · " + str.tostring(f_prox(z), format.mintick) + (ok ? " · REVERSED ✔" : " · continued ✘") + "\nSweep reversal rate so far: " + str.tostring(100.0 * nRevOk / nRev, "0") + "% (n " + str.tostring(nRev) + ") · in-sample")
                            break
while res.size() > keepRes
    MZ d = res.shift()
    f_zDel(d)
 
float maxH2 = 0.0
if act.size() > 0
    for i = 0 to act.size() - 1
        maxH2 := math.max(maxH2, f_heat(act.get(i)))
float lim = maxDist * nz(atr)
int   iUp = -1
int   iDn = -1
float bUp = -1.0
float bDn = -1.0
int   iUpA = -1
int   iDnA = -1
float bUpA = -1.0
float bDnA = -1.0
float inHotP = 0.0
int   inHotS = 0
if act.size() > 0
    for i = 0 to act.size() - 1
        MZ z = act.get(i)
        z.score := f_score(z, maxH2)
        float h  = f_heat(z)
        float hp = maxH2 > 0 ? 100 * math.sqrt(h / maxH2) : 0
        bool above = z.side == -1
        if hp >= hotPct and close <= z.top and close >= z.bot and hp > inHotP
            inHotP := hp
            inHotS := z.side
        if above
            if h > bUpA
                bUpA := h
                iUpA := i
            if math.abs(z.bot - close) <= lim and h > bUp
                bUp := h
                iUp := i
        else
            if h > bDnA
                bDnA := h
                iDnA := i
            if math.abs(z.top - close) <= lim and h > bDn
                bDn := h
                iDn := i
bool  magUpFar = iUp < 0 and iUpA >= 0
bool  magDnFar = iDn < 0 and iDnA >= 0
int   iMagUp = iUp >= 0 ? iUp : iUpA
int   iMagDn = iDn >= 0 ? iDn : iDnA
float magUp = iMagUp >= 0 ? act.get(iMagUp).bot : na
float magDn = iMagDn >= 0 ? act.get(iMagDn).top : na
float pUp = maxH2 > 0 and iMagUp >= 0 ? 100 * math.sqrt(math.max(magUpFar ? bUpA : bUp, 0) / maxH2) : 0
float pDn = maxH2 > 0 and iMagDn >= 0 ? 100 * math.sqrt(math.max(magDnFar ? bDnA : bDn, 0) / maxH2) : 0
float sUp = iMagUp >= 0 ? act.get(iMagUp).score : 0
float sDn = iMagDn >= 0 ? act.get(iMagDn).score : 0
float yUp = magUpFar ? math.min(magUp, close + lim) : magUp
float yDn = magDnFar ? math.max(magDn, close - lim) : magDn
 
var float mtUpP = na
var int   mtUpB = na
var float mtDnP = na
var int   mtDnB = na
bool magHitUp = false
bool magHitDn = false
if conf
    if not na(mtUpP)
        if high >= mtUpP
            magHitUp := true
            mtUpP := na
        else if bar_index - mtUpB >= maxHold * tfMult
            mtUpP := na
    if not na(mtDnP)
        if low <= mtDnP
            magHitDn := true
            mtDnP := na
        else if bar_index - mtDnB >= maxHold * tfMult
            mtDnP := na
    if na(mtUpP) and not na(magUp) and not magUpFar and pUp >= hotPct and magUp - close >= atr
        mtUpP := magUp
        mtUpB := bar_index
    if na(mtDnP) and not na(magDn) and not magDnFar and pDn >= hotPct and close - magDn >= atr
        mtDnP := magDn
        mtDnB := bar_index
 
float gFast = math.max(0.0, (lagLen - 4.0) / (lagLen + 4.0))
float slowN = lagLen * 2.5
float gSlow = math.max(0.0, (slowN - 4.0) / (slowN + 4.0))
f_laguerre(float s, float g) =>
    var float l0 = na
    var float l1 = na
    var float l2 = na
    var float l3 = na
    float pl0 = nz(l0, s)
    float pl1 = nz(l1, s)
    float pl2 = nz(l2, s)
    float pl3 = nz(l3, s)
    l0 := (1 - g) * s + g * pl0
    l1 := -g * l0 + pl0 + g * pl1
    l2 := -g * l1 + pl1 + g * pl2
    l3 := -g * l2 + pl2 + g * pl3
    (l0 + 2 * l1 + 2 * l2 + l3) / 6
float lagF = f_laguerre(close, gFast)
float lagS = f_laguerre(close, gSlow)
bool  lagUp = lagF > nz(lagF[1], lagF)
bool  lagDn = lagF < nz(lagF[1], lagF)
int   trend = lagF > lagS and lagUp ? 1 : lagF < lagS and lagDn ? -1 : 0
bool  bullBias = sigMode == "Any" ? true : sigMode == "Trend aligned" ? (lagF > lagS and lagUp) : (lagF > lagS or lagUp)
bool  bearBias = sigMode == "Any" ? true : sigMode == "Trend aligned" ? (lagF < lagS and lagDn) : (lagF < lagS or lagDn)
 
var array<Tk> tks = array.new<Tk>()
var Tk live = na
var int lastClose = -100000
var int nTk = 0
var int nWin = 0
var float sumWin = 0.0
var float sumLoss = 0.0
var int   swBBar = -100000
var float swBP  = na
var float swBLo = na
var float swBHp = 0.0
var float swBSc = 0.0
var int   swSBar = -100000
var float swSP  = na
var float swSHi = na
var float swSHp = 0.0
var float swSSc = 0.0
bool buySig = false
bool sellSig = false
bool tkTp = false
bool tkSl = false
float sigScore = 0.0
 
if conf and sweepBull
    swBBar := bar_index
    swBP := swBullP
    swBLo := low
    swBHp := swBullHp
    swBSc := swBullSc
if conf and sweepBear
    swSBar := bar_index
    swSP := swBearP
    swSHi := high
    swSHp := swBearHp
    swSSc := swBearSc
if conf and not na(swBLo) and bar_index - swBBar <= sigWin
    swBLo := math.min(swBLo, low)
if conf and not na(swSHi) and bar_index - swSBar <= sigWin
    swSHi := math.max(swSHi, high)
 
f_tip(string head) =>
    float pf = sumLoss > 0 ? sumWin / sumLoss : sumWin > 0 ? 99.0 : 0.0
    head + (nTk > 0 ? "\nTickets closed " + str.tostring(nTk) + " · win " + str.tostring(100.0 * nWin / nTk, "0") + "% · PF " + str.tostring(pf, "0.00") + " · all closed tickets counted · in-sample" : "\nNo closed tickets yet")
 
if conf and not na(live) and live.state == 0
    bool hitSl = live.dir == 1 ? low <= live.sl : high >= live.sl
    bool hitTp = live.dir == 1 ? high >= live.tp : low <= live.tp
    bool tout  = bar_index - live.born >= maxHold
    if hitSl or hitTp or tout
        float rr = hitSl ? -1.0 : hitTp ? (live.dir == 1 ? live.tp - live.entry : live.entry - live.tp) / live.r : (live.dir == 1 ? close - live.entry : live.entry - close) / live.r
        live.state := hitSl ? 2 : hitTp ? 1 : 3
        nTk += 1
        if rr > 0
            nWin += 1
            sumWin += rr
        else
            sumLoss += -rr
        tkSl := hitSl
        tkTp := hitTp
        float ex = hitSl ? live.sl : hitTp ? live.tp : close
        if not na(live.eLn)
            live.eLn.set_x2(bar_index)
            live.sLn.set_x2(bar_index)
            live.tLn.set_x2(bar_index)
            live.rBox.set_right(bar_index)
            live.pBox.set_right(bar_index)
        string txt = hitSl ? "✘ SL  " + str.tostring(rr, "0.0") + "R" : hitTp ? "✔ TP  +" + str.tostring(rr, "0.0") + "R" : "⏱ " + (rr >= 0 ? "+" : "") + str.tostring(rr, "0.0") + "R"
        color oc = hitSl ? cSl : hitTp ? cTp : color.new(chart.fg_color, 30)
        live.out := label.new(bar_index, ex, txt, style=live.dir == 1 ? (hitSl ? label.style_label_up : label.style_label_down) : (hitSl ? label.style_label_down : label.style_label_up), color=color.new(oc, 10), textcolor=color.white, size=size.small, tooltip=f_tip((live.dir == 1 ? "BUY" : "SELL") + " ticket closed · " + str.tostring(rr, "0.00") + "R"))
        lastClose := bar_index
        live := na
 
f_openTk(int dir, float sl, float tp, float rsk, string txt, string tip) =>
    label sg = label.new(bar_index, dir == 1 ? low : high, txt, yloc=dir == 1 ? yloc.belowbar : yloc.abovebar, style=dir == 1 ? label.style_label_up : label.style_label_down, color=color.new(dir == 1 ? cBull : cBear, 0), textcolor=color.white, size=size.small, tooltip=tip)
    line eL = na
    line sL = na
    line tL = na
    box rB = na
    box pB = na
    if showTk
        eL := line.new(bar_index, close, bar_index + 1, close, color=color.new(chart.fg_color, 20), width=1)
        sL := line.new(bar_index, sl, bar_index + 1, sl, color=cSl, width=1, style=line.style_dashed)
        tL := line.new(bar_index, tp, bar_index + 1, tp, color=cTp, width=1, style=line.style_dashed)
        rB := box.new(bar_index, math.max(close, sl), bar_index + 1, math.min(close, sl), border_color=color(na), bgcolor=color.new(cSl, 93))
        pB := box.new(bar_index, math.max(close, tp), bar_index + 1, math.min(close, tp), border_color=color(na), bgcolor=color.new(cTp, 93))
    Tk.new(dir, close, sl, tp, bar_index, rsk, eL, sL, tL, rB, pB, sg)
 
if conf and showSig and na(live) and bar_index - lastClose >= coolBars and not na(atr) and atr > 0
    bool bReady = not na(swBP) and bar_index - swBBar <= sigWin and close > swBP and (close > open or close > close[1])
    if bReady and bullBias
        float ptsZone  = 4.0 * swBSc / 10.0
        float ptsHeat  = 2.0 * swBHp / 100.0
        float ptsTrend = lagF > lagS and lagUp ? 2.0 : (lagF > lagS or lagUp) ? 1.0 : 0.0
        float rsk = f_clamp(close - (swBLo - slPad * atr), minRisk * atr, maxRisk * atr)
        float sl = close - rsk
        float roomR = na(magUp) ? 1.5 : (magUp - close) / rsk
        float ptsRoom = roomR >= 1.5 ? 2.0 : roomR >= 1.0 ? 1.0 : 0.0
        sigScore := f_clamp(ptsZone + ptsHeat + ptsTrend + ptsRoom, 0.0, 10.0)
        if sigScore >= minScore
            buySig := true
            bool tpMag = not na(magUp) and not magUpFar and roomR >= 1.0 and roomR <= maxRR
            float tp = tpMag ? magUp - 0.1 * atr : close + defRR * rsk
            string tip = f_tip("BUY  score " + str.tostring(sigScore, "0.0") + "/10\nSwept MAGNET ZONE BULLS ★ " + str.tostring(swBSc, "0.0") + " · heat " + str.tostring(swBHp, "0") + " · reclaimed " + str.tostring(swBP, format.mintick) + "\nTrend gate " + (trend == 1 ? "bull" : trend == -1 ? "bear" : "flat") + "\nEntry " + str.tostring(close, format.mintick) + " · SL " + str.tostring(sl, format.mintick) + " · TP " + str.tostring(tp, format.mintick) + " (" + str.tostring((tp - close) / rsk, "0.0") + "R" + (tpMag ? " · MAGNET ↑" : "") + ")")
            live := f_openTk(1, sl, tp, rsk, "▲ BUY " + str.tostring(sigScore, "0.0"), tip)
            tks.push(live)
            swBP := na
    bool sReady = na(live) and not na(swSP) and bar_index - swSBar <= sigWin and close < swSP and (close < open or close < close[1])
    if sReady and bearBias
        float ptsZone  = 4.0 * swSSc / 10.0
        float ptsHeat  = 2.0 * swSHp / 100.0
        float ptsTrend = lagF < lagS and lagDn ? 2.0 : (lagF < lagS or lagDn) ? 1.0 : 0.0
        float rsk = f_clamp((swSHi + slPad * atr) - close, minRisk * atr, maxRisk * atr)
        float sl = close + rsk
        float roomR = na(magDn) ? 1.5 : (close - magDn) / rsk
        float ptsRoom = roomR >= 1.5 ? 2.0 : roomR >= 1.0 ? 1.0 : 0.0
        sigScore := f_clamp(ptsZone + ptsHeat + ptsTrend + ptsRoom, 0.0, 10.0)
        if sigScore >= minScore
            sellSig := true
            bool tpMag = not na(magDn) and not magDnFar and roomR >= 1.0 and roomR <= maxRR
            float tp = tpMag ? magDn + 0.1 * atr : close - defRR * rsk
            string tip = f_tip("SELL  score " + str.tostring(sigScore, "0.0") + "/10\nSwept MAGNET ZONE BEARS ★ " + str.tostring(swSSc, "0.0") + " · heat " + str.tostring(swSHp, "0") + " · reclaimed " + str.tostring(swSP, format.mintick) + "\nTrend gate " + (trend == 1 ? "bull" : trend == -1 ? "bear" : "flat") + "\nEntry " + str.tostring(close, format.mintick) + " · SL " + str.tostring(sl, format.mintick) + " · TP " + str.tostring(tp, format.mintick) + " (" + str.tostring((close - tp) / rsk, "0.0") + "R" + (tpMag ? " · MAGNET ↓" : "") + ")")
            live := f_openTk(-1, sl, tp, rsk, "▼ SELL " + str.tostring(sigScore, "0.0"), tip)
            tks.push(live)
            swSP := na
 
if not na(live) and live.state == 0 and not na(live.eLn)
    int xr = bar_index + 1
    live.eLn.set_x2(xr)
    live.sLn.set_x2(xr)
    live.tLn.set_x2(xr)
    live.rBox.set_right(xr)
    live.pBox.set_right(xr)
while tks.size() > keepTk
    Tk d = tks.shift()
    if not na(d.eLn)
        d.eLn.delete()
        d.sLn.delete()
        d.tLn.delete()
        d.rBox.delete()
        d.pBox.delete()
    if not na(d.sig)
        d.sig.delete()
    if not na(d.out)
        d.out.delete()
 
bool  paintHot = hotCandle and inHotP > 0
color hotC = color.new(inHotS == 1 ? cBull : cBear, math.round(55 - inHotP * 0.4))
plotcandle(paintHot ? open : na, paintHot ? high : na, paintHot ? low : na, paintHot ? close : na, "Hot-zone candles", color=hotC, wickcolor=hotC, bordercolor=hotC, editable=true)
 
f_sideC(int side) =>
    side == 1 ? cBull : cBear
f_fill(float p, int side) =>
    color.new(f_sideC(side), math.round(math.max(fillTransp - p * 0.12, 60)))
f_bord(float p, int side) =>
    showBord ? color.new(f_sideC(side), p >= hotPct ? math.max(bordTransp - 20, 0) : bordTransp) : color(na)
f_pct(float h, float mx) =>
    mx > 0 ? 100 * math.sqrt(math.max(h, 0) / mx) : 0.0
 
var array<box> prof = array.new<box>()
var array<line> mLines = array.new<line>()
var array<label> mLbls = array.new<label>()
 
if barstate.islast and not na(atr)
    bool zonesOn = false
    bool profOn = false
    int x0 = bar_index - 4900
    int xr = bar_index + extRight
    if act.size() > 0
        for i = 0 to act.size() - 1
            MZ z = act.get(i)
            float hp = f_pct(f_heat(z), maxH2)
            float ref = z.side == 1 ? z.top : z.bot
            bool cand = showZ and z.score >= minShow and math.abs(ref - close) <= lim
            int rankSide = 0
            int rankAll = 0
            if cand
                for j = 0 to act.size() - 1
                    if j != i
                        MZ o = act.get(j)
                        float oref = o.side == 1 ? o.top : o.bot
                        bool ocand = o.score >= minShow and math.abs(oref - close) <= lim
                        if ocand and (o.score > z.score or (o.score == z.score and j < i))
                            rankAll += 1
                            if o.side == z.side
                                rankSide += 1
            bool vis = cand and rankSide < maxSide
            if not vis
                f_zDel(z)
                z.bx := na
                z.pLn := na
                z.dLn := na
                z.tag := na
            else
                zonesOn := true
                int xl = math.max(z.born, x0)
                color c = f_sideC(z.side)
                color bd = f_bord(hp, z.side)
                if zoneH > 0
                    f_setBounds(z)
                if na(z.bx)
                    z.bx := box.new(xl, z.top, xr, z.bot, border_color=bd, border_width=1, bgcolor=f_fill(hp, z.side))
                else
                    z.bx.set_lefttop(xl, z.top)
                    z.bx.set_rightbottom(xr, z.bot)
                    z.bx.set_bgcolor(f_fill(hp, z.side))
                    z.bx.set_border_color(bd)
                if showEdge
                    if na(z.pLn)
                        z.pLn := line.new(xl, f_prox(z), xr, f_prox(z), color=color.new(c, 10), width=2)
                        z.dLn := line.new(xl, f_dist(z), xr, f_dist(z), color=color.new(c, 40), style=line.style_dashed)
                    else
                        z.pLn.set_xy1(xl, f_prox(z))
                        z.pLn.set_xy2(xr, f_prox(z))
                        z.dLn.set_xy1(xl, f_dist(z))
                        z.dLn.set_xy2(xr, f_dist(z))
                bool lblOn = showLbl and z.score >= lblMin and rankAll < lblMax
                if lblOn
                    string tx = f_zText(z, hp)
                    if na(z.tag)
                        z.tag := label.new(xr, (z.top + z.bot) / 2, tx, style=label.style_label_right, color=color.new(c, 100), textcolor=color.new(c, 0), size=f_zSize())
                    else
                        z.tag.set_xy(xr, (z.top + z.bot) / 2)
                        z.tag.set_text(tx)
                        z.tag.set_textcolor(color.new(c, 0))
                        z.tag.set_size(f_zSize())
                else if not na(z.tag)
                    z.tag.delete()
                    z.tag := na
    if res.size() > 0
        for i = 0 to res.size() - 1
            MZ z = res.get(i)
            float ref = z.side == 1 ? z.top : z.bot
            bool vis = showSwept and math.abs(ref - close) <= lim and z.endBar > x0
            if not vis
                f_zDel(z)
                z.bx := na
                z.pLn := na
                z.dLn := na
                z.tag := na
            else
                if na(z.bx)
                    z.bx := box.new(math.max(z.born, z.endBar - resBars), z.top, z.endBar, z.bot, border_color=color(na), bgcolor=color.new(cSwept, z.state == 1 ? 80 : 84))
                if showLbl and lblRes and na(z.tag)
                    z.tag := label.new(z.endBar, (z.top + z.bot) / 2, f_zBrief(z), style=label.style_label_right, color=color.new(cSwept, 100), textcolor=color.new(cSwept, 20), size=size.tiny)
    while prof.size() > 0
        prof.shift().delete()
    if showProf and act.size() > 0
        float lo = close - lim
        float binH = 2 * lim / profBins
        array<float> bins = array.new<float>(profBins, 0.0)
        for i = 0 to act.size() - 1
            MZ z = act.get(i)
            float mid = (z.top + z.bot) / 2
            if math.abs(mid - close) <= lim
                int b = math.min(math.max(int(math.floor((mid - lo) / binH)), 0), profBins - 1)
                bins.set(b, bins.get(b) + f_heat(z))
        float bm = bins.max()
        if bm > 0
            int px = xr + 1
            for b = 0 to profBins - 1
                float v = bins.get(b)
                if v > 0
                    float p = f_pct(v, bm)
                    int len = math.max(1, int(math.round(profWidth * p / 100)))
                    profOn := true
                    prof.push(box.new(px, lo + (b + 1) * binH - binH * 0.1, px + len, lo + b * binH + binH * 0.1, border_color=color(na), bgcolor=color.new(f_sideC(lo + (b + 0.5) * binH > close ? -1 : 1), math.round(80 - math.max(p, 20) * 0.6))))
    while mLines.size() > 0
        mLines.shift().delete()
    while mLbls.size() > 0
        mLbls.shift().delete()
    int xm = math.max(profOn ? xr + profWidth + 2 : zonesOn ? xr + 1 : bar_index + 4, bar_index + 6)
    if showMag
        if not na(magUp)
            mLines.push(line.new(bar_index, yUp, xm, yUp, color=cBear, width=1, style=magUpFar ? line.style_dotted : line.style_dashed))
            mLbls.push(label.new(xm, yUp, (magUpFar ? "MAGNET ↑ far " : "MAGNET ↑ ") + str.tostring(magUp, format.mintick) + " · ★" + str.tostring(sUp, "0.0") + " · " + str.tostring(math.abs(magUp - close) / atr, "0.0") + " ATR", style=label.style_label_left, color=cBear, textcolor=color.white, size=size.small))
        if not na(magDn)
            mLines.push(line.new(bar_index, yDn, xm, yDn, color=cBull, width=1, style=magDnFar ? line.style_dotted : line.style_dashed))
            mLbls.push(label.new(xm, yDn, (magDnFar ? "MAGNET ↓ far " : "MAGNET ↓ ") + str.tostring(magDn, format.mintick) + " · ★" + str.tostring(sDn, "0.0") + " · " + str.tostring(math.abs(magDn - close) / atr, "0.0") + " ATR", style=label.style_label_left, color=cBull, textcolor=color.white, size=size.small))
 
alertcondition(sweepBear, "Magnet Zone Bears swept", "Strong Magnet Zones: a BEARS zone was swept on {{ticker}} {{interval}}")
alertcondition(sweepBull, "Magnet Zone Bulls swept", "Strong Magnet Zones: a BULLS zone was swept on {{ticker}} {{interval}}")
alertcondition(testEv,    "Zone tested", "Strong Magnet Zones: a zone was tested on {{ticker}} {{interval}}")
alertcondition(workEv,    "Zone worked", "Strong Magnet Zones: a zone reached its target on {{ticker}} {{interval}}")
alertcondition(magHitUp,  "Magnet above reached", "Strong Magnet Zones: magnet above reached on {{ticker}} {{interval}}")
alertcondition(magHitDn,  "Magnet below reached", "Strong Magnet Zones: magnet below reached on {{ticker}} {{interval}}")
bool nearUpNow = not na(magUp) and magUp - close <= 0.5 * atr
bool nearDnNow = not na(magDn) and close - magDn <= 0.5 * atr
var float lastNearUp = na
var float lastNearDn = na
bool nearUp = conf and nearUpNow and magUp != lastNearUp
bool nearDn = conf and nearDnNow and magDn != lastNearDn
if nearUp
    lastNearUp := magUp
if nearDn
    lastNearDn := magDn
alertcondition(nearUp, "Price near magnet above", "Strong Magnet Zones: {{ticker}} within 0.5 ATR of the magnet above")
alertcondition(nearDn, "Price near magnet below", "Strong Magnet Zones: {{ticker}} within 0.5 ATR of the magnet below")
alertcondition(buySig,  "BUY signal",  "Strong Magnet Zones: BUY signal on {{ticker}} {{interval}} @ {{close}}")
alertcondition(sellSig, "SELL signal", "Strong Magnet Zones: SELL signal on {{ticker}} {{interval}} @ {{close}}")
alertcondition(tkTp, "Ticket TP hit", "Strong Magnet Zones: ticket take-profit hit on {{ticker}} {{interval}}")
alertcondition(tkSl, "Ticket SL hit", "Strong Magnet Zones: ticket stop-loss hit on {{ticker}} {{interval}}")
 
if hotMsg != ""
    alert("Strong Magnet Zones | " + syminfo.ticker + " | hot zone swept: " + hotMsg, alert.freq_once_per_bar_close)
if buySig or sellSig
    alert("Strong Magnet Zones | " + syminfo.ticker + " | " + (buySig ? "BUY" : "SELL") + " signal · score " + str.tostring(sigScore, "0.0") + "/10 @ " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)

← 返回列表