本页源码来自 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/
// © Titpaud
// This Pine Script code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Titpaud
// Titpaud ICT - visual aid, no entry / exit signals.
// v1 (2026-11-01): market structure (BOS / CHoCH) with the x4 / x16 trend, equal highs / lows,
// golden pockets on the swings of four layers (x1 x4 x16 x64), previous day / week / month
// highs and lows still untaken, break-even lines around the price,
// premium / discount and sweeps as options.
// v1.2 (2026-11-01): a golden pocket (current or past) disappears once a wick has crossed it completely
// (beyond its far edge); labels of previous highs / lows at nearly the same price are merged.
// v1.3 (2026-11-01): unconfirmed golden pockets: from the last confirmed swing to the extreme reached since then,
// before the reversal is confirmed by a pivot (they move with the price).
// v1.4 (2026-11-01): unconfirmed golden pockets also on the move back from that extreme
// (e.g. last confirmed high -> lowest low since -> highest high after it); orange by default.
// v1.6 (2026-11-01): golden pocket swings by amplitude (default): a high is confirmed once the price falls
// k x ATR50 below it, a low once it rises k x ATR50 above it (k x1, 2k x4, 4k x16, 8k x64).
// The former mode (pivots with a number of bars on each side) stays as an option.
// v1.7 (2026-11-01): premium / discount more visible (transparency setting, "Premium" / "Discount" written in the zones).
// v1.8 (2026-11-01): sweeps on every TF, shown as a small lightning bolt; choice of the smallest swing layer swept
// (x1 x4 x16 x64), sweeps of previous D / W / M levels as a separate option.
// v1.9 (2026-11-01): sweeps on by default with one box per layer (only x16 checked); premium / discount reduced to
// the extremes of the range (5 % by default) with a dotted equilibrium line in the middle.
// v2.0 (2026-11-01): structure (BOS / CHoCH, equal highs / lows, trends, sweeps) on the same amplitude swings as the
// golden pockets (default; pivots with bars as an option); alerts (one alert "Any alert() function call").
// v2.1 (2026-11-01): each alert type also listed on its own in the alert window (alertcondition), next to "Any alert()".
// v2.2 (2026-11-01): the premium / discount range follows a new high or low not yet confirmed as a swing.
// Original code. Every layer (x1 x4 x16 x64) is computed on the chart TF with larger swing thresholds
// (no request of other TFs). A swing is drawn at its exact bar once it is confirmed.
//@version=6
indicator("Titpaud ICT", "TitpaudICT", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_bars_back = 5000)
// ───────────────────────────────────── ON / OFF ─────────────────────────────────────
const string G_ON = "ON / OFF"
bool onStr = input.bool(true, "Structure (BOS / CHoCH)", group = G_ON)
bool onTrd = input.bool(true, "Trend label x1 / x4 / x16", group = G_ON)
bool onEq = input.bool(true, "Equal highs / lows", group = G_ON)
bool onGP = input.bool(true, "Golden pockets", group = G_ON)
bool onGPu = input.bool(true, "Unconfirmed golden pockets", group = G_ON, tooltip = "Zones of the swings not confirmed by a pivot yet, for each layer: last confirmed swing -> extreme reached since then, and that extreme -> the move back from it. They move with the price until pivots confirm them.")
bool onPrev = input.bool(true, "Previous highs / lows still untaken", group = G_ON)
bool onBE = input.bool(true, "Break-even lines", group = G_ON)
bool onPD = input.bool(false, "Premium / discount", group = G_ON)
bool onSw = input.bool(true, "Sweeps", group = G_ON)
// ───────────────────────────────────── ALERTS ─────────────────────────────────────
const string G_AL = "Alerts (create one alert: Any alert() function call)"
bool alPD = input.bool(true, "Premium / discount zone entered", group = G_AL)
bool alGP = input.bool(true, "Golden pocket entered", group = G_AL, tooltip = "Current (yellow) or unconfirmed (orange) golden pocket of a displayed layer, entered by this bar.")
bool alSwGP = input.bool(false, "Sweep inside a golden pocket", group = G_AL, tooltip = "Same bar: a sweep (layers checked in Sweeps) and a wick inside a golden pocket.")
bool alOv = input.bool(false, "Overlapping golden pockets entered", group = G_AL, tooltip = "The bar is inside the golden pockets of at least 2 layers, one of them just entered.")
bool alSw = input.bool(false, "Sweep", group = G_AL)
bool alCh = input.bool(false, "CHoCH", group = G_AL)
string alChL = input.string("x1", "CHoCH of layer", options = ["x1", "x4", "x16"], group = G_AL)
bool alAl = input.bool(false, "Trend alignment x1 / x4 / x16", group = G_AL, tooltip = "The three trends turn the same way (the trend label turns green or red).")
bool alLv = input.bool(false, "Previous D / W / M high / low taken", group = G_AL)
bool alEq = input.bool(false, "Equal highs / lows taken", group = G_AL)
// ───────────────────────────────────── STRUCTURE ─────────────────────────────────────
const string G_ST = "Structure"
string stMode = input.string("Reversal (ATR)", "Structure swings", options = ["Reversal (ATR)", "Pivots (bars)"], group = G_ST, tooltip = "Reversal (ATR): the same swings as the golden pockets (a swing is confirmed once the price comes back k x ATR50, see \"Reversal size x1\"): x1 / x4 / x16 / x64 = k, 2k, 4k, 8k. Pivots (bars): swings with \"Swing length\" bars on each side (x4 / x16 / x64 = 4, 16, 64 times more).")
int strLen = input.int(5, "Swing length x1 (pivot mode)", minval = 2, maxval = 50, group = G_ST, tooltip = "Bars on each side of a swing high / low of the chart TF. The x4 and x16 trends use swings 4 and 16 times larger. A swing is known only this number of bars after it.")
int strKeep = input.int(30, "BOS / CHoCH kept", minval = 1, maxval = 150, group = G_ST)
color colBull = input.color(#26a69a, "Bullish color", group = G_ST)
color colBear = input.color(#ef5350, "Bearish color", group = G_ST)
const string G_EQ = "Equal highs / lows"
float eqTol = input.float(0.1, "Tolerance (x ATR200)", minval = 0.01, maxval = 1.0, step = 0.01, group = G_EQ, tooltip = "Two swing highs (or lows) of the structure are equal when their gap is under this fraction of the ATR200.")
int eqKeep = input.int(20, "Max equal levels per side", minval = 1, maxval = 60, group = G_EQ)
color colEq = input.color(color.new(#b0bec5, 20), "Equal levels color", group = G_EQ, tooltip = "The line disappears as soon as a wick takes the level.")
// ───────────────────────────────────── GOLDEN POCKETS ─────────────────────────────────────
const string G_GP = "Golden pockets"
string gpMode = input.string("Reversal (ATR)", "Swing detection", options = ["Reversal (ATR)", "Pivots (bars)"], group = G_GP, tooltip = "Reversal (ATR): a swing high is confirmed as soon as the price falls k x ATR50 below it (a swing low: rises k x ATR50 above it), however many bars it takes. One strong candle can confirm it. Pivots (bars): a swing needs \"Big swing length\" bars on each side.")
float gpK = input.float(2.0, "Reversal size x1 (x ATR50)", minval = 0.2, maxval = 20.0, step = 0.1, group = G_GP, tooltip = "Reversal mode. Layers x4 / x16 / x64 use 2, 4 and 8 times this size (moves grow about as the square root of time: a TF 4 times larger moves about 2 times more).")
bool gp1 = input.bool(true, "Golden pockets x1 (chart TF)", group = G_GP)
bool gp2 = input.bool(true, "Golden pockets x4", group = G_GP)
bool gp3 = input.bool(true, "Golden pockets x16", group = G_GP)
bool gp4 = input.bool(true, "Golden pockets x64", group = G_GP)
int gpLen = input.int(10, "Big swing length x1 (pivot mode)", minval = 2, maxval = 50, group = G_GP, tooltip = "Bars on each side of a big swing on the x1 layer. Layers x4 / x16 / x64 multiply it (10 x 64 = 640 bars on each side: x64 needs a long history).")
float gpA = input.float(0.618, "Zone from (retracement)", minval = 0.0, maxval = 1.0, step = 0.001, group = G_GP, tooltip = "0.618 - 0.65 = golden pocket. 0.62 - 0.79 = ICT OTE.")
float gpB = input.float(0.65, "Zone to (retracement)", minval = 0.0, maxval = 1.0, step = 0.001, group = G_GP)
int gpPast = input.int(2, "Past golden pockets per layer", minval = 0, maxval = 20, group = G_GP, tooltip = "Golden pockets of the previous swings, stopped where the next swing starts.")
bool gpHideBr = input.bool(true, "Hide when the swing start is broken", group = G_GP, tooltip = "The current golden pocket disappears once a close goes beyond the start of its swing (the swing is no longer valid).")
bool gpFill = input.bool(true, "Hide when completely crossed", group = G_GP, tooltip = "A golden pocket (current or past) disappears once a wick has crossed the whole zone, beyond its far edge. A simple touch keeps it.")
int gpExt = input.int(20, "Extension to the right (bars)", minval = 0, maxval = 400, group = G_GP)
bool gpLbl = input.bool(true, "Labels with overlaps", group = G_GP, tooltip = "\"GP x16 + x4\" = the x16 golden pocket overlaps the x4 one. Overlapping zones also look darker.")
color gpCol = input.color(#ffd600, "Color", group = G_GP)
color gpUCol = input.color(#ff9800, "Unconfirmed color", group = G_GP)
int gpTr = input.int(85, "Fill transparency", minval = 50, maxval = 98, group = G_GP, tooltip = "Each layer is filled with this transparency, so overlapping golden pockets add up and look darker. Past ones are lighter.")
// ───────────────────────────────────── PREVIOUS HIGHS / LOWS ─────────────────────────────────────
const string G_PV = "Previous highs / lows"
bool pvD = input.bool(true, "Daily levels", group = G_PV)
bool pvW = input.bool(true, "Weekly levels", group = G_PV)
bool pvM = input.bool(true, "Monthly levels", group = G_PV)
int pvN = input.int(3, "Nearest untaken levels per side", minval = 1, maxval = 20, group = G_PV, tooltip = "For each period (day, week, month), the untaken highs above and lows below that are nearest to the price. A level disappears as soon as a wick takes it.")
float pvMrg = input.float(0.3, "Merge labels closer than (x ATR200)", minval = 0.0, maxval = 3.0, step = 0.05, group = G_PV, tooltip = "Levels nearer to each other than this share one label (\"DL / PWL\"). 0 = never merge.")
int pvExt = input.int(15, "Extension to the right (bars)", minval = 0, maxval = 400, group = G_PV)
color pvColD = input.color(color.new(#64b5f6, 10), "Daily color", group = G_PV)
color pvColW = input.color(color.new(#ffb74d, 10), "Weekly color", group = G_PV)
color pvColM = input.color(color.new(#ce93d8, 10), "Monthly color", group = G_PV)
// ───────────────────────────────────── BREAK-EVEN ─────────────────────────────────────
const string G_BE = "Break-even lines"
float beIn = input.float(0.1, "Entry fee (%)", minval = 0.0, maxval = 1.0, step = 0.005, group = G_BE, tooltip = "Fee of the entry order. Binance futures: about 0.05 taker / 0.02 maker. Spot: 0.1.")
float beOut = input.float(0.1, "Exit fee (%)", minval = 0.0, maxval = 1.0, step = 0.005, group = G_BE)
float beRef = input.float(0.0, "Entry price (0 = last price)", minval = 0.0, group = G_BE, tooltip = "0: the lines follow the last price (where a trade opened now breaks even). Otherwise: the price of your open trade.")
bool beX2 = input.bool(true, "Also 2x and 3x the fees", group = G_BE, tooltip = "Extra lines at 2 and 3 times the break-even distance (first real gains).")
color beCol = input.color(color.new(#e0e0e0, 30), "Color", group = G_BE)
// ───────────────────────────────────── OPTIONS ─────────────────────────────────────
const string G_PD = "Premium / discount"
string pdLay = input.string("x4", "Swing of layer", options = ["x1", "x4", "x16", "x64"], group = G_PD, tooltip = "Range between the last big swing high and low of this golden pocket layer. Only its extremes are colored: top = premium, bottom = discount, dotted line = equilibrium (50 %).")
float pdExt = input.float(5.0, "Extreme zone size (%)", minval = 1.0, maxval = 50.0, step = 1.0, group = G_PD, tooltip = "Part of the range colored at the top (premium) and at the bottom (discount). 50 = the whole range cut in two.")
int pdTr = input.int(85, "Fill transparency", minval = 0, maxval = 98, group = G_PD)
const string G_SW = "Sweeps"
bool sw1 = input.bool(false, "Sweeps of x1 swings (chart TF)", group = G_SW, tooltip = "Sweep = a wick goes beyond a swing and the bar closes back inside (one bolt per swing). Swing size = structure swing length x 1 / 4 / 16 / 64: x4 is about the 4h swings on a 1h chart.")
bool sw2 = input.bool(false, "Sweeps of x4 swings", group = G_SW)
bool sw3 = input.bool(true, "Sweeps of x16 swings", group = G_SW)
bool sw4 = input.bool(false, "Sweeps of x64 swings", group = G_SW)
bool swLv = input.bool(false, "Sweeps of previous D / W / M highs / lows", group = G_SW, tooltip = "Also a bolt when a wick takes an untaken previous high / low and the bar closes back inside (needs the previous highs / lows on).")
// ───────────────────────────────────── COMMON ─────────────────────────────────────
float atr = ta.atr(200)
int tfSec = timeframe.in_seconds()
f_dur(int bars) => int(bars * tfSec * 1000)
float pHi = high[1]
float pLo = low[1]
float atrZ = ta.atr(50)
// sweep markers (kept up to 100); what was swept on this bar, high side and low side
var array<label> swLbl = array.new<label>()
string swH = ""
string swL = ""
bool swCalc = true // also needed by the alerts of the alert window
// levels taken on this bar (alerts)
string lvTk = ""
string eqTk = ""
// ───────────────────────────────────── AMPLITUDE SWINGS (zigzag) ─────────────────────────────────────
// the extreme of the move in progress becomes a swing once the price has come back by "th" (k x ATR50)
type Zz
int dir = 0 // 1 looking for a high, -1 looking for a low
float p = na // extreme of the move in progress
int b = na
float nH = na // swing high confirmed on this bar (price, bar)
int nHB = na
float nL = na // swing low confirmed on this bar
int nLB = na
method zzStep(Zz z, float th) =>
z.nH := na
z.nHB := na
z.nL := na
z.nLB := na
bool first = z.dir == 0
if first
z.dir := 1
z.p := high
z.b := bar_index
bool lookHi = not first and z.dir == 1
bool lookLo = not first and z.dir == -1
if lookHi and high > z.p
z.p := high
z.b := bar_index
if lookHi and high < z.p and z.p - low >= th
z.nH := z.p
z.nHB := z.b
z.dir := -1
z.p := low
z.b := bar_index
if lookLo and low < z.p
z.p := low
z.b := bar_index
if lookLo and low > z.p and high - z.p >= th
z.nL := z.p
z.nLB := z.b
z.dir := 1
z.p := high
z.b := bar_index
var Zz z1 = Zz.new()
var Zz z2 = Zz.new()
var Zz z3 = Zz.new()
var Zz z4 = Zz.new()
if not na(atrZ)
z1.zzStep(gpK * atrZ)
z2.zzStep(gpK * 2 * atrZ)
z3.zzStep(gpK * 4 * atrZ)
z4.zzStep(gpK * 8 * atrZ)
// ───────────────────────────────────── STRUCTURE ─────────────────────────────────────
type Struct
int len
float sh = na
int shBar = na
bool shOk = false // swing high still unbroken
float sl = na
int slBar = na
bool slOk = false
int trend = 0 // 1 bullish, -1 bearish
bool shSw = false // swing already swept (one sweep label per swing)
bool slSw = false
float brkLvl = na // level and bar of the swing broken by the last event
int brkBar = na
// returns 1 bull BOS, 2 bull CHoCH, -1 bear BOS, -2 bear CHoCH, 0 nothing
method updStruct(Struct s, float ph, int phB, float pl, int plB) =>
int ev = 0
if not na(ph)
s.sh := ph
s.shBar := phB
s.shOk := true
s.shSw := false
if not na(pl)
s.sl := pl
s.slBar := plB
s.slOk := true
s.slSw := false
if s.shOk and close > s.sh
ev := s.trend == 1 ? 1 : 2
s.trend := 1
s.shOk := false
s.brkLvl := s.sh
s.brkBar := s.shBar
else if s.slOk and close < s.sl
ev := s.trend == -1 ? -1 : -2
s.trend := -1
s.slOk := false
s.brkLvl := s.sl
s.brkBar := s.slBar
ev
var Struct st1 = Struct.new(strLen)
var Struct st2 = Struct.new(strLen * 4)
var Struct st3 = Struct.new(strLen * 16)
var Struct st4 = Struct.new(strLen * 64) // sweeps only
float ph1 = ta.pivothigh(strLen, strLen)
float pl1 = ta.pivotlow(strLen, strLen)
float ph2 = ta.pivothigh(strLen * 4, strLen * 4)
float pl2 = ta.pivotlow(strLen * 4, strLen * 4)
float ph3 = ta.pivothigh(strLen * 16, strLen * 16)
float pl3 = ta.pivotlow(strLen * 16, strLen * 16)
float ph4 = ta.pivothigh(strLen * 64, strLen * 64)
float pl4 = ta.pivotlow(strLen * 64, strLen * 64)
// swings fed to the structure: amplitude swings or pivots
bool stZz = stMode == "Reversal (ATR)"
float sH1 = stZz ? z1.nH : ph1
int sH1B = stZz ? z1.nHB : bar_index - strLen
float sL1 = stZz ? z1.nL : pl1
int sL1B = stZz ? z1.nLB : bar_index - strLen
float sH2 = stZz ? z2.nH : ph2
int sH2B = stZz ? z2.nHB : bar_index - strLen * 4
float sL2 = stZz ? z2.nL : pl2
int sL2B = stZz ? z2.nLB : bar_index - strLen * 4
float sH3 = stZz ? z3.nH : ph3
int sH3B = stZz ? z3.nHB : bar_index - strLen * 16
float sL3 = stZz ? z3.nL : pl3
int sL3B = stZz ? z3.nLB : bar_index - strLen * 16
float sH4 = stZz ? z4.nH : ph4
int sH4B = stZz ? z4.nHB : bar_index - strLen * 64
float sL4 = stZz ? z4.nL : pl4
int sL4B = stZz ? z4.nLB : bar_index - strLen * 64
// sweeps of the structure swings of the chosen layers (before the update: a wick above, a close back below)
array<bool> swOn = array.from(sw1, sw2, sw3, sw4)
if swCalc
array<Struct> sts = array.from(st1, st2, st3, st4)
for j = 0 to 3
Struct sj = sts.get(j)
bool jOn = swOn.get(j)
string nm = j == 0 ? "x1" : j == 1 ? "x4" : j == 2 ? "x16" : "x64"
if jOn and sj.shOk and not sj.shSw and high > sj.sh and close <= sj.sh
swH += (swH == "" ? "" : ", ") + nm + " swing high " + str.tostring(sj.sh, format.mintick)
sj.shSw := true
if jOn and sj.slOk and not sj.slSw and low < sj.sl and close >= sj.sl
swL += (swL == "" ? "" : ", ") + nm + " swing low " + str.tostring(sj.sl, format.mintick)
sj.slSw := true
int ev1 = st1.updStruct(sH1, sH1B, sL1, sL1B)
int ev2 = st2.updStruct(sH2, sH2B, sL2, sL2B)
int ev3 = st3.updStruct(sH3, sH3B, sL3, sL3B)
int ev4 = st4.updStruct(sH4, sH4B, sL4, sL4B)
// trend alignment x1 / x4 / x16 (alerts)
int algn = st1.trend + st2.trend + st3.trend == 3 ? 1 : st1.trend + st2.trend + st3.trend == -3 ? -1 : 0
bool algnNew = algn != 0 and algn != algn[1]
int evCh = alChL == "x1" ? ev1 : alChL == "x4" ? ev2 : ev3
var array<line> stLn = array.new<line>()
var array<label> stLb = array.new<label>()
if onStr and ev1 != 0
bool up = ev1 > 0
float lvl = st1.brkLvl
int x1 = st1.brkBar
color c = up ? colBull : colBear
stLn.push(line.new(x1, lvl, bar_index, lvl, color = c, style = math.abs(ev1) == 2 ? line.style_solid : line.style_dashed))
stLb.push(label.new(int(math.round((x1 + bar_index) / 2)), lvl, math.abs(ev1) == 2 ? "CHoCH" : "BOS", style = up ? label.style_label_down : label.style_label_up, color = color(na), textcolor = c, size = size.tiny))
if stLn.size() > strKeep
stLn.shift().delete()
stLb.shift().delete()
// ───────────────────────────────────── EQUAL HIGHS / LOWS ─────────────────────────────────────
type Eq
float p
int x1
line ln
label lb
var array<float> pivH = array.new<float>() // recent untaken swing highs of the structure
var array<int> pivHB = array.new<int>()
var array<float> pivL = array.new<float>()
var array<int> pivLB = array.new<int>()
var array<Eq> eqH = array.new<Eq>()
var array<Eq> eqL = array.new<Eq>()
f_newEq(array<float> piv, array<int> pivB, array<Eq> eqs, float p, int pb, bool isHigh) =>
int found = -1
if piv.size() > 0
for i = piv.size() - 1 to 0
if math.abs(piv.get(i) - p) <= eqTol * atr
found := i
break
if found >= 0 and onEq
float lvl = isHigh ? math.max(p, piv.get(found)) : math.min(p, piv.get(found))
int x1 = pivB.get(found)
line ln = line.new(x1, lvl, bar_index, lvl, color = colEq, style = line.style_dotted)
label lb = label.new(x1, lvl, isHigh ? "EQH" : "EQL", style = isHigh ? label.style_label_down : label.style_label_up, color = color(na), textcolor = colEq, size = size.tiny)
eqs.push(Eq.new(lvl, x1, ln, lb))
if eqs.size() > eqKeep
Eq old = eqs.shift()
old.ln.delete()
old.lb.delete()
piv.push(p)
pivB.push(pb)
if piv.size() > 50
float d1 = piv.shift()
int d2 = pivB.shift()
if not na(sH1)
f_newEq(pivH, pivHB, eqH, sH1, sH1B, true)
if not na(sL1)
f_newEq(pivL, pivLB, eqL, sL1, sL1B, false)
// taken swings leave the lists, taken equal levels disappear, the others are extended
if pivH.size() > 0
for i = pivH.size() - 1 to 0
if high > pivH.get(i)
pivH.remove(i)
pivHB.remove(i)
if pivL.size() > 0
for i = pivL.size() - 1 to 0
if low < pivL.get(i)
pivL.remove(i)
pivLB.remove(i)
if eqH.size() > 0
for i = eqH.size() - 1 to 0
Eq e = eqH.get(i)
bool tk = high > e.p
if not tk
e.ln.set_x2(bar_index)
if tk
eqTk += (eqTk == "" ? "" : ", ") + "EQH " + str.tostring(e.p, format.mintick)
e.ln.delete()
e.lb.delete()
eqH.remove(i)
if eqL.size() > 0
for i = eqL.size() - 1 to 0
Eq e = eqL.get(i)
bool tk = low < e.p
if not tk
e.ln.set_x2(bar_index)
if tk
eqTk += (eqTk == "" ? "" : ", ") + "EQL " + str.tostring(e.p, format.mintick)
e.ln.delete()
e.lb.delete()
eqL.remove(i)
// ───────────────────────────────────── GOLDEN POCKETS ─────────────────────────────────────
type GP
float top
float bot
float org // start of the swing (100 % level)
bool up // up swing: the zone is a pullback down from the high
int x1 // end of the swing
int x2 = na // na = current golden pocket
bool gone = false // completely crossed by a wick
type Layer
int k
int len
float hP = na
int hB = na
float lP = na
int lB = na
int last = 0 // 1 last pivot was a high, -1 a low
array<GP> gps
f_zone(float hi, float lo, bool up) =>
float r = hi - lo
float z1 = up ? hi - r * gpA : lo + r * gpA
float z2 = up ? hi - r * gpB : lo + r * gpB
[math.max(z1, z2), math.min(z1, z2)]
method addSwing(Layer L, bool up, bool replace) =>
[t, b] = f_zone(L.hP, L.lP, up)
GP g = GP.new(t, b, up ? L.lP : L.hP, up, up ? L.hB : L.lB)
// bars already printed since the end of the swing (a swing is known some bars later)
int n = math.min(bar_index - (up ? L.hB : L.lB), 4999)
if n > 0
for i = 0 to n - 1
if up ? low[i] < b : high[i] > t
g.gone := true
bool rep = replace and L.gps.size() > 0
if rep
L.gps.remove(L.gps.size() - 1)
if not rep and L.gps.size() > 0
GP prev = L.gps.get(L.gps.size() - 1)
prev.x2 := up ? L.hB : L.lB
if L.gps.size() > gpPast
L.gps.shift()
L.gps.push(g)
method updLayer(Layer L, float ph, int phB, float pl, int plB) =>
if not na(ph)
int b = phB
if L.last == 1
if ph > L.hP // two highs in a row: keep the higher one
L.hP := ph
L.hB := b
if not na(L.lP)
L.addSwing(true, true)
else
L.hP := ph
L.hB := b
L.last := 1
if not na(L.lP)
L.addSwing(true, false)
if not na(pl)
int b = plB
if L.last == -1
if pl < L.lP
L.lP := pl
L.lB := b
if not na(L.hP)
L.addSwing(false, true)
else
L.lP := pl
L.lB := b
L.last := -1
if not na(L.hP)
L.addSwing(false, false)
var Layer ly1 = Layer.new(1, gpLen, gps = array.new<GP>())
var Layer ly2 = Layer.new(4, gpLen * 4, gps = array.new<GP>())
var Layer ly3 = Layer.new(16, gpLen * 16, gps = array.new<GP>())
var Layer ly4 = Layer.new(64, gpLen * 64, gps = array.new<GP>())
bool zzOn = gpMode == "Reversal (ATR)"
float gph1 = ta.pivothigh(gpLen, gpLen)
float gpl1 = ta.pivotlow(gpLen, gpLen)
float gph2 = ta.pivothigh(gpLen * 4, gpLen * 4)
float gpl2 = ta.pivotlow(gpLen * 4, gpLen * 4)
float gph3 = ta.pivothigh(gpLen * 16, gpLen * 16)
float gpl3 = ta.pivotlow(gpLen * 16, gpLen * 16)
float gph4 = ta.pivothigh(gpLen * 64, gpLen * 64)
float gpl4 = ta.pivotlow(gpLen * 64, gpLen * 64)
if zzOn
ly1.updLayer(z1.nH, z1.nHB, z1.nL, z1.nLB)
ly2.updLayer(z2.nH, z2.nHB, z2.nL, z2.nLB)
ly3.updLayer(z3.nH, z3.nHB, z3.nL, z3.nLB)
ly4.updLayer(z4.nH, z4.nHB, z4.nL, z4.nLB)
if not zzOn
ly1.updLayer(gph1, bar_index - gpLen, gpl1, bar_index - gpLen)
ly2.updLayer(gph2, bar_index - gpLen * 4, gpl2, bar_index - gpLen * 4)
ly3.updLayer(gph3, bar_index - gpLen * 16, gpl3, bar_index - gpLen * 16)
ly4.updLayer(gph4, bar_index - gpLen * 64, gpl4, bar_index - gpLen * 64)
// a golden pocket is filled once a wick goes beyond its far edge (below it after an up swing, above it after a down swing)
array<Layer> allLy = array.from(ly1, ly2, ly3, ly4)
for L in allLy
for g in L.gps
bool cross = g.up ? low < g.bot : high > g.top
if cross and not g.gone
g.gone := true
// ───────────────────────────────────── PREVIOUS HIGHS / LOWS ─────────────────────────────────────
type Lvl
float p
int t // time of the exact bar of the high / low
bool hi
int kind // 0 day, 1 week, 2 month
bool latest // level of the period just closed
var array<Lvl> lvls = array.new<Lvl>()
// running high / low of the current period (day, week, month) and the time of their exact bar
var array<float> rHi = array.new<float>(3, na)
var array<int> rHiT = array.new<int>(3, na)
var array<float> rLo = array.new<float>(3, na)
var array<int> rLoT = array.new<int>(3, na)
bool okD = tfSec <= 86400
bool okW = tfSec <= 604800
bool okM = not timeframe.ismonthly or timeframe.multiplier == 1
array<bool> pChg = array.from(timeframe.change("D"), timeframe.change("W"), timeframe.change("M"))
array<bool> pOn = array.from(onPrev and pvD and okD, onPrev and pvW and okW, onPrev and pvM and okM)
for kind = 0 to 2
bool chg = pChg.get(kind)
if chg and not na(rHi.get(kind)) and pOn.get(kind)
if lvls.size() > 0
for i = 0 to lvls.size() - 1
Lvl lv = lvls.get(i)
if lv.kind == kind
lv.latest := false
lvls.push(Lvl.new(rHi.get(kind), rHiT.get(kind), true, kind, true))
lvls.push(Lvl.new(rLo.get(kind), rLoT.get(kind), false, kind, true))
bool reset = chg or na(rHi.get(kind))
if reset
rHi.set(kind, high)
rHiT.set(kind, time)
rLo.set(kind, low)
rLoT.set(kind, time)
if not reset and high > rHi.get(kind)
rHi.set(kind, high)
rHiT.set(kind, time)
if not reset and low < rLo.get(kind)
rLo.set(kind, low)
rLoT.set(kind, time)
// a wick through the level takes it (closed back inside = sweep); at most 40 levels per period and side
if lvls.size() > 0
for i = lvls.size() - 1 to 0
Lvl l = lvls.get(i)
bool taken = l.hi ? high > l.p : low < l.p
if taken and time > l.t
bool back = l.hi ? close <= l.p : close >= l.p
string lnm = (l.latest ? "P" : "") + (l.kind == 0 ? "D" : l.kind == 1 ? "W" : "M") + (l.hi ? "H" : "L") + " " + str.tostring(l.p, format.mintick)
if swCalc and swLv and back and l.hi
swH += (swH == "" ? "" : ", ") + lnm
if swCalc and swLv and back and not l.hi
swL += (swL == "" ? "" : ", ") + lnm
lvTk += (lvTk == "" ? "" : ", ") + lnm
lvls.remove(i)
// one bolt per side and bar: red above a swept high, green below a swept low
if onSw and swH != ""
swLbl.push(label.new(bar_index, high, "⚡", style = label.style_label_down, color = color(na), textcolor = colBear, size = size.small, tooltip = "Sweep of: " + swH))
if onSw and swL != ""
swLbl.push(label.new(bar_index, low, "⚡", style = label.style_label_up, color = color(na), textcolor = colBull, size = size.small, tooltip = "Sweep of: " + swL))
while swLbl.size() > 100
swLbl.shift().delete()
for kind = 0 to 2
for side = 0 to 1
int n = 0
for l in lvls
if l.kind == kind and l.hi == (side == 0)
n += 1
while n > 40
// drop the level farthest from the price
int far = -1
float dMax = -1.0
for [i, l] in lvls
if l.kind == kind and l.hi == (side == 0) and math.abs(l.p - close) > dMax
dMax := math.abs(l.p - close)
far := i
lvls.remove(far)
n -= 1
// ───────────────────────────────────── DRAWING ON THE LAST BAR ─────────────────────────────────────
var array<box> dBx = array.new<box>()
var array<line> dLn = array.new<line>()
var array<label> dLb = array.new<label>()
f_gpCol(int k, bool past) =>
color.new(gpCol, math.min(98, gpTr + (past ? 6 : 0) + (k == 1 ? 4 : 0)))
f_layerName(int k) => "x" + str.tostring(k)
f_arrow(int t) => t == 1 ? "▲" : t == -1 ? "▼" : "-"
// alert conditions computed on the last bar (golden pockets, premium / discount)
bool acPrem = false
bool acDisc = false
bool acGP = false
bool acOv = false
bool acSwGP = false
if barstate.islast
for b in dBx
b.delete()
for l in dLn
l.delete()
for l in dLb
l.delete()
dBx.clear(), dLn.clear(), dLb.clear()
int xr = bar_index
// alerts of this bar
array<string> alMsg = array.new<string>()
array<string> gIn = array.new<string>() // golden pockets the bar is in
array<string> gNewN = array.new<string>() // golden pockets just entered
// premium / discount range: last swing high and low of the layer, widened by the extremes reached since
// (a new low or high not confirmed yet as a swing still moves the range)
Layer Lr = pdLay == "x1" ? ly1 : pdLay == "x4" ? ly2 : pdLay == "x16" ? ly3 : ly4
float pdH = Lr.hP
float pdL = Lr.lP
int pdX = na
if not na(Lr.hP) and not na(Lr.lP)
pdX := math.min(Lr.hB, Lr.lB)
int nR = math.min(bar_index - math.max(Lr.hB, Lr.lB), 4999)
for i = 0 to nR
pdH := math.max(pdH, high[i])
pdL := math.min(pdL, low[i])
// golden pockets
if onGP
array<Layer> lys = array.from(ly1, ly2, ly3, ly4)
array<bool> ons = array.from(gp1, gp2, gp3, gp4)
array<float> cT = array.new<float>(4, na) // current zone of each layer, for the overlaps
array<float> cB = array.new<float>(4, na)
array<int> cX = array.new<int>(4, na)
array<string> drawn = array.new<string>() // a swing found by two layers is drawn once
for j = 0 to 3
Layer L = lys.get(j)
if ons.get(j) and L.gps.size() > 0
for [i, g] in L.gps
bool cur = na(g.x2)
bool broken = cur and (g.up ? close < g.org : close > g.org)
string key = str.tostring(g.x1) + "|" + str.tostring(g.top) + "|" + str.tostring(cur)
if not (cur and broken and gpHideBr) and not (g.gone and gpFill)
int x2 = cur ? xr + gpExt : g.x2
if not drawn.includes(key)
drawn.push(key)
int wid = L.k >= 16 ? 2 : 1
dBx.push(box.new(g.x1, g.top, x2, g.bot, border_color = color.new(gpCol, cur ? 40 : 70), border_width = wid, border_style = L.k == 1 ? line.style_dotted : line.style_solid, bgcolor = f_gpCol(L.k, not cur)))
if cur
cT.set(j, g.top)
cB.set(j, g.bot)
cX.set(j, x2)
bool inZ = low <= g.top and high >= g.bot
if inZ
gIn.push(f_layerName(L.k))
if inZ and not (pLo <= g.top and pHi >= g.bot)
gNewN.push(f_layerName(L.k))
// one label per group of overlapping current golden pockets: "GP x1 + x4 + x16"
if gpLbl
array<bool> done = array.new<bool>(4, false)
for j = 0 to 3
if not na(cT.get(j)) and not done.get(j)
string txt = "GP " + f_layerName(lys.get(j).k)
float gT = cT.get(j)
float gB = cB.get(j)
done.set(j, true)
if j < 3
for m = j + 1 to 3
bool hit = false
if not done.get(m) and not na(cT.get(m))
hit := cT.get(m) >= gB and cB.get(m) <= gT
if hit
txt += " + " + f_layerName(lys.get(m).k)
gT := math.max(gT, cT.get(m))
gB := math.min(gB, cB.get(m))
done.set(m, true)
dLb.push(label.new(cX.get(j), (gT + gB) / 2, txt, style = label.style_label_left, color = color(na), textcolor = color.new(gpCol, 10), size = size.tiny))
// unconfirmed golden pockets: last confirmed swing of the layer -> extreme reached since then
if onGPu
array<Layer> lys = array.from(ly1, ly2, ly3, ly4)
array<bool> ons = array.from(gp1, gp2, gp3, gp4)
array<string> uK = array.new<string>()
array<label> uL = array.new<label>()
array<string> uT = array.new<string>()
for j = 0 to 3
Layer L = lys.get(j)
bool ok = ons.get(j) and L.last != 0 and not na(L.hP) and not na(L.lP)
if ok
bool up = L.last == -1 // last pivot = a low: the price may be printing the next high
int x0 = up ? L.lB : L.hB
int n = math.min(bar_index - x0, 4999)
float ext = na
int xe = na
for i = 0 to n
float v = up ? high[i] : low[i]
if na(ext) or (up ? v > ext : v < ext)
ext := v
xe := bar_index - i
float hi = up ? ext : L.hP
float lo = up ? L.lP : ext
// second leg: the move back from that extreme (lowest low after the high, or highest high after the low)
float ext2 = na
int xe2 = na
int n2 = bar_index - xe
if n2 > 0
for i = 0 to n2 - 1
float v = up ? low[i] : high[i]
if na(ext2) or (up ? v < ext2 : v > ext2)
ext2 := v
xe2 := bar_index - i
for step = 0 to 1
bool sUp = step == 0 ? up : not up
float sHi = step == 0 ? hi : up ? ext : ext2
float sLo = step == 0 ? lo : up ? ext2 : ext
int sX = step == 0 ? xe : xe2
bool okS = step == 0 or not na(xe2)
if okS
[t, b] = f_zone(sHi, sLo, sUp)
// completely crossed since the end of the leg
bool crossed = false
int m = bar_index - sX
if gpFill and m > 0
for i = 0 to m - 1
if sUp ? low[i] < b : high[i] > t
crossed := true
if sHi > sLo and not crossed
string key = str.tostring(sX) + "|" + str.tostring(sHi) + "|" + str.tostring(sLo)
int at = uK.indexof(key)
string nm = f_layerName(L.k)
bool inU = low <= t and high >= b
if inU
gIn.push(nm + " ?")
if inU and not (pLo <= t and pHi >= b)
gNewN.push(nm + " ?")
if at < 0
dBx.push(box.new(sX, t, xr + gpExt, b, border_color = color.new(gpUCol, 30), border_width = L.k >= 16 ? 2 : 1, border_style = line.style_dashed, bgcolor = color.new(gpUCol, gpTr)))
string txt = "GP " + nm + " ?"
label lb = label.new(xr + gpExt, (t + b) / 2, txt, style = label.style_label_left, color = color(na), textcolor = color.new(gpUCol, 10), size = size.tiny, tooltip = "Unconfirmed golden pocket: a swing whose end is not confirmed by a pivot yet (last confirmed swing -> extreme since then, or that extreme -> the move back from it). It moves with the price.")
dLb.push(lb)
uK.push(key)
uL.push(lb)
uT.push(txt)
if at >= 0
string txt2 = uT.get(at) + " + " + nm
uL.get(at).set_text(txt2)
uT.set(at, txt2)
// premium / discount
if onPD
if not na(pdX)
float eqm = (pdH + pdL) / 2
float ez = (pdH - pdL) * pdExt / 100
int x1 = pdX
dBx.push(box.new(x1, pdH, xr + gpExt, pdH - ez, border_color = color(na), bgcolor = color.new(colBear, pdTr)))
dBx.push(box.new(x1, pdL + ez, xr + gpExt, pdL, border_color = color(na), bgcolor = color.new(colBull, pdTr)))
dLb.push(label.new(xr + gpExt, pdH - ez / 2, "Premium", style = label.style_label_left, color = color(na), textcolor = color.new(colBear, 20), size = size.tiny))
dLb.push(label.new(xr + gpExt, pdL + ez / 2, "Discount", style = label.style_label_left, color = color(na), textcolor = color.new(colBull, 20), size = size.tiny))
dLn.push(line.new(x1, eqm, xr + gpExt, eqm, color = color.new(color.gray, 40), style = line.style_dotted))
dLb.push(label.new(xr + gpExt, eqm, "EQ " + pdLay, style = label.style_label_left, color = color(na), textcolor = color.gray, size = size.tiny))
// previous highs / lows: the nearest untaken ones on each side
if onPrev and lvls.size() > 0
int tEnd = time + f_dur(pvExt)
array<float> mP = array.new<float>()
array<string> mN = array.new<string>()
array<color> mC = array.new<color>()
array<string> mT = array.new<string>()
for kind = 0 to 2
for side = 0 to 1
bool isHi = side == 0
array<float> dist = array.new<float>()
array<int> idx = array.new<int>()
for [i, l] in lvls
if l.kind == kind and l.hi == isHi
dist.push(math.abs(l.p - close)), idx.push(i)
if dist.size() > 0
array<int> ord = dist.sort_indices(order.ascending)
for q = 0 to math.min(pvN, ord.size()) - 1
Lvl l = lvls.get(idx.get(ord.get(q)))
color c = kind == 0 ? pvColD : kind == 1 ? pvColW : pvColM
string nm = (l.latest ? "P" : "") + (kind == 0 ? "D" : kind == 1 ? "W" : "M") + (isHi ? "H" : "L")
dLn.push(line.new(l.t, l.p, tEnd, l.p, xloc = xloc.bar_time, color = c, style = line.style_dotted))
mP.push(l.p)
mN.push(nm)
mC.push(c)
mT.push(nm + " " + str.format_time(l.t, "yyyy-MM-dd HH:mm", syminfo.timezone) + " " + str.tostring(l.p, format.mintick))
// one label per group of levels at nearly the same price
if mP.size() > 0
array<int> so = mP.sort_indices(order.ascending)
float gLo = mP.get(so.get(0))
float gHi = gLo
string gN = mN.get(so.get(0))
string gT = mT.get(so.get(0))
color gC = mC.get(so.get(0))
for q = 1 to so.size()
bool last = q == so.size()
bool join = false
if not last
join := mP.get(so.get(q)) - gHi <= pvMrg * atr
if join
int ix = so.get(q)
gHi := mP.get(ix)
gN += " / " + mN.get(ix)
gT += "\n" + mT.get(ix)
if not join
dLb.push(label.new(tEnd, (gLo + gHi) / 2, gN, xloc = xloc.bar_time, style = label.style_label_left, color = color(na), textcolor = gC, size = size.tiny, tooltip = gT))
if not join and not last
int ix = so.get(q)
gLo := mP.get(ix)
gHi := gLo
gN := mN.get(ix)
gT := mT.get(ix)
gC := mC.get(ix)
// break-even lines
if onBE
float p0 = beRef > 0 ? beRef : close
float fi = beIn / 100
float fo = beOut / 100
float bL = p0 * (1 + fi) / (1 - fo) // long: sell price that pays both fees
float bS = p0 * (1 - fi) / (1 + fo) // short: buy-back price that pays both fees
float pct = (bL / p0 - 1) * 100
int n = beX2 ? 3 : 1
for m = 1 to n
float up = p0 + (bL - p0) * m
float dn = p0 - (p0 - bS) * m
int tr = m == 1 ? 0 : 40
dLn.push(line.new(xr - 3, up, xr + 12, up, color = color.new(beCol, tr), style = m == 1 ? line.style_solid : line.style_dashed))
dLn.push(line.new(xr - 3, dn, xr + 12, dn, color = color.new(beCol, tr), style = m == 1 ? line.style_solid : line.style_dashed))
string t = "BE "
if m == 1
dLb.push(label.new(xr + 12, up, t + "+" + str.tostring(pct * m, "#.##") + "%", style = label.style_label_left, color = color(na), textcolor = color.new(beCol, tr), size = size.tiny))
dLb.push(label.new(xr + 12, dn, t + "-" + str.tostring(pct * m, "#.##") + "%", style = label.style_label_left, color = color(na), textcolor = color.new(beCol, tr), size = size.tiny))
// trend label: green when the three trends agree up, red when they agree down, gray otherwise
if onTrd
string txt = "x1 " + f_arrow(st1.trend) + " x4 " + f_arrow(st2.trend) + " x16 " + f_arrow(st3.trend)
int sum = st1.trend + st2.trend + st3.trend
color c = sum == 3 ? colBull : sum == -3 ? colBear : color.gray
dLb.push(label.new(xr + 3, high + atr, txt, style = label.style_label_left, color = color.new(c, 75), textcolor = color.white, size = size.small))
// ───────── alerts (one alert in TradingView: "Any alert() function call") ─────────
if not na(pdX)
float ezA = (pdH - pdL) * pdExt / 100
acPrem := high >= pdH - ezA and pHi < pdH - ezA
acDisc := low <= pdL + ezA and pLo > pdL + ezA
acGP := gNewN.size() > 0
acOv := gNewN.size() > 0 and gIn.size() >= 2
acSwGP := (swH != "" or swL != "") and gIn.size() > 0
if alPD and acPrem
alMsg.push("Premium zone entered (" + pdLay + ")")
if alPD and acDisc
alMsg.push("Discount zone entered (" + pdLay + ")")
if alGP and acGP
alMsg.push("Golden pocket entered: GP " + gNewN.join(", "))
if alOv and acOv
alMsg.push("Overlapping golden pockets entered: GP " + gIn.join(" + "))
if alSwGP and acSwGP
alMsg.push("Sweep inside golden pocket GP " + gIn.join(" + ") + " (" + swH + (swH != "" and swL != "" ? ", " : "") + swL + ")")
if alSw and swH != ""
alMsg.push("Sweep of " + swH)
if alSw and swL != ""
alMsg.push("Sweep of " + swL)
if alCh and math.abs(evCh) == 2
alMsg.push((evCh > 0 ? "Bullish" : "Bearish") + " CHoCH " + alChL)
if alAl and algnNew
alMsg.push("Trends x1 x4 x16 aligned " + (algn > 0 ? "up" : "down"))
if alLv and lvTk != ""
alMsg.push("Previous level taken: " + lvTk)
if alEq and eqTk != ""
alMsg.push("Equal level taken: " + eqTk)
if alMsg.size() > 0
alert(syminfo.ticker + " " + timeframe.period + ": " + alMsg.join(" | "), alert.freq_once_per_bar_close)
// ───────── the same alerts one by one in the alert window (fixed messages, independent of the Alerts boxes) ─────────
alertcondition(acGP, "GP entered", "{{ticker}} {{interval}}: golden pocket entered, price {{close}}")
alertcondition(acOv, "GP overlap entered", "{{ticker}} {{interval}}: overlapping golden pockets entered, price {{close}}")
alertcondition(acSwGP, "Sweep in GP", "{{ticker}} {{interval}}: sweep inside a golden pocket, price {{close}}")
alertcondition(acPrem, "Premium entered", "{{ticker}} {{interval}}: premium zone entered, price {{close}}")
alertcondition(acDisc, "Discount entered", "{{ticker}} {{interval}}: discount zone entered, price {{close}}")
alertcondition(swH != "", "Sweep of a high", "{{ticker}} {{interval}}: sweep of a high, price {{close}}")
alertcondition(swL != "", "Sweep of a low", "{{ticker}} {{interval}}: sweep of a low, price {{close}}")
alertcondition(evCh == 2, "Bullish CHoCH", "{{ticker}} {{interval}}: bullish CHoCH, price {{close}}")
alertcondition(evCh == -2, "Bearish CHoCH", "{{ticker}} {{interval}}: bearish CHoCH, price {{close}}")
alertcondition(algnNew and algn > 0, "Trends aligned up", "{{ticker}} {{interval}}: trends x1 x4 x16 aligned up, price {{close}}")
alertcondition(algnNew and algn < 0, "Trends aligned down", "{{ticker}} {{interval}}: trends x1 x4 x16 aligned down, price {{close}}")
alertcondition(lvTk != "", "Previous D/W/M level taken", "{{ticker}} {{interval}}: previous day / week / month high or low taken, price {{close}}")
alertcondition(eqTk != "", "Equal high/low taken", "{{ticker}} {{interval}}: equal highs / lows taken, price {{close}}")