amibroker

Home ▸ Knowledge 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(); trade; trade = bo.GetNextTrade() )
    {

      
// check for stop-loss exit reason
        
if( trade.ExitReason == 2 )
        {
         
// increase long or short counter respectively
            
if( trade.IsLong() )
                
stoplossCountLong++;
            else
                
stoplossCountShort++;
        }
    }

   
// add the custom metric
    
bo.AddCustomMetric( "Stoploss trades", stoplossCountLong + stoplossCountShort,
                         
stoplossCountLong, stoplossCountShort, 0 );

}

Buy = Cross( MACD(), Signal() );
Sell = Cross( Signal(), MACD() );
Short = Sell;
Cover = Buy;
ApplyStop( stopTypeLoss, stopModePercent, 2, 1 )

Comments are closed.