本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PhenLabs
//@version=6
indicator("Kill Zone Range Forecast [PhenLabs]", shorttitle = "KZRF [PhenLabs]", overlay = true, max_lines_count = 20, max_boxes_count = 5, max_labels_count = 5)
// ═════════════════════════ Enums ═════════════════════════
enum LearnSpeed
slow = "Slow"
normal = "Normal"
fast = "Fast"
enum TblSize
small = "Small"
normal = "Normal"
large = "Large"
// ═════════════════════════ Inputs ═════════════════════════
string G_STR = "Structure"
string G_FC = "Forecast"
string G_VIS = "Visuals"
string G_TBL = "Dashboard"
int swingLen = input.int(5, "Swing Length", minval = 2, maxval = 20, group = G_STR, tooltip = "Bars on each side that confirm a swing high/low. A close beyond the most recent unbroken swing is a break of structure.")
int horizon = input.int(16, "Forecast Horizon (bars)", minval = 4, maxval = 100, group = G_FC, tooltip = "How many bars ahead the range budget covers. 16 bars on 15m = 4 hours.")
float goGate = input.float(1.0, "GO Gate (× typical)", minval = 0.5, maxval = 2.5, step = 0.05, group = G_FC, tooltip = "A break prints GO only when the forecast range for the next horizon is at least this multiple of a typical horizon.")
LearnSpeed learnSpeed = input.enum(LearnSpeed.normal, "Learning Speed", group = G_FC, tooltip = "How fast each half-hour slot forgets old weeks. Slow = smoother profile, Fast = adapts to recent weeks.")
float activeThr = input.float(1.3, "Active Window Threshold", minval = 1.05, maxval = 3.0, step = 0.05, group = G_FC, tooltip = "A half-hour slot counts as an active window when its learned range is at least this multiple of the average slot.")
bool showZones = input.bool(true, "Shade Learned Active Windows", group = G_VIS)
color zoneCol = input.color(#5B7FA6, "Zone Color", group = G_VIS, active = showZones)
bool showWindow = input.bool(true, "Project Next Active Window", group = G_VIS)
bool showDraw = input.bool(true, "Show Break Level + Liquidity Draw", group = G_VIS)
bool showSkips = input.bool(false, "Show Skipped Breaks", group = G_VIS, tooltip = "Breaks that happened while the range budget was below the GO gate or the model was still learning.")
color bullCol = input.color(#14B8A6, "Bull Color", group = G_VIS)
color bearCol = input.color(#F43F5E, "Bear Color", group = G_VIS)
bool showDash = input.bool(true, "Show Dashboard", group = G_TBL)
TblSize tblSizeIn = input.enum(TblSize.normal, "Table Size", group = G_TBL, active = showDash)
// ═════════════════════════ Constants / mode ═════════════════════════
int SLOTS = 336
float tfSec = timeframe.in_seconds()
bool nonTime = chart.is_renko or chart.is_range or chart.is_pnf or chart.is_kagi or chart.is_linebreak or timeframe.isticks
bool seasonOn = not (timeframe.isweekly or timeframe.ismonthly or nonTime)
string modeTxt = not seasonOn ? "Seasonality OFF · recent average" : timeframe.isdaily ? "Weekday profile (Daily)" : "Half-hour of week · session-aware"
float alphaP = learnSpeed == LearnSpeed.slow ? 0.02 : learnSpeed == LearnSpeed.fast ? 0.10 : 0.05
int lvlN = int(math.max(200, math.min(5000, math.round(604800.0 / math.max(tfSec, 1)))))
float alphaL = 2.0 / (lvlN + 1)
string tblSz = tblSizeIn == TblSize.small ? size.small : tblSizeIn == TblSize.large ? size.normal : size.small
string tblSzT = tblSizeIn == TblSize.small ? size.tiny : tblSizeIn == TblSize.large ? size.normal : size.small
// ═════════════════════════ Helpers (pure) ═════════════════════════
f_slot(int t) =>
int d = dayofweek(t)
(d - 1) * 48 + hour(t) * 2 + (minute(t) >= 30 ? 1 : 0)
f_prof(array<float> pr, array<int> ct, int s, float mp) =>
s >= 0 and s < SLOTS and ct.get(s) > 0 ? pr.get(s) : mp
// ═════════════════════════ State ═════════════════════════
var array<float> prof = array.new_float(SLOTS, 0.0)
var array<int> cnt = array.new_int(SLOTS, 0)
var float profSum = 0.0
var int seen = 0
var int readyN = 0
var float lvl = na
var int nConf = 0
float rng = high - low
int slotNow = f_slot(time)
float meanP = seen > 0 ? profSum / seen : 1.0
float pNow = seasonOn ? f_prof(prof, cnt, slotNow, meanP) : 1.0
float mpUse = seasonOn ? meanP : 1.0
float winRatio = mpUse > 0 ? pNow / mpUse : 1.0
float expBar = na(lvl) ? na : lvl * pNow
float sumR = math.sum(rng, 20)
float sumE = math.sum(nz(expBar, rng), 20)
float regime = sumE > 0 ? math.max(0.5, math.min(2.0, sumR / sumE)) : 1.0
bool ready = seasonOn ? (nConf >= 300 and seen >= 6 and readyN >= 0.8 * seen) : nConf >= 50
// bgcolor uses the profile learned from PRIOR bars only (evaluated before this bar's update)
bgcolor(showZones and seasonOn and ready and winRatio >= activeThr ? color.new(zoneCol, 88) : na, title = "Learned Active Window")
// ═════════════════════════ Learning (closed bars only) ═════════════════════════
if barstate.isconfirmed
nConf += 1
if not na(lvl) and lvl > 0 and seasonOn
float nr = rng / lvl
int c0 = cnt.get(slotNow)
float p0 = prof.get(slotNow)
float a = math.max(alphaP, 1.0 / (c0 + 1))
float p1 = c0 == 0 ? nr : p0 + a * (nr - p0)
prof.set(slotNow, p1)
cnt.set(slotNow, c0 + 1)
profSum += p1 - (c0 == 0 ? 0.0 : p0)
if c0 == 0
seen += 1
if c0 + 1 == 3
readyN += 1
float aL = math.max(alphaL, 1.0 / nConf)
lvl := na(lvl) ? rng : lvl + aL * (rng - lvl)
// ═════════════════════════ Forecast budget (closed bars) ═════════════════════════
var float budget = na
if barstate.isconfirmed
float mpF = seen > 0 ? profSum / seen : 1.0
float acc = 0.0
for j = 1 to horizon
int tj = time(timeframe.period, bars_back = -j)
float pj = 1.0
if seasonOn
pj := na(tj) ? mpF : f_prof(prof, cnt, f_slot(tj), mpF)
acc += pj
float denom = horizon * (seasonOn ? mpF : 1.0)
budget := denom > 0 ? regime * acc / denom : na
// ═════════════════════════ Structure (closed bars) ═════════════════════════
var array<float> shP = array.new_float()
var array<int> shB = array.new_int()
var array<float> slP = array.new_float()
var array<int> slB = array.new_int()
var array<line> lvlLines = array.new<line>()
var array<line> drawLines = array.new<line>()
var int lastDir = 0
var bool lastGo = false
var int lastBar = na
var float lastBudget = na
float ph = ta.pivothigh(swingLen, swingLen)
float pl = ta.pivotlow(swingLen, swingLen)
bool bullBos = false
bool bearBos = false
float bLvl = na
int bBar = na
if barstate.isconfirmed
bool bu = shP.size() > 0 and close > shP.last()
bool be = slP.size() > 0 and close < slP.last()
float upLvl = shP.size() > 0 ? shP.last() : na
int upBar = shB.size() > 0 ? shB.last() : na
float dnLvl = slP.size() > 0 ? slP.last() : na
int dnBar = slB.size() > 0 ? slB.last() : na
// consume every swing the close went through
if shP.size() > 0
for k = shP.size() - 1 to 0
if close > shP.get(k)
shP.remove(k)
shB.remove(k)
if slP.size() > 0
for k = slP.size() - 1 to 0
if close < slP.get(k)
slP.remove(k)
slB.remove(k)
// dual-signal guard: a bar that breaks both sides is ambiguous → no signal
bullBos := bu and not be
bearBos := be and not bu
bLvl := bullBos ? upLvl : bearBos ? dnLvl : na
bBar := bullBos ? upBar : bearBos ? dnBar : na
// register newly confirmed swings (cannot already be broken: pivot is the extreme of its window)
if not na(ph)
shP.push(ph)
shB.push(bar_index - swingLen)
if shP.size() > 10
shP.shift()
shB.shift()
if not na(pl)
slP.push(pl)
slB.push(bar_index - swingLen)
if slP.size() > 10
slP.shift()
slB.shift()
bool gateOk = ready and not na(budget) and budget >= goGate
bool bullGo = bullBos and gateOk
bool bearGo = bearBos and gateOk
bool bullSkip = bullBos and not gateOk
bool bearSkip = bearBos and not gateOk
if bullBos or bearBos
lastDir := bullBos ? 1 : -1
lastGo := gateOk
lastBar := bar_index
lastBudget := budget
// liquidity draw = nearest unbroken opposing swing beyond the close
float drawLvl = na
if bullGo and shP.size() > 0
drawLvl := shP.min()
if bearGo and slP.size() > 0
drawLvl := slP.max()
if showDraw and (bullGo or bearGo)
color c = bullGo ? bullCol : bearCol
if not na(bLvl) and not na(bBar)
lvlLines.push(line.new(bBar, bLvl, bar_index, bLvl, xloc = xloc.bar_index, color = color.new(c, 25), style = line.style_dashed, width = 1))
if lvlLines.size() > 5
line.delete(lvlLines.shift())
if not na(drawLvl)
drawLines.push(line.new(bar_index, drawLvl, bar_index + horizon, drawLvl, xloc = xloc.bar_index, color = color.new(c, 40), style = line.style_dotted, width = 1))
if drawLines.size() > 5
line.delete(drawLines.shift())
plotshape(bullGo, "Bull GO", shape.triangleup, location.belowbar, bullCol, size = size.tiny, text = "GO", textcolor = bullCol)
plotshape(bearGo, "Bear GO", shape.triangledown, location.abovebar, bearCol, size = size.tiny, text = "GO", textcolor = bearCol)
plotshape(bullSkip and showSkips, "Bull Skip", shape.xcross, location.belowbar, color.new(chart.fg_color, 55), size = size.tiny)
plotshape(bearSkip and showSkips, "Bear Skip", shape.xcross, location.abovebar, color.new(chart.fg_color, 55), size = size.tiny)
// ═════════════════════════ Screener / data window plots (first) + scale anchors ═════════════════════════
float sig = bullGo ? 1 : bearGo ? -1 : 0
plot(sig, "Signal (+1 Bull GO / -1 Bear GO)", display = display.data_window + display.pine_screener)
plot(budget, "Next-H Range Budget (x typical)", display = display.data_window + display.pine_screener)
plot(winRatio, "Current Window (x typical)", display = display.data_window + display.pine_screener)
plot(regime, "Activity Regime (x usual)", display = display.data_window + display.pine_screener)
plot(high, "Scale Anchor High", color.new(color.black, 100), editable = false, display = display.pane)
plot(low, "Scale Anchor Low", color.new(color.black, 100), editable = false, display = display.pane)
// ═════════════════════════ Alerts ═════════════════════════
bool windowOpen = barstate.isconfirmed and seasonOn and ready and winRatio >= activeThr and winRatio[1] < activeThr
alertcondition(bullGo, "KZRF Bull GO", "KZRF: bullish break of structure with range budget above the GO gate on {{ticker}} {{interval}}")
alertcondition(bearGo, "KZRF Bear GO", "KZRF: bearish break of structure with range budget above the GO gate on {{ticker}} {{interval}}")
alertcondition(windowOpen, "KZRF Active Window Opens", "KZRF: a learned active window just opened on {{ticker}} {{interval}}")
// ═════════════════════════ Projection + dashboard (last bar) ═════════════════════════
float hiRef = ta.highest(high, 50)
float loRef = ta.lowest(low, 50)
var box winBox = na
var table dash = na
if barstate.islast
float mpL = seen > 0 ? profSum / seen : 1.0
int ahead = int(math.min(500, math.max(horizon, math.round(86400.0 / math.max(tfSec, 1)))))
bool nowActive = seasonOn and ready and winRatio >= activeThr
int wStart = nowActive ? time : na
int wEnd = na
float wSum = nowActive ? winRatio : 0.0
int wN = nowActive ? 1 : 0
bool wDone = false
for j = 1 to ahead
int tj = time(timeframe.period, bars_back = -j)
if na(tj)
break
int sj = f_slot(tj)
bool seenJ = seasonOn and cnt.get(sj) > 0
float rj = seenJ and mpL > 0 ? prof.get(sj) / mpL : 1.0
if seasonOn and ready and not wDone
if rj >= activeThr
if na(wStart)
wStart := tj
wSum += rj
wN += 1
else if not na(wStart)
wEnd := tj
wDone := true
if wDone
break
if not na(wStart) and na(wEnd) and wN > 0
wEnd := time(timeframe.period, bars_back = -ahead)
float wAvg = wN > 0 ? wSum / wN : na
string tz = syminfo.timezone
string endS = na(wEnd) ? "beyond scan" : str.format_time(wEnd, "HH:mm", tz)
string avgS = na(wAvg) ? "" : " · " + str.tostring(wAvg, "#.0") + "×"
string winTxt = not seasonOn ? "n/a (seasonality off)" : not ready ? "Learning…" : na(wStart) ? "None in next " + str.tostring(ahead) + " bars" : nowActive ? "NOW → " + endS + avgS : str.format_time(wStart, "EEE HH:mm", tz) + "–" + endS + avgS
// single forward box, moved instead of re-created
if showWindow and not na(wStart) and not na(wEnd) and not na(hiRef) and not na(loRef)
string bTxt = (nowActive ? "ACTIVE WINDOW" : "NEXT ACTIVE WINDOW") + "\n" + winTxt
if na(winBox)
winBox := box.new(wStart, hiRef, wEnd, loRef, xloc = xloc.bar_time, border_color = color.new(zoneCol, 45), border_style = line.style_dotted, bgcolor = color.new(zoneCol, 88), text = bTxt, text_size = size.small, text_color = color.new(chart.fg_color, 20), text_valign = text.align_top)
else
winBox.set_lefttop(wStart, hiRef)
winBox.set_rightbottom(wEnd, loRef)
winBox.set_text(bTxt)
else if not na(winBox)
winBox.delete()
winBox := na
if showDash
int NC = 12
if na(dash)
dash := table.new(position.top_right, NC + 1, 10, bgcolor = color.new(chart.bg_color, 8), border_color = color.new(chart.fg_color, 85), border_width = 1, frame_color = color.new(chart.fg_color, 70), frame_width = 1)
for r in array.from(0, 1, 2, 3, 6, 7, 8, 9)
dash.merge_cells(1, r, NC, r)
for g = 0 to 3
dash.merge_cells(1 + g * 3, 5, 3 + g * 3, 5)
color fg = chart.fg_color
color dim = color.new(chart.fg_color, 40)
color nowC = winRatio >= activeThr ? bullCol : winRatio < 0.8 ? color.new(chart.fg_color, 45) : fg
color budC = na(budget) ? dim : budget >= goGate ? bullCol : bearCol
string budS = na(budget) ? "—" : str.tostring(budget, "#.00") + "× · " + (budget >= goGate ? "OPEN" : "THIN")
string nowS = str.tostring(winRatio, "#.00") + "× · " + (winRatio >= activeThr ? "ACTIVE" : winRatio < 0.8 ? "QUIET" : "NORMAL")
string lastS = lastDir == 0 ? "None yet" : (lastDir == 1 ? "BULL " : "BEAR ") + (lastGo ? "GO" : "SKIP") + " · " + str.tostring(bar_index - lastBar) + " bars ago"
color lastC = lastDir == 0 ? dim : lastGo ? (lastDir == 1 ? bullCol : bearCol) : dim
float pct = seen > 0 ? 100.0 * readyN / seen : 0.0
string modelS = ready ? "READY · " + str.tostring(seen) + " slots" : "LEARNING " + str.tostring(math.min(99, pct), "#") + "%"
string tfS = tfSec < 3600 ? str.tostring(tfSec / 60, "#") + "m" : tfSec < 86400 ? str.tostring(tfSec / 3600, "#") + "h" : timeframe.period
string tzS = str.replace_all(syminfo.timezone, "Etc/", "")
// Heat strip: 12 cells. Intraday < 4h: each cell = 2 clock hours (4 half-hour slots) → next 24h. 4h+: each cell = 1 future bar.
bool byClock = tfSec < 14400
int t0 = time - time % 1800000
string stripLbl = byClock ? "Next 24h" : "Next 12 bars"
dash.cell(0, 0, "KILL ZONE RANGE FORECAST", text_color = fg, text_size = tblSz, text_halign = text.align_left)
dash.cell(1, 0, tfS + " · " + tzS, text_color = dim, text_size = tblSz, text_halign = text.align_right)
dash.cell(0, 1, "This window", text_color = dim, text_size = tblSzT, text_halign = text.align_left)
dash.cell(1, 1, nowS, text_color = nowC, text_size = tblSzT, text_halign = text.align_right)
dash.cell(0, 2, "Next " + str.tostring(horizon) + " bars", text_color = dim, text_size = tblSzT, text_halign = text.align_left)
dash.cell(1, 2, budS, text_color = budC, text_size = tblSzT, text_halign = text.align_right)
dash.cell(0, 3, "Next window", text_color = dim, text_size = tblSzT, text_halign = text.align_left)
dash.cell(1, 3, winTxt, text_color = fg, text_size = tblSzT, text_halign = text.align_right)
dash.cell(0, 4, stripLbl, text_color = dim, text_size = tblSzT, text_halign = text.align_left, tooltip = "Each cell = " + (byClock ? "2 hours" : "1 bar") + ". Number = expected range vs an average slot (1.0 = typical). Teal = at or above the Active threshold; dot = market closed / not learned yet.")
dash.cell(0, 5, "", text_size = tblSzT)
for k = 0 to NC - 1
float rSum = 0.0
int rN = 0
int tCell = byClock ? t0 + (1 + 4 * k) * 1800000 : time(timeframe.period, bars_back = -(k + 1))
if byClock
for m = 0 to 3
int sm = f_slot(tCell + m * 1800000)
if seasonOn and cnt.get(sm) > 0 and mpL > 0
rSum += prof.get(sm) / mpL
rN += 1
else if not na(tCell) and seasonOn
int sb = f_slot(tCell)
if cnt.get(sb) > 0 and mpL > 0
rSum += prof.get(sb) / mpL
rN += 1
float rc = rN > 0 ? rSum / rN : na
color cellBg = na(rc) ? color.new(chart.fg_color, 94) : rc >= activeThr ? color.from_gradient(rc, activeThr, 2.5, color.new(bullCol, 50), color.new(bullCol, 0)) : color.from_gradient(rc, 0.4, activeThr, color.new(zoneCol, 88), color.new(zoneCol, 50))
color cellTx = na(rc) ? dim : rc >= activeThr ? color.white : fg
dash.cell(1 + k, 4, na(rc) ? "·" : str.tostring(rc, "#.0"), text_color = cellTx, bgcolor = cellBg, text_size = size.tiny, text_halign = text.align_center)
if k % 3 == 0
string tl = na(tCell) ? "" : byClock ? str.format_time(tCell, "HH:mm", syminfo.timezone) : str.format_time(tCell, timeframe.isdaily ? "EEE" : "EEE HH:mm", syminfo.timezone)
dash.cell(1 + k, 5, tl, text_color = dim, text_size = size.tiny, text_halign = text.align_left)
dash.cell(0, 6, "Last break", text_color = dim, text_size = tblSzT, text_halign = text.align_left)
dash.cell(1, 6, lastS, text_color = lastC, text_size = tblSzT, text_halign = text.align_right)
dash.cell(0, 7, "Regime", text_color = dim, text_size = tblSzT, text_halign = text.align_left)
dash.cell(1, 7, str.tostring(regime, "#.00") + "× usual", text_color = fg, text_size = tblSzT, text_halign = text.align_right)
dash.cell(0, 8, "Model", text_color = dim, text_size = tblSzT, text_halign = text.align_left)
dash.cell(1, 8, modelS, text_color = ready ? fg : dim, text_size = tblSzT, text_halign = text.align_right)
dash.cell(0, 9, "Mode", text_color = dim, text_size = tblSzT, text_halign = text.align_left)
dash.cell(1, 9, modeTxt, text_color = dim, text_size = tblSzT, text_halign = text.align_right)