本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Source Code Form is subject to the Mozilla Public License, v. 2.0.
// https://mozilla.org/MPL/2.0/
// Qubit Protocol. Context-aware candle rules from Qubit candle_patterns v6.
// Pattern strength describes the formation, not the probability of a winning trade.
//@version=6
indicator("QubitCandleDetector", shorttitle="QubitCandleDetector", overlay=true, behind_chart=false, max_bars_back=100, max_labels_count=200, dynamic_requests=true)
bool showPanel = input.bool(true, "Show multi-timeframe panel", group="Display")
bool showLabels = input.bool(true, "Label completed chart patterns", group="Display")
bool showNeutral = input.bool(false, "Show neutral chart labels", group="Display")
float minScore = input.float(40, "Minimum chart-label / alert strength", minval=0, maxval=100, group="Display", tooltip="A formation score, not a win probability. Panel always shows the strongest current pattern, regardless of this filter.")
bool tintBars = input.bool(true, "Tint completed pattern candles", group="Display")
string alertDirection = input.string("Bullish and bearish", "Chart alerts", options=["Bullish and bearish", "Bullish only", "Bearish only", "All patterns"], group="Alerts")
type Candle
int code = 0
string name = "No pattern"
string names = ""
int side = 0
float score = 0
int count = 0
float bodyRatio = na
float bodyPct = na
int bodySide = 0
int closedAt = na
float hi = na
float lo = na
bool ready = false
f_body(int k) => math.abs(close[k]-open[k])
f_span(int k) => high[k]-low[k]
f_bottom(int k) => math.min(open[k],close[k])
f_top(int k) => math.max(open[k],close[k])
f_lower(int k) => f_bottom(k)-low[k]
f_upper(int k) => high[k]-f_top(k)
f_sign(int k) => close[k]>open[k] ? 1 : close[k]<open[k] ? -1 : 0
f_share(int k) => f_span(k)>0 ? f_body(k)/f_span(k) : 0.0
f_clamp(float x) => math.max(0.0,math.min(1.0,x))
f_eps(float x) => x>0 ? 16.0*math.pow(2.0,math.floor(math.log(x)/math.log(2.0))-52.0) : 0.0
f_avg(int start, int length, int what) =>
float total=0.0
for j=start to start+length-1
total += what==0 ? close[j] : what==1 ? f_body(j) : f_span(j)
total/length
f_high(int start,int length) =>
float value=high[start]
for j=start to start+length-1
value:=math.max(value,high[j])
value
f_low(int start,int length) =>
float value=low[start]
for j=start to start+length-1
value:=math.min(value,low[j])
value
f_trend(int start) =>
float avg=f_avg(start,20,0), old=f_avg(start+5,20,0), eps=f_eps(f_high(start,25))
close[start]>avg+eps and avg>old+eps ? 1 : close[start]<avg-eps and avg<old-eps ? -1 : 0
// Causal context BEFORE the whole formation. kind: 0 single, 1 engulf/harami,
// 2 star (middle body at extreme), 3 soldiers/crows (first open at extreme).
f_placement(int s,int n,int kind,int side) =>
int first=s+n-1, prior=s+n
float pl=f_low(prior,5), ph=f_high(prior,5), ar=f_avg(prior,5,2)
float eps=f_eps(math.max(ph,f_high(s,n)))
float slope=(-2*close[prior+4]-close[prior+3]+close[prior+1]+2*close[prior])/10
float recent=close[prior]-close[prior+2]
bool leg=side==1 ? slope < -eps and recent < -eps : slope > eps and recent > eps
float anchor=kind==0 ? (open[first]+close[first])/2 : kind==2 ? (open[first-1]+close[first-1])/2 : kind==3 ? open[first] : close[first]
float extreme=side==1 ? (kind==2 ? math.min(low[first],low[first-1]) : low[first]) : (kind==2 ? math.max(high[first],high[first-1]) : high[first])
bool location=side==1 ? anchor<=pl+(ph-pl)/3+eps and extreme<=pl+.25*ar+eps : anchor>=ph-(ph-pl)/3-eps and extreme>=ph-.25*ar-eps
float gap=open[first]-close[prior]
bool opening=side==1 ? gap<=.1*ar+eps : gap>=-.1*ar-eps
bool extends=side==1 ? close[first]<close[prior]-eps : close[first]>close[prior]+eps
ph>pl and ar>0 and leg and location and (kind==0 or kind==3 ? opening : extends)
f_hammer(int s,bool lower) =>
float b=f_body(s),r=f_span(s),eps=f_eps(high[s])
float main=lower ? f_lower(s) : f_upper(s), other=lower ? f_upper(s) : f_lower(s)
r>0 and b>.10*r+eps and b<=.35*r+eps and main>=2*b-eps and other<=math.min(.25*b,.05*r)+eps and b+other<=r/3+eps
f_add(Candle out,int code,string name,int side,int n,float base,float geometry,float size,float denominator,int trend) =>
float ratio=denominator>0 ? size/denominator : 0.0
float score=math.round(math.min(100,base+math.round(25*f_clamp(geometry),2)+math.round(30*f_clamp(ratio/3),2)+(side!=0 and trend!=0 ? 10 : 0)),1)
out.names += (str.length(out.names)>0 ? "\n" : "")+name+" · "+str.tostring(score,"#.0")+"/100"
if out.code==0 or score>out.score or (score==out.score and (n>out.count or (n==out.count and code<out.code)))
out.code:=code
out.name:=name
out.side:=side
out.score:=score
out.count:=n
out
f_detect(int s) =>
Candle out=Candle.new()
out.closedAt:=time_close[s]
out.hi:=high[s]
out.lo:=low[s]
out.bodySide:=f_sign(s)
float avg1=f_avg(s+1,20,1), range1=f_avg(s+1,20,2)
out.bodyRatio:=avg1>0 ? f_body(s)/avg1 : na
out.bodyPct:=open[s]>0 ? (close[s]/open[s]-1)*100 : na
bool valid=not na(close[s+27])
int interval=int(timeframe.in_seconds()*1000)
for j=s to s+27
int duration=time_close[j]-time[j]
// TradingView restarts 2D/3D buckets at the new calendar year, so
// the final bucket can be shorter. Native close/open continuity
// distinguishes this from a missing exchange candle.
bool yearEnd=timeframe.isdaily and (timeframe.multiplier==2 or timeframe.multiplier==3) and year(time_close[j])>year(time[j]) and duration>=86400000 and duration<interval
valid:=valid and low[j]>0 and low[j]<=f_bottom(j) and f_top(j)<=high[j] and (math.abs(duration-interval)<=1000 or yearEnd)
if j<s+27
valid:=valid and math.abs(time[j]-time_close[j+1])<=1000
out.ready:=valid
if valid and f_span(s)>0 and range1>0
float eps=f_eps(f_high(s,28)), b=f_body(s), r=f_span(s), lower=f_lower(s), upper=f_upper(s)
int trend1=f_trend(s+1)
bool doji=b<=.10*r+eps
if doji
if lower>=.70*r-eps and upper<=.10*r+eps
int side=trend1==-1 and f_placement(s,1,0,1) ? 1 : 0
f_add(out,8,"Dragonfly Doji",side,1,15,lower/r,lower,range1,trend1)
else if upper>=.70*r-eps and lower<=.10*r+eps
int side=trend1==1 and f_placement(s,1,0,-1) ? -1 : 0
f_add(out,11,"Gravestone Doji",side,1,15,upper/r,upper,range1,trend1)
else if math.min(upper,lower)>=.35*r-eps and r>=1.5*range1-eps
f_add(out,15,"Long-legged Doji",0,1,15,1-f_share(s),r,range1,trend1)
else
f_add(out,7,"Doji",0,1,10,1-f_share(s)/.10,r,range1,trend1)
else if b<=.35*r+eps
if f_hammer(s,true) and trend1!=0
int side=-trend1
if f_placement(s,1,0,side)
f_add(out,side==1 ? 12 : 13,side==1 ? "Hammer" : "Hanging Man",side,1,20,lower/r,lower,range1,trend1)
else if f_hammer(s,false) and trend1!=0
int side=-trend1
if f_placement(s,1,0,side)
f_add(out,side==1 ? 14 : 18,side==1 ? "Inverted Hammer" : "Shooting Star",side,1,20,upper/r,upper,range1,trend1)
else if math.min(upper,lower)>=b-eps
f_add(out,19,"Spinning Top",0,1,10,1-f_share(s),r,range1,trend1)
if b>=.90*r-eps and math.max(upper,lower)<=.05*r+eps and b>=avg1-eps and avg1>0
int side=f_sign(s)
f_add(out,side==1 ? 6 : 3,side==1 ? "Bullish Marubozu" : "Bearish Marubozu",side,1,20,f_share(s),b,avg1,trend1)
int p=s+1, a=s+2, m=s+1
float avg2=f_avg(s+2,20,1), avg3=f_avg(s+3,20,1)
int trend2=f_trend(s+2), trend3=f_trend(s+3)
for side in array.from(1,-1)
bool bull=side==1
if trend2==-side and avg2>0 and f_sign(p)==-side and f_sign(s)==side and f_body(p)>.10*f_span(p)+eps and b>.10*r+eps
if f_bottom(s)<=f_bottom(p)+eps and f_top(s)>=f_top(p)-eps and b>f_body(p)+eps and b>=avg2-eps
if f_placement(s,2,1,side)
f_add(out,bull ? 4 : 1,bull ? "Bullish Engulfing" : "Bearish Engulfing",side,2,30,.5*f_clamp((b/f_body(p)-1)/2)+.5*f_share(s),b,avg2,trend2)
else if f_body(p)>=avg2-eps and b<=.5*f_body(p)+eps and f_bottom(s)>f_bottom(p)+eps and f_top(s)<f_top(p)-eps
if f_placement(s,2,1,side)
f_add(out,bull ? 5 : 2,bull ? "Bullish Harami" : "Bearish Harami",side,2,25,1-b/f_body(p),f_body(p),avg2,trend2)
if trend3==-side and avg3>0
float half=(open[a]+close[a])/2
bool reclaim=bull ? close[s]>half+eps : close[s]<half-eps
bool location=bull ? f_top(m)<=f_bottom(a)+eps and f_bottom(s)>=f_bottom(m)-eps : f_bottom(m)>=f_top(a)-eps and f_top(s)<=f_top(m)+eps
bool star=f_sign(a)==-side and f_sign(s)==side and f_body(a)>=avg3-eps and f_body(a)>=.60*f_span(a)-eps and f_span(m)>0 and f_body(m)<=math.min(.3*f_body(a),.5*avg3)+eps and b>=math.max(avg3,.5*f_body(a))-eps and b>=.60*r-eps and reclaim and location
if star and f_placement(s,3,2,side)
bool gaps=bull ? f_top(m)<f_bottom(a)-eps and f_bottom(s)>f_top(m)+eps : f_bottom(m)>f_top(a)+eps and f_top(s)<f_bottom(m)-eps
bool middleDoji=f_body(m)<=.10*f_span(m)+eps
string name=(bull ? "Morning" : "Evening")+(middleDoji ? " Doji Star" : " Star")+(gaps ? " (gapped)" : " (24/7)")
f_add(out,bull ? (middleDoji ? 16 : 17) : (middleDoji ? 9 : 10),name,side,3,35,.5*(1-f_body(m)/f_body(a))+.5*f_clamp(math.abs(close[s]-close[a])/f_body(a)),b,avg3,trend3)
bool soldiers=true
for j=s to s+2
soldiers:=soldiers and f_sign(j)==side and f_body(j)>=.60*f_span(j)-eps and f_body(j)>=avg3-eps and (bull ? f_upper(j) : f_lower(j))<=.20*f_span(j)+eps
bool opens=open[m]>=f_bottom(a)-eps and open[m]<=f_top(a)+eps and open[s]>=f_bottom(m)-eps and open[s]<=f_top(m)+eps
bool advances=bull ? close[a]<close[m]-eps and close[m]<close[s]-eps : close[a]>close[m]+eps and close[m]>close[s]+eps
if soldiers and opens and advances and f_placement(s,3,3,side)
f_add(out,bull ? 21 : 20,bull ? "Three White Soldiers" : "Three Black Crows",side,3,35,(f_share(a)+f_share(m)+f_share(s))/3,(f_body(a)+f_body(m)+b)/3,avg3,trend3)
out
f_grade(float score) => score<40 ? "Weak" : score<60 ? "Moderate" : score<80 ? "Strong" : "Very strong"
f_color(int side) => side==1 ? #42D3A6 : side==-1 ? #FF7285 : #A4AEC5
f_meter(float ratio) =>
int filled=int(math.round(math.min(3.0,nz(ratio))/3*8))
str.repeat("▰",filled)+str.repeat("▱",8-filled)
if not chart.is_standard
runtime.error("Use standard time-based candles. Synthetic candles change pattern geometry.")
Candle current=f_detect(0)
Candle previous=f_detect(1)
Candle completed=barstate.isconfirmed ? current : previous
bool chartPattern=barstate.isconfirmed and current.ready and current.code!=0 and current.score>=minScore
bool allowed=current.side==1 ? alertDirection!="Bearish only" : current.side==-1 ? alertDirection!="Bullish only" : alertDirection=="All patterns"
if showLabels and chartPattern and (showNeutral or current.side!=0)
label.new(bar_index,current.side==1 ? low : high,current.name+"\n"+str.tostring(current.score,"#.0")+" · "+f_grade(current.score),style=current.side==1 ? label.style_label_up : label.style_label_down,color=color.new(f_color(current.side),15),textcolor=#101925,size=size.tiny,tooltip=current.names+"\nBody: "+str.tostring(current.bodyRatio,"#.00")+"× preceding 20 bodies\nConfirmed at "+str.format_time(current.closedAt,"yyyy-MM-dd HH:mm","UTC")+" UTC\nStrength is not a win probability.")
barcolor(tintBars and chartPattern ? f_color(current.side) : na)
if chartPattern and allowed
alert("QubitCandleDetector | "+syminfo.tickerid+" | "+timeframe.period+" | "+current.name+" | strength "+str.tostring(current.score,"#.0")+"/100 | completed "+str.format_time(current.closedAt,"yyyy-MM-dd HH:mm","UTC")+" UTC",alert.freq_once_per_bar_close)
alertcondition(chartPattern and current.side==1,"Bullish completed pattern","QubitCandleDetector: bullish completed pattern on {{exchange}}:{{ticker}} {{interval}}.")
alertcondition(chartPattern and current.side==-1,"Bearish completed pattern","QubitCandleDetector: bearish completed pattern on {{exchange}}:{{ticker}} {{interval}}.")
plot(barstate.isconfirmed ? current.code : na,"Pattern code",display=display.data_window)
plot(barstate.isconfirmed ? current.score : na,"Pattern strength",display=display.data_window)
plot(barstate.isconfirmed ? current.bodyRatio : na,"Body / prior 20 average",display=display.data_window)
plot(barstate.isconfirmed ? current.side : na,"Pattern direction",display=display.data_window)
var frames=array.from("15","30","60","120","240","480","720","1D","2D","3D","1W")
var frameNames=array.from("15m","30m","1h","2h","4h","8h","12h","1D","2D","3D","1W")
var cache=array.new<Candle>(11)
var panel=table.new(position.top_right,5,14,bgcolor=#101C2D,frame_color=#2F4A64,frame_width=1,border_width=1,border_color=#1D3046)
// Requests are evaluated on every bar. Higher TFs explicitly offset every
// input by one source bar with lookahead_on; lower TFs use completed intrabars.
for i=0 to 10
string tf=array.get(frames,i)
Candle data=na
if timeframe.in_seconds(tf)>timeframe.in_seconds()
data:=request.security(syminfo.tickerid,tf,f_detect(1),lookahead=barmerge.lookahead_on,calc_bars_count=150)
else if timeframe.in_seconds(tf)==timeframe.in_seconds()
data:=completed
else
intrabars=request.security_lower_tf(syminfo.tickerid,tf,f_detect(0),calc_bars_count=150)
if array.size(intrabars)>0
for j=0 to array.size(intrabars)-1
Candle item=array.get(intrabars,j)
if item.closedAt<=timenow and item.closedAt<=time_close
data:=item
if not na(data)
array.set(cache,i,data)
if barstate.islast and showPanel
Candle row=array.get(cache,i)
bool ready=not na(row) ? row.ready : false
color ink=ready ? f_color(row.side) : #8795AC
table.cell(panel,0,i+2,array.get(frameNames,i),text_color=#DDEAF7,text_size=size.small)
table.cell(panel,1,i+2,ready ? row.name : "Awaiting history",text_color=ink,text_size=size.small,tooltip=ready ? row.names : "Requires 28 consecutive valid closed candles.")
table.cell(panel,2,i+2,ready and row.code!=0 ? str.tostring(row.score,"#.0")+" · "+f_grade(row.score) : "—",text_color=ink,text_size=size.small)
table.cell(panel,3,i+2,ready and not na(row.bodyRatio) ? f_meter(row.bodyRatio)+" "+str.tostring(row.bodyRatio,"#.00")+"×" : "—",text_color=ready ? f_color(row.bodySide) : ink,text_size=size.small,tooltip="Current completed body / preceding 20 bodies. Meter fills at 3×. Green/red reflects candle body colour, not forecast.")
table.cell(panel,4,i+2,ready ? str.format_time(row.closedAt,"dd MMM HH:mm","UTC") : "—",text_color=#9CB2CA,text_size=size.small,tooltip="Source candle closing time, UTC. This is a completed candle, not a developing prediction.")
if barstate.islast and showPanel
table.merge_cells(panel,0,0,4,0)
table.cell(panel,0,0,"QUBIT CANDLE DETECTOR · "+syminfo.ticker,text_color=#90D8FF,bgcolor=#18304A,text_size=size.normal)
for [i,title] in array.from("TF","Completed pattern","Strength / 100","Body size","Closed · UTC")
table.cell(panel,i,1,title,text_color=#BBCDE2,bgcolor=#17273C,text_size=size.small)
table.merge_cells(panel,0,13,4,13)
table.cell(panel,0,13,"Context-checked patterns · same chart market · strength ≠ win probability",text_color=#879CB6,text_size=size.tiny)