本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Zone Clock [Zen]", overlay = true, max_boxes_count = 200)
// Zone Clock [Zen]
// Zones are formed exactly as in Sweep Entry Zone [Zen]. For every zone the script counts candles until the
// first contact and shows how often past zones of the same age got their first contact within the next N candles.
// Descriptive statistics of this chart's history. Not a forecast, not an order or fill model.
// ---------- Inputs ----------
gP = "Pool & zone (rules of Sweep Entry Zone)"
poolLen = input.int(20, "Pool length (candles)", minval = 5, group = gP, display = display.none, tooltip = "Pool = highest high / lowest low of the previous N closed candles. Sweep = wick beyond the pool and close back inside, on a closed candle.")
zoneLife = input.int(48, "Zone life (candles)", minval = 12, maxval = 200, group = gP, display = display.none, tooltip = "One limit for two waits: how long a sweep waits for its BOS, and how long a zone waits for its first contact.")
gS = "Statistics"
fwd = input.int(6, "Forward window (candles)", minval = 1, maxval = 24, group = gS, display = display.none, tooltip = "The percentage answers: of past zones that were still without contact at this age, how many got their first contact within the next N candles. The window must fit into the zone life: a percentage is shown only for ages up to zone life minus window.")
minN = input.int(30, "Minimum sample", minval = 1, group = gS, display = display.none, tooltip = "A percentage is shown only when at least this many past zones reached that age without contact.")
gV = "Display"
keepN = input.int(30, "Finished zones kept on chart", minval = 0, maxval = 150, group = gV, display = display.none)
showTable = input.bool(true, "Show table", group = gV, display = display.none)
compact = input.bool(true, "Compact table", group = gV, display = display.none, tooltip = "Compact: four age rows only. Off: adds the totals.")
tablePos = input.string("Top right", "Table position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = gV, display = display.none)
// ---------- ChartZenFX palette (auto light / dark) ----------
bool isLight = (color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color)) / 3 > 128
color cHI = isLight ? #AD4A12 : #D9703A
color cLO = isLight ? #1B46B4 : #6F88EE
color cMUTED = isLight ? #647482 : #8391A4
int fillU = isLight ? 85 : 78 // live zone
int bordU = isLight ? 60 : 50
int fillF = isLight ? 84 : 82 // finished zone
int bordF = isLight ? 45 : 40
const int LIVE_EXT = 12 // a live zone is drawn this many candles past the last one, so its label stays clear of price
int maxAge = zoneLife - fwd // last age whose forward window still fits into the zone life
bool winOk = maxAge >= 0 // false when the window is longer than the zone life: no percentage at all
// ---------- Pool and sweep (closed candles), as in Sweep Entry Zone ----------
float hh = ta.highest(high, poolLen)[1]
float ll = ta.lowest(low, poolLen)[1]
bool ok = bar_index >= poolLen
bool swH = ok and high > hh and close <= hh
bool swL = ok and low < ll and close >= ll
bool swHonly = swH and not swL // a candle that sweeps both pools is skipped
bool swLonly = swL and not swH
// ---------- Pending sweeps (one per side, waiting for BOS), as in Sweep Entry Zone ----------
var int pHbar = na
var float pHhi = na
var float pHlo = na
var float pHbody = na
var int pLbar = na
var float pLhi = na
var float pLlo = na
var float pLbody = na
// ---------- Zones and statistics ----------
type Zone
int id
int side // 1 = after a high sweep (zone above price), 2 = after a low sweep (zone below)
int born // BOS candle
float top
float bot
box bx
var array<Zone> live = array.new<Zone>()
var array<box> finished = array.new<box>()
var array<int> sBorn = array.new<int>() // every zone: BOS candle index
var array<int> sC = array.new<int>() // every zone: age of first contact; 0 = none; negative = price gapped past the zone at that age
var int sHead = 0 // first zone not yet counted
var array<int> obs = array.new<int>(zoneLife + 1, 0) // per age: zones still live and without contact at that age
var array<int> hits = array.new<int>(zoneLife + 1, 0) // per age: of those, first contact within the next fwd candles
var int nCounted = 0
var int nContact = 0
var int nContactBroken = 0
var int nGap = 0
var int nNoContact = 0
bool anySet = false
bool anyContact = false
bool anyGap = false
bool anyExpired = false
string msg = ""
f_inc(array<int> a, int i) =>
a.set(i, a.get(i) + 1)
f_ok(int age) =>
winOk and age >= 0 and age <= maxAge
f_pct(int age) =>
string s = "-"
if f_ok(age)
int n = obs.get(age)
s := n >= minN ? str.tostring(100.0 * hits.get(age) / n, "#") + "%" : "n<" + str.tostring(minN)
s
f_n(int age) =>
string s = "-"
if f_ok(age)
s := str.tostring(obs.get(age))
s
// label of a live zone: age, then the percentage for exactly this age with its sample size
f_live(int age) =>
string s = "age " + str.tostring(age)
if f_ok(age)
int n = obs.get(age)
s += n >= minN ? " | " + str.tostring(100.0 * hits.get(age) / n, "#") + "% of " + str.tostring(n) : " | n=" + str.tostring(n) + " (<" + str.tostring(minN) + ")"
s
f_rng(float top, float bot) =>
str.tostring(bot, format.mintick) + "-" + str.tostring(top, format.mintick)
f_finish(box b) =>
finished.push(b)
if finished.size() > keepN
box.delete(finished.shift())
f_close(box b, color c, string txt) =>
box.set_right(b, bar_index)
box.set_bgcolor(b, color.new(c, fillF))
box.set_border_color(b, color.new(c, bordF))
box.set_text(b, txt)
box.set_text_size(b, size.small)
box.set_text_color(b, c)
f_finish(b)
f_addZone(int side, int swBar, float top, float bot) =>
float t = top
float b = bot
if t - b < syminfo.mintick // a sweep candle with no wick-to-body gap: keep the zone one tick tall
if side == 1
b := t - syminfo.mintick
else
t := b + syminfo.mintick
color c = side == 1 ? cHI : cLO
int id = sBorn.size()
sBorn.push(bar_index)
sC.push(0)
box bx = box.new(swBar, t, bar_index + LIVE_EXT, b, border_color = color.new(c, bordU), border_width = 1, border_style = line.style_solid, bgcolor = color.new(c, fillU), text = f_live(0), text_size = size.normal, text_color = c, text_halign = text.align_right, text_valign = side == 1 ? text.align_top : text.align_bottom)
live.push(Zone.new(id, side, bar_index, t, b, bx))
f_rng(t, b)
if barstate.isconfirmed
// ----- 1. live zones: first contact / gapped past / expired -----
int k = live.size() - 1
while k >= 0
Zone z = live.get(k)
if z.born < bar_index
int age = bar_index - z.born
color c = z.side == 1 ? cHI : cLO
string sideTxt = (z.side == 1 ? "high sweep zone " : "low sweep zone ") + f_rng(z.top, z.bot)
bool reach = z.side == 1 ? high >= z.bot : low <= z.top // price reached the near edge (Sweep Entry Zone: inZone)
bool inside = z.side == 1 ? low <= z.top : high >= z.bot // the candle's range really overlaps the zone
bool broken = z.side == 1 ? close > z.top : close < z.bot // the candle closed beyond the far edge (Sweep Entry Zone: BROKEN)
if reach and inside
sC.set(z.id, age)
nContact += 1
if broken
nContactBroken += 1
anyContact := true
msg += "First contact: " + sideTxt + ", age " + str.tostring(age) + (broken ? ", closed beyond the zone (BROKEN)" : "") + "\n"
f_close(z.bx, c, "contact @ " + str.tostring(age) + (broken ? ", BROKEN" : ""))
live.remove(k)
else if reach
// the whole candle is beyond the far edge: price jumped over the zone without trading inside it
sC.set(z.id, -age)
nGap += 1
anyGap := true
msg += "Gapped past, no contact: " + sideTxt + ", age " + str.tostring(age) + " (BROKEN)\n"
f_close(z.bx, cMUTED, "gapped past @ " + str.tostring(age) + ", BROKEN")
live.remove(k)
else if age >= zoneLife
nNoContact += 1
anyExpired := true
msg += "No contact in " + str.tostring(zoneLife) + " candles: " + sideTxt + "\n"
f_close(z.bx, cMUTED, "no contact in " + str.tostring(zoneLife))
live.remove(k)
k -= 1
// ----- 2. statistics: a zone is counted only after its full life has passed -----
while sHead < sBorn.size() and bar_index - sBorn.get(sHead) >= zoneLife
int cAge = sC.get(sHead)
int endAge = cAge > 0 ? cAge : cAge < 0 ? -cAge : zoneLife + 1 // the zone was live and without contact at ages below this
if winOk
for a = 0 to maxAge
if a < endAge
f_inc(obs, a)
if cAge > 0 and cAge - a <= fwd
f_inc(hits, a)
nCounted += 1
sHead += 1
// ----- 3. labels of the zones that stay live: after the statistics, so they always match the table -----
if live.size() > 0
for i = 0 to live.size() - 1
Zone z = live.get(i)
box.set_right(z.bx, bar_index + LIVE_EXT)
box.set_text(z.bx, f_live(bar_index - z.born))
// ----- 4. pending high sweep: cancelled / BOS / timed out (Sweep Entry Zone rules) -----
if not na(pHbar)
if high > pHhi
pHbar := na
else if close < pHlo
string r = f_addZone(1, pHbar, pHhi, pHbody)
anySet := true
msg += "Zone set: high sweep zone " + r + "\n"
pHbar := na
else if bar_index - pHbar >= zoneLife
pHbar := na
// ----- pending low sweep -----
if not na(pLbar)
if low < pLlo
pLbar := na
else if close > pLhi
string r = f_addZone(2, pLbar, pLbody, pLlo)
anySet := true
msg += "Zone set: low sweep zone " + r + "\n"
pLbar := na
else if bar_index - pLbar >= zoneLife
pLbar := na
// ----- new sweeps on this candle (a new same-side sweep replaces the pending one) -----
if swHonly
pHbar := bar_index
pHhi := high
pHlo := low
pHbody := math.max(open, close)
if swLonly
pLbar := bar_index
pLhi := high
pLlo := low
pLbody := math.min(open, close)
// ---------- Table ----------
f_pos(string s) =>
s == "Top right" ? position.top_right : s == "Bottom right" ? position.bottom_right : s == "Top left" ? position.top_left : position.bottom_left
f_row(table t, int row, int age, color txt, color bg) =>
table.cell(t, 0, row, str.tostring(age), text_color = txt, bgcolor = bg, text_size = size.small)
table.cell(t, 1, row, f_pct(age), text_color = txt, bgcolor = bg, text_size = size.small)
table.cell(t, 2, row, f_n(age), text_color = txt, bgcolor = bg, text_size = size.small)
f_total(table t, int row, string name, string val, color txt, color bg) =>
table.cell(t, 0, row, name, text_color = txt, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
table.merge_cells(t, 0, row, 1, row)
table.cell(t, 2, row, val, text_color = txt, bgcolor = bg, text_size = size.small)
var table panel = table.new(f_pos(tablePos), 3, 12, border_width = 0)
if barstate.islast and showTable
color txt = chart.fg_color
color hdr = color.new(cMUTED, 65)
color bg = color.new(chart.bg_color, 15) // own background, so the numbers stay readable over candles
int r0 = 0
if str.startswith(tablePos, "Top")
// empty row: keeps the table below the chart status line on narrow charts
table.cell(panel, 0, 0, "", height = 7)
table.merge_cells(panel, 0, 0, 2, 0)
r0 := 1
table.cell(panel, 0, r0, "Zone age", text_color = txt, bgcolor = hdr, text_size = size.small, tooltip = "Candles since the zone was set, with no contact so far.")
table.cell(panel, 1, r0, "Next " + str.tostring(fwd), text_color = txt, bgcolor = hdr, text_size = size.small, tooltip = "Of past zones on this chart that were still without contact at this age: the share that got their first contact within the next " + str.tostring(fwd) + " candles.")
table.cell(panel, 2, r0, "N", text_color = txt, bgcolor = hdr, text_size = size.small, tooltip = "How many past zones reached this age without contact.")
f_row(panel, r0 + 1, 0, txt, bg)
f_row(panel, r0 + 2, 6, txt, bg)
f_row(panel, r0 + 3, 12, txt, bg)
f_row(panel, r0 + 4, 24, txt, bg)
int row = r0 + 5
if not winOk
table.cell(panel, 0, row, "Window > zone life: no %", text_color = cMUTED, bgcolor = bg, text_size = size.small, tooltip = "The forward window (" + str.tostring(fwd) + ") is longer than the zone life (" + str.tostring(zoneLife) + "), so no zone can be watched for the whole window. Reduce the forward window or increase the zone life.")
table.merge_cells(panel, 0, row, 2, row)
row += 1
if not compact
f_total(panel, row, "Zones counted / live", str.tostring(nCounted) + " / " + str.tostring(live.size()), txt, bg)
f_total(panel, row + 1, "First contact", str.tostring(nContact), txt, bg)
f_total(panel, row + 2, " closed beyond (BROKEN)", str.tostring(nContactBroken), txt, bg)
f_total(panel, row + 3, "Gapped past, no contact", str.tostring(nGap), txt, bg)
f_total(panel, row + 4, "No contact in " + str.tostring(zoneLife), str.tostring(nNoContact), txt, bg)
// ---------- Alerts ----------
if barstate.isconfirmed and msg != ""
alert(msg + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
alertcondition(anySet, "Zone set", "Zone set on {{ticker}} {{interval}}")
alertcondition(anyContact, "First contact", "First contact with a zone on {{ticker}} {{interval}}")
alertcondition(anyGap, "Gapped past a zone", "Price gapped past a zone without contact on {{ticker}} {{interval}}")
alertcondition(anyExpired, "No contact in zone life", "A zone expired without contact on {{ticker}} {{interval}}")