hi,

In a backtest on a portfolio of futures, in the 5-minute time domain I am 
trying to close all positions during the day when a certain return threshold is 
reached. I know this can be programmed using high level AFL code by calling the 
~~~EQUITY function and I have done this.

Now I am trying to do the same calculation using CBT code.

I have it working almost. The logic is:
1) loop through all bars
2) calculate the equity at each bar and save in a temporary array
3) loop through the open positions
4) when the equity of the previous bar (bar - 1) is greater that the threshold 
close the open position at the open of "bar".

this should ensure that any other open positions found later during the day 
will be closed out immidiatelly at the open. It almost seems to work but I 
can't figure out what is wrong. Anyone see a problem? As far as I can see it 
uses the wrong price when I exit a trade.  It seems it does not take the price 
at "bar" but at "bar + 1".

thanks ,Ed


SetCustomBacktestProc(""); 
if( Status("action") == actionPortfolio ) 
{ 
bo = GetBacktesterObject(); 
bo.PreProcess(); 
// temporary equity save array 
eqsave = 0; 
for( bar = 0; bar < BarCount; bar++ ) 
{ 
   CurrentPortfolioEquity = bo.Equity; 
   // save portfolio equity on each bar 
   eqsave[ bar ] = CurrentPortfolioEquity; 
    
   for (openpos = bo.GetFirstOpenPos(); openpos; openpos = bo.GetNextOpenPos()) 
   { 
      firstBarOfDayIndex = StaticVarGet( "firstBarOfDayIndex" + openpos.Symbol 
); 
      bi = StaticVarGet( "bi" + openpos.Symbol ); 
      dbar = bi[ bar ] - firstBarOfDayIndex[ bar ]; 
      equityStartDay = eqsave[ bar - dbar ]; 
       
      _TRACE("equityStartDay: " + equityStartDay); 
      _TRACE("CurrentPortfolioEquity - equityStartDay: " + 
(CurrentPortfolioEquity - equityStartDay)); 
      _TRACE("symbol: " + openpos.Symbol); 
      _TRACE("firstBarOfDayIndex[ bar ]: " + firstBarOfDayIndex[ bar ]);        
  
      _TRACE("bi[ bar ]: " + bi[ bar ]);    
      _TRACE("bar: " + bar);    
      _TRACE("dbar: " + dbar);    
       
      // close out open position at open if threshold previous bar has been 
crossed    
      if( eqsave[ bar - 1 ] - equityStartDay > thresholdEquity ) 
      { 
         _TRACE("***** threshold crossed at bar: " + (bar - 1));    
         _TRACE("exit price: " + openpos.GetPrice(bar, "O"));    
         bo.ExitTrade(bar,openpos.Symbol,openpos.GetPrice(bar, "O")); 
      } 
       
      //bo.UpdateStats(bar, 1); // Update MAE/MFE stats for bar 
      //bo.UpdateStats(bar, 2); // Update stats at bar's end 
   } 
   bo.ProcessTradeSignals( bar ); 
} 
bo.PostProcess(); 
} 
else if ( Status( "Actionex" ) == actionBacktest ) 
{ 
   StaticVarSet( "firstBarOfDayIndex" + Name(),firstBarOfDayIndex); 
   StaticVarSet( "bi" + Name(),BarIndex()); 
}

Reply via email to