本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Buy Zone Planner [Rider Algo]", shorttitle="Buy Zone Planner [Rider Algo]", overlay=true, max_labels_count=20, max_boxes_count=10)
// Developed by Rider Algo
//
// A planner for long-term buyers: three buy zones under the price, the chance that price reaches each one within the
// time you are willing to wait, and how buying there worked on this chart before.
//
// How it works (validated 2026-10-18 on 37 assets: 12 cryptos, 22 stocks and ETFs, gold, silver and EURUSD; weekly
// history from Yahoo Finance; every number computed only with the weeks known at the time):
// 1. "Cheap" is measured against the asset's own history: price vs its 200-week average (4 years), ranked against
// the last 416 weeks (8 years). Zone 1 starts where price was this cheap only 30% of the time, Zone 2 at 15%,
// Zone 3 at 5%; Zone 3 ends at 1%. While the chart has less history, the 104-week average is used, and the
// zones move from one to the other gradually over a year (no jump).
// On stocks, the weeks bought in the zones beat buying any week by about 4-8% one year later and 8-15% two years
// later, deeper zones more; it held in both halves of the history and with other cut-offs. It did not work on
// gold, silver or EURUSD: that is why the table judges every chart on its own record.
// 2. Chance to reach: how often price fell that far within the chosen time, in units of its own weekly volatility,
// in this chart's history. Checked out of sample: when it said 45%, price got there about 45% of the time
// (error 1-4 points). On crypto a pure volatility model was more accurate (error 1-3 points), so crypto uses it.
// 3. Everything comes from CLOSED weeks: the levels stay fixed during the week, read the same on 1D and 1W and do
// not repaint.
//──────────────────────────────────────────────
// QUICK GUIDE
//──────────────────────────────────────────────
groupGuide = "Quick Guide"
quickGuide = input.string("Hover the (i) on the right", "How to read it", group=groupGuide, display=display.none, tooltip="1. The three colored zones under the price are good places for buy orders: Zone 1 = good price, Zone 2 = great price, Zone 3 = rare price. They are measured against this asset's own history, not a fixed %.\n2. Each zone shows the chance that price reaches it within the time you can wait (Settings → Plan). Deeper zone = better price, lower chance.\n3. If price is already inside a zone, it lights up: YOU ARE HERE.\n4. The table shows how buying in each zone worked on this chart: how many of those weeks were higher one year later.\n5. Buy in steps: split your money between the zones instead of one single order.\nThe zones move once a week, on the weekly close. Not financial advice.")
//──────────────────────────────────────────────
// 1 · PLAN
//──────────────────────────────────────────────
groupPlan = "1 · Plan"
waitIn = input.string("6 months", "I can wait up to", options=["3 months", "6 months", "1 year"], group=groupPlan, tooltip="How long you are willing to wait for your order to fill. The chances on the chart and in the table are for this time.")
chanceIn = input.string("Auto", "Chance model", options=["Auto", "This chart's history", "Volatility only"], group=groupPlan, tooltip="Auto (recommended): crypto uses the volatility model and everything else uses this chart's history, which were the most accurate in the tests.\nThis chart's history: how often price fell that far within the chosen time before, measured in its own weekly volatility.\nVolatility only: a classic random-walk estimate from the last 52 weeks of volatility.")
split1 = input.int(50, "Budget split (%): Zone 1", minval=0, maxval=100, group=groupPlan, inline="sp")
split2 = input.int(30, "2", minval=0, maxval=100, group=groupPlan, inline="sp")
split3 = input.int(20, "3", minval=0, maxval=100, group=groupPlan, inline="sp", tooltip="How you would split your money between the three zones. The table shows how much of it is likely to be invested within the time you can wait, if you place the orders today and leave them. They do not need to add up to 100: they are scaled.")
//──────────────────────────────────────────────
// 2 · CHART
//──────────────────────────────────────────────
groupCh = "2 · Chart"
showHist = input.bool(true, "Show zones on past candles", group=groupCh, tooltip="Draws the zones as they were each week, so you can see how price behaved in them before.")
showAhead = input.bool(true, "Show zones ahead with prices and chances", group=groupCh)
showAvg = input.bool(false, "Show the 4-year average", group=groupCh, tooltip="The 200-week average the zones are measured against (104-week while the chart has less history).")
c1 = input.color(#4dd0e1, "Zone colors: 1", group=groupCh, inline="zc")
c2 = input.color(#1be5a4, "2", group=groupCh, inline="zc")
c3 = input.color(#ffd54f, "3", group=groupCh, inline="zc")
//──────────────────────────────────────────────
// 3 · TABLE
//──────────────────────────────────────────────
groupTb = "3 · Table"
showTable = input.bool(true, "Show table", group=groupTb)
tblPosIn = input.string("Top Right", "Position", options=["Top Right", "Middle Right", "Top Left", "Bottom Left", "Bottom Right"], group=groupTb, inline="tbl")
tblSizeIn = input.string("Small", "Size", options=["Tiny", "Small", "Normal"], group=groupTb, inline="tbl")
minVisits = input.int(3, "Visits needed for a verdict", minval=1, maxval=20, group=groupTb, tooltip="A visit starts when price enters the zone and ends when a week closes back at the asset's normal level. The weeks of one visit move together, so the verdict needs several separate visits.")
relPct = input.int(60, "RELIABLE from (%)", minval=50, maxval=95, group=groupTb, inline="vd")
mixPct = input.int(45, "MIXED from (%)", minval=10, maxval=90, group=groupTb, inline="vd", tooltip="Share of the weeks bought in the zone that were higher 52 weeks later. Below MIXED = NOT RELIABLE.")
tblSize = tblSizeIn == "Tiny" ? size.tiny : tblSizeIn == "Normal" ? size.normal : size.small
tblPos = switch tblPosIn
"Top Right" => position.top_right
"Middle Right" => position.middle_right
"Top Left" => position.top_left
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
//──────────────────────────────────────────────
// RULES (fixed on purpose: the table and the validation measure exactly these)
//──────────────────────────────────────────────
P_NORM = 0.50 // normal level: a visit ends when a week closes at or above it
P_Z1 = 0.30 // Zone 1 starts where price was this cheap 30% of the time
P_Z2 = 0.15
P_Z3 = 0.05
P_END = 0.01 // Zone 3 ends here (below it is still Zone 3)
WIN = 416 // weeks ranked (8 years)
MIN_HIST = 104 // weeks of ranking needed before drawing zones
MIN_BLEND = 52 // the 200-week ranking starts weighing in at 52 weeks and takes over fully at 104
MIN_MAT = 104 // closed past periods needed before using the chart's own history for the chances
FWD = 52 // a buy is judged 52 weeks later
AHEAD = 12 // width of the zones drawn ahead, in candles
H = waitIn == "3 months" ? 13 : waitIn == "1 year" ? 52 : 26
isCrypto = syminfo.type == "crypto" or str.contains("|BTC|XBT|ETH|SOL|ADA|XRP|BNB|DOGE|LTC|LINK|BCH|DOT|AVAX|TRX|XLM|", "|" + syminfo.basecurrency + "|")
useHist = chanceIn == "This chart's history" or (chanceIn == "Auto" and not isCrypto)
//──────────────────────────────────────────────
// HELPERS
//──────────────────────────────────────────────
// Number of values <= x in an ascending array (binary search)
f_countLE(array<float> a, float x) =>
int lo = 0
int hi = a.size()
while lo < hi
int mid = int(math.floor((lo + hi) / 2))
if a.get(mid) <= x
lo := mid + 1
else
hi := mid
lo
// Percentile of an ascending array, linear interpolation (same as numpy's default)
f_quant(array<float> sorted, float p) =>
int n = sorted.size()
float pos = p * (n - 1)
int lo = int(math.floor(pos))
int hi = math.min(lo + 1, n - 1)
sorted.get(lo) + (sorted.get(hi) - sorted.get(lo)) * (pos - lo)
// Level at percentile p: from the 104-week ranking, the 200-week ranking, or a blend of both (weight w of the 200)
f_lv(array<float> s104, array<float> s200, float b104, float b200, float w, float p) =>
float out = na
if w >= 1.0
out := b200 * math.exp(f_quant(s200, p))
else if s104.size() >= MIN_HIST
float l104 = math.log(b104) + f_quant(s104, p)
if w > 0
out := math.exp(w * (math.log(b200) + f_quant(s200, p)) + (1 - w) * l104)
else
out := math.exp(l104)
out
// Moving window kept sorted: adds the new value, drops the oldest once the window is full
f_winPush(array<float> srt, array<float> fifo, float v) =>
srt.insert(f_countLE(srt, v), v)
fifo.push(v)
if fifo.size() > WIN
float old = fifo.shift()
srt.remove(f_countLE(srt, old) - 1)
srt.size()
// Standard normal distribution (Abramowitz-Stegun 7.1.26, error < 1.5e-7)
f_ncdf(float x) =>
float z = math.abs(x) / math.sqrt(2)
float t = 1.0 / (1.0 + 0.3275911 * z)
float y = 1.0 - ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * math.exp(-z * z)
x >= 0 ? 0.5 * (1 + y) : 0.5 * (1 - y)
// Chance that price touches lvl within h weeks, from close c. srt = past lowest-low moves in units of volatility.
f_reach(array<float> srt, float lvl, float c, float sg, int h, bool hist) =>
float p = na
if not na(lvl) and not na(c)
if lvl >= c
p := 1.0
else if not na(sg) and sg > 0
float x = math.log(lvl / c) / sg
float pVol = math.min(1.0, 2 * f_ncdf(x / math.sqrt(h)))
p := hist and srt.size() >= MIN_MAT ? float(f_countLE(srt, x)) / srt.size() : pVol
p
// One zone's record on weekly candles. lvl = the zone's top known at the start of this week; every week whose low
// reaches it counts as a buy at min(lvl, open). Judged 52 weeks later. A visit ends when a week closes at or above
// the normal level.
f_zone(float lvl, float norm) =>
var array<int> oBar = array.new<int>()
var array<float> oPx = array.new<float>()
var array<bool> oFirst = array.new<bool>()
var array<float> chg = array.new<float>()
var bool armed = true
var int up = 0
var int visits = 0
if not na(lvl) and low <= lvl
oBar.push(bar_index)
oPx.push(math.min(lvl, open))
oFirst.push(armed)
armed := false
if not na(norm) and close >= norm
armed := true
while oBar.size() > 0 and bar_index - oBar.first() >= FWD
float ch = close / oPx.first() - 1
chg.push(ch)
up += ch > 0 ? 1 : 0
visits += oFirst.first() ? 1 : 0
oBar.shift()
oPx.shift()
oFirst.shift()
float med = na
if chg.size() > 0
med := chg.median()
[chg.size(), up, visits, med, oBar.size()]
//──────────────────────────────────────────────
// WEEKLY ENGINE — runs on weekly candles; every output is the last CLOSED week (no repaint, same on 1D and 1W)
//──────────────────────────────────────────────
f_engine(int h, bool hist) =>
float s200 = ta.sma(close, 200)
float s104 = ta.sma(close, 104)
float lr = math.log(close / close[1])
float sig = ta.stdev(lr, 52, false)
float lowH = ta.lowest(low, h)
// lowest low of the h weeks after the week h bars ago, vs that week's close, in its volatility
float mN = not na(sig[h]) and sig[h] > 0 and lowH > 0 ? math.log(lowH / close[h]) / sig[h] : na
var array<float> srt200 = array.new<float>()
var array<float> fifo200 = array.new<float>()
var array<float> srt104 = array.new<float>()
var array<float> fifo104 = array.new<float>()
var array<float> mSrt = array.new<float>()
if not na(s200) and s200 > 0
f_winPush(srt200, fifo200, math.log(close / s200))
if not na(s104) and s104 > 0
f_winPush(srt104, fifo104, math.log(close / s104))
if not na(mN)
mSrt.insert(f_countLE(mSrt, mN), mN)
// weight of the 200-week average: 0 until its ranking has 52 weeks, 1 from 104 (a gradual hand-over, no jump)
int n200 = srt200.size()
float w200 = n200 >= MIN_BLEND ? math.min(1.0, float(n200 - MIN_BLEND) / (MIN_HIST - MIN_BLEND)) : 0.0
bool ready = w200 >= 1.0 or srt104.size() >= MIN_HIST
float base = w200 >= 1.0 ? s200 : w200 > 0 ? math.exp(w200 * math.log(s200) + (1 - w200) * math.log(s104)) : s104
float lvN = na
float lv1 = na
float lv2 = na
float lv3 = na
float lv4 = na
if ready
lvN := f_lv(srt104, srt200, s104, s200, w200, P_NORM)
lv1 := f_lv(srt104, srt200, s104, s200, w200, P_Z1)
lv2 := f_lv(srt104, srt200, s104, s200, w200, P_Z2)
lv3 := f_lv(srt104, srt200, s104, s200, w200, P_Z3)
lv4 := f_lv(srt104, srt200, s104, s200, w200, P_END)
float pr1 = f_reach(mSrt, lv1, close, sig, h, hist)
float pr2 = f_reach(mSrt, lv2, close, sig, h, hist)
float pr3 = f_reach(mSrt, lv3, close, sig, h, hist)
[w1, u1, v1, d1, o1] = f_zone(lv1[1], lvN[1])
[w2, u2, v2, d2, o2] = f_zone(lv2[1], lvN[1])
[w3, u3, v3, d3, o3] = f_zone(lv3[1], lvN[1])
int nMat = mSrt.size()
int nWk = bar_index + 1
[lvN[1], lv1[1], lv2[1], lv3[1], lv4[1], base[1], w200[1], ready[1], pr1[1], pr2[1], pr3[1], nMat[1], w1[1], u1[1], v1[1], d1[1], o1[1], w2[1], u2[1], v2[1], d2[1], o2[1], w3[1], u3[1], v3[1], d3[1], o3[1], nWk[1]]
[zN, z1, z2, z3, z4, zBase, zW200, zReady, pr1, pr2, pr3, nMat, w1, u1, v1, d1, o1, w2, u2, v2, d2, o2, w3, u3, v3, d3, o3, nWk] = request.security(syminfo.tickerid, "W", f_engine(H, useHist), lookahead=barmerge.lookahead_on)
z200 = zW200 >= 1.0
//──────────────────────────────────────────────
// ZONES ON PAST CANDLES
//──────────────────────────────────────────────
pz1 = plot(showHist ? z1 : na, "Zone 1 top", color=color.new(c1, 30), linewidth=1, style=plot.style_linebr)
pz2 = plot(showHist ? z2 : na, "Zone 2 top", color=color.new(c2, 30), linewidth=1, style=plot.style_linebr)
pz3 = plot(showHist ? z3 : na, "Zone 3 top", color=color.new(c3, 30), linewidth=1, style=plot.style_linebr)
pz4 = plot(showHist ? z4 : na, "Zone 3 bottom", color=color.new(c3, 70), linewidth=1, style=plot.style_linebr)
fill(pz1, pz2, color=color.new(c1, 82), title="Zone 1")
fill(pz2, pz3, color=color.new(c2, 78), title="Zone 2")
fill(pz3, pz4, color=color.new(c3, 74), title="Zone 3")
plot(showAvg ? zBase : na, "4-year average", color=color.new(color.gray, 20), linewidth=2, style=plot.style_linebr)
// -1 = no zones yet, 0 = above Zone 1, 1/2/3 = inside that zone (below Zone 3's bottom still counts as Zone 3)
int inZone = not zReady or na(z1) ? -1 : close > z1 ? 0 : close > z2 ? 1 : close > z3 ? 2 : 3
//──────────────────────────────────────────────
// FORMATTING
//──────────────────────────────────────────────
f_px(float x) => str.tostring(x, format.mintick)
f_mv(float px) => (px >= close ? "+" : "") + str.tostring((px / close - 1) * 100, "#") + "%"
f_rate(float x) => na(x) ? "–" : str.tostring(math.round(x * 100)) + "%"
modelTxt = useHist ? "this chart's history (" + str.tostring(nMat) + " past periods" + (nMat < MIN_MAT ? "; too few, volatility model used" : "") + ")" : "the volatility model (last 52 weeks)"
avgTxt = z200 ? "200-week average (4 years)" : zW200 > 0 ? "104-week average moving to the 200-week average (" + str.tostring(zW200 * 100, "#") + "% done; the chart is still building 4 years of history)" : "104-week average (2 years; the chart has less history)"
f_verdict(int weeks, int up, int visits) =>
bool few = visits < minVisits or weeks == 0
float acc = weeks > 0 ? 100.0 * up / weeks : 0.0
string txt = few ? "NOT ENOUGH DATA" : str.tostring(acc, "#") + "% " + (acc >= relPct ? "● RELIABLE" : acc >= mixPct ? "● MIXED" : "● NOT RELIABLE")
color bg = few ? color.new(color.gray, 40) : acc >= relPct ? color.new(#1be5a4, 20) : acc >= mixPct ? color.new(#ff9800, 20) : color.new(#f4362a, 20)
[txt, bg, acc]
f_record(int weeks, int up, int visits, float med, int open) =>
weeks == 0 ? "No buys in this zone that are 52 weeks old yet" + (open > 0 ? " (" + str.tostring(open) + " recent weeks still open)." : ".") : "Bought on " + str.tostring(weeks) + " weeks (" + str.tostring(visits) + " separate visits): " + str.tostring(up) + " were higher 52 weeks later (" + str.tostring(100.0 * up / weeks, "#") + "%), median change " + (med >= 0 ? "+" : "") + str.tostring(med * 100, "#") + "%." + (open > 0 ? " " + str.tostring(open) + " recent weeks still open." : "") + (visits < minVisits ? " NOT ENOUGH DATA: needs " + str.tostring(minVisits) + "+ visits." : "")
[vt1, vb1, va1] = f_verdict(w1, u1, v1)
[vt2, vb2, va2] = f_verdict(w2, u2, v2)
[vt3, vb3, va3] = f_verdict(w3, u3, v3)
//──────────────────────────────────────────────
// ZONES AHEAD (last candle only)
//──────────────────────────────────────────────
var array<box> bxs = array.new<box>()
var array<label> lbs = array.new<label>()
if barstate.islast
for b in bxs
b.delete()
bxs.clear()
for lb in lbs
lb.delete()
lbs.clear()
if showAhead and inZone >= 0
array<float> tops = array.from(z1, z2, z3)
array<float> bots = array.from(z2, z3, z4)
array<float> chs = array.from(pr1, pr2, pr3)
array<color> cols = array.from(c1, c2, c3)
array<string> names = array.from("ZONE 1 · Good price", "ZONE 2 · Great price", "ZONE 3 · Rare price")
array<string> whys = array.from("70%", "85%", "95%")
array<string> vts = array.from(vt1, vt2, vt3)
array<float> vas = array.from(va1, va2, va3)
for k = 0 to 2
float tp = tops.get(k)
float bt = bots.get(k)
color cz = cols.get(k)
bool here = inZone == k + 1
bool passed = inZone > k + 1
int x1 = bar_index + 1
int x2 = bar_index + 1 + AHEAD
bxs.push(box.new(x1, tp, x2, bt, border_color=color.new(cz, here ? 0 : 55), border_width=here ? 2 : 1, bgcolor=color.new(cz, here ? 50 : 80)))
string rec = str.contains(vts.get(k), "NOT ENOUGH") ? "If bought: not enough data yet" : "If bought: " + str.tostring(vas.get(k), "#") + "% up 1y later"
string line2 = (here ? "YOU ARE HERE" : passed ? "Price is already below this zone" : f_mv(tp) + " away · Chance in " + waitIn + ": " + f_rate(chs.get(k))) + " · " + rec
string tip = names.get(k) + ": price is cheaper here, vs its " + avgTxt + ", than " + whys.get(k) + " of the last 8 years. From " + f_px(tp) + " down to " + f_px(bt) + "." + (here or passed ? "" : " Chance that price reaches " + f_px(tp) + " within " + waitIn + ": " + f_rate(chs.get(k)) + ", from " + modelTxt + ", measured from the last weekly close.") + " The zone moves once a week."
lbs.push(label.new(x2, (tp + bt) / 2, (here ? "◀ " : "") + names.get(k) + " " + f_px(tp) + " – " + f_px(bt) + "\n" + line2, style=label.style_label_left, color=color.new(cz, here ? 0 : 15), textcolor=color.black, size=size.small, tooltip=tip))
//──────────────────────────────────────────────
// TABLE — fixed width: monospace cells padded with non-breaking spaces, no merged cells, detail in tooltips
//──────────────────────────────────────────────
CELL_W = 19
MONO = font.family_monospace
NBSP = " "
f_pad(string txt) =>
string t = str.length(txt) > CELL_W ? str.substring(txt, 0, CELL_W) : txt
int extra = CELL_W - str.length(t)
extra > 0 ? t + str.repeat(NBSP, extra) : t
var table tbl = table.new(tblPos, 4, 6, border_width=1, border_color=color.new(color.gray, 70))
f_cell(int col, int row, string txt, color bg, color fg, string tip) =>
tbl.cell(col, row, f_pad(txt), text_color=fg, text_size=tblSize, bgcolor=bg, text_halign=text.align_left, text_font_family=MONO, tooltip=tip)
if showTable and barstate.islast
color hdr = color.new(color.gray, 40)
color row = color.new(#131722, 10)
color wht = color.white
string rule = "Every week the price traded in a zone counts as a buy at the zone's price. Worked = price was higher 52 weeks later. Verdict needs " + str.tostring(minVisits) + "+ separate visits: " + str.tostring(relPct) + "%+ RELIABLE, " + str.tostring(mixPct) + "%+ MIXED, below that NOT RELIABLE. Same rules on 1D and 1W; a 1D chart may load less history."
f_cell(0, 0, "Buy Zones " + syminfo.ticker + " " + timeframe.period, hdr, wht, "Zones measured against the " + avgTxt + ", ranked against the last 8 years of this chart. " + rule)
f_cell(1, 0, "Price · distance", hdr, wht, "Top of each zone (where a buy order would go) and how far it is from the current price. The % is a distance, not a chance.")
f_cell(2, 0, "Chance in " + waitIn, hdr, wht, "Chance that price gets down to the top of the zone within " + waitIn + ", from " + modelTxt + ". Change the time in Settings → Plan.")
f_cell(3, 0, "If bought: up 1y", hdr, wht, "If you had bought in the zone before: share of those weeks that were higher one year later. " + rule)
if inZone < 0
f_cell(0, 1, "Not enough history", row, color.orange, "")
f_cell(1, 1, "Needs ~4 years", row, color.orange, "The zones need about 4 years of weekly candles (104-week average plus 2 years to rank it). This chart has " + str.tostring(nWk) + " weeks. On 1D, a chart with more loaded history may help.")
for c = 2 to 3
f_cell(c, 1, "", row, wht, "")
else
array<float> tops = array.from(z1, z2, z3)
array<float> chs = array.from(pr1, pr2, pr3)
array<color> cols = array.from(c1, c2, c3)
array<string> nms = array.from("1 · Good price", "2 · Great price", "3 · Rare price")
array<string> vts = array.from(vt1, vt2, vt3)
array<color> vbs = array.from(vb1, vb2, vb3)
array<string> recs = array.from(f_record(w1, u1, v1, d1, o1), f_record(w2, u2, v2, d2, o2), f_record(w3, u3, v3, d3, o3))
for k = 0 to 2
float tp = tops.get(k)
bool here = inZone == k + 1
bool passed = inZone > k + 1
f_cell(0, k + 1, (here ? "▶ " : "") + nms.get(k), color.new(cols.get(k), here ? 0 : 25), color.black, "")
f_cell(1, k + 1, f_px(tp) + " " + f_mv(tp), row, wht, "Zone " + str.tostring(k + 1) + " starts at " + f_px(tp) + " (" + f_mv(tp) + " from the current price).")
f_cell(2, k + 1, here ? "YOU ARE HERE" : passed ? "below it now" : f_rate(chs.get(k)), row, here ? cols.get(k) : wht, here or passed ? "" : f_rate(chs.get(k)) + " chance within " + waitIn + ", from " + modelTxt + ".")
f_cell(3, k + 1, vts.get(k), vbs.get(k), str.contains(vts.get(k), "NOT ENOUGH") ? wht : color.black, recs.get(k))
// Where price is now and what a planner would do
float accHere = inZone == 1 ? va1 : inZone == 2 ? va2 : va3
string vHere = inZone == 1 ? vt1 : inZone == 2 ? vt2 : vt3
bool weak = inZone > 0 and str.contains(vHere, "NOT RELIABLE")
string now = inZone == 0 ? f_mv(z1) + " to Zone 1" : "IN ZONE " + str.tostring(inZone)
bool isFar = inZone == 0 and not na(pr1) and pr1 < 0.10 // Zone 1 unlikely within the waiting time
string plan = isFar ? "Expensive now" : inZone == 0 ? "Plan orders below" : weak ? "Caution: weak past" : "Buy in steps"
// Warnings only when they apply; otherwise the corner cell points to the tooltips
bool tfOk = timeframe.in_seconds() >= timeframe.in_seconds("D") and timeframe.in_seconds() <= timeframe.in_seconds("W")
string note = not tfOk ? "Use 1D or 1W" : not z200 ? "2-year avg (short)" : "Hover for detail"
string noteTip = not tfOk ? "The zones are weekly: on intraday or monthly charts they are not tested." : not z200 ? "This chart has less than ~6 years of weekly history: the zones use the " + avgTxt + "." : rule + " Levels, chances and the record come from closed weeks: fixed during the week, the same on 1D and 1W."
f_cell(0, 4, "Now", row, wht, "")
f_cell(1, 4, now, row, inZone > 0 ? cols.get(inZone - 1) : wht, inZone == 0 ? "Price is above Zone 1. Zone 1 starts at " + f_px(z1) + "." : "Price is inside Zone " + str.tostring(inZone) + ".")
f_cell(2, 4, plan, row, weak or isFar ? color.orange : wht, isFar ? "Expensive vs its history: Zone 1 is " + f_mv(z1) + " away, with a " + f_rate(pr1) + " chance within " + waitIn + ". Options long-term buyers often weigh: wait (the zones rise with time if price holds), buy a small part now knowing it is above the zones, or look at assets that are in a zone today." : inZone == 0 ? "Place buy orders in steps at the zones you can afford to wait for." : weak ? "Buying in this zone did not work well on this chart before (" + str.tostring(accHere, "#") + "% of the weeks were higher a year later). Smaller steps, or wait." : "Split your money: part now, part in the deeper zones.")
f_cell(3, 4, note, row, note == "Hover for detail" ? wht : color.orange, noteTip)
// Budget plan: share of the money likely invested within the waiting time (zones already reached count as now)
array<int> spl = array.from(split1, split2, split3)
int sTot = split1 + split2 + split3
float inv = 0.0
string parts = ""
for k = 0 to 2
bool reached = inZone >= k + 1
inv += spl.get(k) * (reached ? 1.0 : nz(chs.get(k)))
parts += (k > 0 ? "; " : "") + "Zone " + str.tostring(k + 1) + " " + str.tostring(spl.get(k)) + "% × " + (reached ? "already there" : f_rate(chs.get(k)) + " chance")
int invPct = sTot > 0 ? int(math.round(100 * inv / sTot)) : na
string planTip = "If you place these orders today and leave them, the share of your money likely to be invested within " + waitIn + ": " + parts + ". It is an average, not a promise. The zones move once a week: update the orders weekly. Change the split in Settings → Plan."
f_cell(0, 5, "Plan " + str.tostring(split1) + "/" + str.tostring(split2) + "/" + str.tostring(split3) + "%", row, wht, planTip)
f_cell(1, 5, "Filled in " + waitIn, row, wht, planTip)
f_cell(2, 5, na(invPct) ? "–" : "≈ " + str.tostring(invPct) + "% of budget", row, wht, planTip)
f_cell(3, 5, na(invPct) ? "" : str.tostring(100 - invPct) + "% stays in cash", row, wht, planTip)
//──────────────────────────────────────────────
// ALERTS
//──────────────────────────────────────────────
inZ1 = zReady and low <= z1 and not (low[1] <= z1[1])
inZ2 = zReady and low <= z2 and not (low[1] <= z2[1])
inZ3 = zReady and low <= z3 and not (low[1] <= z3[1])
alertcondition(inZ1, "Price reached Zone 1", "Buy Zone Planner: price reached Zone 1 (good price)")
alertcondition(inZ2, "Price reached Zone 2", "Buy Zone Planner: price reached Zone 2 (great price)")
alertcondition(inZ3, "Price reached Zone 3", "Buy Zone Planner: price reached Zone 3 (rare price)")
alertcondition(inZ1 or inZ2 or inZ3, "Price reached a buy zone", "Buy Zone Planner: price reached a buy zone")