本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
strategy("Swing Exhaustion Fade", "SEF", overlay = true, explicit_plot_zorder = true,
initial_capital = 100000, default_qty_type = strategy.percent_of_equity,
commission_type = strategy.commission.percent, commission_value = 0.05, slippage = 2,
margin_long = 50, margin_short = 50, pyramiding = 0, calc_on_every_tick = false,
max_labels_count = 50, max_lines_count = 300, max_boxes_count = 100)
// ---------------------------------------------------------------- inputs
gE = "Swing engine"
kMult = input.float(2.5, "Swing size k (ATR)", minval = 0.5, step = 0.1, group = gE)
atrLen = input.int(14, "ATR length", minval = 2, group = gE)
gO = "Learned odds"
lbMin = input.float(0.60, "Min odds (Wilson lower bound)", minval = 0.3, maxval = 0.99, step = 0.01, group = gO)
rhoMin = input.float(0.35, "Min retrace (fraction of k)", minval = 0.0, maxval = 0.9, step = 0.05, group = gO)
rhoMax = input.float(0.80, "Max retrace (fraction of k)", minval = 0.1, maxval = 1.0, step = 0.05, group = gO)
minExt = input.float(2.0, "Min swing size (ATR)", minval = 0.5, step = 0.1, group = gO)
shrinkK = input.int(10, "Shrinkage", minval = 0, maxval = 100, group = gO)
zConf = input.float(1.28, "Wilson z", step = 0.01, group = gO)
warmN = input.int(20, "Swings per direction before trading", minval = 5, group = gO)
gM = "Liquidity sweeps"
useSweep = input.bool(true, "Require a recent sweep", group = gM)
sweepBack = input.int(12, "Sweep lookback (bars)", minval = 1, group = gM)
pivLen = input.int(8, "Pivot length", minval = 3, maxval = 30, group = gM)
tierA = input.float(1.0, "Tier A % (0 = off)", minval = 0.0, step = 0.25, group = gM, inline = "t")
tierB = input.float(2.0, "B %", minval = 0.0, step = 0.25, group = gM, inline = "t")
tierC = input.float(4.0, "C %", minval = 0.0, step = 0.25, group = gM, inline = "t")
mergeTol = input.float(0.35, "Merge tolerance (ATR)", minval = 0.1, step = 0.05, group = gM)
decayF = input.float(0.995, "Mass decay per bar", minval = 0.98, maxval = 1.0, step = 0.001, group = gM)
maxCl = input.int(24, "Max clusters", minval = 6, maxval = 40, group = gM)
gD = "Day position"
useDay = input.bool(true, "Require entry near the day's extreme", group = gD)
dayProx = input.float(0.50, "Max distance from day extreme (ADR)", minval = 0.05, step = 0.05, group = gD)
adrLen = input.int(14, "ADR length (days)", minval = 3, group = gD)
gX = "Exits & sizing"
stopBuf = input.float(0.25, "Stop buffer beyond extreme (ATR)", minval = 0.0, step = 0.05, group = gX)
rrTarget = input.float(1.5, "Target (R)", minval = 0.5, step = 0.1, group = gX)
useMagTg = input.bool(true, "Target nearest opposite cluster (1R-4R away)", group = gX)
maxBars = input.int(40, "Time stop (bars)", minval = 3, group = gX)
sizeMode = input.string("% of equity", "Sizing mode", options = ["% of equity", "Risk per trade"], group = gX)
eqPct = input.float(40.0, "Equity per trade (%)", minval = 1.0, maxval = 200.0, step = 5.0, group = gX)
riskPct = input.float(1.0, "Risk per trade (% equity)", minval = 0.05, step = 0.05, group = gX)
maxLev = input.float(2.0, "Max notional / equity", minval = 0.1, step = 0.1, group = gX)
allowL = input.bool(true, "Longs", group = gX, inline = "sd")
allowS = input.bool(true, "Shorts", group = gX, inline = "sd")
gV = "Style"
theme = input.string("Neon", "Theme", options = ["Neon", "Classic"], group = gV)
showAur = input.bool(true, "Aurora band", group = gV, inline = "au")
cenLen = input.int(21, "EMA", minval = 2, group = gV, inline = "au")
showZig = input.bool(true, "Swing legs", group = gV)
showZone = input.bool(true, "Risk / reward zones", group = gV)
showLiq = input.bool(true, "Liquidity lines", group = gV)
showArm = input.bool(false, "Tint background when armed", group = gV)
showDash = input.bool(true, "Dashboard", group = gV)
color upCol = theme == "Neon" ? #00e5b4 : #26a69a
color dnCol = theme == "Neon" ? #ff4d6d : #ef5350
color acCol = theme == "Neon" ? #ffb21e : #f5b041
color upOut = theme == "Neon" ? #2f80ed : #1e88e5
color dnOut = theme == "Neon" ? #6c3cf0 : #8e24aa
color cHide = color.new(#000000, 100)
// ---------------------------------------------------------------- helpers
f_wilson(float p, float n, float z) =>
n > 0 ? (p + z * z / (2 * n) - z * math.sqrt(math.max(p * (1 - p) / n + z * z / (4 * n * n), 0.0))) / (1 + z * z / n) : 0.0
f_cell(int d, float rho, float r) =>
int ri = math.min(int(math.max(math.min(rho, 1.0), 0.0) / 0.2), 4)
int xi = r < 1.5 ? 0 : r < 2.5 ? 1 : r < 4.0 ? 2 : 3
[d * 20 + ri * 4 + xi, d * 5 + ri]
f_meter(float p) =>
int n = na(p) ? 0 : int(math.round(math.max(0.0, math.min(1.0, p)) * 10))
str.repeat("▰", n) + str.repeat("▱", 10 - n)
f_clamp(float v, float lo, float hi) =>
math.min(hi, math.max(lo, v))
// ---------------------------------------------------------------- series
float atrV = ta.atr(atrLen)
float atrS = na(atrV) ? syminfo.mintick * 10 : atrV
float volSd = ta.stdev(volume, 50)
float volMa = ta.sma(volume, 50)
float volZ = na(volSd) or volSd == 0 ? 0.0 : (volume - volMa) / volSd
float ph = ta.pivothigh(high, pivLen, pivLen)
float pl = ta.pivotlow(low, pivLen, pivLen)
bool newDay = timeframe.change("D")
float adrD = request.security(syminfo.tickerid, "D", ta.atr(adrLen)[1], lookahead = barmerge.lookahead_on)
var float dayHi = na
var float dayLo = na
if na(dayHi) or newDay
dayHi := high
dayLo := low
else
dayHi := math.max(dayHi, high)
dayLo := math.min(dayLo, low)
// ---------------------------------------------------------------- state
var bool started = false
var int sid = 0
var int dir = 1
var int b0 = na
var float p0 = na
var float atr0 = na
var float pe = na
var int be = na
var float atre = na
var float deep = na
var int lastTradeSid = -1
var int kept0 = 0
var int kept1 = 0
var array<int> cN = array.new_int(40, 0)
var array<int> cH = array.new_int(40, 0)
var array<int> mN = array.new_int(10, 0)
var array<int> mH = array.new_int(10, 0)
var array<int> liveT = array.new_int()
var array<int> liveC = array.new_int()
var array<int> liveM = array.new_int()
var array<float> cPx = array.new_float()
var array<float> cMs = array.new_float()
var array<int> cSd = array.new_int() // -1 above price, 1 below
var int lastPurgeUp = na
var int lastPurgeDn = na
var array<line> legs = array.new_line()
// ---------------------------------------------------------------- liquidity clusters
f_add(float px, float ms, int sd) =>
int hit = -1
if cPx.size() > 0
for i = 0 to cPx.size() - 1
if cSd.get(i) == sd and math.abs(cPx.get(i) - px) <= atrV * mergeTol
hit := i
break
if hit >= 0
float w = cMs.get(hit)
cPx.set(hit, (cPx.get(hit) * w + px * ms) / (w + ms))
cMs.set(hit, w + ms)
else
cPx.push(px)
cMs.push(ms)
cSd.push(sd)
float baseM = 1.0 + math.max(volZ, 0.0) * 0.6
if not na(atrV)
if not na(ph)
if tierA > 0
f_add(ph * (1 + tierA / 100), baseM * 0.8, -1)
if tierB > 0
f_add(ph * (1 + tierB / 100), baseM, -1)
if tierC > 0
f_add(ph * (1 + tierC / 100), baseM, -1)
if not na(pl)
if tierA > 0
f_add(pl * (1 - tierA / 100), baseM * 0.8, 1)
if tierB > 0
f_add(pl * (1 - tierB / 100), baseM, 1)
if tierC > 0
f_add(pl * (1 - tierC / 100), baseM, 1)
// sweeps consume clusters
bool purgeUp = false
bool purgeDn = false
if cPx.size() > 0
for i = cPx.size() - 1 to 0
float px = cPx.get(i)
bool gone = false
if cSd.get(i) == -1 and high >= px
purgeUp := true
gone := true
else if cSd.get(i) == 1 and low <= px
purgeDn := true
gone := true
if gone
cPx.remove(i)
cMs.remove(i)
cSd.remove(i)
if purgeUp
lastPurgeUp := bar_index
if purgeDn
lastPurgeDn := bar_index
// decay and cap
if cMs.size() > 0
for i = cMs.size() - 1 to 0
cMs.set(i, cMs.get(i) * decayF)
if cMs.get(i) < 0.25
cPx.remove(i)
cMs.remove(i)
cSd.remove(i)
while cPx.size() > maxCl
int weakest = 0
for i = 1 to cMs.size() - 1
if cMs.get(i) < cMs.get(weakest)
weakest := i
cPx.remove(weakest)
cMs.remove(weakest)
cSd.remove(weakest)
// ---------------------------------------------------------------- swing engine
bool conf = false
if not started and not na(atrV)
started := true
dir := 1
b0 := bar_index
p0 := low
atr0 := atrV
pe := high
be := bar_index
atre := atrV
deep := close
else if started
if dir == 1
if high > pe
pe := high
be := bar_index
atre := atrV
deep := close
else
deep := math.min(deep, low)
conf := pe - deep >= kMult * atre
else
if low < pe
pe := low
be := bar_index
atre := atrV
deep := close
else
deep := math.max(deep, high)
conf := deep - pe >= kMult * atre
if conf
if showZig and sid >= 2
legs.push(line.new(b0, p0, be, pe, color = color.new(dir == 1 ? upCol : dnCol, 35), width = 1))
while legs.size() > 150
line.delete(legs.shift())
if sid >= 2 and liveT.size() > 0
for i = 0 to liveT.size() - 1
int tt = liveT.get(i)
int cc = liveC.get(i)
int mm = liveM.get(i)
int y = be <= tt ? 1 : 0
cN.set(cc, cN.get(cc) + 1)
cH.set(cc, cH.get(cc) + y)
mN.set(mm, mN.get(mm) + 1)
mH.set(mm, mH.get(mm) + y)
if dir == 1
kept0 += 1
else
kept1 += 1
liveT.clear()
liveC.clear()
liveM.clear()
sid += 1
int nd = -dir
p0 := pe
b0 := be
atr0 := atre
pe := deep
be := bar_index
atre := atrV
deep := close
dir := nd
// ---------------------------------------------------------------- live odds
float rho = na
float ext = na
float lbIn = na
if started
int d = dir == 1 ? 0 : 1
rho := dir * (pe - close) / (kMult * atre)
ext := dir * (pe - p0) / atr0
[c, mi] = f_cell(d, rho, ext / kMult)
liveT.push(bar_index)
liveC.push(c)
liveM.push(mi)
int nC = cN.get(c)
int hC = cH.get(c)
int nM = mN.get(mi)
float pm = nM > 0 ? mH.get(mi) / nM : 0.5
float pIn = (hC + shrinkK * pm) / (nC + shrinkK)
lbIn := f_wilson(pIn, nC + shrinkK, zConf)
bool ready = kept0 >= warmN and kept1 >= warmN
// ---------------------------------------------------------------- signals
dayOk(bool isShort) =>
bool ok = true
if useDay and timeframe.isintraday and not na(adrD) and adrD > 0
ok := isShort ? (dayHi - close) / adrD <= dayProx : (close - dayLo) / adrD <= dayProx
ok
sweepOk(bool isShort) =>
bool ok = true
if useSweep
if isShort
ok := not na(lastPurgeUp) and bar_index - lastPurgeUp <= sweepBack
else
ok := not na(lastPurgeDn) and bar_index - lastPurgeDn <= sweepBack
ok
bool oddsOk = started and ready and not na(lbIn) and lbIn >= lbMin and ext >= minExt and rho >= rhoMin and rho <= rhoMax
bool flat = strategy.position_size == 0
bool goShort = oddsOk and flat and sid != lastTradeSid and allowS and dir == 1 and sweepOk(true) and dayOk(true)
bool goLong = oddsOk and flat and sid != lastTradeSid and allowL and dir == -1 and sweepOk(false) and dayOk(false)
bool armed = oddsOk and flat and sid != lastTradeSid
var float stopPx = na
var float tgtPx = na
var int entryBar = na
if goShort or goLong
bool isS = goShort
float stopP = isS ? pe + stopBuf * atre : pe - stopBuf * atre
float risk = math.abs(stopP - close)
float tgt = isS ? close - rrTarget * risk : close + rrTarget * risk
if useMagTg and cPx.size() > 0
float best = na
for i = 0 to cPx.size() - 1
float px = cPx.get(i)
if isS and cSd.get(i) == 1
float dist = close - px
if dist >= risk and dist <= 4 * risk and (na(best) or px > best)
best := px
if not isS and cSd.get(i) == -1
float dist = px - close
if dist >= risk and dist <= 4 * risk and (na(best) or px < best)
best := px
if not na(best)
tgt := best
if risk > 0
float qEq = strategy.equity * eqPct / 100 / (close * syminfo.pointvalue)
float qRisk = strategy.equity * riskPct / 100 / (risk * syminfo.pointvalue)
float qCap = strategy.equity * maxLev / (close * syminfo.pointvalue)
float qty = math.min(sizeMode == "Risk per trade" ? qRisk : qEq, qCap)
stopPx := stopP
tgtPx := tgt
entryBar := bar_index
lastTradeSid := sid
if isS
strategy.entry("Fade S", strategy.short, qty = qty, comment = "S " + str.tostring(lbIn * 100, "0") + "%")
else
strategy.entry("Fade L", strategy.long, qty = qty, comment = "L " + str.tostring(lbIn * 100, "0") + "%")
if goShort or strategy.position_size < 0
strategy.exit("Exit S", "Fade S", stop = stopPx, limit = tgtPx)
if goLong or strategy.position_size > 0
strategy.exit("Exit L", "Fade L", stop = stopPx, limit = tgtPx)
if strategy.position_size != 0 and not na(entryBar) and bar_index - entryBar >= maxBars
strategy.close_all(comment = "time stop")
// ---------------------------------------------------------------- aurora band
float cen = ta.ema(close, cenLen)
float e01 = nz(ta.percentrank(ta.atr(5) / ta.atr(50), 200), 50.0) / 100.0
float score = ta.ema(f_clamp((close - nz(cen, close)) / atrS, -1.0, 1.0), 8)
float hueT = 0.5 + 0.5 * nz(score)
color cIn = color.from_gradient(hueT, 0.0, 1.0, dnCol, upCol)
color cOut = color.from_gradient(hueT, 0.0, 1.0, dnOut, upOut)
float baseW = (0.5 + 1.0 * e01) * atrS
float upW = ta.ema(baseW * (1.0 + 0.5 * math.max(score, 0.0)), 8)
float dnW = ta.ema(baseW * (1.0 + 0.5 * math.max(-score, 0.0)), 8)
bool aurOn = showAur and not na(cen) and not na(upW) and not na(dnW)
f_edge(int k, int side) =>
float w = side == 1 ? upW : dnW
aurOn ? cen + side * w * k / 2.0 : na
f_bc(int j) =>
float f = j / 2.0
color.new(color.from_gradient(f, 0.0, 1.0, cIn, cOut), int(f_clamp(94.0 - 16.0 * (1.0 - f), 0.0, 100.0)))
pC = plot(aurOn ? cen : na, "Aurora axis", cHide, display = display.pane, editable = false)
pU1 = plot(f_edge(1, 1), "Up 1", cHide, display = display.pane, editable = false)
pU2 = plot(f_edge(2, 1), "Up 2", cHide, display = display.pane, editable = false)
pD1 = plot(f_edge(1, -1), "Down 1", cHide, display = display.pane, editable = false)
pD2 = plot(f_edge(2, -1), "Down 2", cHide, display = display.pane, editable = false)
fill(pC, pU1, f_edge(1, 1), cen, f_bc(1), f_bc(0), title = "Up 1")
fill(pU1, pU2, f_edge(2, 1), f_edge(1, 1), f_bc(2), f_bc(1), title = "Up 2")
fill(pC, pD1, cen, f_edge(1, -1), f_bc(0), f_bc(1), title = "Down 1")
fill(pD1, pD2, f_edge(1, -1), f_edge(2, -1), f_bc(1), f_bc(2), title = "Down 2")
plot(aurOn ? cen : na, "Centre line", color.new(cIn, 10), 2, display = display.pane)
// ---------------------------------------------------------------- trade zones
bool inTrade = strategy.position_size != 0
pEntry = plot(inTrade ? strategy.position_avg_price : na, "Entry", color.new(color.gray, 50), 1, plot.style_linebr)
pStop = plot(inTrade ? stopPx : na, "Stop", color.new(dnCol, 30), 1, plot.style_linebr)
pTgt = plot(inTrade ? tgtPx : na, "Target", color.new(upCol, 30), 1, plot.style_linebr)
fill(pEntry, pStop, showZone ? color.new(dnCol, 86) : na, "Risk zone")
fill(pEntry, pTgt, showZone ? color.new(upCol, 86) : na, "Reward zone")
bgcolor(showArm and armed ? color.new(dir == 1 ? dnCol : upCol, 94) : na, title = "Armed")
// ---------------------------------------------------------------- live leg and liquidity lines (last bar)
var line legLn = na
var array<box> heat = array.new_box()
if barstate.islast
if showZig and started
color lc = dir == 1 ? upCol : dnCol
if na(legLn)
legLn := line.new(b0, p0, be, pe, color = color.new(lc, 35), width = 1, style = line.style_dashed)
line.set_xy1(legLn, b0, p0)
line.set_xy2(legLn, be, pe)
line.set_color(legLn, color.new(lc, 35))
while heat.size() > 0
box.delete(heat.shift())
if showLiq and cPx.size() > 0 and not na(atrV)
float mx = 0.1
for i = 0 to cMs.size() - 1
mx := math.max(mx, cMs.get(i))
for i = 0 to cPx.size() - 1
float px = cPx.get(i)
if math.abs(px - close) <= 8 * atrV
float inten = cMs.get(i) / mx
color hc = cSd.get(i) == -1 ? dnCol : upCol
heat.push(box.new(math.max(bar_index - 30, 0), px + atrV * 0.04, bar_index + 3, px - atrV * 0.04, border_color = na, bgcolor = color.new(hc, 90 - int(inten * 20))))
// ---------------------------------------------------------------- dashboard
var table tb = table.new(position.top_right, 2, 6, bgcolor = color.new(chart.bg_color, 6), frame_color = color.new(chart.fg_color, 85), frame_width = 1, border_color = color.new(chart.bg_color, 100), border_width = 2)
f_row(table t, int r, string k, string v, color c) =>
table.cell(t, 0, r, " " + k, text_color = color.new(chart.fg_color, 40), text_size = size.small, text_halign = text.align_left)
table.cell(t, 1, r, v + " ", text_color = c, text_size = size.small, text_halign = text.align_right, text_font_family = font.family_monospace)
if showDash and barstate.islast
color fg = chart.fg_color
int ct = strategy.closedtrades
float wr = ct > 0 ? strategy.wintrades / ct : na
float pf = strategy.grossloss > 0 ? strategy.grossprofit / strategy.grossloss : na
float net = strategy.netprofit / strategy.initial_capital * 100
float dd = strategy.max_drawdown / strategy.initial_capital * 100
string st = not ready ? "Warming " + str.tostring(math.min(kept0, kept1)) + "/" + str.tostring(warmN) : inTrade ? "In trade" : armed ? "Armed" : "Scanning"
table.cell(tb, 0, 0, " SWING FADE", text_color = fg, text_size = size.small, text_halign = text.align_left, text_formatting = text.format_bold)
table.cell(tb, 1, 0, st + " ", text_color = inTrade or armed ? acCol : color.new(fg, 40), text_size = size.small, text_halign = text.align_right)
f_row(tb, 1, "Swing", started ? (dir == 1 ? "▲ " : "▼ ") + str.tostring(ext, "0.0") + " ATR" : "–", dir == 1 ? upCol : dnCol)
f_row(tb, 2, "Extreme in", na(lbIn) ? "–" : f_meter(lbIn) + " " + str.tostring(lbIn * 100, "0") + "%", not na(lbIn) and lbIn >= lbMin ? acCol : fg)
f_row(tb, 3, "Win rate", na(wr) ? "–" : str.tostring(wr * 100, "0") + "% of " + str.tostring(ct), fg)
f_row(tb, 4, "Profit factor", na(pf) ? "–" : str.tostring(pf, "0.00"), na(pf) ? fg : pf >= 1 ? upCol : dnCol)
f_row(tb, 5, "Net / max DD", str.tostring(net, "0.0") + "% / " + str.tostring(dd, "0.0") + "%", net >= 0 ? upCol : dnCol)