本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("XAUUSD Signals", overlay=true, max_lines_count=500, max_labels_count=500)
type TradeViz
line entryL
line slL
line tpL
label sigL
label outL
// ===== Inputs =====
atrLen = input.int(10, "ATR length", minval=1)
atrMult = input.float(2.0, "ATR trail multiplier", minval=0.1, step=0.1)
emaLen = input.int(200, "Trend EMA length", minval=2)
adxLen = input.int(14, "ADX length", minval=1)
adxMin = input.float(20.0, "Minimum ADX", minval=0.0)
useHTF = input.bool(true, "Higher-timeframe confirmation")
htfLen = input.int(50, "HTF EMA length", minval=2)
slMult = input.float(1.5, "Stop loss (x ATR)", minval=0.1, step=0.1)
rr = input.float(2.0, "Reward : Risk", minval=0.5, step=0.1)
minTicks = input.int(50, "Minimum stop (ticks)", minval=1)
spreadPx = input.float(0.17, "Spread cost (price units)", minval=0.0, step=0.01)
useNews = input.bool(true, "News: block trades around listed times")
newsTxt = input.string("", "News times UTC (YYYY-MM-DD HH:MM, comma separated)")
newsBefore = input.int(30, "News: minutes before", minval=0)
newsAfter = input.int(60, "News: minutes after", minval=0)
useNFP = input.bool(false, "News: auto-block US jobs report (1st Friday)")
exitOnNews = input.bool(false, "News: exit open trade when window starts")
useSpike = input.bool(false, "Pause after volatility spike")
spikeX = input.float(3.0, "Spike = bar range above x ATR", minval=1.0, step=0.5)
spikeCool = input.int(3, "Bars to pause after a spike", minval=1, maxval=20)
keepN = input.int(10, "Completed trades kept", minval=5, maxval=100)
tblSize = input.string("Small", "Table text size", options=["Tiny", "Small", "Normal"])
// ===== Symbol validation (XAUUSD spot gold only) =====
string tkr = str.upper(syminfo.ticker)
string stype = syminfo.type
bool nameOk = str.startswith(tkr, "XAUUSD")
bool notT = not str.startswith(tkr, "XAUUSDT")
bool notFut = not str.contains(tkr, "!")
bool typeOk = stype != "futures" and stype != "fund"
typeOk := typeOk and stype != "crypto" and stype != "stock"
bool isGold = nameOk and notT and notFut and typeOk
isGold := isGold and syminfo.currency == "USD"
// ===== Higher timeframe (first standard timeframe >= 4x chart) =====
f_tf(int secs) =>
string r = na
if secs <= 5
r := "5S"
else if secs <= 10
r := "10S"
else if secs <= 15
r := "15S"
else if secs <= 30
r := "30S"
else if secs <= 60
r := "1"
else if secs <= 180
r := "3"
else if secs <= 300
r := "5"
else if secs <= 900
r := "15"
else if secs <= 1800
r := "30"
else if secs <= 2700
r := "45"
else if secs <= 3600
r := "60"
else if secs <= 7200
r := "120"
else if secs <= 10800
r := "180"
else if secs <= 14400
r := "240"
else if secs <= 86400
r := "D"
else if secs <= 604800
r := "W"
else if secs <= 2592000
r := "M"
else if secs <= 7776000
r := "3M"
else if secs <= 15552000
r := "6M"
else if secs <= 31104000
r := "12M"
r
int chartSecs = timeframe.in_seconds()
var string htfTf = na
if barstate.isfirst and chartSecs > 0
htfTf := f_tf(chartSecs * 4)
bool htfOk = not na(htfTf)
string secTf = htfOk ? htfTf : timeframe.period
string sym = syminfo.tickerid
float htfRaw = ta.ema(close, htfLen)
float htfEma = request.security(sym, secTf, htfRaw[1], lookahead=barmerge.lookahead_on)
// ===== News times (parsed once) =====
var array<int> newsTimes = array.new<int>()
if barstate.isfirst and newsTxt != ""
array<string> parts = str.split(newsTxt, ",")
for i = 0 to array.size(parts) - 1
string p = str.trim(array.get(parts, i))
if str.length(p) >= 16
float yy = str.tonumber(str.substring(p, 0, 4))
float mo = str.tonumber(str.substring(p, 5, 7))
float dd = str.tonumber(str.substring(p, 8, 10))
float hh = str.tonumber(str.substring(p, 11, 13))
float mi = str.tonumber(str.substring(p, 14, 16))
bool allOk = not na(yy) and not na(mo) and not na(dd)
allOk := allOk and not na(hh) and not na(mi)
if allOk
int tsv = timestamp("UTC", int(yy), int(mo), int(dd), int(hh), int(mi), 0)
array.push(newsTimes, tsv)
bool manualBlock = false
if useNews and array.size(newsTimes) > 0
for j = 0 to array.size(newsTimes) - 1
int nt = array.get(newsTimes, j)
if time >= nt - newsBefore * 60000 and time <= nt + newsAfter * 60000
manualBlock := true
int dow = dayofweek(time, "UTC")
int dom = dayofmonth(time, "UTC")
int mon = month(time, "UTC")
int minsUtc = hour(time, "UTC") * 60 + minute(time, "UTC")
int nfpHour = (mon >= 4 and mon <= 10) ? 12 : 13
int nfpMin = nfpHour * 60 + 30
bool nfpDay = dow == dayofweek.friday and dom <= 7
bool nfpBlock = useNFP and nfpDay and timeframe.isintraday
nfpBlock := nfpBlock and minsUtc >= nfpMin - newsBefore and minsUtc <= nfpMin + newsAfter
bool newsBlock = manualBlock or nfpBlock
// ===== Core calculations =====
float atrV = ta.atr(atrLen)
float nLoss = atrMult * atrV
float trail = na
float prevTrail = nz(trail[1])
trail := if close > prevTrail and close[1] > prevTrail
math.max(prevTrail, close - nLoss)
else if close < prevTrail and close[1] < prevTrail
math.min(prevTrail, close + nLoss)
else if close > prevTrail
close - nLoss
else
close + nLoss
float emaTrend = ta.ema(close, emaLen)
[diP, diM, adxV] = ta.dmi(adxLen, adxLen)
float spikeF = (high - low) > spikeX * atrV ? 1.0 : 0.0
float spikeMax = ta.highest(spikeF, spikeCool)
bool spikePause = useSpike and spikeMax > 0
bool longRaw = ta.crossover(close, trail)
bool shortRaw = ta.crossunder(close, trail)
bool htfBull = not useHTF or close > htfEma
bool htfBear = not useHTF or close < htfEma
bool bullOk = close > emaTrend and adxV > adxMin and htfBull
bool bearOk = close < emaTrend and adxV > adxMin and htfBear
// ===== Data validity (WAIT conditions) =====
bool chartOk = chart.is_standard and chartSecs > 0
bool warm = bar_index >= emaLen
bool htfReady = not useHTF or (htfOk and not na(htfEma))
bool dataOk = chartOk and warm and htfReady
dataOk := dataOk and not na(atrV) and not na(adxV)
dataOk := dataOk and not na(emaTrend)
bool canTrade = isGold and dataOk and not newsBlock and not spikePause
bool newsExit = exitOnNews and newsBlock
// ===== Trade state =====
var int tradeDir = 0
var float entryP = na
var float slP = na
var float tpP = na
var float riskD = na
var int wins = 0
var int losses = 0
var float netR = 0.0
var array<TradeViz> viz = array.new<TradeViz>()
bool openLong = false
bool openShort = false
bool hitTP = false
bool hitSL = false
bool exitTrade = false
if barstate.isconfirmed
// 1) Manage the active trade
if tradeDir != 0 and array.size(viz) > 0
TradeViz cur = array.last(viz)
line.set_x2(cur.entryL, bar_index)
line.set_x2(cur.slL, bar_index)
line.set_x2(cur.tpL, bar_index)
bool slHit = tradeDir == 1 ? low <= slP : high >= slP
bool tpHit = tradeDir == 1 ? high >= tpP : low <= tpP
bool trendFlip = tradeDir == 1 ? shortRaw : longRaw
bool flipped = trendFlip or newsExit
float resR = na
float exitPx = na
string outTxt = ""
if slHit
hitSL := true
resR := -1.0
exitPx := slP
outTxt := "SL -1R"
else if tpHit
hitTP := true
resR := rr
exitPx := tpP
outTxt := "TP +" + str.tostring(rr, "#.##") + "R"
else if flipped
exitTrade := true
resR := tradeDir * (close - entryP) / riskD
exitPx := close
outTxt := "EXIT " + str.tostring(resR, "#.##") + "R"
if not na(resR)
color outCol = resR > 0 ? color.green : color.red
label ol = label.new(bar_index, exitPx, outTxt)
label.set_style(ol, label.style_label_left)
label.set_color(ol, outCol)
label.set_textcolor(ol, color.white)
label.set_size(ol, size.small)
cur.outL := ol
float netTrade = resR - spreadPx / riskD
if netTrade > 0
wins += 1
else
losses += 1
netR += netTrade
tradeDir := 0
// 2) Look for a new signal
if tradeDir == 0 and canTrade
if longRaw and bullOk
openLong := true
else if shortRaw and bearOk
openShort := true
// 3) Open the trade and draw it
if openLong or openShort
int d = openLong ? 1 : -1
float rd = math.max(slMult * atrV, minTicks * syminfo.mintick)
tradeDir := d
entryP := math.round_to_mintick(close)
slP := math.round_to_mintick(close - d * rd)
tpP := math.round_to_mintick(close + d * rr * rd)
riskD := math.abs(entryP - slP)
line enLine = line.new(bar_index, entryP, bar_index, entryP)
line slLine = line.new(bar_index, slP, bar_index, slP)
line tpLine = line.new(bar_index, tpP, bar_index, tpP)
line.set_color(enLine, color.blue)
line.set_style(enLine, line.style_dashed)
line.set_color(slLine, color.red)
line.set_color(tpLine, color.green)
label lb = na
if openLong
lb := label.new(bar_index, low, "BUY")
label.set_style(lb, label.style_label_up)
label.set_color(lb, color.green)
else
lb := label.new(bar_index, high, "SELL")
label.set_style(lb, label.style_label_down)
label.set_color(lb, color.red)
label.set_textcolor(lb, color.white)
label.set_size(lb, size.small)
array.push(viz, TradeViz.new(enLine, slLine, tpLine, lb, na))
while array.size(viz) > keepN + 1
TradeViz old = array.shift(viz)
line.delete(old.entryL)
line.delete(old.slL)
line.delete(old.tpL)
label.delete(old.sigL)
if not na(old.outL)
label.delete(old.outL)
// ===== Plots =====
plot(isGold ? emaTrend : na, "Trend EMA", color=color.orange, linewidth=2)
plot(isGold ? trail : na, "ATR trail", color=color.gray)
bgcolor(isGold and newsBlock ? color.new(color.yellow, 88) : na, title="News window")
// ===== Compact table =====
string ts = tblSize == "Tiny" ? size.tiny : tblSize == "Normal" ? size.normal : size.small
var table tbl = table.new(position.top_right, 2, 5, border_width=1)
if barstate.islast
color okC = color.new(color.green, 25)
color badC = color.new(color.red, 25)
color neuC = color.new(color.gray, 35)
color tc = color.white
bool good = isGold and dataOk and not newsBlock and not spikePause
string status = "No trade"
if tradeDir == 1
status := "LONG active"
if tradeDir == -1
status := "SHORT active"
if spikePause
status := "Spike pause"
if newsBlock
status := "News pause"
if not dataOk
status := "WAIT"
if not isGold
status := "Not XAUUSD"
int total = wins + losses
float wr = total > 0 ? 100.0 * wins / total : 0.0
string htfTxt = useHTF ? (htfOk ? htfTf : "n/a") : "off"
table.cell(tbl, 0, 0, "Status", text_color=tc, bgcolor=neuC, text_size=ts)
table.cell(tbl, 1, 0, status, text_color=tc, bgcolor=good ? okC : badC, text_size=ts)
table.cell(tbl, 0, 1, "Chart / HTF", text_color=tc, bgcolor=neuC, text_size=ts)
table.cell(tbl, 1, 1, timeframe.period + " / " + htfTxt, text_color=tc, bgcolor=neuC, text_size=ts)
table.cell(tbl, 0, 2, "Wins / Losses", text_color=tc, bgcolor=neuC, text_size=ts)
table.cell(tbl, 1, 2, str.tostring(wins) + " / " + str.tostring(losses), text_color=tc, bgcolor=neuC, text_size=ts)
table.cell(tbl, 0, 3, "Win rate", text_color=tc, bgcolor=neuC, text_size=ts)
table.cell(tbl, 1, 3, str.tostring(wr, "#.#") + "%", text_color=tc, bgcolor=neuC, text_size=ts)
table.cell(tbl, 0, 4, "Net result (R)", text_color=tc, bgcolor=neuC, text_size=ts)
table.cell(tbl, 1, 4, str.tostring(netR, "#.##"), text_color=tc, bgcolor=neuC, text_size=ts)
// ===== Alerts =====
alertcondition(openLong, "BUY signal", "XAUUSD BUY on {{interval}}")
alertcondition(openShort, "SELL signal", "XAUUSD SELL on {{interval}}")
alertcondition(hitTP, "TP hit", "XAUUSD take profit on {{interval}}")
alertcondition(hitSL, "SL hit", "XAUUSD stop loss on {{interval}}")
alertcondition(exitTrade, "Trend-flip or news exit", "XAUUSD exit on {{interval}}")