本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Kalman Scalper", overlay = true, max_labels_count = 500, max_lines_count = 500)
// ── Inputs ──────────────────────────────────────────────────────────────
grpST = "Kalman Supertrend"
srcIn = input.source(hl2, "Source", group = grpST)
atrLen = input.int(10, "ATR length", minval = 1, group = grpST)
mult = input.float(2.5, "ATR multiplier", minval = 0.1, step = 0.1, group = grpST)
kQ = input.float(0.05, "Kalman process noise (Q)", minval = 0.0001, step = 0.01, group = grpST, tooltip = "Higher = filter follows price faster, less smoothing")
useKal = input.bool(true, "Use Kalman filter (off = plain Supertrend)", group = grpST, tooltip = "Backtest on XAUUSD 30m: plain Supertrend did as well or better")
kR = input.float(1.0, "Kalman measurement noise (R)", minval = 0.0001, step = 0.1, group = grpST, tooltip = "Higher = smoother, more lag")
grpHtf = "Higher-timeframe trend filter"
useHtf = input.bool(true, "Only take signals with the higher-TF trend", group = grpHtf, tooltip = "Backtest on XAUUSD 30m: the one change that clearly helped. Daily trend filter beat the 4h filter in the 240-config sweep")
htfTf = input.timeframe("D", "Higher timeframe", group = grpHtf, tooltip = "Best-tested: Daily. 4h (240) was slightly weaker")
grpPlan = "Trade plan (entry / stop-loss / 4 targets)"
showPlan = input.bool(true, "Show trade plan", group = grpPlan)
onlyLast = input.bool(true, "Draw levels for the latest trade only", group = grpPlan)
longOnly = input.bool(true, "Long (BUY) trades only", group = grpPlan, tooltip = "Backtest 30m XAUUSD: longs +88.6R (PF 1.92), shorts -5.8R (PF 0.91). The long-only edge comes from gold rising 3x in the test period; if gold turns into a bear market, switch this off and re-test")
slMult = input.float(3.5, "Stop-loss = ATR x", minval = 0.5, step = 0.1, group = grpPlan, tooltip = "Best-tested plateau: 3.0 to 4.0 x ATR(14), centre 3.5. Wider stops beat tight ones in every test")
slAtrLen = input.int(14, "ATR length for SL", minval = 1, group = grpPlan)
tr1 = input.float(3.0, "TP1 (R multiple)", minval = 0.25, step = 0.25, group = grpPlan, tooltip = "Best-tested ladder: 3 / 4 / 5 / 6 R with 25% closed at each target. Close targets did worse. About 45% of trades win; most trades are small losses and a few big trend winners pay for them")
tr2 = input.float(4.0, "TP2 (R multiple)", minval = 0.25, step = 0.25, group = grpPlan)
tr3 = input.float(5.0, "TP3 (R multiple)", minval = 0.25, step = 0.25, group = grpPlan)
tr4 = input.float(6.0, "TP4 (R multiple)", minval = 0.25, step = 0.25, group = grpPlan)
accBal = input.float(1000.0, "Account balance ($)", minval = 1, group = grpPlan)
riskPct = input.float(2.0, "Risk per trade (%)", minval = 0.1, step = 0.1, group = grpPlan, tooltip = "Lot size is chosen so a stop-out loses about this % of the account (min 0.01 lot). The stop is ~$28/oz, so on a $1,000 account the 0.01 minimum already risks ~2.8%")
leverage = input.float(30.0, "Leverage (1:x)", minval = 1, group = grpPlan)
maxMargin = input.float(50.0, "Max margin used (% of account)", minval = 1, maxval = 100, group = grpPlan)
contract = input.float(100.0, "Contract size (oz per lot)", minval = 1, group = grpPlan, tooltip = "XAUUSD CFD: 1 lot = 100 oz. Check your broker")
grpBand = "Extras (all off by default - no backtest edge)"
showBands = input.bool(false, "Show VWMA overbought / oversold bands", group = grpBand)
bandLen = input.int(20, "VWMA length", minval = 2, group = grpBand)
hhLen = input.int(20, "Highest-high / lowest-low lookback", minval = 2, group = grpBand)
obMult = input.float(1.0, "Band width multiplier", minval = 0.1, step = 0.1, group = grpBand)
showR = input.bool(false, "Show R reversal labels", group = grpBand, tooltip = "Backtest on XAUUSD 30m: fading R labels lost money in every variant")
showAbs = input.bool(false, "Show absorption bubbles", group = grpBand, tooltip = "Backtest: no measurable edge, use as context only")
absLen = input.int(20, "Volume average length", minval = 2, group = grpBand)
absVol = input.float(2.0, "Min volume vs average (x)", minval = 1.0, step = 0.1, group = grpBand)
absRange = input.float(0.8, "Max bar range vs ATR (x)", minval = 0.1, step = 0.1, group = grpBand)
absBig = input.float(3.0, "Large bubble at volume (x)", minval = 1.0, step = 0.1, group = grpBand)
absHuge = input.float(4.5, "Huge bubble at volume (x)", minval = 1.0, step = 0.1, group = grpBand)
grpVis = "Display"
showSig = input.bool(true, "Show BUY / SELL arrows", group = grpVis)
upCol = input.color(color.new(#00c389, 0), "Buy colour (buy targets)", group = grpVis)
dnCol = input.color(color.new(#ff4d4f, 0), "Sell colour (sell targets)", group = grpVis)
slCol = input.color(color.new(#ffb020, 0), "Stop-loss colour", group = grpVis)
// ── Kalman filter (1-D, random-walk model), safe against na inputs ──────
kalman(float src, float q, float r) =>
var float est = na
var float p = 1.0
if not na(src)
if na(est)
est := src
else
p += q
k = p / (p + r)
est := est + k * (src - est)
p := (1 - k) * p
est
// ── Supertrend on filtered price and filtered ATR ───────────────────────
// returns [direction (1 up / -1 down), trailing stop line]
stDir(float src, int len, float m, float q, float r, bool kal) =>
rawA = ta.rma(ta.tr(true), len)
ks = kalman(src, q, r)
ka = kalman(rawA, q, r)
pr = kal ? ks : src
at = kal ? ka : rawA
upR = pr + m * at
loR = pr - m * at
var float uB = na
var float lB = na
var int dr = 1
lB := (loR > nz(lB[1], loR) or close[1] < nz(lB[1], loR)) ? loR : nz(lB[1], loR)
uB := (upR < nz(uB[1], upR) or close[1] > nz(uB[1], upR)) ? upR : nz(uB[1], upR)
if dr == 1 and close < lB
dr := -1
else if dr == -1 and close > uB
dr := 1
[dr, dr == 1 ? lB : uB]
// last COMPLETED higher-timeframe bar's direction (no repainting / lookahead)
htfDirPrev(float src, int len, float m, float q, float r, bool kal) =>
[d, l] = stDir(src, len, m, q, r, kal)
d[1]
[dir, stopLine] = stDir(srcIn, atrLen, mult, kQ, kR, useKal)
htfDir = request.security(syminfo.tickerid, htfTf, htfDirPrev(srcIn, atrLen, mult, kQ, kR, useKal), lookahead = barmerge.lookahead_on)
flipUp = dir == 1 and dir[1] == -1
flipDown = dir == -1 and dir[1] == 1
buySig = flipUp and (not useHtf or htfDir == 1)
sellSig = flipDown and (not useHtf or htfDir == -1) and not longOnly
rawAtr = ta.rma(ta.tr(true), atrLen)
atrSL = ta.atr(slAtrLen)
// ── Trade plan: entry at signal close, SL, TP1-TP4 (25% closed at each), exit on SL / flip ──
frac = 0.25
tpRs = array.from(tr1, tr2, tr3, tr4)
var bool active = false
var bool hasTrade = false
var int tSide = 0
var int entryBar = na
var int closeBar = na
var float entryP = na
var float slP = na
var float slDist = na
var float lots = na
var float rem = 0.0
var float realized = 0.0
var int nHit = 0
var string status = "No trade yet"
var array<float> tps = array.new<float>(4, na)
var array<bool> hits = array.new<bool>(4, false)
var array<line> objL = array.new<line>()
var array<label> objB = array.new<label>()
var int nTrades = 0
var int nWins = 0
var float netR = 0.0
if showPlan
if active
bool slHit = tSide == 1 ? low <= slP : high >= slP
string endTag = ""
if slHit
realized += rem * -1.0
rem := 0.0
endTag := "SL"
else
for q = 0 to 3
if not array.get(hits, q)
lvl = array.get(tps, q)
reached = tSide == 1 ? high >= lvl : low <= lvl
if reached
array.set(hits, q, true)
realized += frac * array.get(tpRs, q)
rem -= frac
nHit += 1
alert(str.format("Kalman Scalper: TP{0} hit on {1} at {2}", str.tostring(q + 1), syminfo.ticker, str.tostring(lvl, "#.##")), alert.freq_once_per_bar_close)
if rem <= 0.0001
endTag := "TP4"
else if (tSide == 1 and flipDown) or (tSide == -1 and flipUp)
realized += rem * tSide * (close - entryP) / slDist
rem := 0.0
endTag := "EXIT"
if endTag != ""
active := false
closeBar := bar_index
nTrades += 1
netR += realized
nWins += realized > 0 ? 1 : 0
status := "CLOSED - " + (endTag == "SL" ? "stop-loss" : endTag == "TP4" ? "all 4 targets" : "trend flip exit") + " (" + str.tostring(realized, "0.0") + "R)"
for l in objL
line.set_extend(l, extend.none)
line.set_x2(l, bar_index)
label.new(bar_index, close, endTag + " " + str.tostring(realized, "0.0") + "R", style = tSide == 1 ? label.style_label_down : label.style_label_up, color = color.new(realized > 0 ? upCol : dnCol, 20), textcolor = color.white, size = size.small)
alert(str.format("Kalman Scalper: trade closed on {0} - {1} ({2}R)", syminfo.ticker, endTag, str.tostring(realized, "0.0")), alert.freq_once_per_bar_close)
if not active and (buySig or sellSig)
if onlyLast
for l in objL
line.delete(l)
for b in objB
label.delete(b)
array.clear(objL)
array.clear(objB)
active := true
hasTrade := true
tSide := buySig ? 1 : -1
entryBar := bar_index
entryP := close
slDist := slMult * atrSL
slP := entryP - tSide * slDist
rem := 1.0
realized := 0.0
nHit := 0
for q = 0 to 3
array.set(tps, q, entryP + tSide * array.get(tpRs, q) * slDist)
array.set(hits, q, false)
lotsRisk = accBal * riskPct / 100 / (slDist * contract)
lotsMargin = accBal * maxMargin / 100 * leverage / (entryP * contract)
lots := math.max(0.01, math.floor(math.min(lotsRisk, lotsMargin) / 0.01) * 0.01)
status := "ACTIVE - waiting for targets"
tCol = tSide == 1 ? upCol : dnCol
array.push(objL, line.new(bar_index, entryP, bar_index + 1, entryP, extend = extend.right, color = color.new(color.white, 0), width = 2))
array.push(objL, line.new(bar_index, slP, bar_index + 1, slP, extend = extend.right, color = slCol, width = 2, style = line.style_dashed))
array.push(objB, label.new(bar_index + 3, entryP, (tSide == 1 ? "BUY " : "SELL ") + str.tostring(entryP, "#.##"), style = label.style_label_left, color = color.new(color.blue, 10), textcolor = color.white, size = size.normal))
array.push(objB, label.new(bar_index + 3, slP, "SL " + str.tostring(slP, "#.##"), style = label.style_label_left, color = color.new(slCol, 10), textcolor = color.black, size = size.small))
for q = 0 to 3
lv = array.get(tps, q)
array.push(objL, line.new(bar_index, lv, bar_index + 1, lv, extend = extend.right, color = tCol, width = 2))
array.push(objB, label.new(bar_index + 3, lv, "TP" + str.tostring(q + 1) + " " + str.tostring(lv, "#.##") + " (" + str.tostring(array.get(tpRs, q), "0.#") + "R)", style = label.style_label_left, color = color.new(tCol, 10), textcolor = color.white, size = size.small))
alert(str.format("Kalman Scalper: {0} {1} entry {2} | SL {3} | TP1 {4} | TP2 {5} | TP3 {6} | TP4 {7} | lots {8}", tSide == 1 ? "BUY" : "SELL", syminfo.ticker, str.tostring(entryP, "#.##"), str.tostring(slP, "#.##"), str.tostring(array.get(tps, 0), "#.##"), str.tostring(array.get(tps, 1), "#.##"), str.tostring(array.get(tps, 2), "#.##"), str.tostring(array.get(tps, 3), "#.##"), str.tostring(lots, "0.00")), alert.freq_once_per_bar_close)
if active and nHit > 0
status := "ACTIVE - " + str.tostring(nHit) + " of 4 targets hit"
// keep the level labels at the right edge of the chart
if barstate.islast and showPlan and array.size(objB) > 0
int xr = (active ? bar_index : nz(closeBar, bar_index)) + 3
for b in objB
label.set_x(b, xr)
// ── Corner box ──────────────────────────────────────────────────────────
var table infoT = table.new(position.top_right, 2, 11, bgcolor = color.new(#101418, 5), border_width = 1, border_color = color.new(color.gray, 40), frame_width = 1, frame_color = color.new(color.gray, 30))
if barstate.islast and showPlan
tCol2 = tSide == 1 ? upCol : dnCol
bool fresh = active and bar_index - entryBar <= 1
string head = not hasTrade ? "WAITING FOR SIGNAL" : (fresh ? "NEW " : "") + (tSide == 1 ? "BUY" : "SELL") + (active ? " SIGNAL" : " (closed)")
table.cell(infoT, 0, 0, head, text_color = color.white, bgcolor = not hasTrade ? color.gray : tCol2, text_size = size.large, text_halign = text.align_center)
table.merge_cells(infoT, 0, 0, 1, 0)
table.cell(infoT, 0, 1, "Entry", text_color = color.white, text_size = size.normal, text_halign = text.align_left)
table.cell(infoT, 1, 1, hasTrade ? str.tostring(entryP, "#.##") : "-", text_color = color.white, text_size = size.normal, text_halign = text.align_right)
table.cell(infoT, 0, 2, "Stop-loss", text_color = slCol, text_size = size.normal, text_halign = text.align_left)
table.cell(infoT, 1, 2, hasTrade ? str.tostring(slP, "#.##") : "-", text_color = slCol, text_size = size.normal, text_halign = text.align_right)
for q = 0 to 3
bool h = hasTrade and array.get(hits, q)
table.cell(infoT, 0, 3 + q, "TP" + str.tostring(q + 1) + " (" + str.tostring(array.get(tpRs, q), "0.#") + "R)" + (h ? " OK" : ""), text_color = tCol2, text_size = size.normal, text_halign = text.align_left)
table.cell(infoT, 1, 3 + q, hasTrade ? str.tostring(array.get(tps, q), "#.##") : "-", text_color = tCol2, text_size = size.normal, text_halign = text.align_right)
table.cell(infoT, 0, 7, "Lots", text_color = color.white, text_size = size.normal, text_halign = text.align_left)
table.cell(infoT, 1, 7, hasTrade ? str.tostring(lots, "0.00") : "-", text_color = color.white, text_size = size.normal, text_halign = text.align_right)
table.cell(infoT, 0, 8, "Risk $ / Margin $", text_color = color.white, text_size = size.small, text_halign = text.align_left)
table.cell(infoT, 1, 8, hasTrade ? str.tostring(lots * slDist * contract, "0") + " / " + str.tostring(lots * contract * entryP / leverage, "0") : "-", text_color = color.white, text_size = size.small, text_halign = text.align_right)
table.cell(infoT, 0, 9, status, text_color = color.new(color.white, 10), text_size = size.small, text_halign = text.align_left)
table.merge_cells(infoT, 0, 9, 1, 9)
table.cell(infoT, 0, 10, "Chart: " + str.tostring(nWins) + "/" + str.tostring(nTrades) + " wins | net " + str.tostring(netR, "0.0") + "R (no costs)", text_color = netR >= 0 ? upCol : dnCol, text_size = size.small, text_halign = text.align_left)
table.merge_cells(infoT, 0, 10, 1, 10)
// ── Bands, R labels, absorption (optional extras) ───────────────────────
basis = ta.vwma(close, bandLen)
topVw = ta.vwma(ta.highest(high, hhLen), bandLen)
botVw = ta.vwma(ta.lowest(low, hhLen), bandLen)
obLine = basis + (topVw - basis) * obMult
osLine = basis - (basis - botVw) * obMult
revDown = showR and high > obLine and close < obLine and close < open
revUp = showR and low < osLine and close > osLine and close > open
volRatio = volume / ta.sma(volume, absLen)
absorbed = showAbs and volRatio >= absVol and (high - low) <= absRange * rawAtr
absBull = absorbed and close >= (high + low) / 2
absBear = absorbed and close < (high + low) / 2
// ── Plots ───────────────────────────────────────────────────────────────
plot(stopLine, "Kalman Supertrend", dir == 1 ? upCol : dnCol, 2, style = plot.style_linebr)
pObL = plot(showBands ? obLine : na, "Overbought", color.new(dnCol, 40))
pOsL = plot(showBands ? osLine : na, "Oversold", color.new(upCol, 40))
pBas = plot(showBands ? basis : na, "VWMA basis", color.new(color.gray, 70))
fill(pObL, pBas, color.new(dnCol, 92))
fill(pOsL, pBas, color.new(upCol, 92))
plotshape(showSig and buySig, "Buy", shape.triangleup, location.belowbar, upCol, size = size.small)
plotshape(showSig and sellSig, "Sell", shape.triangledown, location.abovebar, dnCol, size = size.small)
plotshape(revDown, "R down", shape.labeldown, location.abovebar, color.new(color.orange, 0), text = "R", textcolor = color.white, size = size.tiny)
plotshape(revUp, "R up", shape.labelup, location.belowbar, color.new(color.aqua, 0), text = "R", textcolor = color.white, size = size.tiny)
plotshape(absBull and volRatio < absBig, "Absorb bull", shape.circle, location.belowbar, color.new(upCol, 55), size = size.tiny)
plotshape(absBull and volRatio >= absBig and volRatio < absHuge, "Absorb bull large", shape.circle, location.belowbar, color.new(upCol, 45), size = size.small)
plotshape(absBull and volRatio >= absHuge, "Absorb bull huge", shape.circle, location.belowbar, color.new(upCol, 35), size = size.normal)
plotshape(absBear and volRatio < absBig, "Absorb bear", shape.circle, location.abovebar, color.new(dnCol, 55), size = size.tiny)
plotshape(absBear and volRatio >= absBig and volRatio < absHuge, "Absorb bear large", shape.circle, location.abovebar, color.new(dnCol, 45), size = size.small)
plotshape(absBear and volRatio >= absHuge, "Absorb bear huge", shape.circle, location.abovebar, color.new(dnCol, 35), size = size.normal)
// ── Alerts (the alert() calls above carry full levels; use "Any alert() function call") ──
alertcondition(buySig, "Buy signal", "Kalman Scalper: BUY on {{ticker}} @ {{close}}")
alertcondition(sellSig, "Sell signal", "Kalman Scalper: SELL on {{ticker}} @ {{close}}")
alertcondition(revDown, "Bearish R", "Kalman Scalper: bearish reversal (R) on {{ticker}}")
alertcondition(revUp, "Bullish R", "Kalman Scalper: bullish reversal (R) on {{ticker}}")
alertcondition(absBull, "Bullish absorption", "Kalman Scalper: bullish absorption on {{ticker}}")
alertcondition(absBear, "Bearish absorption", "Kalman Scalper: bearish absorption on {{ticker}}")