Would greatly appreciate assistance with code to add custom backtest metrics to Backtest Reports for these 2 values.
I've spent quite a bit reading this helpful post today, but skills not up to separating the matrix of closed trades into a series of winners and losers - and then finding the median of those 2 series.
Thank you. So, re-purposing that code using winning and losing matricies, my effort is below.
(Forgive my indiscretion choosing middle term in each array - technically should be mean of 2 middle terms for an even number of terms. Seems close enough checked manually in Excel for closed trades, especially for large number of trades)
/// @link https://forum.amibroker.com/t/using-custom-backtest-to-find-min-max-mae-mfe-per-loosing-winning-trades/15376/2
/// Storing separate winning/losing MAE/MFE of closed trades to 2-dim array
/// And getting separate winning/losing min/max MAE/MFE of closed trades
/// by fxshrat@gmail.com
SetCustomBacktestProc("");
if (Status("action") == actionPortfolio) {
bo = GetBacktesterObject();
bo.Backtest();
wi = li = 0;
for (trade=bo.GetFirstTrade(); trade; trade=bo.GetNextTrade()) {
if (trade.GetPercentProfit() > 0)
wi++;
else
li++;
}
// Calculate Median of % Profit and % Loss
mat1 = Matrix(Max(1,wi), 1);// winning
mat2 = Matrix(Max(1,li), 1);// losing
wi = li = 0;
for (trade=bo.GetFirstTrade(); trade; trade=bo.GetNextTrade()) {
if (trade.GetPercentProfit() > 0) {
mat1[wi][0] = trade.GetPercentProfit();
wi++;
} else {
mat2[li][0] = trade.GetPercentProfit();
li++;
}
}
sort1 = MxSort(mat1, 1);
sort2 = MxSort(mat2, 1);
//_TRACE(MxToString(sort1));
//_TRACE(MxToString(sort2));
last_wi = MxGetSize(sort1, 0)-1;
last_li = MxGetSize(sort2, 0)-1;
// Median % Profit for winning trades:
Median_wi = sort1[last_wi/2][0];
// Median % Loss for losing trades:
Median_Li = sort2[last_li/2][0];
bo.AddCustomMetric("#Winning", wi);
bo.AddCustomMetric("#Losing", li);
// Winning ones
bo.AddCustomMetric("Median % Profit Winning", Median_wi);
// Losing ones
bo.AddCustomMetric("Median % Loss Losing", Median_li);
}
```