本页源码来自 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/
//@version=6
// Gaussian Trend Targets Strategy
// Trend: median + Gaussian-smoothed basis with trailing supertrend bands.
// Entry: trend flip, confirmed on bar close, with optional momentum / regime / higher-timeframe filters.
// Exit: stop at the band, scale-out at 1R / 2R, runner to 3R or trailing the band. An opposite flip closes the trade.
strategy("Gaussian Trend Targets Strategy", shorttitle = "GTT Strategy", overlay = true,
initial_capital = 100000, default_qty_type = strategy.fixed, default_qty_value = 1,
commission_type = strategy.commission.percent, commission_value = 0.05, slippage = 2,
pyramiding = 0, process_orders_on_close = true, calc_on_every_tick = false,
fill_orders_on_standard_ohlc = true, margin_long = 100, margin_short = 100)
// ───────────────────────────── Inputs ─────────────────────────────
grTrade = "Trading"
tradeDir = input.string("Long & Short", "Direction", options = ["Long & Short", "Long only", "Short only"], group = grTrade)
lateEntry = input.bool(false, "Allow late entry (once per trend leg)", group = grTrade,
tooltip = "Off: trade only on the flip bar. On: if a filter blocks the flip bar, enter later in the same trend leg once filters pass.")
useDates = input.bool(false, "Limit to date range", group = grTrade)
dateFrom = input.time(timestamp("1 Jan 2023 00:00 +0000"), "From", group = grTrade)
dateTo = input.time(timestamp("1 Jan 2031 00:00 +0000"), "To", group = grTrade)
grTr = "Trend engine"
basisMode = input.string("Median Gaussian", "Basis", options = ["Median Gaussian", "HL2", "Close"], group = grTr)
srcIn = input.source(close, "Source", group = grTr)
gLen = input.int(16, "Gaussian length", minval = 2, group = grTr)
gSigma = input.float(5.0, "Gaussian sigma", minval = 0.1, step = 0.1, group = grTr)
widthMode = input.string("ATR", "Band width", options = ["ATR", "Gaussian deviation"], group = grTr)
atrLen = input.int(10, "ATR length", minval = 1, group = grTr)
atrMult = input.float(3.0, "ATR multiplier", minval = 0.5, step = 0.1, group = grTr)
sdLen = input.int(20, "Deviation length", minval = 2, group = grTr)
sdMult = input.float(2.2, "Deviation multiplier", minval = 0.5, step = 0.1, group = grTr)
grFilt = "Entry filters"
useRmi = input.bool(true, "RMI momentum", group = grFilt, inline = "rmi")
rmiLen = input.int(14, "Length", minval = 2, group = grFilt, inline = "rmi")
rmiLongMin = input.float(50, "Long needs RMI above", group = grFilt)
rmiShortMax = input.float(50, "Short needs RMI below", group = grFilt)
useRegime = input.bool(false, "Regime: long above / short below WMA", group = grFilt, inline = "reg")
regimeLen = input.int(186, "Length", minval = 2, group = grFilt, inline = "reg")
useHtf = input.bool(false, "Higher-timeframe EMA", group = grFilt, inline = "htf")
htfTf = input.timeframe("240", "TF", group = grFilt, inline = "htf")
htfLen = input.int(50, "EMA length", minval = 2, group = grFilt)
grStop = "Stop & targets"
stopMode = input.string("Trend band", "Initial stop", options = ["Trend band", "ATR from entry", "Swing high/low"], group = grStop)
stopAtr = input.float(2.0, "ATR from entry: multiplier", minval = 0.5, step = 0.1, group = grStop)
swingLen = input.int(10, "Swing lookback (bars)", minval = 2, group = grStop)
stopBuf = input.float(0.1, "Stop buffer (x ATR)", minval = 0, step = 0.05, group = grStop)
minRiskAtr = input.float(0.5, "Minimum stop distance (x ATR)", minval = 0.1, step = 0.1, group = grStop,
tooltip = "A closer stop is pushed out to this distance.")
tp1R = input.float(1.0, "TP1 (R)", minval = 0.25, step = 0.25, group = grStop, inline = "t1")
tp1Pct = input.int(40, "% of position", minval = 5, maxval = 90, group = grStop, inline = "t1")
tp2R = input.float(2.0, "TP2 (R)", minval = 0.25, step = 0.25, group = grStop, inline = "t2")
tp2Pct = input.int(30, "% of position", minval = 5, maxval = 90, group = grStop, inline = "t2")
tp3R = input.float(3.0, "TP3 (R)", minval = 0.25, step = 0.25, group = grStop)
runnerMode = input.string("Fixed TP3", "Runner (rest of position)", options = ["Fixed TP3", "Trail band"], group = grStop,
tooltip = "Fixed TP3: the remainder exits at TP3. Trail band: after TP2 the remainder follows the band with no target.")
beAfterTp1 = input.bool(true, "Break-even after TP1", group = grStop)
lockAfterTp2 = input.bool(true, "Lock TP1 level after TP2", group = grStop)
grRisk = "Position sizing"
riskPct = input.float(1.0, "Risk per trade (% of equity)", minval = 0.1, maxval = 10, step = 0.1, group = grRisk)
maxLev = input.float(1.0, "Max notional (x equity)", minval = 0.1, step = 0.1, group = grRisk)
wholeUnits = input.bool(false, "Round quantity down to whole units", group = grRisk)
grShow = "Visuals"
colMode = input.string("Standard", "Color mode", options = ["Standard", "Nordic", "Warm", "Simple"], group = grShow)
showBand = input.bool(true, "Trend band", group = grShow)
showCandles = input.bool(true, "Trend-colored candles", group = grShow)
showRibbon = input.bool(false, "EMA ribbon", group = grShow)
showLevels = input.bool(true, "Trade levels", group = grShow, inline = "lv")
showZones = input.bool(true, "Zones", group = grShow, inline = "lv")
showLabels = input.bool(true, "Level labels", group = grShow, inline = "lv")
showTable = input.bool(true, "Stats table", group = grShow)
tblPosIn = input.string("Top Right", "Table position", options = ["Top Left", "Top Right", "Middle Right", "Bottom Left", "Bottom Right"], group = grShow)
[colUp, colDn] = switch colMode
"Standard" => [color.rgb(0, 255, 200), color.rgb(32, 94, 144)]
"Nordic" => [color.rgb(46, 161, 255), color.rgb(150, 154, 169)]
"Warm" => [color.rgb(111, 179, 168), color.rgb(212, 154, 137)]
"Simple" => [color.lime, color.red]
=> [color.rgb(0, 255, 200), color.rgb(32, 94, 144)]
colStop = color.rgb(255, 82, 82)
colText = chart.fg_color
// ───────────────────────────── Functions ─────────────────────────────
gaussianFilter(float s, int len, float sigma) =>
float tw = 0.0
float ws = 0.0
for i = 0 to len - 1
float w = math.exp(-0.5 * math.pow((i - (len - 1) / 2.0) / sigma, 2))
tw += w
ws += s[i] * w
ws / tw
gaussianDev(float s, int len) =>
float sw = 0.0
float sm = 0.0
for i = 0 to len - 1
float w = math.exp(-math.pow((i / float(len)) / 2, 2))
sw += w
sm += s[i] * w
float mean = sm / sw
float sv = 0.0
for i = 0 to len - 1
float w = math.exp(-math.pow((i / float(len)) / 2, 2))
sv += math.pow(s[i] - mean, 2) * w
math.sqrt(sv / sw)
// trailing supertrend around any basis; direction -1 = up trend, 1 = down trend
supertrendFromBasis(float basis, float bandW) =>
float upper = basis + bandW
float lower = basis - bandW
float pUpper = nz(upper[1], upper)
float pLower = nz(lower[1], lower)
lower := lower > pLower or close[1] < pLower ? lower : pLower
upper := upper < pUpper or close[1] > pUpper ? upper : pUpper
int d = na
float st = na
float pSt = st[1]
if na(bandW[1])
d := 1
else if pSt == pUpper
d := close > upper ? -1 : 1
else
d := close < lower ? 1 : -1
st := d == -1 ? lower : upper
[st, d]
// moves a stop only in the protective direction
tighten(int s, float a, float b) => s == 1 ? math.max(a, b) : math.min(a, b)
tblPosition(string p) =>
p == "Top Left" ? position.top_left : p == "Middle Right" ? position.middle_right : p == "Bottom Left" ? position.bottom_left : p == "Bottom Right" ? position.bottom_right : position.top_right
pctStr(int c, int n) => n > 0 ? str.tostring(100.0 * c / n, "#") + "%" : "–"
barStr(int c, int n) =>
int f = n > 0 ? int(math.round(10.0 * c / n)) : 0
string out = ""
for i = 0 to 9
out += i < f ? "▰" : "▱"
out
// ───────────────────────────── Trend engine ─────────────────────────────
atrV = ta.atr(atrLen)
medRaw = ta.median(srcIn, gLen)
gMed = gaussianFilter(medRaw, gLen, gSigma)
basis = basisMode == "Median Gaussian" ? gMed : basisMode == "HL2" ? hl2 : close
sdBand = gaussianDev(srcIn, sdLen) * sdMult
bandW = widthMode == "ATR" ? atrV * atrMult : sdBand
[st, dir] = supertrendFromBasis(basis, bandW)
isUp = dir < 0
flipUp = dir < 0 and dir[1] > 0
flipDn = dir > 0 and dir[1] < 0
// ───────────────────────────── Filters ─────────────────────────────
rRsi = ta.rsi(close, rmiLen)
rMfi = ta.mfi(hlc3, rmiLen)
rmi = na(rMfi) ? rRsi : math.avg(rRsi, rMfi)
regime = ta.wma(close, regimeLen)
[htfC, htfE] = request.security(syminfo.tickerid, htfTf, [close[1], ta.ema(close, htfLen)[1]], lookahead = barmerge.lookahead_off)
htfValid = timeframe.in_seconds(htfTf) > timeframe.in_seconds()
longOkF = (not useRmi or rmi > rmiLongMin) and (not useRegime or close > regime) and (not useHtf or not htfValid or htfC > htfE)
shortOkF = (not useRmi or rmi < rmiShortMax) and (not useRegime or close < regime) and (not useHtf or not htfValid or htfC < htfE)
swingLo = ta.lowest(low, swingLen)
swingHi = ta.highest(high, swingLen)
warmBars = math.max(math.max(gLen, sdLen), math.max(atrLen, 30)) + (useRegime ? regimeLen : 0) + 5
warm = bar_index >= warmBars
inRange = not useDates or (time >= dateFrom and time <= dateTo)
allowLong = tradeDir != "Short only"
allowShort = tradeDir != "Long only"
// ───────────────────────────── State ─────────────────────────────
var int tradeSide = 0
var float entryPx = na
var float riskPx = na
var float initStop = na
var float curStop = na
var float tp1Px = na
var float tp2Px = na
var float tp3Px = na
var float qTotal = na
var float q1 = na
var float q2 = na
var float q3 = na
var int stage = 0 // highest target reached by price (0..3)
var bool statDone = true
var bool legUsed = false
var int entries = 0
var int cnt1 = 0
var int cnt2 = 0
var int cnt3 = 0
var int cntEnd0 = 0 // ended before 1R (stop or opposite flip)
bool enteredNow = false
bool flipClose = false
bool hit1 = false
bool hit2 = false
bool hit3 = false
bool stopMark = false
if flipUp or flipDn
legUsed := false
// 1) price events for the open trade (the stop wins if stop and target share a bar)
if tradeSide != 0 and not statDone
bool stopHit = tradeSide == 1 ? low <= curStop : high >= curStop
if stopHit
statDone := true
stopMark := true
if stage == 0
cntEnd0 += 1
else
for k = 1 to 3
float lv = k == 1 ? tp1Px : k == 2 ? tp2Px : tp3Px
bool reach = tradeSide == 1 ? high >= lv : low <= lv
if reach and stage == k - 1
stage := k
if k == 1
cnt1 += 1
hit1 := true
else if k == 2
cnt2 += 1
hit2 := true
else
cnt3 += 1
hit3 := true
if stage == 3
statDone := true
// 2) an opposite flip closes the open trade
if (flipUp and strategy.position_size < 0) or (flipDn and strategy.position_size > 0)
flipClose := true
strategy.close_all(comment = "Flip")
if tradeSide != 0 and not statDone
statDone := true
if stage == 0
cntEnd0 += 1
// 3) clear a finished trade
if tradeSide != 0 and strategy.position_size == 0 and not flipClose
tradeSide := 0
// 4) new entry
bool newLong = isUp and (flipUp or (lateEntry and not legUsed)) and allowLong and longOkF and inRange and warm and strategy.position_size <= 0
bool newShort = (not isUp) and (flipDn or (lateEntry and not legUsed)) and allowShort and shortOkF and inRange and warm and strategy.position_size >= 0
if (newLong or newShort) and not na(st) and not na(atrV)
int sd = newLong ? 1 : -1
float px = close
float baseStop = stopMode == "Trend band" ? st : stopMode == "ATR from entry" ? px - sd * stopAtr * atrV : (sd == 1 ? swingLo : swingHi)
float stopPx = baseStop - sd * stopBuf * atrV
float r = math.max((px - stopPx) * sd, minRiskAtr * atrV)
stopPx := px - sd * r
float eq = strategy.equity
float q = math.min(eq * riskPct / 100 / (r * syminfo.pointvalue), eq * maxLev / (px * syminfo.pointvalue))
if wholeUnits
q := math.floor(q)
if q > 0 and r > 0
float a = q * tp1Pct / 100
float b = q * tp2Pct / 100
if wholeUnits
a := math.max(1, math.round(a))
b := math.round(b)
a := math.min(a, q)
b := math.max(math.min(b, math.min(q * 0.95, q) - a), 0)
tradeSide := sd
entryPx := px
riskPx := r
initStop := stopPx
curStop := stopPx
tp1Px := px + sd * tp1R * r
tp2Px := px + sd * tp2R * r
tp3Px := px + sd * tp3R * r
qTotal := q
q1 := a
q2 := b
q3 := math.max(q - a - b, 0)
stage := 0
statDone := false
legUsed := true
entries += 1
enteredNow := true
strategy.entry(sd == 1 ? "Long" : "Short", sd == 1 ? strategy.long : strategy.short, qty = q, comment = sd == 1 ? "Long" : "Short")
// 5) manage the open trade: ratchet the stop and place the scale-out orders
if tradeSide != 0 and (enteredNow or not flipClose)
float eps = qTotal * 0.001
float rem = enteredNow ? qTotal : math.abs(strategy.position_size)
bool tp1Done = rem <= qTotal - q1 + eps
bool tp2Done = rem <= q3 + eps
bool trailRunner = runnerMode == "Trail band"
if not enteredNow
float cand = initStop
if beAfterTp1 and tp1Done
cand := tighten(tradeSide, cand, entryPx)
if lockAfterTp2 and tp2Done
cand := tighten(tradeSide, cand, tp1Px)
if trailRunner and tp2Done and not na(st)
cand := tighten(tradeSide, cand, st - tradeSide * stopBuf * atrV)
curStop := tighten(tradeSide, curStop, cand)
string eid = tradeSide == 1 ? "Long" : "Short"
if not tp1Done and q1 > eps
strategy.exit("TP1", eid, qty = q1, limit = tp1Px, stop = curStop, comment_profit = "TP1", comment_loss = "Stop")
if not tp2Done and q2 > eps
strategy.exit("TP2", eid, qty = q2, limit = tp2Px, stop = curStop, comment_profit = "TP2", comment_loss = "Stop")
if q3 > eps
if trailRunner
strategy.exit("TP3", eid, qty = q3, stop = curStop, comment_loss = "Trail/Stop")
else
strategy.exit("TP3", eid, qty = q3, limit = tp3Px, stop = curStop, comment_profit = "TP3", comment_loss = "Stop")
// ───────────────────────────── Visuals ─────────────────────────────
trendCol = isUp ? colUp : colDn
// EMA ribbon
rb1 = ta.ema(close, 21)
rb2 = ta.ema(close, 55)
rb3 = ta.ema(close, 100)
rb4 = ta.ema(close, 200)
pRb1 = plot(showRibbon ? rb1 : na, "Ribbon 1", display = display.none)
pRb2 = plot(showRibbon ? rb2 : na, "Ribbon 2", display = display.none)
pRb3 = plot(showRibbon ? rb3 : na, "Ribbon 3", display = display.none)
pRb4 = plot(showRibbon ? rb4 : na, "Ribbon 4", display = display.none)
fill(pRb1, pRb2, color.new(rb1 >= rb2 ? colUp : colDn, 82), title = "Ribbon 1-2")
fill(pRb2, pRb3, color.new(rb2 >= rb3 ? colUp : colDn, 88), title = "Ribbon 2-3")
fill(pRb3, pRb4, color.new(rb3 >= rb4 ? colUp : colDn, 93), title = "Ribbon 3-4")
// trend band with gradient fill toward the basis
pBasis = plot(basis, "Basis", display = display.none)
pUp = plot(showBand and isUp ? st : na, "Up band", color = colUp, linewidth = 2, style = plot.style_linebr)
pDn = plot(showBand and not isUp ? st : na, "Down band", color = colDn, linewidth = 2, style = plot.style_linebr)
fill(pBasis, pUp, showBand and isUp ? basis : na, showBand and isUp ? st : na, color.new(colUp, 100), color.new(colUp, 70), title = "Up fill")
fill(pBasis, pDn, showBand and not isUp ? st : na, showBand and not isUp ? basis : na, color.new(colDn, 70), color.new(colDn, 100), title = "Down fill")
// candles: brighter the further price sits from the band
distAtr = na(st) or na(atrV) ? 0.0 : math.abs(close - st) / atrV
candleCol = color.from_gradient(math.min(distAtr, 4.0), 0.0, 4.0, color.new(trendCol, 70), trendCol)
barcolor(showCandles ? candleCol : na, title = "Trend candles")
// entries
plotshape(enteredNow and tradeSide == 1, "Long entry", shape.triangleup, location.belowbar, colUp, size = size.small)
plotshape(enteredNow and tradeSide == -1, "Short entry", shape.triangledown, location.abovebar, colDn, size = size.small)
// trade levels and zones
bool lvOn = showLevels and tradeSide != 0
color sideC = tradeSide == 1 ? colUp : colDn
pStop = plot(lvOn ? curStop : na, "Stop", color = colStop, linewidth = 1, style = plot.style_linebr, linestyle = plot.linestyle_dashed)
pEntry = plot(lvOn ? entryPx : na, "Entry", color = color.new(colText, 55), linewidth = 1, style = plot.style_linebr)
plot(lvOn ? tp1Px : na, "TP1", color = color.new(sideC, 30), style = plot.style_linebr, linestyle = plot.linestyle_dotted)
plot(lvOn ? tp2Px : na, "TP2", color = color.new(sideC, 30), style = plot.style_linebr, linestyle = plot.linestyle_dotted)
pTp3 = plot(lvOn ? tp3Px : na, "TP3", color = color.new(sideC, 30), style = plot.style_linebr, linestyle = plot.linestyle_dotted)
fill(pStop, pEntry, showZones ? color.new(colStop, 90) : na, title = "Risk zone")
fill(pEntry, pTp3, showZones ? color.new(sideC, 91) : na, title = "Reward zone")
// target / stop markers
plotshape(hit1 ? tp1Px : na, "TP1 hit", shape.diamond, location.absolute, sideC, size = size.tiny)
plotshape(hit2 ? tp2Px : na, "TP2 hit", shape.diamond, location.absolute, sideC, size = size.tiny)
plotshape(hit3 ? tp3Px : na, "TP3 hit", shape.diamond, location.absolute, sideC, size = size.tiny)
plotshape(stopMark ? curStop : na, "Stop hit", shape.xcross, location.absolute, colStop, size = size.tiny)
// right-edge labels for the open trade
var array<label> lvLbls = array.new<label>()
addLbl(float y, string t, color c) =>
lvLbls.push(label.new(bar_index + 2, y, t + " " + str.tostring(y, format.mintick), color = color.new(color.black, 100), textcolor = c, style = label.style_label_left, size = size.small))
if barstate.islast
for lb in lvLbls
lb.delete()
lvLbls.clear()
if showLevels and showLabels and tradeSide != 0
addLbl(entryPx, "Entry", color.new(colText, 20))
addLbl(curStop, "Stop", colStop)
addLbl(tp1Px, (stage >= 1 ? "✓ " : "") + "TP1", sideC)
addLbl(tp2Px, (stage >= 2 ? "✓ " : "") + "TP2", sideC)
addLbl(tp3Px, (stage >= 3 ? "✓ " : "") + "TP3", sideC)
// stats table
var table tbl = table.new(tblPosition(tblPosIn), 3, 8, bgcolor = color.new(chart.bg_color, 20), frame_color = color.new(colText, 80), frame_width = 1)
setRow(int r, string l, string m, string v, color c) =>
table.cell(tbl, 0, r, l, text_color = color.new(colText, 25), text_halign = text.align_left, text_size = size.small, text_font_family = font.family_monospace)
table.cell(tbl, 1, r, m, text_color = c, text_halign = text.align_center, text_size = size.small, text_font_family = font.family_monospace)
table.cell(tbl, 2, r, v, text_color = c, text_halign = text.align_right, text_size = size.small, text_font_family = font.family_monospace)
if barstate.islast and showTable
table.cell(tbl, 0, 0, "GAUSSIAN TREND", text_color = trendCol, text_halign = text.align_left, text_size = size.small, text_font_family = font.family_monospace)
table.cell(tbl, 1, 0, "", text_size = size.small)
table.cell(tbl, 2, 0, isUp ? "▲ UP" : "▼ DOWN", text_color = trendCol, text_halign = text.align_right, text_size = size.small, text_font_family = font.family_monospace)
setRow(1, "Signals", "", str.tostring(entries), colText)
setRow(2, "1R", barStr(cnt1, entries), pctStr(cnt1, entries), colUp)
setRow(3, "2R", barStr(cnt2, entries), pctStr(cnt2, entries), colUp)
setRow(4, "3R", barStr(cnt3, entries), pctStr(cnt3, entries), colUp)
setRow(5, "<1R", barStr(cntEnd0, entries), pctStr(cntEnd0, entries), colStop)
setRow(6, "RMI", "", na(rmi) ? "–" : str.tostring(rmi, "#.0"), colText)
setRow(7, "Open", "", tradeSide == 1 ? "Long" : tradeSide == -1 ? "Short" : "Flat", tradeSide == 0 ? color.new(colText, 40) : sideC)