BarsInTrade logic question

Hello,
I would expect the following code to never allow for trades lasting more than 3 bars. That is not the case. I realize this could be done with an nbar ApplyStop but I need to do it this way to get to my final objective.

Buy = C>Ref(H,-1);

Sell1 = ROC(C,1)>0;


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

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

  if( BarsInTrade > 3 )
  { 
     Sell[ i ] = 1;
     BarsInTrade = 0;
  }
}

I believe it has something to do with simultaneous Buy/Sell signals but I don't know how to fix it.

Thanks for any thoughts provided.

Probably the "barssince (buy)" function will solve your question.

barssince(buy);

Check the AFL function reference (I cannot attach the link)

Thanks but I don't think that will work because the signal is IN STATE form as opposed to Signal (Pulse) form.

1 Like

Use these tools to help understand what's happening.

image

1 Like

@burger, have you looked at the SUM or CUM functions?

They may give you what you need without the loop.

I think you have to explain what you want to do when you have a Buy and Sell Signal on the same bar. Then code suggestion is possible. .

Thank you for the replies. I did try CUM unsuccessfully. I'm trying to understand why the loop never triggers the BarsInTrade > 3 Sell logic. I've debugged it to the point of finding that it's not simultaneous signals that are making this behave unexpectedly. It's when Sell1==TRUE.

My final objective with this is to add a Sell trigger when the breakout fails. In other words, I'm buying when it closes above yesterday's high. For an example, lets assume yesterday's high was 100. Once I'm in the trade, I want to sell if it closes below 100. Is this possible to code without a loop?

You sure about that!

image

If it's your backtest results that don't line-up then you need to check your backtest settings / trade scenario.


Thanks TrendSurfer. When I run the same Exploration there is not a single instance where Sell triggered and Sell1 did not. The fact that it worked for you makes me think it must be something in my settings. I'll keep testing.

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.