ExcursionReport

503
Strategy Trade Excursion Report (library)

This library adds a MAE / MFE report to your own strategy. For every closed trade it measures how far price went against the position (MAE, maximum adverse excursion) and how far it went in favor (MFE, maximum favorable excursion). It then shows the distribution of these values and two simple what-if tables in a table on the chart.

WHAT IT SHOWS
- Closed trades, winners, and trades with a valid stop ("With stop (R)").
- MAE and MFE: mean, median (P50), P75, P90 and P95, in price units and in R (multiples of the initial stop distance).
- "If stop were X": for 1 to 5 stop levels, the share of winning trades whose MAE reached X, i.e. how many winners would have been stopped out by a tighter stop.
- "If target were Y": for 1 to 5 target levels, the share of all trades whose MFE reached Y.

WHAT IS DIFFERENT FROM THE BUILT-IN COLUMNS
The Strategy Tester's List of Trades already shows Run-up and Drawdown trade by trade. This library does not repeat that list. It summarizes all trades at once (mean and percentiles, in price and in R), removes the entry commission that TradingView includes in those columns, and answers two what-if questions: how many winners came close to a given stop, and how many trades reached a given target.

HOW TO USE
1. Add the import line below your strategy() declaration. Use the version number shown in the import line on this page (the latest published version):
import Ku_Hero/ExcursionReport/1 as xr
2. At the end of your script (after strategy.entry / strategy.exit), call run() once, at global scope:
xr.run(stopPrice = myStopPrice)
- stopPrice: the stop-loss price you use in strategy.exit, or
- stopDistance = myStopDistance if you work with a distance in price units.
- stopTiming = "Signal bar" (default) or "Fill bar" (see below).
- If you do not use stops, leave stopPrice and stopDistance out and set levelUnit = "Price".
3. Optional arguments (defaults): includeCommission = false, slLevels = "0.5, 0.75, 1, 1.25", tpLevels = "0.5, 1, 1.5, 2, 3", levelUnit = "R" (or "Price"), tablePosition = position.bottom_right, textSize = size.small, showTable = true.
4. Helper functions: xr.maePrice(tradeNum) and xr.mfePrice(tradeNum) return the MAE / MFE of one closed trade in price units (optional second argument includeCommission).

A separate demo strategy, "Strategy Trade Excursion Report - Demo", shows a complete example with inputs for all of these settings.

HOW IT WORKS
- Source: strategy.closedtrades.max_drawdown() and max_runup(), the same data as the Drawdown and Run-up columns of the List of Trades.
- Commission: TradingView includes the entry commission in these figures (drawdown = adverse move + entry commission, run-up = favorable move - entry commission). By default (includeCommission = false) the library removes it, so MAE / MFE are pure price moves. Set includeCommission = true to use the Tester figures as they are. When the Tester shows a run-up of 0, MFE is shown as 0.
- Price units: the money value is divided by (position size x point value).
- Account currency different from the symbol currency: each trade's exchange rate is recovered from its own drawdown and run-up percent figures, so the conversion does not use today's rate. The entry commission is then estimated (exact for percentage commission, approximate for fixed commission). The table shows "Converted at each trade's own rate." in this case.
- R = excursion / initial stop distance, measured from the actual fill price. stopTiming chooses which bar's stop value is recorded:
- "Signal bar" (default): the value one bar before the entry is first seen as filled, i.e. the bar where a market order is sent. Use this when the stop is fixed when the order is sent (for example stop = close - ATR x k on the signal bar).
- "Fill bar": the value on the bar where the entry is first seen as filled. Use this when the stop is computed after the fill, for example from strategy.position_avg_price.
For stop or limit entry orders that wait several bars, keep the stop value unchanged while the order waits, or use "Fill bar".
- Trades without a stop are left out of the R columns and R levels; the price columns still include them. Trades whose stop is on the wrong side of the fill price are also left out of R and counted in a "Not in R" row.
- Winner = closed trade with net profit above zero.
- A value within 0.1% below a level counts as reaching it (this absorbs rounding, e.g. 1.9998R for a trade that hit a 2R target).
- Percentiles use linear interpolation between closest ranks (rank = (n - 1) x p / 100), the same convention as PERCENTILE.INC in spreadsheets, so you can check them against an exported trade list.
- The statistics are calculated on the last confirmed bar (and again when a new real-time bar closes). Closed trades do not change, so the report does not repaint. No request.security() calls are used.

LIMITATIONS
- Hindsight only. A trade that touched a tighter stop would have closed earlier; the tables do not re-run the strategy and do not show what the result would have been.
- The order of prices inside a historical bar is not known. MAE / MFE follow the assumptions of TradingView's backtest engine (Bar Magnifier changes them).
- If stop and target are set as prices from the signal bar's close, gaps and slippage change the real distance from the fill, so a trade that hit a "2R" target can show, for example, 1.93R. Exits given as distances from the fill (strategy.exit with loss / profit in ticks), as in the demo, avoid this. A stopped trade can show slightly more than 1R because of stop slippage.
- If the fill price gaps close to the stop, the stop distance is very small and R values can be very large.
- With different account and symbol currencies and a fixed (non-percentage) commission, the removed entry commission is an estimate.
- When TradingView trims the oldest trades of a very long backtest, the report covers only the trades still available ("Closed trades" shows the count).
- A table at the top left can overlap the chart legend; choose another position if it does.
- It needs a strategy script. It cannot read trades from indicators or from a broker account.

This is a measurement tool for your own backtests. It does not give trading signals and does not predict future results. Past backtest results do not guarantee future results.

---

【日本語】ExcursionReport(ストラテジー用 MAE/MFE レポートのライブラリ)
自分のストラテジーに数行で組み込むと、決済済みの各トレードの最大逆行幅(MAE)と最大順行幅(MFE)を集め、チャート上の表にまとめます。
- 表示:取引数、勝ちトレード数、MAE と MFE の平均・中央値・75/90/95 パーセンタイル(価格差と R。R=初期の損切り幅に対する倍数)。
- 「損切りを X にしていたら」:勝ちトレードのうち、途中で X まで逆行していたものの割合(1〜5段階)。
- 「利確を Y にしていたら」:全トレードのうち、MFE が Y に届いていたものの割合(1〜5段階)。
- 内蔵の「ラン・アップ/ドローダウン」列との違い:一覧を繰り返すのではなく、全トレードの分布と上の2つの集計を出します。内蔵の値に含まれるエントリー手数料は、既定では取り除いて純粋な値動きの幅にします(includeCommission = true で内蔵の値のまま)。
- 損切り幅は、注文を出した足の値(既定 "Signal bar")か、約定した足の値("Fill bar")かを選べます。
- 口座通貨と銘柄の通貨が違う場合は、トレードごとの当時のレートで換算します。
- 損切りを渡さなかったトレードは R の集計から外れます。損切りが約定価格の反対側にあるトレードも外し、「Not in R」の行に件数を出します。
- 水準に 0.1% 以内まで届いた値は「届いた」と数えます(丸め誤差の吸収)。
- 計算は最後の確定足で行い、リペイントしません。
- 限界:あと知恵の集計です。損切りや利確を変えた場合の損益を計算し直すものではありません。足の中の値動きの順序は TradingView のバックテストの仮定に従います。表を左上に置くと凡例と重なることがあります。
自分のバックテストを測るための道具です。売買シグナルや将来の成績を示すものではありません。過去のバックテストの結果は将来の成績を保証しません。

Wyłączenie odpowiedzialności

Informacje i publikacje nie stanowią i nie powinny być traktowane jako porady finansowe, inwestycyjne, tradingowe ani jakiekolwiek inne rekomendacje dostarczane lub zatwierdzone przez TradingView. Więcej informacji znajduje się w Warunkach użytkowania.