本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © kasapop56394
//@version=6
indicator("KP Double Blade v1.0", shorttitle="KP-DB", overlay=true, max_labels_count=500, max_lines_count=500)
// ======================= Inputs =======================
// NOTE: all distances are in PRICE POINTS of the chart symbol (XAUUSD: 1.00 = 1 point = $1 move in price)
gM = "HTF Bias (MACD)"
fastLen = input.int(12, "MACD Fast", minval=1, group=gM)
slowLen = input.int(26, "MACD Slow", minval=1, group=gM)
sigLen = input.int(9, "MACD Signal", minval=1, group=gM)
biasTF = input.timeframe("15", "Bias timeframe", group=gM)
bPeak = input.float(5.0, "Prev wave peak must exceed (+/-)", step=0.5, group=gM)
bDeep = input.float(10.0, "Deep level (+/-)", step=0.5, group=gM)
bExit = input.float(5.0, "Exit when MACD back to (+/-)", step=0.5, group=gM)
spkMode = input.string("Points", "Spike filter", options=["Points", "ATR", "Off"], group=gM)
spkPts = input.float(30.0, "Spike: Open-High or Open-Low > points", step=1, group=gM)
spkATR = input.float(2.5, "Spike: High-Low > ATR(14) x", step=0.1, group=gM)
spkBars = input.int(3, "Spike bars checked (incl. cross bar)", minval=1, maxval=10, group=gM)
gS = "Stochastic Entry / Exit"
entryTF = input.timeframe("5", "Sto timeframe (>= chart TF)", group=gS)
kLen = input.int(9, "%K length", minval=1, group=gS)
kSm = input.int(3, "%K smoothing", minval=1, group=gS)
dSm = input.int(3, "%D smoothing", minval=1, group=gS)
lvlMode = input.string("%K only", "Level check at cross", options=["%K only", "%K and %D"], group=gS)
buyIn = input.float(30, "Buy entry: cross up below", group=gS)
buyOut = input.float(60, "Buy exit: cross down at/above", group=gS)
sellIn = input.float(70, "Sell entry: cross down above", group=gS)
sellOut = input.float(30, "Sell exit: cross up at/below", group=gS)
useMF = input.bool(false, "MACD filter at Sto cross (Buy: red & < -X, Sell: green & > +X)", group=gS)
mfLvl = input.float(2.0, "MACD filter X", step=0.5, group=gS)
gF = "Entry timing filter (entry-TF MACD)"
timMode = input.string("Off", "Timing mode", options=["Off", "Hook", "Slope", "Decel", "Arm & Wait"], group=gF, tooltip="Hook: MACD turned in trade direction. Slope: block if MACD moved too steeply against trade over N bars (in ATR units). Decel: MACD-Signal gap shrinking. Arm & Wait: after Sto signal, wait up to N bars for MACD hook.")
slopeN = input.int(3, "Slope lookback bars", minval=1, group=gF)
slopeMax = input.float(0.5, "Slope max (MACD change / ATR)", step=0.05, group=gF)
waitN = input.int(3, "Arm & Wait: max bars to wait", minval=1, group=gF)
gE = "Execution (points)"
slPts = input.float(10.0, "Initial SL (points)", step=0.5, group=gE)
useBE = input.bool(false, "Use BE (move SL to entry +/- lock)", group=gE)
beTrig = input.float(5.0, "BE trigger: profit >= points", step=0.25, group=gE)
beOff = input.float(0.25, "BE lock: entry +/- points", step=0.05, group=gE)
costPts = input.float(0.0, "Cost per trade (spread, points)", step=0.05, group=gE)
doSell = input.bool(true, "Trade Sell", group=gE)
doBuy = input.bool(true, "Trade Buy", group=gE)
endClose = input.bool(true, "Bias end: close if in profit, else keep", group=gE)
gT = "Display"
fromT = input.time(timestamp("01 Jan 2026 00:00 +0700"), "Start from", group=gT)
showBg = input.bool(true, "Bias background", group=gT)
showTr = input.bool(true, "Draw trades (+/- points labels)", group=gT)
gA = "Alerts"
alOn = input.bool(true, "Enable alert() messages (create alert: Any alert() function call)", group=gA)
alBias = input.bool(true, "Alert: bias start / end", group=gA)
alEntry = input.bool(true, "Alert: entries", group=gA)
alExit = input.bool(true, "Alert: exits (STO / SL / BE / bias end)", group=gA)
alBE = input.bool(true, "Alert: BE moved", group=gA)
// ======================= HTF Bias =======================
f_bias() =>
[m, s, h] = ta.macd(close, fastLen, slowLen, sigLen)
a = ta.atr(14)
xDn = ta.crossunder(m, s)
xUp = ta.crossover(m, s)
var int st = 0
var float pk = na
var float tr = na
var bool pkUsed = false
var bool trUsed = false
var bool deep = false
var bool flip = false
if m >= 0 and nz(m[1]) < 0
pk := m
pkUsed := false
else if m >= 0
pk := math.max(nz(pk, m), m)
if m < 0 and nz(m[1]) >= 0
tr := m
trUsed := false
else if m < 0
tr := math.min(nz(tr, m), m)
bool spike = false
if spkMode != "Off"
for i = 0 to spkBars - 1
bool hit = spkMode == "Points" ? (high[i] - open[i] > spkPts or open[i] - low[i] > spkPts) : (high[i] - low[i] > spkATR * a[i])
if hit
spike := true
if st == -1
deep := deep or m <= -bDeep
flip := flip or m < 0
if (deep and xUp) or (flip and m >= bExit)
st := 0
else if st == 1
deep := deep or m >= bDeep
flip := flip or m > 0
if (deep and xDn) or (flip and m <= -bExit)
st := 0
if st == 0
if xDn and not na(pk) and pk > bPeak and not pkUsed and not spike
st := -1
pkUsed := true
deep := m <= -bDeep
flip := m < 0
else if xUp and not na(tr) and tr < -bPeak and not trUsed and not spike
st := 1
trUsed := true
deep := m >= bDeep
flip := m > 0
st[1]
// ======================= Stochastic on entry TF (last closed bar) =======================
f_sto() =>
k = ta.sma(ta.stoch(close, high, low, kLen), kSm)
d = ta.sma(k, dSm)
xUp = ta.crossover(k, d)
xDn = ta.crossunder(k, d)
[m, s, h] = ta.macd(close, fastLen, slowLen, sigLen)
a = ta.atr(14)
[k[1], d[1], xUp[1], xDn[1], m[1], m[2], m[1] - s[1], m[2] - s[2], m[1] - m[1 + slopeN], a[1]]
biasSt = request.security(syminfo.tickerid, biasTF, f_bias(), lookahead=barmerge.lookahead_on)
[sK, sD, sUp, sDn, sM, sM2, sG, sG2, sSlp, sAtr] = request.security(syminfo.tickerid, entryTF, f_sto(), lookahead=barmerge.lookahead_on)
newEBar = timeframe.change(entryTF)
tfBad = timeframe.in_seconds(entryTF) < timeframe.in_seconds()
bool bothMode = lvlMode == "%K and %D"
baseBuy = newEBar and sUp and sK < buyIn and (not bothMode or sD < buyIn) and (not useMF or sM < -mfLvl)
baseSell = newEBar and sDn and sK > sellIn and (not bothMode or sD > sellIn) and (not useMF or sM > mfLvl)
buyExit = newEBar and sDn and sK >= buyOut and (not bothMode or sD >= buyOut)
sellExit = newEBar and sUp and sK <= sellOut and (not bothMode or sD <= sellOut)
// ---- entry timing filter ----
bool hookB = sM > sM2
bool hookS = sM < sM2
bool decB = sG > sG2
bool decS = sG < sG2
float slpN = sAtr > 0 ? sSlp / sAtr : 0.0
bool slopeB = slpN > -slopeMax
bool slopeS = slpN < slopeMax
var int armDir = 0
var int armCnt = 0
bool trigB = false
bool trigS = false
if timMode == "Arm & Wait" and newEBar
if armDir != 0
armCnt += 1
if armDir == 1 and hookB
trigB := true
armDir := 0
else if armDir == -1 and hookS
trigS := true
armDir := 0
else if armCnt >= waitN
armDir := 0
if baseBuy
if hookB
trigB := true
else
armDir := 1
armCnt := 0
if baseSell
if hookS
trigS := true
else
armDir := -1
armCnt := 0
buyEntry = timMode == "Off" ? baseBuy : timMode == "Hook" ? (baseBuy and hookB) : timMode == "Slope" ? (baseBuy and slopeB) : timMode == "Decel" ? (baseBuy and decB) : trigB
sellEntry = timMode == "Off" ? baseSell : timMode == "Hook" ? (baseSell and hookS) : timMode == "Slope" ? (baseSell and slopeS) : timMode == "Decel" ? (baseSell and decS) : trigS
// ======================= Trade simulation (points only) =======================
var int pos = 0
var float ent = na
var float slP = na
var bool beOn = false
var int entBar = na
inTest = time >= fromT
float exitPx = na
string why = ""
int dirNow = 0
bool enteredNow = false
bool beNow = false
int exitDir = 0
float exitEnt = na
float exitPts = na
// 1) bias ended while holding -> close at open if in profit
if pos != 0 and biasSt != pos and nz(biasSt[1]) == pos and endClose
if (pos == 1 ? open - ent : ent - open) > 0
exitPx := open
why := "END"
// 2) Sto exit signal from the bar that just closed -> exit at open
if pos != 0 and na(exitPx)
if (pos == 1 and buyExit) or (pos == -1 and sellExit)
exitPx := open
why := "STO"
// 3) entry at open (flat, no exit on this bar)
if pos == 0 and na(exitPx) and inTest
if biasSt == 1 and buyEntry and doBuy
pos := 1
ent := open
slP := open - slPts
beOn := false
entBar := bar_index
enteredNow := true
else if biasSt == -1 and sellEntry and doSell
pos := -1
ent := open
slP := open + slPts
beOn := false
entBar := bar_index
enteredNow := true
dirNow := pos
// 4) SL / BE stop check within this bar
if pos != 0 and na(exitPx)
bool hit = pos == 1 ? low <= slP : high >= slP
if hit
// realistic fill: if the bar opens beyond the stop (gap), fill at open
exitPx := pos == 1 ? math.min(open, slP) : math.max(open, slP)
why := beOn ? "BE" : "SL"
// 5) BE move (conservative: becomes active from next bar)
if useBE and pos != 0 and na(exitPx) and not beOn
float fav = pos == 1 ? high - ent : ent - low
if fav >= beTrig
slP := pos == 1 ? ent + beOff : ent - beOff
beOn := true
beNow := true
f_sgn(float v) =>
(v >= 0 ? "+" : "") + str.tostring(v, "#.##")
// 6) record (points)
if not na(exitPx)
float pts = (pos == 1 ? exitPx - ent : ent - exitPx) - costPts
exitDir := pos
exitEnt := ent
exitPts := pts
if showTr
line.new(entBar, ent, bar_index, exitPx, color=(pts > 0 ? color.teal : color.red), width=2)
string txt = (pos == 1 ? "B " : "S ") + why + " " + f_sgn(pts)
label.new(bar_index, exitPx, txt, style=(pos == 1 ? label.style_label_down : label.style_label_up), color=(pts > 0 ? color.new(color.teal, 20) : color.new(color.red, 20)), textcolor=color.white, size=size.tiny)
pos := 0
ent := na
slP := na
beOn := false
entBar := na
// ======================= Alerts =======================
bool biasSStart = biasSt == -1 and nz(biasSt[1]) != -1
bool biasBStart = biasSt == 1 and nz(biasSt[1]) != 1
bool biasEnd = biasSt == 0 and nz(biasSt[1]) != 0
bool exitNow = not na(exitPx)
string tk = syminfo.ticker + " "
if alOn and barstate.isrealtime
if alBias and biasSStart
alert("KP-DB " + tk + "BIAS SELL started (" + biasTF + ")", alert.freq_once_per_bar)
if alBias and biasBStart
alert("KP-DB " + tk + "BIAS BUY started (" + biasTF + ")", alert.freq_once_per_bar)
if alBias and biasEnd
alert("KP-DB " + tk + "BIAS ended -> NONE", alert.freq_once_per_bar)
if alEntry and enteredNow
alert("KP-DB " + tk + (dirNow == 1 ? "BUY" : "SELL") + " @ " + str.tostring(open, "#.##") + " SL " + str.tostring(dirNow == 1 ? open - slPts : open + slPts, "#.##") + " | Sto K " + str.tostring(sK, "#.0"), alert.freq_once_per_bar)
if alExit and exitNow
alert("KP-DB " + tk + "EXIT " + (exitDir == 1 ? "BUY" : "SELL") + " by " + why + " @ " + str.tostring(exitPx, "#.##") + " (entry " + str.tostring(exitEnt, "#.##") + ") " + f_sgn(exitPts) + " pts", alert.freq_once_per_bar)
if alBE and beNow
alert("KP-DB " + tk + "BE moved: SL -> " + str.tostring(slP, "#.##"), alert.freq_once_per_bar)
alertcondition(enteredNow and dirNow == 1, "KP-DB Buy entry", "KP-DB BUY entry {{ticker}} @ {{open}}")
alertcondition(enteredNow and dirNow == -1, "KP-DB Sell entry", "KP-DB SELL entry {{ticker}} @ {{open}}")
alertcondition(exitNow, "KP-DB Exit", "KP-DB EXIT {{ticker}} @ {{close}}")
alertcondition(biasSStart, "KP-DB Bias Sell start", "KP-DB BIAS SELL started {{ticker}}")
alertcondition(biasBStart, "KP-DB Bias Buy start", "KP-DB BIAS BUY started {{ticker}}")
alertcondition(biasEnd, "KP-DB Bias end", "KP-DB BIAS ended {{ticker}}")
// ======================= Visuals =======================
bgcolor(showBg and biasSt == -1 ? color.new(color.red, 92) : showBg and biasSt == 1 ? color.new(color.teal, 92) : na, title="Bias BG")
plotshape(enteredNow and dirNow == -1, "Sell entry", shape.triangledown, location.abovebar, color.red, size=size.small)
plotshape(enteredNow and dirNow == 1, "Buy entry", shape.triangleup, location.belowbar, color.teal, size=size.small)
plot(pos != 0 ? slP : na, "Current stop", color=color.orange, style=plot.style_linebr)
// timeframe warning (Sto TF must be >= chart TF)
var label warnLb = na
if barstate.islast
label.delete(warnLb)
warnLb := na
if tfBad
warnLb := label.new(bar_index, high, "KP-DB: Sto timeframe < chart timeframe!", style=label.style_label_down, color=color.orange, textcolor=color.black, size=size.small)