VIBE QSFM-00155037 S v1.0 Trailing SL Indicator Pine by Panduck

ittichai31 · study · 329 行 · 点赞 2 · TradingView 原页

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

Pine Script

//@version=6
indicator("VIBE QSFM-00155037 S v1.0 Trailing SL Indicator Pine", overlay=true, max_bars_back=500, max_labels_count=200)
// ============================================================================
// RECREATE/HANDOFF — QSFM-00155037 SHORT momentum_continuation, Trailing SL.
// User request2026-10-19:finishTHISstrategyonebyone;QSFM-00220347isUNCHECKED.
// StrategyPinecurrentv1.1;thisIndicatorhasindependentv1.0. Noautomaticpublishing.
// ORIGINALtrainingJan1 2025 23:00UTC..May27 2026 11:45UTC:21closed,
//16wins/5losses,WR76.190476%,net9612.50USD,closedDD3000,1.252trades/month.
// UnmodifiedoriginalJSengineandtranslatedsourceformulasreproducedall21trades
// from99,023originalM5bars. NativeTVfillscanlegitimatelydiffer.
// FORWARDJun3 2026 00:00UTC..Oct16 2026 09:10UTC(exclusive):8closed,
//6wins/2losses,WR75%,net5361USD,closedDD2000. UserTVv1.0matched8times/qty/PnL,
//7/8pricepairs;June24entry/exitboth0.145lower,unchanged1000loss.
// UserTVv1.1PARTIALLast365days:14trades12wins,WR85.714%,net10371,
//closedDD1000,intrabarDD1261. ThisisNOTthefull21-tradetrainingresult.
// All14entrytimes/pricesandexittimesmatchedsource#8..21;13/14exitprices/PnL.
// March4 2026 18:20UTCbothSL/TPtouched:QSFMstopfirst377.50profitvsTVTP2000.
// Fullsource9612.50-omittedearly7net864+exitdifference1622.50=TV10371.
// DoNOTpresent85.71%asoriginalWRorforecast. Full21-tradeTVwindowstillpending.
// HistoricalWRisNOTexpectedfutureaccuracy. Newindicatorcompile/alertsPENDING.
//
// SourcefileSHA256:A37788D9265503398996FD1FE8B3E2E6458B62DFBECF434A19CED15FE50C6642
// EngineSHA256:81596b6cffc71687bd6410b7fba98e34073c0a6f5f202dfd4c5e74e8e425a27c
// TrainingM5SHA256:3c884014f08a8fbb46dbb984b6d14ab99a5b8e3b941a8eca5f51a7a731016c71
// STANDARD OANDA:XAUUSD M5. DefaultLIVE,noenddate,seedJun3 2026UTC,cap1.
// Originalbacktestmode seedJan1 2025 23UTC/endMay27 2026 11:45UTC/cap1.
// Forwardreference seedJun3/endOct16 09:10UTC/cap1. Noendforcedliquidation.
// Sourceforwardseed/pricebasisunconfirmed. Loadchartseedhistory;indicatorcannot
// inheritStrategyReportDeepBacktesthistory. ChangingseedcanalterATR/HTFsignals.
//
// ALLconfirmedCLOSEentryrules (decisiontimestamp=BAROPEN):
//UTCopeninghour18;excludeSat/SunUTC.18UTC=01hNEXTDAYBangkok;confirmedexecute
//18:05..19:00UTC=01:05..02:00BangkokNEXTDAY. DoNOTshiftUTCweekdayfilter.
//momentum=close-close[3] STRICTLY < -0.8*currentATR14;currentclose<open;
//RSI14>28STRICT;ATRinclusiveRank120 in[0.40,0.95]INCLUSIVE.
//CompletedH1close<EMA50,H2close<EMA20,customH4UTC+3close<EMA50,ALLstrict.
//H1/H2anchorUTCoffset0;H4bucket=floor((time-3h)/4h)*4h+3h:
//starts03,07,11,15,19,23UTC,FIXEDoffset,notNewYorkDSTorbrokerdefaultH4.
//Requirefull12/24/48M5barsrespectively,discardpartialbuckets/skipEMAupdate.
//HTFEMAsseedfirstacceptedclose,alpha2/(len+1). CompletedHTFavailableatdecision
//BAROPEN>=bucketend:finalizepreviousbucketBEFOREingestingcurrentM5bar.
//ATR14:TRfirst=H-L;later=max(H-L,abs(H-prevC),abs(L-prevC));mean14TRseed
//atindex13,then(prevATR*13+TR)/14. Rankcountlast120validATR<=current/120,
//includingcurrent,tiesinclusive,validindex132. Firstsignalindex240/241stbar.
//RSI:meanfirst14closechangesatindex14;Wildergain/loss;avgLoss0=>100(flattoo).
//NoM5EMAtrend/RSIupper/body/range/retestfilter. EMAreadinessimplicitby241bars.
//Unusedlookback12/body.55/compression.55/retest.5donotjustifyextraentryfilters.
//30mincooldown=signalOPEN-lastmodelENTRYOPEN>=30min. Oneopen/pendingtrade.
//Confirmedclose->nextavailableM5OPENmodelentry. Nootherdaily/afterexitpause.
//SourceoperationslossCooldown60/twoLosspause5days/threeLossRemovearemetadata.
//
// MANAGEMENTshortactualfillE:initialSL=E+10,FIXEDTP=E-20,2R.
//OldSL/TPcheckedFIRST,entrybarincluded;sourceconservativeSLwinsbothhit.
//Onlyifsurviving,bestLow=min(previous,barLow);atE-bestLow>=10,
//nextSL=min(oldSL,bestLow+10). Loweronly,applyAFTERclose/NEXTbar. Wickactivates.
//TPNEVERTRAILS. ExampleE4300:SL4310,TP4280;low4290=>nextSL4300;
//low4285=>4295;TP4280unchanged. Nativecontinuousbrokertraildiffers.
//Chartmidpoint/modellevelsNOTbrokerfills.RecalculateSL/TPfromYOURactualfill;
//modecannotread/submit/amendbrokerorders. Actualbid/ask/gaps/costschangefills.
//
// PREPAREprovisionalcurrentbearishmomentum<-0.60ATR(defaultadjustable0..0.8),
//otherfilters/session/RSI/rank/HTF/history/date/cap/cooldownpass. Heads-upONLY,
//NOTtestedentryfilter/NOTprerequisiteforEXECUTE. Maycancel. Realtimeonly,
//once/barvariplatchresetbarstate.isnew. Historicalpreparecannotbereconstructed.
// EXECUTEallEXACTclosecriteria,estimatedSL/TPfromsignalCLOSEnotactualfill;
//MOVE SLconfirmedlowernewstop,nextbaronly;MODEL EXITconfirmedcharttouch,
//notproofbrokerexit. Keepbrokerprotectionactive,don'twaitforclosealerts.
//ONETradingViewUIalert:Any alert() function call. FourtogglesdefaultON.
//DynamicmessagesID/version/SHORT/symbol/M5/UTCdecisionclose/refprice/SL/TP.
//alert.freq_allpermitsseparateeventtypes;confirmedguards/preparelatchdedupe.
//Recreatealertaftercode/input/symbol/timeframechanges;servercopyisimmutable.
//Statechangesonlyonconfirmedclose;previewpendingnextbarOPENintrabar.
//Visualsentry/activeSL/nextSL/fixedTP/activation,signals/labels;tablelocation,
//shortdescriptiontoggle,optionalsourceWR. SourceUSD1000risk=>100goldunits,
//butindicatorgeneratesNOqtyrecommendationandplacesNOorders.
// Source and replay data,referenceJSONs,StrategyPinev1.1,manual,recreationguide,
// priorTVreviews preservedinQSFM-00155037-SunderuserChatGPTWorkingFolder.
// NumericalmodelchecksnotPinecompiler/realtimeproof. DooneIDatatime.
// ============================================================================
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 = 1
prepareOn = input.bool(true,"PREPARE alert",group="Alerts")
prepareMultiplier = input.float(0.6,"Prepare momentum ATR multiplier (early only)",minval=0,maxval=0.8,step=0.05,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")
showHtf = input.bool(false,"Completed H1/H2/H4 EMA lines",group="Display")
showLevels = input.bool(true,"Model entry / SL / TP / activation",group="Display")
showSignals = input.bool(true,"Execute and model exit markers",group="Display")
showLabels = input.bool(true,"Entry and stop-update labels",group="Display")
showPrepare = input.bool(true,"Provisional prepare highlight",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 WR (not forecasts)",group="Display")
anchor = input.string("Top right","Table anchor",options=["Top right","Top left","Bottom right","Bottom left"],group="Display")
float stopDistance = 10.0
float targetDistance = 20.0
string tag = "VIBE QSFM-00155037 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 QSFM-00155037.")
var int firstLoaded = time
 
// 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)
 
var int sourceBars = 0
var float trSum = 0.0
var float atr14 = na
var float avgGain = 0.0
var float avgLoss = 0.0
float rsi14 = na
if time >= seedTime
    sourceBars += 1
    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
    if sourceBars > 1
        float change = close-close[1]
        float gain = math.max(change,0)
        float loss = math.max(-change,0)
        if sourceBars <= 15
            avgGain += gain
            avgLoss += loss
            if sourceBars == 15
                avgGain /= 14
                avgLoss /= 14
        else
            avgGain := (avgGain*13+gain)/14
            avgLoss := (avgLoss*13+loss)/14
        if sourceBars >= 15
            rsi14 := avgLoss == 0 ? 100 : 100-100/(1+avgGain/avgLoss)
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 htfOk = not na(h1Ema) and not na(h2Ema) and not na(h4Ema) and h1Close < h1Ema and h2Close < h2Ema and h4Close < h4Ema
bool sessionOk = hour(time,"UTC") == 18 and dayofweek(time,"UTC") != dayofweek.saturday and dayofweek(time,"UTC") != dayofweek.sunday
bool atrOk = not na(atrRank) and atrRank >= 0.4 and atrRank <= 0.95
float momentum = close-close[3]
bool momentumOk = momentum < -atr14*0.8
bool rsiOk = not na(rsi14) and rsi14 > 28
bool criteria = sourceBars > 240 and sessionOk and htfOk and atrOk and momentumOk and rsiOk and close < open
 
 
// 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+10 : previousSize > 0 ? array.get(stops,previousSize-1) : na
float barTP = entering ? open-20 : not na(barEntry) ? barEntry-20 : 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+10)
        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-20
            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 >= 10 ? math.min(sl,best+10) : 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+10,close-20,"ESTIMATED from signal close. If entering next bar,reset SL=actual fill+10,TP=fill-20;trail starts at fill-10."),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) < 1
bool prepareNow = sourceBars > 240 and dateOk and sessionOk and htfOk and atrOk and rsiOk and close < open and momentum < -atr14*prepareMultiplier 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+10,close-20,"Do not enter yet. Wait for confirmed EXECUTE. Developing momentum may 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-20 : na
plot(showHtf ? h1Ema : na,"Completed H1 EMA50",color=color.blue)
plot(showHtf ? h2Ema : na,"Completed H2 EMA20",color=color.purple)
plot(showHtf ? h4Ema : na,"Completed custom H4 EMA50",color=color.gray)
plot(showLevels ? barEntry : na,"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-10 : na,"Trailing activation reference",color=color.new(color.yellow,40),style=plot.style_linebr)
plot(atrRank,"ATR inclusive rank",display=display.data_window)
plot(rsi14,"Source RSI14",display=display.data_window)
plot(momentum,"Three-bar price momentum",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-00155037 S","v1.0 Trailing SL Indicator Pine",color.white)
        f_row(1,"Mode / one model position",mode,color.white)
        f_row(2,"Signal hour18UTC",f_flag(sessionOk)+" | 01h NEXT DAY Bangkok",sessionOk ? color.lime : color.orange)
        f_row(3,"Completed H1 close<EMA50",f_flag(not na(h1Ema) and h1Close < h1Ema),color.white)
        f_row(4,"Completed H2 close<EMA20",f_flag(not na(h2Ema) and h2Close < h2Ema),color.white)
        f_row(5,"Custom H4 close<EMA50",f_flag(not na(h4Ema) and h4Close < h4Ema),color.white)
        f_row(6,"ATR rank0.40..0.95",f_flag(atrOk)+" | "+str.tostring(atrRank,"#.000"),color.white)
        f_row(7,"Momentum < -0.8ATR",f_flag(momentumOk)+" | "+f_price(momentum),color.white)
        f_row(8,"RSI>28 / bearish",f_flag(rsiOk)+" / "+f_flag(close < open),color.white)
        f_row(9,"Warmup / 30min / flat",f_flag(sourceBars > 240)+" / "+f_flag(coolNow)+" / "+f_flag(capacityOk),color.white)
        f_row(10,"Model state",pending ? "Confirmed / entry pending" : modelOpen > 0 ? "OPEN" : "FLAT",color.aqua)
        float displayEntry = pending and executeEvent ? close : entering and not barstate.isconfirmed ? open : modelEntry
        float displaySL = pending and executeEvent ? close+10 : entering and not barstate.isconfirmed ? open+10 : modelSL
        float displayTP = pending and executeEvent ? close-20 : entering and not barstate.isconfirmed ? open-20 : modelTP
        f_row(11,"Entry ref / estimate",f_price(displayEntry),color.aqua)
        f_row(12,"SL ref after close=new",f_price(displaySL),color.orange)
        f_row(13,"Fixed TP reference",f_price(displayTP),color.lime)
        f_row(14,"Trail activation reference",f_price(displayEntry-10),color.yellow)
        f_row(15,"Completed custom H4 start",na(h4Start) ? "n/a" : str.format_time(h4Start,"yyyy-MM-dd HH:mm","UTC")+"UTC",color.silver)
        f_row(16,"Seed history",firstLoaded > seedTime ? "INCOMPLETE; parity uncertain" : "Loaded; forward seed unconfirmed",color.orange)
        f_row(17,"Last event",lastEvent,color.white)
        f_row(18,"Short method",showDescription ? "3-bar momentum; RSI; ATR band; H1/H2/H4" : "Description hidden",color.silver)
        f_row(19,"SOURCE historical WR",showStats ? "Training76.19%/21; forward75%/8" : "Not a forecast; indicator TV test pending",color.silver)
    else
        table.clear(panel,0,0,1,19)

← 返回列表