本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Reversal Radar X | 10-in-1 Divergence, Reversal & Volume Intelligence [jjart]", "Radar X | jjart", overlay=true, max_labels_count=300, max_lines_count=250, max_boxes_count=200, max_bars_back=1200)
// Independent price-action analytics. Historical pivot labels are stamped on CONFIRMATION bars, never backdated.
// Scores represent heuristic evidence, NOT probability. Signals are not trades.
const string A="01 | Signal Engine"
const string B="02 | Divergence Cluster (8 Methods)"
const string C="03 | Price Action & Liquidity"
const string D="04 | Regime & Context"
const string E="05 | Visuals & Alerts"
const string F="06 | Outcome Research"
minCluster=input.int(3,"Minimum agreeing divergences",minval=1,maxval=8,group=A,tooltip="Suggested 3. Minimum number of oscillator divergences agreeing on the same price pivot; correlated oscillators do not equal independent evidence.")
setupScore=input.int(55,"SETUP threshold (0–100)",minval=20,maxval=95,group=A,tooltip="Suggested 55. Cluster + price action + context; higher values mean fewer opportunities.")
confirmScore=input.int(70,"CONFIRM threshold (0–100)",minval=30,maxval=100,group=A,tooltip="Suggested 70. Confirmation additionally requires a recent directional trigger.")
requireCluster=input.bool(true,"Require divergence cluster for SETUP",group=A,tooltip="Recommended ON. Prevents ordinary oscillation or candlestick patterns alone creating many setups.")
clusterLife=input.int(14,"Divergence cluster lifetime (bars)",minval=1,maxval=60,group=A,tooltip="Suggested 14. Evidence expires after this many closed bars since pivot confirmation.")
triggerLife=input.int(8,"Trigger lifetime (bars)",minval=1,maxval=30,group=A,tooltip="Suggested 8. Structural / reclaim triggers must be recent to confirm a candidate.")
cooldown=input.int(24,"Same-side signal cooldown (bars)",minval=1,maxval=200,group=A,tooltip="Suggested 24. Minimizes repeated signals on the same swing.")
confirmWindow=input.int(18,"Maximum bars from SETUP to CONFIRM",minval=2,maxval=100,group=A,tooltip="Suggested 18. Unconfirmed scenarios expire automatically.")
swing=input.int(5,"Price pivot strength (left/right)",minval=2,maxval=20,group=B,tooltip="Suggested 5. Confirmed pivots appear after RIGHT bars; no future values are used to generate past signals.")
minMoveATR=input.float(0.65,"Minimum pivot separation (ATR)",minval=0.0,maxval=5,step=0.05,group=B,tooltip="Suggested 0.65. Filter tiny successive pivots; use 0 to allow all.")
divMode=input.string("Regular + Hidden","Divergence families",options=["Regular","Hidden","Regular + Hidden"],group=B,tooltip="Regular: possible reversal. Hidden: potential trend continuation. Default both, but continuation is scored more conservatively.")
useRSI=input.bool(true,"RSI divergence",group=B,tooltip="Suggested ON. RSI compares average rising and falling price changes.")
useMACD=input.bool(true,"MACD histogram divergence",group=B,tooltip="Suggested ON. MACD histogram measures momentum relative to signal line.")
useCCI=input.bool(true,"CCI divergence",group=B,tooltip="Suggested ON. CCI uses deviation from typical price mean.")
useStoch=input.bool(true,"Stochastic divergence",group=B,tooltip="Suggested ON. Stochastic estimates close position in its high-low range.")
useMFI=input.bool(true,"Money Flow Index divergence",group=B,tooltip="Suggested ON if volume is available. Price-volume momentum; unavailable volume falls back to neutral.")
useOBV=input.bool(true,"OBV divergence",group=B,tooltip="Suggested ON if volume exists. Cumulative signed volume.")
useROC=input.bool(true,"Rate of Change divergence",group=B,tooltip="Suggested ON. Percentage price change over 12 bars.")
useCMF=input.bool(true,"Chaikin Money Flow divergence",group=B,tooltip="Suggested ON if volume exists. Closing-location-weighted volume over 20 bars.")
sweepLen=input.int(25,"Liquidity sweep lookback (bars)",minval=5,maxval=150,group=C,tooltip="Suggested 25. Detect a wick through the PREVIOUS lookback high/low followed by a close back within range.")
patternBars=input.int(10,"Price pattern evidence lifetime (bars)",minval=1,maxval=40,group=C,tooltip="Suggested 10. Old candle patterns should not continue validating new signals.")
structureLen=input.int(8,"Micro structure break period",minval=3,maxval=50,group=C,tooltip="Suggested 8. Confirmation needs a close beyond a past, non-current range extreme.")
wickRatio=input.float(0.55,"Rejection wick minimum fraction",minval=0.2,maxval=0.9,step=0.05,group=C,tooltip="Suggested 0.55. A long lower/upper wick can validate a rejection event.")
volumeMultiplier=input.float(1.6,"Climax relative volume",minval=1,maxval=5,step=0.1,group=C,tooltip="Suggested 1.6. Candle volume / SMA(volume,20); disabled naturally when no volume data.")
htfEnabled=input.bool(true,"Use last closed HTF trend",group=D,tooltip="Recommended ON for chart periods below the selected timeframe. Last confirmed HTF EMA reduces repainting.")
htf=input.timeframe("240","Higher timeframe",group=D,tooltip="Suggested 4H for 15m or 1H charts; choose 1D for 4H charts. Ignored when not higher than chart timeframe.")
emaLength=input.int(100,"Context EMA period",minval=20,maxval=400,group=D,tooltip="Suggested 100. HTF direction is used as a small scoring adjustment, not a veto.")
adxThreshold=input.float(27,"Strong trend ADX level",minval=10,maxval=50,group=D,tooltip="Suggested 27. Strong countertrend setups receive a penalty to reduce premature reversal calls.")
showClusters=input.bool(true,"Show multi-divergence cluster labels",group=E,tooltip="Recommended ON. A single label such as DIV 4/8 is stamped at confirmation, not on the old pivot bar.")
showSetups=input.bool(true,"Show SETUP markers",group=E,tooltip="Suggested ON. One label per side per cooldown. No historical WATCH labels.")
showConfirms=input.bool(true,"Show CONFIRM markers",group=E,tooltip="Suggested ON. Requires a recent structure / VWAP confirmation, not just a high score.")
showGuide=input.bool(true,"Show active invalidation and target",group=E,tooltip="Suggested ON. Non-trading guide levels; target uses frozen ATR at SETUP.")
showDashboard=input.bool(true,"Show compact status dashboard",group=E,tooltip="Suggested ON. Displays live cluster counts, regime and outcome research.")
showVWAP=input.bool(false,"Show session VWAP",group=E,tooltip="Suggested OFF. Enable for visual context; when volume is missing the VWAP signal is unavailable.")
maxLabels=input.int(70,"Maximum historical labels",minval=10,maxval=250,group=E,tooltip="Suggested 70. Old objects are explicitly deleted to keep the chart readable.")
bullCol=input.color(#A8D9D2,"Bullish accent",group=E,tooltip="Muted mint; applies to bullish markers and guides.")
bearCol=input.color(#E8B5C1,"Bearish accent",group=E,tooltip="Muted rose; applies to bearish markers and guides.")
divCol=input.color(#B9B4E6,"Cluster accent",group=E,tooltip="Soft lavender; distinguishes divergence research from actual confirmation.")
horizon=input.int(30,"Outcome horizon (bars)",minval=5,maxval=150,group=F,tooltip="Suggested 30. Research from confirmed candle CLOSE; evaluate first subsequent bar onward.")
rewardATR=input.float(1.5,"Outcome favorable distance (ATR)",minval=0.25,maxval=8,step=0.25,group=F,tooltip="Suggested 1.5. Research-only frozen take profit multiple; NOT an order.")
riskATR=input.float(1.0,"Outcome adverse distance (ATR)",minval=0.25,maxval=8,step=0.25,group=F,tooltip="Suggested 1.0. Research-only frozen stop distance; NOT an order.")
// Original support/resistance and previous-session value context modules.
const string G="07 | Smart Support & Resistance"
const string H="08 | Previous Session Value Map"
showSR=input.bool(true,"Show adaptive support / resistance zones",group=G,tooltip="Recommended ON. Confirmed swing zones, not all historical pivots. Broken and expired zones are removed to avoid clutter.")
srLeft=input.int(8,"S/R pivot left bars",minval=2,maxval=40,group=G,tooltip="Recommended 8. More bars identify stronger but less frequent pivots.")
srRight=input.int(8,"S/R pivot right bars",minval=2,maxval=40,group=G,tooltip="Recommended 8. A pivot is known only after this number of bars; zones are NEVER available in real time before confirmation.")
srWidth=input.float(0.25,"S/R thickness in ATR",minval=0.05,maxval=2,step=0.05,group=G,tooltip="Recommended 0.25. ATR is taken from the confirmed pivot candle.")
srMax=input.int(24,"Maximum live S/R zones",minval=2,maxval=100,group=G,tooltip="Recommended 24. Prunes oldest zones; no accumulation of stale rectangles.")
srMaxAge=input.int(450,"Expire S/R after N bars",minval=20,maxval=2000,group=G,tooltip="Recommended 450. Prevents very old untouched pivots from dominating the chart.")
srMerge=input.float(0.55,"Merge nearby zones (ATR)",minval=0.05,maxval=3,step=0.05,group=G,tooltip="Recommended 0.55. Avoid creating multiple same-side zones with nearly identical midpoints.")
srBullColor=input.color(#5D9FE6,"Support zone color",group=G,tooltip="Saturated pastel blue. Support zones are independent from divergence colors.")
srBearColor=input.color(#E27884,"Resistance zone color",group=G,tooltip="Soft red. Adjust separately from bear signal labels.")
srOpacity=input.int(84,"S/R fill transparency",minval=50,maxval=100,group=G,tooltip="Recommended 84. Higher = more transparent, cleaner chart.")
showValue=input.bool(false,"Show previous-session value levels",group=H,tooltip="Recommended OFF initially. Enable when analyzing intraday charts; previous day POC/VAH/VAL are estimated from chart bars and chart volume, NOT exchange tick-by-tick volume profile.")
valueRows=input.int(32,"Approximate profile price bins",minval=10,maxval=80,group=H,tooltip="Recommended 32. Chart bars are allocated to bins by typical price. This approximation is NOT an exact footprint volume profile.")
valueAreaPct=input.float(70,"Previous-session value area (%)",minval=50,maxval=90,step=5,group=H,tooltip="Recommended 70. Expand from the highest-volume bin until this fraction of prior session bar volume is included.")
valueMaxBars=input.int(450,"Maximum bars per session",minval=50,maxval=1500,group=H,tooltip="Recommended 450. Caps profile computation cost. On 1m charts this may cover only part of the day.")
valueConfluenceATR=input.float(0.3,"Value / S/R proximity (ATR)",minval=0.05,maxval=2,step=0.05,group=H,tooltip="Recommended 0.30. Small score bonus only when prices are near a prior-day value level or active S/R zone.")
valueScoreBonus=input.int(5,"Context score bonus",minval=0,maxval=10,group=H,tooltip="Recommended 5. Additional independent contextual evidence. Value levels are used only if previous-session map is enabled.")
valueColor=input.color(#B2A0D7,"Value level color",group=H,tooltip="Pastel purple, visually distinct from supports and resistances.")
float atr=ta.atr(14)
float rsi=ta.rsi(close,14)
float macdFast=ta.ema(close,12)
float macdSlow=ta.ema(close,26)
float macdLine=macdFast-macdSlow
float macdHist=macdLine-ta.ema(macdLine,9)
float cci=ta.cci(hlc3,20)
float lowest14=ta.lowest(low,14)
float highest14=ta.highest(high,14)
float stoch=highest14>lowest14 ? 100*(close-lowest14)/(highest14-lowest14) : 50
float roc=not na(close[12]) and close[12]!=0 ? 100*(close/close[12]-1) : na
float posFlow=hlc3>hlc3[1] ? hlc3*volume : 0
float negFlow=hlc3<hlc3[1] ? hlc3*volume : 0
float posMF=ta.sma(posFlow,14), negMF=ta.sma(negFlow,14)
float mfi=negMF>0 ? 100-100/(1+posMF/negMF) : posMF>0 ? 100 : 50
float obv=ta.cum(close>close[1]?nz(volume):close<close[1]?-nz(volume):0)
float mfmult=high>low ? ((close-low)-(high-close))/(high-low) : 0
float avgVol=ta.sma(volume,20)
float cmf=avgVol>0 ? ta.sma(mfmult*volume,20)/avgVol : na
float vwap=ta.vwap(hlc3)
float ema=ta.ema(close,emaLength)
[diPlus,diMinus,adx]=ta.dmi(14,14)
bool validHTF=htfEnabled and timeframe.in_seconds(htf)>timeframe.in_seconds(timeframe.period)
float htfClose=request.security(syminfo.tickerid,htf,close[1],lookahead=barmerge.lookahead_on)
float htfEma=request.security(syminfo.tickerid,htf,ta.ema(close,emaLength)[1],lookahead=barmerge.lookahead_on)
bool biasBull=not validHTF or htfClose>htfEma
bool biasBear=not validHTF or htfClose<htfEma
bool volOK=not na(volume) and avgVol>0
float ph=ta.pivothigh(high,swing,swing), pl=ta.pivotlow(low,swing,swing)
// Compare all 8 oscillators AT THE SAME two PRICE pivots (not asynchronous oscillator pivots).
var float prevHigh=na
var float prevLow=na
var float prevHighATR=na
var float prevLowATR=na
var array<float> previousHighOsc=array.new_float(8,na)
var array<float> previousLowOsc=array.new_float(8,na)
var int bullCount=0
var int bearCount=0
var int bullRegular=0
var int bearRegular=0
var int bullHidden=0
var int bearHidden=0
var int bullClusterBar=na
var int bearClusterBar=na
var array<label> marks=array.new<label>()
array<float> osc=array.from(rsi[swing],macdHist[swing],cci[swing],stoch[swing],mfi[swing],obv[swing],roc[swing],cmf[swing])
array<bool> active=array.from(useRSI,useMACD,useCCI,useStoch,useMFI and volOK,useOBV and volOK,useROC,useCMF and volOK)
if barstate.isconfirmed
if not na(pl)
int reg=0, hid=0
if not na(prevLow) and math.abs(pl-prevLow)>=minMoveATR*nz(atr[swing],0)
for i=0 to 7
float cur=array.get(osc,i), old=array.get(previousLowOsc,i)
if array.get(active,i) and not na(cur) and not na(old)
bool regular=pl<prevLow and cur>old
bool hidden=pl>prevLow and cur<old
if regular and divMode!="Hidden"
reg+=1
if hidden and divMode!="Regular"
hid+=1
bullCount:=math.max(reg,hid)
bullRegular:=reg
bullHidden:=hid
if bullCount>=minCluster
bullClusterBar:=bar_index
if showClusters
label lab=label.new(bar_index,low,"DIV "+str.tostring(bullCount)+"/8 "+(reg>=hid?"R":"H")+" ↑",style=label.style_label_up,color=color.new(divCol,24),textcolor=#35344D,size=size.tiny)
array.push(marks,lab)
prevLow:=pl
prevLowATR:=atr[swing]
for i=0 to 7
array.set(previousLowOsc,i,array.get(osc,i))
if not na(ph)
int reg=0, hid=0
if not na(prevHigh) and math.abs(ph-prevHigh)>=minMoveATR*nz(atr[swing],0)
for i=0 to 7
float cur=array.get(osc,i), old=array.get(previousHighOsc,i)
if array.get(active,i) and not na(cur) and not na(old)
bool regular=ph>prevHigh and cur<old
bool hidden=ph<prevHigh and cur>old
if regular and divMode!="Hidden"
reg+=1
if hidden and divMode!="Regular"
hid+=1
bearCount:=math.max(reg,hid)
bearRegular:=reg
bearHidden:=hid
if bearCount>=minCluster
bearClusterBar:=bar_index
if showClusters
label lab=label.new(bar_index,high,"DIV "+str.tostring(bearCount)+"/8 "+(reg>=hid?"R":"H")+" ↓",style=label.style_label_down,color=color.new(divCol,24),textcolor=#35344D,size=size.tiny)
array.push(marks,lab)
prevHigh:=ph
prevHighATR:=atr[swing]
for i=0 to 7
array.set(previousHighOsc,i,array.get(osc,i))
bool bullCluster=not na(bullClusterBar) and bar_index-bullClusterBar<=clusterLife
bool bearCluster=not na(bearClusterBar) and bar_index-bearClusterBar<=clusterLife
float candleRange=high-low
float body=math.abs(close-open)
bool bullPin=candleRange>0 and (math.min(open,close)-low)/candleRange>=wickRatio and body/candleRange<0.42
bool bearPin=candleRange>0 and (high-math.max(open,close))/candleRange>=wickRatio and body/candleRange<0.42
bool bullEngulf=close>open and close[1]<open[1] and close>=open[1] and open<=close[1]
bool bearEngulf=close<open and close[1]>open[1] and close<=open[1] and open>=close[1]
bool bullStar=close>open and close[2]<open[2] and math.abs(close[1]-open[1])<math.abs(close[2]-open[2])*0.5 and close>(open[2]+close[2])/2
bool bearStar=close<open and close[2]>open[2] and math.abs(close[1]-open[1])<math.abs(close[2]-open[2])*0.5 and close<(open[2]+close[2])/2
bool bullSweep=low<ta.lowest(low[1],sweepLen) and close>ta.lowest(low[1],sweepLen)
bool bearSweep=high>ta.highest(high[1],sweepLen) and close<ta.highest(high[1],sweepLen)
bool volClimax=volOK and volume>=avgVol*volumeMultiplier
bool bullAbsorb=volClimax and (bullPin or (close>open and low<low[1]))
bool bearAbsorb=volClimax and (bearPin or (close<open and high>high[1]))
var int bpAt=na
var int spAt=na
var int bsAt=na
var int ssAt=na
var int baAt=na
var int saAt=na
if barstate.isconfirmed
if bullPin or bullEngulf or bullStar
bpAt:=bar_index
if bearPin or bearEngulf or bearStar
spAt:=bar_index
if bullSweep
bsAt:=bar_index
if bearSweep
ssAt:=bar_index
if bullAbsorb
baAt:=bar_index
if bearAbsorb
saAt:=bar_index
bool recentBullPattern=not na(bpAt) and bar_index-bpAt<=patternBars
bool recentBearPattern=not na(spAt) and bar_index-spAt<=patternBars
bool recentBullSweep=not na(bsAt) and bar_index-bsAt<=patternBars
bool recentBearSweep=not na(ssAt) and bar_index-ssAt<=patternBars
bool recentBullAbsorb=not na(baAt) and bar_index-baAt<=patternBars
bool recentBearAbsorb=not na(saAt) and bar_index-saAt<=patternBars
float priorHi=ta.highest(high[1],structureLen)
float priorLo=ta.lowest(low[1],structureLen)
bool shiftBull=close>priorHi and close[1]<=priorHi[1]
bool shiftBear=close<priorLo and close[1]>=priorLo[1]
bool reclaimBull=not na(vwap) and ta.crossover(close,vwap)
bool reclaimBear=not na(vwap) and ta.crossunder(close,vwap)
var int bullTriggerAt=na
var int bearTriggerAt=na
if barstate.isconfirmed
if shiftBull or reclaimBull
bullTriggerAt:=bar_index
if shiftBear or reclaimBear
bearTriggerAt:=bar_index
bool bullTrigger=not na(bullTriggerAt) and bar_index-bullTriggerAt<=triggerLife
bool bearTrigger=not na(bearTriggerAt) and bar_index-bearTriggerAt<=triggerLife
// Zone engine: track active, confirmed levels only. Avoid historical clutter and duplicate prices.
type SRZone
bool support
float upper
float lower
int created
box rect
var array<SRZone> srZones=array.new<SRZone>()
float pivotR=ta.pivothigh(high,srLeft,srRight)
float pivotS=ta.pivotlow(low,srLeft,srRight)
if barstate.isconfirmed and showSR
// First evaluate existing zones; new zones never get retroactively tested on confirmation bar.
if array.size(srZones)>0
for i=array.size(srZones)-1 to 0
SRZone z=array.get(srZones,i)
bool broken=z.support?close<z.lower:close>z.upper
bool stale=bar_index-z.created>srMaxAge
if broken or stale
box.delete(z.rect)
array.remove(srZones,i)
else
box.set_right(z.rect,bar_index+6)
if not na(pivotS) and not na(atr[srRight])
float zzLow=pivotS
float zzHigh=pivotS+math.max(atr[srRight]*srWidth,syminfo.mintick)
bool duplicate=false
if array.size(srZones)>0
for j=0 to array.size(srZones)-1
SRZone z=array.get(srZones,j)
if z.support and math.abs((zzLow+zzHigh-z.lower-z.upper)*0.5)<=atr*srMerge
duplicate:=true
break
// Pivot must still be unbroken at the moment it becomes confirmed.
bool valid=true
for j=0 to srRight-1
if close[j]<zzLow
valid:=false
break
if not duplicate and valid
box b=box.new(bar_index-srRight,zzHigh,bar_index+6,zzLow,border_color=color.new(srBullColor,35),bgcolor=color.new(srBullColor,srOpacity))
array.push(srZones,SRZone.new(true,zzHigh,zzLow,bar_index,b))
if not na(pivotR) and not na(atr[srRight])
float zzHigh=pivotR
float zzLow=pivotR-math.max(atr[srRight]*srWidth,syminfo.mintick)
bool duplicate=false
if array.size(srZones)>0
for j=0 to array.size(srZones)-1
SRZone z=array.get(srZones,j)
if not z.support and math.abs((zzLow+zzHigh-z.lower-z.upper)*0.5)<=atr*srMerge
duplicate:=true
break
bool valid=true
for j=0 to srRight-1
if close[j]>zzHigh
valid:=false
break
if not duplicate and valid
box b=box.new(bar_index-srRight,zzHigh,bar_index+6,zzLow,border_color=color.new(srBearColor,35),bgcolor=color.new(srBearColor,srOpacity))
array.push(srZones,SRZone.new(false,zzHigh,zzLow,bar_index,b))
while array.size(srZones)>srMax
SRZone old=array.shift(srZones)
box.delete(old.rect)
// Previous DAY profile approximation: each completed chart bar assigns its own volume
// to ONE typical-price bin. It does NOT claim tick-level distribution or external futures volume.
var array<float> vpPrice=array.new_float()
var array<float> vpVol=array.new_float()
var float dayPoc=na
var float dayVah=na
var float dayVal=na
bool dayChange=timeframe.change("D")
if barstate.isconfirmed and showValue
if dayChange
int count=array.size(vpPrice)
if count>=3
float lo=array.min(vpPrice)
float hi=array.max(vpPrice)
float step=math.max((hi-lo)/valueRows,syminfo.mintick)
array<float> bins=array.new_float(valueRows,0.0)
for j=0 to count-1
int idx=int(math.max(0,math.min(valueRows-1,math.floor((array.get(vpPrice,j)-lo)/step))))
array.set(bins,idx,array.get(bins,idx)+array.get(vpVol,j))
float allVol=array.sum(bins)
int peak=array.indexof(bins,array.max(bins))
int lower=peak
int upper=peak
float used=array.get(bins,peak)
while used<allVol*valueAreaPct/100.0 and (lower>0 or upper<valueRows-1)
float lVol=lower>0?array.get(bins,lower-1):-1.0
float uVol=upper<valueRows-1?array.get(bins,upper+1):-1.0
if uVol>=lVol and upper<valueRows-1
upper+=1
used+=array.get(bins,upper)
else if lower>0
lower-=1
used+=array.get(bins,lower)
else
break
dayPoc:=lo+(peak+0.5)*step
dayVah:=lo+(upper+1)*step
dayVal:=lo+lower*step
array.clear(vpPrice)
array.clear(vpVol)
if array.size(vpPrice)<valueMaxBars and not na(volume) and volume>0
array.push(vpPrice,hlc3)
array.push(vpVol,volume)
bool nearSupport=false
bool nearResistance=false
if showSR and array.size(srZones)>0 and not na(atr)
for j=0 to array.size(srZones)-1
SRZone z=array.get(srZones,j)
float mid=(z.upper+z.lower)*0.5
if math.abs(close-mid)<=atr*valueConfluenceATR
if z.support
nearSupport:=true
else
nearResistance:=true
bool nearValue=showValue and not na(atr) and ((not na(dayPoc) and math.abs(close-dayPoc)<atr*valueConfluenceATR) or (not na(dayVah) and math.abs(close-dayVah)<atr*valueConfluenceATR) or (not na(dayVal) and math.abs(close-dayVal)<atr*valueConfluenceATR))
plot(showValue?dayPoc:na,"Prior day POC (approx)",color=valueColor,linewidth=2,style=plot.style_stepline)
plot(showValue?dayVah:na,"Prior day VAH (approx)",color=color.new(valueColor,35),style=plot.style_stepline)
plot(showValue?dayVal:na,"Prior day VAL (approx)",color=color.new(valueColor,35),style=plot.style_stepline)
// One contribution per evidence FAMILY; eight correlated oscillators cannot dominate the score.
float bullScore=(bullCluster?math.min(35,10+5*bullCount):0)+(recentBullSweep?20:0)+(recentBullPattern?15:0)+(recentBullAbsorb?10:0)+(bullTrigger?20:0)
float bearScore=(bearCluster?math.min(35,10+5*bearCount):0)+(recentBearSweep?20:0)+(recentBearPattern?15:0)+(recentBearAbsorb?10:0)+(bearTrigger?20:0)
bullScore:=math.max(0,math.min(100,bullScore+(nearSupport or nearValue?valueScoreBonus:0)-(adx>=adxThreshold and close<ema?10:0)-(not biasBull?5:0)-(bullCluster and bullHidden>bullRegular?10:0)))
bearScore:=math.max(0,math.min(100,bearScore+(nearResistance or nearValue?valueScoreBonus:0)-(adx>=adxThreshold and close>ema?10:0)-(not biasBear?5:0)-(bearCluster and bearHidden>bearRegular?10:0)))
// Candidate is frozen at signal close; a confirmation is not placed retroactively.
var int candidateDir=0
var int candidateBar=na
var int candidateCluster=0
var int lastBull=na
var int lastBear=na
var float candidateRisk=na
var float candidateTarget=na
var line riskLine=na
var line goalLine=na
bool setupB=false
bool setupS=false
bool confirmedB=false
bool confirmedS=false
var array<int> evalBar=array.new_int()
var array<int> evalDir=array.new_int()
var array<float> evalTarget=array.new_float()
var array<float> evalStop=array.new_float()
var int wins=0
var int losses=0
var int ambiguous=0
var int expired=0
if barstate.isconfirmed and not na(atr)
if array.size(evalBar)>0
for i=array.size(evalBar)-1 to 0
int age=bar_index-array.get(evalBar,i)
if age>0
int side=array.get(evalDir,i)
bool hitWin=side==1?high>=array.get(evalTarget,i):low<=array.get(evalTarget,i)
bool hitLoss=side==1?low<=array.get(evalStop,i):high>=array.get(evalStop,i)
if hitWin or hitLoss or age>=horizon
if hitWin and hitLoss
ambiguous+=1
else if hitWin
wins+=1
else if hitLoss
losses+=1
else
expired+=1
array.remove(evalBar,i)
array.remove(evalDir,i)
array.remove(evalTarget,i)
array.remove(evalStop,i)
if candidateDir!=0 and (bar_index-candidateBar>confirmWindow or (candidateDir==1 and close<candidateRisk) or (candidateDir==-1 and close>candidateRisk))
candidateDir:=0
line.delete(riskLine)
line.delete(goalLine)
riskLine:=na
goalLine:=na
bool eligibleBull=bullScore>=setupScore and (not requireCluster or bullCluster) and (na(lastBull) or bar_index-lastBull>cooldown)
bool eligibleBear=bearScore>=setupScore and (not requireCluster or bearCluster) and (na(lastBear) or bar_index-lastBear>cooldown)
if candidateDir==0 and (eligibleBull or eligibleBear)
candidateDir:=eligibleBull and (not eligibleBear or bullScore>=bearScore)?1:-1
candidateBar:=bar_index
candidateCluster:=candidateDir==1?bullCount:bearCount
candidateRisk:=candidateDir==1?low-atr*0.35:high+atr*0.35
candidateTarget:=close+candidateDir*atr*rewardATR
setupB:=candidateDir==1
setupS:=candidateDir==-1
if setupB
lastBull:=bar_index
else
lastBear:=bar_index
if showSetups
label lab=label.new(bar_index,candidateDir==1?low:high,"SETUP "+str.tostring(int(candidateDir==1?bullScore:bearScore))+" | DIV "+str.tostring(candidateCluster),style=candidateDir==1?label.style_label_up:label.style_label_down,color=candidateDir==1?bullCol:bearCol,textcolor=#29353F,size=size.tiny)
array.push(marks,lab)
if showGuide
line.delete(riskLine)
line.delete(goalLine)
riskLine:=line.new(bar_index,candidateRisk,bar_index+confirmWindow,candidateRisk,color=color.new(color.gray,35),style=line.style_dotted)
goalLine:=line.new(bar_index,candidateTarget,bar_index+confirmWindow,candidateTarget,color=color.new(candidateDir==1?bullCol:bearCol,25),style=line.style_dashed)
// Confirm only on a NEW directional event, after SETUP creation, before expiry.
if candidateDir!=0 and bar_index>candidateBar and bar_index-candidateBar<=confirmWindow
bool directionTrigger=candidateDir==1?(shiftBull or reclaimBull):(shiftBear or reclaimBear)
float score=candidateDir==1?bullScore:bearScore
if directionTrigger and score>=confirmScore
confirmedB:=candidateDir==1
confirmedS:=candidateDir==-1
if showConfirms
label lab=label.new(bar_index,candidateDir==1?low:high,"CONFIRM "+str.tostring(int(score))+" | DIV "+str.tostring(candidateCluster),style=candidateDir==1?label.style_label_up:label.style_label_down,color=candidateDir==1?bullCol:bearCol,textcolor=#1B2D37,size=size.small)
array.push(marks,lab)
array.push(evalBar,bar_index)
array.push(evalDir,candidateDir)
array.push(evalTarget,close+candidateDir*rewardATR*atr)
array.push(evalStop,close-candidateDir*riskATR*atr)
candidateDir:=0
line.delete(riskLine)
line.delete(goalLine)
riskLine:=na
goalLine:=na
while array.size(marks)>maxLabels
label.delete(array.shift(marks))
plot(showVWAP?vwap:na,"Session VWAP",color=color.new(divCol,5))
alertcondition(setupB,"Bullish SETUP","Reversal Radar X: bullish setup {{ticker}} {{interval}}")
alertcondition(setupS,"Bearish SETUP","Reversal Radar X: bearish setup {{ticker}} {{interval}}")
alertcondition(confirmedB,"Bullish CONFIRM","Reversal Radar X: bullish confirmed {{ticker}} {{interval}}")
alertcondition(confirmedS,"Bearish CONFIRM","Reversal Radar X: bearish confirmed {{ticker}} {{interval}}")
var table dash=table.new(position.top_right,2,6,border_width=1)
if barstate.islast and showDashboard
int total=wins+losses
table.cell(dash,0,0,"REVERSAL RADAR X | jjart",bgcolor=#313B4C,text_color=color.white)
table.cell(dash,1,0,"10-IN-1 FUSION",bgcolor=#313B4C,text_color=color.white)
table.cell(dash,0,1,"Bull / Bear score")
table.cell(dash,1,1,str.tostring(int(bullScore))+" / "+str.tostring(int(bearScore)))
table.cell(dash,0,2,"Bull / Bear cluster")
table.cell(dash,1,2,str.tostring(bullCluster?bullCount:0)+" / "+str.tostring(bearCluster?bearCount:0))
table.cell(dash,0,3,"Current candidate")
table.cell(dash,1,3,candidateDir==1?"BULL":candidateDir==-1?"BEAR":"NONE")
table.cell(dash,0,4,"1st touch W/L")
table.cell(dash,1,4,str.tostring(wins)+" / "+str.tostring(losses))
table.cell(dash,0,5,"Win% / Ambig / Timeout")
table.cell(dash,1,5,(total>0?str.tostring(100.0*wins/total,"#.0")+"%":"n/a")+" / "+str.tostring(ambiguous)+" / "+str.tostring(expired))