Exit on friday - Backtest stops after first friday - futures io
futures io futures trading



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 1,883 views
    2. thumb_up 10 thanks given
    3. group 3 followers
    1. forum 10 posts
    2. attach_file 1 attachments




Welcome to futures io: the largest futures trading community on the planet, with well over 125,000 members
  • Genuine reviews from real traders, not fake reviews from stealth vendors
  • Quality education from leading professional traders
  • We are a friendly, helpful, and positive community
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts
  • We are here to help, just let us know what you need
You'll need to register in order to view the content of the threads and start contributing to our community.  It's free and simple.

-- Big Mike, Site Administrator

(If you already have an account, login at the top of the page)

 
Search this Thread
 

Exit on friday - Backtest stops after first friday

(login for full post details)
  #1 (permalink)
Zurich, Switzerland
 
Experience: Beginner
Platform: NinjaTrader
Broker: iqfeed
Trading: Stocks, Forex
 
cago's Avatar
 
Posts: 8 since Oct 2011
Thanks: 25 given, 41 received

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

Journal Challenge February 2021 results (so far):
Competing for $1500 in prizes from Topstep
looks_oneSBtrader82 's Trading Journalby SBtrader82
(169 thanks from 31 posts)
looks_twoJust BEING a Trader: Letting Go!!by iqgod
(116 thanks from 33 posts)
looks_3Wisdom is Emptinessby Mtype
(68 thanks from 25 posts)
looks_4Deetee’s DAX Trading Journal (time based)by Deetee
(31 thanks from 17 posts)
looks_5Journal for peanuts1956by peanuts1956
(23 thanks from 13 posts)
 
 
(login for full post details)
  #3 (permalink)
Wrocław, Poland
 
Experience: Intermediate
Platform: NinjaTrader, Racket
Trading: Ockham's razor
 
gregid's Avatar
 
Posts: 651 since Aug 2009
Thanks: 320 given, 620 received


@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
The following user says Thank You to gregid for this post:
 
(login for full post details)
  #4 (permalink)
Gits (Hooglede) Belgium
 
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
 
rleplae's Avatar
 
Posts: 2,991 since Sep 2013
Thanks: 2,437 given, 5,801 received

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 futures io Trade Journal Reply With Quote
The following user says Thank You to rleplae for this post:
 
(login for full post details)
  #5 (permalink)
Zurich, Switzerland
 
Experience: Beginner
Platform: NinjaTrader
Broker: iqfeed
Trading: Stocks, Forex
 
cago's Avatar
 
Posts: 8 since Oct 2011
Thanks: 25 given, 41 received

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
 
(login for full post details)
  #6 (permalink)
Gits (Hooglede) Belgium
 
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
 
rleplae's Avatar
 
Posts: 2,991 since Sep 2013
Thanks: 2,437 given, 5,801 received


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 futures io Trade Journal Reply With Quote
The following 2 users say Thank You to rleplae for this post:
 
(login for full post details)
  #7 (permalink)
Wrocław, Poland
 
Experience: Intermediate
Platform: NinjaTrader, Racket
Trading: Ockham's razor
 
gregid's Avatar
 
Posts: 651 since Aug 2009
Thanks: 320 given, 620 received


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
The following 2 users say Thank You to gregid for this post:
 
(login for full post details)
  #8 (permalink)
Zurich, Switzerland
 
Experience: Beginner
Platform: NinjaTrader
Broker: iqfeed
Trading: Stocks, Forex
 
cago's Avatar
 
Posts: 8 since Oct 2011
Thanks: 25 given, 41 received

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
 
(login for full post details)
  #9 (permalink)
Wrocław, Poland
 
Experience: Intermediate
Platform: NinjaTrader, Racket
Trading: Ockham's razor
 
gregid's Avatar
 
Posts: 651 since Aug 2009
Thanks: 320 given, 620 received


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
The following user says Thank You to gregid for this post:
 
(login for full post details)
  #10 (permalink)
Wrocław, Poland
 
Experience: Intermediate
Platform: NinjaTrader, Racket
Trading: Ockham's razor
 
gregid's Avatar
 
Posts: 651 since Aug 2009
Thanks: 320 given, 620 received


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
The following 2 users say Thank You to gregid for this post:
 
(login for full post details)
  #11 (permalink)
Zurich, Switzerland
 
Experience: Beginner
Platform: NinjaTrader
Broker: iqfeed
Trading: Stocks, Forex
 
cago's Avatar
 
Posts: 8 since Oct 2011
Thanks: 25 given, 41 received

OK guys, thank you so much aganin for your help!
It exits now on friday. But that function is triggered very rarely. So it doesn't really have an influence on the result.

Nevertheless, I attached this code for backtesting entries on their "percent profitable". For those who wanna use it.

-> For Forex, turn "exit on close" off and "exit on friday" on.
-> The entry rule is of course just an example.
-> "Bars since Entry" is there for the exit since we just wanna compare how good the entry rule is. If you have a similar result on several values (like exit after 2, 4 and 6 bars) thats a good sign.

Attached Files
Register to download File Type: cs EntryTest 3.cs (5.3 KB, 4 views)
Started this thread Reply With Quote
The following user says Thank You to cago for this post:


futures io Trading Community Platforms and Indicators NinjaTrader > Exit on friday - Backtest stops after first friday


Last Updated on May 2, 2015


Upcoming Webinars and Events
 

NinjaTrader Indicator Challenge!

Ongoing
 

Journal Challenge w/$1500 prizes from Topstep!

February
 

Battlestations! Show us your trading desk - $1,500 in prizes!

March
 

Call Option Buying: The New Pain Trade? w/Carley Garner

Elite only
     



Copyright © 2021 by futures io, s.a., Av Ricardo J. Alfaro, Century Tower, Panama, +507 833-9432, info@futures.io
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.
no new posts