本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Ziggy Stardust — Swing Analytics", shorttitle="Ziggy Stardust", overlay=true, behind_chart=false, max_lines_count=500, max_labels_count=500)
// ============================================================
// SWING DETECTION
// ============================================================
string tf = input.timeframe("1D", "Analysis timeframe", group="Swing Detection", tooltip="Must be equal to or higher than the chart timeframe.")
string mode = input.string("Percent", "Reversal mode", options=["Percent", "ATR"], group="Swing Detection")
float revPct = input.float(3.0, "Reversal (%)", minval=0.1, step=0.1, group="Swing Detection", active=mode=="Percent") / 100.0
float atrMult = input.float(1.5, "ATR multiplier", minval=0.1, step=0.1, group="Swing Detection", active=mode=="ATR")
int atrPeriod = input.int(14, "ATR period", minval=1, group="Swing Detection", tooltip="Wilder ATR period. Also used for the ATR statistics row.")
int minBars = input.int(4, "Minimum bars", minval=1, group="Swing Detection", tooltip="Minimum age from running extreme to reversal confirmation, inclusive. Not a minimum pivot-to-pivot length.")
// ============================================================
// STUDY WINDOW
// ============================================================
string period = input.string("3Y", "Study period", options=["YTD", "1Y", "3Y", "5Y", "Custom", "All loaded"], group="Study Window")
int customStart = input.time(timestamp("01 Jan 2021 00:00 +0000"), "Custom start", group="Study Window", active=period=="Custom")
int customEnd = input.time(timestamp("31 Dec 2035 00:00 +0000"), "Custom end", group="Study Window", active=period=="Custom")
// ============================================================
// DISPLAY
// ============================================================
bool showZZ = input.bool(true, "Confirmed ZigZag", group="Display")
bool showLive = input.bool(true, "Developing leg", group="Display")
color lineColor = input.color(color.rgb(44,105,255), "Line color", group="Display")
int lineWidth = input.int(2, "Line width", minval=1, maxval=5, group="Display")
int maxSegments = input.int(240, "Maximum segments", minval=10, maxval=450, group="Display")
// ============================================================
// PIVOT LABELS
// ============================================================
bool labelPrice = input.bool(true, "Pivot price", group="Pivot Labels")
bool labelPercent = input.bool(true, "Swing change (%)", group="Pivot Labels")
bool labelDollars = input.bool(false, "Swing change ($)", group="Pivot Labels")
bool labelVolume = input.bool(true, "Cumulative swing volume", group="Pivot Labels")
bool labelAge = input.bool(false, "Swing age (bars)", group="Pivot Labels")
bool labelLive = input.bool(false, "Developing swing label", group="Pivot Labels")
string fontChoice = input.string("Normal", "Label font size", options=["Tiny","Small","Normal","Large","Huge"], group="Pivot Labels")
float labelOffsetATR = input.float(0.50, "Label distance (ATR)", minval=0.05, maxval=3.0, step=0.05, group="Pivot Labels", tooltip="Vertical gap between a pivot and its text label, measured in ATR. Low labels use 1.3 times this spacing. Increase if labels overlap candles.")
int maxLabels = input.int(200, "Maximum pivot labels", minval=10, maxval=450, group="Pivot Labels")
string labelTextSize = switch fontChoice
"Tiny" => size.tiny
"Small" => size.small
"Large" => size.large
"Huge" => size.huge
=> size.normal
// ============================================================
// STATISTICS TABLE
// ============================================================
bool showTable = input.bool(true, "Show statistics table", group="Statistics Table")
bool tableN = input.bool(true, "Sample count (N)", group="Statistics Table", active=showTable)
bool tablePct = input.bool(true, "Percentage distribution", group="Statistics Table", active=showTable)
bool tableDollar = input.bool(true, "Dollar distribution", group="Statistics Table", active=showTable)
bool tableAge = input.bool(false, "Swing duration distribution", group="Statistics Table", active=showTable)
bool tableMode = input.bool(true, "Mode (most common range)", group="Statistics Table", active=showTable and tablePct)
bool tableNormal = input.bool(true, "Normal (Mode + 1σ)", group="Statistics Table", active=showTable and tablePct)
bool tableP90 = input.bool(true, "Impulse (P90)", group="Statistics Table", active=showTable)
bool tableMedian = input.bool(true, "Median", group="Statistics Table", active=showTable)
bool tableMean = input.bool(true, "Mean", group="Statistics Table", active=showTable)
bool tableRange = input.bool(true, "Min–Max range", group="Statistics Table", active=showTable)
float modeBinWidth = input.float(1.0, "Mode bin width (%)", minval=0.1, maxval=20.0, step=0.1, group="Statistics Table", active=showTable and tablePct and (tableMode or tableNormal), tooltip="Percentage-point width of modal histogram bins. Normal = modal-bin midpoint + 1 standard deviation.")
bool tableCurrent = input.bool(true, "Current swing", group="Statistics Table", active=showTable)
bool tableRank = input.bool(true, "Current magnitude percentile", group="Statistics Table", active=showTable and tableCurrent)
bool tableAgeRank = input.bool(true, "Current age percentile", group="Statistics Table", active=showTable and tableAge and tableCurrent)
bool tableVsP90 = input.bool(true, "Current / P90", group="Statistics Table", active=showTable and tableCurrent)
bool tableReversal = input.bool(true, "Reversal trigger", group="Statistics Table", active=showTable)
bool tableATR = input.bool(true, "Current ATR ($ and %)", group="Statistics Table", active=showTable)
string tableFontChoice = input.string("Small", "Table font size", options=["Tiny","Small","Normal","Large"], group="Statistics Table", active=showTable)
string tableTextSize = switch tableFontChoice
"Tiny" => size.tiny
"Normal" => size.normal
"Large" => size.large
=> size.small
// ============================================================
// VALIDATION
// ============================================================
bool isHTF = timeframe.in_seconds(tf) > timeframe.in_seconds()
if timeframe.in_seconds(tf) < timeframe.in_seconds()
runtime.error("Analysis timeframe must be equal to or higher than the chart timeframe.")
if period=="Custom" and customEnd<=customStart
runtime.error("Custom end must be after custom start.")
// ============================================================
// REVERSAL HELPERS
// ============================================================
f_reversal(float extreme, float test, float atr) =>
bool result = false
if not na(extreme) and extreme!=0
if mode=="Percent"
result := math.abs(test-extreme)/math.abs(extreme)>=revPct
else
result := not na(atr) and atr>0 and math.abs(test-extreme)>=atrMult*atr
result
f_aged(int extremeBar) =>
bar_index-extremeBar+1>=minBars
// ============================================================
// FULL-LEG EXTREMES DETECTOR
//
// Trend: 0 = unknown, 1 = up, -1 = down
// Pivot: 1 = high, -1 = low
// ============================================================
f_engine() =>
float atr = ta.atr(atrPeriod)
float cum = ta.cum(nz(volume,0))
var int trend = 0
var int seq = 0
var float hi = na
var float lo = na
var int hiBar = na
var int loBar = na
var int hiTime = na
var int loTime = na
var float hiCum = na
var float loCum = na
var float hiVol = na
var float loVol = na
var float seedLo = na
var int seedLoBar = na
var int seedLoTime = na
var float seedLoCum = na
var float seedLoVol = na
var float seedHi = na
var int seedHiBar = na
var int seedHiTime = na
var float seedHiCum = na
var float seedHiVol = na
var float lastPivot = na
var int lastPivotTime = na
var int lastPivotBar = na
var int lastKind = 0
var float lastPivotCum = na
var float lastPivotVol = na
int eventTime = na
int eventBar = na
float eventPrice = na
int eventKind = 0
float eventCum = na
float eventVol = na
if na(hi)
hi := high
lo := low
hiBar := bar_index
loBar := bar_index
hiTime := time
loTime := time
hiCum := cum
loCum := cum
hiVol := nz(volume,0)
loVol := nz(volume,0)
else
// UNKNOWN TREND
if trend==0
if high>=hi
hi := high
hiBar := bar_index
hiTime := time
hiCum := cum
hiVol := nz(volume,0)
seedLo := na
else if na(seedLo) or low<=seedLo
seedLo := low
seedLoBar := bar_index
seedLoTime := time
seedLoCum := cum
seedLoVol := nz(volume,0)
if low<=lo
lo := low
loBar := bar_index
loTime := time
loCum := cum
loVol := nz(volume,0)
seedHi := na
else if na(seedHi) or high>=seedHi
seedHi := high
seedHiBar := bar_index
seedHiTime := time
seedHiCum := cum
seedHiVol := nz(volume,0)
if hiBar<bar_index and f_aged(hiBar) and f_reversal(hi,low,atr) and low<hi
seq+=1
eventTime := hiTime
eventBar := hiBar
eventPrice := hi
eventKind := 1
eventCum := hiCum
eventVol := hiVol
lastPivot := hi
lastPivotTime := hiTime
lastPivotBar := hiBar
lastKind := 1
trend := -1
if not na(seedLo) and seedLoBar>hiBar
lo := seedLo
loBar := seedLoBar
loTime := seedLoTime
loCum := seedLoCum
loVol := seedLoVol
else
lo := low
loBar := bar_index
loTime := time
loCum := cum
loVol := nz(volume,0)
seedHi := na
if trend==0 and loBar<bar_index and f_aged(loBar) and f_reversal(lo,high,atr) and high>lo
seq+=1
eventTime := loTime
eventBar := loBar
eventPrice := lo
eventKind := -1
eventCum := loCum
eventVol := loVol
lastPivot := lo
lastPivotTime := loTime
lastPivotBar := loBar
lastKind := -1
trend := 1
if not na(seedHi) and seedHiBar>loBar
hi := seedHi
hiBar := seedHiBar
hiTime := seedHiTime
hiCum := seedHiCum
hiVol := seedHiVol
else
hi := high
hiBar := bar_index
hiTime := time
hiCum := cum
hiVol := nz(volume,0)
seedLo := na
// UP LEG
else if trend==1
if high>=hi
hi := high
hiBar := bar_index
hiTime := time
hiCum := cum
hiVol := nz(volume,0)
seedLo := na
else
if na(seedLo) or low<=seedLo
seedLo := low
seedLoBar := bar_index
seedLoTime := time
seedLoCum := cum
seedLoVol := nz(volume,0)
if f_aged(hiBar) and f_reversal(hi,low,atr)
seq+=1
eventTime := hiTime
eventBar := hiBar
eventPrice := hi
eventKind := 1
eventCum := hiCum
eventVol := hiVol
lastPivot := hi
lastPivotTime := hiTime
lastPivotBar := hiBar
lastKind := 1
trend := -1
if not na(seedLo) and seedLoBar>hiBar
lo := seedLo
loBar := seedLoBar
loTime := seedLoTime
loCum := seedLoCum
loVol := seedLoVol
else
lo := low
loBar := bar_index
loTime := time
loCum := cum
loVol := nz(volume,0)
seedHi := na
// DOWN LEG
else
if low<=lo
lo := low
loBar := bar_index
loTime := time
loCum := cum
loVol := nz(volume,0)
seedHi := na
else
if na(seedHi) or high>=seedHi
seedHi := high
seedHiBar := bar_index
seedHiTime := time
seedHiCum := cum
seedHiVol := nz(volume,0)
if f_aged(loBar) and f_reversal(lo,high,atr)
seq+=1
eventTime := loTime
eventBar := loBar
eventPrice := lo
eventKind := -1
eventCum := loCum
eventVol := loVol
lastPivot := lo
lastPivotTime := loTime
lastPivotBar := loBar
lastKind := -1
trend := 1
if not na(seedHi) and seedHiBar>loBar
hi := seedHi
hiBar := seedHiBar
hiTime := seedHiTime
hiCum := seedHiCum
hiVol := seedHiVol
else
hi := high
hiBar := bar_index
hiTime := time
hiCum := cum
hiVol := nz(volume,0)
seedLo := na
if eventKind!=0
lastPivotCum := eventCum
lastPivotVol := eventVol
int extremeTime = trend==1 ? hiTime : loTime
float extremePrice = trend==1 ? hi : lo
float extremeCum = trend==1 ? hiCum : loCum
int age = na(lastPivotBar) ? na : bar_index-lastPivotBar+1
[seq,eventTime,eventBar,eventPrice,eventKind,eventCum,eventVol,lastPivotTime,lastPivot,lastPivotBar,lastKind,lastPivotCum,lastPivotVol,extremeTime,extremePrice,extremeCum,age,atr,close]
// ============================================================
// HIGHER TIMEFRAME — COMPLETED CANDLES
// ============================================================
f_confirmedEngine() =>
[s,et,eb,ep,ek,ec,ev,pt,pp,pb,pk,pc,pv,xt,xp,xc,age,atr,cl] = f_engine()
[s[1],et[1],eb[1],ep[1],ek[1],ec[1],ev[1],pt[1],pp[1],pb[1],pk[1],pc[1],pv[1],xt[1],xp[1],xc[1],age[1],atr[1],cl[1]]
// ============================================================
// FETCH ANALYSIS TIMEFRAME
// ============================================================
int seq = na
int eventTime = na
int eventBar = na
float eventPrice = na
int eventKind = 0
float eventCum = na
float eventVol = na
int pivotTime = na
float pivotPrice = na
int pivotBar = na
int pivotKind = 0
float pivotCum = na
float pivotVol = na
int extremeTime = na
float extremePrice = na
float extremeCum = na
int swingAge = na
float currentATR = na
float analysisClose = na
if isHTF
[s,et,eb,ep,ek,ec,ev,pt,pp,pb,pk,pc,pv,xt,xp,xc,age,atr,cl] = request.security(syminfo.tickerid,tf,f_confirmedEngine(),gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_on)
seq := s
eventTime := et
eventBar := eb
eventPrice := ep
eventKind := ek
eventCum := ec
eventVol := ev
pivotTime := pt
pivotPrice := pp
pivotBar := pb
pivotKind := pk
pivotCum := pc
pivotVol := pv
extremeTime := xt
extremePrice := xp
extremeCum := xc
swingAge := age
currentATR := atr
analysisClose := cl
else
[s,et,eb,ep,ek,ec,ev,pt,pp,pb,pk,pc,pv,xt,xp,xc,age,atr,cl] = f_engine()
seq := s
eventTime := et
eventBar := eb
eventPrice := ep
eventKind := ek
eventCum := ec
eventVol := ev
pivotTime := pt
pivotPrice := pp
pivotBar := pb
pivotKind := pk
pivotCum := pc
pivotVol := pv
extremeTime := xt
extremePrice := xp
extremeCum := xc
swingAge := age
currentATR := atr
analysisClose := cl
// ============================================================
// STUDY WINDOW
// ============================================================
int msYear = 31557600000
int startTime = switch period
"YTD" => timestamp(syminfo.timezone,year(last_bar_time),1,1,0,0)
"1Y" => last_bar_time-msYear
"3Y" => last_bar_time-3*msYear
"5Y" => last_bar_time-5*msYear
"Custom" => customStart
=> 0
int endTime = period=="Custom" ? customEnd : last_bar_time
// ============================================================
// HISTORICAL DISTRIBUTIONS
// ============================================================
var array<float> upPct = array.new_float()
var array<float> downPct = array.new_float()
var array<float> upDollar = array.new_float()
var array<float> downDollar = array.new_float()
var array<float> upBars = array.new_float()
var array<float> downBars = array.new_float()
var array<line> lines = array.new_line()
var array<label> labels = array.new_label()
var int prevTime = na
var int prevBar = na
var float prevPrice = na
var int prevKind = 0
var float prevCum = na
var float prevVol = na
// ============================================================
// LABEL FORMATTER
// ============================================================
f_pivotLabel(float px,int kind,float dollars,float pct,float vol,int bars,bool hasSwing) =>
string result = labelPrice ? str.tostring(px,format.mintick) : ""
if hasSwing and labelPercent
string part = (kind==1 ? "+" : "-")+str.tostring(pct,"#.##")+"%"
result := result=="" ? part : result+"\n"+part
if hasSwing and labelDollars
string part = (kind==1 ? "+$" : "-$")+str.tostring(dollars,"#.##")
result := result=="" ? part : result+"\n"+part
if hasSwing and labelVolume
string volText = vol>=1000000 ? str.tostring(vol/1000000,"#.0")+"M" : vol>=1000 ? str.tostring(vol/1000,"#.0")+"K" : str.tostring(vol,"#.0")
string part = "Vol "+volText
result := result=="" ? part : result+"\n"+part
if hasSwing and labelAge
string part = str.tostring(bars)+" bars"
result := result=="" ? part : result+"\n"+part
result
// ============================================================
// LABEL OFFSET HELPER — NEW IN v1.6.4
//
// High label: above pivot
// Low label: below pivot
//
// Uses ATR for adaptive spacing. The fallback is 2%
// of price if ATR is not available.
// ============================================================
f_labelY(float px,int kind,float atrValue) =>
float atrBase = nz(atrValue,math.abs(px)*0.02)
float baseGap = math.max(atrBase*labelOffsetATR,syminfo.mintick*5)
// Extra gap below lows to avoid overlapping lower wicks.
float gap = kind==1 ? baseGap : baseGap*1.30
kind==1 ? px+gap : px-gap
// ============================================================
// CONFIRMED PIVOTS
// ============================================================
bool newPivot = not na(seq) and not na(seq[1]) and seq!=seq[1]
bool canCommit = isHTF or barstate.isconfirmed
if newPivot and canCommit and not na(eventTime)
bool hasPrevious = not na(prevPrice)
float dollars = hasPrevious ? math.abs(eventPrice-prevPrice) : na
float pct = hasPrevious and prevPrice!=0 ? dollars/math.abs(prevPrice)*100.0 : na
float vol = hasPrevious ? math.max(0.0,eventCum-prevCum+prevVol) : na
int bars = hasPrevious and not na(prevBar) and not na(eventBar) ? eventBar-prevBar+1 : na
bool inWindow = hasPrevious and prevTime>=startTime and eventTime>=startTime and eventTime<=endTime
if inWindow and not na(pct)
if prevKind==-1 and eventKind==1
array.push(upPct,pct)
array.push(upDollar,dollars)
if not na(bars)
array.push(upBars,float(bars))
else if prevKind==1 and eventKind==-1
array.push(downPct,pct)
array.push(downDollar,dollars)
if not na(bars)
array.push(downBars,float(bars))
if showZZ and hasPrevious
line ln = line.new(
prevTime,prevPrice,
eventTime,eventPrice,
xloc=xloc.bar_time,
color=lineColor,
width=lineWidth
)
array.push(lines,ln)
if array.size(lines)>maxSegments
line.delete(array.shift(lines))
// BOX-FREE LABELS WITH ADAPTIVE POSITIONING
if labelPrice or labelPercent or labelDollars or labelVolume or labelAge
string txt = f_pivotLabel(eventPrice,eventKind,dollars,pct,vol,bars,hasPrevious)
if txt!=""
float labelY = f_labelY(eventPrice,eventKind,currentATR)
label lbl = label.new(
eventTime,
eventPrice,
txt,
xloc=xloc.bar_time,
yloc=yloc.price,
style=eventKind == 1 ? label.style_label_down : label.style_label_up,
color=color.new(color.white, 100),
textcolor=eventKind == 1 ? color.rgb(24,153,94) : color.rgb(213,65,70),
size=labelTextSize,
textalign=text.align_center
)
array.push(labels,lbl)
if array.size(labels)>maxLabels
label.delete(array.shift(labels))
prevTime := eventTime
prevBar := eventBar
prevPrice := eventPrice
prevKind := eventKind
prevCum := eventCum
prevVol := eventVol
// ============================================================
// DEVELOPING LEG
// ============================================================
bool hasLeg = pivotKind!=0 and not na(pivotPrice) and not na(extremePrice)
int direction = pivotKind==-1 ? 1 : pivotKind==1 ? -1 : 0
float currentDollar = hasLeg ? math.abs(extremePrice-pivotPrice) : na
float currentPct = hasLeg and pivotPrice!=0 ? currentDollar/math.abs(pivotPrice)*100.0 : na
float currentVolume = hasLeg ? math.max(0.0,extremeCum-pivotCum+pivotVol) : na
var line developingLine = na
var label developingLabel = na
if barstate.islast
if not na(developingLine)
line.delete(developingLine)
developingLine := na
if not na(developingLabel)
label.delete(developingLabel)
developingLabel := na
if showLive and hasLeg
developingLine := line.new(
pivotTime,pivotPrice,
extremeTime,extremePrice,
xloc=xloc.bar_time,
color=lineColor,
width=lineWidth,
style=line.style_dashed
)
if labelLive
int liveKind = direction==1 ? 1 : -1
string liveText = f_pivotLabel(
extremePrice,
liveKind,
currentDollar,
currentPct,
currentVolume,
swingAge,
true
)
if liveText!=""
float liveY = f_labelY(extremePrice,liveKind,currentATR)
developingLabel := label.new(
extremeTime,
extremePrice,
liveText,
xloc=xloc.bar_time,
yloc=yloc.price,
style=direction == 1 ? label.style_label_down : label.style_label_up,
color=color.new(color.white, 100),
textcolor=direction == 1 ? color.rgb(24,153,94) : color.rgb(213,65,70),
size=labelTextSize,
textalign=text.align_center
)
// ============================================================
// STATISTICAL HELPERS
// ============================================================
f_mean(array<float> a) =>
array.size(a)>0 ? array.avg(a) : na
f_quantile(array<float> a,float p) =>
float result = na
int n = array.size(a)
if n>0
array<float> sorted = array.copy(a)
array.sort(sorted,order.ascending)
if n==1
result := array.get(sorted,0)
else
float pos = p/100.0*(n-1)
int lowerIdx = int(math.floor(pos))
int upperIdx = int(math.ceil(pos))
float weight = pos-lowerIdx
result := array.get(sorted,lowerIdx)*(1-weight)+array.get(sorted,upperIdx)*weight
result
f_rank(array<float> a,float v) =>
float result = na
int n = array.size(a)
if n>0 and not na(v)
int count = 0
for i=0 to n-1
if array.get(a,i)<=v
count+=1
result := 100.0*count/n
result
// ============================================================
// HISTOGRAM MODE
// ============================================================
f_histMode(array<float> a,float width) =>
float binLow = na
float binHigh = na
float midpoint = na
int frequency = 0
int n = array.size(a)
if n>0 and width>0
array<int> keys = array.new_int()
array<int> counts = array.new_int()
for i=0 to n-1
float value = array.get(a,i)
int key = int(math.floor(value/width))
int found = -1
int kCount = array.size(keys)
if kCount>0
for j=0 to kCount-1
if array.get(keys,j)==key
found := j
break
if found>=0
array.set(counts,found,array.get(counts,found)+1)
else
array.push(keys,key)
array.push(counts,1)
int bestKey = na
int binCount = array.size(keys)
if binCount>0
for j=0 to binCount-1
int key = array.get(keys,j)
int cnt = array.get(counts,j)
if cnt>frequency or (cnt==frequency and (na(bestKey) or key<bestKey))
frequency := cnt
bestKey := key
binLow := bestKey*width
binHigh := binLow+width
midpoint := (binLow+binHigh)/2.0
[binLow,binHigh,midpoint,frequency]
f_pct(float v) =>
na(v) ? "—" : str.tostring(v,"#.##")+"%"
f_usd(float v) =>
na(v) ? "—" : "$"+str.tostring(v,"#.##")
f_bars(float v) =>
na(v) ? "—" : str.tostring(v,"#.#")
f_range(array<float> a,string suffix) =>
array.size(a)==0 ? "—" : str.tostring(array.min(a),"#.##")+"–"+str.tostring(array.max(a),"#.##")+suffix
f_modeText(float lo,float hi) =>
na(lo) ? "—" : str.tostring(lo,"#.##")+"–"+str.tostring(hi,"#.##")+"%"
// ============================================================
// MODE / NORMAL / IMPULSE
// ============================================================
[upModeLow,upModeHigh,upModeMid,upModeCount] = f_histMode(upPct,modeBinWidth)
[downModeLow,downModeHigh,downModeMid,downModeCount] = f_histMode(downPct,modeBinWidth)
float upSigma = array.size(upPct)>1 ? array.stdev(upPct,true) : na
float downSigma = array.size(downPct)>1 ? array.stdev(downPct,true) : na
float upNormal = not na(upModeMid) and not na(upSigma) ? upModeMid+upSigma : na
float downNormal = not na(downModeMid) and not na(downSigma) ? downModeMid+downSigma : na
float upImpulse = f_quantile(upPct,90)
float downImpulse = f_quantile(downPct,90)
// ============================================================
// CURRENT SWING
// ============================================================
array<float> comparison = direction==1 ? upPct : downPct
array<float> ageComparison = direction==1 ? upBars : downBars
float currentRank = direction!=0 ? f_rank(comparison,currentPct) : na
float currentAgeRank = direction!=0 and not na(swingAge) ? f_rank(ageComparison,float(swingAge)) : na
float currentNormal = direction==1 ? upNormal : direction==-1 ? downNormal : na
float currentP90 = direction==1 ? upImpulse : direction==-1 ? downImpulse : na
float currentVsNormal = not na(currentNormal) and currentNormal>0 ? currentPct/currentNormal*100.0 : na
float currentVsP90 = not na(currentP90) and currentP90>0 ? currentPct/currentP90*100.0 : na
// ============================================================
// ATR
// ============================================================
float currentATRPercent = not na(currentATR) and not na(analysisClose) and analysisClose!=0 ? currentATR/math.abs(analysisClose)*100.0 : na
string atrText = na(currentATR) ? "—" : f_usd(currentATR)+" ("+f_pct(currentATRPercent)+")"
// ============================================================
// REVERSAL TRIGGER
// ============================================================
float reversalLevel = na
if hasLeg
if mode=="Percent"
reversalLevel := direction==1 ? extremePrice*(1-revPct) : extremePrice*(1+revPct)
else if not na(currentATR)
reversalLevel := direction==1 ? extremePrice-atrMult*currentATR : extremePrice+atrMult*currentATR
// ============================================================
// ALERTS — NORMAL AND IMPULSE
// ============================================================
bool aboveNormal = hasLeg and not na(currentNormal) and currentPct>currentNormal
bool aboveImpulse = hasLeg and not na(currentP90) and currentPct>currentP90
bool normalCross = barstate.isconfirmed and aboveNormal and not aboveNormal[1]
bool impulseCross = barstate.isconfirmed and aboveImpulse and not aboveImpulse[1]
alertcondition(normalCross,"Swing exceeds Normal",'{{ticker}}: Swing exceeds Mode + 1 sigma. Current={{plot("Current swing %")}}%, Normal={{plot("Normal threshold %")}}%.')
alertcondition(normalCross and direction==1,"Up swing exceeds Normal",'{{ticker}}: UP swing exceeds Normal. Current={{plot("Current swing %")}}%.')
alertcondition(normalCross and direction==-1,"Down swing exceeds Normal",'{{ticker}}: DOWN swing exceeds Normal. Current={{plot("Current swing %")}}%.')
alertcondition(impulseCross,"Swing exceeds Impulse P90",'{{ticker}}: Swing exceeds P90. Current={{plot("Current swing %")}}%, P90={{plot("Historical P90 %")}}%.')
alertcondition(impulseCross and direction==1,"Up swing exceeds P90",'{{ticker}}: UP swing exceeds P90. Current={{plot("Current swing %")}}%.')
alertcondition(impulseCross and direction==-1,"Down swing exceeds P90",'{{ticker}}: DOWN swing exceeds P90. Current={{plot("Current swing %")}}%.')
// ============================================================
// TABLE STYLING
// ============================================================
color bg = color.rgb(43,48,57)
color header = color.rgb(35,43,56)
color focusBg = color.rgb(64,69,79)
color muted = color.rgb(195,203,215)
color whiteText = color.white
// ============================================================
// TABLE INITIALIZATION
// ============================================================
var table t = table.new(position.top_right,3,30,border_width=1)
var bool atrMerged = false
// ============================================================
// TABLE ROW HELPER
// ============================================================
f_row(int row,string name,string upValue,string downValue,bool highlight=false) =>
color rowBg = highlight ? focusBg : bg
table.cell(t,0,row,name,bgcolor=rowBg,text_color=highlight ? whiteText : muted,text_size=tableTextSize)
table.cell(t,1,row,upValue,bgcolor=rowBg,text_color=whiteText,text_size=tableTextSize)
table.cell(t,2,row,downValue,bgcolor=rowBg,text_color=whiteText,text_size=tableTextSize)
// ============================================================
// TABLE RENDERING
// ============================================================
if barstate.islast
table.clear(t,0,0,2,29)
if showTable
table.cell(t,0,0,"ZIGGY ✦",bgcolor=header,text_color=whiteText,text_size=tableTextSize)
table.cell(t,1,0,"UP ↑",bgcolor=header,text_color=color.rgb(100,235,177),text_size=tableTextSize)
table.cell(t,2,0,"DOWN ↓",bgcolor=header,text_color=color.rgb(255,140,140),text_size=tableTextSize)
int r = 1
if tableN
f_row(r,"Swings (N)",str.tostring(array.size(upPct)),str.tostring(array.size(downPct)))
r+=1
// PERCENTAGE DISTRIBUTION
if tablePct
if tableMode
f_row(r,"Mode %",f_modeText(upModeLow,upModeHigh),f_modeText(downModeLow,downModeHigh))
r+=1
if tableNormal
f_row(r,"Normal (Mode+1σ)",f_pct(upNormal),f_pct(downNormal))
r+=1
if tableP90
f_row(r,"Impulse (P90) %",f_pct(upImpulse),f_pct(downImpulse))
r+=1
if tableMedian
f_row(r,"Median %",f_pct(f_quantile(upPct,50)),f_pct(f_quantile(downPct,50)))
r+=1
if tableMean
f_row(r,"Mean %",f_pct(f_mean(upPct)),f_pct(f_mean(downPct)))
r+=1
if tableRange
f_row(r,"Range %",f_range(upPct,"%"),f_range(downPct,"%"))
r+=1
// DOLLAR DISTRIBUTION
if tableDollar
if tableMedian
f_row(r,"Median $",f_usd(f_quantile(upDollar,50)),f_usd(f_quantile(downDollar,50)))
r+=1
if tableMean
f_row(r,"Mean $",f_usd(f_mean(upDollar)),f_usd(f_mean(downDollar)))
r+=1
if tableP90
f_row(r,"Impulse (P90) $",f_usd(f_quantile(upDollar,90)),f_usd(f_quantile(downDollar,90)))
r+=1
if tableRange
f_row(r,"Range $",f_range(upDollar,""),f_range(downDollar,""))
r+=1
// SWING DURATION
if tableAge
if tableMedian
f_row(r,"Median bars",f_bars(f_quantile(upBars,50)),f_bars(f_quantile(downBars,50)))
r+=1
if tableMean
f_row(r,"Mean bars",f_bars(f_mean(upBars)),f_bars(f_mean(downBars)))
r+=1
if tableP90
f_row(r,"P90 bars",f_bars(f_quantile(upBars,90)),f_bars(f_quantile(downBars,90)))
r+=1
if tableRange
f_row(r,"Range bars",f_range(upBars,""),f_range(downBars,""))
r+=1
// CURRENT SWING
if tableCurrent
f_row(r,"CURRENT",direction==1 ? f_pct(currentPct) : "—",direction==-1 ? f_pct(currentPct) : "—",true)
r+=1
if tableDollar
f_row(r,"Current $",direction==1 ? f_usd(currentDollar) : "—",direction==-1 ? f_usd(currentDollar) : "—")
r+=1
if tableRank
f_row(r,"Magnitude rank",direction==1 ? f_pct(currentRank) : "—",direction==-1 ? f_pct(currentRank) : "—")
r+=1
if tableNormal
f_row(r,"Current / Normal",direction==1 ? f_pct(currentVsNormal) : "—",direction==-1 ? f_pct(currentVsNormal) : "—")
r+=1
if tableVsP90
f_row(r,"Current / P90",direction==1 ? f_pct(currentVsP90) : "—",direction==-1 ? f_pct(currentVsP90) : "—",true)
r+=1
f_row(r,"Current age",direction==1 and not na(swingAge) ? str.tostring(swingAge)+" bars" : "—",direction==-1 and not na(swingAge) ? str.tostring(swingAge)+" bars" : "—")
r+=1
if tableAge and tableAgeRank
f_row(r,"Age rank",direction==1 ? f_pct(currentAgeRank) : "—",direction==-1 ? f_pct(currentAgeRank) : "—")
r+=1
// REVERSAL TRIGGER — NO HIGHLIGHT
if tableReversal
f_row(r,"Reversal trigger",direction==1 ? f_usd(reversalLevel) : "—",direction==-1 ? f_usd(reversalLevel) : "—")
r+=1
// CURRENT ATR — MERGED UP/DOWN CELL
if tableATR
table.cell(t,0,r,"Current ATR ("+str.tostring(atrPeriod)+")",bgcolor=bg,text_color=muted,text_size=tableTextSize)
table.cell(t,1,r,atrText,bgcolor=bg,text_color=whiteText,text_size=tableTextSize,text_halign=text.align_center)
if not atrMerged
table.merge_cells(t,1,r,2,r)
atrMerged := true
// ============================================================
// DATA WINDOW
// ============================================================
plot(currentPct,"Current swing %",display=display.data_window,editable=false)
plot(currentRank,"Current magnitude percentile",display=display.data_window,editable=false)
plot(currentAgeRank,"Current age percentile",display=display.data_window,editable=false)
plot(currentNormal,"Normal threshold %",display=display.data_window,editable=false)
plot(currentP90,"Historical P90 %",display=display.data_window,editable=false)
plot(currentVsNormal,"Current / Normal (%)",display=display.data_window,editable=false)
plot(currentVsP90,"Current / P90 (%)",display=display.data_window,editable=false)
plot(reversalLevel,"Reversal threshold",display=display.data_window,editable=false)
plot(currentVolume,"Developing swing volume",display=display.data_window,editable=false)
plot(currentATR,"Current ATR $",display=display.data_window,editable=false)
plot(currentATRPercent,"Current ATR %",display=display.data_window,editable=false)