本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator(title = "Confluence Zone Retest Pyramid", shorttitle = "CZR Pyramid", overlay = true, max_bars_back = 500, max_labels_count = 500, max_lines_count = 500, max_boxes_count = 100)
// ═══════════════════════════════ INPUTS ═══════════════════════════════
grpL = "Key Levels"
pivType = input.string("Traditional", "Pivot Formula", options = ["Traditional", "Fibonacci", "Camarilla"], group = grpL, tooltip = "Formula used for daily and weekly pivot levels (P, R1, S1, R2, S2). Camarilla levels sit closer to price; Traditional levels are wider.")
useDaily = input.bool(true, "Daily Levels", group = grpL, tooltip = "Add previous day high, low, close and daily pivots. Only used on charts below the daily timeframe.")
useWeekly = input.bool(true, "Weekly Levels", group = grpL, tooltip = "Add previous week high, low and weekly pivots. Only used on charts below the weekly timeframe. Weekly levels add a bonus to the zone score.")
useSwing = input.bool(true, "Swing Highs / Lows", group = grpL, tooltip = "Add the last two confirmed swing highs and swing lows as levels. Swing levels add a bonus to the zone score.")
swingLen = input.int(10, "Swing Length", minval = 2, maxval = 50, group = grpL, tooltip = "Bars on each side needed to confirm a swing. Higher = fewer, more important swings but confirmed later. Lower = more swings, faster but noisier.")
useRound = input.bool(true, "Round Numbers", group = grpL, tooltip = "Add the nearest round numbers above and below price as levels. The step is scaled automatically from the price magnitude.")
grpZ = "Confluence Zones"
atrLen = input.int(14, "ATR Length", minval = 1, group = grpZ, tooltip = "ATR length used to size zones, tolerances, buffers and stops. Higher = steadier distances. Lower = reacts faster to volatility changes.")
mergeTol = input.float(0.35, "Merge Tolerance (ATR)", minval = 0.05, maxval = 1.5, step = 0.05, group = grpZ, tooltip = "Levels closer than this many ATR are merged into one zone. Higher = wider zones with more levels. Lower = tighter, rarer zones.")
minSrc = input.int(2, "Min Levels per Zone", minval = 2, maxval = 8, group = grpZ, tooltip = "Minimum number of levels that must stack inside a zone. Higher = fewer but stronger zones.")
needMixed = input.bool(true, "Require Mixed Sources", group = grpZ, tooltip = "Zone must contain at least one price-structure level (high, low, close, swing) and one formula level (pivot, round number).")
respLook = input.int(100, "Respect Lookback Bars", minval = 10, maxval = 400, group = grpZ, tooltip = "Bars scanned to count how often price touched a zone and closed back outside it. Higher = longer memory, heavier calculation.")
respPts = input.float(5.0, "Points per Respect Touch", minval = 0.0, maxval = 20.0, step = 0.5, group = grpZ, tooltip = "Score added per past respected touch (capped at 30 points). Higher = historically respected zones rank much higher. 0 disables respect scoring.")
minScore = input.float(45.0, "Min Zone Score", minval = 0.0, maxval = 100.0, step = 1.0, group = grpZ, tooltip = "Only zones with at least this score can create signals. Higher = fewer, higher-quality signals. Lower = more signals.")
grpS = "Signals"
sigMode = input.string("Both", "Signal Mode", options = ["Both", "Rejection Only", "Breakout Only"], group = grpS, tooltip = "Rejection = wick into a zone and close back out of it. Breakout = strong close through a zone. Both = allow either type.")
wickMin = input.float(0.35, "Min Rejection Wick (fraction)", minval = 0.1, maxval = 0.9, step = 0.05, group = grpS, tooltip = "Rejection wick must be at least this fraction of the bar range. Higher = only sharp rejections, fewer signals.")
bodyMin = input.float(0.5, "Min Breakout Body (fraction)", minval = 0.1, maxval = 0.95, step = 0.05, group = grpS, tooltip = "Breakout candle body must be at least this fraction of the bar range. Higher = only decisive breakouts, fewer signals.")
brkBuf = input.float(0.10, "Breakout Close Buffer (ATR)", minval = 0.0, maxval = 1.0, step = 0.05, group = grpS, tooltip = "Close must clear the zone edge by this many ATR to count as a breakout. Higher = fewer false breaks, later entries.")
retestWin = input.int(8, "Retest Window Bars", minval = 1, maxval = 50, group = grpS, tooltip = "Bars allowed after a breakout for price to come back and retest the zone. Higher = more retests caught but older breakouts.")
retestTol = input.float(0.15, "Retest Tolerance (ATR)", minval = 0.0, maxval = 1.0, step = 0.05, group = grpS, tooltip = "How close (in ATR) price must come back to the broken zone edge to count as a retest. Higher = easier retests.")
grpF = "Weakness Fixes"
useConfirmed = input.bool(true, "Confirmed Bars Only (No Repaint)", group = grpF, tooltip = "Signals, stops and pyramid adds are only generated after the bar closes, so they never appear and disappear on the live bar.")
useRetest = input.bool(true, "Require Retest After Breakout", group = grpF, tooltip = "Breakout signals fire only after price returns to the broken zone and holds. Filters false breakouts but skips runaway moves.")
useTrend = input.bool(true, "Trend Filter", group = grpF, tooltip = "Buy only above the trend EMA and sell only below it, for the signal types chosen in Trend Filter Scope.")
trendLen = input.int(100, "Trend EMA Length", minval = 10, group = grpF, tooltip = "Length of the trend EMA. Higher = slower, long-term trend. Lower = reacts faster to trend changes.")
trendScope = input.string("Breakouts Only", "Trend Filter Scope", options = ["Breakouts Only", "All Signals"], group = grpF, tooltip = "Breakouts Only keeps counter-trend rejection signals. All Signals also filters rejections, giving fewer but trend-aligned trades.")
useAdx = input.bool(true, "ADX Filter for Breakouts", group = grpF, tooltip = "Block breakout signals when ADX is below the minimum, reducing false breakouts in sideways markets. Rejections are not affected.")
adxLen = input.int(14, "ADX Length", minval = 1, group = grpF, tooltip = "DI and ADX smoothing length. Higher = smoother but slower ADX.")
adxMin = input.float(18.0, "ADX Minimum", minval = 1.0, step = 1.0, group = grpF, tooltip = "Minimum ADX required for a breakout signal. Higher = only strong trends, fewer breakout signals.")
useAct = input.bool(true, "Activity Filter", group = grpF, tooltip = "Require volume above its 20-bar average times the minimum. Symbols without volume use bar range divided by ATR instead.")
actMin = input.float(0.9, "Min Activity Ratio", minval = 0.1, step = 0.05, group = grpF, tooltip = "Signal bar activity must be at least this ratio of normal. Higher = only high-participation bars, fewer signals.")
cooldown = input.int(5, "Signal Cooldown Bars", minval = 0, group = grpF, tooltip = "Minimum bars between two main signals of any side. Higher = fewer back-to-back or flip-flop signals.")
oneDir = input.bool(true, "Block Repeated Same-Side Signals", group = grpF, tooltip = "After a Buy, another main Buy is ignored until a Sell or a stop exit occurs (and vice versa). Extra entries come only from the pyramid.")
grpR = "Risk / Stop"
useStop = input.bool(true, "Stop Resets Side", group = grpR, tooltip = "When price closes beyond the stop, the active side is closed and order counts reset. Prevents pyramiding into a broken zone.")
stopBuf = input.float(0.25, "Stop Buffer (ATR)", minval = 0.0, maxval = 3.0, step = 0.05, group = grpR, tooltip = "Stop is placed beyond the signal zone edge and signal wick by this many ATR. Higher = wider stop, fewer stop-outs, larger risk.")
showStop = input.bool(true, "Show Stop Line", group = grpR, tooltip = "Draw the active stop level on the chart.")
grpP = "Pyramid Orders"
usePyr = input.bool(true, "Enable Pyramid", group = grpP, tooltip = "Allow extra orders in the direction of the active signal when price moves the set distance from the last order.")
maxOrders = input.int(4, "Max Orders Per Side", minval = 1, maxval = 10, group = grpP, tooltip = "Total orders allowed per side, including the first signal. Higher = larger possible position and risk.")
pyrDir = input.string("Against (Average In)", "Pyramid Direction", options = ["Against (Average In)", "With Trend (Scale In)"], group = grpP, tooltip = "Average In: add Buy when price drops (Sell when it rises) by the step. Scale In: add Buy when price rises (Sell when it falls) by the step.")
distMode = input.string("ATR", "Step Distance Mode", options = ["ATR", "Ticks"], group = grpP, tooltip = "Measure distance between pyramid orders in ATR multiples (adapts to volatility) or a fixed number of ticks.")
distTicks = input.int(200, "Step Distance (Ticks)", minval = 1, group = grpP, tooltip = "Distance in ticks (syminfo.mintick) between pyramid orders when mode is Ticks. Higher = fewer, wider-spaced adds.")
distAtrLen = input.int(14, "Step ATR Length", minval = 1, group = grpP, tooltip = "ATR length for the step distance when mode is ATR. Higher = steadier step size.")
distAtrMul = input.float(1.0, "Step ATR Multiplier", minval = 0.1, step = 0.1, group = grpP, tooltip = "Step distance = ATR x this value. Higher = fewer, wider-spaced pyramid adds.")
grpV = "Visuals"
showZones = input.bool(true, "Show Zones", group = grpV, tooltip = "Draw the nearest confluence zones as boxes on the last bar.")
zonesShown = input.int(4, "Zones Shown", minval = 1, maxval = 10, group = grpV, tooltip = "Number of zones nearest to price that are drawn. Higher = more context but a busier chart.")
showLabels = input.bool(true, "Show Order Labels", group = grpV, tooltip = "Show B1, B2... and S1, S2... labels for each order and X labels for stop exits.")
showTrend = input.bool(true, "Show Trend EMA", group = grpV, tooltip = "Plot the trend EMA used by the trend filter.")
showTable = input.bool(true, "Show Dashboard", group = grpV, tooltip = "Show a small status table with active side, order count and nearest zones.")
bullCol = input.color(#00E5A8, "Bullish Color", group = grpV, tooltip = "Color for Buy orders, support zones and long stops.")
bearCol = input.color(#FF4D6D, "Bearish Color", group = grpV, tooltip = "Color for Sell orders, resistance zones and short stops.")
zoneCol = input.color(#F5C542, "Zone Color", group = grpV, tooltip = "Color for zones that price is currently inside.")
// ═══════════════════════════════ CORE SERIES ═══════════════════════════════
float atrV = ta.atr(atrLen)
float rngC = math.max(high - low, syminfo.mintick)
float lwFrac = (math.min(open, close) - low) / rngC
float uwFrac = (high - math.max(open, close)) / rngC
float bodyFrac = math.abs(close - open) / rngC
float tfms = timeframe.in_seconds() * 1000.0
// FIX: no-volume fallback — symbols without volume use range/ATR as activity
bool hasVol = ta.cum(nz(volume)) > 0
float volAvg = ta.sma(nz(volume), 20)
float actV = hasVol ? nz(volume) / math.max(nz(volAvg), 1e-10) : (high - low) / math.max(nz(atrV), 1e-10)
// FIX: repaint protection — previous completed HTF bar ([1]) with lookahead_on is the
// standard non-repainting idiom (lookahead_off + [1] would return the bar two periods back).
int tfSec = timeframe.in_seconds()
bool dOk = useDaily and tfSec < 86400
bool wOk = useWeekly and tfSec < 604800
[pdh, pdl, pdc] = request.security(syminfo.tickerid, "D", [high[1], low[1], close[1]], lookahead = barmerge.lookahead_on)
[pwh, pwl, pwc] = request.security(syminfo.tickerid, "W", [high[1], low[1], close[1]], lookahead = barmerge.lookahead_on)
f_piv(string typ, float h, float l, float c) =>
float p = (h + l + c) / 3.0
float rg = h - l
float r1 = na
float s1 = na
float r2 = na
float s2 = na
if typ == "Fibonacci"
r1 := p + 0.382 * rg
s1 := p - 0.382 * rg
r2 := p + 0.618 * rg
s2 := p - 0.618 * rg
else if typ == "Camarilla"
r1 := c + rg * 1.1 / 12.0
s1 := c - rg * 1.1 / 12.0
r2 := c + rg * 1.1 / 6.0
s2 := c - rg * 1.1 / 6.0
else
r1 := 2.0 * p - l
s1 := 2.0 * p - h
r2 := p + rg
s2 := p - rg
[p, r1, s1, r2, s2]
[dP, dR1, dS1, dR2, dS2] = f_piv(pivType, pdh, pdl, pdc)
[wP, wR1, wS1, wR2, wS2] = f_piv(pivType, pwh, pwl, pwc)
// Swing levels (confirmed pivots only — no repaint, but swingLen bars of lag)
float swH = ta.pivothigh(high, swingLen, swingLen)
float swL = ta.pivotlow(low, swingLen, swingLen)
var float sh1 = na
var float sh2 = na
var float sl1 = na
var float sl2 = na
if not na(swH)
sh2 := sh1
sh1 := swH
if not na(swL)
sl2 := sl1
sl1 := swL
// Round numbers: step = one decade below price magnitude (e.g. 4500 -> 100, 1.08 -> 0.1)
float mag = close > 0 ? math.pow(10.0, math.floor(math.log10(close))) : na
float rStep = na(mag) ? na : mag * 0.1
float rnDn = na(rStep) ? na : math.floor(close / rStep) * rStep
float rnUp = na(rStep) ? na : rnDn + rStep
// ═══════════════════════════════ LEVEL COLLECTION ═══════════════════════════════
// src: 0 = price structure, 1 = formula. tier: 0 round, 1 daily, 2 weekly, 3 swing
var array<float> lvP = array.new<float>()
var array<int> lvS = array.new<int>()
var array<int> lvT = array.new<int>()
var array<string> lvN = array.new<string>()
array.clear(lvP)
array.clear(lvS)
array.clear(lvT)
array.clear(lvN)
f_add(float v, int src, int tier, string nm) =>
if not na(v)
array.push(lvP, v)
array.push(lvS, src)
array.push(lvT, tier)
array.push(lvN, nm)
true
if dOk
f_add(pdh, 0, 1, "PDH")
f_add(pdl, 0, 1, "PDL")
f_add(pdc, 0, 1, "PDC")
f_add(dP, 1, 1, "DP")
f_add(dR1, 1, 1, "DR1")
f_add(dS1, 1, 1, "DS1")
f_add(dR2, 1, 1, "DR2")
f_add(dS2, 1, 1, "DS2")
if wOk
f_add(pwh, 0, 2, "PWH")
f_add(pwl, 0, 2, "PWL")
f_add(wP, 1, 2, "WP")
f_add(wR1, 1, 2, "WR1")
f_add(wS1, 1, 2, "WS1")
if useSwing
f_add(sh1, 0, 3, "SWH")
f_add(sh2, 0, 3, "SWH2")
f_add(sl1, 0, 3, "SWL")
f_add(sl2, 0, 3, "SWL2")
if useRound
f_add(rnDn, 1, 0, "RND")
f_add(rnUp, 1, 0, "RND")
// ═══════════════════════════════ CONFLUENCE ZONES ═══════════════════════════════
var array<float> zTop = array.new<float>()
var array<float> zBot = array.new<float>()
var array<float> zScore = array.new<float>()
var array<int> zCnt = array.new<int>()
var array<int> zTouch = array.new<int>()
var array<string> zName = array.new<string>()
array.clear(zTop)
array.clear(zBot)
array.clear(zScore)
array.clear(zCnt)
array.clear(zTouch)
array.clear(zName)
// NEW: respect count — past bars that touched the zone and closed back outside it
f_touches(float t, float b, int look) =>
int n = 0
for i = 1 to look
if high[i] >= b and low[i] <= t and (close[i] > t or close[i] < b)
n += 1
n
f_push(int cnt, bool hasS, bool hasF, bool wk, bool sw, float lo, float hi, string nm) =>
bool ok = cnt >= minSrc and (not needMixed or (hasS and hasF))
if ok
float mid = (lo + hi) / 2.0
float h = math.max(hi - lo, 0.12 * atrV)
float t = mid + h / 2.0
float b = mid - h / 2.0
int tc = respPts > 0 ? f_touches(t, b, respLook) : 0
float sc = math.min(100.0, math.min(cnt, 5) * 16.0 + (wk ? 8.0 : 0.0) + (sw ? 6.0 : 0.0) + math.min(tc * respPts, 30.0))
array.push(zTop, t)
array.push(zBot, b)
array.push(zScore, sc)
array.push(zCnt, cnt)
array.push(zTouch, tc)
array.push(zName, nm)
ok
int nLv = array.size(lvP)
if nLv >= 2 and not na(atrV)
array<int> idx = array.sort_indices(lvP, order.ascending)
float tol = mergeTol * atrV
int gCnt = 0
bool gS = false
bool gF = false
bool gW = false
bool gSw = false
float gLo = na
float gHi = na
string gNm = ""
for k = 0 to nLv - 1
int j = array.get(idx, k)
float v = array.get(lvP, j)
// Width cap (2x tolerance) stops chain-merging into one giant zone
if gCnt > 0 and (v - gHi > tol or v - gLo > 2.0 * tol)
f_push(gCnt, gS, gF, gW, gSw, gLo, gHi, gNm)
gCnt := 0
gS := false
gF := false
gW := false
gSw := false
gNm := ""
if gCnt == 0
gLo := v
gHi := v
gCnt += 1
int src = array.get(lvS, j)
int tier = array.get(lvT, j)
gS := gS or src == 0
gF := gF or src == 1
gW := gW or tier == 2
gSw := gSw or tier == 3
gNm := gNm == "" ? array.get(lvN, j) : gNm + "+" + array.get(lvN, j)
if gCnt > 0
f_push(gCnt, gS, gF, gW, gSw, gLo, gHi, gNm)
// ═══════════════════════════════ RAW SIGNAL DETECTION ═══════════════════════════════
int rejDir = 0
float rejTop = na
float rejBot = na
float bestRej = -1.0
int brkDir = 0
float brkTop = na
float brkBot = na
float bestBrk = -1.0
int nZ = array.size(zTop)
if nZ > 0 and not na(atrV)
for i = 0 to nZ - 1
float t = array.get(zTop, i)
float b = array.get(zBot, i)
float sc = array.get(zScore, i)
if sc >= minScore
// Rejection: wick into zone, close back out on the side price came from
if sigMode != "Breakout Only" and sc > bestRej
if low <= t and low >= b - 0.5 * atrV and close > t and close > open and lwFrac >= wickMin and close[1] > b
rejDir := 1
rejTop := t
rejBot := b
bestRej := sc
else if high >= b and high <= t + 0.5 * atrV and close < b and close < open and uwFrac >= wickMin and close[1] < t
rejDir := -1
rejTop := t
rejBot := b
bestRej := sc
// Breakout: decisive body close through the zone
if sigMode != "Rejection Only" and sc > bestBrk
if close[1] <= t and close > t + brkBuf * atrV and close > open and bodyFrac >= bodyMin
brkDir := 1
brkTop := t
brkBot := b
bestBrk := sc
else if close[1] >= b and close < b - brkBuf * atrV and close < open and bodyFrac >= bodyMin
brkDir := -1
brkTop := t
brkBot := b
bestBrk := sc
// FIX: repaint protection — act only on closed bars
bool confOk = not useConfirmed or barstate.isconfirmed
// ═══════════════════════════════ RETEST ENGINE ═══════════════════════════════
// FIX: false-breakout filter — a breakout is stored as "pending" and only becomes a
// signal when price returns to the broken edge and closes back in the breakout direction.
var int pbDir = 0
var float pbTop = na
var float pbBot = na
var int pbBar = na
bool retestBuy = false
bool retestSell = false
float rtTop = na
float rtBot = na
if confOk and useRetest and not na(atrV)
if pbDir != 0
int age = bar_index - pbBar
if age > retestWin
pbDir := 0
else if age >= 1
if pbDir == 1
if close < pbBot
pbDir := 0 // failed breakout — cancel
else if low <= pbTop + retestTol * atrV and close > pbTop and close > open
retestBuy := true
rtTop := pbTop
rtBot := pbBot
pbDir := 0
else
if close > pbTop
pbDir := 0 // failed breakdown — cancel
else if high >= pbBot - retestTol * atrV and close < pbBot and close < open
retestSell := true
rtTop := pbTop
rtBot := pbBot
pbDir := 0
if brkDir != 0
pbDir := brkDir
pbTop := brkTop
pbBot := brkBot
pbBar := bar_index
bool brkBuy = useRetest ? retestBuy : brkDir == 1
bool brkSell = useRetest ? retestSell : brkDir == -1
float bkTop = useRetest ? rtTop : brkTop
float bkBot = useRetest ? rtBot : brkBot
// ═══════════════════════════════ FILTERS ═══════════════════════════════
float emaT = ta.ema(close, trendLen)
[diPlus, diMinus, adxV] = ta.dmi(adxLen, adxLen)
bool trendAll = trendScope == "All Signals"
bool upOk = not useTrend or close > emaT
bool dnOk = not useTrend or close < emaT
// FIX: ADX sideways filter (breakouts only — rejections are designed for ranges)
bool adxOk = not useAdx or (not na(adxV) and adxV >= adxMin)
// FIX: activity filter
bool actOk = not useAct or actV >= actMin
bool rejBuyOk = rejDir == 1 and (not trendAll or upOk)
bool rejSellOk = rejDir == -1 and (not trendAll or dnOk)
bool brkBuyOk = brkBuy and upOk and adxOk
bool brkSellOk = brkSell and dnOk and adxOk
// ═══════════════════════════════ MAIN SIGNALS ═══════════════════════════════
var int side = 0 // 1 = buy side active, -1 = sell side active, 0 = flat
var int buyCount = 0
var int sellCount = 0
var float lastBuyPrice = na
var float lastSellPrice = na
var float stopPx = na
var int lastSignalBar = na
// FIX: cooldown against back-to-back / flip-flop signals
bool cdOk = na(lastSignalBar) or (bar_index - lastSignalBar) > cooldown
// FIX: block repeated same-side signals
bool buySignal = (rejBuyOk or brkBuyOk) and actOk and confOk and cdOk and (not oneDir or side != 1)
bool sellSignal = (rejSellOk or brkSellOk) and actOk and confOk and cdOk and (not oneDir or side != -1) and not buySignal
string buyKind = rejBuyOk ? "REJECT" : useRetest ? "RETEST" : "BREAK"
string sellKind = rejSellOk ? "REJECT" : useRetest ? "RETEST" : "BREAK"
float buyZBot = rejBuyOk ? rejBot : bkBot
float sellZTop = rejSellOk ? rejTop : bkTop
// ═══════════════════════════════ PYRAMID ENGINE ═══════════════════════════════
// Average In : Buy adds when close <= lastBuyPrice - step ; Sell adds when close >= lastSellPrice + step
// Scale In : Buy adds when close >= lastBuyPrice + step ; Sell adds when close <= lastSellPrice - step
// Counters reset on an opposite main signal or on a stop exit.
float stepAtr = ta.atr(distAtrLen) * distAtrMul
float stepDist = distMode == "Ticks" ? distTicks * syminfo.mintick : stepAtr
bool averageIn = pyrDir == "Against (Average In)"
bool pyrBuy = false
bool pyrSell = false
bool exitLong = false
bool exitShort = false
if buySignal
side := 1
buyCount := 1
lastBuyPrice := close
sellCount := 0
lastSellPrice := na
stopPx := math.min(nz(buyZBot, low), low) - stopBuf * atrV
lastSignalBar := bar_index
else if sellSignal
side := -1
sellCount := 1
lastSellPrice := close
buyCount := 0
lastBuyPrice := na
stopPx := math.max(nz(sellZTop, high), high) + stopBuf * atrV
lastSignalBar := bar_index
else if confOk
// FIX: zone-break stop resets the side so the pyramid never keeps adding into a failed zone
if useStop and side == 1 and not na(stopPx) and close < stopPx
exitLong := true
side := 0
buyCount := 0
lastBuyPrice := na
stopPx := na
else if useStop and side == -1 and not na(stopPx) and close > stopPx
exitShort := true
side := 0
sellCount := 0
lastSellPrice := na
stopPx := na
else if usePyr and not na(stepDist)
if side == 1 and buyCount < maxOrders and not na(lastBuyPrice)
bool hitBuy = averageIn ? close <= lastBuyPrice - stepDist : close >= lastBuyPrice + stepDist
if hitBuy
buyCount += 1
lastBuyPrice := close
pyrBuy := true
else if side == -1 and sellCount < maxOrders and not na(lastSellPrice)
bool hitSell = averageIn ? close >= lastSellPrice + stepDist : close <= lastSellPrice - stepDist
if hitSell
sellCount += 1
lastSellPrice := close
pyrSell := true
// ═══════════════════════════════ LABELS ═══════════════════════════════
if showLabels and (buySignal or pyrBuy)
string bTxt = "B" + str.tostring(buyCount) + (buySignal ? "\n" + buyKind : "")
label.new(bar_index, low - atrV * 0.6, bTxt, style = label.style_label_up, color = buySignal ? bullCol : color.new(bullCol, 40), textcolor = color.black, size = size.small)
if showLabels and (sellSignal or pyrSell)
string sTxt = "S" + str.tostring(sellCount) + (sellSignal ? "\n" + sellKind : "")
label.new(bar_index, high + atrV * 0.6, sTxt, style = label.style_label_down, color = sellSignal ? bearCol : color.new(bearCol, 40), textcolor = color.black, size = size.small)
if showLabels and (exitLong or exitShort)
label.new(bar_index, exitLong ? low - atrV * 0.6 : high + atrV * 0.6, "X STOP", style = exitLong ? label.style_label_up : label.style_label_down, color = color.new(color.gray, 20), textcolor = color.white, size = size.tiny)
// ═══════════════════════════════ PLOTS ═══════════════════════════════
plot(showTrend and useTrend ? emaT : na, "Trend EMA", color = color.new(color.gray, 30), linewidth = 1)
plot(useStop and showStop and side != 0 ? stopPx : na, "Active Stop", color = side == 1 ? bullCol : bearCol, style = plot.style_linebr, linewidth = 1)
plotshape(buySignal, "Buy", shape.triangleup, location.belowbar, color.green, size = size.small)
plotshape(pyrBuy, "Pyramid Buy", shape.circle, location.belowbar, color.new(color.green, 30), size = size.tiny)
plotshape(sellSignal, "Sell", shape.triangledown, location.abovebar, color.red, size = size.small)
plotshape(pyrSell, "Pyramid Sell", shape.circle, location.abovebar, color.new(color.red, 30), size = size.tiny)
plotshape(exitLong or exitShort, "Stop Exit", shape.xcross, location.abovebar, color.gray, size = size.tiny)
// ═══════════════════════════════ ZONE DRAWINGS (last bar) ═══════════════════════════════
var array<box> zBoxes = array.new<box>()
color fgC = chart.fg_color
if barstate.islast
if array.size(zBoxes) > 0
for i = array.size(zBoxes) - 1 to 0
box.delete(array.get(zBoxes, i))
array.clear(zBoxes)
if showZones and nZ > 0
array<float> dist = array.new<float>()
for i = 0 to nZ - 1
array.push(dist, math.abs((array.get(zTop, i) + array.get(zBot, i)) / 2.0 - close))
array<int> ord = array.sort_indices(dist, order.ascending)
int shown = math.min(zonesShown, nZ)
for k = 0 to shown - 1
int i = array.get(ord, k)
float t = array.get(zTop, i)
float b = array.get(zBot, i)
float sc = array.get(zScore, i)
color base = b > close ? bearCol : t < close ? bullCol : zoneCol
int tr = int(math.max(55.0, 90.0 - sc * 0.35))
string txt = str.tostring(array.get(zCnt, i)) + "x [" + array.get(zName, i) + "] · " + str.tostring(array.get(zTouch, i)) + " touches · " + str.tostring(sc, "#")
box bx = box.new(int(time - 40 * tfms), t, int(time + 25 * tfms), b, xloc = xloc.bar_time, bgcolor = color.new(base, tr), border_color = color.new(base, 60), text = txt, text_size = size.tiny, text_color = color.new(fgC, 10), text_halign = text.align_right, text_valign = text.align_center)
array.push(zBoxes, bx)
// ═══════════════════════════════ DASHBOARD ═══════════════════════════════
var table dash = table.new(position.top_right, 2, 6, bgcolor = color.new(chart.bg_color, 10), border_color = color.new(chart.fg_color, 80), border_width = 1, frame_color = color.new(chart.fg_color, 70), frame_width = 1)
if barstate.islast and showTable
float supSc = na
float resSc = na
float supD = 1e18
float resD = 1e18
if nZ > 0
for i = 0 to nZ - 1
float t = array.get(zTop, i)
float b = array.get(zBot, i)
if t < close and close - t < supD
supD := close - t
supSc := array.get(zScore, i)
if b > close and b - close < resD
resD := b - close
resSc := array.get(zScore, i)
string sideTxt = side == 1 ? "LONG · " + str.tostring(buyCount) + "/" + str.tostring(maxOrders) : side == -1 ? "SHORT · " + str.tostring(sellCount) + "/" + str.tostring(maxOrders) : "FLAT"
color sideCol = side == 1 ? bullCol : side == -1 ? bearCol : color.new(fgC, 40)
table.cell(dash, 0, 0, "CZR PYRAMID", text_color = zoneCol, text_size = size.small)
table.merge_cells(dash, 0, 0, 1, 0)
table.cell(dash, 0, 1, "Side", text_color = color.new(fgC, 30), text_size = size.small, text_halign = text.align_left)
table.cell(dash, 1, 1, sideTxt, text_color = sideCol, text_size = size.small, text_halign = text.align_left)
table.cell(dash, 0, 2, "Stop", text_color = color.new(fgC, 30), text_size = size.small, text_halign = text.align_left)
table.cell(dash, 1, 2, na(stopPx) or side == 0 ? "—" : str.tostring(stopPx, format.mintick), text_color = fgC, text_size = size.small, text_halign = text.align_left)
table.cell(dash, 0, 3, "Support Score", text_color = color.new(fgC, 30), text_size = size.small, text_halign = text.align_left)
table.cell(dash, 1, 3, na(supSc) ? "—" : str.tostring(supSc, "#"), text_color = bullCol, text_size = size.small, text_halign = text.align_left)
table.cell(dash, 0, 4, "Resistance Score", text_color = color.new(fgC, 30), text_size = size.small, text_halign = text.align_left)
table.cell(dash, 1, 4, na(resSc) ? "—" : str.tostring(resSc, "#"), text_color = bearCol, text_size = size.small, text_halign = text.align_left)
table.cell(dash, 0, 5, "Data", text_color = color.new(fgC, 30), text_size = size.small, text_halign = text.align_left)
table.cell(dash, 1, 5, hasVol ? "VOLUME" : "RANGE PROXY", text_color = color.new(fgC, 40), text_size = size.small, text_halign = text.align_left)
// ═══════════════════════════════ ALERTS ═══════════════════════════════
alertcondition(buySignal, "CZR Buy", "CZR Buy at confluence zone on {{ticker}} {{interval}} @ {{close}}")
alertcondition(sellSignal, "CZR Sell", "CZR Sell at confluence zone on {{ticker}} {{interval}} @ {{close}}")
alertcondition(pyrBuy, "CZR Pyramid Buy", "CZR Pyramid Buy add on {{ticker}} @ {{close}}")
alertcondition(pyrSell, "CZR Pyramid Sell", "CZR Pyramid Sell add on {{ticker}} @ {{close}}")
alertcondition(exitLong or exitShort, "CZR Stop Exit", "CZR stop exit, side reset on {{ticker}} @ {{close}}")