// Downloaded From https://www.WiseStockTrader.com
SetOption("UseCustomBacktestProc", True );
SetCustomBacktestProc("",True);

if( Status("action") == actionPortfolio ) // point to correct iteration of backtest engine
{
	//initialize custom backtest engine
	//bo is backtestobject
	
	bo = GetBacktesterObject();
	
	bo.Backtest(); // run default backtest procedure
	st = bo.GetPerformanceStats(0); // get stats for all trades
	totalLossTrades = totalWinTrades = totalRuns = 0;
	for (trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade())
    {	//  Loop through all closed trades
        if (trade.GetProfit() > 0)	//  If this was a winning trade
        {
			if (totalWinTrades == 0) totalRuns++;
            totalWinTrades++;
			totalLossTrades = 0;			
        }
		if (trade.GetProfit() < 0)	//  If this was a winning trade
        {
			if (totalLossTrades == 0) totalRuns++;
            totalLossTrades++;
			totalWinTrades = 0;
        }
		
    }	//  End of for loop over all trades

	
	
	N = st.GetValue("AllQty");
	R = totalRuns;
	WIN = st.GetValue("WinnersQty");
	LOSS = st.GetValue("LosersQty");
	X = 2 * WIN * LOSS;
	Z_Score = (N*(R-0.5)-X)/SQRT((X*(X-N))/(N-1));
	
	
	bo.AddCustomMetric( "Z-Score",Z_Score );
	bo.AddCustomMetric( "totalRuns",totalRuns );
}