本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// (c) K'u Hero
//@version=6
// Strategy Trade Excursion Report - library v1.1
// Collects MAE (maximum adverse excursion) and MFE (maximum favorable excursion) of every closed trade of the
// strategy it is called from, and shows their distribution and simple stop / target what-if tables.
// Source: strategy.closedtrades.max_drawdown() / max_runup() (the "Drawdown" / "Run-up" columns of the
// Strategy Tester trade list). TradingView includes the entry commission in these figures; by default the
// library removes it again so that excursions are pure price moves (see _excursions).
// R = excursion / initial stop distance (only for trades where a valid stop was passed).
// All statistics are calculated once, on the last confirmed bar. Closed trades never change: no repainting.
// @description Per-trade MAE / MFE report for strategies: distribution, percentiles and stop / target what-if tables. Add one call of run() at the end of your strategy.
library("ExcursionReport", overlay = true)
// ===== Internal helpers =====
// MAE and MFE of one closed trade as price distances.
// - Tester figures: run-up = favorable move - entry commission (shown as 0 when that is negative),
// drawdown = adverse move + entry commission, percent figures = amount / (entry value + entry commission).
// - Same account and symbol currency: the entry commission is recovered exactly from the percent figure.
// Different currencies: the trade's own exchange rate is recovered from the percent figure instead, and the
// entry commission is estimated by splitting the trade's commission in proportion to entry / exit price
// (exact for percentage commission, approximate for fixed commission).
// - Money -> price: divided by (size x point value x rate).
_excursions(int i, bool includeCommission) =>
float mae = na
float mfe = na
float qty = math.abs(strategy.closedtrades.size(i))
float ep = strategy.closedtrades.entry_price(i)
float xp = strategy.closedtrades.exit_price(i)
float dd = strategy.closedtrades.max_drawdown(i)
float ru = strategy.closedtrades.max_runup(i)
float pv = syminfo.pointvalue
if qty > 0 and ep > 0 and not na(dd) and not na(ru)
float com = nz(strategy.closedtrades.commission(i))
// fallback split of the trade's commission: in proportion to entry / exit price
float ec = ep + nz(xp, ep) > 0 ? com * ep / (ep + nz(xp, ep)) : 0.0
float pctDd = strategy.closedtrades.max_drawdown_percent(i)
float pctRu = strategy.closedtrades.max_runup_percent(i)
bool hasDd = dd > 0 and not na(pctDd) and pctDd > 0
bool hasRu = ru > 0 and not na(pctRu) and pctRu > 0
float rateDd = 1.0
float rateRu = 1.0
if strategy.account_currency == syminfo.currency
// exact entry commission: percent = amount / (entry value + entry commission)
if hasDd or hasRu
ec := math.max((hasDd ? dd * 100.0 / pctDd : ru * 100.0 / pctRu) - ep * qty * pv, 0.0)
else
// each figure's own exchange rate, from its own percent figure (entry commission from the fallback split)
float fallback = strategy.convert_to_account(1.0)
rateDd := hasDd ? (dd * 100.0 / pctDd - ec) / (ep * qty * pv) : hasRu ? (ru * 100.0 / pctRu - ec) / (ep * qty * pv) : fallback
rateRu := hasRu ? (ru * 100.0 / pctRu - ec) / (ep * qty * pv) : rateDd
float denDd = qty * pv * rateDd
float denRu = qty * pv * rateRu
if denDd > 0 and denRu > 0
if includeCommission
mae := dd / denDd
mfe := ru / denRu
else
mae := math.max(dd - ec, 0.0) / denDd
mfe := ru > 0 ? (ru + ec) / denRu : 0.0
[mae, mfe]
// Key that identifies an entry (shared by the open trade and the closed trade(s) it becomes).
_key(string id, int t, float p) =>
id + "|" + str.tostring(t) + "|" + str.tostring(p)
// Signed initial risk: > 0 = valid stop distance, <= 0 = stop on the wrong side of the fill, na = no stop.
_risk(float entryPrice, bool isLong, float stopPrice, float stopDistance) =>
float r = na
if not na(stopPrice)
r := isLong ? entryPrice - stopPrice : stopPrice - entryPrice
else if not na(stopDistance) and stopDistance > 0
r := stopDistance
r
// "0.5, 1, 1.5" -> [0.5, 1, 1.5] (positive numbers only, at most 5).
_parseLevels(string s) =>
array<float> out = array.new<float>()
array<string> parts = str.split(s, ",")
for part in parts
float v = str.tonumber(str.trim(part))
if not na(v) and v > 0 and out.size() < 5
out.push(v)
out
// Percentile with linear interpolation between closest ranks: rank = (n - 1) x p / 100 on the sorted values
// (same convention as spreadsheet PERCENTILE.INC, so results can be checked against an exported trade list).
_pctl(array<float> a, float p) =>
float res = na
int n = a.size()
if n > 0
array<float> s = a.copy()
s.sort(order.ascending)
float rnk = (n - 1) * p / 100.0
int lo = int(math.floor(rnk))
int hi = math.min(lo + 1, n - 1)
res := s.get(lo) + (s.get(hi) - s.get(lo)) * (rnk - lo)
res
_fmtP(float v) =>
na(v) ? "-" : str.tostring(v, format.mintick)
_fmtR(float v) =>
na(v) ? "-" : str.tostring(v, "0.00") + "R"
_fmtPct(int num, int den) =>
den > 0 ? str.tostring(100.0 * num / den, "0.0") + "%" : "-"
// A value within 0.1% below the level counts as reaching it (absorbs float rounding and the small
// commission / exchange-rate estimate error, e.g. 1.9998R for a trade that hit a 2R target).
_countAtLeast(array<float> a, float level) =>
int c = 0
float lim = level * (1.0 - 0.001)
for v in a
if v >= lim
c += 1
c
// ===== Exported functions =====
// @function MAE of one closed trade as a price distance.
// @param tradeNum Closed trade number (0 = first closed trade).
// @param includeCommission false (default) = pure price move; true = Tester "Drawdown" figure (includes entry commission).
// @returns MAE price distance (0 or more), or na if the trade number is not available.
export maePrice(int tradeNum, bool includeCommission = false) =>
float res = na
if tradeNum >= strategy.closedtrades.first_index and tradeNum < strategy.closedtrades
[ae, fe] = _excursions(tradeNum, includeCommission)
res := ae
res
// @function MFE of one closed trade as a price distance.
// @param tradeNum Closed trade number (0 = first closed trade).
// @param includeCommission false (default) = pure price move; true = Tester "Run-up" figure (entry commission deducted).
// @returns MFE price distance (0 or more), or na if the trade number is not available.
export mfePrice(int tradeNum, bool includeCommission = false) =>
float res = na
if tradeNum >= strategy.closedtrades.first_index and tradeNum < strategy.closedtrades
[ae, fe] = _excursions(tradeNum, includeCommission)
res := fe
res
// @function Records the initial stop of each new trade and, on the last confirmed bar, draws the MAE / MFE report table. Call it once per bar, at global scope, after your strategy.entry / strategy.exit calls.
// @param stopPrice Stop-loss price of the trade (series). Used if not na.
// @param stopDistance Stop-loss distance in price units (series). Used when stopPrice is na. Leave both na if you do not use stops: R values and R levels are then not shown.
// @param stopTiming Which bar's stop value becomes the trade's initial stop. "Signal bar" (default): the value one bar before the entry is first seen as filled, i.e. the bar where a market order is placed; for strategies that set the stop when they send the order. "Fill bar": the value on the bar where the entry is first seen; for strategies that compute the stop from strategy.position_avg_price after the fill.
// @param includeCommission false (default): excursions are pure price moves (entry commission removed). true: the Tester's run-up / drawdown figures as they are.
// @param slLevels Comma-separated stop levels for the "if stop were X" table (1 to 5 positive numbers, in levelUnit).
// @param tpLevels Comma-separated target levels for the "if target were Y" table (1 to 5 positive numbers, in levelUnit).
// @param levelUnit "R" (multiples of the initial stop distance) or "Price" (price distance).
// @param tablePosition Table position, e.g. position.bottom_right.
// @param textSize Table text size, e.g. size.small.
// @param showTable Set false to hide the table.
// @returns Number of closed trades included in the report (0 until the last bar).
export run(series float stopPrice = na, series float stopDistance = na, string stopTiming = "Signal bar", bool includeCommission = false, string slLevels = "0.5, 0.75, 1, 1.25", string tpLevels = "0.5, 1, 1.5, 2, 3", string levelUnit = "R", string tablePosition = position.bottom_right, string textSize = size.small, bool showTable = true) =>
var map<string, float> riskMap = map.new<string, float>()
var array<string> keyQueue = array.new<string>()
var int lastClosed = 0
var float lastSig = -1.0 // not na: a comparison with na is never true
var table tbl = na
// stop values used for a trade first seen on this bar
bool useSignalBar = stopTiming != "Fill bar"
float sp = useSignalBar ? stopPrice[1] : stopPrice
float sd = useSignalBar ? stopDistance[1] : stopDistance
// --- 1) record the initial risk of trades that appeared since the previous bar ---
int nOpen = strategy.opentrades
float sig = nOpen > 0 ? strategy.opentrades.entry_time(nOpen - 1) * 1.0 + nOpen : 0.0
if sig != lastSig
lastSig := sig
if nOpen > 0
for j = 0 to nOpen - 1
string k = _key(strategy.opentrades.entry_id(j), strategy.opentrades.entry_time(j), strategy.opentrades.entry_price(j))
if not riskMap.contains(k)
riskMap.put(k, _risk(strategy.opentrades.entry_price(j), strategy.opentrades.size(j) > 0, sp, sd))
keyQueue.push(k)
int nClosed = strategy.closedtrades
if nClosed > lastClosed and nClosed > strategy.closedtrades.first_index
// trades that opened and closed between two script executions
for i = math.max(lastClosed, strategy.closedtrades.first_index) to nClosed - 1
string k = _key(strategy.closedtrades.entry_id(i), strategy.closedtrades.entry_time(i), strategy.closedtrades.entry_price(i))
if not riskMap.contains(k)
riskMap.put(k, _risk(strategy.closedtrades.entry_price(i), strategy.closedtrades.size(i) > 0, sp, sd))
keyQueue.push(k)
lastClosed := nClosed
// keep the map well below the 50,000 pair limit (the oldest keys belong to long-gone trades)
while keyQueue.size() > 20000
riskMap.remove(keyQueue.shift())
// --- 2) report on the last confirmed bar ---
int used = 0
bool isLast = barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed)
if showTable and isLast
array<float> maeP = array.new<float>()
array<float> mfeP = array.new<float>()
array<float> maeR = array.new<float>()
array<float> mfeR = array.new<float>()
array<float> winMaeP = array.new<float>()
array<float> winMaeR = array.new<float>()
int wins = 0
int wrongSide = 0
int firstI = strategy.closedtrades.first_index
if nClosed > firstI
for i = firstI to nClosed - 1
[ae, fe] = _excursions(i, includeCommission)
if not na(ae) and not na(fe)
bool isWin = strategy.closedtrades.profit(i) > 0
maeP.push(ae)
mfeP.push(fe)
if isWin
wins += 1
winMaeP.push(ae)
string k = _key(strategy.closedtrades.entry_id(i), strategy.closedtrades.entry_time(i), strategy.closedtrades.entry_price(i))
float r = riskMap.get(k)
if not na(r)
if r > 0
maeR.push(ae / r)
mfeR.push(fe / r)
if isWin
winMaeR.push(ae / r)
else
wrongSide += 1
used := maeP.size()
bool useR = levelUnit == "R"
array<float> slL = _parseLevels(slLevels)
array<float> tpL = _parseLevels(tpLevels)
if na(tbl)
tbl := table.new(tablePosition, 5, 24, bgcolor = color.new(#131722, 10), frame_color = color.gray, frame_width = 1, border_color = color.new(color.gray, 70), border_width = 1)
else
table.clear(tbl, 0, 0, 4, 23)
color txt = color.white
color dim = color.new(color.white, 30)
color head = color.new(#2962ff, 40)
color sect = color.new(color.gray, 60)
table.cell(tbl, 0, 0, "Trade Excursion Report (MAE / MFE)", text_color = txt, text_size = textSize, bgcolor = head)
table.merge_cells(tbl, 0, 0, 4, 0)
if used == 0
table.cell(tbl, 0, 1, "No closed trades yet", text_color = txt, text_size = textSize)
table.merge_cells(tbl, 0, 1, 4, 1)
else
int row = 1
table.cell(tbl, 0, row, "Closed trades", text_color = txt, text_size = textSize, text_halign = text.align_left)
table.cell(tbl, 1, row, str.tostring(used), text_color = txt, text_size = textSize)
table.cell(tbl, 2, row, "Winners " + str.tostring(wins), text_color = txt, text_size = textSize)
table.cell(tbl, 3, row, "With stop (R)", text_color = txt, text_size = textSize)
table.cell(tbl, 4, row, str.tostring(maeR.size()), text_color = txt, text_size = textSize)
if wrongSide > 0
row += 1
table.cell(tbl, 0, row, "Not in R: " + str.tostring(wrongSide) + " trade(s) with the stop on the wrong side of the fill", text_color = dim, text_size = textSize, text_halign = text.align_left)
table.merge_cells(tbl, 0, row, 4, row)
row += 1
table.cell(tbl, 0, row, "Statistic", text_color = txt, text_size = textSize, bgcolor = sect, text_halign = text.align_left)
table.cell(tbl, 1, row, "MAE (price)", text_color = txt, text_size = textSize, bgcolor = sect)
table.cell(tbl, 2, row, "MFE (price)", text_color = txt, text_size = textSize, bgcolor = sect)
table.cell(tbl, 3, row, "MAE (R)", text_color = txt, text_size = textSize, bgcolor = sect)
table.cell(tbl, 4, row, "MFE (R)", text_color = txt, text_size = textSize, bgcolor = sect)
array<string> statNames = array.from("Mean", "Median (P50)", "P75", "P90", "P95")
array<float> statP = array.from(0.0, 50.0, 75.0, 90.0, 95.0)
for s = 0 to 4
row += 1
float p = statP.get(s)
table.cell(tbl, 0, row, statNames.get(s), text_color = txt, text_size = textSize, text_halign = text.align_left)
table.cell(tbl, 1, row, _fmtP(s == 0 ? maeP.avg() : _pctl(maeP, p)), text_color = txt, text_size = textSize)
table.cell(tbl, 2, row, _fmtP(s == 0 ? mfeP.avg() : _pctl(mfeP, p)), text_color = txt, text_size = textSize)
table.cell(tbl, 3, row, _fmtR(maeR.size() == 0 ? na : s == 0 ? maeR.avg() : _pctl(maeR, p)), text_color = txt, text_size = textSize)
table.cell(tbl, 4, row, _fmtR(mfeR.size() == 0 ? na : s == 0 ? mfeR.avg() : _pctl(mfeR, p)), text_color = txt, text_size = textSize)
string unitTxt = useR ? "R" : "price"
bool rMissing = useR and maeR.size() == 0
// stop what-if
row += 1
table.cell(tbl, 0, row, "If stop were X (" + unitTxt + "): share of winners whose MAE reached X", text_color = txt, text_size = textSize, bgcolor = sect, text_halign = text.align_left)
table.merge_cells(tbl, 0, row, 4, row)
if rMissing
row += 1
table.cell(tbl, 0, row, "No stop passed to run(): use levelUnit = Price", text_color = txt, text_size = textSize)
table.merge_cells(tbl, 0, row, 4, row)
else
array<float> wm = useR ? winMaeR : winMaeP
for lv in slL
row += 1
int c = _countAtLeast(wm, lv)
table.cell(tbl, 0, row, "X = " + (useR ? str.tostring(lv) + "R" : _fmtP(lv)), text_color = txt, text_size = textSize, text_halign = text.align_left)
table.cell(tbl, 1, row, _fmtPct(c, wm.size()), text_color = txt, text_size = textSize)
table.cell(tbl, 2, row, str.tostring(c) + " / " + str.tostring(wm.size()), text_color = txt, text_size = textSize)
table.merge_cells(tbl, 2, row, 4, row)
// target what-if
row += 1
table.cell(tbl, 0, row, "If target were Y (" + unitTxt + "): share of all trades whose MFE reached Y", text_color = txt, text_size = textSize, bgcolor = sect, text_halign = text.align_left)
table.merge_cells(tbl, 0, row, 4, row)
if rMissing
row += 1
table.cell(tbl, 0, row, "No stop passed to run(): use levelUnit = Price", text_color = txt, text_size = textSize)
table.merge_cells(tbl, 0, row, 4, row)
else
array<float> fm = useR ? mfeR : mfeP
for lv in tpL
row += 1
int c = _countAtLeast(fm, lv)
table.cell(tbl, 0, row, "Y = " + (useR ? str.tostring(lv) + "R" : _fmtP(lv)), text_color = txt, text_size = textSize, text_halign = text.align_left)
table.cell(tbl, 1, row, _fmtPct(c, fm.size()), text_color = txt, text_size = textSize)
table.cell(tbl, 2, row, str.tostring(c) + " / " + str.tostring(fm.size()), text_color = txt, text_size = textSize)
table.merge_cells(tbl, 2, row, 4, row)
row += 1
string comNote = includeCommission ? "Tester run-up / drawdown (incl. entry commission)." : "Price moves (entry commission removed)."
table.cell(tbl, 0, row, comNote + " Hindsight only.", text_color = dim, text_size = textSize, text_halign = text.align_left)
table.merge_cells(tbl, 0, row, 4, row)
if strategy.account_currency != syminfo.currency
row += 1
table.cell(tbl, 0, row, "Converted at each trade's own rate.", text_color = dim, text_size = textSize, text_halign = text.align_left)
table.merge_cells(tbl, 0, row, 4, row)
used