本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TheVeiledSage
//@version=6
// The Veiled Sage - Cycle Composite + Distribution Window
// Two public daily on-chain series (MVRV and MVRV Z-Score) are each mapped onto a fixed 0-100
// scale, averaged, then passed through a linear map (intercept and slope are user inputs).
// Shown in its own pane. Optional event markers, cycle-spacing marks, cycle-regime phase
// shading, and a calendar Distribution window (last 15% of halving -> halving + 535 days,
// with an optional extension on a completed daily close). Optional price-pane candle colours
// and a JSON alert() payload (vs_alert/3) can be turned on in the settings.
//
// The default intercept and slope are our own calibration constants. They are not validated
// here, and no fit, tracking, or accuracy figures are claimed. The fixed scale extremes come
// from public history of the two feeds through 2026. A fixed scale is hindsight when applied
// to earlier bars. The linear map can exceed 0-100; the unclamped value is what is plotted.
//
// Data: only the public TradingView symbols named in the settings (Coin Metrics MVRV and
// MVRV Z-Score for the composite; Bybit BTCUSDT.P for the optional low-break and
// Distribution extension rules). Nothing private is read. This is a two-feed composite
// plus calendar rules. It does not predict tops, bottoms, or returns. #NFA
//
// MARKERS
// 7-day average of the daily composite crosses above / below the 30-day average,
// with a 1-point dead-band (|7d-30d| must exceed 1).
// Composite enters (filled) / leaves (hollow) the low zone (<= 22) or the high zone
// (>= 55), with 1 point of hysteresis (leave low only above 23, leave high only below 54).
// Evaluated once per completed day, on a daily chart or lower. On intraday charts a
// marker lands on the first bar of the next day. Weekly and higher: markers not supported.
//
// CYCLE SPACING (calendar arithmetic from the anchor dates, not a forecast)
// Bottom mark = latest top + (latest bottom - previous top) days
// Bottom window = latest top + min / max historical top-to-bottom spans
// Top (bottom rule) = bottom mark + 1061 d
// Top (halving) = next halving (estimate) + 526 d
// Cycle-length mark = latest top + 1461 d
// All of these are computed from the anchor inputs, never typed in as dates.
//
// CYCLE REGIME PHASES (additive shading)
// halving -> top = Markup, top -> cycle low = Markdown,
// cycle low -> next halving = Accumulation (dated anchors; cycles 1-3 and the
// current-cycle accumulation are fixed dates; the current-cycle top reuses the
// "C4 top date" input, the current-cycle low is an input).
// The map starts at the Nov 2012 halving (no band before it). A completed
// BYBIT:BTCUSDT.P daily close below the map low can turn the shading Markdown.
//
// DISTRIBUTION WINDOW (additive shading)
// Expected-top date = halving + "Halving -> top count" days (default 535 = mean of
// cycles 2-4 on Bitstamp daily closes: 525 / 546 / 534; cycle 1 = 371, excluded as
// an outlier). That is a three-cycle mean, a small sample.
// Window = the last "Window %" of the halving -> expected-top span, ending on the
// expected-top date (amber). Default 15%.
// Extension = if at window end the chosen daily close is still within "hold %" of
// the cycle high, the window stays open (lighter amber) until the first daily close
// "trigger %" below the running high. The next cycle's window uses the
// "Next halving (est.)" input. This is a calendar shade, not a sell instruction.
// Cycle 1's window falls after the 2013 top (the window does not cover that top).
// BYBIT:BTCUSDT.P history does not cover the early cycles, so the extension rule
// cannot be evaluated there.
indicator("The Veiled Sage - Cycle Composite + Distribution Window", "VS Cycle", overlay=false, precision=1, max_lines_count=60, max_labels_count=60, max_boxes_count=30)
// ---- inputs -------------------------------------------------------------
mvrvSym = input.symbol("COINMETRICS:BTC_MVRV", "MVRV feed", group="Data")
mvrvzSym = input.symbol("COINMETRICS:BTC_MVRVZ", "MVRV Z feed", group="Data")
mvrvLo = input.float(0.4422, "MVRV scale low", step=0.0001, group="Scaling")
mvrvHi = input.float(6.5616, "MVRV scale high", step=0.0001, group="Scaling")
mvrvzLo = input.float(-0.7437, "MVRV Z scale low", step=0.0001, group="Scaling")
mvrvzHi = input.float(10.2660, "MVRV Z scale high", step=0.0001, group="Scaling")
calA = input.float(6.6468, "Intercept", step=0.0001, group="Calibration")
calB = input.float(1.5905, "Slope", step=0.0001, group="Calibration")
loZone = input.float(22.0, "Low zone: at or below", group="Zones")
hiZone = input.float(55.0, "High zone: at or above", group="Zones")
// ---- feed reads --------------------------------------------------------
// Read on the daily series so the value does not depend on chart timeframe.
rawMvrv = request.security(mvrvSym, "D", close, barmerge.gaps_off, barmerge.lookahead_off)
rawMvrvz = request.security(mvrvzSym, "D", close, barmerge.gaps_off, barmerge.lookahead_off)
scale(x, lo, hi) =>
hi - lo == 0 ? 50.0 : math.max(0.0, math.min(100.0, 100.0 * (x - lo) / (hi - lo)))
pMvrv = scale(rawMvrv, mvrvLo, mvrvHi)
pMvrvz = scale(rawMvrvz, mvrvzLo, mvrvzHi)
live = (pMvrv + pMvrvz) / 2.0
composite = calA + calB * live
// ---- plot ---------------------------------------------------------------
plot(composite, "Cycle composite", color=color.new(#e0b34a, 0), linewidth=2)
hline(hiZone, "High zone", color=color.new(color.red, 40), linestyle=hline.style_dashed)
hline(loZone, "Low zone", color=color.new(color.teal, 40), linestyle=hline.style_dashed)
pHiTop = plot(100, display=display.none)
pHiBot = plot(hiZone, display=display.none)
pLoTop = plot(loZone, display=display.none)
pLoBot = plot(0, display=display.none)
fill(pHiBot, pHiTop, color=color.new(color.red, 93))
fill(pLoBot, pLoTop, color=color.new(color.teal, 93))
// ---- v3 event markers (daily) ---------------------------------------------
showMarks = input.bool(true, "Show event markers", group="Markers")
xBand = input.float(1.0, "7d/30d cross dead-band (points)", step=0.1, group="Markers")
hyst = input.float(1.0, "Zone hysteresis (points)", step=0.1, group="Markers")
COL_LONG = #22c55e
COL_SHORT = #ef4444
isDaily = timeframe.isdaily and timeframe.multiplier == 1
intraday = timeframe.isintraday
// one confirmed composite value per day: the bar itself on a 1D chart,
// yesterday's last value on the first intraday bar of a new day
newDay = timeframe.change("D")
dayVal = isDaily ? composite : (intraday and newDay ? composite[1] : na)
var float[] days = array.new_float()
var string xState = na
var int inLong = -1 // -1 unknown, 0 outside, 1 inside (v6 bools cannot be na)
var int inHot = -1
xUp = false
xDn = false
lIn = false
lOut = false
hIn = false
hOut = false
float m7v = na
float m30v = na
if not na(dayVal)
array.push(days, dayVal)
if array.size(days) > 30
array.shift(days)
n = array.size(days)
if n >= 7
s7 = 0.0
for i = n - 7 to n - 1
s7 += array.get(days, i)
m7v := s7 / 7
if n >= 30
m30v := array.avg(days)
if not na(m7v) and not na(m30v)
diff = m7v - m30v
string s = diff > xBand ? "up" : diff < -xBand ? "dn" : xState
if not na(xState) and s != xState
xUp := s == "up"
xDn := s == "dn"
xState := s
int nl = dayVal <= loZone ? 1 : dayVal > loZone + hyst ? 0 : inLong
int nh = dayVal >= hiZone ? 1 : dayVal < hiZone - hyst ? 0 : inHot
if inLong != -1 and nl != inLong
lIn := nl == 1
lOut := nl == 0
if inHot != -1 and nh != inHot
hIn := nh == 1
hOut := nh == 0
inLong := nl
inHot := nh
plot(showMarks ? m7v : na, "7d avg (daily)", color=color.new(#f59e0b, 30), linewidth=1, style=plot.style_linebr, display=display.none)
plot(showMarks ? m30v : na, "30d avg (daily)", color=color.new(#14d3c3, 30), linewidth=1, style=plot.style_linebr, display=display.none)
mY = dayVal
plotshape(showMarks and xUp ? mY + 6 : na, "7d crossed above 30d", shape.triangleup, location.absolute, COL_LONG, size=size.tiny)
plotshape(showMarks and xDn ? mY - 6 : na, "7d crossed below 30d", shape.triangledown, location.absolute, COL_SHORT, size=size.tiny)
plotshape(showMarks and lIn ? mY : na, "Entered low zone", shape.circle, location.absolute, COL_LONG, size=size.tiny)
plotchar(showMarks and lOut ? mY : na, "Left low zone", "○", location.absolute, COL_LONG, size=size.small)
plotshape(showMarks and hIn ? mY : na, "Entered high zone", shape.circle, location.absolute, COL_SHORT, size=size.tiny)
plotchar(showMarks and hOut ? mY : na, "Left high zone", "○", location.absolute, COL_SHORT, size=size.small)
alertcondition(xUp, "7d crossed above 30d", "VS Cycle: 7d average crossed above 30d")
alertcondition(xDn, "7d crossed below 30d", "VS Cycle: 7d average crossed below 30d")
alertcondition(lIn, "Entered low zone", "VS Cycle: entered low zone")
alertcondition(lOut, "Left low zone", "VS Cycle: left low zone")
alertcondition(hIn, "Entered high zone", "VS Cycle: entered high zone")
alertcondition(hOut, "Left high zone", "VS Cycle: left high zone")
// ---- v4 4-year cycle harmonics ---------------------------------------------
showHarm = input.bool(true, "Show 4-year cycle harmonics", group="Cycle harmonics")
showHist = input.bool(true, "Historical tops / bottoms / halvings", group="Cycle harmonics")
showPhase = input.bool(true, "Shade bull / bear phases", group="Cycle harmonics")
showProj = input.bool(true, "Spacing marks (bottom, halving, top)", group="Cycle harmonics")
hBotTop = input.int(1061, "Bottom -> top (days)", group="Cycle harmonics")
hHalvTop = input.int(526, "Halving -> top (days)", group="Cycle harmonics")
hCycle = input.int(1461, "Cycle length (days)", group="Cycle harmonics")
t2bA = input.int(406, "Hist. top -> bottom C1 (days, window)", group="Cycle harmonics")
t2bB = input.int(364, "Hist. top -> bottom C2 (days, window)", group="Cycle harmonics")
t2bC = input.int(378, "Hist. top -> bottom C3 (days, window)", group="Cycle harmonics")
c4TopT = input.time(timestamp("06 Oct 2025 00:00 +0000"), "C4 top date (ATH)", group="Cycle harmonics")
c4TopP = input.float(126272.0, "C4 top price", group="Cycle harmonics")
nextHalvT = input.time(timestamp("12 Apr 2028 00:00 +0000"), "Next halving (est.)", group="Cycle harmonics")
confBotT = input.time(timestamp("01 Jan 2000 00:00 +0000"), "Confirmed bottom (leave at 2000-01-01 = none)", group="Cycle harmonics")
DAYMS = 86400000
// historical landmarks (date, price)
c1BotT = timestamp("UTC", 2011, 11, 18)
c1TopT = timestamp("UTC", 2013, 12, 4)
c2BotT = timestamp("UTC", 2015, 1, 14)
c2HalT = timestamp("UTC", 2016, 7, 9)
c2TopT = timestamp("UTC", 2017, 12, 17)
c3BotT = timestamp("UTC", 2018, 12, 15)
c3HalT = timestamp("UTC", 2020, 5, 11)
c3TopT = timestamp("UTC", 2021, 11, 10)
c4BotT = timestamp("UTC", 2022, 11, 21)
c4HalT = timestamp("UTC", 2024, 4, 20)
COL_TOP = #00ff88
COL_BOT = #ff4757
COL_HVL = #ffa502
fmtD(int tt) => str.format_time(tt, "yyyy-MM-dd", "UTC")
fmtP(p) => "$" + str.tostring(p, "#,##0")
vmark(int tt, string txt, color col, string sty, float y, string lstyle) =>
line.new(tt, 0, tt, 100, xloc=xloc.bar_time, extend=extend.none, color=col, style=sty, width=1)
label.new(tt, y, txt, xloc=xloc.bar_time, yloc=yloc.price, color=color.new(#1e272e, 10), style=lstyle, textcolor=col, size=size.tiny)
span(int a, int b, color c) =>
box.new(a, 100, b, 0, xloc=xloc.bar_time, border_color=color.new(c, 100), bgcolor=c)
// spacing marks, computed from the anchors
c3t2b = math.round((c4BotT - c3TopT) / DAYMS) // 376 d
projBot = confBotT > timestamp("UTC", 2001, 1, 1) ? confBotT : c4TopT + c3t2b * DAYMS
winLo = c4TopT + math.min(t2bA, t2bB, t2bC) * DAYMS
winHi = c4TopT + math.max(t2bA, t2bB, t2bC) * DAYMS
topB = projBot + hBotTop * DAYMS
topH = nextHalvT + hHalvTop * DAYMS
topC = c4TopT + hCycle * DAYMS
topLo = math.min(topB, topH)
topHi = math.max(topB, topH)
var bool harmDrawn = false
if showHarm and barstate.islast and not harmDrawn
harmDrawn := true
if showPhase
span(c1BotT, c1TopT, color.new(color.aqua, 94))
span(c2BotT, c2TopT, color.new(color.aqua, 94))
span(c3BotT, c3TopT, color.new(color.aqua, 94))
span(c4BotT, c4TopT, color.new(color.aqua, 94))
span(c1TopT, c2BotT, color.new(color.red, 94))
span(c2TopT, c3BotT, color.new(color.red, 94))
span(c3TopT, c4BotT, color.new(color.red, 94))
span(c4TopT, projBot, color.new(color.red, 94))
if showHist
vmark(c1BotT, "C1 bottom\n" + fmtP(2.0), COL_BOT, line.style_dotted, 8, label.style_label_up)
vmark(c1TopT, "C1 top\n" + fmtP(1163.0), COL_TOP, line.style_dotted, 92, label.style_label_down)
vmark(c2BotT, "C2 bottom\n" + fmtP(152.0), COL_BOT, line.style_dotted, 8, label.style_label_up)
vmark(c2HalT, "C2 halving\n" + fmtP(650.0), COL_HVL, line.style_dotted, 50, label.style_label_center)
vmark(c2TopT, "C2 top\n" + fmtP(19783.0), COL_TOP, line.style_dotted, 92, label.style_label_down)
vmark(c3BotT, "C3 bottom\n" + fmtP(3128.0), COL_BOT, line.style_dotted, 8, label.style_label_up)
vmark(c3HalT, "C3 halving\n" + fmtP(8600.0), COL_HVL, line.style_dotted, 50, label.style_label_center)
vmark(c3TopT, "C3 top\n" + fmtP(69000.0), COL_TOP, line.style_dotted, 92, label.style_label_down)
vmark(c4BotT, "C4 bottom\n" + fmtP(15479.0), COL_BOT, line.style_dotted, 8, label.style_label_up)
vmark(c4HalT, "C4 halving\n" + fmtP(65000.0), COL_HVL, line.style_dotted, 50, label.style_label_center)
vmark(c4TopT, "C4 top\n" + fmtP(c4TopP) + "\n" + fmtD(c4TopT), COL_TOP, line.style_dotted, 92, label.style_label_down)
if showProj
span(winLo, winHi, color.new(#ffd700, 85))
label.new(winLo, 20, "Bottom spacing window\n" + fmtD(winLo) + " .. " + fmtD(winHi), xloc=xloc.bar_time, yloc=yloc.price, color=color.new(#1e272e, 10), style=label.style_label_right, textcolor=#ffd700, size=size.tiny)
vmark(projBot, "Top + prior top-to-bottom #NFA\n" + fmtD(projBot), #ffd700, line.style_dashed, 35, label.style_label_left)
vmark(nextHalvT, "Next halving (est.)\n" + fmtD(nextHalvT), COL_HVL, line.style_dashed, 50, label.style_label_center)
span(topLo, topHi + DAYMS, color.new(color.green, 80))
vmark(topB, "Bottom + 1061 d #NFA\n" + fmtD(topB), #1e90ff, line.style_dotted, 88, label.style_label_right)
vmark(topH, "Halving + 526 d #NFA\n" + fmtD(topH), #2ed573, line.style_dotted, 62, label.style_label_right)
vmark(topC, "Top + 1461 d #NFA\n" + fmtD(topC), #a55eea, line.style_dotted, 36, label.style_label_left)
// ---- v5 cycle regime phases ------------------------------------------------
showRegime = input.bool(true, "Shade cycle regime phases", group="Cycle regime phases")
regAlpha = input.int(85, "Phase shading transparency", minval=0, maxval=100, group="Cycle regime phases")
c4LowT = input.time(timestamp("30 Jun 2026 00:00 +0000"), "C4 cycle low date (map)", group="Cycle regime phases")
c4LowP = input.float(58526.17, "C4 cycle low close (map)", group="Cycle regime phases")
watchBreak = input.bool(true, "Low-break watch: daily close below the low = Markdown", group="Cycle regime phases")
brkSym = input.symbol("BYBIT:BTCUSDT.P", "Low-break price feed", group="Cycle regime phases")
showRegTbl = input.bool(true, "Phase readout", group="Cycle regime phases")
COL_ACC = #1f77b4
COL_MKU = #2ca02c
COL_DIS = #ff7f0e
COL_MKD = #d62728
// regime-map dates; C2/C3 tops are daily-close dates and differ from the
// harmonics table above on purpose
rmC1HalT = timestamp("UTC", 2012, 11, 28)
rmC1TopT = timestamp("UTC", 2013, 12, 4)
rmC2BotT = timestamp("UTC", 2015, 1, 14)
rmC2HalT = timestamp("UTC", 2016, 7, 9)
rmC2TopT = timestamp("UTC", 2017, 12, 16)
rmC3BotT = timestamp("UTC", 2018, 12, 15)
rmC3HalT = timestamp("UTC", 2020, 5, 11)
rmC3TopT = timestamp("UTC", 2021, 11, 8)
rmC4BotT = timestamp("UTC", 2022, 11, 21)
rmC4HalT = timestamp("UTC", 2024, 4, 20)
// completed daily close only (yesterday's close, no repaint)
brkClose = request.security(brkSym, "D", close[1], barmerge.gaps_off, barmerge.lookahead_on)
var int brkT = na
if watchBreak and na(brkT) and time >= c4LowT + 2 * DAYMS and not na(brkClose) and brkClose < c4LowP - 0.005
brkT := time
regimeAt(int tt, int brk) =>
string p = na
int s = na
if not na(brk) and tt >= brk
p := "Markdown"
s := brk
else if tt >= c4LowT
p := "Accumulation"
s := c4LowT
else if tt >= c4TopT
p := "Markdown"
s := c4TopT
else if tt >= rmC4HalT
p := "Markup"
s := rmC4HalT
else if tt >= rmC4BotT
p := "Accumulation"
s := rmC4BotT
else if tt >= rmC3TopT
p := "Markdown"
s := rmC3TopT
else if tt >= rmC3HalT
p := "Markup"
s := rmC3HalT
else if tt >= rmC3BotT
p := "Accumulation"
s := rmC3BotT
else if tt >= rmC2TopT
p := "Markdown"
s := rmC2TopT
else if tt >= rmC2HalT
p := "Markup"
s := rmC2HalT
else if tt >= rmC2BotT
p := "Accumulation"
s := rmC2BotT
else if tt >= rmC1TopT
p := "Markdown"
s := rmC1TopT
else if tt >= rmC1HalT
p := "Markup"
s := rmC1HalT
[p, s]
phaseCol(string p) =>
switch p
"Accumulation" => COL_ACC
"Markup" => COL_MKU
"Distribution" => COL_DIS
"Markdown" => COL_MKD
=> color(na)
phaseName(string p) =>
switch p
"Accumulation" => "Accumulation"
"Markup" => "Markup / Bull"
"Distribution" => "Distribution / Late Bull"
"Markdown" => "Markdown / Bear"
=> "outside map"
[regPh, regSince] = regimeAt(time, brkT)
bgcolor(showRegime and not na(regPh) ? color.new(phaseCol(regPh), regAlpha) : na, title="Cycle regime phase")
var table tp = table.new(position.bottom_right, 2, 3, border_width=1)
if showRegTbl and barstate.islast
table.cell(tp, 0, 0, "Phase (map)", text_color=color.gray, text_size=size.small)
table.cell(tp, 1, 0, phaseName(regPh), text_color=na(regPh) ? color.gray : phaseCol(regPh), text_size=size.small)
table.cell(tp, 0, 1, "Since", text_color=color.gray, text_size=size.small)
table.cell(tp, 1, 1, na(regSince) ? "-" : fmtD(regSince) + " (" + str.tostring(math.floor((time - regSince) / DAYMS)) + " d)", text_size=size.small)
table.cell(tp, 0, 2, "Low-break watch", text_color=color.gray, text_size=size.small)
table.cell(tp, 1, 2, not watchBreak ? "off" : na(brkT) ? "held (" + fmtP(c4LowP) + ")" : "BROKEN " + fmtD(brkT), text_color=na(brkT) ? color.gray : COL_MKD, text_size=size.small)
// ---- v6 distribution window ---------------------------------------------------
showDist = input.bool(true, "Shade Distribution window", group="Distribution window")
distPct = input.float(15.0, "Window % of halving -> expected top", minval=1.0, maxval=40.0, step=1.0, group="Distribution window")
distCount = input.int(535, "Halving -> top count (days)", minval=300, maxval=800, group="Distribution window")
distExt = input.bool(true, "Extend while BTC holds near its high", group="Distribution window")
distHold = input.float(10.0, "Extend if close within % of cycle high", minval=1.0, maxval=50.0, group="Distribution window")
distTrig = input.float(20.0, "Extension ends at close % below high", minval=1.0, maxval=60.0, group="Distribution window")
distSym = input.symbol("BYBIT:BTCUSDT.P", "Distribution price feed", group="Distribution window")
distAlpha = input.int(70, "Window shading transparency", minval=0, maxval=100, group="Distribution window")
showDistTbl = input.bool(true, "Distribution readout", group="Distribution window")
COL_DSW = #f59e0b
distSpanD = math.round(distCount * distPct / 100.0)
expTop(int h) => h + distCount * DAYMS
winStart(int h) => expTop(h) - distSpanD * DAYMS
// latest halving at or before tt (map halvings, then the next-halving input)
halvingFor(int tt) =>
int h = na
if tt >= nextHalvT
h := nextHalvT
else if tt >= rmC4HalT
h := rmC4HalT
else if tt >= rmC3HalT
h := rmC3HalT
else if tt >= rmC2HalT
h := rmC2HalT
else if tt >= rmC1HalT
h := rmC1HalT
h
// completed daily close only (yesterday's close, no repaint)
dPx = request.security(distSym, "D", close[1], barmerge.gaps_off, barmerge.lookahead_on)
curH = halvingFor(time)
var int dH = na
var float dRunHi = na
var int dExt = 0 // 0 not decided, 1 extending, 2 closed
if not na(curH) and (na(dH) or curH != dH)
dH := curH
dRunHi := na
dExt := 0
if not na(dPx) and not na(curH)
dRunHi := na(dRunHi) ? dPx : math.max(dRunHi, dPx)
inWin = showDist and not na(curH) and time >= winStart(curH) and time <= expTop(curH)
inExt = false
if showDist and distExt and not na(curH) and time > expTop(curH)
if dExt == 0
dExt := not na(dPx) and not na(dRunHi) and dPx >= dRunHi * (1 - distHold / 100.0) ? 1 : 2
if dExt == 1
inExt := true
if not na(dPx) and dPx <= dRunHi * (1 - distTrig / 100.0)
dExt := 2
bgcolor(inWin ? color.new(COL_DSW, distAlpha) : inExt ? color.new(COL_DSW, math.min(100, distAlpha + 12)) : na, title="Distribution window")
nxtS = winStart(nextHalvT)
nxtE = expTop(nextHalvT)
var bool distDrawn = false
if showDist and barstate.islast and not distDrawn
distDrawn := true
if nxtE > time
box.new(nxtS, 100, nxtE, 0, xloc=xloc.bar_time, border_color=color.new(COL_DSW, 40), border_style=line.style_dashed, bgcolor=color.new(COL_DSW, 85))
label.new(nxtS, 96, "Next distribution window #NFA\n" + fmtD(nxtS) + " .. " + fmtD(nxtE), xloc=xloc.bar_time, yloc=yloc.price, color=color.new(#1e272e, 10), style=label.style_label_right, textcolor=COL_DSW, size=size.tiny)
var table td = table.new(position.middle_right, 2, 3, border_width=1)
if showDistTbl and barstate.islast
string st = inWin ? "IN WINDOW" : inExt ? "EXTENSION (until -" + str.tostring(distTrig, "#") + "%)" : "none"
table.cell(td, 0, 0, "Distribution", text_color=color.gray, text_size=size.small)
table.cell(td, 1, 0, st, text_color=(inWin or inExt) ? COL_DSW : color.gray, text_size=size.small)
table.cell(td, 0, 1, "Next window (" + str.tostring(distPct, "#") + "%)", text_color=color.gray, text_size=size.small)
table.cell(td, 1, 1, fmtD(nxtS) + " .. " + fmtD(nxtE), text_color=COL_DSW, text_size=size.small)
table.cell(td, 0, 2, "Window end", text_color=color.gray, text_size=size.small)
table.cell(td, 1, 2, fmtD(nxtE) + " (halving + " + str.tostring(distCount) + " d, #NFA)", text_size=size.small)
// ---- readout ------------------------------------------------------------
var table t = table.new(position.top_right, 2, 6, border_width=1)
if barstate.islast
zone = composite >= hiZone ? "HIGH" : composite <= loZone ? "LOW" : "MID"
table.cell(t, 0, 0, "VS Cycle", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 0, str.tostring(composite, "#.0"), text_color=color.new(#e0b34a, 0), text_size=size.normal)
table.cell(t, 0, 1, "MVRV", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 1, str.tostring(rawMvrv, "#.####"), text_size=size.small)
table.cell(t, 0, 2, "MVRV Z", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 2, str.tostring(rawMvrvz, "#.####"), text_size=size.small)
table.cell(t, 0, 3, "Zone", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 3, zone, text_size=size.small)
table.cell(t, 0, 4, "Markers", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 4, isDaily or intraday ? "daily rules" : "use 1D or lower", text_size=size.small)
if showHarm and showProj
table.cell(t, 0, 5, "Top mark span", text_color=color.gray, text_size=size.small)
table.cell(t, 1, 5, fmtD(topLo) + " .. " + fmtD(topHi), text_color=#2ed573, text_size=size.small)
// ---- alerts -------------------------------------------------------------
alertcondition(ta.crossover(composite, hiZone), "Into high zone", "{{ticker}} VS Cycle: composite crossed into the high zone")
alertcondition(ta.crossunder(composite, loZone), "Into low zone", "{{ticker}} VS Cycle: composite crossed into the low zone")
// ---- public add-on: optional candle colours + JSON alert() (does not change calculations above) ----
// Candle colours and the JSON payload read the same composite, 7d/30d state, zones, phase and
// Distribution flags already computed. Defaults keep the pane looking as it did: candle
// overlay off, brand label off. JSON is available when the user creates an "Any alert()
// function call" alert. Existing alertcondition() entries are unchanged.
grpP = "Palette (Veiled Sage, optional candle colours)"
cGold = input.color(#D4A017, "Gold", group=grpP)
cViolet = input.color(#7B2CBF, "Violet", group=grpP)
showBars = input.bool(true, "Candle colours by 7d vs 30d state", group="Layers", tooltip="Optional. Repaints candles on the price chart from the 7d-vs-30d state already computed above (gold = up, violet = down). On by default; turn off to leave the chart candles unchanged. When on, barcolor and a price-pane candle overlay use the same colour.")
showBrand = input.bool(false, "Show The Veiled Sage label", group="Layers")
color barCol = (timeframe.isintraday or (timeframe.isdaily and timeframe.multiplier == 1)) and xState == "up" ? cGold : (timeframe.isintraday or (timeframe.isdaily and timeframe.multiplier == 1)) and xState == "dn" ? cViolet : na
barcolor(showBars ? barCol : na, title="Candles by 7d vs 30d state")
plotcandle(open, high, low, close, title="Candle overlay (draws over the chart candles)", color=showBars ? barCol : na, wickcolor=showBars ? barCol : na, bordercolor=showBars ? barCol : na, force_overlay=true)
var table brandTbl = table.new(position.bottom_left, 1, 1, bgcolor=color.new(#16121D, 100), border_width=0)
if barstate.islast
table.cell(brandTbl, 0, 0, showBrand ? "The Veiled Sage - Cycle Composite" : "", text_size=size.small, text_color=color.new(cGold, 45))
// JSON alert() (vs_alert/3). ONE alert, condition "Any alert() function call". Confirmed bars only.
// execution_intent is always state_only. This does not change the alertcondition() entries above.
string SCRIPT_VER = "vs_cycle_composite_distribution_public"
string SCHEMA = "vs_alert/3"
grpJ = "JSON alert"
jsonMode = input.string("Events + 15m pulse", "JSON alert() mode", options=["Events + 15m pulse", "Events only", "Every closed bar", "Off"], group=grpJ, tooltip="Create ONE alert on this indicator with the condition 'Any alert() function call'. Events + 15m pulse: a message on bars where an event confirms, plus one state message on every closed 15m bar. Events only: event bars only. Every closed bar: one state message per closed bar. Off: no alert() calls. The alertcondition() entries are independent of this setting.")
jnum(float x, string fmt) => na(x) ? "null" : str.tostring(x, fmt)
jbool(bool x) => x ? "true" : "false"
buildPayload(string ev, string eventsJson, bool pulse) =>
string isoT = str.format_time(time, "yyyy-MM-dd'T'HH:mm:ss'Z'", "UTC")
string id = syminfo.ticker + "_" + timeframe.period + "_" + str.tostring(time) + "_" + ev
string zNm = composite >= hiZone ? "high" : composite <= loZone ? "low" : "mid"
string mom = na(xState) ? "none" : xState == "up" ? "up" : xState == "dn" ? "down" : "none"
string dSt = inWin ? "window" : inExt ? "extension" : "none"
string s = "{\"schema\":\"" + SCHEMA + "\",\"id\":\"" + id + "\",\"event\":\"" + ev + "\""
s += ",\"version\":\"" + SCRIPT_VER + "\",\"indicator\":\"cycle_composite\",\"execution_intent\":\"state_only\",\"state_only\":true"
s += ",\"ticker\":\"" + syminfo.ticker + "\",\"exchange\":\"" + syminfo.prefix + "\",\"timeframe\":\"" + timeframe.period + "\""
s += ",\"bar_time\":" + str.tostring(time) + ",\"bar_time_iso\":\"" + isoT + "\",\"confirmed\":true,\"heartbeat\":" + jbool(pulse)
s += ",\"open\":" + jnum(open, "#.########") + ",\"high\":" + jnum(high, "#.########") + ",\"low\":" + jnum(low, "#.########") + ",\"close\":" + jnum(close, "#.########") + ",\"volume\":" + jnum(volume, "#.####")
s += ",\"composite\":" + jnum(composite, "#.##") + ",\"composite_avg7\":" + jnum(m7v, "#.##") + ",\"composite_avg30\":" + jnum(m30v, "#.##")
s += ",\"mvrv\":" + jnum(rawMvrv, "#.####") + ",\"mvrv_z\":" + jnum(rawMvrvz, "#.####") + ",\"mvrv_scaled\":" + jnum(pMvrv, "#.##") + ",\"mvrv_z_scaled\":" + jnum(pMvrvz, "#.##")
s += ",\"zone\":\"" + zNm + "\",\"momentum\":\"" + mom + "\""
s += ",\"zone_lo\":" + jnum(loZone, "#.##") + ",\"zone_hi\":" + jnum(hiZone, "#.##") + ",\"hysteresis\":" + jnum(hyst, "#.##") + ",\"cross_band\":" + jnum(xBand, "#.##")
s += ",\"phase\":" + (na(regPh) ? "null" : "\"" + regPh + "\"") + ",\"distribution_state\":\"" + dSt + "\""
s += ",\"dist_window_start_iso\":" + (na(curH) ? "null" : "\"" + fmtD(winStart(curH)) + "\"") + ",\"dist_window_end_iso\":" + (na(curH) ? "null" : "\"" + fmtD(expTop(curH)) + "\"")
s += ",\"dist_next_start_iso\":\"" + fmtD(nxtS) + "\",\"dist_next_end_iso\":\"" + fmtD(nxtE) + "\",\"spacing_is_forecast\":false"
s += ",\"events\":" + eventsJson + "}"
s
if barstate.isconfirmed and jsonMode != "Off"
string evList = ""
if xUp
evList += "\"comp_avg7_cross_above_avg30\""
if xDn
evList += (evList == "" ? "" : ",") + "\"comp_avg7_cross_below_avg30\""
if lIn
evList += (evList == "" ? "" : ",") + "\"entered_low_zone\""
if lOut
evList += (evList == "" ? "" : ",") + "\"left_low_zone\""
if hIn
evList += (evList == "" ? "" : ",") + "\"entered_high_zone\""
if hOut
evList += (evList == "" ? "" : ",") + "\"left_high_zone\""
bool pulseBar = jsonMode == "Events + 15m pulse" and timeframe.period == "15"
if jsonMode == "Every closed bar" or pulseBar or evList != ""
alert(buildPayload("cycle_composite_snapshot", "[" + evList + "]", evList == ""), alert.freq_once_per_bar_close)