W/D Body S/R + PDH/PDL PWH/PWL [DAVIES T]

DAVIES_T · study · 259 行 · 点赞 3 · TradingView 原页

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

Pine Script

//@version=6
indicator("W/D Body S/R + PDH/PDL PWH/PWL [DAVIES T]", "Body S/R [DAVIES T]", overlay = true, max_lines_count = 500, max_labels_count = 500)
 
// ============================== GENERAL ==============================
string G0 = "General"
srcMode    = input.string("Body", "Level Source", options = ["Body", "Wick"], group = G0, tooltip = "Body = levels from open/close only (wicks ignored). Wick = levels from high/low.")
edgeMode   = input.string("Both", "Body Edge", options = ["Both", "Close Only", "Open Only"], group = G0, tooltip = "Body mode only. Both = top and bottom of every body.")
showSup    = input.bool(true, "Show Support (below price)", group = G0)
showRes    = input.bool(true, "Show Resistance (above price)", group = G0)
brokenMode = input.string("Show", "Body-Crossed Levels", options = ["Show", "Dim", "Hide"], group = G0, tooltip = "Crossed = a LATER candle of the same timeframe has its BODY pass through the level. Show (default) keeps them as normal levels and targets - old body levels often get revisited. Dim/Hide treat them as spent.")
mergePct   = input.float(0.05, "Merge Levels Within %", minval = 0.0, step = 0.01, group = G0, tooltip = "Levels closer than this are merged into one (e.g. close of one candle and open of the next).")
maxSide    = input.int(5, "Levels Each Side (0 = all)", minval = 0, group = G0, tooltip = "Nearest N levels above price (resistance) AND nearest N below price (support / future targets), per timeframe.")
showLbl    = input.bool(true, "Show Labels", group = G0)
showPx     = input.bool(true, "Price In Label", group = G0)
lblOff     = input.int(5, "Label Offset (bars)", minval = 0, group = G0)
tgtSide    = input.string("Support", "Target Tag Side", options = ["Support", "Resistance", "Both", "None"], group = G0, tooltip = "Tags the nearest unbroken level on that side with the Target Text.")
 
// ============================== WEEKLY ==============================
string GW = "Weekly"
wOn  = input.bool(true, "Show Weekly", group = GW)
wN   = input.int(150, "Lookback (candles)", minval = 1, maxval = 500, group = GW, tooltip = "How far back to scan for levels. Keep it large so untested levels further away (future targets) are found.")
wSup = input.color(color.lime, "Support", group = GW, inline = "wc")
wRes = input.color(color.red, "Resistance", group = GW, inline = "wc")
wWid = input.int(2, "Width", minval = 1, maxval = 5, group = GW, inline = "ws")
wSty = input.string("Solid", "Style", options = ["Solid", "Dashed", "Dotted"], group = GW, inline = "ws")
wPre = input.string("W", "Label Prefix", group = GW)
wTgt = input.string("weekly target", "Target Text", group = GW)
 
// ============================== DAILY ==============================
string GD = "Daily"
dOn  = input.bool(true, "Show Daily", group = GD)
dN   = input.int(150, "Lookback (candles)", minval = 1, maxval = 500, group = GD, tooltip = "How far back to scan for levels. Keep it large so untested levels further away (future targets) are found.")
dSup = input.color(color.aqua, "Support", group = GD, inline = "dc")
dRes = input.color(color.orange, "Resistance", group = GD, inline = "dc")
dWid = input.int(1, "Width", minval = 1, maxval = 5, group = GD, inline = "ds")
dSty = input.string("Dashed", "Style", options = ["Solid", "Dashed", "Dotted"], group = GD, inline = "ds")
dPre = input.string("D", "Label Prefix", group = GD)
dTgt = input.string("daily target", "Target Text", group = GD)
 
// ============================== PREV DAY / WEEK ==============================
string GP = "Previous Day / Week High-Low"
showPD = input.bool(true, "Show PDH / PDL", group = GP, inline = "pd")
pdCol  = input.color(color.yellow, "", group = GP, inline = "pd")
showPW = input.bool(true, "Show PWH / PWL", group = GP, inline = "pw")
pwCol  = input.color(color.fuchsia, "", group = GP, inline = "pw")
pWid   = input.int(1, "Width", minval = 1, maxval = 5, group = GP, inline = "ps")
pSty   = input.string("Dotted", "Style", options = ["Solid", "Dashed", "Dotted"], group = GP, inline = "ps")
pOff   = input.int(20, "Label Offset (bars)", minval = 0, group = GP, tooltip = "Kept further right than the S/R labels so they do not overlap.")
 
// ============================== TYPES / HELPERS ==============================
type Lvl
    float px
    int   t
    bool  broken
 
f_style(string s) =>
    s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
 
tfOK(string tf) =>
    timeframe.in_seconds() <= timeframe.in_seconds(tf)
 
// Tracks completed candles of tf on the chart itself (index 0 = most recent completed).
// O(1) per bar, so long lookbacks stay fast. History is limited to what the chart has loaded.
f_track(string tf, int cap) =>
    var float[] o = array.new<float>()
    var float[] c = array.new<float>()
    var float[] h = array.new<float>()
    var float[] l = array.new<float>()
    var int[]   t = array.new<int>()
    var float co = na
    var float ch = na
    var float cl = na
    var float cc = na
    var int   ct = na
    if timeframe.change(tf) or na(co)
        if not na(co)
            o.unshift(co)
            c.unshift(cc)
            h.unshift(ch)
            l.unshift(cl)
            t.unshift(ct)
            while o.size() > cap
                o.pop()
                c.pop()
                h.pop()
                l.pop()
                t.pop()
        co := open
        ch := high
        cl := low
        ct := time
    else
        ch := math.max(ch, high)
        cl := math.min(cl, low)
    cc := close
    [o, c, h, l, t]
 
[wO, wC, wH, wL, wT] = f_track("W", wN)
[dO, dC, dH, dL, dT] = f_track("D", dN)
 
// Previous completed day / week high-low (wick based by definition, non-repainting)
[pdh, pdl, pdt] = request.security(syminfo.tickerid, "D", [high[1], low[1], time[1]], lookahead = barmerge.lookahead_on)
[pwh, pwl, pwt] = request.security(syminfo.tickerid, "W", [high[1], low[1], time[1]], lookahead = barmerge.lookahead_on)
 
// Broken if any NEWER candle's body straddles the level
f_broken(float[] o, float[] c, int i, float px) =>
    bool b = false
    if i > 0 and not na(px)
        for j = 0 to i - 1
            float bt = math.max(o.get(j), c.get(j))
            float bb = math.min(o.get(j), c.get(j))
            if not na(bt) and px > bb and px < bt
                b := true
                break
    b
 
f_add(Lvl[] lv, float px, int t, bool brk) =>
    if not na(px)
        bool found = false
        if lv.size() > 0
            for k = 0 to lv.size() - 1
                Lvl e = lv.get(k)
                if math.abs(e.px - px) <= math.abs(px) * mergePct / 100.0
                    found := true
                    e.t := math.min(e.t, t)
                    e.broken := e.broken and brk
                    break
        if not found
            lv.push(Lvl.new(px, t, brk))
    lv
 
f_build(float[] o, float[] c, float[] h, float[] l, int[] t) =>
    Lvl[] lv = array.new<Lvl>()
    int sz = o.size()
    if sz > 0
        for i = 0 to sz - 1
            float oo = o.get(i)
            float cc = c.get(i)
            if not na(oo) and not na(cc)
                float a = na
                float b = na
                if srcMode == "Wick"
                    a := h.get(i)
                    b := l.get(i)
                else if edgeMode == "Close Only"
                    a := cc
                else if edgeMode == "Open Only"
                    a := oo
                else
                    a := math.max(oo, cc)
                    b := math.min(oo, cc)
                int ti = t.get(i)
                f_add(lv, a, ti, f_broken(o, c, i, a))
                if not na(b)
                    f_add(lv, b, ti, f_broken(o, c, i, b))
    lv
 
// ============================== DRAWING ==============================
var line[]  gL = array.new<line>()
var label[] gB = array.new<label>()
 
f_clear() =>
    while gL.size() > 0
        line.delete(gL.pop())
    while gB.size() > 0
        label.delete(gB.pop())
    true
 
// Draws one side (support or resistance) of one tier, returns nearest unbroken level
f_side(Lvl[] lv, bool isSup, color col0, int wid, string sty, string pre, string tgt, bool doTgt) =>
    float nearest = na
    float[] key  = array.new<float>()
    Lvl[]   pick = array.new<Lvl>()
    if lv.size() > 0
        for k = 0 to lv.size() - 1
            Lvl e = lv.get(k)
            bool below = e.px < close
            if below == isSup and not (e.broken and brokenMode == "Hide")
                pick.push(e)
                key.push(e.px)
    if pick.size() > 0
        int[] idx = key.sort_indices(isSup ? order.descending : order.ascending)
        int lim = maxSide > 0 ? math.min(maxSide, pick.size()) : pick.size()
        int msBar = timeframe.in_seconds() * 1000
        bool tagged = false
        for n = 0 to lim - 1
            Lvl e = pick.get(idx.get(n))
            bool brk = e.broken and brokenMode != "Show"
            bool dim = brk
            color col = dim ? color.new(col0, 75) : color.new(col0, 0)
            gL.push(line.new(e.t, e.px, time, e.px, xloc.bar_time, extend.right, col, f_style(sty), wid))
            bool isTgt = doTgt and not tagged and not brk
            if not brk and na(nearest)
                nearest := e.px
            if isTgt
                tagged := true
            if showLbl
                string txt = isTgt ? tgt : pre + (isSup ? " S" : " R") + (brk ? " x" : "")
                if showPx
                    txt += "  " + str.tostring(e.px, format.mintick)
                gB.push(label.new(time + lblOff * msBar, e.px, txt, xloc.bar_time, yloc.price, color(na), label.style_label_left, col, size.small))
    nearest
 
f_pline(float px, int t0, color col0, string txt) =>
    if not na(px) and not na(t0) and t0 < time
        color col = color.new(col0, 0)
        gL.push(line.new(t0, px, time, px, xloc.bar_time, extend.right, col, f_style(pSty), pWid))
        if showLbl
            string tx = showPx ? txt + "  " + str.tostring(px, format.mintick) : txt
            gB.push(label.new(time + pOff * timeframe.in_seconds() * 1000, px, tx, xloc.bar_time, yloc.price, color(na), label.style_label_left, col, size.small))
    true
 
// ============================== MAIN ==============================
bool tagSup = tgtSide == "Support" or tgtSide == "Both"
bool tagRes = tgtSide == "Resistance" or tgtSide == "Both"
 
var float wNS = na
var float wNR = na
var float dNS = na
var float dNR = na
 
if barstate.islast
    // Alerts: body close through the nearest level from the previous bar
    if barstate.isrealtime and barstate.isconfirmed
        if not na(wNS) and close < wNS
            alert("Weekly support " + str.tostring(wNS, format.mintick) + " lost on body close", alert.freq_once_per_bar_close)
        if not na(wNR) and close > wNR
            alert("Weekly resistance " + str.tostring(wNR, format.mintick) + " broken on body close", alert.freq_once_per_bar_close)
        if not na(dNS) and close < dNS
            alert("Daily support " + str.tostring(dNS, format.mintick) + " lost on body close", alert.freq_once_per_bar_close)
        if not na(dNR) and close > dNR
            alert("Daily resistance " + str.tostring(dNR, format.mintick) + " broken on body close", alert.freq_once_per_bar_close)
 
    f_clear()
    wNS := na
    wNR := na
    dNS := na
    dNR := na
 
    if wOn and tfOK("W")
        Lvl[] wLv = f_build(wO, wC, wH, wL, wT)
        if showSup
            wNS := f_side(wLv, true, wSup, wWid, wSty, wPre, wTgt, tagSup)
        if showRes
            wNR := f_side(wLv, false, wRes, wWid, wSty, wPre, wTgt, tagRes)
 
    if dOn and tfOK("D")
        Lvl[] dLv = f_build(dO, dC, dH, dL, dT)
        if showSup
            dNS := f_side(dLv, true, dSup, dWid, dSty, dPre, dTgt, tagSup)
        if showRes
            dNR := f_side(dLv, false, dRes, dWid, dSty, dPre, dTgt, tagRes)
 
    if showPD and tfOK("D")
        f_pline(pdh, pdt, pdCol, "PDH")
        f_pline(pdl, pdt, pdCol, "PDL")
    if showPW and tfOK("W")
        f_pline(pwh, pwt, pwCol, "PWH")
        f_pline(pwl, pwt, pwCol, "PWL")

← 返回列表