XAUUSD Traffic Lights + Doji + Daily Overall + 5-Factor Bias V33

andy_j_k · study · 755 行 · 点赞 19 · TradingView 原页

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

Pine Script

//@version=6
import TradingView/LibraryCOT/6 as cot
// VERSION 33: STRICT EMA-RESPECT TWO-CANDLE DOJI SETUPS.
// BUY requires bearish pullback THEN bullish wick rejection.
// SELL requires bullish pullback THEN bearish wick rejection.
// No multi-candle zone, breakout or momentum-only signals exist.
// Alerts fire ONLY at the confirmation candle's close.
// V33 uses confirmed MTF snapshots; scores are heuristics, not certainties.
indicator("XAUUSD Traffic Lights + Doji + Daily Overall + 5-Factor Bias V33", overlay=true, max_lines_count=2, max_labels_count=500, precision=2)
 
// ==========================================================
// 1. LIVE DISTANCE LINES: USER CONVENTION, 1 GOLD PIP = 0.10
// ==========================================================
pipGroup = "Live price-distance lines"
pips = input.int(60, "Distance in pips", minval=1, group=pipGroup)
pipSize = input.float(0.10, "Gold price movement per pip", minval=0.01, step=0.01, group=pipGroup)
 
// ==========================================================
// 2. EMA TRAFFIC LIGHTS + VWAP
// ==========================================================
ema50 = ta.ema(close, 50)
ema100 = ta.ema(close, 100)
ema200 = ta.ema(close, 200)
vwapValue = ta.vwap(hlc3)
 
plot(ema50, "50 EMA", color=color.lime, linewidth=2)
plot(ema100, "100 EMA", color=color.orange, linewidth=2)
plot(ema200, "200 EMA", color=color.red, linewidth=2)
plot(vwapValue, "VWAP", color=color.purple, linewidth=2)
 
bullStack = ema50 > ema100 and ema100 > ema200
bearStack = ema50 < ema100 and ema100 < ema200
upperColor = bullStack ? color.lime : bearStack ? color.red : color.gray
lowerColor = bearStack ? color.lime : bullStack ? color.red : color.gray
upperPrice = close + pips * pipSize
lowerPrice = close - pips * pipSize
var line upperLine = line.new(na, na, na, na, extend=extend.right, width=3)
var line lowerLine = line.new(na, na, na, na, extend=extend.right, width=3)
line.set_xy1(upperLine, bar_index, upperPrice)
line.set_xy2(upperLine, bar_index + 1, upperPrice)
line.set_color(upperLine, upperColor)
line.set_xy1(lowerLine, bar_index, lowerPrice)
line.set_xy2(lowerLine, bar_index + 1, lowerPrice)
line.set_color(lowerLine, lowerColor)
plot(upperPrice, "Upper live distance", color=upperColor, display=display.price_scale)
plot(lowerPrice, "Lower live distance", color=lowerColor, display=display.price_scale)
 
// ==========================================================
// 3. STRICT TWO-CANDLE ENTRIES: M1 OR M5 ONLY
// The candle immediately before the rejection must have
// the opposite colour, a substantial body and enough volume.
// A signal is NEVER based on a bullish/bearish candle
// several bars back. No momentum-only triggers are allowed.
// ==========================================================
entryGroup = "Two-candle EMA/VWAP entries"
showBuys = input.bool(true, "Show BUY labels", group=entryGroup)
showSells = input.bool(true, "Show SELL labels", group=entryGroup)
allowVWAP = input.bool(true, "Allow VWAP as an entry level", group=entryGroup)
nearPips = input.float(4.0, "Either wick within (pips)", minval=0, maxval=20, step=0.5, group=entryGroup)
// Both candle closes MUST remain on the correct side of the target line.
// No extra pip tolerance is allowed; only half a minimum tick is used
// internally for floating-point price comparisons.
useNearestTarget = input.bool(true, "Use closest EMA/VWAP to pullback CLOSE", group=entryGroup)
showMatchedLevel = input.bool(false, "Show matched line under BUY/SELL label", group=entryGroup)
maxEntryDistanceATR = input.float(0.90, "Maximum signal distance from level / ATR", minval=0.20, maxval=3, step=0.05, group=entryGroup)
minImpulseATR1 = input.float(0.50, "M1 previous candle BODY / ATR", minval=0.10, maxval=3, step=0.05, group=entryGroup)
minImpulseATR5 = input.float(0.55, "M5 previous candle BODY / ATR", minval=0.10, maxval=3, step=0.05, group=entryGroup)
minImpulseBodyShare = input.float(0.55, "Previous candle BODY / full range", minval=0.10, maxval=1, step=0.05, group=entryGroup)
requireVolume = input.bool(true, "Require volume on immediately preceding candle", group=entryGroup)
volumeMultiple = input.float(0.80, "Previous candle volume / earlier 20-bar mean", minval=0.10, maxval=4, step=0.05, group=entryGroup)
cooldownBars = input.int(0, "Minimum bars between same-direction alerts", minval=0, maxval=30, group=entryGroup)
 
// ==========================================================
// 4. TREND FILTER: SPACED EMAS AND SLOWER EMA DIRECTION
// Unlike V21, do NOT require EMA50 to slope throughout a
// pullback, since it may flatten or curl during a valid retest.
// EMA100 and EMA200 must still slope in trend direction.
// ==========================================================
trendGroup = "Trending market filter"
requireTrend = input.bool(true, "Require EMA spread and trend direction", group=trendGroup)
minGap50_100_M1 = input.float(0.20, "M1 gap 50-100 / ATR", minval=0, maxval=3, step=0.05, group=trendGroup)
minGap100_200_M1 = input.float(0.25, "M1 gap 100-200 / ATR", minval=0, maxval=3, step=0.05, group=trendGroup)
minGap50_100_M5 = input.float(0.25, "M5 gap 50-100 / ATR", minval=0, maxval=3, step=0.05, group=trendGroup)
minGap100_200_M5 = input.float(0.30, "M5 gap 100-200 / ATR", minval=0, maxval=3, step=0.05, group=trendGroup)
trendSlopeBars = input.int(7, "EMA slope lookback", minval=2, maxval=25, group=trendGroup)
minSlope100ATR = input.float(0.04, "Minimum EMA100 slope / ATR", minval=0, maxval=2, step=0.01, group=trendGroup)
minSlope200ATR = input.float(0.01, "Minimum EMA200 slope / ATR", minval=0, maxval=2, step=0.01, group=trendGroup)
 
// ==========================================================
// 4A. ADDITIONAL TREND-QUALITY CLASSIFICATION - NON BLOCKING
// IMPORTANT: This does NOT alter V27 BUY/SELL entry criteria.
// Every entry qualifying under original V27 remains a signal.
// Entries failing these MORE demanding filters get REVIEW label.
// ==========================================================
qualityGroup = "Signal quality (does not block entries)"
showReviewLabels = input.bool(true, "Show REVIEW entries as well as STRONG", group=qualityGroup)
showQualityWords = input.bool(true, "Show STRONG / REVIEW in labels", group=qualityGroup)
qualityGap1M1 = input.float(0.25, "STRONG M1 minimum 50-100 gap / ATR", minval=0.0, maxval=3.0, step=0.05, group=qualityGroup)
qualityGap2M1 = input.float(0.30, "STRONG M1 minimum 100-200 gap / ATR", minval=0.0, maxval=3.0, step=0.05, group=qualityGroup)
qualityGap1M5 = input.float(0.30, "STRONG M5 minimum 50-100 gap / ATR", minval=0.0, maxval=3.0, step=0.05, group=qualityGroup)
qualityGap2M5 = input.float(0.35, "STRONG M5 minimum 100-200 gap / ATR", minval=0.0, maxval=3.0, step=0.05, group=qualityGroup)
qualitySlope100 = input.float(0.06, "STRONG minimum EMA100 slope / ATR", minval=0.0, maxval=2.0, step=0.01, group=qualityGroup)
qualitySlope200 = input.float(0.02, "STRONG minimum EMA200 slope / ATR", minval=0.0, maxval=2.0, step=0.01, group=qualityGroup)
qualityUseADX = input.bool(true, "Use ADX for STRONG classification", group=qualityGroup)
qualityDiLength = input.int(14, "ADX DI length", minval=2, maxval=50, group=qualityGroup)
qualityAdxSmoothing = input.int(14, "ADX smoothing", minval=2, maxval=50, group=qualityGroup)
qualityMinADX1 = input.float(20.0, "STRONG M1 minimum ADX", minval=5.0, maxval=60.0, step=0.5, group=qualityGroup)
qualityMinADX5 = input.float(22.0, "STRONG M5 minimum ADX", minval=5.0, maxval=60.0, step=0.5, group=qualityGroup)
qualityRequireDI = input.bool(false, "STRONG also needs directional DI agreement", group=qualityGroup)
 
// ==========================================================
// 5. STOCH RSI - ADVISORY BY DEFAULT; OPTIONAL REQUIRED
// ==========================================================
stochGroup = "Stochastic RSI"
stochMode = input.string("Advisory", "Stoch RSI mode", options=["Advisory", "Required", "Off"], group=stochGroup)
rsiLength = input.int(14, "RSI length", minval=2, group=stochGroup)
stochLength = input.int(14, "Stoch length", minval=2, group=stochGroup)
smoothK = input.int(3, "K smoothing", minval=1, group=stochGroup)
smoothD = input.int(3, "D smoothing", minval=1, group=stochGroup)
stochOversold = input.float(20, "BUY K oversold threshold", minval=0, maxval=50, group=stochGroup)
stochOverbought = input.float(80, "SELL K overbought threshold", minval=50, maxval=100, group=stochGroup)
 
rsiValue = ta.rsi(close, rsiLength)
rsiLowest = ta.lowest(rsiValue, stochLength)
rsiHighest = ta.highest(rsiValue, stochLength)
rawStoch = rsiHighest > rsiLowest ? 100 * (rsiValue - rsiLowest) / (rsiHighest - rsiLowest) : 50.0
stochK = ta.sma(rawStoch, smoothK)
stochD = ta.sma(stochK, smoothD)
buyStochOK = stochMode != "Required" or (not na(stochK) and stochK <= stochOversold or not na(stochK[1]) and stochK[1] <= stochOversold)
sellStochOK = stochMode != "Required" or (not na(stochK) and stochK >= stochOverbought or not na(stochK[1]) and stochK[1] >= stochOverbought)
plot(stochK, "Stoch RSI K (Data Window)", display=display.data_window)
plot(stochD, "Stoch RSI D (Data Window)", display=display.data_window)
 
// ==========================================================
// 6. TREND, IMMEDIATE PRIOR CANDLE AND REJECTION SHAPE
// ==========================================================
validTF = timeframe.isminutes and (timeframe.multiplier == 1 or timeframe.multiplier == 5)
atrValue = ta.atr(14)
atrSafe = math.max(nz(atrValue, syminfo.mintick), syminfo.mintick)
volumeAverage = ta.sma(volume, 20)
wickGap = nearPips * pipSize
closeGap = syminfo.mintick * 0.5
minImpulseATR = timeframe.multiplier == 1 ? minImpulseATR1 : minImpulseATR5
minGapFirst = timeframe.multiplier == 1 ? minGap50_100_M1 : minGap50_100_M5
minGapSecond = timeframe.multiplier == 1 ? minGap100_200_M1 : minGap100_200_M5
emaGapFirst = math.abs(ema50 - ema100) / atrSafe
emaGapSecond = math.abs(ema100 - ema200) / atrSafe
emaSlope100 = (ema100 - ema100[trendSlopeBars]) / atrSafe
emaSlope200 = (ema200 - ema200[trendSlopeBars]) / atrSafe
spreadOK = not na(emaGapFirst) and not na(emaGapSecond) and emaGapFirst >= minGapFirst and emaGapSecond >= minGapSecond
bullDirectionOK = not na(emaSlope100) and not na(emaSlope200) and emaSlope100 >= minSlope100ATR and emaSlope200 >= minSlope200ATR
bearDirectionOK = not na(emaSlope100) and not na(emaSlope200) and emaSlope100 <= -minSlope100ATR and emaSlope200 <= -minSlope200ATR
buyTrendOK = not requireTrend or (spreadOK and bullDirectionOK)
sellTrendOK = not requireTrend or (spreadOK and bearDirectionOK)
 
// Classification uses MORE demanding V28-style conditions, but
// these booleans are NEVER used to determine buySignal/sellSignal.
// ADX and DI are taken from the preceding COMPLETED candle.
[qualityPlusDI, qualityMinusDI, qualityADX] = ta.dmi(qualityDiLength, qualityAdxSmoothing)
qualityFirstGap = timeframe.multiplier == 1 ? qualityGap1M1 : qualityGap1M5
qualitySecondGap = timeframe.multiplier == 1 ? qualityGap2M1 : qualityGap2M5
qualityNeededADX = timeframe.multiplier == 1 ? qualityMinADX1 : qualityMinADX5
qualityGapsOK = not na(emaGapFirst) and not na(emaGapSecond) and emaGapFirst >= qualityFirstGap and emaGapSecond >= qualitySecondGap
qualityADXOK = not qualityUseADX or (not na(qualityADX[1]) and qualityADX[1] >= qualityNeededADX)
qualityBullDI = not qualityRequireDI or (not na(qualityPlusDI[1]) and not na(qualityMinusDI[1]) and qualityPlusDI[1] > qualityMinusDI[1])
qualityBearDI = not qualityRequireDI or (not na(qualityPlusDI[1]) and not na(qualityMinusDI[1]) and qualityMinusDI[1] > qualityPlusDI[1])
qualityBuyStrong = qualityGapsOK and qualityADXOK and qualityBullDI and not na(emaSlope100) and not na(emaSlope200) and emaSlope100 >= qualitySlope100 and emaSlope200 >= qualitySlope200
qualitySellStrong = qualityGapsOK and qualityADXOK and qualityBearDI and not na(emaSlope100) and not na(emaSlope200) and emaSlope100 <= -qualitySlope100 and emaSlope200 <= -qualitySlope200
 
// Previous candle MUST be a sizable opposite-colour candle.
previousBody = math.abs(close[1] - open[1])
previousSpan = math.max(high[1] - low[1], syminfo.mintick)
previousBodyShare = previousBody / previousSpan
priorSizeOK = not na(atrValue[1]) and previousBody >= minImpulseATR * atrValue[1] and previousBodyShare >= minImpulseBodyShare
// ta.sma(volume, 20)[2] covers the 20 candles BEFORE the prior candle.
priorVolMean = volumeAverage[2]
priorVolumeOK = not requireVolume or (not na(volume[1]) and not na(priorVolMean) and priorVolMean > 0 and volume[1] >= volumeMultiple * priorVolMean)
previousBearish = close[1] < open[1]
previousBullish = close[1] > open[1]
buyPullbackOK = previousBearish and priorSizeOK and priorVolumeOK
sellPullbackOK = previousBullish and priorSizeOK and priorVolumeOK
 
// Only the candle IMMEDIATELY AFTER the strong pullback can signal.
// No momentum-only or multi-candle Z entry can bypass this shape.
// BUY: a green rejection candle with the lower wick longer than
// both its real body and its upper wick (equal opposing wick allowed).
// SELL: a red rejection candle with the upper wick longer than
// both its real body and its lower wick (equal opposing wick allowed).
// Set wick/body to 1.00 for your original strict "wick > body" rule.
rejectionGroup = "Rejection candle wick requirements"
minWickBodyRatio = input.float(1.00, "Main wick must exceed body by ratio", minval=1.00, maxval=3.00, step=0.05, group=rejectionGroup)
 
realBody = math.abs(close - open)
upperWick = high - math.max(open, close)
lowerWick = math.min(open, close) - low
priceEpsilon = syminfo.mintick / 2.0
buyRejection = close > open and lowerWick > realBody * minWickBodyRatio and lowerWick + priceEpsilon >= upperWick
sellRejection = close < open and upperWick > realBody * minWickBodyRatio and upperWick + priceEpsilon >= lowerWick
 
// ==========================================================
// 7. STRICT SAME-LINE RESPECT: BOTH CLOSES ON CORRECT SIDE
// ==========================================================
// The FIRST candle must move towards the selected EMA/VWAP.
// Its CLOSE must respect the line. The NEXT rejection doji must
// also CLOSE on the correct side of that exact same line.
// A wick on either candle may cross the line. At least one wick
// must touch or be no more than 4 user-defined pips away.
// This requires actual proximity; a wick far beyond a level
// no longer counts automatically as a valid test.
//
// By default, only the line nearest to the pullback's closing
// price is considered. A farther EMA/VWAP cannot silently
// substitute when the closer level was broken by the candle.
f_twoCandleLevel(float level, bool isBuy) =>
    bool available = not na(level) and not na(level[1])
    bool priorRespects = available and (isBuy ? close[1] >= level[1] - closeGap : close[1] <= level[1] + closeGap)
    bool dojiRespects = available and (isBuy ? close >= level - closeGap : close <= level + closeGap)
    bool priorApproaches = available and math.abs(close[1] - level[1]) <= math.abs(open[1] - level[1]) + syminfo.mintick * 0.5
    bool firstWickNear = available and low[1] <= level[1] + wickGap and high[1] >= level[1] - wickGap
    bool dojiWickNear = available and low <= level + wickGap and high >= level - wickGap
    bool touchedOrNear = firstWickNear or dojiWickNear
    float closingDistance = isBuy ? close - level : level - close
    bool nearOnCorrectSide = available and closingDistance >= -closeGap and closingDistance <= maxEntryDistanceATR * atrSafe
    priorRespects and dojiRespects and priorApproaches and touchedOrNear and nearOnCorrectSide
 
// Find the closest EMA/VWAP to the bearish/bullish pullback
// candle's close, including levels which the candle broke.
// If the closest one was broken, the setup is rejected rather
// than silently qualifying against a more distant lower line.
float farAway = 1000000000.0
float d50 = not na(ema50[1]) ? math.abs(close[1] - ema50[1]) : farAway
float d100 = not na(ema100[1]) ? math.abs(close[1] - ema100[1]) : farAway
float d200 = not na(ema200[1]) ? math.abs(close[1] - ema200[1]) : farAway
float dVWAP = allowVWAP and not na(vwapValue[1]) ? math.abs(close[1] - vwapValue[1]) : farAway
float closestLineDistance = math.min(math.min(d50, d100), math.min(d200, dVWAP))
float tieTol = syminfo.mintick * 0.5
bool choose50 = not useNearestTarget or d50 <= closestLineDistance + tieTol
bool choose100 = not useNearestTarget or d100 <= closestLineDistance + tieTol
bool choose200 = not useNearestTarget or d200 <= closestLineDistance + tieTol
bool chooseVWAP = not useNearestTarget or dVWAP <= closestLineDistance + tieTol
 
// Evaluate every history-dependent function on every bar before
// applying the nearest-target selection.
bool rawBuy50 = f_twoCandleLevel(ema50, true)
bool rawBuy100 = f_twoCandleLevel(ema100, true)
bool rawBuy200 = f_twoCandleLevel(ema200, true)
bool rawBuyVWAP = f_twoCandleLevel(vwapValue, true)
bool rawSell50 = f_twoCandleLevel(ema50, false)
bool rawSell100 = f_twoCandleLevel(ema100, false)
bool rawSell200 = f_twoCandleLevel(ema200, false)
bool rawSellVWAP = f_twoCandleLevel(vwapValue, false)
 
buy50 = choose50 and rawBuy50
buy100 = choose100 and rawBuy100
buy200 = choose200 and rawBuy200
buyVWAP = allowVWAP and chooseVWAP and rawBuyVWAP
sell50 = choose50 and rawSell50
sell100 = choose100 and rawSell100
sell200 = choose200 and rawSell200
sellVWAP = allowVWAP and chooseVWAP and rawSellVWAP
 
buyLevelOK = buy50 or buy100 or buy200 or buyVWAP
sellLevelOK = sell50 or sell100 or sell200 or sellVWAP
string buyMatched = buy50 ? "50 EMA" : buy100 ? "100 EMA" : buy200 ? "200 EMA" : buyVWAP ? "VWAP" : "None"
string sellMatched = sell50 ? "50 EMA" : sell100 ? "100 EMA" : sell200 ? "200 EMA" : sellVWAP ? "VWAP" : "None"
 
// ==========================================================
// 8. SIGNALS: NO HISTORICAL REPOSITIONING, NO LOOKAHEAD
// A label belongs to the candle whose CLOSE confirms it.
// ==========================================================
var int lastBuyBar = na
var int lastSellBar = na
bool buyCooldownOK = na(lastBuyBar) or bar_index - lastBuyBar > cooldownBars
bool sellCooldownOK = na(lastSellBar) or bar_index - lastSellBar > cooldownBars
buySignal = validTF and barstate.isconfirmed and bullStack and buyTrendOK and buyPullbackOK and buyRejection and buyLevelOK and buyStochOK and buyCooldownOK
sellSignal = validTF and barstate.isconfirmed and bearStack and sellTrendOK and sellPullbackOK and sellRejection and sellLevelOK and sellStochOK and sellCooldownOK
 
if buySignal
    lastBuyBar := bar_index
if sellSignal
    lastSellBar := bar_index
 
// Each original V27 entry is still emitted on exactly the same bar.
// Only its presentation and available alert categories change.
buyStrongSignal = buySignal and qualityBuyStrong
sellStrongSignal = sellSignal and qualitySellStrong
buyReviewSignal = buySignal and not qualityBuyStrong
sellReviewSignal = sellSignal and not qualitySellStrong
 
if buySignal and showBuys and (qualityBuyStrong or showReviewLabels)
    string buyCaption = showQualityWords ? (qualityBuyStrong ? "BUY STRONG" : "BUY REVIEW") : "BUY"
    string buyLabel = showMatchedLevel ? buyCaption + "\n" + buyMatched : buyCaption
    label.new(bar_index, low, buyLabel, style=label.style_label_up, color=qualityBuyStrong ? color.lime : color.new(color.lime, 65), textcolor=qualityBuyStrong ? color.black : color.white, size=size.small)
if sellSignal and showSells and (qualitySellStrong or showReviewLabels)
    string sellCaption = showQualityWords ? (qualitySellStrong ? "SELL STRONG" : "SELL REVIEW") : "SELL"
    string sellLabel = showMatchedLevel ? sellCaption + "\n" + sellMatched : sellCaption
    label.new(bar_index, high, sellLabel, style=label.style_label_down, color=qualitySellStrong ? color.red : color.new(color.red, 65), textcolor=color.white, size=size.small)
 
// ==========================================================
// 9. DIAGNOSTICS AND ALERTS
// ==========================================================
debugGroup = "Diagnostics"
showBlocked = input.bool(false, "Explain blocked rejection candles", group=debugGroup)
if showBlocked and validTF and barstate.isconfirmed and buyRejection and not buySignal
    string reason = not bullStack ? "EMA order" : not buyTrendOK ? "EMA spread/slope" : not previousBearish ? "Previous not bearish" : not priorSizeOK ? "Previous body too small" : not priorVolumeOK ? "Previous volume" : not buyLevelOK ? "EMA close/target/proximity" : not buyStochOK ? "Stoch RSI" : "Cooldown"
    label.new(bar_index, low, "BUY blocked: " + reason, style=label.style_label_up, color=color.new(color.gray, 40), textcolor=color.white, size=size.tiny)
if showBlocked and validTF and barstate.isconfirmed and sellRejection and not sellSignal
    string reason = not bearStack ? "EMA order" : not sellTrendOK ? "EMA spread/slope" : not previousBullish ? "Previous not bullish" : not priorSizeOK ? "Previous body too small" : not priorVolumeOK ? "Previous volume" : not sellLevelOK ? "EMA close/target/proximity" : not sellStochOK ? "Stoch RSI" : "Cooldown"
    label.new(bar_index, high, "SELL blocked: " + reason, style=label.style_label_down, color=color.new(color.gray, 40), textcolor=color.white, size=size.tiny)
 
plot(emaGapFirst, "Trend 50-100 gap / ATR", display=display.data_window)
plot(emaGapSecond, "Trend 100-200 gap / ATR", display=display.data_window)
plot(emaSlope100, "Trend EMA100 slope / ATR", display=display.data_window)
plot(emaSlope200, "Trend EMA200 slope / ATR", display=display.data_window)
plot(previousBodyShare, "Previous candle body / range", display=display.data_window)
plot(qualityADX, "Trend quality ADX", display=display.data_window)
plot(qualityNeededADX, "STRONG ADX threshold", display=display.data_window)
plot(qualityGapsOK ? 1.0 : 0.0, "STRONG EMA gaps qualify (1/0)", display=display.data_window)
plot(qualityBuyStrong ? 1.0 : 0.0, "STRONG BUY environment (1/0)", display=display.data_window)
plot(qualitySellStrong ? 1.0 : 0.0, "STRONG SELL environment (1/0)", display=display.data_window)
plot(closestLineDistance / pipSize, "Nearest EMA/VWAP to pullback close (pips)", display=display.data_window)
plot(buy50 or sell50 ? 50.0 : buy100 or sell100 ? 100.0 : buy200 or sell200 ? 200.0 : buyVWAP or sellVWAP ? 999.0 : na, "Matched level (50/100/200, 999=VWAP)", display=display.data_window)
 
alertcondition(buySignal, "V33 XAUUSD BUY", "XAUUSD BUY confirmed on {{ticker}} {{interval}} at {{close}}")
alertcondition(sellSignal, "V33 XAUUSD SELL", "XAUUSD SELL confirmed on {{ticker}} {{interval}} at {{close}}")
alertcondition(buySignal or sellSignal, "V33 XAUUSD BUY or SELL", "XAUUSD EMA/VWAP rejection confirmed on {{ticker}} {{interval}} at {{close}}")
alertcondition(buyStrongSignal, "V33 STRONG BUY", "XAUUSD STRONG BUY {{ticker}} {{interval}} at {{close}}")
alertcondition(sellStrongSignal, "V33 STRONG SELL", "XAUUSD STRONG SELL {{ticker}} {{interval}} at {{close}}")
alertcondition(buyReviewSignal, "V33 REVIEW BUY", "XAUUSD REVIEW BUY {{ticker}} {{interval}} at {{close}}")
alertcondition(sellReviewSignal, "V33 REVIEW SELL", "XAUUSD REVIEW SELL {{ticker}} {{interval}} at {{close}}")
if buySignal
    alert((qualityBuyStrong ? "XAUUSD BUY STRONG | " : "XAUUSD BUY REVIEW | ") + syminfo.ticker + " | " + timeframe.period + " | " + str.tostring(close, format.mintick) + " | Stoch K " + str.tostring(stochK, "#.0"), alert.freq_once_per_bar_close)
if sellSignal
    alert((qualitySellStrong ? "XAUUSD SELL STRONG | " : "XAUUSD SELL REVIEW | ") + syminfo.ticker + " | " + timeframe.period + " | " + str.tostring(close, format.mintick) + " | Stoch K " + str.tostring(stochK, "#.0"), alert.freq_once_per_bar_close)
 
// ==========================================================
// 10. SYNCHRONISED TREND DASHBOARD - FIVE CONFLUENCES
// On a higher-timeframe CHART, use security_lower_tf() for M1/M5.
// Historical intrabars are sorted; select the latest available one.
// Each requested intrabar carries its PREVIOUS completed candle value.
// For equal/higher requested timeframes, use lookahead_on WITH [1].
// This avoids V32's first-intrabar discrepancy on M15 charts.
// All dashboard classification is ADVISORY ONLY; no entry gate.
// ==========================================================
panelGroup = "Compact confirmed trend dashboard V33"
showTrendPanel = input.bool(true, "Show bottom-right dashboard", group=panelGroup)
minBiasScore = input.float(5.5, "Minimum directional confluence score / 10", minval=2.0, maxval=9.0, step=0.5, group=panelGroup)
minDominance = input.float(1.5, "Minimum score lead over opposing direction", minval=0.0, maxval=7.0, step=0.5, group=panelGroup)
panelEfficiencyLen = input.int(12, "Trend efficiency lookback", minval=5, maxval=40, group=panelGroup)
panelDiLen = input.int(14, "Directional movement (DMI) length", minval=5, maxval=40, group=panelGroup)
panelAdxSmooth = input.int(14, "ADX smoothing", minval=5, maxval=40, group=panelGroup)
 
f_confluencePack() =>
    float e50 = ta.ema(close, 50)
    float e100 = ta.ema(close, 100)
    float e200 = ta.ema(close, 200)
    float a = math.max(nz(ta.atr(14), syminfo.mintick), syminfo.mintick)
    float vw = ta.vwap(hlc3)
    float r = ta.rsi(close, 14)
    [diPlus, diMinus, adx] = ta.dmi(panelDiLen, panelAdxSmooth)
    bool upOrder = e50 > e100 and e100 > e200
    bool downOrder = e50 < e100 and e100 < e200
    float g1 = math.abs(e50 - e100) / a
    float g2 = math.abs(e100 - e200) / a
    float req1 = timeframe.multiplier == 1 ? minGap50_100_M1 : minGap50_100_M5
    float req2 = timeframe.multiplier == 1 ? minGap100_200_M1 : minGap100_200_M5
    float gPts1 = g1 >= req1 ? 3.0 : g1 >= req1 * 0.70 ? 2.0 : g1 >= req1 * 0.40 ? 1.0 : 0.0
    float gPts2 = g2 >= req2 ? 3.0 : g2 >= req2 * 0.70 ? 2.0 : g2 >= req2 * 0.40 ? 1.0 : 0.0
    float upEMA = upOrder ? 4.0 + gPts1 + gPts2 : 0.0
    float downEMA = downOrder ? 4.0 + gPts1 + gPts2 : 0.0
 
    float s50 = (e50 - e50[trendSlopeBars]) / a
    float s100 = (e100 - e100[trendSlopeBars]) / a
    float s200 = (e200 - e200[trendSlopeBars]) / a
    float upSlope = (s50 >= minSlope100ATR ? 3.0 : s50 > 0 ? 1.0 : 0.0) + (s100 >= minSlope100ATR ? 4.0 : s100 > 0 ? 2.0 : 0.0) + (s200 >= minSlope200ATR ? 3.0 : s200 > 0 ? 1.0 : 0.0)
    float downSlope = (s50 <= -minSlope100ATR ? 3.0 : s50 < 0 ? 1.0 : 0.0) + (s100 <= -minSlope100ATR ? 4.0 : s100 < 0 ? 2.0 : 0.0) + (s200 <= -minSlope200ATR ? 3.0 : s200 < 0 ? 1.0 : 0.0)
 
    float adxBase = na(adx) ? 0.0 : adx >= 30.0 ? 6.0 : adx >= 25.0 ? 5.0 : adx >= 20.0 ? 4.0 : adx >= 15.0 ? 2.0 : 0.0
    float plusLead = nz(diPlus) - nz(diMinus)
    float minusLead = nz(diMinus) - nz(diPlus)
    float upDMI = plusLead > 0 ? adxBase + (plusLead >= 5.0 ? 4.0 : plusLead >= 2.0 ? 3.0 : 2.0) : 0.0
    float downDMI = minusLead > 0 ? adxBase + (minusLead >= 5.0 ? 4.0 : minusLead >= 2.0 ? 3.0 : 2.0) : 0.0
 
    float upPos = (close >= e50 ? 3.0 : 0.0) + (close >= e100 ? 2.0 : 0.0) + (na(vw) ? 1.0 : close >= vw ? 2.0 : 0.0) + (r >= 55.0 ? 3.0 : r >= 50.0 ? 2.0 : r >= 45.0 ? 1.0 : 0.0)
    float downPos = (close <= e50 ? 3.0 : 0.0) + (close <= e100 ? 2.0 : 0.0) + (na(vw) ? 1.0 : close <= vw ? 2.0 : 0.0) + (r <= 45.0 ? 3.0 : r <= 50.0 ? 2.0 : r <= 55.0 ? 1.0 : 0.0)
 
    float path = math.sum(math.abs(close - close[1]), panelEfficiencyLen)
    float net = close - close[panelEfficiencyLen]
    float er = not na(path) and path > 0 ? math.abs(net) / path : 0.0
    float effBase = er >= 0.65 ? 8.0 : er >= 0.45 ? 6.0 : er >= 0.30 ? 4.0 : er >= 0.20 ? 2.0 : 0.0
    float upEff = net > 0 ? effBase + (close >= close[3] ? 2.0 : 0.0) : 0.0
    float downEff = net < 0 ? effBase + (close <= close[3] ? 2.0 : 0.0) : 0.0
 
    float upTotal = (upEMA + upSlope + upDMI + upPos + upEff) / 5.0
    float downTotal = (downEMA + downSlope + downDMI + downPos + downEff) / 5.0
    // A directional label also requires non-flat, visibly separated
    // slower EMAs. This prevents several unrelated confluences from
    // mislabelling a tightly packed, flat EMA cluster as a trend.
    bool spreadGate = g1 >= req1 * 0.70 and g2 >= req2 * 0.70
    bool bullGate = upOrder and spreadGate and s100 >= minSlope100ATR * 0.75 and s200 >= minSlope200ATR * 0.75
    bool bearGate = downOrder and spreadGate and s100 <= -minSlope100ATR * 0.75 and s200 <= -minSlope200ATR * 0.75
    int bias = bullGate and upTotal >= minBiasScore and upTotal - downTotal >= minDominance ? 1 : bearGate and downTotal >= minBiasScore and downTotal - upTotal >= minDominance ? -1 : 0
    bool upLeading = upTotal >= downTotal
    float displayedTotal = upLeading ? upTotal : downTotal
    // Count successive CLOSED timeframe candles with the same class.
    // E.g. seven 5-minute BEARISH classifications = 35 trading minutes.
    // Do not use wall-clock time (weekends/gaps would inflate duration).
    var int stateBars = 0
    stateBars := na(bias[1]) or bias != bias[1] ? 1 : nz(stateBars[1]) + 1
    // Request ONLY the preceding confirmed candle from each context.
    [bias[1], displayedTotal[1], stateBars[1], time_close[1]]
 
 
// Always request the same confirmed calculation from the underlying
// XAUUSD symbol. The chart timeframe controls ONLY the retrieval route.
[htfBias15, htfScore15, htfBars15, htfClose15] = request.security(syminfo.tickerid, "15", f_confluencePack(), lookahead=barmerge.lookahead_on)
[htfBias5, htfScore5, htfBars5, htfClose5] = request.security(syminfo.tickerid, "5", f_confluencePack(), lookahead=barmerge.lookahead_on)
[htfBias1, htfScore1, htfBars1, htfClose1] = request.security(syminfo.tickerid, "1", f_confluencePack(), lookahead=barmerge.lookahead_on)
 
// A 5m chart has one 5m candle, but a 15m chart contains 3x 5m.
// LTF arrays solve first-intrabar lookahead mismatch in V32.
[l5BiasA, l5ScoreA, l5BarsA, l5CloseA] = request.security_lower_tf(syminfo.tickerid, "5", f_confluencePack(), ignore_invalid_timeframe=true)
[l1BiasA, l1ScoreA, l1BarsA, l1CloseA] = request.security_lower_tf(syminfo.tickerid, "1", f_confluencePack(), ignore_invalid_timeframe=true)
 
f_lastInt(array<int> data) =>
    array.size(data) > 0 ? array.get(data, array.size(data) - 1) : na
 
f_lastFloat(array<float> data) =>
    array.size(data) > 0 ? array.get(data, array.size(data) - 1) : na
 
bool chartAbove5 = timeframe.in_seconds() > timeframe.in_seconds("5")
bool chartAbove1 = timeframe.in_seconds() > timeframe.in_seconds("1")
int bias15 = htfBias15
float score15 = htfScore15
int bars15 = htfBars15
int checked15 = htfClose15
int bias5 = chartAbove5 ? f_lastInt(l5BiasA) : htfBias5
float score5 = chartAbove5 ? f_lastFloat(l5ScoreA) : htfScore5
int bars5 = chartAbove5 ? f_lastInt(l5BarsA) : htfBars5
int checked5 = chartAbove5 ? f_lastInt(l5CloseA) : htfClose5
int bias1 = chartAbove1 ? f_lastInt(l1BiasA) : htfBias1
float score1 = chartAbove1 ? f_lastFloat(l1ScoreA) : htfScore1
int bars1 = chartAbove1 ? f_lastInt(l1BarsA) : htfBars1
int checked1 = chartAbove1 ? f_lastInt(l1CloseA) : htfClose1
 
// A first realtime lower-TF bar might not exist at a chart boundary.
// In that case do not invent the latest state; show WAIT for that row.
// ==========================================================
// 11. OVERALL DAILY BIAS: NON-BLOCKING HIGHER-TIMEFRAME CONTEXT
// This is a research-style directional CONSENSUS estimate, not
// a guarantee, an entry trigger, or a win-probability reading.
// Score is absolute weight-adjusted directional conviction.
// Confirmed D1/H4/H1/M15 bars + last completed M1 minute.
// Weekly COT and multi-timeframe DXY/US10Y context are lighter.
// Daily opening price and previous day's H/L inform structure.
// News data: Pine CANNOT read upcoming event calendars or
// news headlines; a manually entered high-risk event is shown.
// ==========================================================
overallGroup = "OVERALL daily bias (research-based; non-blocking)"
overallMinConviction = input.float(2.0, "Minimum net directional strength for a bias / 10", minval=0.5, maxval=9.0, step=0.5, group=overallGroup)
dxyTicker = input.symbol("TVC:DXY", "US dollar index proxy symbol", group=overallGroup)
yieldTicker = input.symbol("TVC:US10Y", "US 10-year yield proxy symbol", group=overallGroup)
includeDXY = input.bool(true, "Include DXY context (inverse association)", group=overallGroup)
includeYield = input.bool(true, "Include US10Y context (inverse association)", group=overallGroup)
// H1 leads to reflect macro context; M15 detects nearer-term dollar/yield turns.
// These are ADVISORY and never block a previously valid two-candle entry.
macroH1Weight = input.float(0.65, "Macro blend: hourly weight (remainder M15)", minval=0.0, maxval=1.0, step=0.05, group=overallGroup)
macroMaxH1Age = input.int(180, "Ignore hourly macro feed older than (minutes)", minval=60, maxval=720, group=overallGroup)
macroMaxM15Age = input.int(60, "Ignore M15 macro feed older than (minutes)", minval=15, maxval=240, group=overallGroup)
includeCOT = input.bool(true, "Include available weekly COMEX gold managed-money COT", group=overallGroup)
newsGroup = "Scheduled news warning - MANUAL (Pine cannot retrieve calendar)"
useManualNews = input.bool(false, "Enable manually scheduled high-impact event", group=newsGroup)
newsEventTime = input.time(timestamp("01 Jan 2030 13:30 +0000"), "Event date/time - set in settings", group=newsGroup)
newsLeadMinutes = input.int(30, "Warn this many minutes BEFORE event", minval=1, maxval=240, group=newsGroup)
newsLagMinutes = input.int(15, "Warn this many minutes AFTER event", minval=1, maxval=120, group=newsGroup)
 
f_clamp(float val, float lowBound, float highBound) =>
    math.max(lowBound, math.min(highBound, val))
 
// Deliberately uses only information known at the CLOSE of the
// requested timeframe. HTF return offset [1] prevents a future leak.
f_htfDailyVote() =>
    float e21 = ta.ema(close, 21)
    float e50 = ta.ema(close, 50)
    float e100 = ta.ema(close, 100)
    float e200 = ta.ema(close, 200)
    float rsi = ta.rsi(close, 14)
    float atr = math.max(nz(ta.atr(14), syminfo.mintick), syminfo.mintick)
    [plusD, minusD, adxD] = ta.dmi(14, 14)
    float stack = e50 > e100 and e100 > e200 ? 0.30 : e50 < e100 and e100 < e200 ? -0.30 : e50 > e100 ? 0.10 : e50 < e100 ? -0.10 : 0.0
    float location = (close > e21 ? 0.12 : -0.12) + (close > e50 ? 0.09 : -0.09) + (close > e200 ? 0.07 : -0.07)
    float slope = (e50 - e50[5]) / atr
    float slopeVote = f_clamp(slope / 2.0, -1.0, 1.0) * 0.15
    float momentum = f_clamp((rsi - 50.0) / 20.0, -1.0, 1.0) * 0.12
    float dmiVote = not na(adxD) and adxD >= 18.0 ? (plusD > minusD ? 0.15 : -0.15) : 0.0
    float raw = stack + location + slopeVote + momentum + dmiVote
    float vote = f_clamp(raw, -1.0, 1.0)
    vote[1]
 
// Confirmed M1 intraday price impulse (updates after each minute).
f_intradayMinuteVote() =>
    float e21 = ta.ema(close, 21)
    float e50 = ta.ema(close, 50)
    float r = ta.rsi(close, 14)
    float a = math.max(nz(ta.atr(14), syminfo.mintick), syminfo.mintick)
    float impulse = f_clamp((close - close[10]) / (3.0 * a), -1.0, 1.0)
    float loc = close > e21 ? 0.2 : -0.2
    float order = e21 > e50 ? 0.15 : -0.15
    float rVote = f_clamp((r - 50) / 25.0, -1.0, 1.0) * 0.15
    float v = f_clamp(0.50 * impulse + loc + order + rVote, -1.0, 1.0)
    v[1]
 
// Both the vote and its source-bar timestamp refer to a CONFIRMED
// macro candle. Evaluated in the requested symbol's native context.
f_marketPack() =>
    float e20 = ta.ema(close, 20)
    float e50 = ta.ema(close, 50)
    float a = math.max(nz(ta.atr(14), syminfo.mintick), syminfo.mintick)
    float change12 = f_clamp((close - close[12]) / (4.0 * a), -1.0, 1.0)
    float slope = f_clamp((e20 - e20[6]) / (2.0 * a), -1.0, 1.0)
    float position = e20 > e50 ? 0.30 : -0.30
    float vote = f_clamp(position + change12 * 0.40 + slope * 0.30, -1.0, 1.0)
    [vote[1], time[1]]
 
f_macroFresh(float vote, int candleTime, int ageLimitMinutes, int referenceTime) =>
    not na(vote) and not na(candleTime) and not na(referenceTime) and referenceTime >= candleTime and referenceTime - candleTime <= ageLimitMinutes * 60000
 
f_macroBlend(float hourly, float quarterHour) =>
    not na(hourly) and not na(quarterHour) ? hourly * macroH1Weight + quarterHour * (1.0 - macroH1Weight) : not na(hourly) ? hourly : quarterHour
 
// No future data on higher timeframes. The M1 request on an M5
// chart has lower-TF sampling limits. Use an M1 chart for true
// one-minute-close dashboard assessments.
float d1Vote = request.security(syminfo.tickerid, "1D", f_htfDailyVote(), lookahead=barmerge.lookahead_on)
float h4Vote = request.security(syminfo.tickerid, "240", f_htfDailyVote(), lookahead=barmerge.lookahead_on)
float h1Vote = request.security(syminfo.tickerid, "60", f_htfDailyVote(), lookahead=barmerge.lookahead_on)
float m15Vote = request.security(syminfo.tickerid, "15", f_htfDailyVote(), lookahead=barmerge.lookahead_on)
float m1VoteDirect = request.security(syminfo.tickerid, "1", f_intradayMinuteVote(), lookahead=barmerge.lookahead_on)
array<float> minuteVoteArray = request.security_lower_tf(syminfo.tickerid, "1", f_intradayMinuteVote(), ignore_invalid_timeframe=true)
float m1Vote = chartAbove1 ? f_lastFloat(minuteVoteArray) : m1VoteDirect
float yesterdayHigh = request.security(syminfo.tickerid, "1D", high[1], lookahead=barmerge.lookahead_on)
float yesterdayLow = request.security(syminfo.tickerid, "1D", low[1], lookahead=barmerge.lookahead_on)
float yesterdayClose = request.security(syminfo.tickerid, "1D", close[1], lookahead=barmerge.lookahead_on)
// Today's opening print is known at the start of the session.
float todayOpen = request.security(syminfo.tickerid, "1D", open, lookahead=barmerge.lookahead_on)
[minuteCloseDirect, minuteTimeDirect] = request.security(syminfo.tickerid, "1", [close[1], time_close[1]], lookahead=barmerge.lookahead_on)
[minuteCloseArray, minuteTimeArray] = request.security_lower_tf(syminfo.tickerid, "1", [close[1], time_close[1]], ignore_invalid_timeframe=true)
float minuteClose = chartAbove1 ? f_lastFloat(minuteCloseArray) : minuteCloseDirect
int minuteTime = chartAbove1 ? f_lastInt(minuteTimeArray) : minuteTimeDirect
// Inverse proxies for XAUUSD, not fixed universal correlations.
// H1/M15 requests use only completed macro candles (vote[1]).
// A macro component is NA when the provider is unavailable/stale.
[dxyH1Raw, dxyH1Time] = request.security(dxyTicker, "60", f_marketPack(), lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
[dxyM15Raw, dxyM15Time] = request.security(dxyTicker, "15", f_marketPack(), lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
[yieldH1Raw, yieldH1Time] = request.security(yieldTicker, "60", f_marketPack(), lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
[yieldM15Raw, yieldM15Time] = request.security(yieldTicker, "15", f_marketPack(), lookahead=barmerge.lookahead_on, ignore_invalid_symbol=true)
 
float dxyH1GoldVote = includeDXY and f_macroFresh(dxyH1Raw, dxyH1Time, macroMaxH1Age, minuteTime) ? -dxyH1Raw : na
float dxyM15GoldVote = includeDXY and f_macroFresh(dxyM15Raw, dxyM15Time, macroMaxM15Age, minuteTime) ? -dxyM15Raw : na
float yieldH1GoldVote = includeYield and f_macroFresh(yieldH1Raw, yieldH1Time, macroMaxH1Age, minuteTime) ? -yieldH1Raw : na
float yieldM15GoldVote = includeYield and f_macroFresh(yieldM15Raw, yieldM15Time, macroMaxM15Age, minuteTime) ? -yieldM15Raw : na
 
// Timeframes pointing in opposite directions naturally offset.
// Missing values do NOT silently count as a bullish/bearish vote.
float dxyGoldVote = includeDXY ? f_macroBlend(dxyH1GoldVote, dxyM15GoldVote) : na
float yieldGoldVote = includeYield ? f_macroBlend(yieldH1GoldVote, yieldM15GoldVote) : na
 
// Macro directional consensus is an observation, NOT an entry filter.
float macroSum = (na(dxyGoldVote) ? 0.0 : dxyGoldVote * 7.0) + (na(yieldGoldVote) ? 0.0 : yieldGoldVote * 5.0)
float macroAvailableWeight = (na(dxyGoldVote) ? 0.0 : 7.0) + (na(yieldGoldVote) ? 0.0 : 5.0)
float macroGoldVote = macroAvailableWeight > 0.0 ? macroSum / macroAvailableWeight : na
 
 
// Official TradingView LibraryCOT; fixed COMEX gold CFTC 088691.
// Gold data uses the Disaggregated report / Managed Money.
// request.security's ignore_invalid_symbol avoids breaking the
// original signals when the optional COT symbol is unavailable.
string cotLongSymbol = cot.COTTickerid("Disaggregated", "088691", false, "Managed Money Positions", "Long", "All")
string cotShortSymbol = cot.COTTickerid("Disaggregated", "088691", false, "Managed Money Positions", "Short", "All")
float cotLongs = request.security(cotLongSymbol, "1W", close, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
float cotShorts = request.security(cotShortSymbol, "1W", close, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
// Net positioning is compared with its own historical level,
// rather than assuming net-long always predicts higher prices.
float cotNet = not na(cotLongs) and not na(cotShorts) ? cotLongs - cotShorts : na
// Calculate baselines IN THE WEEKLY CONTEXT; averaging on an M1
// chart would mistakenly average 26 MINUTES, not 26 reports.
float cotLongAvg26 = request.security(cotLongSymbol, "1W", ta.sma(close, 26), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
float cotShortAvg26 = request.security(cotShortSymbol, "1W", ta.sma(close, 26), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
float cotLongPrev = request.security(cotLongSymbol, "1W", close[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
float cotShortPrev = request.security(cotShortSymbol, "1W", close[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true)
float cotBaseline = not na(cotLongAvg26) and not na(cotShortAvg26) ? cotLongAvg26 - cotShortAvg26 : na
float cotWeekChange = not na(cotNet) and not na(cotLongPrev) and not na(cotShortPrev) ? cotNet - (cotLongPrev - cotShortPrev) : na
float cotVote = includeCOT and not na(cotNet) and not na(cotBaseline) ? f_clamp((cotNet - cotBaseline) / math.max(10000.0, math.abs(cotBaseline) * 0.30), -1.0, 1.0) : na
 
// Asia session in EUROPE/LONDON local time: 00:00 to 07:59.
// Uses last COMPLETED one-minute bar; before 08:00 its range
// is still forming and it contributes no vote. A confirmed
// breakout of Asia range is directional; inside is neutral.
f_asiaData() =>
    int dayKey = year(time, "Europe/London") * 10000 + month(time, "Europe/London") * 100 + dayofmonth(time, "Europe/London")
    bool resetDay = ta.change(dayKey) != 0
    bool asiaSession = not na(time("1", "0000-0800", "Europe/London"))
    var float asiaH = na
    var float asiaL = na
    if resetDay
        asiaH := na
        asiaL := na
    if asiaSession
        asiaH := na(asiaH) ? high : math.max(asiaH, high)
        asiaL := na(asiaL) ? low : math.min(asiaL, low)
    bool completedAsia = not asiaSession and not na(asiaH) and not na(asiaL)
    [asiaH[1], asiaL[1], completedAsia[1]]
 
[asiaHighDirect, asiaLowDirect, asiaCompleteDirect] = request.security(syminfo.tickerid, "1", f_asiaData(), lookahead=barmerge.lookahead_on)
[asiaHighArray, asiaLowArray, asiaCompleteArray] = request.security_lower_tf(syminfo.tickerid, "1", f_asiaData(), ignore_invalid_timeframe=true)
float asiaHigh = chartAbove1 ? f_lastFloat(asiaHighArray) : asiaHighDirect
float asiaLow = chartAbove1 ? f_lastFloat(asiaLowArray) : asiaLowDirect
bool asiaComplete = chartAbove1 ? (array.size(asiaCompleteArray) > 0 ? array.get(asiaCompleteArray, array.size(asiaCompleteArray) - 1) : false) : asiaCompleteDirect
float asiaVote = not asiaComplete or na(minuteClose) or na(asiaHigh) or na(asiaLow) ? na : minuteClose > asiaHigh ? 1.0 : minuteClose < asiaLow ? -1.0 : 0.0
 
// Current price relative to day open, yesterday close and the
// last completed day's high/low. This is price STRUCTURE, not
// a liquidity sweep detector (cannot infer resting liquidity).
float dayLocation = na(minuteClose) or na(todayOpen) or na(yesterdayClose) ? na : (minuteClose > todayOpen ? 0.45 : minuteClose < todayOpen ? -0.45 : 0.0) + (minuteClose > yesterdayClose ? 0.25 : minuteClose < yesterdayClose ? -0.25 : 0.0) + (minuteClose > yesterdayHigh ? 0.30 : minuteClose < yesterdayLow ? -0.30 : 0.0)
dayLocation := na(dayLocation) ? na : f_clamp(dayLocation, -1.0, 1.0)
 
// Weighted votes, scaled only over AVAILABLE observations.
float voteSum = 0.0
float voteWeight = 0.0
if not na(d1Vote)
    voteSum += d1Vote * 18.0
    voteWeight += 18.0
if not na(h4Vote)
    voteSum += h4Vote * 16.0
    voteWeight += 16.0
if not na(h1Vote)
    voteSum += h1Vote * 12.0
    voteWeight += 12.0
if not na(m15Vote)
    voteSum += m15Vote * 9.0
    voteWeight += 9.0
if not na(m1Vote)
    voteSum += m1Vote * 10.0
    voteWeight += 10.0
if not na(dayLocation)
    voteSum += dayLocation * 12.0
    voteWeight += 12.0
if not na(dxyGoldVote)
    voteSum += dxyGoldVote * 7.0
    voteWeight += 7.0
if not na(yieldGoldVote)
    voteSum += yieldGoldVote * 5.0
    voteWeight += 5.0
if not na(cotVote)
    voteSum += cotVote * 6.0
    voteWeight += 6.0
if not na(asiaVote)
    voteSum += asiaVote * 5.0
    voteWeight += 5.0
 
float overallSigned = voteWeight > 0 ? voteSum / voteWeight : na
float overallScore = na(overallSigned) ? na : math.abs(overallSigned) * 10.0
bool htfConflict = not na(d1Vote) and not na(h4Vote) and (d1Vote >= 0.20 and h4Vote <= -0.20 or d1Vote <= -0.20 and h4Vote >= 0.20)
int overallBias = na(overallScore) ? 0 : htfConflict or overallScore < overallMinConviction ? 0 : overallSigned > 0 ? 1 : -1
string overallText = htfConflict ? "MIXED HTF" : overallBias > 0 ? "BULLISH" : overallBias < 0 ? "BEARISH" : "RANGING"
float dataCoverage = voteWeight  // out of 100 planned points; absent components excluded
// Macro-vs-price conflict is displayed separately, never hidden in the score.
float goldHTFCore = not na(d1Vote) and not na(h4Vote) and not na(h1Vote) ? (d1Vote * 0.39 + h4Vote * 0.35 + h1Vote * 0.26) : na
bool macroConflict = not na(goldHTFCore) and not na(macroGoldVote) and math.abs(goldHTFCore) >= 0.20 and math.abs(macroGoldVote) >= 0.20 and goldHTFCore * macroGoldVote < 0.0
string macroText = na(macroGoldVote) ? "NO FEED" : macroGoldVote > 0.15 ? "FAVOURS GOLD" : macroGoldVote < -0.15 ? "AGAINST GOLD" : "MACRO MIXED"
string macroAgreement = na(macroGoldVote) or na(goldHTFCore) ? "N/A" : macroConflict ? "CONFLICT" : math.abs(macroGoldVote) < 0.15 or math.abs(goldHTFCore) < 0.20 ? "UNCLEAR" : "AGREES"
// News is a RISK warning, not a prediction of direction.
bool eventWindow = useManualNews and time >= newsEventTime - newsLeadMinutes * 60000 and time <= newsEventTime + newsLagMinutes * 60000
string newsStatus = not useManualNews ? "NOT LINKED" : eventWindow ? "EVENT RISK" : time < newsEventTime ? "SCHEDULED" : "PAST EVENT"
 
// ==========================================================
// 12. COMPACT FOUR-ROW VISUAL, NO BREAKDOWN OR MACRO CLUTTER
// Column 1: timeframe; 2: direction; 3: quality and 0-10 score;
// Column 4: number of consecutive completed bars in this regime.
// Overall is DAILY consensus and intentionally reads "DAY" rather
// than inventing a regime start from host-chart bars.
// ==========================================================
f_biasText(int bias) =>
    na(bias) ? "WAIT" : bias > 0 ? "BULLISH" : bias < 0 ? "BEARISH" : "RANGING"
 
f_biasTextColor(int bias) =>
    na(bias) ? color.orange : bias > 0 ? color.lime : bias < 0 ? color.rgb(255, 120, 120) : color.silver
 
f_biasBg(int bias) =>
    na(bias) ? color.new(color.gray, 82) : bias > 0 ? color.new(color.green, 81) : bias < 0 ? color.new(color.red, 81) : color.new(color.gray, 88)
 
f_strengthText(int bias, float score) =>
    na(bias) or na(score) ? "--" : bias == 0 ? "NEUTRAL " + str.tostring(int(math.round(score))) + "/10" : score >= 7.0 ? "STRONG " + str.tostring(int(math.round(score))) + "/10" : "WEAK " + str.tostring(int(math.round(score))) + "/10"
 
f_overallQuality(int bias, float score) =>
    na(score) ? "--" : bias == 0 ? "NEUTRAL " + str.tostring(score, "#.0") + "/10" : score >= 7.0 ? "STRONG " + str.tostring(score, "#.0") + "/10" : "WEAK " + str.tostring(score, "#.0") + "/10"
 
f_ageLabel(int countBars, int minutesPerBar) =>
    if na(countBars) or countBars < 1
        "--"
    else
        int totalMinutes = countBars * minutesPerBar
        totalMinutes >= 1440 ? str.tostring(int(totalMinutes / 1440)) + "d " + str.tostring(int(totalMinutes % 1440 / 60)) + "h" : totalMinutes >= 60 ? str.tostring(int(totalMinutes / 60)) + "h " + str.tostring(totalMinutes % 60) + "m" : str.tostring(totalMinutes) + "m"
 
f_addRow(table t, int rowID, string tf, int direction, float score, int countBars, int frameMinutes) =>
    color bg = f_biasBg(direction)
    color txt = f_biasTextColor(direction)
    table.cell(t, 0, rowID, tf, text_color=color.white, bgcolor=color.new(color.black, 20), text_size=size.tiny)
    table.cell(t, 1, rowID, f_biasText(direction), text_color=txt, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 2, rowID, f_strengthText(direction, score), text_color=txt, bgcolor=bg, text_size=size.tiny)
    table.cell(t, 3, rowID, f_ageLabel(countBars, frameMinutes), text_color=color.silver, bgcolor=color.new(color.black, 20), text_size=size.tiny)
    0
 
var table trendPanel = table.new(position.bottom_right, 4, 5, bgcolor=color.new(color.black, 12), frame_color=color.new(color.gray, 55), frame_width=1, border_color=color.new(color.gray, 80), border_width=1)
if barstate.islast
    if showTrendPanel
        table.cell(trendPanel, 0, 0, "XAUUSD", text_color=color.white, bgcolor=color.new(color.gray, 38), text_size=size.tiny)
        table.cell(trendPanel, 1, 0, "TREND", text_color=color.white, bgcolor=color.new(color.gray, 38), text_size=size.tiny)
        table.cell(trendPanel, 2, 0, "STRENGTH", text_color=color.white, bgcolor=color.new(color.gray, 38), text_size=size.tiny)
        table.cell(trendPanel, 3, 0, "AGE", text_color=color.white, bgcolor=color.new(color.gray, 38), text_size=size.tiny)
        table.cell(trendPanel, 0, 1, "OVERALL / DAY", text_color=color.white, bgcolor=color.new(color.blue, 72), text_size=size.tiny)
        bool insufficientData = dataCoverage < 65.0
        table.cell(trendPanel, 1, 1, insufficientData ? "LOW DATA" : overallText, text_color=insufficientData ? color.orange : f_biasTextColor(overallBias), bgcolor=f_biasBg(insufficientData ? 0 : overallBias), text_size=size.tiny)
        table.cell(trendPanel, 2, 1, insufficientData ? "UNAVAILABLE" : f_overallQuality(overallBias, overallScore), text_color=insufficientData ? color.orange : f_biasTextColor(overallBias), bgcolor=f_biasBg(insufficientData ? 0 : overallBias), text_size=size.tiny)
        table.cell(trendPanel, 3, 1, "DAY", text_color=color.silver, bgcolor=color.new(color.blue, 84), text_size=size.tiny)
        f_addRow(trendPanel, 2, "15 MIN", bias15, score15, bars15, 15)
        f_addRow(trendPanel, 3, "5 MIN", bias5, score5, bars5, 5)
        f_addRow(trendPanel, 4, "1 MIN", bias1, score1, bars1, 1)
    else
        table.clear(trendPanel, 0, 0, 3, 4)
 
// For the TradingView Data Window; does NOT change the signal engine.
plot(overallSigned, "OVERALL daily signed conviction (-1 to +1)", display=display.data_window)
plot(overallScore, "OVERALL daily magnitude / 10 (not win probability)", display=display.data_window)
plot(cotNet, "COT COMEX gold weekly managed-money net (contracts)", display=display.data_window)
plot(cotWeekChange, "COT change (weekly sampling caution)", display=display.data_window)
plot(dataCoverage, "OVERALL available data coverage / 100", display=display.data_window)
plot(asiaHigh, "Asia 00-08 London high (data window)", display=display.data_window)
plot(asiaLow, "Asia 00-08 London low (data window)", display=display.data_window)
 
// Optional macro-data audit, shown only in TradingView's Data Window.
plot(dxyH1GoldVote, "DXY H1 inverse gold vote (confirmed)", display=display.data_window)
plot(dxyM15GoldVote, "DXY M15 inverse gold vote (confirmed)", display=display.data_window)
plot(yieldH1GoldVote, "US10Y H1 inverse gold vote (confirmed)", display=display.data_window)
plot(yieldM15GoldVote, "US10Y M15 inverse gold vote (confirmed)", display=display.data_window)
plot(macroGoldVote, "USD and yields macro consensus for gold", display=display.data_window)
plot(macroConflict ? 1.0 : 0.0, "Macro vs Gold HTF conflict (1/0)", display=display.data_window)
 
// Confirmed source timestamps make chart-to-chart checks auditable.
plot(checked15, "V33 last completed 15m candle timestamp (ms)", display=display.data_window)
plot(checked5, "V33 last completed 5m candle timestamp (ms)", display=display.data_window)
plot(checked1, "V33 last completed 1m candle timestamp (ms)", display=display.data_window)
plot(bars15, "V33 completed 15m candles in current trend", display=display.data_window)
plot(bars5, "V33 completed 5m candles in current trend", display=display.data_window)
plot(bars1, "V33 completed 1m candles in current trend", display=display.data_window)

← 返回列表