本页源码来自 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/
// © 2026 Genexus
//
// GX Key Zones 0.2.0
// Confluence zones built from key levels (previous day/week, premarket, opening range, swings, pivots,
// round numbers). Marks how price reacts to a zone: HOLD (rejection, closes back out of the zone with a wick)
// or BREAK (decisive close through the zone). The strongest zone on screen gets a star.
// Defaults for US stocks on a 15-minute chart.
//
// Idea credit: "Key Level Confluence & Target Zones" by PhenLabs (MPL 2.0) — level clustering into
// confluence zones and the hold / breakout candle rules. This file is a rewrite with a different level set,
// weighted scoring, optional regime filter, no trade plan and no performance table.
//
// Reference levels only: no entries, stops or targets. Not investment advice. Trading involves risk of loss.
//@version=6
indicator("GX Key Zones", shorttitle = "GX Zones", overlay = true, max_boxes_count = 50, max_labels_count = 300)
const string TZ = "America/New_York"
// ═══════════════════════════ INPUTS ═══════════════════════════
const string G_LV = "1. Levels"
bool useDay = input.bool(true, "Previous day high / low / close", group = G_LV)
bool useWeek = input.bool(true, "Previous week high / low", group = G_LV)
bool usePM = input.bool(true, "Premarket high / low", group = G_LV, tooltip = "From extended-hours data (04:00–09:30 ET). Used from 09:30.")
bool useOR = input.bool(true, "Opening range", group = G_LV, inline = "or")
int orMin = input.int(15, "", options = [5, 15, 30], group = G_LV, inline = "or", tooltip = "Minutes after 09:30 ET. Used once the range is complete.")
bool useSwing = input.bool(true, "Swing highs / lows", group = G_LV, inline = "sw")
int swingLen = input.int(10, "length", minval = 3, maxval = 50, group = G_LV, inline = "sw", tooltip = "A swing is confirmed this many bars after it forms. The last two swing highs and lows are used.")
bool usePiv = input.bool(true, "Daily pivots (P, R1/S1, R2/S2)", group = G_LV)
bool useRound = input.bool(true, "Round numbers", group = G_LV)
const string G_ZN = "2. Zones"
float tolAtr = input.float(0.35, "Merge distance (ATR)", minval = 0.05, maxval = 1.5, step = 0.05, group = G_ZN, tooltip = "Levels this close together are merged into one zone.")
float minScore = input.float(3.0, "Min zone score", minval = 1.0, maxval = 15.0, step = 0.5, group = G_ZN, tooltip = "Weights: prev week H/L 3 · prev day H/L 2 · premarket H/L 2 · prev close 1.5 · opening range 1.5 · swing 1.5 · pivot 1 · round 1. A zone also needs at least 2 levels.")
float strongSc = input.float(5.0, "Strong zone from score", minval = 2.0, maxval = 20.0, step = 0.5, group = G_ZN, tooltip = "Strong zones get a thicker border.")
const string G_RX = "3. Zone reactions"
string rxMode = input.string("Both", "Mark", options = ["Both", "Hold only", "Break only"], group = G_RX, tooltip = "HOLD ▲ / ▼: the bar dips into a zone and closes back out of it with a wick (the zone held).\nBREAK ▲ / ▼: the bar closes through a zone with a strong body.")
float wickMin = input.float(0.35, "Hold: min rejection wick (% of bar)", minval = 0.1, maxval = 0.8, step = 0.05, group = G_RX)
float bodyMin = input.float(0.50, "Break: min body (% of bar)", minval = 0.2, maxval = 0.95, step = 0.05, group = G_RX)
float brkBuf = input.float(0.10, "Break: close beyond zone (ATR)", minval = 0.0, maxval = 1.0, step = 0.05, group = G_RX)
float brkVol = input.float(1.2, "Break: min relative volume", minval = 0.0, maxval = 5.0, step = 0.1, group = G_RX, tooltip = "Volume / 20-bar average. 0 = off. Ignored on symbols without volume.")
bool strongOnly = input.bool(false, "Only at strong zones", group = G_RX)
int cooldown = input.int(5, "Min bars between marks", minval = 0, maxval = 100, group = G_RX)
bool regFilt = input.bool(false, "Hide marks against the trend (GX Regime rules)", group = G_RX, tooltip = "Hides ▲ marks while the chart is in Trend Down and ▼ marks while in Trend Up. Trend = close vs EMA 50, EMA slope over 5 bars, ADX(14) ≥ 20 and DI direction.")
bool rthOnly = input.bool(true, "Regular session only (09:30–16:00 ET)", group = G_RX, tooltip = "Turn off for 24-hour markets (crypto, forex, futures).")
const string G_DS = "4. Display"
int nShow = input.int(4, "Zones shown (nearest)", minval = 1, maxval = 12, group = G_DS)
int zBack = input.int(40, "Zone box: bars back / forward", minval = 5, maxval = 300, group = G_DS, inline = "zb")
int zFwd = input.int(15, "", minval = 0, maxval = 100, group = G_DS, inline = "zb")
bool showTxt = input.bool(true, "Level names in zones", group = G_DS)
bool starOn = input.bool(true, "★ on the strongest zone shown", group = G_DS)
bool showTable = input.bool(true, "Table", group = G_DS, inline = "tb")
string tbPosIn = input.string("Bottom Right", "", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = G_DS, inline = "tb")
color bullC = input.color(#089981, "Below / Above / In zone", group = G_DS, inline = "c")
color bearC = input.color(#f23645, "", group = G_DS, inline = "c")
color zoneC = input.color(#ffd600, "", group = G_DS, inline = "c")
const string G_AL = "5. Alerts"
string alFormat = input.string("Text", "Alert message", options = ["Text", "Discord"], group = G_AL, tooltip = "For alerts created with \"Any alert() function call\". Discord: JSON for a Discord channel webhook.")
string alName = input.string("GX Key Zones", "Name in message", group = G_AL)
// ═══════════════════════════ CORE SERIES ═══════════════════════════
bool intraday = timeframe.isintraday
int tfSec = timeframe.in_seconds()
float atr = ta.atr(14)
bool hasVol = ta.cum(nz(volume)) > 0
float relVol = volume / math.max(nz(ta.sma(volume, 20)), 1e-9)
f_dayKey(int t) =>
year(t, TZ) * 10000 + month(t, TZ) * 100 + dayofmonth(t, TZ)
int nyKey = f_dayKey(time)
bool newDay = nyKey != nyKey[1]
bool inRTH = not na(time(timeframe.period, "0930-1600", TZ))
bool afterOpn = not na(time(timeframe.period, "0930-2000", TZ))
bool sessOk = not rthOnly or not intraday or inRTH
// Regime (same rules as GX Regime, no confirmation)
float emaT = ta.ema(close, 50)
[diP, diM, adx] = ta.dmi(14, 14)
int regime = close > emaT and emaT > emaT[5] and adx >= 20 and diP > diM ? 1 : close < emaT and emaT < emaT[5] and adx >= 20 and diM > diP ? -1 : 0
// ═══════════════════════════ LEVELS ═══════════════════════════
// Previous completed day / week: [1] inside the request + lookahead_on = closed bars only, no repaint
[pdh, pdl, pdc] = request.security(syminfo.tickerid, "D", [high[1], low[1], close[1]], lookahead = barmerge.lookahead_on)
[pwh, pwl] = request.security(syminfo.tickerid, "W", [high[1], low[1]], lookahead = barmerge.lookahead_on)
// Premarket from the extended-hours feed, same timeframe, no lookahead
f_pm() =>
var float h = na
var float l = na
var int k = na
if not na(time(timeframe.period, "0400-0930", TZ))
int dk = f_dayKey(time)
if dk != k
h := high
l := low
k := dk
else
h := math.max(h, high)
l := math.min(l, low)
[h, l, k]
[pmH, pmL, pmK] = request.security(ticker.modify(syminfo.tickerid, session.extended), timeframe.period, f_pm())
bool pmOk = intraday and pmK == nyKey and afterOpn
// Opening range, used only after it is complete
string orEnd = orMin == 5 ? "0935" : orMin == 30 ? "1000" : "0945"
bool inOR = not na(time(timeframe.period, "0930-" + orEnd, TZ))
bool orFits = intraday and tfSec <= orMin * 60 and (orMin * 60) % tfSec == 0
var float orH = na
var float orL = na
if newDay
orH := na
orL := na
if inOR
orH := na(orH) ? high : math.max(orH, high)
orL := na(orL) ? low : math.min(orL, low)
bool orOk = orFits and afterOpn and not inOR and not na(orH)
// Swings (confirmed swingLen bars later)
float ph = ta.pivothigh(high, swingLen, swingLen)
float pl = ta.pivotlow(low, swingLen, swingLen)
var float sh1 = na
var float sh2 = na
var float sl1 = na
var float sl2 = na
if not na(ph)
sh2 := sh1
sh1 := ph
if not na(pl)
sl2 := sl1
sl1 := pl
// Classic daily pivots from the previous day
float pvP = (pdh + pdl + pdc) / 3.0
float pvR1 = 2.0 * pvP - pdl
float pvS1 = 2.0 * pvP - pdh
float pvR2 = pvP + (pdh - pdl)
float pvS2 = pvP - (pdh - pdl)
// Round numbers: nearest below and above, step by price size
f_step(float p) =>
p < 20 ? 1.0 : p < 100 ? 5.0 : p < 500 ? 10.0 : p < 2000 ? 50.0 : p < 20000 ? 500.0 : 1000.0
float rStep = f_step(close)
float rnDn = math.floor(close / rStep) * rStep
float rnUp = rnDn + rStep
var array<float> lvP = array.new<float>()
var array<float> lvW = array.new<float>()
var array<string> lvN = array.new<string>()
lvP.clear()
lvW.clear()
lvN.clear()
f_add(float v, float w, string nm) =>
if not na(v)
lvP.push(v)
lvW.push(w)
lvN.push(nm)
true
bool dOk = tfSec <= 86400
bool wOk = tfSec <= 604800
if useDay and dOk
f_add(pdh, 2.0, "PDH")
f_add(pdl, 2.0, "PDL")
f_add(pdc, 1.5, "PDC")
if useWeek and wOk
f_add(pwh, 3.0, "PWH")
f_add(pwl, 3.0, "PWL")
if usePM and pmOk
f_add(pmH, 2.0, "PMH")
f_add(pmL, 2.0, "PML")
if useOR and orOk
f_add(orH, 1.5, "ORH")
f_add(orL, 1.5, "ORL")
if useSwing
f_add(sh1, 1.5, "SwH")
f_add(sh2, 1.5, "SwH2")
f_add(sl1, 1.5, "SwL")
f_add(sl2, 1.5, "SwL2")
if usePiv and dOk
f_add(pvP, 1.0, "P")
f_add(pvR1, 1.0, "R1")
f_add(pvS1, 1.0, "S1")
f_add(pvR2, 1.0, "R2")
f_add(pvS2, 1.0, "S2")
if useRound
f_add(rnDn, 1.0, "Rnd")
f_add(rnUp, 1.0, "Rnd")
// ═══════════════════════════ ZONES (clustering) ═══════════════════════════
var array<float> zTop = array.new<float>()
var array<float> zBot = array.new<float>()
var array<float> zSc = array.new<float>()
var array<int> zCnt = array.new<int>()
var array<string> zNm = array.new<string>()
zTop.clear()
zBot.clear()
zSc.clear()
zCnt.clear()
zNm.clear()
f_push(int cnt, float sc, float lo, float hi, string nm) =>
if cnt >= 2 and sc >= minScore
float mid = (lo + hi) / 2.0
float h = math.max(hi - lo, 0.15 * atr)
zTop.push(mid + h / 2.0)
zBot.push(mid - h / 2.0)
zSc.push(sc)
zCnt.push(cnt)
zNm.push(nm)
true
int nLv = lvP.size()
if nLv >= 2 and not na(atr)
array<int> idx = lvP.sort_indices(order.ascending)
float tol = tolAtr * atr
int gCnt = 0
float gSc = 0.0
float gLo = na
float gHi = na
string gNm = ""
for k = 0 to nLv - 1
int j = idx.get(k)
float v = lvP.get(j)
if gCnt > 0 and (v - gHi > tol or v - gLo > 2.0 * tol)
f_push(gCnt, gSc, gLo, gHi, gNm)
gCnt := 0
gSc := 0.0
gNm := ""
if gCnt == 0
gLo := v
gHi := v
gCnt += 1
gSc += lvW.get(j)
gNm := gNm == "" ? lvN.get(j) : gNm + " + " + lvN.get(j)
if gCnt > 0
f_push(gCnt, gSc, gLo, gHi, gNm)
int nZ = zTop.size()
// ═══════════════════════════ ZONE REACTIONS ═══════════════════════════
// rDir: +1 ▲ (support held / broke up), -1 ▼ (resistance held / broke down). rKind: 1 HOLD, 2 BREAK
int rDir = 0
int rKind = 0
int rZi = -1
var int lastMark = na
bool cdOk = na(lastMark) or bar_index - lastMark >= cooldown
if barstate.isconfirmed and nZ > 0 and not na(atr) and sessOk and cdOk
float rng = math.max(high - low, syminfo.mintick)
float lw = (math.min(open, close) - low) / rng
float uw = (high - math.max(open, close)) / rng
float bodyR = math.abs(close - open) / rng
float pc = nz(close[1], close)
bool volOk = not hasVol or brkVol <= 0 or relVol >= brkVol
float best = -1.0
for i = 0 to nZ - 1
float t = zTop.get(i)
float b = zBot.get(i)
float sc = zSc.get(i)
int d = 0
int k = 0
if rxMode != "Break only"
// HOLD: came from the outside, dipped into the zone (not far through), closed back out with a wick
if pc >= b and low <= t and low >= b - 0.5 * atr and close > t and close > open and lw >= wickMin
d := 1
k := 1
else if pc <= t and high >= b and high <= t + 0.5 * atr and close < b and close < open and uw >= wickMin
d := -1
k := 1
if d == 0 and rxMode != "Hold only"
// BREAK: previous close on the other side, decisive close through with a strong body and volume
if pc <= t and close > t + brkBuf * atr and close > open and bodyR >= bodyMin and volOk
d := 1
k := 2
else if pc >= b and close < b - brkBuf * atr and close < open and bodyR >= bodyMin and volOk
d := -1
k := 2
bool regOk = not regFilt or (d == 1 ? regime != -1 : regime != 1)
bool scOk = not strongOnly or sc >= strongSc
if d != 0 and regOk and scOk and sc > best
rDir := d
rKind := k
rZi := i
best := sc
f_rxName(int d, int k) =>
(k == 1 ? "HOLD " : "BREAK ") + (d == 1 ? "▲" : "▼")
var int lDir = 0
var int lKind = 0
var int lBar = na
var float lPx = na
var string lZone = ""
var float lSc = na
if rDir != 0
lastMark := bar_index
lDir := rDir
lKind := rKind
lBar := bar_index
lPx := close
lZone := zNm.get(rZi)
lSc := zSc.get(rZi)
string tt = (rKind == 1 ? "Zone held" : "Close through zone") + " · " + lZone + " · score " + str.tostring(lSc, "#.#")
label.new(bar_index, rDir == 1 ? low : high, f_rxName(rDir, rKind), style = rDir == 1 ? label.style_label_up : label.style_label_down, color = color.new(rDir == 1 ? bullC : bearC, rKind == 1 ? 25 : 0), textcolor = color.white, size = size.small, tooltip = tt)
// ═══════════════════════════ DRAW: ZONES + STAR (last bar) ═══════════════════════════
var array<box> zBoxes = array.new<box>()
var label starLb = na
if barstate.islast
for bx in zBoxes
bx.delete()
zBoxes.clear()
starLb.delete()
if nZ > 0
array<float> dist = array.new<float>()
for i = 0 to nZ - 1
dist.push(math.abs((zTop.get(i) + zBot.get(i)) / 2.0 - close))
array<int> ord = dist.sort_indices(order.ascending)
int cnt = math.min(nShow, nZ)
int topI = -1
float topSc = -1.0
for k = 0 to cnt - 1
int i = ord.get(k)
float t = zTop.get(i)
float b = zBot.get(i)
float sc = zSc.get(i)
bool strong = sc >= strongSc
if sc > topSc
topSc := sc
topI := i
color base = b > close ? bearC : t < close ? bullC : zoneC
string txt = showTxt ? zNm.get(i) + " · " + str.tostring(sc, "#.#") : ""
zBoxes.push(box.new(bar_index - zBack, t, bar_index + zFwd, b, bgcolor = color.new(base, strong ? 75 : 87), border_color = color.new(base, strong ? 30 : 65), border_width = strong ? 2 : 1, text = txt, text_size = size.tiny, text_color = color.new(chart.fg_color, 15), text_halign = text.align_right, text_valign = text.align_center))
if starOn and topI >= 0
float midS = (zTop.get(topI) + zBot.get(topI)) / 2.0
starLb := label.new(bar_index + zFwd + 1, midS, "★", style = label.style_label_left, color = color.new(color.black, 100), textcolor = zoneC, size = size.large, tooltip = "Strongest zone shown · " + zNm.get(topI) + " · score " + str.tostring(topSc, "#.#"))
// ═══════════════════════════ TABLE ═══════════════════════════
string tbPos = switch tbPosIn
"Top Right" => position.top_right
"Top Left" => position.top_left
"Bottom Left" => position.bottom_left
=> position.bottom_right
var table tb = table.new(tbPos, 2, 6, bgcolor = color.new(#131722, 10), frame_color = #363a45, frame_width = 1, border_color = #363a45, border_width = 1)
f_cell(int c, int r, string t, color tc, bool bold = false) =>
table.cell(tb, c, r, t, text_color = tc, text_size = size.small, text_halign = c == 0 ? text.align_left : text.align_right, text_formatting = bold ? text.format_bold : text.format_none)
f_px(float x) =>
na(x) ? "—" : str.tostring(x, format.mintick)
f_tf() =>
timeframe.isintraday ? (timeframe.multiplier % 60 == 0 ? str.tostring(timeframe.multiplier / 60) + "h" : str.tostring(timeframe.multiplier) + "m") : timeframe.period
if barstate.islast and showTable
color txt = #d1d4dc
color dim = #9598a1
// nearest zone below price (support) and above price (resistance)
string supT = "—"
string resT = "—"
string inT = ""
float supD = 1e18
float resD = 1e18
if nZ > 0
for i = 0 to nZ - 1
float t = zTop.get(i)
float b = zBot.get(i)
string d = f_px((t + b) / 2.0) + " · " + str.tostring(zSc.get(i), "#.#")
if t < close and close - t < supD
supD := close - t
supT := d
else if b > close and b - close < resD
resD := b - close
resT := d
else if b <= close and t >= close
inT := d
f_cell(0, 0, "GX Key Zones", txt, true)
f_cell(1, 0, f_tf(), dim)
f_cell(0, 1, "Last mark", dim)
f_cell(1, 1, lDir == 0 ? "—" : f_rxName(lDir, lKind) + " · " + str.tostring(bar_index - lBar) + " bars ago", lDir == 1 ? bullC : lDir == -1 ? bearC : dim, true)
f_cell(0, 2, "At zone", dim)
f_cell(1, 2, lDir == 0 ? "—" : lZone + " · " + str.tostring(lSc, "#.#"), dim)
f_cell(0, 3, "Above", dim)
f_cell(1, 3, inT != "" ? "In zone " + inT : resT, inT != "" ? zoneC : bearC)
f_cell(0, 4, "Below", dim)
f_cell(1, 4, supT, bullC)
f_cell(0, 5, "Regime", dim)
f_cell(1, 5, regime == 1 ? "Trend Up" : regime == -1 ? "Trend Down" : "No trend", regime == 1 ? bullC : regime == -1 ? bearC : dim)
// ═══════════════════════════ DATA WINDOW ═══════════════════════════
plot(rDir * rKind, "Mark (±1 hold, ±2 break)", display = display.data_window)
plot(nZ, "Zones", display = display.data_window)
// ═══════════════════════════ ALERTS ═══════════════════════════
alertcondition(rKind == 1 and rDir == 1, "HOLD ▲ (support held)", "GX Key Zones: HOLD ▲ on {{ticker}} {{interval}} at {{close}}")
alertcondition(rKind == 1 and rDir == -1, "HOLD ▼ (resistance held)", "GX Key Zones: HOLD ▼ on {{ticker}} {{interval}} at {{close}}")
alertcondition(rKind == 2 and rDir == 1, "BREAK ▲ (closed above)", "GX Key Zones: BREAK ▲ on {{ticker}} {{interval}} at {{close}}")
alertcondition(rKind == 2 and rDir == -1, "BREAK ▼ (closed below)", "GX Key Zones: BREAK ▼ on {{ticker}} {{interval}} at {{close}}")
alertcondition(rDir != 0, "Any zone mark", "GX Key Zones: zone mark on {{ticker}} {{interval}} at {{close}}")
if rDir != 0
string nm = str.replace_all(str.replace_all(alName, "\\", ""), "\"", "'")
string what = rKind == 1 ? (rDir == 1 ? "Support zone held" : "Resistance zone held") : (rDir == 1 ? "Closed above zone" : "Closed below zone")
string title = f_rxName(rDir, rKind) + " · " + syminfo.ticker + " · " + f_tf()
string body = what + "\nZone " + lZone + " (score " + str.tostring(lSc, "#.#") + ")\nClose " + f_px(close)
if alFormat == "Discord"
string foot = "GX Key Zones · Reference levels only · Not a trade signal · Not investment advice · Trading involves risk of loss"
int col = rDir == 1 ? 563585 : 15873605
alert("{\"username\":\"" + nm + "\",\"embeds\":[{\"title\":\"" + title + "\",\"description\":\"" + str.replace_all(body, "\n", "\\n") + "\",\"color\":" + str.tostring(col) + ",\"footer\":{\"text\":\"" + foot + "\"}}]}", alert.freq_once_per_bar_close)
else
alert(nm + " · " + title + " | " + str.replace_all(body, "\n", " | "), alert.freq_once_per_bar_close)