I am trying to figure out how to get the custom backtester to take only buy signals when greater than 5% net short and take only short signals when I'm greater than 5% long. I recognize that is not the best feedback loop required to maintain a "hedge" but for learning purposes, I'm OK with an approximation. There are examples of how to trade based on a built in calculation of Equity, but there's apparently no canned way to calculate Longs - Minus Shorts (net dollar exposure), or similar.
I cannot figure out why this code below does not only take buy trades when I'm short. I've put this together using the Houston slides, plus the 01-2005 newsletter and http://www.amibroker.com/library/detail.php?id=934: SetOption("UseCustomBacktestProc", True ); Tradesize = 10; net=0; if( Status("action") == actionPortfolio ) { bo = GetBacktesterObject(); bo.PreProcess(); // Initialize backtester for(bar=1; bar < BarCount; bar++) //i set this to bar=1 instead of zero to prevent bar-1 from goign out of subscript range error { bo.ProcessTradeSignals( bar ); CurEquity = bo.Equity; for( pos = bo.GetFirstOpenPos(); pos; pos = bo.GetNextOpenPos() ) { posval = pos.GetPositionValue(); if(pos.islong == -1){LongOrShort = 1;}if(pos.islong == 0) {LongOrShort = -1;} net = net+ pos.GetPositionValue() * LongOrShort; diff = posval - 0.05 * CurEquity; price = pos.GetPrice( bar, "O" ); // rebalance only if difference between desired and // current position value is greater than 0.5% of equity // and greater than price of single share for (trade=bo.GetFirstOpenPos(); trade; trade = bo.GetnextOpenPos()) {//loop through all open positions if( net[bar - 1] > .05 ) { scalesize = trade.getentryvalue() * 2; bo.ScaleTrade( bar, pos.Symbol, net[bar-1] > .05, price, Scalesize); } if( net[bar - 1] < -.05 ) { scalesize = trade.getentryvalue() * .5; bo.ScaleTrade( bar, pos.Symbol, net[bar-1] < -.05, price, scalesize); } // bo.UpdateStats(bar,2); // trade.addcustommetric("net",net); } // end of for loop over trades at this bar } } bo.PostProcess(); // Finalize backtester } Buy=Cover=C > MA(C,500); Sell=Short=C < MA(C,500);