Counting bars in trade resulting in 2 sell exit strategies

Hello,

I am struggling to solve the following puzzle. I would like to count the bars while after I bought (and remove signals in between). Based on the bar count I want to let Ami decide on two sell exits. One is if bars intrade is less than 10(days) than sell = RSI(2)>70 and if bars in trade is => 10 than RSI(2)> 90. I have used a code part which was available here and are trying now to make it work without succes. Can anyone help? I think I am writing the loop in the wrong order and I am also not initializing barsintrade on the right spot…I guess

BuyPrice=Close;
SellPrice=Close;
SetTradeDelays(0,0,0,0);


Buy = RSI(2) < 22 
		
Sell =(barsintrade <10 AND RSI(2) > 72) OR
	(barsintrade =10 OR Bars>10 AND RSI(2) > 92)


Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell, Buy);

BarsInTrade = 0;
for( i = 0; i < BarCount; i++ )
{
  // if in-trade, then increase bar counter
  if( BarsInTrade > 0 ) BarsInTrade ++;
  else
 
 if( Buy[ i ] ) BarsInTrade = 1; // on buy signal start counting bars-in-trade
 
  if( Sell[ i ] ) BarsInTrade = 0; // on sell reset barsintrade flag
}

Many thanks in advance!

Swen

Moderator comment: Use [code] tags as explained in “How to use this site” Yet again I had to correct someone’s post for sole purpose of not reading instructions by the poster

First you need to understand the difference between state and pulse form. BarsSince can be used if signal is in pulse form

Buy = Cross( 22, RSI( 2 ) ); // pulse form of buy signal

Your Buy is NOT in pulse form and you can’t use BarsSince then.

Secondly, you are doing other mistakes such as using = (assignment) instead of comparison (==).
These are basic mistakes that you need to get rid of otherwise all formulas will be wrong.
https://www.amibroker.com/guide/a_mistakes.html

Thirdly if you are using loop, you don’t need ExRem or BarsSince or anything like that:

r = RSI( 2 );
Buy = r < 22; // state form

Sell1 = r > 72; // state form
Sell2 = r > 92; // state form

Sell = 0;
BarsInTrade = 0;
for( i = 0; i < BarCount; i++ )
{
   if( BarsInTrade > 0 ) 
     BarsInTrade++;
   else if( Buy[ i ] ) BarsInTrade = 1;

   if( BarsInTrade < 10 AND Sell1[ i ] ) 
    {
       Sell[ i ] = 1;
       BarsInTrade = 0;
   }

  if( BarsInTrade >= 10 AND Sell2[ i ] )
  { 
     Sell[ i ] = 1;
     BarsInTrade = 0;
  }
}
8 Likes

Hi, Is it possible to add a text string to the two sell signals so that the backtest results show which exit was taken?

Thanks.

http://www.amibroker.com/kb/2014/09/24/how-to-identify-which-signal-triggers/

1 Like