Zone Master [SimpleAlgo]

SimpleAlgoAI · study · 419 行 · 点赞 323 · TradingView 原页

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

Pine Script

//@version=6
// Zone Master
//
// Supply and demand zones, kept honest. A zone is the quiet base price left in a hurry: a
// handful of bars that stayed inside a couple of ATRs, followed by a departure of a few ATRs
// within a few bars. The base is where the orders that drove the move were filled, and what is
// left of them waits there. Each zone knows how fast price left it, how many times it has been
// tested, and how much of it has been spent: as price trades back into a zone it melts from the
// edge price meets first, and a close beyond the far edge ends it. The base is drawn as a pad
// with its departure written on it, a launch line runs from the pad to where the departure
// ended, and the zone glows at its near edge and fades toward the far one. The panel names the
// nearest demand and supply, and keeps the score of what happened on this chart the last ten
// times a zone was tested.
//
// The zones do the drawing, the panel does the words, the alerts carry the events.
 
indicator("Zone Master [SimpleAlgo]", "Zone Master [SimpleAlgo]", overlay = true, max_bars_back = 500, max_boxes_count = 150, max_labels_count = 60, max_lines_count = 80)
 
// ───────────────────────── Settings ─────────────────────────
 
grpZ = "Zones"
baseATR  = input.float(2.0, "Base no taller than (ATR)", minval = 0.5, maxval = 5, step = 0.1, group = grpZ, tooltip = "The base is the quiet part. It can be any length from the shortest to the longest below, as long as its whole range stays inside this many ATRs.")
depATR   = input.float(2.5, "Departure of at least (ATR)", minval = 1, maxval = 8, step = 0.1, group = grpZ, tooltip = "How far price has to travel away from the base, from the base's edge to a close, to make it a zone.")
lookIn   = input.int(8, "Departure within (bars)", minval = 2, maxval = 30, group = grpZ, tooltip = "The departure has to happen within this many bars of the base ending. A slow drift away is not a departure.")
minBase  = input.int(4, "Shortest base (bars)", minval = 2, maxval = 20, group = grpZ)
maxBase  = input.int(12, "Longest base (bars)", minval = 3, maxval = 40, group = grpZ)
maxTests = input.int(4, "Retire after (tests)", minval = 1, maxval = 20, group = grpZ, tooltip = "A zone weakens every time price comes back to it. After this many tests it is retired, whatever is left of it.")
keepIn   = input.int(2000, "Zones age out after (bars)", minval = 200, maxval = 5000, step = 100, group = grpZ, tooltip = "A zone this old is dropped even if price never came back to it.")
 
grpL = "Look"
drawN    = input.int(3, "Zones to draw, each side", minval = 1, maxval = 6, group = grpL, tooltip = "The nearest zones above price and the nearest below. The rest are tracked but not drawn.")
reachIn  = input.float(20, "Within (ATR)", minval = 2, maxval = 100, step = 1, group = grpL, tooltip = "Zones further from price than this are tracked but not drawn, so an old zone far away does not stretch the chart.")
extendIn = input.int(12, "Extend right (bars)", minval = 0, maxval = 100, group = grpL)
themeIn  = input.string("Mint and Pink", "Colours", options = ["Mint and Pink", "Ice", "Neon", "Custom"], group = grpL)
cDemIn   = input.color(#00FFA3, "", group = grpL, inline = "c")
cSupIn   = input.color(#FF3D71, "", group = grpL, inline = "c")
brightIn = input.int(3, "Brightness", minval = 1, maxval = 5, group = grpL)
showLab  = input.bool(true, "Names", group = grpL, inline = "n")
showEdge = input.bool(true, "Edges", group = grpL, inline = "n")
showLaunch = input.bool(true, "Launch lines", group = grpL, inline = "n", tooltip = "The pad over the base bars with the departure written on it, and the line from the base to where the departure ended: the move that made the zone.")
showPanel = input.bool(true, "Panel", group = grpL, inline = "p")
panelPos  = input.string("Top right", "", options = ["Top left", "Top right", "Bottom left", "Bottom right"], group = grpL, inline = "p")
panelSize = input.string("Normal", "", options = ["Small", "Normal", "Large"], group = grpL, inline = "p")
 
[colDem, colSup] = switch themeIn
    "Mint and Pink" => [#00FFA3, #FF3D71]
    "Ice"           => [#7DD3FC, #FFFFFF]
    "Neon"          => [#FFFFFF, #D946EF]
    => [cDemIn, cSupIn]
color colPanel = #262B38
 
// fixed rules
int   dupBars  = 15     // a base within this many bars of another zone at the same price is the same zone
int   recN     = 10     // tests remembered
int   deadKeep = 60     // a broken zone is remembered this long, so its base cannot come back as a new zone
 
// ───────────────────────── The zones ─────────────────────────
// one row per zone: side (1 demand, -1 supply), base start, top, bottom, departure in ATRs,
// how far price has eaten into it, tests, the bar it was born, alive, and whether price is in it
 
var zSide  = array.new_int()
var zStart = array.new_int()
var zTop   = array.new_float()
var zBot   = array.new_float()
var zStr   = array.new_float()
var zExt   = array.new_float()
var zTests = array.new_int()
var zBorn  = array.new_int()
var zAlive = array.new_bool()
var zIn    = array.new_bool()
var zBase  = array.new_int()
var zDepP  = array.new_float()
var recHeld = array.new_bool()
 
float atr = ta.atr(14)
 
removeZone(int j) =>
    array.remove(zSide, j)
    array.remove(zStart, j)
    array.remove(zTop, j)
    array.remove(zBot, j)
    array.remove(zStr, j)
    array.remove(zExt, j)
    array.remove(zTests, j)
    array.remove(zBorn, j)
    array.remove(zAlive, j)
    array.remove(zIn, j)
    array.remove(zBase, j)
    array.remove(zDepP, j)
    true
 
addZone(int side, int start, float top, float bot, float dep, int baseLen) =>
    array.push(zSide, side)
    array.push(zStart, start)
    array.push(zTop, top)
    array.push(zBot, bot)
    array.push(zStr, dep)
    array.push(zExt, side == 1 ? top : bot)
    array.push(zTests, 0)
    array.push(zBorn, bar_index)
    array.push(zAlive, true)
    array.push(zIn, false)
    array.push(zBase, baseLen)
    array.push(zDepP, close)
    true
 
noteTest(bool held) =>
    array.push(recHeld, held)
    if array.size(recHeld) > recN
        array.shift(recHeld)
    true
 
// ───────────────────────── Finding them ─────────────────────────
// on every closed bar: is this close a departure from a quiet base that ended a few bars ago?
// For each possible base end, the base grows backwards one bar at a time while it stays quiet,
// and the longest quiet base is the zone
 
bool newDemand = false
bool newSupply = false
if barstate.isconfirmed and not na(atr) and bar_index > lookIn + maxBase + 2
    for d = 1 to lookIn
        float hmax = -1e308
        float lmin = 1e308
        int   bestL = na
        float bestH = na
        float bestL_ = na
        for L = 1 to maxBase
            int k = d + L                       // the base bar L bars before the departure window
            hmax := math.max(hmax, high[k])
            lmin := math.min(lmin, low[k])
            if hmax - lmin > baseATR * atr
                break
            if L >= minBase
                bestL := L
                bestH := hmax
                bestL_ := lmin
        if not na(bestL)
            float up = close - bestH
            float dn = bestL_ - close
            int side = up >= depATR * atr and up >= dn ? 1 : dn >= depATR * atr ? -1 : 0
            if side != 0
                int start = bar_index - d - bestL
                float dep = (side == 1 ? up : dn) / atr
                // the same base again? then it is the same zone, keep the bigger departure
                bool dup = false
                int n = array.size(zSide)
                if n > 0
                    for j = 0 to n - 1
                        float zt = array.get(zTop, j)
                        float zb = array.get(zBot, j)
                        bool overlap = bestH > zb and bestL_ < zt
                        bool sameBase = overlap and math.abs(start - array.get(zStart, j)) <= dupBars
                        // the same price again on the same side, and the old zone still alive: one zone, not two
                        bool samePrice = overlap and array.get(zSide, j) == side and array.get(zAlive, j) and (math.min(bestH, zt) - math.max(bestL_, zb)) >= 0.5 * math.min(bestH - bestL_, zt - zb)
                        if sameBase or samePrice
                            dup := true
                            if array.get(zSide, j) == side and array.get(zAlive, j)
                                array.set(zStr, j, math.max(array.get(zStr, j), dep))
                if not dup
                    addZone(side, start, bestH, bestL_, dep, bestL)
                    if side == 1
                        newDemand := true
                    else
                        newSupply := true
 
// ───────────────────────── Spending them ─────────────────────────
// every bar, every living zone: price trading into it spends it as far as it reached, leaving
// it is a test held, a close beyond the far edge breaks it
 
bool demandReached = false
bool supplyReached = false
bool zoneHeld = false
bool zoneBroke = false
int nz = array.size(zSide)
if nz > 0
    for j = nz - 1 to 0
        if array.get(zAlive, j)
            int side = array.get(zSide, j)
            float top = array.get(zTop, j)
            float bot = array.get(zBot, j)
            bool inside = array.get(zIn, j)
            if array.get(zBorn, j) < bar_index
                if side == 1
                    if low < top
                        array.set(zExt, j, math.min(array.get(zExt, j), low))
                        if not inside
                            array.set(zTests, j, array.get(zTests, j) + 1)
                            demandReached := true
                        array.set(zIn, j, true)
                    else
                        if inside
                            noteTest(true)
                            zoneHeld := true
                            if array.get(zTests, j) >= maxTests        // worn out, retired after this hold
                                array.set(zAlive, j, false)
                        array.set(zIn, j, false)
                    if close < bot or array.get(zExt, j) <= bot        // a close beyond it, or every last bit of it traded through
                        array.set(zAlive, j, false)
                        noteTest(false)
                        zoneBroke := true
                else
                    if high > bot
                        array.set(zExt, j, math.max(array.get(zExt, j), high))
                        if not inside
                            array.set(zTests, j, array.get(zTests, j) + 1)
                            supplyReached := true
                        array.set(zIn, j, true)
                    else
                        if inside
                            noteTest(true)
                            zoneHeld := true
                            if array.get(zTests, j) >= maxTests
                                array.set(zAlive, j, false)
                        array.set(zIn, j, false)
                    if close > top or array.get(zExt, j) >= top
                        array.set(zAlive, j, false)
                        noteTest(false)
                        zoneBroke := true
            if bar_index - array.get(zBorn, j) > keepIn
                array.set(zAlive, j, false)
        else if bar_index - array.get(zBorn, j) > deadKeep
            removeZone(j)
 
// ───────────────────────── The readings ─────────────────────────
 
int   nearDem = na
int   nearSup = na
int   inZone  = na
float bestDem = -1e308
float bestSup = 1e308
nz := array.size(zSide)
if nz > 0
    for j = 0 to nz - 1
        if array.get(zAlive, j)
            float top = array.get(zTop, j)
            float bot = array.get(zBot, j)
            int side = array.get(zSide, j)
            if close >= bot and close <= top
                inZone := j
            if side == 1 and top <= close and top > bestDem
                bestDem := top
                nearDem := j
            if side == -1 and bot >= close and bot < bestSup
                bestSup := bot
                nearSup := j
 
int held = 0
int nRec = array.size(recHeld)
if nRec > 0
    for k = 0 to nRec - 1
        if array.get(recHeld, k)
            held += 1
 
// ───────────────────────── Drawing ─────────────────────────
 
var boxes = array.new<box>()
var labs  = array.new<label>()
var edges = array.new<line>()
 
clearAll() =>
    for b in boxes
        box.delete(b)
    for l in labs
        label.delete(l)
    for e in edges
        line.delete(e)
    array.clear(boxes)
    array.clear(labs)
    array.clear(edges)
    true
 
fmtP(float x) =>
    syminfo.mintick >= 1 ? str.tostring(x, "#,##0") : syminfo.mintick >= 0.01 ? str.tostring(x, "#,##0.00") : str.tostring(x, format.mintick)
 
zoneTxt(int j) =>
    float top = array.get(zTop, j)
    float bot = array.get(zBot, j)
    int side = array.get(zSide, j)
    float edge = side == 1 ? top : bot
    float dAtr = math.abs(close - edge) / atr
    fmtP(bot) + " to " + fmtP(top) + ", " + str.tostring(dAtr, "0.0") + " ATR " + (side == 1 ? "below" : "above") + ", " + str.tostring(array.get(zStr, j), "0.0") + " ATR departure, " + (array.get(zTests, j) == 0 ? "fresh" : "tested " + str.tostring(array.get(zTests, j)) + "x")
 
if barstate.islast
    clearAll()
    // the nearest zones to price, up to drawN
    int n = array.size(zSide)
    if n > 0
        order = array.new_int()
        dist  = array.new_float()
        for j = 0 to n - 1
            if array.get(zAlive, j)
                float mid = (array.get(zTop, j) + array.get(zBot, j)) / 2
                if math.abs(close - mid) <= reachIn * atr
                    array.push(order, j)
                    array.push(dist, math.abs(close - mid))
        int m = array.size(order)
        if m > 0
            // sort by distance, simple insertion since m is small
            for a = 1 to m - 1
                int ja = array.get(order, a)
                float da = array.get(dist, a)
                int b = a - 1
                bool go = true
                while go and b >= 0
                    if array.get(dist, b) > da
                        array.set(order, b + 1, array.get(order, b))
                        array.set(dist, b + 1, array.get(dist, b))
                        b -= 1
                    else
                        go := false
                array.set(order, b + 1, ja)
                array.set(dist, b + 1, da)
            // the nearest drawN above price and the nearest drawN below
            int upN = 0
            int dnN = 0
            for a = 0 to m - 1
                int j = array.get(order, a)
                int side = array.get(zSide, j)
                float midj = (array.get(zTop, j) + array.get(zBot, j)) / 2
                bool abovePx = midj >= close
                if abovePx
                    upN += 1
                else
                    dnN += 1
                if (abovePx and upN > drawN) or (not abovePx and dnN > drawN)
                    continue
                float top = array.get(zTop, j)
                float bot = array.get(zBot, j)
                float ext = array.get(zExt, j)
                float dep = array.get(zStr, j)
                int tests = array.get(zTests, j)
                int start = array.get(zStart, j)
                int baseLen = array.get(zBase, j)
                int x0 = math.max(start, bar_index - 4800)
                int x1 = bar_index + extendIn
                int xEnd = x1 + 12
                color col = side == 1 ? colDem : colSup
                bool fresh = tests == 0
                float bright = 0.6 + 0.2 * brightIn
                // what is left of the zone, and what price has already traded through
                float uTop = side == 1 ? ext : top
                float uBot = side == 1 ? bot : ext
                float sTop = side == 1 ? top : ext
                float sBot = side == 1 ? ext : bot
                float alph = (0.10 + 0.10 * math.min(dep / 4, 1)) * bright
                if uTop > uBot
                    // the ingot: five slabs, bright at the edge price meets first, faint at the far edge
                    for k = 0 to 4
                        float y0 = uBot + (uTop - uBot) * k / 5
                        float y1 = uBot + (uTop - uBot) * (k + 1) / 5
                        float t = side == 1 ? (k + 0.5) / 5 : 1 - (k + 0.5) / 5     // 1 at the near edge
                        float ak = alph * (0.25 + 0.75 * t)
                        array.push(boxes, box.new(x0, y1, x1, y0, xloc = xloc.bar_index, border_width = 0, bgcolor = color.new(col, int(math.round(100 - 100 * ak)))))
                    // it dissolves into the future instead of ending in a wall
                    for k = 0 to 2
                        array.push(boxes, box.new(x1 + k * 4, uTop, x1 + (k + 1) * 4, uBot, xloc = xloc.bar_index, border_width = 0, bgcolor = color.new(col, int(math.round(100 - 100 * alph * 0.5 * (0.6 - 0.2 * k))))))
                if sTop > sBot
                    array.push(boxes, box.new(x0, sTop, x1, sBot, xloc = xloc.bar_index, border_width = 0, bgcolor = color.new(col, 97)))
                if showEdge
                    float near = ext
                    float far = side == 1 ? bot : top
                    if uTop > uBot
                        array.push(edges, line.new(x0, near, xEnd, near, xloc = xloc.bar_index, color = color.new(col, fresh ? 5 : 50), width = fresh ? 2 : 1))
                    array.push(edges, line.new(x0, far, xEnd, far, xloc = xloc.bar_index, color = color.new(col, 55), style = line.style_dotted, width = 1))
                if showLaunch and start >= bar_index - 4800
                    // the pad over the quiet bars, the departure written on it, and the launch line to where the move ended
                    int padEnd = start + baseLen - 1
                    array.push(boxes, box.new(start, top, padEnd, bot, xloc = xloc.bar_index, border_color = color.new(col, 45), border_width = 1, bgcolor = color.new(col, 82)))
                    float yFrom = side == 1 ? top : bot
                    float yTo = array.get(zDepP, j)
                    int born = array.get(zBorn, j)
                    array.push(edges, line.new(padEnd, yFrom, born, yTo, xloc = xloc.bar_index, color = color.new(col, 90), width = 4))
                    array.push(edges, line.new(padEnd, yFrom, born, yTo, xloc = xloc.bar_index, color = color.new(col, 20), width = 1))
                    // the departure, written at the left of the pad so it stays clear of the launch line
                    array.push(labs, label.new(start, (top + bot) / 2, str.tostring(dep, "0.0") + " ATR", xloc = xloc.bar_index, yloc = yloc.price, color = color.new(#000000, 100), style = label.style_label_right, textcolor = color.new(col, 10), size = size.small))
                if showLab
                    string txt = (side == 1 ? "Demand" : "Supply") + "  ·  " + (fresh ? "fresh" : "tested " + str.tostring(tests) + "x")
                    array.push(labs, label.new(xEnd + 1, uTop > uBot ? (uTop + uBot) / 2 : (top + bot) / 2, txt, xloc = xloc.bar_index, yloc = yloc.price, color = color.new(#000000, 100), style = label.style_label_left, textcolor = color.new(col, fresh ? 0 : 40), size = size.small))
 
// ───────────────────────── Panel ─────────────────────────
 
var table panel = na
if showPanel and barstate.islast
    if na(panel)
        tablePos = switch panelPos
            "Top left"     => position.top_left
            "Bottom left"  => position.bottom_left
            "Bottom right" => position.bottom_right
            => position.top_right
        panel := table.new(tablePos, 2, 5, bgcolor = color.new(colPanel, 15), frame_color = color.new(colPanel, 0), frame_width = 1, border_width = 0)
    txtSize = panelSize == "Small" ? size.small : panelSize == "Large" ? size.large : size.normal
    color txt = #D1D4DC
    color dim = color.new(#D1D4DC, 40)
    string demTxt = na(nearDem) ? "None in range" : zoneTxt(nearDem)
    string supTxt = na(nearSup) ? "None in range" : zoneTxt(nearSup)
    string recTxt = nRec == 0 ? "No tests yet" : "Held " + str.tostring(held) + " of the last " + str.tostring(nRec) + " tests"
    float dDem = na(nearDem) ? na : (close - array.get(zTop, nearDem)) / atr
    float dSup = na(nearSup) ? na : (array.get(zBot, nearSup) - close) / atr
    string read = not na(inZone) ? ("Testing " + (array.get(zSide, inZone) == 1 ? "demand" : "supply") + " now, a close " + (array.get(zSide, inZone) == 1 ? "below " + fmtP(array.get(zBot, inZone)) : "above " + fmtP(array.get(zTop, inZone))) + " breaks it") : not na(nearDem) and dDem < 0.3 ? "Sitting on demand at " + fmtP(array.get(zTop, nearDem)) + ", a close below " + fmtP(array.get(zBot, nearDem)) + " breaks it" : not na(nearSup) and dSup < 0.3 ? "Pressing into supply at " + fmtP(array.get(zBot, nearSup)) + ", a close above " + fmtP(array.get(zTop, nearSup)) + " breaks it" : na(nearDem) and na(nearSup) ? "No zones in reach, price is in open ground" : na(nearSup) ? "Nothing above but open ground, demand " + str.tostring(dDem, "0.0") + " ATR below is the first thing in the way" : na(nearDem) ? "Nothing below but open ground, supply " + str.tostring(dSup, "0.0") + " ATR above is the first thing in the way" : dDem <= dSup ? "Demand " + str.tostring(dDem, "0.0") + " ATR below is the first thing in the way, supply is " + str.tostring(dSup, "0.0") + " ATR up" : "Supply " + str.tostring(dSup, "0.0") + " ATR above is the first thing in the way, demand is " + str.tostring(dDem, "0.0") + " ATR down"
    color readClr = not na(inZone) ? (array.get(zSide, inZone) == 1 ? colDem : colSup) : not na(nearDem) and dDem < 0.3 ? colDem : not na(nearSup) and dSup < 0.3 ? colSup : txt
    table.cell(panel, 0, 0, "ZONE MASTER", text_color = txt, text_size = txtSize, text_halign = text.align_left)
    table.cell(panel, 1, 0, str.tostring(array.size(zSide)) + " zones tracked", text_color = dim, text_size = txtSize, text_halign = text.align_right)
    table.cell(panel, 0, 1, "Nearest demand", text_color = dim, text_size = txtSize, text_halign = text.align_left)
    table.cell(panel, 1, 1, demTxt, text_color = colDem, text_size = txtSize, text_halign = text.align_right)
    table.cell(panel, 0, 2, "Nearest supply", text_color = dim, text_size = txtSize, text_halign = text.align_left)
    table.cell(panel, 1, 2, supTxt, text_color = colSup, text_size = txtSize, text_halign = text.align_right)
    table.cell(panel, 0, 3, "Zones here", text_color = dim, text_size = txtSize, text_halign = text.align_left)
    table.cell(panel, 1, 3, recTxt, text_color = txt, text_size = txtSize, text_halign = text.align_right)
    table.cell(panel, 0, 4, "Read", text_color = dim, text_size = txtSize, text_halign = text.align_left)
    table.cell(panel, 1, 4, read, text_color = readClr, text_size = txtSize, text_halign = text.align_right)
 
// ───────────────────────── Alerts ─────────────────────────
 
alertcondition(newDemand,     "New demand zone",  "Zone Master: a new demand zone was born")
alertcondition(newSupply,     "New supply zone",  "Zone Master: a new supply zone was born")
alertcondition(demandReached, "Demand reached",   "Zone Master: price has entered a demand zone")
alertcondition(supplyReached, "Supply reached",   "Zone Master: price has entered a supply zone")
alertcondition(zoneHeld,      "Zone held",        "Zone Master: price left a zone without closing through it")
alertcondition(zoneBroke,     "Zone broke",       "Zone Master: a close beyond the far edge ended a zone")

← 返回列表