Buy not earlier then n bars after sell


#1

I tried to implement a condition, that it should not be allowed to enter a new trade earlier then 10 bars from the last sell without using loops... I end up in a compiler error 29 "variable 'Sell' used before having been initialized"

barsSinceLastTrade = BarsSince(Sell); //--- error 29 received!
Buy = Cross( Close, MA(Close, 35) ) && (barsSinceLastTrade >=10); // if I change the order, the error 29 occurs in this line...
Sell=LinRegSlope( MA(Close,18), 2 )<0; 

This example simplifies my entry and exit conditions but shows my dilemma. How can I avoid the error 29 working only with arrays?


#2

Try this:

Sell=false;
barsSinceLastTrade = BarsSince(Sell); //--- error 29 received!
Buy = Cross( Close, MA(Close, 35) ) && (barsSinceLastTrade >=10); // if I change the order, the error 29 occurs in this line...
Sell=LinRegSlope( MA(Close,18), 2 )<0;

You need to initialize variable Sell somewhere at the beginning of your formula.


#3

This post was flagged by the community and is temporarily hidden.


#4

FYI, the upper code I have posted is not correct. It's nonsense. So do not use it. It was an "after midnight" idea. But "after-midnight" ideas are not the best ones (no detailed check). I only used Buy = 1 and Sell = 1 as signals. If you use more common signals then it will not work.

For example if you use this one

period = 20;
m = MA( Close, period ); 
Buy = Cross( Close, m ); 
Sell = Cross( m, Close );

// min. re-entry delay of n-bars after sell
nbars = 10;// bar delay
Buy = Buy AND ExRemSpan( Buy, nbars);

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

Short = Cover = 0;

Then it will still have occasions where there are entries with less than minimum n-bars since sell.
125619

AFAICS, as of now I don't think there is a way using inbuilt array functions. The only function I know that has a re-entry delay is ApplyStop() function. But in 1st post there are not any stops involved.


Anyway... below I have made a loop version that should operate correctly (I only post this loop code because of my wrong upper post). You just have to insert your buy and sell signals in lines 12 and 13 and above of them adjusting your settings. That's all

/////////////////////////////////////////////////////////////////////////////////////
/// @link http://forum.amibroker.com/t/buy-not-earlier-then-n-bars-after-sell/5558/4
/// Code to set re-entry delay for Buys occurring n-bars AFTER Sell
/// by fxshrat@gmail.com, April 2018
/////////////////////////////////////////////////////////////////////////////////////
reentrydelay = 10;// min. Buy re-entry delay of n-bars since sell signal
tradedelay = 0;// trade entry delay

SetPositionSize( 100, spsShares );

// insert your buy, sell signals here
BuySignal = Cross( C, MA( C, 20 ) );
SellSignal = Cross( MA( C, 20 ), C );

/////////////////////////////////////////////////////////////////////////////////////
Buy = Sell = 0;
Short = Cover = 0;

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

BuySig = SellSig = 0;
buyentryprice = sellexitbarbar = 0; 
tradedelay = Min(tradedelay, Barcount-1);
for( i = tradedelay; i < BarCount; i++ ) {
	if( SellSignal[i-tradedelay] && buyentryprice > 0 ) {
		sellexitbarbar = i;
	}
	
	BuySignal2 = BuySignal[i-tradedelay] && i >= sellexitbarbar + reentrydelay;
	
	if( BuySignal2 && buyentryprice == 0 ) {
		Buy[ i ] = 1;
		buyentryprice = BuyPrice[ i ];	
		BuySig[i-tradedelay] = BuySignal2;
		sellexitbarbar = 0;
	} 
	
	if( SellSignal[i-tradedelay] && buyentryprice > 0 ) {
		Sell[ i ] = 1;    
		buyentryprice = 0;	
		SellSig[i-tradedelay] = SellSignal[i-tradedelay];		
	}	
} 

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 ) );
Plot( C, "Close", ParamColor( "Color Price", colorDefault ), styleNoTitle | ParamStyle( "Style" ) | GetPriceStyle(), 0, 1, 0, 0);

PlotShapes( BuySig*shapeUpArrow, colorGreen, 0, L, -15 );
PlotShapes( Buy*shapeHollowSmallCircle, colorLightYellow, 0, BuyPrice, 0 );

PlotShapes( SellSig*shapeDownArrow, colorRed, 0, H, -15 );
PlotShapes( Sell*shapeHollowSmallCircle, colorLightYellow, 0, SellPrice, 0 );

Lower pane in below picture is showing output of that loop version with minimum re-entry delay and upper pane of below picture is showing entry exit without any (minimum) re-entry delay but using same signals.
130209


#5

Update of loop version (small fix and simpler loop plus adding signals of first post):

/////////////////////////////////////////////////////////////////////////////////////
/// @link http://forum.amibroker.com/t/buy-not-earlier-then-n-bars-after-sell/5558/5
/// Code to set re-entry delay for Buys occurring n-bars AFTER Sell, vrs. 1.1
/// by fxshrat@gmail.com, April 2018
/////////////////////////////////////////////////////////////////////////////////////
reentrydelay = 10;// min. Buy re-entry delay of n-bars since sell signal
tradedelay = 0;// trade entry delay

SetPositionSize( 100, spsShares );

// insert your buy, sell signals here
BuySignal = Cross( C, MA( C, 35 ) );
SellSignal = LinRegSlope( MA(Close, 18), 2 ) < 0;

/////////////////////////////////////////////////////////////////////////////////////
Buy = Sell = 0;
Short = Cover = 0;

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

BuySig = SellSig = 0;
buyentryprice = sellexitbar = 0;
tradedelay = Min(tradedelay, Barcount-1); 
for( i = tradedelay; i < BarCount; i++ ) {
	b = i - tradedelay;	
	
	if( SellSignal[ b ] && buyentryprice > 0 ) {
		Sell[ i ] = 1;
		SellSig[ b ] = SellSignal[ b ];
		sellexitbar = i;		
		buyentryprice = 0;	
	}
	
	BuySignal2 = BuySignal[ b ] && i >= sellexitbar + reentrydelay;
	
	if( BuySignal2 && buyentryprice == 0 ) {
		Buy[ i ] = 1;
		buyentryprice = BuyPrice[ i ];
		BuySig[ b ] = BuySignal2;
		sellexitbar = 0;
	} 	
} 

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 ) );
Plot( C, "Close", ParamColor( "Color Price", colorDefault ), styleNoTitle | ParamStyle( "Style" ) | GetPriceStyle(), 0, 1, 0, 0);

PlotShapes( BuySig*shapeUpArrow, colorGreen, 0, L, -15 );
PlotShapes( Buy*shapeHollowSmallCircle, colorLightYellow, 0, BuyPrice, 0 );

PlotShapes( SellSig*shapeDownArrow, colorRed, 0, H, -15 );
PlotShapes( Sell*shapeHollowSmallCircle, colorLightYellow, 0, SellPrice, 0 );

803


#6

Thanks a lot, it works :slight_smile:


#7

Here is last version with adding ExRem (comment or uncomment it), output calculated min and max bar delay of array, and text output for bars since last sell when there's new buy as well as MA and LinearReg plot for signal check.

/////////////////////////////////////////////////////////////////////////////////////
/// @link http://forum.amibroker.com/t/buy-not-earlier-then-n-bars-after-sell/5558/7
/// Code to set re-entry delay for Buys occurring n-bars AFTER Sell, vrs. 1.2
/// by fxshrat@gmail.com, April 2018
/////////////////////////////////////////////////////////////////////////////////////
SetBarsRequired( -2 );// set number of bars required (-2 -> sbrall)

SetPositionSize( 100, spsShares );

reentrydelay = 10;// min. Buy re-entry delay of n-bars since sell signal
tradedelay = 0;// trade entry delay

// insert your buy, sell signals here
per = 35;
BuySignal = Cross( C, MA( C, per ) );//C > MA( C, per );// 
SellSignal = LinRegSlope( MA(Close, 18), 2 ) < 0;// Cross( MA( C, per ), C );// MA( C, per ) > C;// 

Plot( MA( C, per ), "MA"+per, colorRed );
Plot( LinRegSlope( MA(Close, 18), 2 ) < 0, "LinRegSlope < 0", colorGold, styleOwnScale );

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

// (un-)comment to remove/keep excessive signals
BuySignal = ExRem( BuySignal, SellSignal );
SellSignal = ExRem( SellSignal, BuySignal );

Buy = Sell = 0;
Short = Cover = 0;

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

maxbars = 0;
minbars = 1e9;
BuySig = SellSig = 0;
buyentryprice = sellexitbar = 0;
tradedelay = Min(tradedelay, Barcount-1); 
for( i = tradedelay; i < BarCount; i++ ) {
	b = i - tradedelay;

	BuySignal2 = BuySignal[ b ] && i >= sellexitbar + reentrydelay;
	
	if( BuySignal2 && buyentryprice == 0 ) {
		Buy[ i ] = 1;
		buyentryprice = BuyPrice[ i ];
		BuySig[ b ] = BuySignal2;
		minbars[ i ] = maxbars[ i ] = (i - sellexitbar);
		sellexitbar = 0;	
	} 	
	
	if( SellSignal[ b ] && buyentryprice > 0 ) {
		Sell[ i ] = 1;
		SellSig[ b ] = SellSignal[ b ];
		sellexitbar = i;		
		buyentryprice = 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( BuySig*shapeUpArrow, colorGreen, 0, L, -15 );
PlotShapes( Buy*shapeHollowSmallCircle, colorLightYellow, 0, BuyPrice, 0 );

PlotShapes( SellSig*shapeDownArrow, colorRed, 0, H, -15 );
PlotShapes( Sell*shapeHollowSmallCircle, colorLightYellow, 0, SellPrice, 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 ( Buy[i] )
        PlotText( "Buy\nBars since Sell: " + minbars[i], i, L[ i ], colorGreen, colorDefault, -txtdist );
    if ( Sell[i] )
        PlotText( "Sell\n", i, H[ i ], colorRed, colorDefault, txtdist-fntsize );
}

658


#8

Good work @fxshrat ,
Your examples are very instructive & detailed , and i like this so much :slight_smile:

Just one small suggestion ,
I think it's always better for novice to see wrong examples as seeing right one
so they know the best techniques in code writing they should go through and also the less efficient solutions which they must avoid beside that they can see how your thinking evolved from one post to another

So my humble suggestion is to keep the right and the wrong answer , cause i think both of them are important for novices

Thanks again