Dajavue's Magic ORB Pro V2.5

dajavue1083 · study · 507 行 · 点赞 35 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=6
indicator("Dajavue's Magic ORB Pro V2.5", overlay=true, max_lines_count=300, max_labels_count=500, max_boxes_count=50)
 
// ─── Inputs ────────────────────────────────────────────────────────────────
string G1="01 • Sessions / ORB", G2="02 • Signals / Filters", G3="03 • Risk / Targets", G4="04 • Levels / EMAs", G5="05 • Dashboard / Appearance"
string tz="America/New_York"
string orbPreset=input.string("15", "ORB minutes", options=["5","10","15","30","Custom"], group=G1)
int customMinutes=input.int(20,"Custom ORB minutes",minval=1,maxval=120,group=G1)
int orbMinutes=orbPreset=="Custom"?customMinutes:int(str.tonumber(orbPreset))
string tradeSession=input.session("0935-1200","Entry window (New York)",group=G1)
int maxTrades=input.int(2,"Max entries per day",minval=1,maxval=10,group=G1)
string signalMode=input.string("Both","Entry types",options=["Both","Momentum","Retest"],group=G2)
float minBody=input.float(0.60,"Momentum minimum body/range",minval=0,maxval=1,step=0.05,group=G2)
int retestBars=input.int(5,"Retest expires after N bars",minval=1,maxval=50,group=G2)
int retestTicks=input.int(2,"Retest tolerance (ticks)",minval=0,group=G2)
bool useVwap=input.bool(false,"STRICT: Require VWAP alignment",group=G2)
bool useVolume=input.bool(false,"STRICT: Require relative volume",group=G2)
int volumeLen=input.int(20,"Relative volume MA",minval=1,group=G2)
float minRVOL=input.float(1.2,"Minimum relative volume",minval=0.1,step=0.1,group=G2)
bool useEma=input.bool(false,"STRICT: Require EMA alignment",group=G2)
bool useHTF=input.bool(false,"STRICT: Require confirmed HTF alignment",group=G2)
string htf=input.timeframe("60","HTF",group=G2)
int htfEmaLen=input.int(50,"HTF EMA length",minval=1,group=G2)
float maxChase=input.float(0.5,"Max close distance beyond ORB (range multiples)",minval=0.0,step=0.1,group=G2)
string minGrade=input.string("D","Minimum TRADE grade (strict mode only)",options=["A+","A","B","C","D"],group=G2)
bool strictGrade=input.bool(false,"STRICT: Block trade entries below minimum grade",group=G2)
string stopMode=input.string("Swing","Stop model",options=["Swing","ORB","ATR"],group=G3)
int swingBars=input.int(5,"Confirmed swing pivot length",minval=1,maxval=30,group=G3)
int stopBuffer=input.int(2,"Stop buffer ticks",minval=0,group=G3)
int atrLen=input.int(14,"ATR length",minval=1,group=G3)
float atrMult=input.float(1.5,"ATR stop multiple",minval=0.1,step=0.1,group=G3)
float maxRiskATR=input.float(4.0,"Maximum initial risk (ATR multiples)",minval=0.1,step=0.25,group=G3)
string targetMode=input.string("R multiples","Target calculation",options=["R multiples","ORB multiples"],group=G3)
float target1=input.float(1.0,"TP1 multiple",minval=0.1,step=0.1,group=G3)
float target2=input.float(2.0,"TP2 multiple",minval=0.1,step=0.1,group=G3)
float target3=input.float(3.0,"TP3 multiple",minval=0.1,step=0.1,group=G3)
bool showPD=input.bool(true,"Previous day high / low",group=G4)
bool showPM=input.bool(true,"Premarket high / mid / low",group=G4)
bool showORB=input.bool(true,"ORB high / mid / low",group=G4)
bool shadeORB=input.bool(true,"Shade ORB range",group=G4)
bool showVWAP=input.bool(true,"Session VWAP",group=G4)
bool showFastEMA=input.bool(true,"Show EMA 1",inline="ema1",group=G4)
int emaFast=input.int(13,"Length",minval=1,inline="ema1",group=G4)
color fastEMAColor=input.color(#FFD21F,"Color",inline="ema1",group=G4)
bool showMidEMA=input.bool(true,"Show EMA 2",inline="ema2",group=G4)
int emaMid=input.int(48,"Length",minval=1,inline="ema2",group=G4)
color midEMAColor=input.color(#9C5DE8,"Color",inline="ema2",group=G4)
bool showSlowEMA=input.bool(true,"Show EMA 3",inline="ema3",group=G4)
int emaSlow=input.int(200,"Length",minval=1,inline="ema3",group=G4)
color slowEMAColor=input.color(#F23645,"Color",inline="ema3",group=G4)
string dashboard=input.string("Full","Dashboard",options=["Full","Compact","Hidden"],group=G5)
bool showSignals=input.bool(true,"Show CALL / PUT setup markers",group=G5)
bool showSetupGrade=input.bool(false,"Show grade on CALL / PUT markers",group=G5)
bool showTradeLines=input.bool(true,"Show active entry / SL / TP lines",group=G5)
bool showLevelLabels=input.bool(true,"Show level name labels",group=G5)
string levelLabelSize=input.string("Tiny","Level label size",options=["Tiny","Small","Normal","Large"],group=G5)
string signalLabelSize=input.string("Large","Signal label size",options=["Tiny","Small","Normal","Large"],group=G5)
bool showTPLabels=input.bool(true,"Show TP1 / TP2 / TP3 labels",group=G5)
string tpLabelSize=input.string("Normal","TP label size",options=["Tiny","Small","Normal","Large"],group=G5)
bool keepTPHistory=input.bool(true,"Keep TP levels after trade closes",group=G5)
int tpHistoryLimit=input.int(20,"Historical trades with TP lines",minval=1,maxval=40,group=G5)
bool showBlockedSignals=input.bool(false,"Show filtered breakout markers",group=G5,tooltip="Small amber marks show a valid directional breakout that was blocked by filters, grading, risk, or trade limits. These are NOT trade entries.")
string levelScope=input.string("Premarket + RTH","Premarket level display",options=["Premarket + RTH","RTH only"],group=G5)
sizeFromText(string choice) =>
    switch choice
        "Tiny" => size.tiny
        "Small" => size.small
        "Normal" => size.normal
        => size.large
string levelSize=sizeFromText(levelLabelSize)
string signalSize=sizeFromText(signalLabelSize)
string tpSize=sizeFromText(tpLabelSize)
 
color BULL=#089981, BEAR=#F23645, GOLD=#E0B85A, BLUE=#5B9CF6
// This version is intended for intraday US-equity charts with a bar interval
// that evenly divides the selected ORB duration. Otherwise signals are disabled.
int chartSec=timeframe.in_seconds(timeframe.period)
bool supported=timeframe.isintraday and chartSec>=60 and chartSec<=orbMinutes*60 and (orbMinutes*60)%chartSec==0
int minuteOfDay=hour(time,tz)*60+minute(time,tz)
int startMinute=570
bool rth=not na(time(timeframe.period,"0930-1600",tz))
bool pm=not na(time(timeframe.period,"0400-0930",tz))
bool tradeTime=not na(time(timeframe.period,tradeSession,tz))
int dateKey=year(time,tz)*10000+month(time,tz)*100+dayofmonth(time,tz)
bool newDay=na(dateKey[1]) or dateKey!=dateKey[1]
bool inOrb=rth and minuteOfDay>=startMinute and minuteOfDay<startMinute+orbMinutes
bool orbJustFinished=not inOrb and inOrb[1]
bool rthEnd=not rth and rth[1]
bool levelPMWindow=levelScope=="RTH only"?rth:(pm or rth)
 
// ─── Session levels ────────────────────────────────────────────────────────
float pdh=request.security(syminfo.tickerid,"D",high[1],lookahead=barmerge.lookahead_on)
float pdl=request.security(syminfo.tickerid,"D",low[1],lookahead=barmerge.lookahead_on)
var float pmHigh=na
var float pmLow=na
var float orbHigh=na
var float orbLow=na
var bool orbReady=false
var float pv=0.0
var float volSum=0.0
if newDay
    pmHigh:=na
    pmLow:=na
    orbHigh:=na
    orbLow:=na
    orbReady:=false
    pv:=0.0
    volSum:=0.0
if pm
    pmHigh:=na(pmHigh)?high:math.max(pmHigh,high)
    pmLow:=na(pmLow)?low:math.min(pmLow,low)
if inOrb
    orbHigh:=na(orbHigh)?high:math.max(orbHigh,high)
    orbLow:=na(orbLow)?low:math.min(orbLow,low)
if orbJustFinished and not na(orbHigh) and not na(orbLow)
    orbReady:=true
if rth
    pv+=hlc3*nz(volume)
    volSum+=nz(volume)
float vwap=volSum>0?pv/volSum:na
float pmMid=(pmHigh+pmLow)/2
float orbMid=(orbHigh+orbLow)/2
float orbWidth=orbHigh-orbLow
float ef=ta.ema(close,emaFast), em=ta.ema(close,emaMid), es=ta.ema(close,emaSlow)
bool emaBull=ef>em and em>es
bool emaBear=ef<em and em<es
float htfClose=request.security(syminfo.tickerid,htf,close[1],lookahead=barmerge.lookahead_on)
float htfEma=request.security(syminfo.tickerid,htf,ta.ema(close,htfEmaLen)[1],lookahead=barmerge.lookahead_on)
bool htfBull=htfClose>htfEma
bool htfBear=htfClose<htfEma
float atr=ta.atr(atrLen)
float avgVol=ta.sma(volume,volumeLen)
float rvol=avgVol>0?volume/avgVol:na
float bodyRatio=math.abs(close-open)/math.max(high-low,syminfo.mintick)
float pivotLo=ta.pivotlow(low,swingBars,swingBars)
float pivotHi=ta.pivothigh(high,swingBars,swingBars)
var float lastSwingLo=na, var float lastSwingHi=na
if not na(pivotLo)
    lastSwingLo:=pivotLo
if not na(pivotHi)
    lastSwingHi:=pivotHi
 
// ─── Trade state / breakout state ─────────────────────────────────────────
// Entries are modeled at the CONFIRMATION CLOSE for this indicator preview.
// A separate strategy version must model next-bar-open execution and slippage.
var int breakoutDir=0
var int breakoutBar=na
var bool breakoutConsumed=false
var int tradeCount=0
var int setupCount=0
var int tradeDir=0
var int stage=0
var float entry=na
var float stop=na
var float initialStop=na
var float tp1=na
var float tp2=na
var float tp3=na
var float realizedR=0.0
var int wins=0
var int losses=0
var int breakevens=0
var int completed=0
var float netR=0.0
var float grossWinR=0.0
var float grossLossR=0.0
var int signalGrade=0
var string signalKind="—"
var bool pendingActivation=false
if newDay
    breakoutDir:=0
    breakoutBar:=na
    breakoutConsumed:=false
    tradeCount:=0
    setupCount:=0
    // Close any prior-day simulated position at the last available close.
    if tradeDir!=0
        float lastExit=nz(close[1],close)
        float fraction=stage==0?1.0:stage==1?0.67:0.34
        float finalR=realizedR+fraction*tradeDir*(lastExit-entry)/math.abs(entry-initialStop)
        completed+=1
        netR+=finalR
        if finalR>0
            wins+=1
            grossWinR+=finalR
        else if finalR<0
            losses+=1
            grossLossR+=-finalR
        else
            breakevens+=1
    tradeDir:=0
    stage:=0
    pendingActivation:=false
    entry:=na
    stop:=na
    initialStop:=na
    tp1:=na
    tp2:=na
    tp3:=na
    realizedR:=0.0
 
bool longBreak=orbReady and rth and close>orbHigh and close[1]<=orbHigh
bool shortBreak=orbReady and rth and close<orbLow and close[1]>=orbLow
if barstate.isconfirmed and (longBreak or shortBreak)
    breakoutDir:=longBreak?1:-1
    breakoutBar:=bar_index
    breakoutConsumed:=false
// Invalidate a pending breakout after close returns inside its ORB boundary.
if barstate.isconfirmed and breakoutDir==1 and close<orbHigh
    breakoutDir:=0
if barstate.isconfirmed and breakoutDir==-1 and close>orbLow
    breakoutDir:=0
 
bool longFilters=(not useVwap or close>vwap) and (not useEma or emaBull) and (not useHTF or htfBull) and (not useVolume or (not na(rvol) and rvol>=minRVOL))
bool shortFilters=(not useVwap or close<vwap) and (not useEma or emaBear) and (not useHTF or htfBear) and (not useVolume or (not na(rvol) and rvol>=minRVOL))
bool momLong=longBreak and close>open and bodyRatio>=minBody and (close-orbHigh)<=maxChase*orbWidth
bool momShort=shortBreak and close<open and bodyRatio>=minBody and (orbLow-close)<=maxChase*orbWidth
bool rtLong=breakoutDir==1 and not breakoutConsumed and not na(breakoutBar) and bar_index>breakoutBar and bar_index-breakoutBar<=retestBars and low<=orbHigh+retestTicks*syminfo.mintick and close>orbHigh and close>open
bool rtShort=breakoutDir==-1 and not breakoutConsumed and not na(breakoutBar) and bar_index>breakoutBar and bar_index-breakoutBar<=retestBars and high>=orbLow-retestTicks*syminfo.mintick and close<orbLow and close<open
if not na(breakoutBar) and bar_index-breakoutBar>retestBars
    breakoutDir:=0
// Raw confirmed setups are independent of the trade simulator's filters and risk model.
// A setup marker is informational; only an accepted trade starts TP/SL tracking.
bool setupLong=barstate.isconfirmed and supported and orbReady and rth and tradeTime and ((signalMode!="Retest" and momLong) or (signalMode!="Momentum" and rtLong))
bool setupShort=barstate.isconfirmed and supported and orbReady and rth and tradeTime and ((signalMode!="Retest" and momShort) or (signalMode!="Momentum" and rtShort))
bool wantLong=setupLong and longFilters
bool wantShort=setupShort and shortFilters
 
// ─── Confluence grading (score at signal, frozen thereafter) ──────────────
int minScore=minGrade=="A+"?90:minGrade=="A"?80:minGrade=="B"?70:minGrade=="C"?60:0
int scoreLong=(htfBull?20:0)+(close>vwap?20:0)+(emaBull?15:0)+(nz(rvol)>=minRVOL?15:0)+(close>open and bodyRatio>=minBody?15:0)+(not na(pmMid) and close>pmMid?10:0)+(orbWidth>0 and orbWidth<=atr*3?5:0)
int scoreShort=(htfBear?20:0)+(close<vwap?20:0)+(emaBear?15:0)+(nz(rvol)>=minRVOL?15:0)+(close<open and bodyRatio>=minBody?15:0)+(not na(pmMid) and close<pmMid?10:0)+(orbWidth>0 and orbWidth<=atr*3?5:0)
grade(int points) =>points>=90?"A+":points>=80?"A":points>=70?"B":points>=60?"C":"D"
 
bool canEnter=supported and orbReady and orbWidth>0 and tradeTime and rth and barstate.isconfirmed and tradeDir==0 and tradeCount<maxTrades and not pendingActivation
bool longSignal=false
bool shortSignal=false
bool tp1Event=false
bool tp2Event=false
bool tp3Event=false
bool stopEvent=false
var label tp1Label=na
var label tp2Label=na
var label tp3Label=na
var line tp1HistLine=na
var line tp2HistLine=na
var line tp3HistLine=na
var array<label> pastTPLabels=array.new<label>()
var array<line> pastTPLines=array.new<line>()
bool blockedLong=false
bool blockedShort=false
string blockedReason="—"
if setupLong or setupShort
    setupCount+=1
if canEnter and (wantLong or wantShort)
    int dir=wantLong?1:-1
    int points=dir==1?scoreLong:scoreShort
    float proposedEntry=close
    float proposedStop=stopMode=="Swing"?(dir==1?lastSwingLo-stopBuffer*syminfo.mintick:lastSwingHi+stopBuffer*syminfo.mintick):stopMode=="ORB"?(dir==1?orbLow-stopBuffer*syminfo.mintick:orbHigh+stopBuffer*syminfo.mintick):proposedEntry-dir*atr*atrMult
    float risk=dir*(proposedEntry-proposedStop)
    bool validRisk=not na(risk) and risk>syminfo.mintick and risk<=atr*maxRiskATR
    float dist=targetMode=="R multiples"?risk:orbWidth
    bool validTargets=target1<target2 and target2<target3 and dist>0
    if (not strictGrade or points>=minScore) and validRisk and validTargets
        tradeDir:=dir
        entry:=proposedEntry
        stop:=proposedStop
        initialStop:=proposedStop
        tp1:=entry+dir*dist*target1
        tp2:=entry+dir*dist*target2
        tp3:=entry+dir*dist*target3
        stage:=0
        realizedR:=0.0
        signalGrade:=points
        signalKind:=(dir==1?momLong:momShort)?"MOM":"RT"
        tradeCount+=1
        breakoutConsumed:=true
        pendingActivation:=true // Prevent fills on the signal candle.
        longSignal:=dir==1
        shortSignal:=dir==-1
        // Anchor each TP name just LEFT of its corresponding horizontal line.
        // Retain a limited number of completed trades for visual review.
        if showTradeLines and showTPLabels
            color targetColor=dir==1?color.lime:color.rgb(255,95,110)
            tp1Label:=label.new(bar_index-1,tp1,"TP 1",style=label.style_label_right,color=color.new(targetColor,100),textcolor=targetColor,size=tpSize)
            tp2Label:=label.new(bar_index-1,tp2,"TP 2",style=label.style_label_right,color=color.new(targetColor,100),textcolor=targetColor,size=tpSize)
            tp3Label:=label.new(bar_index-1,tp3,"TP 3",style=label.style_label_right,color=color.new(targetColor,100),textcolor=targetColor,size=tpSize)
            tp1HistLine:=line.new(bar_index,tp1,bar_index+1,tp1,color=color.new(targetColor,25),width=1)
            tp2HistLine:=line.new(bar_index,tp2,bar_index+1,tp2,color=color.new(targetColor,25),width=1)
            tp3HistLine:=line.new(bar_index,tp3,bar_index+1,tp3,color=color.new(targetColor,25),width=1)
            array.push(pastTPLabels,tp1Label)
            array.push(pastTPLabels,tp2Label)
            array.push(pastTPLabels,tp3Label)
            array.push(pastTPLines,tp1HistLine)
            array.push(pastTPLines,tp2HistLine)
            array.push(pastTPLines,tp3HistLine)
            while array.size(pastTPLabels)>tpHistoryLimit*3
                label.delete(array.shift(pastTPLabels))
            while array.size(pastTPLines)>tpHistoryLimit*3
                line.delete(array.shift(pastTPLines))
    else
        blockedLong:=dir==1
        blockedShort:=dir==-1
        blockedReason:=strictGrade and points<minScore?"GRADE":not validRisk?"STOP/RISK":"TARGETS"
// Show a blocked momentum breakout even if strict confirmation filters or session limits reject it.
if barstate.isconfirmed and supported and orbReady and rth and tradeTime
    if momLong and not longSignal and signalMode!="Retest"
        blockedLong:=true
        if blockedReason=="—"
            blockedReason:=not longFilters?"FILTER":not canEnter?"LIMIT/ACTIVE":"NO ENTRY"
    if momShort and not shortSignal and signalMode!="Retest"
        blockedShort:=true
        if blockedReason=="—"
            blockedReason:=not shortFilters?"FILTER":not canEnter?"LIMIT/ACTIVE":"NO ENTRY"
 
// Extend target lines only while the modeled trade is active.
if tradeDir!=0 and showTradeLines and showTPLabels
    if not na(tp1HistLine)
        line.set_x2(tp1HistLine,bar_index)
    if not na(tp2HistLine)
        line.set_x2(tp2HistLine,bar_index)
    if not na(tp3HistLine)
        line.set_x2(tp3HistLine,bar_index)
 
// Conservative OHLC ordering: if stop and target are both touched on a bar,
// the stop is filled first. No optimistic same-bar stop adjustments.
if tradeDir!=0 and not pendingActivation and barstate.isconfirmed
    bool stopTouched=tradeDir==1?low<=stop:high>=stop
    if stopTouched
        float fraction=stage==0?1.0:stage==1?0.67:0.34
        realizedR+=fraction*tradeDir*(stop-entry)/math.abs(entry-initialStop)
        stopEvent:=true
        tradeDir:=0
    else
        bool hit1=tradeDir==1?high>=tp1:low<=tp1
        bool hit2=tradeDir==1?high>=tp2:low<=tp2
        bool hit3=tradeDir==1?high>=tp3:low<=tp3
        if stage==0 and hit1
            realizedR+=0.33*tradeDir*(tp1-entry)/math.abs(entry-initialStop)
            stage:=1
            stop:=entry // Remaining 67% moves to BE after TP1.
            tp1Event:=true
 
        if stage==1 and hit2
            realizedR+=0.33*tradeDir*(tp2-entry)/math.abs(entry-initialStop)
            stage:=2
            tp2Event:=true
 
        if stage==2 and hit3
            realizedR+=0.34*tradeDir*(tp3-entry)/math.abs(entry-initialStop)
            tradeDir:=0
            tp3Event:=true
    if tradeDir==0
        completed+=1
        netR+=realizedR
        if realizedR>0
            wins+=1
            grossWinR+=realizedR
        else if realizedR<0
            losses+=1
            grossLossR+=-realizedR
        else
            breakevens+=1
        if not keepTPHistory
            if not na(tp1Label)
                label.delete(tp1Label)
            if not na(tp2Label)
                label.delete(tp2Label)
            if not na(tp3Label)
                label.delete(tp3Label)
            if not na(tp1HistLine)
                line.delete(tp1HistLine)
            if not na(tp2HistLine)
                line.delete(tp2HistLine)
            if not na(tp3HistLine)
                line.delete(tp3HistLine)
        tp1Label:=na
        tp2Label:=na
        tp3Label:=na
        tp1HistLine:=na
        tp2HistLine:=na
        tp3HistLine:=na
        stage:=0
        entry:=na
        stop:=na
        initialStop:=na
        tp1:=na
        tp2:=na
        tp3:=na
        realizedR:=0
if pendingActivation and not (longSignal or shortSignal)
    pendingActivation:=false
 
// ─── Session-separated levels and right-edge labels ───────────────────────
// plot.style_linebr + na outside each session prevents overnight connectors.
// Each session gets its own set of labels, which stop moving at session end.
float dayHighPlot=showPD and rth?pdh:na
float dayLowPlot=showPD and rth?pdl:na
float pmHighPlot=showPM and levelPMWindow?pmHigh:na
float pmMidPlot=showPM and levelPMWindow?pmMid:na
float pmLowPlot=showPM and levelPMWindow?pmLow:na
float orbHighPlot=showORB and rth?orbHigh:na
float orbMidPlot=showORB and rth?orbMid:na
float orbLowPlot=showORB and rth?orbLow:na
plot(dayHighPlot,"PDH",color.new(BLUE,15),1,plot.style_linebr)
plot(dayLowPlot,"PDL",color.new(BLUE,15),1,plot.style_linebr)
plot(pmHighPlot,"PMH",color.new(#15B8BE,15),1,plot.style_linebr)
plot(pmMidPlot,"PM midpoint",color.new(GOLD,40),1,plot.style_linebr)
plot(pmLowPlot,"PML",color.new(#15B8BE,15),1,plot.style_linebr)
pH=plot(orbHighPlot,"ORB high",BLUE,2,plot.style_linebr)
pL=plot(orbLowPlot,"ORB low",BLUE,2,plot.style_linebr)
plot(orbMidPlot,"ORB midpoint",color.new(GOLD,20),1,plot.style_linebr)
fill(pH,pL,color=shadeORB and rth?color.new(BLUE,92):na,title="ORB zone")
plot(showVWAP and rth?vwap:na,"RTH VWAP",color.white,2,plot.style_linebr)
plot(showFastEMA?ef:na,"Fast EMA",fastEMAColor,1)
plot(showMidEMA?em:na,"Mid EMA",midEMAColor,1)
plot(showSlowEMA?es:na,"Slow EMA",slowEMAColor,2)
plot(showTradeLines and rth?entry:na,"Active entry",BLUE,2,plot.style_linebr)
plot(showTradeLines and rth?stop:na,"Active stop",BEAR,2,plot.style_linebr)
plot(showTradeLines and rth and stage==0?tp1:na,"TP1",BULL,1,plot.style_linebr)
plot(showTradeLines and rth and stage<=1?tp2:na,"TP2",BULL,1,plot.style_linebr)
plot(showTradeLines and rth?tp3:na,"TP3",BULL,2,plot.style_linebr)
 
// Create a label when a level first becomes visible, then update its position
// until the last bar of that session. Preserve completed sessions' labels.
var array<label> activeLevelLabels=array.new<label>(8,na)
var array<bool> levelSeen=array.new<bool>(8,false)
if newDay
    for i=0 to 7
        array.set(activeLevelLabels,i,na)
        array.set(levelSeen,i,false)
float[] levelValues=array.from(dayHighPlot,dayLowPlot,pmHighPlot,pmMidPlot,pmLowPlot,orbHighPlot,orbMidPlot,orbLowPlot)
string[] levelNames=array.from("PDH","PDL","PMH","PM MID","PML","ORB H","ORB MID","ORB L")
color[] levelColors=array.from(BLUE,BLUE,#15B8BE,GOLD,#15B8BE,BLUE,GOLD,BLUE)
if showLevelLabels
    for i=0 to 7
        float y=array.get(levelValues,i)
        if not na(y)
            label lab=array.get(activeLevelLabels,i)
            if na(lab)
                lab:=label.new(bar_index,y,array.get(levelNames,i),style=label.style_label_left,color=array.get(levelColors,i),textcolor=color.white,size=levelSize)
                array.set(activeLevelLabels,i,lab)
            else
                label.set_xy(lab,bar_index,y)
                label.set_text(lab,array.get(levelNames,i))
                label.set_size(lab,levelSize)
 
if showSignals and setupLong
    label.new(bar_index,low,"▲ CALL"+(showSetupGrade?" • "+grade(scoreLong):""),style=label.style_label_up,color=BULL,textcolor=color.white,size=signalSize)
if showSignals and setupShort
    label.new(bar_index,high,"PUT ▼"+(showSetupGrade?" • "+grade(scoreShort):""),style=label.style_label_down,color=BEAR,textcolor=color.white,size=signalSize)
plotshape(showBlockedSignals and blockedLong and not longSignal,title="Diagnostic: CALL setup not traded",style=shape.triangleup,location=location.belowbar,color=GOLD,size=size.tiny,text="X")
plotshape(showBlockedSignals and blockedShort and not shortSignal,title="Diagnostic: PUT setup not traded",style=shape.triangledown,location=location.abovebar,color=GOLD,size=size.tiny,text="X")
plotshape(tp1Event,title="TP1 hit",style=shape.circle,location=location.abovebar,color=GOLD,size=size.tiny,text="1")
plotshape(tp2Event,title="TP2 hit",style=shape.circle,location=location.abovebar,color=BULL,size=size.tiny,text="2")
plotshape(tp3Event,title="TP3 hit",style=shape.diamond,location=location.abovebar,color=BULL,size=size.tiny,text="3")
plotshape(stopEvent,title="Stop hit",style=shape.xcross,location=location.abovebar,color=BEAR,size=size.tiny,text="SL")
 
// ─── Dashboard ────────────────────────────────────────────────────────────
var table dash=table.new(position.top_right,2,14,border_width=1)
int biasScore=(htfBull?1:htfBear?-1:0)+(close>vwap?1:close<vwap?-1:0)+(close>pmMid?1:close<pmMid?-1:0)+(close>orbMid?1:close<orbMid?-1:0)
string bias=biasScore>0?"BULLISH":biasScore<0?"BEARISH":"NEUTRAL"
color biasColor=biasScore>0?BULL:biasScore<0?BEAR:GOLD
if barstate.islast
    table.clear(dash,0,0,1,13)
    if dashboard!="Hidden"
        table.cell(dash,0,0,"MAGIC ORB PRO V2",bgcolor=color.new(color.gray,65),text_color=GOLD)
        table.cell(dash,1,0,bias,bgcolor=color.new(biasColor,70),text_color=color.white)
        table.cell(dash,0,1,"ORB",text_color=color.white)
        table.cell(dash,1,1,str.tostring(orbMinutes)+"m • "+(orbReady?"READY":"BUILDING"),text_color=orbReady?BULL:GOLD)
        table.cell(dash,0,2,"CHART SUPPORT",text_color=color.white)
        table.cell(dash,1,2,supported?"OK":"UNSUPPORTED TF",text_color=supported?BULL:BEAR)
        table.cell(dash,0,3,"LAST GRADE",text_color=color.white)
        table.cell(dash,1,3,signalKind+" • "+grade(signalGrade)+" ("+str.tostring(signalGrade)+")",text_color=GOLD)
        table.cell(dash,0,4,"TRADE",text_color=color.white)
        table.cell(dash,1,4,tradeDir==0?"FLAT":stage==0?"ACTIVE":stage==1?"TP1 • BE STOP":"TP2 • BE STOP",text_color=tradeDir==0?color.silver:BULL)
        table.cell(dash,0,12,"SIGNAL FILTER",text_color=color.white)
        table.cell(dash,1,12,(strictGrade?"Min "+minGrade:"GRADE INFO")+" • "+(useVolume?"RVOL STRICT":"RVOL INFO"),text_color=GOLD)
        table.cell(dash,0,13,"SETUPS / BLOCK",text_color=color.white)
        table.cell(dash,1,13,str.tostring(setupCount)+" / "+blockedReason,text_color=GOLD)
        if dashboard=="Full"
            table.cell(dash,0,5,"HTF / EMA",text_color=color.white)
            table.cell(dash,1,5,(htfBull?"BULL":htfBear?"BEAR":"—")+" / "+(emaBull?"BULL":emaBear?"BEAR":"MIXED"),text_color=color.white)
            table.cell(dash,0,6,"VWAP / RVOL",text_color=color.white)
            table.cell(dash,1,6,(close>vwap?"ABOVE":"BELOW")+" / "+str.tostring(rvol,"#.##")+"x",text_color=color.white)
            table.cell(dash,0,7,"MODELED ENTRIES",text_color=color.white)
            table.cell(dash,1,7,str.tostring(tradeCount)+" / "+str.tostring(maxTrades),text_color=color.white)
            table.cell(dash,0,8,"W / L / BE",text_color=color.white)
            table.cell(dash,1,8,str.tostring(wins)+" / "+str.tostring(losses)+" / "+str.tostring(breakevens),text_color=color.white)
            table.cell(dash,0,9,"WIN RATE",text_color=color.white)
            table.cell(dash,1,9,completed>0?str.tostring(100.0*wins/completed,"#.0")+"%":"—",text_color=BULL)
            table.cell(dash,0,10,"NET R",text_color=color.white)
            table.cell(dash,1,10,str.tostring(netR,"#.##")+" R",text_color=netR>=0?BULL:BEAR)
            table.cell(dash,0,11,"PROFIT FACTOR",text_color=color.white)
            table.cell(dash,1,11,grossLossR>0?str.tostring(grossWinR/grossLossR,"#.##"):grossWinR>0?"∞":"—",text_color=color.white)
 
// ─── Alerts: setup markers are distinct from modeled trade entries.
alertcondition(setupLong,"Magic ORB B Setup","Magic ORB Pro bullish setup B on {{ticker}} at {{close}}")
alertcondition(setupShort,"Magic ORB S Setup","Magic ORB Pro bearish setup S on {{ticker}} at {{close}}")
// Existing CALL/PUT alerts below indicate simulated trade acceptance, not every B/S setup.
alertcondition(longSignal,"Magic ORB CALL","Magic ORB Pro confirmed CALL on {{ticker}} at {{close}}")
alertcondition(shortSignal,"Magic ORB PUT","Magic ORB Pro confirmed PUT on {{ticker}} at {{close}}")
alertcondition(tp1Event,"Magic ORB TP1","Magic ORB Pro TP1 reached on {{ticker}}")
alertcondition(tp2Event,"Magic ORB TP2","Magic ORB Pro TP2 reached on {{ticker}}")
alertcondition(tp3Event,"Magic ORB TP3","Magic ORB Pro TP3 reached on {{ticker}}")
alertcondition(stopEvent,"Magic ORB STOP","Magic ORB Pro stop reached on {{ticker}}")

← 返回列表