amibroker

HomeKnowledge Base

Preventing exit during first N bars

Here is sample technique that allows to prevent exiting position during first N bars since entry. The implementation uses loops that checks for signals in Buy array and if it finds one it starts counting bars in trade. During first N bars all sell signals are then removed (set to zero) only once counter reaches user-defined limit sell signals are accepted.

To change the N parameter please modify MinHoldBars variable (in this sample formula it is set to 17).

Note also that code works only for regular trading systems that do not use any stops.
If you use stops or use rotational trading then the only solution would be using custom backtester. On the positive side: next version of AmiBroker (4.78) will have native implementation of MinHoldBars so you will not need to code it for yourself.

// Sample system
// Buy when MACD is greater than zero AND RSI is greater than 30
// Sell if either MACD is less than zero
// OR RSI crosses below 70

Buy MACD() > AND RSI() > 30;
Sell MACD() < OR Cross70RSI() );

// now we would like to ensure that position is NOT
// exited during first MinHoldBars 

MinHoldBars 17// say don't want to exit for first 17 bars since entry

// first filter out buy signals occuring outside testing range
Buy Buy AND Status("barinrange");

BarsInTrade 0;
for( 
0BarCounti++ )
{
  
// if in-trade, then increase bar counter
  
if( BarsInTrade BarsInTrade ++;
  else
  if( 
Buy] ) BarsInTrade 1// on buy signal start counting bars-in-trade
 
  // if we are in trade - remove sells occurring too soon
  
if( BarsInTrade MinHoldBars Sell] = 0;
  else
  if( 
Sell] ) BarsInTrade 0// on sell reset barsintrade flag
}

No comments yet. Be the first.

Leave a reply