NexusFi: Find Your Edge


Home Menu

 





Exit on friday - Backtest stops after first friday


Discussion in NinjaTrader

Updated
      Top Posters
    1. looks_one gregid with 4 posts (6 thanks)
    2. looks_two cago with 4 posts (1 thanks)
    3. looks_3 rleplae with 2 posts (3 thanks)
    4. looks_4 Quick Summary with 1 posts (0 thanks)
    1. trending_up 3,307 views
    2. thumb_up 10 thanks given
    3. group 3 followers
    1. forum 10 posts
    2. attach_file 1 attachments




 
Search this Thread

Exit on friday - Backtest stops after first friday

  #1 (permalink)
 
cago's Avatar
 cago 
Zurich, Switzerland
 
Experience: Beginner
Platform: NinjaTrader
Broker: iqfeed
Trading: Stocks, Forex
Posts: 8 since Oct 2011
Thanks Given: 25
Thanks Received: 41

Hi

I have the code attachet below which is supposed to exit on friday. In backtest unfortunately it does exit on the first friday, but then there are no more trades in the following weeks. If I turn off the first part of the code (with /**/), of course it does not exit on friday anymore, but it keeps trading/backtesting.
Can it be, that "backtesting" doesnt work with some of the time-propertys?
Thanks a lot
cago

1. Part
protected override void OnBarUpdate()
{

DateTime dayFromLocal = Bars.GetTradingDayFromLocal(Time[0]);

if (currentDate != dayFromLocal )
{
currentDate = dayFromLocal;
if(currentDate.DayOfWeek == DayOfWeek.Friday)
{
DateTime cacheSessionBegin, cacheSessionEnd;
Bars.Session.GetNextBeginEnd(Time[0], out cacheSessionBegin, out cacheSessionEnd);
dtEntryCancel = cacheSessionEnd.AddMinutes(-60);
}
}


// Entryrule


2. Part (i can keep that active, has no influence)
if( Time[0] >= dtEntryCancel )
{
dtEntryCancel = Cbi.Globals.MaxDate;

{
// entries löschen
if (entryOrder.OrderState == OrderState.Working || entryOrder.OrderState == OrderState.Unknown || entryOrder.OrderState == OrderState.Rejected)
CancelOrder( entryOrder );

// Position schliessen
if( exitOnFriday )
{
switch( Position.MarketPosition )
{
case MarketPosition.Long:
if( entryOrder.OrderState == OrderState.Filled || entryOrder.OrderState == OrderState.PartFilled )
ExitLong(10, "fridayexitlong", "enterlong");
break;
case MarketPosition.Short:
if( entryOrder.OrderState == OrderState.Filled || entryOrder.OrderState == OrderState.PartFilled )
ExitShort(10, "fridayexitshort", "entershort");
break;

}
}
}
}


and those are the variables:
private DateTime currentDate = Cbi.Globals.MinDate;
private DateTime dtEntryCancel = Cbi.Globals.MaxDate;
private bool exitOnFriday = false;

Started this thread Reply With Quote

Can you help answer these questions
from other members on NexusFi?
ZombieSqueeze
Platforms and Indicators
The space time continuum and the dynamics of a financial …
Emini and Emicro Index
My NT8 Volume Profile Split by Asian/Euro/Open
NinjaTrader
Exit Strategy
NinjaTrader
Deepmoney LLM
Elite Quantitative GenAI/LLM
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Get funded firms 2023/2024 - Any recommendations or word …
61 thanks
Funded Trader platforms
38 thanks
NexusFi site changelog and issues/problem reporting
26 thanks
GFIs1 1 DAX trade per day journal
19 thanks
The Program
18 thanks
  #3 (permalink)
 
gregid's Avatar
 gregid 
Wrocław, Poland
 
Experience: Intermediate
Platform: NinjaTrader, Racket
Trading: Ockham's razor
Posts: 650 since Aug 2009
Thanks Given: 320
Thanks Received: 623


@cago,
You didn't provide your entry rules - so it is hard to advise you anything as the part in question is missing.
If you could attach stripped down version of your strategy with some dummy rule like: MA crossover this would be the most helpful

Reply With Quote
Thanked by:
  #4 (permalink)
 
rleplae's Avatar
 rleplae 
Gits (Hooglede) Belgium
Legendary Market Wizard
 
Experience: Master
Platform: NinjaTrader, Proprietary,
Broker: Ninjabrokerage/IQfeed + Synthetic datafeed
Trading: 6A, 6B, 6C, 6E, 6J, 6S, ES, NQ, YM, AEX, CL, NG, ZB, ZN, ZC, ZS, GC
Posts: 3,003 since Sep 2013
Thanks Given: 2,442
Thanks Received: 5,863

Are you using replay mode ?

I would add some print's in the code and then open the output window
then you can actually print the values and understand and try to debug ...

Follow me on Twitter Visit my NexusFi Trade Journal Reply With Quote
Thanked by:
  #5 (permalink)
 
cago's Avatar
 cago 
Zurich, Switzerland
 
Experience: Beginner
Platform: NinjaTrader
Broker: iqfeed
Trading: Stocks, Forex
Posts: 8 since Oct 2011
Thanks Given: 25
Thanks Received: 41

hi gregid, thanks for your reply!

I didn't wanna hide the entryrules :-) I just thought that they don't matter, but here the whole code:
 
Code
public class EntryTest2015 : Strategy
    {
		
        #region Variables      
        private int barsago 			= 5; 
		int adxperiod 					= 20;
		int adxtoplevel 				= 35;
		int adxlowlevel 				= 20;
		int smaLongPeriod 				= 21;
		int smaShortPeriod 				= 7;
		private DateTime currentDate 	= Cbi.Globals.MinDate;	
		private DateTime dtEntryCancel 	= Cbi.Globals.MaxDate;
		private bool exitOnFriday 		= false;
		private IOrder entryOrder		= null;
		private IOrder stopOrder		= null;
		#endregion

   		#region INitialize
        protected override void Initialize()
        {

            CalculateOnBarClose = true;
			ExitOnClose 		= false;	
			TraceOrders      	= true;
        }
		#endregion

       	#region ONBarUpdate
        protected override void OnBarUpdate()
        {
			
			DateTime dayFromLocal = Bars.GetTradingDayFromLocal(Time[0]);
				
				if (currentDate != dayFromLocal )
					{
						currentDate = dayFromLocal;
						if(currentDate.DayOfWeek == DayOfWeek.Friday)
							{
								DateTime cacheSessionBegin, cacheSessionEnd;
								Bars.Session.GetNextBeginEnd(Time[0], out cacheSessionBegin, out cacheSessionEnd);
								dtEntryCancel =  cacheSessionEnd.AddMinutes(-60);
							}
					}	
			
			
            // Entrirule:    
						
				if (entryOrder == null && Position.MarketPosition == MarketPosition.Flat && (ADX (adxperiod)[0] > adxtoplevel))
				{
					if (CrossAbove (SMA(smaShortPeriod), SMA(smaLongPeriod), 1))
					{
                		entryOrder = EnterLong(10, "enterlong");
					}
				}
						
				else 
				{
					if (entryOrder == null && Position.MarketPosition == MarketPosition.Flat &&(ADX(adxperiod)[0] < adxlowlevel) )
					{
						if (CrossBelow (SMA(smaShortPeriod), SMA(smaLongPeriod), 1))
						{
                			entryOrder = EnterShort(10, "entershort");
						}
					}
				}
				
					
					
			// Exitrule:
					
				if (BarsSinceEntry() == barsago)
					{
						ExitLong(10, "exitlong", "enterlong");
						ExitShort(10, "exitshort", "entershort");
						entryOrder = null;
					}
					
												

           		
			//2. part of exitonfriday
				if( Time[0] >= dtEntryCancel ) 								
					{
						dtEntryCancel = Cbi.Globals.MaxDate;					
					
						{
							// delete entries
							if (entryOrder.OrderState == OrderState.Working || entryOrder.OrderState == OrderState.Unknown || entryOrder.OrderState == OrderState.Rejected)
								CancelOrder( entryOrder );
						
							// close positions
							if( exitOnFriday )
							{
								switch( Position.MarketPosition )
								{
									case MarketPosition.Long:
										if( entryOrder.OrderState == OrderState.Filled || entryOrder.OrderState == OrderState.PartFilled )
											ExitLong(10, "fridayexitlong", "enterlong");
										break;
									case MarketPosition.Short:
										if( entryOrder.OrderState == OrderState.Filled || entryOrder.OrderState == OrderState.PartFilled )
											ExitShort(10, "fridayexitshort", "entershort");
										break;
									
								}
							}
						}
					}
        				
		
		
		}
		
		#endregion							
		
				
        #region Properties
        [Description("")]
        [GridCategory("Parameters")]
        public int Barsago_for_Exit
        {
            get { return barsago; }
            set { barsago = Math.Max(1, value); }
        }
		
		[Description("")]
        [GridCategory("Parameters")]
		public int ADXPeriod
        {
            get { return adxperiod; }
            set { adxperiod = Math.Max(1, value); }
        }
		[Description("")]
        [GridCategory("Parameters")]
		public int ADXToplevel
        {
            get { return adxtoplevel; }
            set { adxtoplevel = Math.Max(1, value); }
        }
		[Description("")]
        [GridCategory("Parameters")]
		public int Adxlowlevel
        {
            get { return adxlowlevel; }
            set { adxlowlevel = Math.Max(1, value); }
        }
		[Description("")]
        [GridCategory("Parameters")]
		public int SmaLongPeriod
        {
            get { return smaLongPeriod; }
            set { smaLongPeriod = Math.Max(1, value); }
        }
		[Description("")]
        [GridCategory("Parameters")]
		public int SmaShortPeriod
        {
            get { return smaShortPeriod; }
            set { smaShortPeriod = Math.Max(1, value); }
        }
		
		[Description("Exit on Friday ein/aus")]
		[Category("Order Handling")]
		[Gui.Design.DisplayNameAttribute("Exit on Friday")]
		public bool ExitOnFriday 
		{
			get { return exitOnFriday; }
			set { exitOnFriday = value; }
		}
		
        #endregion
		
    }
}

I basically just want a strategy to test different entrys on theyr "percent profitable" result. But, because I want to backtest currencies and not stocks, I can't use "exitonclose", but I d'like to have the exit on friday.


@rleplae: Thanks for your advice! I will do that tomorrow! the output window I have already used, I'm also using "traceorders" to have more info about whats going on.

Started this thread Reply With Quote
  #6 (permalink)
 
rleplae's Avatar
 rleplae 
Gits (Hooglede) Belgium
Legendary Market Wizard
 
Experience: Master
Platform: NinjaTrader, Proprietary,
Broker: Ninjabrokerage/IQfeed + Synthetic datafeed
Trading: 6A, 6B, 6C, 6E, 6J, 6S, ES, NQ, YM, AEX, CL, NG, ZB, ZN, ZC, ZS, GC
Posts: 3,003 since Sep 2013
Thanks Given: 2,442
Thanks Received: 5,863


cago View Post
hi gregid, thanks for your reply!

I didn't wanna hide the entryrules :-) I just thought that they don't matter, but here the whole code:
 
Code
public class EntryTest2015 : Strategy
    {
		
        #region Variables      
        private int barsago 			= 5; 
		int adxperiod 					= 20;
		int adxtoplevel 				= 35;
		int adxlowlevel 				= 20;
		int smaLongPeriod 				= 21;
		int smaShortPeriod 				= 7;
		private DateTime currentDate 	= Cbi.Globals.MinDate;	
		private DateTime dtEntryCancel 	= Cbi.Globals.MaxDate;
		private bool exitOnFriday 		= false;
		private IOrder entryOrder		= null;
		private IOrder stopOrder		= null;
		#endregion

   		#region INitialize
        protected override void Initialize()
        {

            CalculateOnBarClose = true;
			ExitOnClose 		= false;	
			TraceOrders      	= true;
        }
		#endregion

       	#region ONBarUpdate
        protected override void OnBarUpdate()
        {
			
			DateTime dayFromLocal = Bars.GetTradingDayFromLocal(Time[0]);
				
				if (currentDate != dayFromLocal )
					{
						currentDate = dayFromLocal;
						if(currentDate.DayOfWeek == DayOfWeek.Friday)
							{
								DateTime cacheSessionBegin, cacheSessionEnd;
								Bars.Session.GetNextBeginEnd(Time[0], out cacheSessionBegin, out cacheSessionEnd);
								dtEntryCancel =  cacheSessionEnd.AddMinutes(-60);
							}
					}	
			
			
            // Entrirule:    
						
				if (entryOrder == null && Position.MarketPosition == MarketPosition.Flat && (ADX (adxperiod)[0] > adxtoplevel))
				{
					if (CrossAbove (SMA(smaShortPeriod), SMA(smaLongPeriod), 1))
					{
                		entryOrder = EnterLong(10, "enterlong");
					}
				}
						
				else 
				{
					if (entryOrder == null && Position.MarketPosition == MarketPosition.Flat &&(ADX(adxperiod)[0] < adxlowlevel) )
					{
						if (CrossBelow (SMA(smaShortPeriod), SMA(smaLongPeriod), 1))
						{
                			entryOrder = EnterShort(10, "entershort");
						}
					}
				}
				
					
					
			// Exitrule:
					
				if (BarsSinceEntry() == barsago)
					{
						ExitLong(10, "exitlong", "enterlong");
						ExitShort(10, "exitshort", "entershort");
						entryOrder = null;
					}
					
												

           		
			//2. part of exitonfriday
				if( Time[0] >= dtEntryCancel ) 								
					{
						dtEntryCancel = Cbi.Globals.MaxDate;					
					
						{
							// delete entries
							if (entryOrder.OrderState == OrderState.Working || entryOrder.OrderState == OrderState.Unknown || entryOrder.OrderState == OrderState.Rejected)
								CancelOrder( entryOrder );
						
							// close positions
							if( exitOnFriday )
							{
								switch( Position.MarketPosition )
								{
									case MarketPosition.Long:
										if( entryOrder.OrderState == OrderState.Filled || entryOrder.OrderState == OrderState.PartFilled )
											ExitLong(10, "fridayexitlong", "enterlong");
										break;
									case MarketPosition.Short:
										if( entryOrder.OrderState == OrderState.Filled || entryOrder.OrderState == OrderState.PartFilled )
											ExitShort(10, "fridayexitshort", "entershort");
										break;
									
								}
							}
						}
					}
        				
		
		
		}
		
		#endregion							
		
				
        #region Properties
        [Description("")]
        [GridCategory("Parameters")]
        public int Barsago_for_Exit
        {
            get { return barsago; }
            set { barsago = Math.Max(1, value); }
        }
		
		[Description("")]
        [GridCategory("Parameters")]
		public int ADXPeriod
        {
            get { return adxperiod; }
            set { adxperiod = Math.Max(1, value); }
        }
		[Description("")]
        [GridCategory("Parameters")]
		public int ADXToplevel
        {
            get { return adxtoplevel; }
            set { adxtoplevel = Math.Max(1, value); }
        }
		[Description("")]
        [GridCategory("Parameters")]
		public int Adxlowlevel
        {
            get { return adxlowlevel; }
            set { adxlowlevel = Math.Max(1, value); }
        }
		[Description("")]
        [GridCategory("Parameters")]
		public int SmaLongPeriod
        {
            get { return smaLongPeriod; }
            set { smaLongPeriod = Math.Max(1, value); }
        }
		[Description("")]
        [GridCategory("Parameters")]
		public int SmaShortPeriod
        {
            get { return smaShortPeriod; }
            set { smaShortPeriod = Math.Max(1, value); }
        }
		
		[Description("Exit on Friday ein/aus")]
		[Category("Order Handling")]
		[Gui.Design.DisplayNameAttribute("Exit on Friday")]
		public bool ExitOnFriday 
		{
			get { return exitOnFriday; }
			set { exitOnFriday = value; }
		}
		
        #endregion
		
    }
}

I basically just want a strategy to test different entrys on theyr "percent profitable" result. But, because I want to backtest currencies and not stocks, I can't use "exitonclose", but I d'like to have the exit on friday.


@rleplae: Thanks for your advice! I will do that tomorrow! the output window I have already used, I'm also using "traceorders" to have more info about whats going on.


I think your entryOrder is not put to null in the Friday part of your code
that is why it does not take new trades
would that be possible ?

Follow me on Twitter Visit my NexusFi Trade Journal Reply With Quote
Thanked by:
  #7 (permalink)
 
gregid's Avatar
 gregid 
Wrocław, Poland
 
Experience: Intermediate
Platform: NinjaTrader, Racket
Trading: Ockham's razor
Posts: 650 since Aug 2009
Thanks Given: 320
Thanks Received: 623


rleplae View Post
I think your entryOrder is not put to null in the Friday part of your code
that is why it does not take new trades
would that be possible ?

I concur with this assessment

Reply With Quote
Thanked by:
  #8 (permalink)
 
cago's Avatar
 cago 
Zurich, Switzerland
 
Experience: Beginner
Platform: NinjaTrader
Broker: iqfeed
Trading: Stocks, Forex
Posts: 8 since Oct 2011
Thanks Given: 25
Thanks Received: 41

Hi guys, thank you so much for your help.

Unfortunately that didn't help, I placed the entryOrder = null on three positions.

 
Code
// delete entries
if (entryOrder.OrderState == OrderState.Working || entryOrder.OrderState == OrderState.Unknown || entryOrder.OrderState == OrderState.Rejected)
CancelOrder( entryOrder );
entryOrder = null;
						
// close positions
if( exitOnFriday )
{
switch( Position.MarketPosition )
    {
	case MarketPosition.Long:
if( entryOrder.OrderState == OrderState.Filled || entryOrder.OrderState == OrderState.PartFilled )
ExitLong(10, "fridayexitlong", "enterlong");
entryOrder = null;
break;
case MarketPosition.Short:
if( entryOrder.OrderState == OrderState.Filled || entryOrder.OrderState == OrderState.PartFilled )
ExitShort(10, "fridayexitshort", "entershort");
entryOrder = null;
break;
The output window has it's last entry on the first friday and says:
**NT** Error on calling 'OnBarUpdate' method for strategy 'EntryTest2015/f810438ca706453ebbe8e0757e71a03d': Object reference not set to an object instance.

Started this thread Reply With Quote
  #9 (permalink)
 
gregid's Avatar
 gregid 
Wrocław, Poland
 
Experience: Intermediate
Platform: NinjaTrader, Racket
Trading: Ockham's razor
Posts: 650 since Aug 2009
Thanks Given: 320
Thanks Received: 623


cago View Post
The output window has it's last entry on the first friday and says:
**NT** Error on calling 'OnBarUpdate' method for strategy 'EntryTest2015/f810438ca706453ebbe8e0757e71a03d': Object reference not set to an object instance.

Since you have now set entryOrder to null in the right places, you need to ensure that every time you check for for entryOrder, eg. here:
 
Code
if( entryOrder.OrderState == OrderState.Filled || entryOrder.OrderState == OrderState.PartFilled )
You need to make sure you first ask if entryOrder != null, only then you can ask for the following conditions, eg.:
 
Code
if(entryOrder != null && (entryOrder.OrderState == OrderState.Filled || entryOrder.OrderState == OrderState.PartFilled ))
The error simply says that you are checking for a condition of the null object which is not possible (conditions are checked left to right so if the first one is true the following are ignored)

Reply With Quote
Thanked by:
  #10 (permalink)
 
gregid's Avatar
 gregid 
Wrocław, Poland
 
Experience: Intermediate
Platform: NinjaTrader, Racket
Trading: Ockham's razor
Posts: 650 since Aug 2009
Thanks Given: 320
Thanks Received: 623


To make it even simpler you can add the following before your "//2. part of exitonfriday"
 
Code
if (entryOrder == null) return;
//2. part of exitonfriday
This will ignore the remaining code if there is nothing to manage (ie: entryOrder is null)

Reply With Quote
Thanked by:




Last Updated on May 2, 2015


© 2024 NexusFi™, s.a., All Rights Reserved.
Av Ricardo J. Alfaro, Century Tower, Panama City, Panama, Ph: +507 833-9432 (Panama and Intl), +1 888-312-3001 (USA and Canada)
All information is for educational use only and is not investment advice. There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
About Us - Contact Us - Site Rules, Acceptable Use, and Terms and Conditions - Privacy Policy - Downloads - Top
no new posts