本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("VIBE QSFM-00220347 S v1.0 Trailing SL Indicator Pine", overlay=true, max_bars_back=500, max_labels_count=200)
// RECREATION NOTES — QSFM-00220347 S / short EMA rejection / Trailing SL.
// User requested this indicator after reviewing the partial TradingView test, 2026-10-19.
// TV Last365days: 43 trades,30 wins/13 losses,WR69.77%,net16507.67USD,
// PF2.27,intrabarDD3331.53USD. All43entrytimes/prices andexittimes match source;
// 42exitprices match. Report excludes30earlier source entries; full73TVunverified.
// Mar19 2026: new shortSL4708.655 alreadythroughmarket; TVnextopen4709.265
// vs source theoreticalSL. Coveredsource16610 -101.666667 executiondifference,
// thenqty166.66/166.6666667 => TV16507.67. Noentryrulechangeindicated.
// Originalsourceengine training replay VERIFIED:73trades,53wins/20losses,
// WR72.60274%,net33393.333333USD,closedDD2880.833333,Jan1 2025 23:00UTC
// throughMay27 2026 11:45UTC. Sourceforward27trades,15wins/12losses,
// WR55.55556%,net6677.50USD,closedDD3000,Jun3-Oct16 2026. NOT future forecasts.
// Capacity5 TRAINING vs capacity1 LIVE/FORWARD:trainingcap1would67trades/49wins,
// WR73.13%,net33245. Do not mislabel raw73statistics as cap1 performance.
// Source rawcap5thenforwardpostfiltercap1 is approximated bycap1generation;
// historicalforwardrecords report0rejections,but exact parity not guaranteed.
// Formula/source verification99,023actualM5bars:all122raweligible flags match.
// This new INDICATOR has NOT been TradingView-compiled/realtime-alert tested.
//
// UseSTANDARD OANDA:XAUUSD M5. DefaultLIVE,no expiry,source seedJun3 2026UTC.
// Originalbacktestmode seedJan1 2025 23UTC/endMay27 2026 11:45UTC/cap5.
// Forwardreferencemode seedJun3/endOct16 09:10UTC/cap1. No forcedendliquidation.
// SignalbarOPEN hour9UTC,weekdaysUTC;executeclose09:05..10UTC=16:05..17Bangkok.
// EXACT CLOSE SETUP:high>=currentM5EMA20,close<EMA20,close<open,
// abs(close-open)<=0.55ATR14,andcompletedH1close<H1EMA50. Rank120valid[0,1].
// M5EMA20 seedsfirstsourceclose,alpha2/21. ATR14firstTR=H-L,latertrueRange;
// meanfirst14TR thenWilder(alpha1/14). InclusiveATRrankcount<=current/120;
// firstvalidindex132. Firsteligiblesignalindex240(241stsourcebar).
// H1UTCbucketsrequire12M5bars;dropincomplete/skipEMAupdate;firstacceptedH1close
// seedsEMA50alpha2/51. FinalizeoldbucketatnextbucketOPENbeforecurrentbarinput;
// no developing/futureH1. NoH2/H4,momentum/RSIdirectional/range/retestfilters.
// Cooldown:signalOPEN-lastmodelENTRYOPEN>=30min,nextavailablebarOPENentry.
// Pendingentryreservesonecapacityslot;cap5modeeachentryownsitsstop/TP/bestlow.
//
// MANAGEMENT:shortfillE,initialSL=E+6,FIXEDTP=E-9. CheckOLDprotectionfirst;
// sourceconservativemodelSLwinsbothhit. IfsurvivingbestLow=min(previous,barLow).
// OnceE-bestLow>=6,nextSL=min(oldSL,bestLow+6). ApplyAFTERclose/NEXTbaronly.
// NeverraiseSL;TPNEVERTRAILS.Wicklowactivates evenifclosebounces.
// ExampleE4300:SL4306,TP4291;low4294=>nextSL4300;low4292=>4298,TP4291fixed.
// Nativecontinuousbrokertrailing,gapfills,chartmidpointvsbid/ask differ.
// AllmodellevelsareREFERENCEONLY:recomputeinitialSL/TPfromYOURactualfill;
// modelcannotread/submit/amendbrokerpositions.Ask/bid/spreadcancauseearlyfills.
//
// PREPARE:developingbar,bearish+bodyfilter+H1/session/history/date/cap/cooldown,
// hightouchesEMA20,close<=EMA20+0.50defaulttolerance. Provisionalheads-up,
// cancancel,NOTentryconditionandNOTprerequisiteforEXECUTE. Realtimeonly,
// variponce/barlatchresetbarstate.isnew;noinventedhistoricalpreparemarkers.
// EXECUTE:allEXACTconfirmedcloserules;pendingmodelentrynextbarOPEN;
// alertprice/SL/TPareESTIMATESfromsignalCLOSE,notfillconfirmation.
// MOVE SL:eachsurvivingconfirmedbarlowersastop,withtradeID,nextbarSL,fixedTP.
// MODEL EXIT:confirmedSL/TPcharttouch,notbrokerexitproof;honorbrokerprotection
// withoutwaitingfortheclosealert. Checkoldprotectionbeforetrail,entrybarincluded.
// Allalerts usealert()dynamicID/version/SHORT/symbol/M5/UTCtime/prices/notes,
// freq_allwithconfirmedguardsandpreparelatchallowsdistincteventsinonebar.
// CreateONEUIalert=Any alert() function call;4eventtogglesdefaultON.
// Recreateaftercode/inputs/symbol/timeframechanges;servercopiesdonotupdate.
// Array/modelstatecommitsonlyatconfirmedclose;previewnextbarOPENintrabar.
// Table/plots=NEWESTmodeltradeonly,allIDsmanagedseparatelyintrainingcap5;
// visualtoggles,tableanchor,shortdescriptiontoggle,historicalWRtoggleincluded.
// SourcefileSHA256:A81A040849646CA36782A69D03FCBDED27270D0CC1CEF3619CE207BB7138A90C
// EngineSHA256:81596b6cffc71687bd6410b7fba98e34073c0a6f5f202dfd4c5e74e8e425a27c
// OriginaldataSHA256:3c884014f08a8fbb46dbb984b6d14ab99a5b8e3b941a8eca5f51a7a731016c71
// Originalsource/phaseJSONs/verification/StrategyPine andmanual/recreationguide
// preservedalongside. Actualforwardseed/feedunconfirmed;loadseedhistory.
// SourceoperationslossCooldown60/loss-streakpausesnotimplementedenginefilters.
// Unusedlookback20/compression.55/momentum3*.8/retest.5/useH4Utc3false.
// Sourcefrequency4.35training/6.07forwardtrades/monthbelow10threshold;
// forwardconfidence=degrading. Userrequestauthorizesartifact,notbrokeractions.
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")
trailOn = input.bool(true,"MOVE SL alert",group="Alerts")
exitOn = input.bool(true,"MODEL EXIT alert",group="Alerts")
showEma = input.bool(true,"M5 EMA20",group="Display")
showH1 = input.bool(false,"Completed H1 EMA50",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,"Trade and stop-update 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 SOURCE 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 = 9.0
string tag = "VIBE QSFM-00220347 S v1.0 Trailing SL 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
// H1 source aggregation: strict full-count retained candles and first-close EMA.
var int h1Bucket = na
var int h1Count = 0
var float h1WorkingClose = na
var float h1Close = na
var float h1Ema50 = na
var int h1Start = na
if time >= seedTime
int nextBucket = int(math.floor(time/3600000))*3600000
if na(h1Bucket)
h1Bucket := nextBucket
else if nextBucket != h1Bucket
if h1Count >= 12
h1Close := h1WorkingClose
h1Ema50 := na(h1Ema50) ? h1WorkingClose : h1WorkingClose*(2.0/51)+h1Ema50*(1-2.0/51)
h1Start := h1Bucket
h1Bucket := nextBucket
h1Count := 0
h1Count += 1
h1WorkingClose := close
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") == 9 and dayofweek(time,"UTC") != dayofweek.saturday and dayofweek(time,"UTC") != dayofweek.sunday
bool htfOk = not na(h1Ema50) and h1Close < h1Ema50
bool rankOk = not na(atrRank) and atrRank >= 0 and atrRank <= 1
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 array<float> bests = 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-9 : not na(barEntry) ? barEntry-9 : na
bool executeEvent = false
bool exitEvent = false
bool trailEvent = 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)
array.push(bests,open)
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-9
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)
array.remove(bests,i)
else
float best = math.min(array.get(bests,i),low)
float nextSL = ep-best >= 6 ? math.min(sl,best+6) : sl
array.set(bests,i,best)
array.set(stops,i,nextSL)
if nextSL < sl
trailEvent := true
lastEvent := "Model "+id+" nextSL "+f_price(nextSL)
if trailOn
alert(f_alert("MOVE SL / NEXT BAR",id,ep,nextSL,tp,"Lower only; keep TP fixed. MODEL reference; actual fill differs. Best low "+f_price(best)),alert.freq_all)
if showLabels
label.new(bar_index,nextSL,id+" NEXT SL\n"+f_price(nextSL),style=label.style_label_left,color=color.orange,textcolor=color.black,size=size.tiny)
bool cool = na(lastEntryTime) or time-lastEntryTime >= 30*60000
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-9,"ESTIMATED from signal close. If entering next bar,reset SL=actual fill+6,TP=fill-9;trail starts at fill-6."),alert.freq_all)
varip bool preparedThisBar = false
if barstate.isnew
preparedThisBar := false
bool coolNow = na(lastEntryTime) or time-lastEntryTime >= 30*60000
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-9,"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-9 : na
plot(showEma ? ema20 : na,"Source M5 EMA20",color=color.blue)
plot(showH1 ? h1Ema50 : na,"Completed H1 EMA50",color=color.purple)
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 ? modelSL : na,"SL after close / next bar",color=color.orange,linewidth=2,style=plot.style_circles)
plot(showLevels ? barTP : na,"Fixed TP reference",color=color.lime,linewidth=2,style=plot.style_linebr)
plot(showLevels ? barEntry-6 : na,"Trailing activation reference",color=color.new(color.yellow,40),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,18,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-00220347 S","v1.0 Trailing SL Indicator Pine",color.white)
f_row(1,"Mode / capacity",mode+" / "+str.tostring(openCap),color.white)
f_row(2,"Signal hour9UTC",f_flag(sessionOk)+" | 16hBangkok",sessionOk ? color.lime : color.orange)
f_row(3,"Completed H1 bearish",f_flag(htfOk),htfOk ? color.lime : color.orange)
f_row(4,"High touches EMA20",f_flag(high >= ema20)+" | "+f_price(ema20),color.white)
f_row(5,"Bearish close below EMA",f_flag(close < open and close < ema20),color.white)
f_row(6,"Body <=0.55ATR",f_flag(bodyOk),color.white)
f_row(7,"Warmup / valid rank",f_flag(sourceBars > 240 and rankOk)+" | "+str.tostring(sourceBars)+" bars",color.white)
f_row(8,"30min / capacity",f_flag(coolNow)+" / "+f_flag(capacityOk),color.white)
f_row(9,"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-9 : entering and not barstate.isconfirmed ? open-9 : modelTP
f_row(10,"Newest entry ref / estimate",f_price(displayEntry),color.aqua)
f_row(11,"SL ref after close=new",f_price(displaySL),color.orange)
f_row(12,"Fixed TP reference",f_price(displayTP),color.lime)
f_row(13,"Last event",lastEvent,color.white)
f_row(14,"Seed history",firstLoaded > seedTime ? "INCOMPLETE; parity uncertain" : "Loaded; forward seed unconfirmed",color.orange)
f_row(15,"Short description",showDescription ? "EMA20 rejection; small body; H1 trend" : "Description hidden",color.silver)
f_row(16,"SOURCE historical WR",showStats ? "Train72.60%/73cap5; forward55.56%/27" : "Not a forecast; indicator check pending",color.silver)
f_row(17,"Date gate",dateOk ? "OPEN" : "OUTSIDE selected dates",color.silver)
else
table.clear(panel,0,0,1,17)