本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Gold Trader · Weekly Plan Loader", shorttitle = "GT Plan", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
// ─────────────────────────────────────────────────────────────────────────────
// Gold Trader · Weekly Plan Loader (v1.5)
//
// Paste the weekly plan string into the settings. The script then:
// • draws every zone, alert level and setup trigger
// • tracks the capital-protection alerts (on / cleared) from 1H, 4H, daily and weekly closes
// • detects setup confirmations, fill caps, retests, stops and targets
// • sends everything through ONE TradingView alert ("Any alert() function call")
//
// Use a 15-minute chart or lower on OANDA:XAUUSD.
// After pasting a new string: delete the old alert and create a new one.
//
// String format (items separated by ";"):
// GT1;W=2026-11-16;
// Z=name,low,high
// A=id,timeframe,below|above,level,reset,resetLevel,Display_name (timeframe: 15M, 1H, 4H, D or W)
// T=id,long|short,tf:15M,zone:lo-hi,trig:x,cap:x,sl:x,tp:a/b
// optional T fields: retest:lo-hi slx:points be:x off:ID exit:ID half:ID need:ID label:Display_name
// off:, exit: and half: accept several alert ids joined with "+"
// Alerts whose ids end in -Y, -O, -R form a ladder per side: while a higher one is on, the lower ones count as on.
// Display names use "_" for spaces. Ids LONG-Y/-O/-R, SHORT-Y/-O/-R, SW1, LS1, SS1 get names automatically.
// ─────────────────────────────────────────────────────────────────────────────
// ───── Inputs
string planInput = input.text_area("", "Weekly plan string", tooltip = "Paste the line from this week's playbook. After pasting a new string, delete your old alert and create a new one.")
float pxOffset = input.float(0.0, "Price offset", step = 0.1, tooltip = "Added to every level. Keep 0 on XAUUSD. On GC or MGC enter futures minus spot.")
float overPts = input.float(5.0, "Zone overshoot allowed (points)", minval = 0, step = 0.5, tooltip = "For setups whose stop is measured from the push: if price runs further than this past the far side of the zone, the setup waits for a fresh approach.")
bool showZones = input.bool(true, "Zones", group = "Chart")
bool showRules = input.bool(true, "Alert levels", group = "Chart")
bool showTrig = input.bool(true, "Setup trigger levels", group = "Chart")
bool showTrades = input.bool(true, "Entry, stop and target lines", group = "Chart")
bool showMarks = input.bool(true, "Event markers on candles", group = "Chart")
int rightPad = input.int(30, "Extend levels to the right (bars)", minval = 5, maxval = 300, group = "Chart")
string tagSizeIn = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = "Chart")
bool showOld = input.bool(false, "Show expired plan (review mode)", group = "Chart")
bool showPanel = input.bool(true, "Show status panel", group = "Status panel")
string posIn = input.string("Top right", "Position", options = ["Top right", "Top center", "Top left", "Middle right", "Middle center", "Middle left", "Bottom right", "Bottom center", "Bottom left"], group = "Status panel")
string panelSzIn = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = "Status panel")
bool panelMore = input.bool(true, "Show the 'what happens next' column", group = "Status panel")
bool alertRules = input.bool(true, "Alert state changes", group = "Alerts")
bool alertSetup = input.bool(true, "Setup confirmations, entries, targets and stops", group = "Alerts")
// ───── Style
color C_BULL = #26a69a
color C_BEAR = #ef5350
color C_Y = #f0b90b
color C_O = #ff8a3d
color C_R = #f23645
color C_N = #787b86
color C_INK = #131722
string tagSize = tagSizeIn == "Tiny" ? size.tiny : tagSizeIn == "Normal" ? size.normal : size.small
string panelSize = panelSzIn == "Tiny" ? size.tiny : panelSzIn == "Normal" ? size.normal : size.small
string panelPos = switch posIn
"Top center" => position.top_center
"Top left" => position.top_left
"Middle right" => position.middle_right
"Middle center" => position.middle_center
"Middle left" => position.middle_left
"Bottom right" => position.bottom_right
"Bottom center" => position.bottom_center
"Bottom left" => position.bottom_left
=> position.top_right
// ───── Types
type Zone
string name
float lo
float hi
type Rule
string name
string label
string side
int ladder
string sev
string tf
bool below
float lvl
float resetLvl
bool usable = true
bool active = false
bool chgOn = false
bool chgOff = false
float lastPx
bool eff = false
bool wasEff = false
bool under = false
string effBy = ""
type Setup
string name
string label
bool isLong
string tf
float zLo
float zHi
float trig
float cap
float sl
float slx
float tp1
float tp2
float beLvl
float rLo
float rHi
string offRule
string exitRule
string halfRule
string needRule
bool usable = true
int state = 0
bool touched = false
bool blown = false
float ext
int retestLeft = 0
float entry
float stopPx
bool beDone = false
bool tp1Done = false
bool halfDone = false
bool exitArmed = false
bool halfArmed = false
bool needSeen = false
int trades = 0
string lastRes = ""
line lnE
line lnS
line lnT1
line lnT2
// ───── Helpers
f_clean(string src) =>
string r = str.replace_all(src, " ", "")
r := str.replace_all(r, "\n", "")
r := str.replace_all(r, "\t", "")
r := str.replace_all(r, " ", "")
r
f_normTf(string t) =>
string u = str.upper(t)
u == "15" or u == "15M" ? "15" : u == "60" or u == "1H" ? "60" : u == "240" or u == "4H" ? "240" : u == "W" or u == "1W" ? "W" : "D"
f_tfSec(string tf) =>
tf == "15" ? 900 : tf == "60" ? 3600 : tf == "240" ? 14400 : tf == "W" ? 604800 : 86400
f_tfTxt(string tf) =>
tf == "15" ? "15M" : tf == "60" ? "1H" : tf == "240" ? "4H" : tf == "W" ? "weekly" : "daily"
f_p(float v) =>
str.tostring(v, "#.##")
f_icon(string sev) =>
sev == "Y" ? "🟡" : sev == "O" ? "🟠" : sev == "R" ? "🔴" : "⚪"
f_sevColor(string sev) =>
sev == "Y" ? C_Y : sev == "O" ? C_O : sev == "R" ? C_R : C_N
f_sevRank(string sev) =>
sev == "R" ? 4 : sev == "O" ? 3 : sev == "Y" ? 2 : 1
f_add(string cur, string msg) =>
cur == "" ? msg : cur + "\n" + msg
// Plain-English names
f_ruleLabel(string id, string custom) =>
string res = custom
if res == ""
array<string> pp = str.split(id, "-")
string pa = pp.get(0)
string pb = pp.size() > 1 ? pp.get(pp.size() - 1) : ""
string who = pa == "LONG" ? "Longs" : pa == "SHORT" ? "Shorts" : ""
string lvl = pb == "Y" ? "Yellow alert" : pb == "O" ? "Orange alert" : pb == "R" ? "Red alert" : ""
res := who != "" and lvl != "" ? who + " · " + lvl : id
res
f_setupLabel(string id, bool isLong, string custom) =>
string res = custom
if res == ""
string pre = str.length(id) >= 2 ? str.substring(id, 0, 2) : id
string num = str.length(id) > 2 ? " " + str.substring(id, 2) : ""
res := pre == "SW" ? "Swing" + num + (isLong ? " · long" : " · short") : pre == "LS" ? "Long scalp" + num : pre == "SS" ? "Short scalp" + num : id
res
f_zoneLabel(string nm) =>
str.startswith(nm, "NOTRADE") ? "No-trade zone" : nm == "PIVOT" ? "Pivot" : nm
// ───── Plan storage
var array<Zone> zones = array.new<Zone>()
var array<Rule> rules = array.new<Rule>()
var array<Setup> setups = array.new<Setup>()
var array<box> zBoxes = array.new<box>()
var array<label> zTags = array.new<label>()
var array<line> lvLines = array.new<line>()
var array<label> lvTags = array.new<label>()
// Levels that share a price are merged into one line and one label
var array<float> lvPx = array.new<float>()
var array<string> lvTop = array.new<string>()
var array<string> lvTip = array.new<string>()
var array<int> lvRank = array.new<int>()
var array<color> lvCol = array.new<color>()
var array<int> lvCnt = array.new<int>()
var string weekStr = ""
var int weekStart = na
var int weekEnd = na
var bool hasPlan = false
var int badTok = 0
int chartSec = timeframe.in_seconds()
f_addLevel(float px, string txt, string tip, int rank, color col) =>
int idx = lvPx.indexof(px)
if idx < 0
lvPx.push(px)
lvTop.push(txt)
lvTip.push(tip)
lvRank.push(rank)
lvCol.push(col)
lvCnt.push(1)
if idx >= 0
lvTip.set(idx, lvTip.get(idx) + "\n" + tip)
lvCnt.set(idx, lvCnt.get(idx) + 1)
if rank > lvRank.get(idx)
lvRank.set(idx, rank)
lvCol.set(idx, col)
lvTop.set(idx, txt)
// ───── Parse the string once
if barstate.isfirst
array<string> months = array.from("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
string src = f_clean(planInput)
if str.length(src) > 0
array<string> toks = str.split(src, ";")
for tok in toks
if str.length(tok) > 0
array<string> kv = str.split(tok, "=")
bool ok = kv.size() == 1
if kv.size() == 2
string k = str.upper(kv.get(0))
string v = kv.get(1)
array<string> f = str.split(v, ",")
// W = week date
if k == "W"
array<string> dp = str.split(v, "-")
if dp.size() == 3
float yy = str.tonumber(dp.get(0))
float mm = str.tonumber(dp.get(1))
float dd = str.tonumber(dp.get(2))
if not na(yy) and not na(mm) and not na(dd)
weekStr := mm >= 1 and mm <= 12 ? months.get(int(mm) - 1) + " " + str.tostring(int(dd)) : v
weekStart := timestamp("UTC", int(yy), int(mm), int(dd), 0, 0) - 86400000
weekEnd := weekStart + 7 * 86400000
ok := true
// Z = zone
if k == "Z" and f.size() >= 3
float za = str.tonumber(f.get(1))
float zb = str.tonumber(f.get(2))
if not na(za) and not na(zb)
zones.push(Zone.new(f.get(0) == "" ? "ZONE" : str.upper(f.get(0)), math.min(za, zb) + pxOffset, math.max(za, zb) + pxOffset))
ok := true
// A = alert rule
if k == "A" and f.size() >= 5
string rn = str.upper(f.get(0))
array<string> np = str.split(rn, "-")
string rs = np.size() > 1 ? np.get(np.size() - 1) : ""
string rtf = f_normTf(f.get(1))
float lv = str.tonumber(f.get(3))
int ri = str.lower(f.get(4)) == "reset" ? 5 : 4
float rv = f.size() > ri ? str.tonumber(f.get(ri)) : na
string rl = f.size() > ri + 1 ? str.replace_all(f.get(ri + 1), "_", " ") : ""
if not na(lv) and not na(rv)
rules.push(Rule.new(name = rn, label = f_ruleLabel(rn, rl), side = np.get(0), ladder = rs == "Y" ? 1 : rs == "O" ? 2 : rs == "R" ? 3 : 0, sev = rs, tf = rtf, below = str.lower(f.get(2)) == "below", lvl = lv + pxOffset, resetLvl = rv + pxOffset, usable = chartSec <= f_tfSec(rtf) and f_tfSec(rtf) % chartSec == 0))
ok := true
// T = trade setup
if k == "T" and f.size() >= 3
string sName = str.upper(f.get(0))
bool sLong = str.lower(f.get(1)) == "long"
string sTf = ""
string sLab = ""
float zl = na
float zh = na
float tg = na
float cp = na
float sl0 = na
float sx = na
float t1 = na
float t2 = na
float be0 = na
float r1 = na
float r2 = na
string rOff = ""
string rExit = ""
string rHalf = ""
string rNeed = ""
for [i, fld] in f
if i >= 2
array<string> pr = str.split(fld, ":")
if pr.size() == 2
string pk = str.lower(pr.get(0))
string pv = str.replace_all(pr.get(1), "–", "-")
if pk == "tf"
sTf := f_normTf(pv)
if pk == "label"
sLab := str.replace_all(pv, "_", " ")
if pk == "zone" or pk == "retest"
array<string> zz = str.split(pv, "-")
if zz.size() == 2
float qa = str.tonumber(zz.get(0))
float qb = str.tonumber(zz.get(1))
if pk == "zone"
zl := math.min(qa, qb)
zh := math.max(qa, qb)
if pk == "retest"
r1 := math.min(qa, qb)
r2 := math.max(qa, qb)
if pk == "tp"
array<string> tt = str.split(pv, "/")
t1 := str.tonumber(tt.get(0))
if tt.size() > 1
t2 := str.tonumber(tt.get(1))
if pk == "trig"
tg := str.tonumber(pv)
if pk == "cap"
cp := str.tonumber(pv)
if pk == "sl"
sl0 := str.tonumber(pv)
if pk == "slx"
sx := str.tonumber(pv)
if pk == "be"
be0 := str.tonumber(pv)
if pk == "off"
rOff := str.upper(pv)
if pk == "exit"
rExit := str.upper(pv)
if pk == "half"
rHalf := str.upper(pv)
if pk == "need"
rNeed := str.upper(pv)
bool good = sTf != "" and not na(zl) and not na(zh) and not na(tg) and not na(cp) and not na(t1) and (not na(sl0) or not na(sx))
if good
if rExit == ""
rExit := rOff
setups.push(Setup.new(name = sName, label = f_setupLabel(sName, sLong, sLab), isLong = sLong, tf = sTf, zLo = zl + pxOffset, zHi = zh + pxOffset, trig = tg + pxOffset, cap = cp + pxOffset, sl = sl0 + pxOffset, slx = sx, tp1 = t1 + pxOffset, tp2 = t2 + pxOffset, beLvl = be0 + pxOffset, rLo = r1 + pxOffset, rHi = r2 + pxOffset, offRule = rOff, exitRule = rExit, halfRule = rHalf, needRule = rNeed, usable = chartSec <= 900 and 900 % chartSec == 0))
ok := true
if not ok
badTok += 1
hasPlan := zones.size() + rules.size() + setups.size() > 0
bool expired = hasPlan and not na(weekEnd) and timenow >= weekEnd
bool visible = hasPlan and not na(weekStart) and (showOld or not expired)
// ───── Static drawings (their right edge follows the latest bar, see below)
if barstate.isfirst and visible
if showZones
for z in zones
string c1 = str.substring(z.name, 0, 1)
color zc = c1 == "R" ? C_BEAR : c1 == "S" ? C_BULL : C_N
if z.hi > z.lo
zBoxes.push(box.new(left = weekStart, top = z.hi, right = weekStart, bottom = z.lo, xloc = xloc.bar_time, border_color = color.new(zc, 100), bgcolor = color.new(zc, c1 == "R" or c1 == "S" ? 86 : 92)))
zTags.push(label.new(x = weekStart, y = (z.hi + z.lo) / 2, text = f_zoneLabel(z.name) + " " + f_p(z.lo) + "–" + f_p(z.hi), xloc = xloc.bar_time, style = label.style_label_right, color = color.new(zc, 100), textcolor = color.new(zc, 15), size = tagSize))
if z.hi == z.lo
f_addLevel(z.lo, f_zoneLabel(z.name), f_zoneLabel(z.name) + " at " + f_p(z.lo), 1, zc)
if showRules
for r in rules
string rshort = r.label + " · " + f_tfTxt(r.tf) + " close " + (r.below ? "below" : "above")
string rtip = r.label + ": switches on with a " + f_tfTxt(r.tf) + " close " + (r.below ? "below " : "above ") + f_p(r.lvl) + ", clears with a " + f_tfTxt(r.tf) + " close " + (r.below ? "above " : "below ") + f_p(r.resetLvl)
f_addLevel(r.lvl, rshort, rtip, f_sevRank(r.sev), f_sevColor(r.sev))
if showTrig
for s in setups
string sshort = s.label + " · " + f_tfTxt(s.tf) + " close " + (s.isLong ? "above" : "below")
string stip = s.label + ": confirms with a " + f_tfTxt(s.tf) + " close " + (s.isLong ? "above " : "below ") + f_p(s.trig) + " after price has been in " + f_p(s.zLo) + "–" + f_p(s.zHi) + ". Fill " + (s.isLong ? "cap " : "floor ") + f_p(s.cap)
f_addLevel(s.trig, sshort, stip, 0, s.isLong ? C_BULL : C_BEAR)
for [i, px] in lvPx
color lc = lvCol.get(i)
int extra = lvCnt.get(i) - 1
string ltxt = f_p(px) + " " + lvTop.get(i) + (extra > 0 ? " +" + str.tostring(extra) + " more" : "")
lvLines.push(line.new(x1 = weekStart, y1 = px, x2 = weekStart, y2 = px, xloc = xloc.bar_time, color = color.new(lc, 35), style = lvRank.get(i) == 0 ? line.style_dotted : line.style_dashed, width = 1))
lvTags.push(label.new(x = weekStart, y = px, text = ltxt, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(lc, 100), textcolor = color.new(lc, 5), size = tagSize, tooltip = lvTip.get(i)))
// ───── Higher-timeframe candle tracking (no request.security, no repainting)
bool chg15 = timeframe.change("15")
bool chg60 = timeframe.change("60")
bool chg240 = timeframe.change("240")
bool chgD = timeframe.change("D")
bool chgW = timeframe.change("W")
bool end15 = time_close == time_close("15")
bool end60 = time_close == time_close("60")
bool end240 = time_close == time_close("240")
bool endD = time_close == time_close("D")
bool endW = time_close == time_close("W")
var float o15 = na
var float o60 = na
var float o240 = na
var float oD = na
var float oW = na
var float h15 = na
var float l15 = na
if chg15
o15 := open
h15 := high
l15 := low
if not chg15
h15 := math.max(nz(h15, high), high)
l15 := math.min(nz(l15, low), low)
if chg60
o60 := open
if chg240
o240 := open
if chgD
oD := open
if chgW
oW := open
// If the last bar of a candle is missing from the feed, catch the close one bar late
bool late15 = chg15 and not end15[1]
bool late60 = chg60 and not end60[1]
bool late240 = chg240 and not end240[1]
bool lateD = chgD and not endD[1]
bool lateW = chgW and not endW[1]
bool cl15 = barstate.isconfirmed and (end15 or late15)
bool cl60 = barstate.isconfirmed and (end60 or late60)
bool cl240 = barstate.isconfirmed and (end240 or late240)
bool clD = barstate.isconfirmed and (endD or lateD)
bool clW = barstate.isconfirmed and (endW or lateW)
float px15 = end15 ? close : close[1]
float px60 = end60 ? close : close[1]
float px240 = end240 ? close : close[1]
float pxD = endD ? close : close[1]
float pxW = endW ? close : close[1]
float op15 = end15 ? o15 : o15[1]
float op60 = end60 ? o60 : o60[1]
float op240 = end240 ? o240 : o240[1]
float opD = endD ? oD : oD[1]
float opW = endW ? oW : oW[1]
float hi15 = end15 ? h15 : h15[1]
float lo15 = end15 ? l15 : l15[1]
f_closed(string tf) =>
tf == "15" ? cl15 : tf == "60" ? cl60 : tf == "240" ? cl240 : tf == "W" ? clW : clD
f_px(string tf) =>
tf == "15" ? px15 : tf == "60" ? px60 : tf == "240" ? px240 : tf == "W" ? pxW : pxD
f_op(string tf) =>
tf == "15" ? op15 : tf == "60" ? op60 : tf == "240" ? op240 : tf == "W" ? opW : opD
// Alert ladder: Yellow < Orange < Red on the same side. While a higher alert is on,
// the lower ones count as on too. Returns the highest alert that is on above this one.
f_above(Rule r) =>
Rule res = na
if r.ladder > 0
for q in rules
if q.active and q.side == r.side and q.ladder > r.ladder
bool better = true
if not na(res)
better := q.ladder > res.ladder
if better
res := q
res
// True if any of the listed alert ids ("A" or "A+B") is on, directly or through the ladder
f_ruleOn(string ids) =>
bool res = false
if ids != ""
array<string> parts = str.split(ids, "+")
for r in rules
if r.eff and parts.includes(r.name)
res := true
res
// True only if a listed alert's own trigger is on (used for "need:")
f_ruleOnRaw(string ids) =>
bool res = false
if ids != ""
array<string> parts = str.split(ids, "+")
for r in rules
if parts.includes(r.name) and r.active
res := true
res
// Display name of the alert that is keeping a listed alert on
f_whichOn(string ids) =>
string res = ""
if ids != ""
array<string> parts = str.split(ids, "+")
for r in rules
if res == "" and r.eff and parts.includes(r.name)
res := r.effBy
res
// Display name of the first listed alert, on or not
f_nameOf(string ids) =>
string res = ids
if ids != ""
array<string> parts = str.split(ids, "+")
for r in rules
if res == ids and parts.includes(r.name)
res := r.label
res
f_hline(float y, color col, string sty) =>
line.new(x1 = time, y1 = y, x2 = time, y2 = y, xloc = xloc.bar_time, color = color.new(col, 20), style = sty, width = 1)
// ───── Engine: runs on closed chart bars inside the plan week
var int firstBarTime = na
if barstate.isfirst
firstBarTime := time
bool inWeek = hasPlan and not na(weekStart) and time >= weekStart and time < weekEnd
string alertMsg = ""
if inWeek and barstate.isconfirmed
// 1) Capital-protection alerts
for r in rules
r.wasEff := r.eff
r.chgOn := false
r.chgOff := false
for r in rules
if r.usable and f_closed(r.tf)
float p = f_px(r.tf)
bool was = r.active
bool hit = r.below ? p < r.lvl : p > r.lvl
bool rst = r.below ? p > r.resetLvl : p < r.resetLvl
if not was and hit
r.active := true
r.chgOn := true
r.lastPx := p
if was and rst
r.active := false
r.chgOff := true
r.lastPx := p
// Ladder: while a higher alert on the same side is on, the lower ones count as on
for r in rules
Rule top = f_above(r)
r.under := not na(top)
r.eff := r.active or r.under
r.effBy := r.label
if not na(top)
r.effBy := top.label
// Announce only what changes the picture: a lower alert stays silent while a higher one is on
for r in rules
if r.chgOn and not r.wasEff and not r.under
string m1 = f_icon(r.sev) + " " + r.label + " is ON · " + f_tfTxt(r.tf) + " close at " + f_p(r.lastPx) + (r.below ? ", below " : ", above ") + f_p(r.lvl) + " · clears with a " + f_tfTxt(r.tf) + " close " + (r.below ? "above " : "below ") + f_p(r.resetLvl)
if alertRules
alertMsg := f_add(alertMsg, m1)
if showMarks and visible
label.new(x = bar_index, y = r.below ? low : high, text = r.label, style = r.below ? label.style_label_up : label.style_label_down, color = color.new(f_sevColor(r.sev), 15), textcolor = C_INK, size = size.tiny, tooltip = m1)
if r.chgOff and not r.under
bool higherCleared = false
string stays = ""
int staysRank = 0
if r.ladder > 0
for q in rules
if q.side == r.side and q.chgOff and q.ladder > r.ladder
higherCleared := true
if q.side == r.side and q.active and q.ladder > staysRank and q.ladder < r.ladder
staysRank := q.ladder
stays := q.label
if not higherCleared
string m2 = "✅ " + r.label + " cleared · " + f_tfTxt(r.tf) + " close at " + f_p(r.lastPx) + (r.below ? ", back above " : ", back below ") + f_p(r.resetLvl) + (stays != "" ? " · " + stays + " is still on" : "")
if alertRules
alertMsg := f_add(alertMsg, m2)
if showMarks and visible
label.new(x = bar_index, y = r.below ? high : low, text = r.label + " cleared", style = r.below ? label.style_label_down : label.style_label_up, color = color.new(C_N, 45), textcolor = color.white, size = size.tiny, tooltip = m2)
// 2) Setups
for s in setups
if s.usable
int st0 = s.state
bool offOn = f_ruleOn(s.offRule)
bool needOk = s.needRule == "" or f_ruleOnRaw(s.needRule)
// "After the alert": the candle on which a needed alert comes on does not count itself
bool gate = needOk and not offOn and (s.needRule == "" or s.needSeen)
s.needSeen := needOk
bool twoStep = not na(s.rLo)
float enterAt = na
// Track the extreme of the current push into the zone (used for "slx" stops)
if st0 != 2 and s.touched
s.ext := s.isLong ? math.min(nz(s.ext, low), low) : math.max(nz(s.ext, high), high)
// State 0 · waiting for the zone and the confirmation close
if st0 == 0
if not gate
s.touched := false
s.blown := false
s.ext := na
if gate
bool touch = s.isLong ? low <= s.zHi : high >= s.zLo
if touch and not s.touched
s.touched := true
s.ext := s.isLong ? low : high
// A push that runs through the zone is not this setup: wait for a fresh approach
float lim = not na(s.sl) ? s.sl : (s.isLong ? s.zLo - overPts : s.zHi + overPts)
s.blown := s.touched and (s.isLong ? s.ext < lim : s.ext > lim)
if s.touched and f_closed(s.tf)
float cp0 = f_px(s.tf)
float co0 = f_op(s.tf)
bool beyond = s.isLong ? cp0 > s.trig : cp0 < s.trig
bool conf = beyond and (s.isLong ? cp0 > co0 : cp0 < co0)
bool wasBlown = s.blown
// The push is over once a candle closes back beyond the trigger. It only counts
// if that candle closed in the trade's direction and the zone was not overshot.
if beyond and (wasBlown or not conf)
s.touched := false
s.blown := false
s.ext := na
if conf and not wasBlown and twoStep
s.state := 4
if alertSetup
alertMsg := f_add(alertMsg, "👀 " + s.label + " confirmed · " + f_tfTxt(s.tf) + " close at " + f_p(cp0) + (s.isLong ? ", above " : ", below ") + f_p(s.trig) + " · do not enter yet · wait for a 15M " + (s.isLong ? "bullish" : "bearish") + " close inside " + f_p(s.rLo) + "–" + f_p(s.rHi))
if conf and not wasBlown and not twoStep
bool within0 = s.isLong ? cp0 <= s.cap : cp0 >= s.cap
if within0
enterAt := cp0
if not within0
s.state := 1
s.retestLeft := s.tf == "240" ? 4 : 2
if alertSetup
alertMsg := f_add(alertMsg, "⏳ " + s.label + " confirmed, but the candle closed past the fill " + (s.isLong ? "cap " : "floor ") + f_p(s.cap) + " (close " + f_p(cp0) + ") · valid only if price returns to " + f_p(s.cap) + " within " + str.tostring(s.retestLeft) + " 15M candles")
// State 4 · two-step setups: wait for the 15M entry candle
if st0 == 4
bool ranAway = s.isLong ? high >= s.tp1 : low <= s.tp1
bool dead = not gate or ranAway or (not na(s.sl) and (s.isLong ? low < s.sl : high > s.sl))
if dead
s.state := 0
s.touched := false
s.blown := false
s.ext := na
s.lastRes := not gate ? "cancelled by an alert before entry" : ranAway ? "first target reached before entry" : "stop level broken before entry"
if alertSetup
alertMsg := f_add(alertMsg, "✖️ " + s.label + " cancelled · " + s.lastRes)
if not dead and cl15
bool inR = lo15 <= s.rHi and hi15 >= s.rLo
bool dirOk = s.isLong ? px15 > op15 : px15 < op15
if inR and dirOk
bool within4 = s.isLong ? px15 <= s.cap : px15 >= s.cap
if within4
enterAt := px15
if not within4
s.state := 1
s.retestLeft := 2
if alertSetup
alertMsg := f_add(alertMsg, "⏳ " + s.label + " entry candle closed past the fill " + (s.isLong ? "cap " : "floor ") + f_p(s.cap) + " · valid only if price returns to " + f_p(s.cap) + " within 2 15M candles")
// State 1 · closed past the cap: wait for price to come back to it
if st0 == 1
bool back = s.isLong ? low <= s.cap : high >= s.cap
if gate and back
enterAt := s.cap
if not gate or not back
if cl15
s.retestLeft := s.retestLeft - 1
if s.retestLeft <= 0 or not gate
s.state := 0
s.touched := false
s.blown := false
s.ext := na
s.lastRes := gate ? "no fill" : "cancelled by an alert before entry"
if alertSetup
alertMsg := f_add(alertMsg, "✖️ " + s.label + (gate ? " expired · price did not return to " + f_p(s.cap) : " cancelled · " + s.lastRes))
// Entry
if not na(enterAt)
s.state := 2
s.entry := enterAt
s.stopPx := not na(s.sl) ? s.sl : (s.isLong ? s.ext - s.slx : s.ext + s.slx)
s.beDone := false
s.tp1Done := false
s.halfDone := false
s.exitArmed := not f_ruleOn(s.exitRule)
s.halfArmed := not f_ruleOn(s.halfRule)
s.touched := false
s.blown := false
string tgt = na(s.tp2) ? f_p(s.tp1) : f_p(s.tp1) + " and " + f_p(s.tp2)
string m3 = (s.isLong ? "🟢 " : "🔴 ") + s.label + (s.isLong ? " · BUY" : " · SELL") + " triggered at " + f_p(enterAt) + " · stop " + f_p(s.stopPx) + " · targets " + tgt
if alertSetup
alertMsg := f_add(alertMsg, m3)
if showTrades and visible
s.lnE := f_hline(s.entry, C_N, line.style_solid)
s.lnS := f_hline(s.stopPx, C_R, line.style_solid)
s.lnT1 := f_hline(s.tp1, C_BULL, line.style_solid)
if not na(s.tp2)
s.lnT2 := f_hline(s.tp2, C_BULL, line.style_solid)
if showMarks and visible
label.new(x = bar_index, y = s.isLong ? low : high, text = s.label + (s.isLong ? " ▲ " : " ▼ ") + f_p(enterAt), style = s.isLong ? label.style_label_up : label.style_label_down, color = s.isLong ? C_BULL : C_BEAR, textcolor = color.white, size = size.tiny, tooltip = m3)
// State 2 · position is live
if st0 == 2
if not f_ruleOn(s.exitRule)
s.exitArmed := true
if not f_ruleOn(s.halfRule)
s.halfArmed := true
float stp = s.beDone ? s.entry : s.stopPx
bool exitOn = s.exitArmed and f_ruleOn(s.exitRule)
bool stopHit = s.isLong ? low <= stp : high >= stp
bool hit1 = s.isLong ? high >= s.tp1 : low <= s.tp1
bool hit2 = not na(s.tp2) and (s.isLong ? high >= s.tp2 : low <= s.tp2)
bool hitBe = not na(s.beLvl) and (s.isLong ? high >= s.beLvl : low <= s.beLvl)
string res = ""
// A hard stop is a resting order, so it is hit before any candle-close alert
if stopHit
res := s.beDone ? "stopped at breakeven" : "stopped at " + f_p(s.stopPx)
if res == "" and exitOn
res := f_whichOn(s.exitRule) + " came on · close the position"
if res == "" and s.halfRule != "" and not s.halfDone and s.halfArmed and f_ruleOn(s.halfRule)
s.halfDone := true
if alertSetup
alertMsg := f_add(alertMsg, "✂️ " + s.label + " · " + f_whichOn(s.halfRule) + " came on · cut half")
if res == "" and hitBe and not s.beDone
s.beDone := true
line.set_y1(s.lnS, s.entry)
line.set_y2(s.lnS, s.entry)
if alertSetup
alertMsg := f_add(alertMsg, "🔒 " + s.label + " reached " + f_p(s.beLvl) + " · move the stop to breakeven")
if res == "" and hit1 and not s.tp1Done
s.tp1Done := true
if na(s.tp2)
res := "target " + f_p(s.tp1) + " reached"
if not na(s.tp2)
s.beDone := true
line.set_y1(s.lnS, s.entry)
line.set_y2(s.lnS, s.entry)
if alertSetup
alertMsg := f_add(alertMsg, "🎯 " + s.label + " · first target " + f_p(s.tp1) + " reached · take half · move the stop to breakeven")
if res == "" and s.tp1Done and hit2
res := "second target " + f_p(s.tp2) + " reached"
if res != ""
s.state := 0
s.trades := s.trades + 1
s.lastRes := res
s.ext := na
line.set_x2(s.lnE, time)
line.set_x2(s.lnS, time)
line.set_x2(s.lnT1, time)
line.set_x2(s.lnT2, time)
if alertSetup
alertMsg := f_add(alertMsg, "🏁 " + s.label + " closed · " + res)
if showMarks and visible
label.new(x = bar_index, y = s.isLong ? high : low, text = s.label + " closed", style = s.isLong ? label.style_label_down : label.style_label_up, color = color.new(C_N, 25), textcolor = color.white, size = size.tiny, tooltip = s.label + " closed · " + res)
// ───── One alert carries everything
if alertMsg != ""
alert("Gold Trader plan · " + syminfo.ticker + "\n" + alertMsg, alert.freq_once_per_bar_close)
// ───── Right edge of every level follows the latest bar
if barstate.islast and visible
int barMs = chartSec * 1000
int edge = math.min(time + rightPad * barMs, weekEnd)
// Before the week opens, show the levels across the latest bars so the plan can be prepared
int leftX = time < weekStart ? time - rightPad * barMs : weekStart
for zb in zBoxes
box.set_left(zb, leftX)
box.set_right(zb, edge)
for zt in zTags
label.set_x(zt, edge)
for ll in lvLines
line.set_x1(ll, leftX)
line.set_x2(ll, edge)
for lt in lvTags
label.set_x(lt, edge)
for s in setups
if s.state == 2
line.set_x2(s.lnE, edge)
line.set_x2(s.lnS, edge)
line.set_x2(s.lnT1, edge)
line.set_x2(s.lnT2, edge)
// ───── Status panel
color P_TXT = chart.fg_color
color P_DIM = color.new(chart.fg_color, 50)
f_cell(table tb, int c, int r, string txt, color col, string al) =>
table.cell(tb, c, r, txt, text_color = col, text_size = panelSize, text_halign = al)
var table panel = table.new(panelPos, 4, 40, bgcolor = color.new(chart.bg_color, 6), frame_color = color.new(C_N, 55), frame_width = 1, border_width = 0)
if barstate.islast and showPanel
table.clear(panel, 0, 0, 3, 39)
int row = 0
f_cell(panel, 0, row, not hasPlan ? "Gold Trader plan" : "Gold Trader plan · week of " + weekStr, P_TXT, text.align_center)
table.merge_cells(panel, 0, row, 3, row)
row += 1
string note = not hasPlan ? "Paste this week's plan in the settings" : na(weekStart) ? "The plan has no week date (W=)" : expired and not showOld ? "This plan has expired · paste this week's plan" : expired ? "Expired plan · review mode" : ""
if note != ""
f_cell(panel, 0, row, note, C_O, text.align_center)
table.merge_cells(panel, 0, row, 3, row)
row += 1
if badTok > 0
f_cell(panel, 0, row, str.tostring(badTok) + " item(s) in the plan could not be read", C_O, text.align_center)
table.merge_cells(panel, 0, row, 3, row)
row += 1
if visible
if rules.size() > 0 and row < 39
f_cell(panel, 1, row, "Protection alerts", P_DIM, text.align_left)
f_cell(panel, 2, row, "Status", P_DIM, text.align_left)
if panelMore
f_cell(panel, 3, row, "What changes it", P_DIM, text.align_left)
row += 1
for r in rules
if row < 39
color rc = f_sevColor(r.sev)
string topLab = r.under ? r.effBy : ""
bool rOn = r.eff
string rState = not r.usable ? "Not tracked" : rOn ? "ON" : "Clear"
string rMore = not r.usable ? "open a " + f_tfTxt(r.tf) + " chart or lower" : topLab != "" ? "included in " + topLab : r.active ? "clears with a " + f_tfTxt(r.tf) + " close " + (r.below ? "above " : "below ") + f_p(r.resetLvl) : "switches on with a " + f_tfTxt(r.tf) + " close " + (r.below ? "below " : "above ") + f_p(r.lvl)
f_cell(panel, 0, row, "●", rOn ? rc : color.new(rc, 65), text.align_center)
f_cell(panel, 1, row, r.label, rOn ? P_TXT : P_DIM, text.align_left)
f_cell(panel, 2, row, rState, rOn ? rc : P_DIM, text.align_left)
if panelMore
f_cell(panel, 3, row, rMore, P_DIM, text.align_left)
row += 1
if setups.size() > 0 and row < 39
f_cell(panel, 1, row, "Trade setups", P_DIM, text.align_left)
f_cell(panel, 2, row, "Status", P_DIM, text.align_left)
if panelMore
f_cell(panel, 3, row, "What happens next", P_DIM, text.align_left)
row += 1
for s in setups
if row < 39
color sc = s.isLong ? C_BULL : C_BEAR
bool pOff = f_ruleOn(s.offRule)
bool pNeed = s.needRule == "" or f_ruleOnRaw(s.needRule)
float pStop = s.beDone ? s.entry : s.stopPx
string pTgt = na(s.tp2) ? f_p(s.tp1) : s.tp1Done ? f_p(s.tp2) : f_p(s.tp1) + " then " + f_p(s.tp2)
string sState = "Waiting"
string sMore = "for price to reach " + f_p(s.zLo) + "–" + f_p(s.zHi)
color sCol = P_DIM
if not s.usable
sState := "Not tracked"
sMore := "open a 15M chart or lower"
if s.usable and s.state == 0 and pOff
sState := "Switched off"
sMore := "while " + f_whichOn(s.offRule) + " is on"
if s.usable and s.state == 0 and not pOff and not pNeed
sState := "Standby"
sMore := "goes live once " + f_nameOf(s.needRule) + " is on"
if s.usable and s.state == 0 and not pOff and pNeed and s.touched and not s.blown
sState := "In the zone"
sMore := "needs a " + f_tfTxt(s.tf) + " close " + (s.isLong ? "above " : "below ") + f_p(s.trig)
sCol := C_Y
if s.usable and s.state == 0 and not pOff and pNeed and s.blown
sState := "Overshot"
sMore := "price ran past " + f_p(s.isLong ? s.zLo : s.zHi) + " · this move is skipped · waiting for a new move into " + f_p(s.zLo) + "–" + f_p(s.zHi)
if s.usable and s.state == 0 and s.lastRes != ""
sMore := sMore + " · last trade: " + s.lastRes
if s.usable and s.state == 4
sState := "Confirmed"
sMore := "enter on a 15M " + (s.isLong ? "bullish" : "bearish") + " close inside " + f_p(s.rLo) + "–" + f_p(s.rHi)
sCol := C_Y
if s.usable and s.state == 1
sState := "Missed the fill"
sMore := "valid if price returns to " + f_p(s.cap) + " · " + str.tostring(s.retestLeft) + " candles left"
sCol := C_Y
if s.usable and s.state == 2
sState := "IN TRADE"
sMore := "from " + f_p(s.entry) + " · stop " + f_p(pStop) + " · target " + pTgt
sCol := sc
f_cell(panel, 0, row, s.isLong ? "▲" : "▼", s.state == 2 ? sc : color.new(sc, 55), text.align_center)
f_cell(panel, 1, row, s.label, s.state == 2 ? P_TXT : P_DIM, text.align_left)
f_cell(panel, 2, row, sState, sCol, text.align_left)
if panelMore
f_cell(panel, 3, row, sMore, P_DIM, text.align_left)
row += 1
if (chartSec > 900 or 900 % chartSec != 0) and row < 39
f_cell(panel, 0, row, "Use a 15M, 5M, 3M or 1M chart to track setups and 1H alerts", C_O, text.align_center)
table.merge_cells(panel, 0, row, 3, row)
row += 1
if not expired and firstBarTime > weekStart and row < 39
f_cell(panel, 0, row, "This chart's history starts after the week began · statuses may be incomplete · try a 15M chart", C_O, text.align_center)
table.merge_cells(panel, 0, row, 3, row)
row += 1
if not expired and time < weekStart and row < 39
f_cell(panel, 0, row, "Preview · tracking starts when the week opens", P_DIM, text.align_center)
table.merge_cells(panel, 0, row, 3, row)