本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("VIBE QSFM-00508939 S v1.0 Indicator Pine",overlay=true,max_bars_back=500,max_labels_count=200)
// SHORT EMA REJECTION WITH FIXED SL AND TP. Neither level trails.
// Standard OANDA:XAUUSD M5. Signal opens hour11 UTC weekdays; confirmed
// EXECUTE at11:05-12:00UTC /18:05-19:00Bangkok, next-bar-open model entry.
// Exact setup: high>=currentM5EMA20,close<EMA20,close<open,body<=.55ATR14;
// inclusiveATRrank120 in[.20,.85]; completedH1close<EMA50,H2close<EMA20,
// customH4close<EMA50. H4starts03/07/11/15/19/23UTC, fixed year-round.
// Full-count HTF buckets12/24/48M5bars only; skip partials/no EMA update.
// EMA seedfirstacceptedclose,alpha2/(length+1); finalize priorbucket before
// currentM5input,so only completed-at-decision-OPEN HTF values are used.
// ATR14: meanfirst14TR,thenWilder;firstTR=H-L. Rank120 counts<=current,
// includescurrent. Firsteligiblesourceindex240. NoRSIdirectional,momentum,
// range-size,retest or M5EMA50trend filters. Zero-minute entrycooldown.
// LiveDEFAULT:onevirtualposition,June3 2026seed,noexpiry. Originalbacktest
// Jan1 2025 23UTC-May27 2026 11:45UTC(cap5). ForwardreferenceJune3-Oct16
// 09:10UTCexclusive(cap1). All states commit atconfirmedclose;pending
// EXECUTE entersnextavailablebarOPEN. Separate pertradefixedbrackets.
// Your actualshortfillE: SL=E+6,TP=E-6.90. Example4300=>4306/4293.10.
// Never trail or addbreakeven. Source model checksSLfirst ifbothhit,including
// entrybar. Charttouches/levels are advisory,notbroker execution evidence.
// PREPARE:developing bearish EMA-touch/body setup and allothercurrentgates,
// close<=EMA20+.50defaulttolerance. Provisional,can cancel,notentrypermission
// and notprerequisiteforEXECUTE. Onceperdevelopingbar;nohistoricalprepares.
// EXECUTE:exactconfirmedrules; SL/TP estimatesfromdecisionclose;recalculate
// fromyouractualfill. MODELEXIT:confirmedcharttouch;brokerprotectionmust
// execute whenhit,do notwaitfortheclosemessage. Scriptcannotplace/amendorders.
// CreateONEalert:Any alert() function call. ThreeeventtogglesdefaultON;
// distinctevents mayoccur on samebar. Recreate aftercode/inputs/symbol/timeframe
// changes. Notifications are realtimeonly. Live chartusesavailablehistory,
// not DeepReporthistory; missingseedcontext canchangeEMAfilters/signals.
// Source historical training:40trades32wins80%,netUSD28800,cap5,Jan2025-May2026.
// Source cap1trainingalternative:22/17wins77.27%,net14550. Sourceforward:
// 16/8wins50%,net1200,Jun-Oct2026;raw19minus3safetyoverlaprejections.
// UserStrategyv1.0Last365days:23/18wins78.26%,net15699.37,PF4.14,
// intrabarDD2734.06. Short-historyreplaymatchesall23times/prices;22match
// fullsource and1extraOct21setup reflectsH4EMAinitialization;18earliertrades
// excluded. ExactTVhistorystartunconfirmed. Full40TVcomparisonnotverified.
// Results are sample-specific historical evidence,not expected future winrates.
// Native strategybothhit/gapfills,bid/ask/spread/fees and manualfills can differ.
// Forwardcap1generation approximates original rawcap5then safetyfilter.
// Plots/table shownewestmodeltrade;allIDsmanaged separately in cap5mode.
// Indicator Pine compilation, chart overlay and live alert delivery need checking.
mode = input.string("Live", "Mode", options=["Live","Original backtest","Forward reference"])
liveSeed = input.time(timestamp("03 Jun 2026 00:00 +0000"), "Live source seed / first signal date (UI follows chart timezone)")
int seedTime = mode == "Original backtest" ? timestamp("01 Jan 2025 23:00 +0000") : mode == "Forward reference" ? timestamp("03 Jun 2026 00:00 +0000") : liveSeed
int startTime = seedTime
int endTime = mode == "Original backtest" ? timestamp("27 May 2026 11:45 +0000") : timestamp("16 Oct 2026 09:10 +0000")
int openCap = mode == "Original backtest" ? 5 : 1
prepareOn = input.bool(true,"PREPARE alert",group="Alerts")
prepareTolerance = input.float(0.5,"Prepare tolerance above EMA20 (price dollars)",minval=0,maxval=6,group="Alerts")
executeOn = input.bool(true,"EXECUTE alert",group="Alerts")
exitOn = input.bool(true,"MODEL EXIT alert",group="Alerts")
showEma = input.bool(true,"M5 EMA20",group="Display")
showHtf = input.bool(false,"Completed H1/H2/H4 EMA lines",group="Display")
showLevels = input.bool(true,"Newest model entry / SL / TP",group="Display")
showSignals = input.bool(true,"Confirmed execute and model exit markers",group="Display")
showLabels = input.bool(true,"Model entry labels",group="Display")
showPrepare = input.bool(true,"Provisional prepare shading",group="Display")
showTable = input.bool(true,"Criteria / management table",group="Display")
showDescription = input.bool(true,"Short method description",group="Display")
showStats = input.bool(false,"Historical sample win rates (not forecasts)",group="Display")
anchor = input.string("Top right","Table anchor",options=["Top right","Top left","Bottom right","Bottom left"],group="Display")
float stopDistance = 6.0
float targetDistance = 6.9
string tag = "VIBE QSFM-00508939 S v1.0 Indicator Pine"
f_price(float x) => na(x) ? "n/a" : str.tostring(x,format.mintick)
f_flag(bool ok) => ok ? "PASS" : "WAIT"
f_alert(string event,string id,float ep,float sl,float tp,string note) =>
tag+" | "+event+" | "+id+" | SHORT | "+syminfo.tickerid+" | M5 | UTC "+str.format_time(time_close,"yyyy-MM-dd HH:mm","UTC")+" | Reference "+f_price(ep)+" | SL "+f_price(sl)+" | FIXED TP "+f_price(tp)+" | "+note
if barstate.isfirst
if not chart.is_standard or not timeframe.isminutes or timeframe.multiplier != 5
runtime.error("Use standard5-minute candles.")
if syminfo.prefix != "OANDA" or syminfo.ticker != "XAUUSD"
runtime.error("Use OANDA:XAUUSD for this indicator.")
var int firstLoaded = time
var int sourceBars = 0
var float ema20 = na
var float trSum = 0.0
var float atr14 = na
// Each written call owns independent persistent bucket/EMA state.
// Finalize old bucket BEFORE ingesting current candle. Completed-at-OPEN matches
// the source even though Pine strategy calculation occurs at the candle close.
f_sourceHtf(int minutes, int offsetHours, int emaLength) =>
var int bucket = na
var int count = 0
var float workingClose = na
var float acceptedClose = na
var float acceptedEma = na
var int acceptedStart = na
int duration = minutes*60000
int offset = offsetHours*3600000
if time >= seedTime
int nextBucket = int(math.floor((time-offset)/duration))*duration+offset
if na(bucket)
bucket := nextBucket
else if nextBucket != bucket
if count >= minutes/5
acceptedClose := workingClose
float alpha = 2.0/(emaLength+1)
acceptedEma := na(acceptedEma) ? workingClose : workingClose*alpha+acceptedEma*(1-alpha)
acceptedStart := bucket
bucket := nextBucket
count := 0
count += 1
workingClose := close
[acceptedClose, acceptedEma, acceptedStart]
[h1Close,h1Ema,h1Start] = f_sourceHtf(60,0,50)
[h2Close,h2Ema,h2Start] = f_sourceHtf(120,0,20)
[h4Close,h4Ema,h4Start] = f_sourceHtf(240,3,50)
if time >= seedTime
sourceBars += 1
ema20 := na(ema20) ? close : close*(2.0/21)+ema20*(1-2.0/21)
float tr = sourceBars == 1 ? high-low : math.max(high-low,math.max(math.abs(high-close[1]),math.abs(low-close[1])))
if sourceBars <= 14
trSum += tr
if sourceBars == 14
atr14 := trSum/14
else
atr14 := (atr14*13+tr)/14
float atrRank = na
if sourceBars >= 133
int count = 0
for k = 0 to 119
count += atr14[k] <= atr14 ? 1 : 0
atrRank := count/120.0
bool sessionOk = hour(time,"UTC") == 11 and dayofweek(time,"UTC") != dayofweek.saturday and dayofweek(time,"UTC") != dayofweek.sunday
bool htfOk = not na(h1Ema) and not na(h2Ema) and not na(h4Ema) and h1Close < h1Ema and h2Close < h2Ema and h4Close < h4Ema
bool rankOk = not na(atrRank) and atrRank >= 0.2 and atrRank <= 0.85
bool rejection = high >= ema20 and close < ema20 and close < open and math.abs(close-open) <= atr14*0.55
bool criteria = sourceBars > 240 and sessionOk and htfOk and rankOk and rejection
// Per-position virtual model: all mutation deferred to confirmed chart close.
var array<int> tradeIds = array.new_int()
var array<float> entries = array.new_float()
var array<float> stops = array.new_float()
var bool pending = false
var int pendingBar = na
var int pendingId = na
var int serial = 0
var int lastEntryTime = na
var string lastEvent = "Waiting for setup"
bool entering = pending and bar_index > nz(pendingBar,bar_index)
int previousSize = array.size(entries)
float barEntry = entering ? open : previousSize > 0 ? array.get(entries,previousSize-1) : na
float barSL = entering ? open+6 : previousSize > 0 ? array.get(stops,previousSize-1) : na
float barTP = entering ? open-targetDistance : not na(barEntry) ? barEntry-targetDistance : na
bool executeEvent = false
bool exitEvent = false
bool dateOk = time >= startTime and (mode == "Live" or time < endTime)
if barstate.isconfirmed
if entering
array.push(tradeIds,pendingId)
array.push(entries,open)
array.push(stops,open+6)
pending := false
lastEntryTime := time
lastEvent := "Model entry S-"+str.tostring(pendingId)+" "+f_price(open)
if showLabels
label.new(bar_index,high,"MODEL S-"+str.tostring(pendingId)+"\n"+f_price(open),style=label.style_label_down,color=color.blue,textcolor=color.white,size=size.tiny)
if array.size(entries) > 0
for i = array.size(entries)-1 to 0
string id = "S-"+str.tostring(array.get(tradeIds,i))
float ep = array.get(entries,i)
float sl = array.get(stops,i)
float tp = ep-targetDistance
bool stopHit = high >= sl
bool targetHit = low <= tp
if stopHit or targetHit
float xp = stopHit ? sl : tp
string reason = stopHit ? "SL" : "FIXED TP"
exitEvent := true
lastEvent := "Model "+id+" "+reason+" "+f_price(xp)
if exitOn
alert(f_alert("MODEL EXIT "+reason,id,ep,sl,tp,"Chart touch only. Verify your broker position; model exit "+f_price(xp)),alert.freq_all)
array.remove(tradeIds,i)
array.remove(entries,i)
array.remove(stops,i)
bool cool = na(lastEntryTime) or time-lastEntryTime >= 0
if criteria and dateOk and cool and not pending and array.size(entries) < openCap
serial += 1
pending := true
pendingBar := bar_index
pendingId := serial
executeEvent := true
lastEvent := "EXECUTE S-"+str.tostring(serial)+" confirmed; next-bar entry"
if executeOn
alert(f_alert("EXECUTE / CONFIRMED","S-"+str.tostring(serial),close,close+6,close-targetDistance,"ESTIMATED from signal close. If entering next bar,reset SL=actual fill+6,TP=fill-6.90;both stay fixed. No trailing."),alert.freq_all)
varip bool preparedThisBar = false
if barstate.isnew
preparedThisBar := false
bool coolNow = na(lastEntryTime) or time-lastEntryTime >= 0
bool capacityOk = not pending and array.size(entries) < openCap
bool bodyOk = math.abs(close-open) <= atr14*0.55
bool prepareNow = sourceBars > 240 and dateOk and sessionOk and htfOk and rankOk and close < open and bodyOk and high >= ema20 and close <= ema20+prepareTolerance and coolNow and capacityOk
if barstate.isrealtime and not barstate.isconfirmed and prepareNow and not preparedThisBar
preparedThisBar := true
if prepareOn
alert(f_alert("PREPARE / PROVISIONAL","candidate",close,close+6,close-targetDistance,"Do not enter yet. Wait for confirmed EXECUTE. Developing EMA rejection can cancel."),alert.freq_all)
int modelOpen = array.size(entries)
float modelEntry = modelOpen > 0 ? array.get(entries,modelOpen-1) : na
float modelSL = modelOpen > 0 ? array.get(stops,modelOpen-1) : na
float modelTP = modelOpen > 0 ? modelEntry-targetDistance : na
plot(showEma ? ema20 : na,"Source M5 EMA20",color=color.blue)
plot(showHtf ? h1Ema : na,"Completed H1 EMA50",color=color.purple)
plot(showHtf ? h2Ema : na,"Completed H2 EMA20",color=color.teal)
plot(showHtf ? h4Ema : na,"Completed H4 EMA50 UTC+3",color=color.fuchsia)
plot(showLevels ? barEntry : na,"Newest model entry reference",color=color.aqua,style=plot.style_linebr)
plot(showLevels ? barSL : na,"SL active during current bar",color=color.red,linewidth=2,style=plot.style_linebr)
plot(showLevels ? barTP : na,"Fixed TP reference",color=color.lime,linewidth=2,style=plot.style_linebr)
plot(atrRank,"ATR inclusive rank",display=display.data_window)
plot(serial,"Model signals",display=display.data_window)
plot(executeEvent ? 1 : 0,"Confirmed execute event",display=display.data_window)
plotshape(showSignals and executeEvent,title="EXECUTE short",style=shape.triangledown,location=location.abovebar,color=color.red,size=size.small,text="EXEC S",textcolor=color.white)
plotshape(showSignals and exitEvent,title="Model exit",style=shape.xcross,location=location.belowbar,color=color.orange,size=size.tiny,text="EXIT")
bgcolor(showPrepare and barstate.isrealtime and not barstate.isconfirmed and prepareNow ? color.new(color.yellow,88) : na,title="Provisional prepare")
string pos = switch anchor
"Top left" => position.top_left
"Bottom right" => position.bottom_right
"Bottom left" => position.bottom_left
=> position.top_right
var table panel = table.new(pos,2,20,bgcolor=color.new(color.black,12),frame_color=color.gray,frame_width=1)
f_row(int row,string left,string right,color txt) =>
table.cell(panel,0,row,left,text_color=color.silver,text_size=size.small,text_halign=text.align_left)
table.cell(panel,1,row,right,text_color=txt,text_size=size.small,text_halign=text.align_left)
if barstate.islast
if showTable
f_row(0,"VIBE QSFM-00508939 S","v1.0 Indicator Pine",color.white)
f_row(1,"Mode / capacity",mode+" / "+str.tostring(openCap),color.white)
f_row(2,"Signal hour11UTC",f_flag(sessionOk)+" | 18hBangkok",sessionOk ? color.lime : color.orange)
f_row(3,"Completed H1 bearish",f_flag(not na(h1Ema) and h1Close < h1Ema),color.white)
f_row(4,"Completed H2 bearish",f_flag(not na(h2Ema) and h2Close < h2Ema),color.white)
f_row(5,"Completed H4 bearish",f_flag(not na(h4Ema) and h4Close < h4Ema)+" | UTC+3",color.white)
f_row(6,"EMA20 touch / bearish close",f_flag(high >= ema20)+" / "+f_flag(close < open and close < ema20),color.white)
f_row(7,"Body <=0.55ATR",f_flag(bodyOk),color.white)
f_row(8,"ATR rank20-85%",f_flag(rankOk)+" | "+str.tostring(atrRank*100,"#.##")+"%",color.white)
f_row(9,"Warmup / capacity",f_flag(sourceBars > 240)+" / "+f_flag(capacityOk),color.white)
f_row(10,"Model state",pending ? "Confirmed / entry pending" : modelOpen > 0 ? "OPEN "+str.tostring(modelOpen) : "FLAT",color.aqua)
float displayEntry = pending and executeEvent ? close : entering and not barstate.isconfirmed ? open : modelEntry
float displaySL = pending and executeEvent ? close+6 : entering and not barstate.isconfirmed ? open+6 : modelSL
float displayTP = pending and executeEvent ? close-targetDistance : entering and not barstate.isconfirmed ? open-targetDistance : modelTP
f_row(11,"Newest entry ref / estimate",f_price(displayEntry),color.aqua)
f_row(12,"FIXED SL reference",f_price(displaySL),color.red)
f_row(13,"FIXED TP reference",f_price(displayTP),color.lime)
f_row(14,"Last event",lastEvent,color.white)
f_row(15,"Seed history",firstLoaded > seedTime ? "INCOMPLETE; signals may differ" : "Loaded; forward seed unconfirmed",color.orange)
f_row(16,"Short description",showDescription ? "EMA rejection; H1/H2/H4 bearish; NO trailing" : "Description hidden",color.silver)
f_row(17,"SOURCE historical WR",showStats ? "Train80%/40cap5; forward50%/16" : "Hidden; historical only",color.silver)
f_row(18,"TV partial historical WR",showStats ? "78.26%/23; shortened history" : "Hidden; not a forecast",color.silver)
f_row(19,"Date gate",dateOk ? "OPEN" : "OUTSIDE selected dates",color.silver)
else
table.clear(panel,0,0,1,19)