本页源码来自 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/
// © preuss_steffen
//@version=6
// Trend Following Anatomy — where the profit of a simple trend rule comes from, on the chart you are looking at.
// Runs one transparent trend rule on closed bars (fills at the next open, costs per side), then shows: the rule's value
// against buy & hold, every closed trade sorted from worst to best (the "trade ladder"), the trades that made most of the
// profit shaded on the price chart, and a table with hit rate, payoff, profit factor, concentration and drawdowns.
// History only. No forecast, no parameter search, no performance claim.
indicator("Trend Following Anatomy", shorttitle="Trend Anatomy", overlay=false, max_boxes_count=500, max_labels_count=500, max_lines_count=500)
// ════════ Rule ════════
var string gR = "Rule"
string iRule = input.string("Moving average", "Trend rule", options=["Moving average", "Two EMAs", "Breakout (Donchian)"], group=gR,
tooltip="Moving average: long while the close is above the SMA. Two EMAs: long while the fast EMA is above the slow EMA. Breakout: long after a close above the highest high of the last N bars, out after a close below the lowest low of the last M bars. All signals use closed bars; fills happen at the next bar's open.")
int iSma = input.int(200, "SMA length (Moving average)", minval=2, group=gR)
int iFast = input.int(50, "Fast EMA (Two EMAs)", minval=1, group=gR, inline="ema")
int iSlow = input.int(200, "Slow EMA", minval=2, group=gR, inline="ema")
int iBrkN = input.int(50, "Entry: highest high of N bars (Breakout)", minval=2, group=gR, inline="brk")
int iBrkM = input.int(25, "Exit: lowest low of M bars", minval=2, group=gR, inline="brk")
string iDir = input.string("Long only", "Direction", options=["Long only", "Long and short"], group=gR,
tooltip="Long only: long or flat. Long and short: always in the market, long or short.")
float iCost = input.float(0.10, "Cost per side (%)", minval=0, step=0.05, group=gR, tooltip="Commission plus half the spread, charged on entry and on exit.")
int iLook = input.int(2520, "Analyse the last N bars (0 = all)", minval=0, group=gR, tooltip="2520 daily bars are about 10 years. Keeps the numbers readable on charts with a very long history. A start date below can shorten the range further.")
bool iUseFrom = input.bool(false, "Start on", group=gR, inline="from")
int iFrom = input.time(timestamp("2015-01-01T00:00:00"), "", group=gR, inline="from")
// ════════ Display ════════
var string gD = "Display"
bool iShowEq = input.bool(true, "Rule value and buy & hold (%)", group=gD)
bool iShowDd = input.bool(true, "Shade drawdowns of the rule", group=gD)
bool iLadder = input.bool(true, "Trade ladder (all trades sorted)", group=gD)
bool iBestOn = input.bool(true, "Best trades on the price chart", group=gD, inline="best")
float iBestPct = input.float(20, "top %", minval=1, maxval=100, step=1, group=gD, inline="best",
tooltip="The best x % of all trades (by result) are drawn as boxes on the price chart with their result.")
bool iAllOn = input.bool(false, "All other trades on the price chart (faint)", group=gD)
bool iTable = input.bool(true, "Table", group=gD, inline="tb")
string iPos = input.string("Top left", "", options=["Top left", "Top right", "Bottom left", "Bottom right"], group=gD, inline="tb",
tooltip="Top left keeps the trade ladder at the right end of the pane visible.")
string iSize = input.string("Small", "Text size", options=["Tiny", "Small", "Normal"], group=gD)
color cRule = input.color(#169c86, "Rule", group=gD, inline="c")
color cHold = input.color(#787b86, "Buy & hold", group=gD, inline="c")
color cWin = input.color(#169c86, "Winning trade", group=gD, inline="c2")
color cLoss = input.color(#e0532c, "Losing trade", group=gD, inline="c2")
float cost = iCost / 100
// ════════ Signal on closed bars ════════
float sma = ta.sma(close, iSma)
float emaF = ta.ema(close, iFast)
float emaS = ta.ema(close, iSlow)
float hiN = ta.highest(high, iBrkN)[1] // highest high of the N bars before this one
float loM = ta.lowest(low, iBrkM)[1]
bool longShort = iDir == "Long and short"
int flatOrShort = longShort ? -1 : 0
// want = position the rule asks for after this bar closes (1 long, 0 flat, -1 short); na until the rule has enough history
var int want = 0
bool ready = false
if iRule == "Moving average"
ready := not na(sma)
if ready
want := close > sma ? 1 : close < sma ? flatOrShort : want
else if iRule == "Two EMAs"
ready := bar_index >= math.max(iFast, iSlow)
if ready
want := emaF > emaS ? 1 : emaF < emaS ? flatOrShort : want
else
ready := not na(hiN) and not na(loM)
if ready
if want <= 0 and close > hiN
want := 1
else if want >= 0 and close < loM
want := flatOrShort
bool inRange = (not iUseFrom or time >= iFrom) and (iLook == 0 or bar_index >= last_bar_index - iLook + 1)
bool active = ready and inRange
// ════════ Fills at the next open, trade book ════════
var int pos = 0
var float entryPx = na
var int entryT = na
var float eqBase = 1.0 // product of (1 + r) over closed trades
var float holdBase = na
var int startT = na
var int nBars = 0 // bars counted (from the start)
var int nInMkt = 0
var array<float> tRet = array.new<float>()
var array<int> tDir = array.new<int>()
var array<int> tT1 = array.new<int>()
var array<int> tT2 = array.new<int>()
var array<float> tPx1 = array.new<float>()
var array<float> tPx2 = array.new<float>()
float tradeOut = na // result of a trade closed on this bar (at the open)
bool startedNow = false
if active and na(startT)
startT := time
holdBase := close
startedNow := true
// execute the previous bar's decision at this bar's open (previous bar must have been active)
int desired = active[1] ? want[1] : pos
if not na(startT) and desired != pos
if pos != 0
float r = pos * (open / entryPx - 1) - 2 * cost
array.push(tRet, r)
array.push(tDir, pos)
array.push(tT1, entryT)
array.push(tT2, time)
array.push(tPx1, entryPx)
array.push(tPx2, open)
eqBase := eqBase * (1 + r)
tradeOut := r
entryPx := na
entryT := na
pos := desired
if pos != 0
entryPx := open
entryT := time
if not na(startT)
nBars += 1
if pos != 0
nInMkt += 1
// value of the rule if the open trade were closed at this close, and buy & hold from the same start
float eqMark = pos != 0 ? eqBase * (1 + pos * (close / entryPx - 1) - 2 * cost) : eqBase
float hold = na(holdBase) ? na : close / holdBase
var float loSeen = na
var float hiSeen = na
var float eqPeak = 1.0
var float holdPeak = 1.0
var float maxDdRule = 0.0
var float maxDdHold = 0.0
if not na(startT)
eqPeak := math.max(eqPeak, eqMark)
holdPeak := math.max(holdPeak, hold)
maxDdRule := math.min(maxDdRule, eqMark / eqPeak - 1)
maxDdHold := math.min(maxDdHold, hold / holdPeak - 1)
float lo_ = math.min((eqMark - 1) * 100, (hold - 1) * 100)
float hi_ = math.max((eqMark - 1) * 100, (hold - 1) * 100)
loSeen := na(loSeen) ? lo_ : math.min(loSeen, lo_)
hiSeen := na(hiSeen) ? hi_ : math.max(hiSeen, hi_)
// ════════ Pane: value lines in percent ════════
float rulePct = na(startT) ? na : (eqMark - 1) * 100
float holdPct = na(startT) ? na : (hold - 1) * 100
float ddPct = na(startT) ? na : (eqMark / eqPeak - 1) * 100
plot(iShowEq ? rulePct : na, "Rule value (%)", color=cRule, linewidth=2)
plot(iShowEq ? holdPct : na, "Buy & hold (%)", color=cHold, linewidth=1)
hline(0, "Start", color=color.new(color.gray, 60))
bgcolor(iShowDd and iShowEq and not na(ddPct) and ddPct < -10 ? color.new(cLoss, 93) : na, title="Rule more than 10% below its high")
// values for other scripts / data window
plot(pos, "Export: position (1 long, 0 flat, -1 short)", display=display.data_window)
plot(tradeOut * 100, "Export: trade result closed on this bar (%)", display=display.data_window)
plot(rulePct, "Export: rule value (%)", display=display.data_window)
plot(holdPct, "Export: buy & hold (%)", display=display.data_window)
// ════════ Alerts (on the signal bar; the fill is the next open) ════════
alertcondition(active and want == 1 and want[1] != 1, title="Rule turns long", message="Trend Anatomy: rule turns long on {{ticker}} ({{interval}}) — fill at the next open")
alertcondition(active and want != 1 and want[1] == 1, title="Rule leaves long", message="Trend Anatomy: rule leaves long on {{ticker}} ({{interval}}) — fill at the next open")
// ════════ Last bar: table, trade ladder, best trades on the price chart ════════
tablePos(string s) =>
switch s
"Top left" => position.top_left
"Bottom left" => position.bottom_left
"Bottom right" => position.bottom_right
=> position.top_right
textSize(string s) =>
switch s
"Tiny" => size.tiny
"Normal" => size.normal
=> size.small
pct(float v) =>
na(v) ? "–" : (v >= 0 ? "+" : "") + str.tostring(v * 100, "0.0") + "%"
pct0(float v) =>
na(v) ? "–" : str.tostring(v * 100, "0") + "%"
var table tb = na
// one table row: key left, value right. The leading spaces keep the widest value from being clipped on the left
// (TradingView sizes the column slightly too narrow for long strings of digits).
row(table t, int r, string k, string v, color vc, string ts) =>
table.cell(t, 0, r, k, text_color=chart.fg_color, text_size=ts, text_halign=text.align_left)
table.cell(t, 1, r, " " + v, text_color=vc, text_size=ts, text_halign=text.align_right)
var array<box> bxLadder = array.new<box>()
var array<box> bxChart = array.new<box>()
var array<label> lbChart = array.new<label>()
clearAll() =>
for b in bxLadder
box.delete(b)
for b in bxChart
box.delete(b)
for l in lbChart
label.delete(l)
array.clear(bxLadder)
array.clear(bxChart)
array.clear(lbChart)
if barstate.islast
clearAll()
table.delete(tb)
int n = array.size(tRet)
// sorted copy: ascending for the ladder, descending for "best"
array<int> order = n > 0 ? array.sort_indices(tRet, order.ascending) : array.new<int>()
float sumWin = 0.0
float sumLoss = 0.0
int nWin = 0
float total = 0.0
for r in tRet
total += r
if r > 0
sumWin += r
nWin += 1
else
sumLoss += r
int kBest = n > 0 ? math.max(1, math.ceil(n * iBestPct / 100)) : 0
float sumBest = 0.0
float sumTop3 = 0.0
if n > 0
for i = 0 to kBest - 1
sumBest += array.get(tRet, array.get(order, n - 1 - i))
for i = 0 to math.min(3, n) - 1
sumTop3 += array.get(tRet, array.get(order, n - 1 - i))
float winRate = n > 0 ? nWin / n : na
float avgWin = nWin > 0 ? sumWin / nWin : na
float avgLoss = n - nWin > 0 ? sumLoss / (n - nWin) : na
float payoff = not na(avgWin) and not na(avgLoss) and avgLoss < 0 ? avgWin / -avgLoss : na
float pf = sumLoss < 0 ? sumWin / -sumLoss : na
float shareBest = total > 0 ? sumBest / total : na
float median = n > 0 ? (n % 2 == 1 ? array.get(tRet, array.get(order, n / 2)) : (array.get(tRet, array.get(order, n / 2 - 1)) + array.get(tRet, array.get(order, n / 2))) / 2) : na
float meanTr = n > 0 ? total / n : na
// ---- trade ladder in the pane: one column per trade (bucketed above 300 trades), worst to best, drawn on the pane's
// own range: the tallest bar is 30% of the range of the value lines; numbers for the extremes stand on the bars ----
if iLadder and n > 0
int cols = math.min(n, 300)
int colW = math.max(1, math.min(10, 300 / cols)) // bars per column, ladder at most 300 bars wide
float rng = na(hiSeen) or hiSeen - loSeen <= 0 ? 1.0 : hiSeen - loSeen
float base = na(loSeen) ? 0.0 : loSeen + 0.32 * rng
float worst = array.get(tRet, array.get(order, 0)) * 100
float best = array.get(tRet, array.get(order, n - 1)) * 100
float amp = math.max(math.abs(worst), math.abs(best))
float k = amp > 0 ? 0.30 * rng / amp : 0.0
for j = 0 to cols - 1
int a = math.floor(j * n / cols)
int b = math.floor((j + 1) * n / cols) - 1
float v = 0.0
for i = a to math.max(a, b)
v += array.get(tRet, array.get(order, i))
v := v / (math.max(a, b) - a + 1) * 100
int x = bar_index - (cols - 1 - j) * colW
array.push(bxLadder, box.new(x - colW + 1, base + math.max(v, 0) * k, x, base + math.min(v, 0) * k, border_color=colW > 2 ? color.new(chart.bg_color, 0) : na, bgcolor=color.new(v >= 0 ? cWin : cLoss, 15), xloc=xloc.bar_index))
int xLeft = bar_index - (cols - 1) * colW - colW + 1
array.push(lbChart, label.new(bar_index, base + best * k, pct(best / 100), xloc=xloc.bar_index, style=label.style_label_lower_right, color=color.new(cWin, 100), textcolor=cWin, size=size.small))
array.push(lbChart, label.new(xLeft + colW / 2, base + worst * k, pct(worst / 100), xloc=xloc.bar_index, style=label.style_label_up, color=color.new(cLoss, 100), textcolor=cLoss, size=size.small))
array.push(lbChart, label.new((xLeft + bar_index) / 2, base + math.min(worst, 0) * k, "\n" + str.tostring(n) + " trades, worst to best", xloc=xloc.bar_index, style=label.style_label_up, color=color.new(chart.bg_color, 100), textcolor=color.new(chart.fg_color, 30), size=size.small))
// ---- best trades (and optionally all others) on the price chart ----
if (iBestOn or iAllOn) and n > 0
for rank = 0 to n - 1
int i = array.get(order, n - 1 - rank)
bool isBest = rank < kBest
if (isBest and iBestOn) or (not isBest and iAllOn)
float r = array.get(tRet, i)
float p1 = array.get(tPx1, i)
float p2 = array.get(tPx2, i)
color cc = r >= 0 ? cWin : cLoss
int transp = isBest ? 75 : 92
array.push(bxChart, box.new(array.get(tT1, i), math.max(p1, p2), array.get(tT2, i), math.min(p1, p2), xloc=xloc.bar_time,
border_color=color.new(cc, isBest ? 30 : 80), border_width=1, bgcolor=color.new(cc, transp), force_overlay=true))
if isBest
array.push(lbChart, label.new(array.get(tT2, i), math.max(p1, p2), pct(r), xloc=xloc.bar_time, style=label.style_label_down,
color=color.new(cc, 20), textcolor=color.white, size=size.small, force_overlay=true))
// ---- table ----
if iTable
string ts = textSize(iSize)
string ruleTxt = iRule == "Moving average" ? "Close vs SMA " + str.tostring(iSma) : iRule == "Two EMAs" ? "EMA " + str.tostring(iFast) + "/" + str.tostring(iSlow) : "Breakout " + str.tostring(iBrkN) + "/" + str.tostring(iBrkM)
string period = na(startT) ? "–" : str.format_time(startT, "yyyy-MM-dd", syminfo.timezone) + " to " + str.format_time(time, "yyyy-MM-dd", syminfo.timezone) + " · " + timeframe.period
// top left: an empty first row carries the indicator's status line, so the line never covers a value
int off = iPos == "Top left" ? 1 : 0
tb := table.new(tablePos(iPos), 2, 12 + off, bgcolor=color.new(chart.bg_color, 10), frame_color=color.new(color.gray, 60), frame_width=1, border_color=color.new(color.gray, 80), border_width=1)
color fg = chart.fg_color
if off == 1
row(tb, 0, " ", " ", fg, ts)
row(tb, 0 + off, "Rule", ruleTxt + (longShort ? ", long/short" : ", long only"), fg, ts)
row(tb, 1 + off, "Period", period, fg, ts)
row(tb, 2 + off, "Trades · time in market", str.tostring(n) + " · " + (nBars > 0 ? pct0(nInMkt / nBars) : "–"), fg, ts)
row(tb, 3 + off, "Win rate", pct0(winRate), fg, ts)
row(tb, 4 + off, "Avg win · avg loss · payoff", pct(avgWin) + " · " + pct(avgLoss) + " · " + (na(payoff) ? "–" : str.tostring(payoff, "0.0")), fg, ts)
row(tb, 5 + off, "Profit factor", na(pf) ? "–" : str.tostring(pf, "0.00"), fg, ts)
row(tb, 6 + off, "Best " + str.tostring(iBestPct, "0") + "% of trades (" + str.tostring(kBest) + ")", na(shareBest) ? "–" : str.tostring(shareBest * 100, "0") + "% of net profit", na(shareBest) ? fg : cRule, ts)
row(tb, 7 + off, "Without the 3 best trades", n > 0 ? pct(total - sumTop3) + " (sum of trades)" : "–", fg, ts)
row(tb, 8 + off, "Median trade · mean trade", pct(median) + " · " + pct(meanTr), fg, ts)
row(tb, 9 + off, "Rule · buy & hold", pct(eqMark - 1) + " · " + pct(hold - 1), (eqMark - 1) >= (hold - 1) ? cRule : fg, ts)
row(tb, 10 + off, "Max drawdown rule · hold", pct(maxDdRule) + " · " + pct(maxDdHold), maxDdRule >= maxDdHold ? cRule : fg, ts)
row(tb, 11 + off, "Costs " + str.tostring(iCost, "0.00") + "% per side", "history only · no forecast", color.new(fg, 40), ts)