Exit on friday - Backtest stops after first friday - NinjaTrader Programming | futures io social day trading
futures io futures trading


Exit on friday - Backtest stops after first friday
Updated: Views / Replies:1,025 / 10
Created: by cago Attachments:1

Welcome to futures io.

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

futures io is the largest futures trading community on the planet, with over 90,000 members. At futures io, our goal has always been and always will be to create a friendly, positive, forward-thinking community where members can openly share and discuss everything the world of trading has to offer. The community is one of the friendliest you will find on any subject, with members going out of their way to help others. Some of the primary differences between futures io and other trading sites revolve around the standards of our community. Those standards include a code of conduct for our members, as well as extremely high standards that govern which partners we do business with, and which products or services we recommend to our members.

At futures io, our focus is on quality education. No hype, gimmicks, or secret sauce. The truth is: trading is hard. To succeed, you need to surround yourself with the right support system, educational content, and trading mentors – all of which you can find on futures io, utilizing our social trading environment.

With futures io, you can find honest trading reviews on brokers, trading rooms, indicator packages, trading strategies, and much more. Our trading review process is highly moderated to ensure that only genuine users are allowed, so you don’t need to worry about fake reviews.

We are fundamentally different than most other trading sites:
  • We are here to help. Just let us know what you need.
  • We work extremely hard to keep things positive in our community.
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts.
  • We firmly believe in and encourage sharing. The holy grail is within you, we can help you find it.
  • We expect our members to participate and become a part of the community. Help yourself by helping others.

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

Reply
 1  
 
Thread Tools Search this Thread
 

Exit on friday - Backtest stops after first friday

  #1 (permalink)
Elite Member
Zurich, Switzerland
 
Futures Experience: Beginner
Platform: NinjaTrader
Broker/Data: iqfeed
Favorite Futures: Stocks, Forex
 
cago's Avatar
 
Posts: 8 since Oct 2011
Thanks: 17 given, 38 received

Exit on friday - Backtest stops after first friday

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;


Last edited by cago; April 26th, 2015 at 10:28 AM.
Reply With Quote
 
  #2 (permalink)
Quick Summary
Quick Summary Post

Quick Summary is created and edited by users like you... Add FAQ's, Links and other Relevant Information by clicking the edit button in the lower right hand corner of this message.

 
  #3 (permalink)
Elite Member
Wrocław, Poland
 
Futures Experience: Intermediate
Platform: NinjaTrader, Racket
Favorite Futures: Ockham's razor
 
gregid's Avatar
 
Posts: 651 since Aug 2009
Thanks: 321 given, 605 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:
 
  #4 (permalink)
Elite Member
Omer עומר / Israel י
 
Futures Experience: Master
Platform: NinjaTrader, Proprietary,
Broker/Data: Ninjabrokerage/IQfeed + Synthetic datafeed
Favorite Futures: 6A, 6B, 6C, 6E, 6J, 6S, ES, NQ, YM, AEX, CL, NG, ZB, ZN, ZC, ZS, GC
 
rleplae's Avatar
 
Posts: 2,463 since Sep 2013
Thanks: 1,691 given, 3,656 received
Forum Reputation: Legendary

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 ...

Reply With Quote
The following user says Thank You to rleplae for this post:
 
  #5 (permalink)
Elite Member
Zurich, Switzerland
 
Futures Experience: Beginner
Platform: NinjaTrader
Broker/Data: iqfeed
Favorite Futures: Stocks, Forex
 
cago's Avatar
 
Posts: 8 since Oct 2011
Thanks: 17 given, 38 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.

Reply With Quote
 
  #6 (permalink)
Elite Member
Omer עומר / Israel י
 
Futures Experience: Master
Platform: NinjaTrader, Proprietary,
Broker/Data: Ninjabrokerage/IQfeed + Synthetic datafeed
Favorite Futures: 6A, 6B, 6C, 6E, 6J, 6S, ES, NQ, YM, AEX, CL, NG, ZB, ZN, ZC, ZS, GC
 
rleplae's Avatar
 
Posts: 2,463 since Sep 2013
Thanks: 1,691 given, 3,656 received
Forum Reputation: Legendary


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 ?

Reply With Quote
The following 2 users say Thank You to rleplae for this post:
 
  #7 (permalink)
Elite Member
Wrocław, Poland
 
Futures Experience: Intermediate
Platform: NinjaTrader, Racket
Favorite Futures: Ockham's razor
 
gregid's Avatar
 
Posts: 651 since Aug 2009
Thanks: 321 given, 605 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:
 
  #8 (permalink)
Elite Member
Zurich, Switzerland
 
Futures Experience: Beginner
Platform: NinjaTrader
Broker/Data: iqfeed
Favorite Futures: Stocks, Forex
 
cago's Avatar
 
Posts: 8 since Oct 2011
Thanks: 17 given, 38 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.

Reply With Quote
 
  #9 (permalink)
Elite Member
Wrocław, Poland
 
Futures Experience: Intermediate
Platform: NinjaTrader, Racket
Favorite Futures: Ockham's razor
 
gregid's Avatar
 
Posts: 651 since Aug 2009
Thanks: 321 given, 605 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)


Last edited by gregid; April 27th, 2015 at 07:10 PM.
Reply With Quote
The following user says Thank You to gregid for this post:
 
  #10 (permalink)
Elite Member
Wrocław, Poland
 
Futures Experience: Intermediate
Platform: NinjaTrader, Racket
Favorite Futures: Ockham's razor
 
gregid's Avatar
 
Posts: 651 since Aug 2009
Thanks: 321 given, 605 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:

Reply



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

Thread Tools Search this Thread
Search this Thread:

Advanced Search



Upcoming Webinars and Events (4:30PM ET unless noted)

Linda Bradford Raschke: Reading The Tape

Elite only

Adam Grimes: TBA

Elite only

NinjaTrader: TBA

January

Ran Aroussi: TBA

Elite only
     

Similar Threads
Thread Thread Starter Forum Replies Last Post
black Friday deal(s) cory Off-Topic 3 November 28th, 2013 12:48 PM
Friday Look Ahead: For Markets, It's All About Jobs Quick Summary News and Current Events 0 May 5th, 2011 05:40 PM
STATS - Friday before a three days weekend trendisyourfriend Emini Index Futures Trading 4 March 7th, 2011 10:45 AM


All times are GMT -4. The time now is 07:48 AM.

Copyright © 2017 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
Page generated 2017-12-11 in 0.15 seconds with 20 queries on phoenix via your IP 54.226.132.197