Supply Demand Zones - Fresh, Touched, Broken

Ku_Hero · study · 269 行 · 点赞 88 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// (c) K'u Hero
//@version=6
// Supply Demand Zones - Fresh, Touched, Broken  v1.0
//
// Zone rule (closed bars only, the same rule for the chart timeframe and the optional higher timeframe)
//  - True Range = max(high, previous close) - min(low, previous close)
//  - ATR        = simple average of the True Range of the N bars BEFORE the strong bar (the strong bar is not included)
//  - Strong bar = |close - open| >= X * ATR
//  - Base       = counting back from the bar just before the strong bar, bars with |close - open| <= Y * ATR,
//                 one after another, up to the maximum count. No base bar -> no zone.
//  - Zone edges = highest high / lowest low of the base bars (or highest / lowest open-close with "Bodies only")
//  - Demand     = the strong bar is bullish and closes above the zone top
//    Supply     = the strong bar is bearish and closes below the zone bottom
// State, from the bar after the strong bar
//  - Demand: broken when a bar closes below the bottom, touched when a bar's low reaches the top.
//    Supply: broken when a bar closes above the top,   touched when a bar's high reaches the bottom.
//  - Touch count = bars that entered the zone while the previous bar was outside it. "Fresh" = no touch yet.
// Zones are created and updated only when a bar closes (barstate.isconfirmed). A zone never moves after it is created.
// Higher timeframe zones are requested with [1] and lookahead_on, so only closed higher timeframe bars are used.
// Display only. This is not a buy/sell signal and not a forecast.
indicator("Supply Demand Zones - Fresh, Touched, Broken", shorttitle = "SD Zones", overlay = true, max_boxes_count = 500, max_bars_back = 501)
 
// ---------- Inputs ----------
grpR = "Zone rules"
inAtr     = input.int(14, "ATR period", minval = 2, maxval = 500, group = grpR)
inX       = input.float(1.5, "Strong bar: body >= X * ATR", minval = 0.2, maxval = 20.0, step = 0.1, group = grpR)
inY       = input.float(0.5, "Base bar: body <= Y * ATR (below X)", minval = 0.01, maxval = 10.0, step = 0.05, group = grpR)
inBaseMax = input.int(3, "Base bars: maximum count", minval = 1, maxval = 10, group = grpR)
inEdge    = input.string("Wicks", "Zone edges", options = ["Wicks", "Bodies only"], group = grpR)
inScan    = input.int(5000, "Bars to scan", minval = 300, maxval = 100000, group = grpR)
 
grpD = "Display"
inMaxZ    = input.int(5, "Unbroken zones shown per side", minval = 1, maxval = 50, group = grpD, display = display.none)
inMaxAge  = input.int(1000, "Remove zones older than N bars (0 = never)", minval = 0, maxval = 100000, group = grpD, display = display.none)
inBroken  = input.string("Hide", "Broken zones", options = ["Hide", "Show as grey outline"], group = grpD, display = display.none)
inMaxBrk  = input.int(3, "Broken zones shown per side", minval = 1, maxval = 50, group = grpD, display = display.none)
inExtend  = input.int(10, "Extend unbroken zones to the right by N bars", minval = 0, maxval = 500, group = grpD, display = display.none)
inLabels  = input.bool(true, "Show zone labels", group = grpD, display = display.none)
inLblSize = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = grpD, display = display.none)
inFillT   = input.int(70, "Fill transparency (0-100)", minval = 0, maxval = 100, group = grpD, display = display.none)
cDemF     = input.color(#81C784, "Demand: fresh / touched", group = grpD, inline = "dem", display = display.none)
cDemT     = input.color(#C8E6C9, "", group = grpD, inline = "dem", display = display.none)
cSupF     = input.color(#EF9A9A, "Supply: fresh / touched", group = grpD, inline = "sup", display = display.none)
cSupT     = input.color(#FFCDD2, "", group = grpD, inline = "sup", display = display.none)
cBrk      = input.color(#9E9E9E, "Broken zone color", group = grpD, display = display.none)
inLblAuto = input.bool(true, "Label color: auto", group = grpD, inline = "lbl", display = display.none)
cLbl      = input.color(#606060, "", group = grpD, inline = "lbl", display = display.none)
 
grpH = "Higher timeframe zones (one, optional)"
inHtf     = input.timeframe("", "Higher timeframe (empty = off)", group = grpH)
inHtfMaxZ = input.int(3, "HTF unbroken zones shown per side", minval = 1, maxval = 50, group = grpH, display = display.none)
 
inLang    = input.string("English", "Language / 言語", options = ["English", "日本語"], display = display.none)
 
// ---------- Checks ----------
if not (inY < inX)
    runtime.error("Supply Demand Zones: Y must be below X.")
 
bool useBody  = inEdge == "Bodies only"
bool showBrk  = inBroken == "Show as grey outline"
bool ja       = inLang == "日本語"
bool htfSet   = inHtf != ""
bool htfBad   = htfSet and timeframe.in_seconds(inHtf) <= timeframe.in_seconds(timeframe.period)
bool htfOn    = htfSet and not htfBad
 
// ---------- Zone engine ----------
type Zone
    float top
    float bot
    int   dir      // +1 demand / -1 supply
    int   birth    // bar_index of the strong bar
    int   tFirst   // time of the first base bar
    int   brk      // bar_index of the breaking bar (-1 = not broken)
    int   tBrk     // time of the breaking bar
    int   touch    // touch count
    bool  pin      // previous bar was inside the zone
 
// Processes the current bar when gate is true. Returns the zones that can still be displayed (oldest first).
// Zones older than maxAge bars and broken zones beyond the display limit are dropped; dropping them never changes
// which zones are shown or the state of the remaining zones.
f_engine(bool gate, int start, int atrP, float kx, float ky, int bmax, bool bodyEdge, int maxAge, bool keepBrk, int maxBrk) =>
    var array<Zone> zs = array.new<Zone>()
    float tr = na(close[1]) ? high - low : math.max(high, close[1]) - math.min(low, close[1])
    if gate and bar_index >= start
        int k = bar_index
        // 1) update the existing zones with this closed bar
        for z in zs
            if z.brk < 0
                if z.dir > 0
                    if close < z.bot
                        z.brk  := k
                        z.tBrk := time
                    else
                        bool inz = low <= z.top
                        if inz and not z.pin
                            z.touch += 1
                        z.pin := inz
                else
                    if close > z.top
                        z.brk  := k
                        z.tBrk := time
                    else
                        bool inz = high >= z.bot
                        if inz and not z.pin
                            z.touch += 1
                        z.pin := inz
        // 2) a strong bar makes a new zone
        if k >= start + math.max(atrP + 1, bmax)
            float sum = 0.0
            for j = 1 to atrP
                sum += tr[j]
            float atr = sum / atrP
            float body = math.abs(close - open)
            if atr > 0 and body >= kx * atr
                int nb = 0
                for j = 1 to bmax
                    if math.abs(close[j] - open[j]) <= ky * atr
                        nb += 1
                    else
                        break
                if nb > 0
                    float zt = na
                    float zb = na
                    for j = 1 to nb
                        float up = bodyEdge ? math.max(open[j], close[j]) : high[j]
                        float dn = bodyEdge ? math.min(open[j], close[j]) : low[j]
                        zt := na(zt) or up > zt ? up : zt
                        zb := na(zb) or dn < zb ? dn : zb
                    if zt > zb
                        int d = close > open and close > zt ? 1 : close < open and close < zb ? -1 : 0
                        if d != 0
                            zs.push(Zone.new(zt, zb, d, k, time[nb], -1, 0, 0, false))
        // 3) drop zones that can never be displayed again
        if maxAge > 0
            while zs.size() > 0 and k - zs.get(0).birth > maxAge
                zs.shift()
        int n = zs.size()
        if n > 0
            int bD = 0
            int bS = 0
            for i = n - 1 to 0
                Zone z = zs.get(i)
                if z.brk >= 0
                    if not keepBrk
                        zs.remove(i)
                    else if z.dir > 0
                        if bD >= maxBrk
                            zs.remove(i)
                        else
                            bD += 1
                    else
                        if bS >= maxBrk
                            zs.remove(i)
                        else
                            bS += 1
    zs
 
// Higher timeframe: a deep copy per bar so that [1] returns the state of the previous (closed) HTF bar.
f_htfCopy(int atrP, float kx, float ky, int bmax, bool bodyEdge, int maxAge, bool keepBrk, int maxBrk) =>
    array<Zone> src = f_engine(barstate.isconfirmed, 0, atrP, kx, ky, bmax, bodyEdge, maxAge, keepBrk, maxBrk)
    array<Zone> out = array.new<Zone>()
    for z in src
        out.push(z.copy())
    out
 
// ---------- Chart timeframe ----------
var int scanStart = math.max(0, last_bar_index - inScan)
array<Zone> cz = f_engine(barstate.isconfirmed, scanStart, inAtr, inX, inY, inBaseMax, useBody, inMaxAge, showBrk, inMaxBrk)
 
// ---------- Higher timeframe ----------
array<Zone> hz = na
if htfOn
    hz := request.security(syminfo.tickerid, inHtf, f_htfCopy(inAtr, inX, inY, inBaseMax, useBody, inMaxAge, showBrk, inMaxBrk)[1], lookahead = barmerge.lookahead_on)
 
// ---------- Data window: newest unbroken zone of each side (chart timeframe) ----------
// Each bar holds the zones as known at the close of the last processed bar; the forming bar repeats the last closed bar.
f_latest(array<Zone> zs, int d) =>
    Zone r = na
    int n = zs.size()
    if n > 0
        for i = n - 1 to 0
            Zone z = zs.get(i)
            if z.dir == d and z.brk < 0
                r := z
                break
    r
Zone lD = f_latest(cz, 1)
Zone lS = f_latest(cz, -1)
plot(na(lD) ? na : lD.top, "Demand zone top", display = display.data_window)
plot(na(lD) ? na : lD.bot, "Demand zone bottom", display = display.data_window)
plot(na(lD) ? na : lD.touch, "Demand zone touches", display = display.data_window)
plot(na(lS) ? na : lS.top, "Supply zone top", display = display.data_window)
plot(na(lS) ? na : lS.bot, "Supply zone bottom", display = display.data_window)
plot(na(lS) ? na : lS.touch, "Supply zone touches", display = display.data_window)
 
// ---------- Drawing (last bar only) ----------
f_tfName(string tf) =>
    int s = timeframe.in_seconds(tf)
    s >= 2419200 ? str.tostring(math.round(s / 2628003.0)) + "M" : s >= 604800 ? str.tostring(s / 604800) + "W" : s >= 86400 ? str.tostring(s / 86400) + "D" : s >= 3600 ? str.tostring(s / 3600) + "H" : s >= 60 ? str.tostring(s / 60) + "m" : str.tostring(s) + "s"
 
f_label(Zone z, string pre) =>
    string side = z.dir > 0 ? (ja ? "需要" : "Demand") : (ja ? "供給" : "Supply")
    string st = z.brk >= 0 ? (ja ? " ブレイク済" : " broken") : z.touch == 0 ? (ja ? " 未接触" : " fresh") : (ja ? " 接触" + str.tostring(z.touch) + "回" : " touched " + str.tostring(z.touch))
    pre + side + st
 
f_txtSize() =>
    inLblSize == "Tiny" ? size.tiny : inLblSize == "Normal" ? size.normal : size.small
 
// auto = the chart's own text color, so labels stay readable on light and dark backgrounds
f_lblColor() =>
    inLblAuto ? chart.fg_color : cLbl
 
// Draws the newest maxU unbroken and maxB broken zones per side (oldest first, so newer zones are on top).
f_drawSet(array<Zone> zs, bool isHtf, int maxU, int rightT, int htfMs, string pre, array<box> store) =>
    int n = zs.size()
    array<int> pick = array.new<int>()
    if n > 0
        int uD = 0
        int uS = 0
        int bD = 0
        int bS = 0
        for i = n - 1 to 0
            Zone z = zs.get(i)
            bool dem = z.dir > 0
            if z.brk < 0
                if dem and uD < maxU
                    uD += 1
                    pick.push(i)
                else if not dem and uS < maxU
                    uS += 1
                    pick.push(i)
            else if showBrk
                if dem and bD < inMaxBrk
                    bD += 1
                    pick.push(i)
                else if not dem and bS < inMaxBrk
                    bS += 1
                    pick.push(i)
    int m = pick.size()
    if m > 0
        color lc = f_lblColor()
        for q = m - 1 to 0
            Zone z = zs.get(pick.get(q))
            bool broken = z.brk >= 0
            color col = broken ? cBrk : z.dir > 0 ? (z.touch == 0 ? cDemF : cDemT) : (z.touch == 0 ? cSupF : cSupT)
            int r = broken ? (isHtf ? z.tBrk + htfMs : z.tBrk) : rightT
            bool fill = not broken and not isHtf
            store.push(box.new(z.tFirst, z.top, r, z.bot, xloc = xloc.bar_time, border_color = col, border_width = isHtf ? 2 : 1,
                 bgcolor = fill ? color.new(col, inFillT) : color.new(col, 100),
                 text = inLabels ? f_label(z, pre) : "", text_size = f_txtSize(), text_color = lc,
                 text_halign = text.align_left, text_valign = text.align_top))
 
var array<box> boxes = array.new<box>()
var table msgTbl = table.new(position.bottom_left, 1, 1, border_width = 0)
if barstate.islast
    for b in boxes
        b.delete()
    boxes.clear()
    int tfMs = timeframe.in_seconds(timeframe.period) * 1000
    int rightT = time + inExtend * tfMs
    if htfOn and not na(hz)
        f_drawSet(hz, true, inHtfMaxZ, rightT, timeframe.in_seconds(inHtf) * 1000, f_tfName(inHtf) + " ", boxes)
    f_drawSet(cz, false, inMaxZ, rightT, 0, "", boxes)
    string msg = htfBad ? (ja ? "SDZ: 上位足はチャートの足より長くしてください" : "SDZ: higher timeframe must be above the chart timeframe") : htfOn and na(hz) ? (ja ? "SDZ: 上位足のデータを読み込み中" : "SDZ: loading higher timeframe data") : ""
    if msg != ""
        table.cell(msgTbl, 0, 0, msg, text_color = color.rgb(255, 69, 0), text_size = size.small)
    else
        table.clear(msgTbl, 0, 0)

← 返回列表