HomeKnowledge Base

Number of stopped-out trades as a custom metric

For the purpose of counting trades closed by particular stop we can refer to ExitReason property of the trade object in the custom backtester. The custom backtest formula presented below iterates through the list of closed trades, then counts the trades, which indicate exit reason = 2, that is stop-loss.

The following values are used for indication of the particular exit reason:

  1. normal exit
  2. maximum loss stop
  3. profit target stop
  4. trailing stop
  5. n-bar stop
  6. ruin stop (losing 99.96% of entry value)
SetCustomBacktestProc"" );

/* Now custom-backtest procedure follows */
if( Status"action" ) == actionPortfolio )
bo GetBacktesterObject();

bo.Backtest(); // run default backtest procedure

    // initialize counter
stoplossCountLong stoplossCountShort 0;

// iterate through closed trades
for( trade bo.GetFirstTrade(); tradetrade bo.GetNextTrade() )
// check for stop-loss exit reason
if( trade.ExitReason == )
// increase long or short counter respectively
if( trade.IsLong() )

// add the custom metric
bo.AddCustomMetric"Stoploss trades"stoplossCountLong stoplossCountShort


Buy CrossMACD(), Signal() );
Sell CrossSignal(), MACD() );
Short Sell;
Cover Buy;

How to display interest gains in the backtest report

The default backtest report shows total Net Profit figure, which includes both trading profits and interest earnings. With Custom Backtest procedure we can easily isolate these components by summing up profits and loses from individual trades, then subtracting trading gains from the Net Profit and report them as separate metrics.

SetCustomBacktestProc"" );

if ( 
Status"action" ) == actionPortfolio )
bo GetBacktesterObject();
bo.Backtest(); // run default backtest procedure

    // read Net Profit, Winners and Losers profits from the report
st bo.GetPerformanceStats);
netProfit st.GetValue"NetProfit" );
tradeProfits st.GetValue("WinnersTotalProfit") + st.GetValue("LosersTotalLoss");

bo.AddCustomMetric"Trading profits"tradeProfits ); 
bo.AddCustomMetric"Interest earnings"netProfit tradeProfits );


// trading rules here
Buy CrossMACD(), Signal() );
Sell CrossSignal(), MACD() );

After backtest is run, we can see our custom metrics in the backtest report.

More information about creating custom metrics can be found in the manual:

Historical portfolio backtest metrics

Recently on the AmiBroker mailing list some users expressed wish to have access to some of portfolio backtest metrics available in “historical” form (i.e. as date series, as opposed to scalars), so they can be plotted as an indicator.

Implementing such functionality is actually easy with existing tools and does not require any OLE scripts. Everything you need is small custom-backtester procedure that just reads built-in stats every bar and puts them into composite ticker.
In the accompanying indicator code all you need to do is simply use Foreign() function to access the historical metrics data generated during backtest.

The code below shows the BACKTEST formula with custom backtester part:

// Replace lines below with YOUR TRADING SYSTEM
PositionScore 1/RSI(14); 
PositionSize = -25;

// that can read any built-in metric (in this example UlcerIndex)
// and store it into composite ticker for further
// retrieval as data series

SetOption("UseCustomBacktestProc"True ); 

Status("action") == actionPortfolio )
bo GetBacktesterObject();
bo.PreProcess(); // Initialize backtester
  // initialize with null 
  // you can have as many historical metrics as you want 
  // (just duplicate line below for many metrics you want)
MyHistStat1 Null
MyHistStat2 Null// add your own 

for(bar=0bar BarCountbar++)
bo.ProcessTradeSignalsbar );
// recalculate built-in stats on EACH BAR
stats bo.GetPerformanceStats); 
// the line below reads the metric and stores it as array element
   // you can add many lines for each metric of your choice
MyHistStat1bar ] = stats.GetValue("UlcerIndex"); // get ulcer index value calculated this bar
MyHistStat2bar ] = stats.GetValue("WinnersPercent"); // add your own


bo.PostProcess(); // Finalize backtester

  // now STORE the historical data series representing the metric of your choice
  // duplicate the line below for as many metrics as you want
AddToCompositeMyHistStat1"~~~UI_HISTORICAL""X"atcFlagEnableInPortfolio atcFlagDefaults );

// you can add your own as shown below
AddToCompositeMyHistStat2"~~~WP_HISTORICAL""X"atcFlagEnableInPortfolio atcFlagDefaults ); 

In the code above, for illustration purposes, we are exporting UlcerIndex and Winners Percent metrics as data series. They are stored in composite tickers for easy retrieval from indicator level.
You can easily extend code to include ANY number of metrics you want.

Now in order to Plot metrics as indicators, use this simple formula:

PlotForeign("~~~UI_HISTORICAL""UlcerIndex Historical"colorRedstyleLine );
PlotForeign("~~~WP_HISTORICAL""Winners Percent"colorBluestyleLine styleOwnScale );

As you can see with one Foreign function call you can read the historical value of any metric generated by the backtester.

NOTE: when running backtest please setup a filter in AA that EXCLUDES composites (group 253) from backtest set.

Adding custom metric: Average adverse excursion

Here is a sample that shows how to create custom metric based on per-trade statisitics.
In this example we will calculate the average value of MAE (maximum adverse excursion) from all trades.