How do I check the Number of Bars SInce Last Trade Exit and New Trade?

I am trying to check the number of bars between my last trade Exit and Entry of a Fresh Trade. Based on the numbers of days I want to add some filter to the new trade.

I tried this method but I cant use BarSince Cover condition to check that before Initialising Cover.

BarsSinceLastExit=BarsSince(Cover);
Short= if(BarsSinceLastExit < 20, (C < MA(C,20) AND C < Ref(LLV(20),-1)),(C< MA(20)));
Cover= C > MA(C,20);

Initially it would be good, in terms of barsince, to look at this link. BarSince measure Query

I think you're asking to measure the white candles in the attached photograph. Did I understand that correctly?
Buy%20to%20Short%20signal

Where, in the above chart, the first white candle will be the exit from the last trade and the first blue bar will be the entrance to a fresh trade. Something like that?

@vishaldalvi Your code is flawed and your "Short" condition is wrongly coded.

But more importantly please follow the rules of this forum and properly format code. It is so easy to type three little "backtick" lines, ``` and then put in your code, and then type in three more backticks.

And read this entire thread,

What/where are those backtick's?
image

The are the lower case of the key that has the "tilde" as the uppercase. Yes I know these are words most people do not use in their everyday conversation.

Others have written this description,

(`/~) The tilde key, since the name for the unshifted "grave accent" or "backtick" character is not widely known. (This may also go by the "squiggle key" or "the key next to the 1 with the squiggle on it" for people who don't know the name for "tilde" either; neither are commonly used outside of programming

Yes, you are right. I am trying to count the white bars...Which is the Number of Bars Since Last Exit and New Trade Entry.

I get your point...Apologies for the wrong codes. Below is the set of code I am trying.

BarsSinceLastExit=BarsSince(Cover);
Short= (BarsSinceLastExit > 20 AND (C < MA(C,20)) OR 
           (BarsSinceLastExit < 20 AND C < Ref(LLV(L,20),-1)) AND (C< MA(C,20)));
Cover= C > MA(C,20);

I am getting the error - " Variable used without having been initialized.

The issue I am facing is -

  • I have to check a variable BarSinceExit which is dependent on my Cover condition. And I need to use that same variable in my Short Trade condition. I am not able to use Cover condition to check Bars since the Exit.
  • Idea is to avoid too many signals back to back in a sideways market, hence I am adding a Filter on break below N bar low , if the new entry is within 20 bars from last trade Exit.

How can I code this ?

There's no reason that you can't assign your Cover variable before your Short, so you can at least start with something like this:

Cover= Cross(C, MA(C,20));
BarsSinceLastExit=BarsSince(Cover);
Short= (BarsSinceLastExit > 20 AND (C < MA(C,20)) OR 
           (BarsSinceLastExit < 20 AND C < Ref(LLV(L,20),-1)) AND (C< MA(C,20)));

Using the Cross() function (impulse signal) instead of the logical greater than operator (state signal) will help reduce the number of excess Cover signals that you have. However, you'll need to decide whether those excess signals are acceptable for purposes of counting bars.

2 Likes

Thread in regards re-entry delay exists already.

Code:

1 Like

Here is modified code from upper re-entry delay thread but with short rules of 5th post of this thread here.

/////////////////////////////////////////////////////////////////////////////////////
/// @link https://forum.amibroker.com/t/how-do-i-check-the-number-of-bars-since-last-trade-exit-and-new-trade/5993/9
/// Code to set re-entry delay for Shorts occurring n-bars AFTER Cover
/// And adding filter if signal is in between reentry delay
/// by fxshrat@gmail.com, May 2018
/////////////////////////////////////////////////////////////////////////////////////
SetBarsRequired( -2 );// set number of bars required (-2 is equal to sbrall -> all bars)

SetPositionSize( 100, spsShares );

reentrydelay = 20;// min. Short re-entry delay of n-bars since Cover signal
tradedelay = 0;// trade entry delay

// insert your Short, Cover signals here
per = 20;
ShortSignal = C < MA(C,per);
CoverSignal = C > MA(C,per);

myLL = Ref(LLV(L,20), -1);

Plot( MA( C, per ), "MA"+per, colorRed );
Plot( myLL, "LLV20", colorGold, styleOwnScale );

/////////////////////////////////////////////////////////////////////////////////////

// (un-)comment to remove/keep excessive signals
//ShortSignal = ExRem( ShortSignal, CoverSignal );
//CoverSignal = ExRem( CoverSignal, ShortSignal );

Buy = Sell = Short = Cover = 0;

if( tradedelay > 0 )	BuyPrice = SellPrice = ShortPrice = CoverPrice = O;
else					BuyPrice = SellPrice = ShortPrice = CoverPrice = C;

maxbars = 0;
minbars = 1e9;
ShortSig = CoverSig = 0;
Shortentryprice = Coverexitbar = 0;
tradedelay = Min(tradedelay, Barcount-1); 
for( i = tradedelay; i < BarCount; i++ ) {
	b = i - tradedelay;

	Shortreentrybar = Coverexitbar + reentrydelay;
	// if #bars below "bars since last exit" limit but C below LLV then Short
	ShortSignal1 = ShortSignal[ b ] && C[ b ] < myLL[ b ] && i < Shortreentrybar;
	// else only enter Short after min "bars since last exit"
	ShortSignal2 = ShortSignal[ b ] && i >= Shortreentrybar;
	
	if( (ShortSignal1 || ShortSignal2) && Shortentryprice == 0 ) {
		Short[ i ] = 1;
		Shortentryprice = ShortPrice[ i ];
		if( ShortSignal1 )
			ShortSig[ b ] = ShortSignal1;
		else
			ShortSig[ b ] = ShortSignal2;
		minbars[ i ] = maxbars[ i ] = (i - Coverexitbar);
		Coverexitbar = 0;	
	} 	
	
	if( CoverSignal[ b ] && Shortentryprice > 0 ) {
		Cover[ i ] = 1;
		CoverSig[ b ] = CoverSignal[ b ];
		Coverexitbar = i;		
		Shortentryprice = 0;	
	}	
} 

GraphXSpace = 8;

SetChartOptions( 0, chartShowArrows | chartShowDates | chartWrapTitle );
_N( Title = StrFormat( "{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%), Vol %g {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ), V ) );
_N( Title += StrFormat( EncodeColor(colorRed) + "\nCalculated Lowest re-entry delay: %g bars", SelectedValue(Lowest(minbars)) ));
_N( Title += StrFormat( EncodeColor(colorGreen) + "\nCalculated Highest re-entry delay: %g bars", SelectedValue(Highest(maxbars)) ));
Plot( C, "Close", ParamColor( "Color Price", colorDefault ), styleNoTitle | ParamStyle( "Style" ) | GetPriceStyle(), 0, 1, 0, 0);

PlotShapes( ShortSig*shapeDownArrow, colorRed, 0, H, -15 );
PlotShapes( Short*shapeHollowSmallCircle, colorLightYellow, 0, ShortPrice, 0 );

PlotShapes( CoverSig*shapeUpArrow, colorGreen, 0, L, -15 );
PlotShapes( Cover*shapeHollowSmallCircle, colorLightYellow, 0, CoverPrice, 0 );

bi = Barindex();
fvb = FirstVisiblevalue( bi );
lvb = LastVisiblevalue( bi );

fnt = "Arial";
fntsize = 8;
txtdist = 30;

PlotTextSetFont( "", fnt, fntsize, lvb, 0, -1 );
for ( i = fvb; i <= lvb; i++ ) {
    if ( Short[i] )
        PlotText( "Short\nBars since Cover: " + (minbars[i]+tradedelay), i, H[ i ], colorRed, colorDefault, txtdist+fntsize );
    if ( Cover[i] )
        PlotText( "Cover\n", i, L[ i ], colorGreen, colorDefault, -txtdist );
}

So If within "bars since last exit" limit then see if Close is below LLV and if so then Short entry
2018-05-15_155154

Else wait for new Short entry until "bars since last exit" limit has been reached.

1 Like

In upper code there is one line from the other thread's code that needs to be changed because otherwise plotted LLV line in ownscale mode would be misleading. In other thread's code it wasn't because there it was slope condition line that needed to be in own scale mode.

So long story short... go to line 22 of upper code and change

Plot( myLL, "LLV20", colorGold, styleOwnScale );

To

Plot( myLL, "LLV20", colorGold);

2018-05-15_204501

2 Likes

Thanks a lot for the detailed explanation...This helps.

1 Like