Max opened positions per bar

Hi,
I'm working with daily bars on a portfolio and I want to limit the number of positions that I can open in a day (on different markets).
For example, I want to be able to open no more then 5 new positions per bar, with overall 20 MaxOpenPositions and I can't be overall exposed to more then 50% of current equity.

How can I do that? Thanks.

The answer to this question is already present in the Knowledge Base:
http://www.amibroker.com/kb/2015/09/26/limit-number-of-trades-per-day-in-a-backtest/
this however covers intraday data.

If you want EOD data, and limit number of open positions you need mid-level custom backtester http://www.amibroker.com/guide/a_custombacktest.html

Iterate thru signals and set price for 6th and subsequent signals to -1 - this will tell backtester to stop processing signals. Something along these lines:

SetCustomBacktestProc("");

if (Status("action") == actionPortfolio) 
{
    bo = GetBacktesterObject();	//  Get backtester object
    bo.PreProcess();	//  Do pre-processing (always required)

    for (i = 0; i < BarCount; i++)	//  Loop through all bars
    {
        k = 0;
        for (sig = bo.GetFirstSignal( i ); sig; sig = bo.GetNextSignal( i ) )
        {	
              // do your custom signal processing
              
              if( ++k > 5 ) sig.Price = -1; // tell backtester to ignore signal
              
        }	
        
        bo.ProcessTradeSignals( i );	//  Process trades at bar (always required)
    }	  
      
    bo.PostProcess();	//  Do post-processing (always required)
}
4 Likes

@Tomasz I have gone through the mentioned link and forums as well. I am looking to control max no. of positions in real trading on intraday basis. Using "Exrem" function in a single AFL will keep max position to 1. What if I am running 5 AFL and I want only 1 BUY at a time in all the 5 AFL together? That is at any time max open position will be 1. There is no limit to no. of trades in a day or no. of trades limit for a script. I just need to see 1 open position altogether. Below is my code that I want to run on 5 different charts. What should I do to make one buy and one sell for all chats? Please guide

_SECTION_BEGIN("EmaCrossovers with trail");

SetPositionSize(1*RoundLotSize,spsShares);
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );

tsl = Param("% Trailing Stoploss",2,0.25,10,0.25);

Buy1 = Cross(EMA(Close,20),EMA(Close,50));
Buy2 = Cross(EMA(Close,9),EMA(Close,26));
Buy3 = Cross(MA(Close,8),EMA(Close,20));

Buy = Buy1 OR Buy2 OR Buy3 ;

Sell1 = Cross(EMA(Close,50),EMA(Close,20));
Sell2 = Cross(EMA(Close,26),EMA(Close,9));
Sell3 = Cross(MA(Close,20),EMA(Close,8));
Sell4 = Cross(TimeNum(), 152800) ;

BuyPrice = ValueWhen(Buy,Close);
entryprice = BuyPrice;
stoplevel = (1 -   tsl / 100);  //initial stoploss
//initialize the variables before using it inside the forloop
Sell = 0;
trailstop = 0;  
trailArray = Null;

for( i =1 ; i<BarCount; i++)  

{
    if(trailstop == 0 AND Buy[i])  
	{
	trailstop = entryprice[i] - entryprice[i] * tsl/100; 
	}
	else
	{
	Buy[i] = 0; 
	}
	
    if(trailstop > 0 AND L[i] < trailstop)
	{
	Sell[i] = True;
	SellPrice[i] = trailstop;
	trailstop = 0;  
	}
	if(trailstop > 0 AND sell1[i])
	{
	Sell[i] = True;
	SellPrice[i] = sell1[i];
	trailstop = 0; 
	}
	if(trailstop > 0 AND sell2[i])
	{
	Sell[i] = True;
	SellPrice[i] = sell2[i];
	trailstop = 0; 
	}
	if(trailstop > 0 AND sell3[i])
	{
	Sell[i] = True;
	SellPrice[i] = sell3[i];
	trailstop = 0; 
	}
	if(trailstop > 0 AND sell4[i])
	{
	Sell[i] = True;
	SellPrice[i] = Open[i];
	trailstop = 0; 
	}
	if(trailstop > 0) 
	{
	trailstop = Max(High[i] * stoplevel, trailstop); 
	trailarray[i] = trailstop;
	
	}


}//for loop


Plot(trailarray,"TSL Value",colorYellow,styleDashed | styleThick);


/* Plot Buy and Sell Signal Arrows */
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);




_SECTION_END();

It is an interesting use case. I use amibroker to trade live automated. Such logic I have personally implemented outside amibroker with amibroker used for signal generation, order placing and order management and other logic with scripts around it.

Just a hint to try within amibroker- use static variable as an indicator to know a position is taken and use critical section concepts to operate on this variable across the AFLs. May be there are better ways to achieve the same

@amiuser Thanks for reply. I tried using staticvariable like this in code below. May I know if I am using it right. Because this is not working. All signals disappears after using staticvar like this. Can you correct if there is a mistake?

_SECTION_BEGIN("EmaCrossovers with trail");

SetPositionSize(1*RoundLotSize,spsShares);
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );

tsl = Param("% Trailing Stoploss",0.25,0.25,10,0.25);

Buy1 = Cross(EMA(Close,20),EMA(Close,50));
Buy2 = Cross(EMA(Close,9),EMA(Close,26));
Buy3 = Cross(MA(Close,8),EMA(Close,20));

Buy = Buy1 OR Buy2 OR Buy3 ;

Buy = Buy AND Nz(StaticVarGet("commonflag"))==0 ;

Sell1 = Cross(EMA(Close,50),EMA(Close,20));
Sell2 = Cross(EMA(Close,26),EMA(Close,9));
Sell3 = Cross(MA(Close,20),EMA(Close,8));
Sell4 = Cross(TimeNum(), 152800) ;

BuyPrice = ValueWhen(Buy,Close);
entryprice = BuyPrice;
stoplevel = (1 -   tsl / 100);  //initial stoploss
//initialize the variables before using it inside the forloop
Sell = 0;
trailstop = 0;  
trailArray = Null;

for( i =1 ; i<BarCount; i++)  

{
    if(trailstop == 0 AND Buy[i] AND StaticVarGet("commonflag")==0)  
	{
	trailstop = entryprice[i] - entryprice[i] * tsl/100; 
	StaticVarSet("commonflag",1) ;
	}
	else
	{
	Buy[i] = 0; 
	}
	
    if(trailstop > 0 AND L[i] < trailstop)
	{
	Sell[i] = True;
	SellPrice[i] = trailstop;
	trailstop = 0;  
	StaticVarSet("commonflag",0) ;
	}
	if(trailstop > 0 AND sell1[i])
	{
	Sell[i] = True;
	SellPrice[i] = sell1[i];
	trailstop = 0; 
	StaticVarSet("commonflag",0) ;
	}
	if(trailstop > 0 AND sell2[i])
	{
	Sell[i] = True;
	SellPrice[i] = sell2[i];
	trailstop = 0; 
	StaticVarSet("commonflag",0) ;
	}
	if(trailstop > 0 AND sell3[i])
	{
	Sell[i] = True;
	SellPrice[i] = sell3[i];
	trailstop = 0; 
	StaticVarSet("commonflag",0) ;
	}
	if(trailstop > 0 AND sell4[i])
	{
	Sell[i] = True;
	SellPrice[i] = Open[i];
	trailstop = 0; 
	StaticVarSet("commonflag",0) ;
	}
	if(trailstop > 0) 
	{
	trailstop = Max(High[i] * stoplevel, trailstop); 
	trailarray[i] = trailstop;
	
	}


}//for loop


Plot(trailarray,"TSL Value",colorYellow,styleDashed | styleThick);


/* Plot Buy and Sell Signal Arrows */
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);




_SECTION_END();

You are right, and that is probably due to how static variable is used. May be if you update the static variable only for the last bar, it may help? In the end , you have to set that static variable for the current bar as you are interested in the live trade.

The problem as i see in current code is because the static variable is not an array and the same variable is update as you iterate through the bars.