Check if previous bar is in a position

I have a pretty simple strategy designed to experiment with R-multiples and seeing the relationship with take profit and stop loss. It buys on breakouts. I'm having an issue with this strategy where if a breakout occurs that hits an open position's take-profit level, a new position is opened (which I don't want), and it also does not create a new take profit level for this new position. I would like to ensure that no new position can be opened if the previous bar is already in a position.

AmiBroker - NUE - Nucor Corp Common - Daily 2022

I have added else Buy[i] = 0; to try to remove excess buy signals while in a position to my code, but I think since the same candle that exits a position also would then create a new position (had I not already been in one) triggers this, this is not behaving as I want.

So I think I need a way to check to see if the previous bar is in a position, and if so to ignore the buy signal. This seems like it should be simple enough, but searching on the forum did not produce relevant results, so I'm potentially using incorrect terms here.

Any tips on avoiding new entries when the previous bar was in an entry already would be appreciated.

// ==========================================================================================
// === TRADING SYSTEM PARAMETERS ===
// ==========================================================================================
SetOption("InitialEquity", 100000);
SetTradeDelays( 0, 0, 0, 0 ); // 1 - Delays the trades to the next day, 0 - Trades same day via stops
SetOption("AllowPositionShrinking", True);
SetOption("AccountMargin",100); // 100 = Cash account, 75 = Using half available margin
SetOption("MaxOpenPositions", 20);
RoundLotSize = 1;  // Disallow fractional share purchasing


// ==========================================================================================
// === RISK MANAGEMENT & POSITION SIZING ===
// ==========================================================================================
// Initial (MAX) stop loss
SetOption("ActivateStopsImmediately", False);
stopLoss = 5; // Change this to a small number to experience the issue with trade entries being ignored
ApplyStop(stopTypeLoss, stopModePercent, stopLoss, ExitAtStop = 1);

// Position size based on risk and max stop loss
PositionRisk = 1;  
PosSize = 100 * PositionRisk / stopLoss;
SetPositionSize(PosSize, spsPercentOfEquity);
         

// ==========================================================================================
// === PLOT CHART & INDICATORS ===
// ==========================================================================================
// Chart
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - " + FullName() + " | {{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() ); 

// Donchian Channel
pdsU=3;  // High channel lookback
pdsL=5;  // Low channel lookback

DonchianUpper =HHV(H,pdsU);
DonchianLower = LLV(L,pdsL);

Plot(DonchianUpper,"DU",color = colorBlueGrey,styleDashed);
//Plot(DonchianLower,"DL",color = colorBlueGrey, styleDashed);
  
// ==========================================================================================
// === BUY & SELL LOGIC ===
// ==========================================================================================
Buy=Cross(High, Ref(DonchianUpper, -1)); 
BuyPrice=Max(Ref(DonchianUpper, -1), Open);

// == EXIT CONDITIONS ===
// Initialize variables
Sell=0;
trailArray = Null;
trailStop = 0;
ptArray = Null;
priceatbuy = 0;
highsincebuy = 0;

//profitTarget = Optimize("PT", 10, 5, 15, 1);  // Unhide to Optimize - looks like the higher the better...so might as well not use a PT
profitTarget = 5;  // Profit target in percentage

//Stop/Profit Target Logic
for( i = 0; i < BarCount; i++ )
{ 
  if( priceatbuy == 0 AND Buy[ i ] )
    {
		priceatbuy = BuyPrice[ i ];
    }
  if( priceatbuy > 0 )
	{
		highsincebuy = Max( High[ i ], highsincebuy );
		ptarray[i] = (1 + profitTarget * 0.01) * priceatbuy;
		
		if( High[ i ] >= ( 1 + profitTarget * 0.01 ) * priceatbuy )
		{
			Sell[i] = 1;
			SellPrice[i] = Max(Open[i], ( 1 + profitTarget * 0.01 ) * priceatbuy);
			trailstop = 0;
			priceatbuy = 0;
			highsincebuy = 0;
		}
		if( trailstop == 0 AND Buy[ i ] ) 
		{ 
			trailstop = BuyPrice[i] * (1- stopLoss/100);
		}	
			else Buy[i] = 0; // remove excess buy signals - having this here also ensures max stop loss can be hit, was avoiding entries otherwise.
			if( trailstop > 0 AND Low[ i ] < trailstop AND Buy[i] != True)  // adding Buy check ensures you don't stop out on the breakout candle when the stop is within it
		{   
			Sell[ i ] = 1; 
			SellPrice[ i ] = Min( Open[ i ], trailstop );
			trailstop = 0;
			priceatbuy = 0;
			highsincebuy = 0;
		}
	   
	    if( trailstop > 0 )
	    {
			//trailStop = Max(DonchianLower[i], trailStop); // Unide to turn on trailing stop option
			trailARRAY[ i ] = trailstop;
	    }
	}
}

Plot(trailArray, "Trailing Stop Level", colorRed, styleThick);
Plot(ptarray, "profit target", colorLightBlue);

// Plot arrows indicating trades
PlotShapes(IIf(Buy, shapeUpTriangle, shapeNone),color = colorLime, 0, L, Offset=-50);
PlotShapes(IIf(Sell, shapeDownTriangle, shapeNone),color = colorRed, 0, H, Offset=-50);

// ==========================================================================================
// === EXPLORATION / SCANNING COLUMNS ===
// ==========================================================================================
Filter = 1;
AddTextColumn(FullName(), "Name");
AddColumn(Buy, "Buy Array");


Your Code is fine. Need only proper arrangement.
Below is the required code

// ==========================================================================================
// === TRADING SYSTEM PARAMETERS ===
// ==========================================================================================
SetBarsRequired(sbrAll, 0);
SetOption("InitialEquity", 100000);
SetTradeDelays( 0, 0, 0, 0 ); // 1 - Delays the trades to the next day, 0 - Trades same day via stops
SetOption("AllowPositionShrinking", True);
SetOption("AccountMargin",100); // 100 = Cash account, 75 = Using half available margin
SetOption("MaxOpenPositions", 20);
RoundLotSize = 1;  // Disallow fractional share purchasing


// ==========================================================================================
// === RISK MANAGEMENT & POSITION SIZING ===
// ==========================================================================================
// Initial (MAX) stop loss
SetOption("ActivateStopsImmediately", False);
stopLoss = 5; // Change this to a small number to experience the issue with trade entries being ignored
ApplyStop(stopTypeLoss, stopModePercent, stopLoss, ExitAtStop = 1);

// Position size based on risk and max stop loss
PositionRisk = 1;  
PosSize = 100 * PositionRisk / stopLoss;
SetPositionSize(PosSize, spsPercentOfEquity);
         

// ==========================================================================================
// === PLOT CHART & INDICATORS ===
// ==========================================================================================
// Chart
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - " + FullName() + " | {{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() ); 

// Donchian Channel
pdsU=3;  // High channel lookback
pdsL=5;  // Low channel lookback

DonchianUpper =HHV(H,pdsU);
DonchianLower = LLV(L,pdsL);

Plot(DonchianUpper,"DU",color = colorBlueGrey,styleDashed);
//Plot(DonchianLower,"DL",color = colorBlueGrey, styleDashed);
  
// ==========================================================================================
// === BUY & SELL LOGIC ===
// ==========================================================================================
Buy=Cross(High, Ref(DonchianUpper, -1)); 
BuyPrice=Max(Ref(DonchianUpper, -1), Open);

// == EXIT CONDITIONS ===
// Initialize variables
Sell=0;
trailArray = Null;
trailStop = 0;
ptArray = Null;
priceatbuy = 0;
highsincebuy = 0;

//profitTarget = Optimize("PT", 10, 5, 15, 1);  // Unhide to Optimize - looks like the higher the better...so might as well not use a PT
profitTarget = 5;  // Profit target in percentage

//Stop/Profit Target Logic
for( i = 0; i < BarCount; i++ )
{ 
  if( priceatbuy == 0 AND Buy[ i ] )
    {
		priceatbuy = BuyPrice[ i ];
    }
    else Buy[i] = 0; // remove excess buy signals - having this here also ensures max stop loss can be hit, was avoiding entries otherwise.
		
  if( priceatbuy > 0 )
	{
		highsincebuy = Max( High[ i ], highsincebuy );
		ptarray[i] = (1 + profitTarget * 0.01) * priceatbuy;
		
			 if( trailstop == 0 AND Buy[ i ] ) 
		{ 
			trailstop = BuyPrice[i] * (1- stopLoss/100);
		}	
		
		    if( trailstop > 0 )
	    {
			//trailStop = Max(DonchianLower[i], trailStop); // Unide to turn on trailing stop option
			trailARRAY[ i ] = trailstop;
	    }
		
		if( High[ i ] >= ( 1 + profitTarget * 0.01 ) * priceatbuy )
		{
			Sell[i] = 1;
			SellPrice[i] = Max(Open[i], ( 1 + profitTarget * 0.01 ) * priceatbuy);
			trailstop = 0;
			priceatbuy = 0;
			highsincebuy = 0;
		}

		else	if( trailstop > 0 AND Low[ i ] < trailstop AND Buy[i] != True)  // adding Buy check ensures you don't stop out on the breakout candle when the stop is within it
		{   
			Sell[ i ] = 1; 
			SellPrice[ i ] = Min( Open[ i ], trailstop );
			trailstop = 0;
			priceatbuy = 0;
			highsincebuy = 0;
		}
	   
	
	}
}

Plot(trailArray, "Trailing Stop Level", colorRed, styleThick);
Plot(ptarray, "profit target", colorLightBlue);

// Plot arrows indicating trades
PlotShapes(IIf(Buy, shapeUpTriangle, shapeNone),color = colorLime, 0, L, Offset=-50);
PlotShapes(IIf(Sell, shapeDownTriangle, shapeNone),color = colorRed, 0, H, Offset=-50);

// ==========================================================================================
// === EXPLORATION / SCANNING COLUMNS ===
// ==========================================================================================
Filter = 1;
AddTextColumn(FullName(), "Name");
AddColumn(Buy, "Buy Array");
1 Like

On quick examination, this seems to have done it except one odd thing. I see the backtester arrow plotted in the same old location, however, there is no green triangle (that my code shows when a buy happens). And later on, there is a green triangle, but no backtester arrow. Looking at the trade log, the entries align with the green triangle (as expected). Do you know why the backtester arrows wouldn't match up?

This is just the recent price action on $NUE if you want to look at it.

arrorw

I'll examine the diff between your rearrangement and my earlier one to see if I can spot what was going on. I appreciate you posting that.

I came back this evening after the Norgate update and re-ran it and now I'm not seeing the arrow issue any longer. so perhaps this was some odd random data behavior. Thanks for your help, I think this can be closed.

Arrows acting as expected:
arrownew

1 Like

Hi @Yogyatrader I am curious if you could look over this adaptation of this code for doing partial profit taking. I added a variable (exit) for storing the condition of a freshly opened position vs. one that has taken a partial. I also rearranged some of the variable resets so they don't go back to 0 until the trailing stop is hit.

Does this look right to you?

// ==========================================================================================
// === TRADING SYSTEM PARAMETERS ===
// ==========================================================================================
SetOption("InitialEquity", 100000);
SetTradeDelays( 0, 0, 0, 0 ); // 1 - Delays the trades to the next day, 0 - Trades same day via stops
SetOption("AllowPositionShrinking", True);
SetOption("AccountMargin",100); // 100 = Cash account, 75 = Using half available margin
SetOption("MaxOpenPositions", 20);
RoundLotSize = 1;  // Disallow fractional share purchasing


// ==========================================================================================
// === RISK MANAGEMENT & POSITION SIZING ===
// ==========================================================================================
// Initial (MAX) stop loss
SetOption("ActivateStopsImmediately", False);
stopLoss = 5; // Change this to a small number to experience the issue with trade entries being ignored
ApplyStop(stopTypeLoss, stopModePercent, stopLoss, ExitAtStop = 1);

// Position size based on risk and max stop loss
PositionRisk = 1;  
PosSize = 100 * PositionRisk / stopLoss;
SetPositionSize(PosSize, spsPercentOfEquity);
         

// ==========================================================================================
// === PLOT CHART & INDICATORS ===
// ==========================================================================================
// Chart
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - " + FullName() + " | {{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() ); 

// Donchian Channel
pdsU=4;  // High channel lookback
pdsL=5;  // Low channel lookback

DonchianUpper =HHV(H,pdsU);
DonchianLower = LLV(L,pdsL);

Plot(DonchianUpper,"DU",color = colorBlueGrey,styleDashed);
//Plot(DonchianLower,"DL",color = colorBlueGrey, styleDashed);
  
// ==========================================================================================
// === BUY & SELL LOGIC ===
// ==========================================================================================
Buy=Cross(High, Ref(DonchianUpper, -1)); 
BuyPrice=Max(Ref(DonchianUpper, -1), Open);

// == EXIT CONDITIONS ===
// Initialize variables
Sell=0;
trailArray = Null;
trailStop = 0;
ptArray = Null;
priceatbuy = 0;
highsincebuy = 0;
exit = 0;

//profitTarget = Optimize("PT", 10, 5, 15, 1);  // Unhide to Optimize - looks like the higher the better...so might as well not use a PT
profitTarget = 20;  // Profit target in percentage

//Stop/Profit Target Logic for full take profit
//for( i = 0; i < BarCount; i++ )
//{ 
//  if( priceatbuy == 0 AND Buy[ i ] )
//    {
//		priceatbuy = BuyPrice[ i ];
//    }
//    else Buy[i] = 0; // remove excess buy signals
		
//  if( priceatbuy > 0 )
//	{
//		highsincebuy = Max( High[ i ], highsincebuy );
//		ptarray[i] = (1 + profitTarget * 0.01) * priceatbuy;
		
//		if( trailstop == 0 AND Buy[ i ] ) 
//		{ 
//			trailstop = BuyPrice[i] * (1- stopLoss/100);
//		}	
		
//		if( trailstop > 0 )
//	    {
			//trailStop = Max(DonchianLower[i], trailStop); // Unide to turn on trailing stop option
//			trailARRAY[ i ] = trailstop;
//	    }
		
//		if( High[ i ] >= ( 1 + profitTarget * 0.01 ) * priceatbuy )
//		{
//			Sell[i] = 1;
//			SellPrice[i] = Max(Open[i], ( 1 + profitTarget * 0.01 ) * priceatbuy);
//			trailstop = 0;
//			priceatbuy = 0;
//			highsincebuy = 0;
//		}

//		else if( trailstop > 0 AND Low[ i ] < trailstop AND (Buy[i] != True OR (Buy[i] == True AND Close[i] < Open[i])))  // adding Buy check ensures you don't stop out on the breakout candle when the stop is within it
//		{   
//			Sell[ i ] = 1; 
//			SellPrice[ i ] = Min( Open[ i ], trailstop );
//			trailstop = 0;
//			priceatbuy = 0;
//			highsincebuy = 0;
//		}
//	}
//}

// New partial profit target and trailing stop logic
for( i = 0; i < BarCount; i++ )
{ 
  if( priceatbuy == 0 AND Buy[ i ] )
    {
		priceatbuy = BuyPrice[ i ];
    }
	else Buy[i] = 0; // remove excess buy signals
  
  if( priceatbuy > 0 )
	{
		highsincebuy = Max( High[ i ], highsincebuy );
		ptarray[i] = (1 + profitTarget * 0.01) * priceatbuy;
		
		if( trailstop == 0 AND Buy[ i ] ) 
		{ 
			trailstop = BuyPrice[i] * (1- stopLoss/100);
		}	
		
		if( trailstop > 0 )
	    {
			trailStop = Max(DonchianLower[i], trailStop); // Unide to turn on trailing stop option
			trailARRAY[ i ] = trailstop;
	    }
		
		if( exit == 0 AND (High[ i ] >= ( 1 + profitTarget * 0.01 ) * priceatbuy) )
		{
			Buy[ i ] = sigScaleOut;
			BuyPrice[i] = Max(Open[i], ( 1 + profitTarget * 0.01 ) * priceatbuy);
			exit = 1;
		}
		
		else if( trailstop > 0 AND Low[ i ] < trailstop AND (Buy[i] != True OR (Buy[i] == True AND Close[i] < Open[i])))  // adding Buy check ensures you don't stop out on the breakout candle when the stop is within it
		{   
			exit = 0;
			Sell[ i ] = 1; 
			SellPrice[ i ] = Min( Open[ i ], trailstop );
			trailstop = 0;
			priceatbuy = 0;
			highsincebuy = 0;
		}
	}
}

pctTP = 50;
SetPositionSize( pctTP, spsPercentOfPosition * ( Buy == sigScaleOut ) ); // scale out 50% of position

Plot(trailArray, "Trailing Stop Level", colorRed, styleThick);
Plot(ptarray, "profit target", colorLightBlue);

// Plot arrows indicating trades
PlotShapes(IIf(Buy, shapeUpTriangle, shapeNone),color = colorLime, 0, L, Offset=-50);
PlotShapes(IIf(Sell, shapeDownTriangle, shapeNone),color = colorRed, 0, H, Offset=-50);

// ==========================================================================================
// === EXPLORATION / SCANNING COLUMNS ===
// ==========================================================================================
Filter = 1;
AddTextColumn(FullName(), "Name");
AddColumn(Buy, "Buy Array");


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