Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Strategy do not buy

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Strategy do not buy

    Hi,
    I have a problem with my own strategy. I'm learning ninjascript so if i make any mistakes please tell me, thanks.
    I wrote script, compiled with no errors, next step? Backtest! I was angry as ... Its not buying, just do nothink. I don't see any mistakes but its not working so i made one. I need help, you are my last chance.
    Thanks a lot!.
    Code:
    #region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Gui.SuperDom;
    using NinjaTrader.Gui.Tools;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;
    using NinjaTrader.NinjaScript.Indicators;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion
    
    //This namespace holds Strategies in this folder and is required. Do not change it. 
    namespace NinjaTrader.NinjaScript.Strategies
    {
    	public class pricebreaker : Strategy
    	{
    	 //	private Series<double> OpPrice = Bars.GetOpen(1);
    	//	private Series<double> ClPrice = Close[1];
    		private double Vol;
    		private double BarVolAvg;
    		
    		
    		protected override void OnStateChange()
    		{
    			
    			
    			if (State == State.SetDefaults)
    			{
    				Description									= @"v1.0 ALPHA";
    				Name										= "PriceBreaks";
    				Calculate									= Calculate.OnPriceChange;
    				EntriesPerDirection							= 1;
    				EntryHandling								= EntryHandling.AllEntries;
    				IsExitOnSessionCloseStrategy				= true;
    				ExitOnSessionCloseSeconds					= 30;
    				IsFillLimitOnTouch							= false;
    				MaximumBarsLookBack							= MaximumBarsLookBack.TwoHundredFiftySix;
    				OrderFillResolution							= OrderFillResolution.Standard;
    				Slippage									= 0;
    				StartBehavior								= StartBehavior.WaitUntilFlat;
    				TimeInForce									= TimeInForce.Gtc;
    				TraceOrders									= false;
    				RealtimeErrorHandling						= RealtimeErrorHandling.StopCancelClose;
    				StopTargetHandling							= StopTargetHandling.PerEntryExecution;
    				BarsRequiredToTrade							= 20;
    				// Disable this property for performance gains in Strategy Analyzer optimizations
    				// See the Help Guide for additional information
    				IsInstantiatedOnEachOptimizationIteration	= true;
    								
    			}
    			else if (State == State.Configure)
    			{
    				int Target		= 3;
    				SetProfitTarget("",CalculationMode.Ticks, Target);
    			}
    		}
    
    		protected override void OnBarUpdate()
    		{
    			if( BarsInProgress !=0 )
    					return;
    			if( CurrentBars[0] < 2 )
    				return;
    			
    			#region Variables
    			double OpPrice 		= Bars.GetOpen(1);
    			double ClPrice 		= Bars.GetClose(1);
    
    	
    			
    			#endregion
    				
    		// SET 1 //						LICZ VOL
    					
    			if (MarketPosition.Long == Position.MarketPosition)								//		long OR short; 
    			{
    				if(IsFirstTickOfBar) 																	// musi byc sprawdzenie czy to nowa swieczka
    			{
    				Vol 		= ClPrice - OpPrice;   													// 		licz Vol;
    				BarVolAvg	= (OpPrice + ClPrice) / 2;												// srodek swieczki;
    				if((Vol + BarVolAvg) < Open[0])
    				{
    						EnterLong(Convert.ToInt32(DefaultQuantity), "");
    				}
    				else
    				{
    					return;
    				}
    				
    			}
    
    
    							
    			}		
    			else
    			{
    				return;
    			}
    			
    				
    			
    		}
    	}
    }

    I found it, Position.MarketPosition == MarketPosition.Long is a wrong line, but why and how to fix?
    Attached Files
    Last edited by kamix265; 09-25-2018, 07:00 AM.

    #2
    Hello kamix265,

    Thank you for the post and welcome to the NinjaTrader support forum.

    In a situation where you have no errors but nothing happens, this would indicate that your logic or conditions are not happening as you expect. To find the reason, you would need to debug the script. You can use Prints as one way to do this.

    We have a guide for debugging here: https://ninjatrader.com/support/help...script_cod.htm

    As you noted you have found one problem, the Market Position will not be Long until you enter Long, so checking this before you enter would prevent it from happening. You would likely need to use "Flat" instead of "Long" here if you intended to go from a Flat position to a Long position.

    Also, I see you are using IsFirstTickOfBar which will work differently in a backtest than it will in real-time. Please review the following documentation surrounding common differences between historical and real-time trading, specifically the (at the Close of a Bar or Tick by Tick): https://ninjatrader.com/support/help...lightsub=discr


    I look forward to being of further assistance.
    JesseNinjaTrader Customer Service

    Comment


      #3
      Ok i fix it, now i have another problem.
      OpPrice and ClPrice is not refreshing every price change. They are having only one value for all time.
      I met that error in output: An order placed at '17.09.2018 08:22:06' has been ignored since the order was submitted before the strategy property BarsRequiredToTrade had been met.
      Is it important error or only information that i don't have enough bars?
      Thanks

      Comment


        #4
        Hello kamix265,

        Thank you for the reply.

        Yes looking back at what you provided, it looks like you are using the incorrect method to access data.

        You are using the way to access data that you would from OnRender, you instead need to use the Series.

        Instead of:
        Code:
        Bars.GetOpen(1);
        use
        Code:
        Open[1]
        assuming you wanted 1 BarsAgo.

        Here is a link to more information on the basic price series you have access to along with samples: https://ninjatrader.com/support/help...riceseries.htm


        BarsRequiredToTrade is the amount of bars required before the script can trade, this is configurable: https://ninjatrader.com/support/help...equiredToTrade

        The warning just lets you know your logic became true before the BarsRequireToTrade so the order was ignored.

        I look forward to being of further assistance.
        JesseNinjaTrader Customer Service

        Comment


          #5
          Is it possible to use Close[0] om CrossAbove?
          I was trying to use it to, but nt returned CS1502 and 1503 error code, thanks for help.

          Comment


            #6
            Hello kamix265,

            You would just use Close in most cases in the CrossAbove statement although you can use a double as well.

            You can see the various ways it can be used here: https://ninjatrader.com/support/help...sub=crossabove

            For example:

            Code:
            CrossAbove(EMA(10), Close, 1)
            or

            Code:
            CrossAbove(EMA(20), Close[0], 1)
            If you are trying to use two doubles, that would cause an error you need either two series or a series and a double.

            I look forward to being of further assistance.
            JesseNinjaTrader Customer Service

            Comment


              #7
              Code:
              #region Using declarations
              using System;
              using System.Collections.Generic;
              using System.ComponentModel;
              using System.ComponentModel.DataAnnotations;
              using System.Linq;
              using System.Text;
              using System.Threading.Tasks;
              using System.Windows;
              using System.Windows.Input;
              using System.Windows.Media;
              using System.Xml.Serialization;
              using NinjaTrader.Cbi;
              using NinjaTrader.Gui;
              using NinjaTrader.Gui.Chart;
              using NinjaTrader.Gui.SuperDom;
              using NinjaTrader.Gui.Tools;
              using NinjaTrader.Data;
              using NinjaTrader.NinjaScript;
              using NinjaTrader.Core.FloatingPoint;
              using NinjaTrader.NinjaScript.Indicators;
              using NinjaTrader.NinjaScript.DrawingTools;
              #endregion
              
              //This namespace holds Strategies in this folder and is required. Do not change it. 
              namespace NinjaTrader.NinjaScript.Strategies
              {
              	public class DynamicCrossV3 : Strategy
              	{	
              		#region Vars
              		private double Range;
              	    private double ValueDot3;
              		private Series<double> RedLine;
              		private bool BuyLimit; 
              		private  TrendBack;
              		#endregion
              		
              		protected override void OnStateChange()
              		{
              			if (State == State.SetDefaults)
              			{	
              				#region Defs
              				Description									= @"Enter the description for your new custom Strategy here.";
              				Name										= "DynamicCrossV3";
              				Calculate									= Calculate.OnPriceChange;
              				EntriesPerDirection							= 1;
              				EntryHandling								= EntryHandling.AllEntries;
              				IsExitOnSessionCloseStrategy				= true;
              				ExitOnSessionCloseSeconds					= 30;
              				IsFillLimitOnTouch							= false;
              				MaximumBarsLookBack							= MaximumBarsLookBack.TwoHundredFiftySix;
              				OrderFillResolution							= OrderFillResolution.High;
              				OrderFillResolutionType						= BarsPeriodType.Minute;
              				OrderFillResolutionValue					= 1;
              				Slippage									= 0;
              				StartBehavior								= StartBehavior.WaitUntilFlat;
              				TimeInForce									= TimeInForce.Gtc;
              				TraceOrders									= false;
              				RealtimeErrorHandling						= RealtimeErrorHandling.StopCancelClose;
              				StopTargetHandling							= StopTargetHandling.PerEntryExecution;
              				BarsRequiredToTrade							= 20;
              				// Disable this property for performance gains in Strategy Analyzer optimizations
              				// See the Help Guide for additional information
              				IsInstantiatedOnEachOptimizationIteration	= true;
              				#endregion 
              				}
              			else if (State == State.Configure)
              			{	
              				RedLine = new Series<double>(this);
              		//		TrendBack = new Series<double>(this);
              			
              				SetProfitTarget("",CalculationMode.Ticks, Target);
              			}
              		}
              
              		protected override void OnBarUpdate()
              		{	
              			#region Defaults to new bar
              			if(IsFirstTickOfBar)
              			{
              				BuyLimit = false;	
              			}
              			#endregion
              			
              			#region Defaults
              			if (BarsInProgress != 0) 
              				return;
              
              			if (CurrentBars[0] < 1)
              			return;
              			#endregion
              			
              			#region Open == Close
              			
              			if( Open[1] == Close[1] ) 										// last open == last close
              				{															// licz z High i low
              					Range 	= Instrument.MasterInstrument.RoundToTickSize(High[1] - Low[1]); 																											Print(Range);	
              					Range 	= Instrument.MasterInstrument.RoundToTickSize(Range / 3); 																													Print("range przez 3:    "+Range);	
              					ValueDot3 = Instrument.MasterInstrument.RoundToTickSize(High[1] - Range);																											Print("ValDot3 :        "+ValueDot3);
              					RedLine[1] = Instrument.MasterInstrument.RoundToTickSize(ValueDot3);
              					Draw.HorizontalLine(this, "1P3Bar", RedLine[1], Brushes.Green);
              				}
              			#endregion
              				
              			#region	Open > Close (Long)
              				
              			if( Open[1] < Close[1])
              				{
              					Range 	= Instrument.MasterInstrument.RoundToTickSize(High[1] - Low[1]); 																											Print(Range);	
              					Range 	= Instrument.MasterInstrument.RoundToTickSize(Range / 3); 																													Print("1/3 range long:     "+Range);	
              					ValueDot3 = Instrument.MasterInstrument.RoundToTickSize(High[1] - Range);																											Print("ValDot3 :        "+ValueDot3);
              					RedLine[1] = Instrument.MasterInstrument.RoundToTickSize(ValueDot3);
              					Draw.HorizontalLine(this, "1P3Bar", RedLine[1], Brushes.Green);
              					
              					#region Change Trend
              					TrendBack = Close[0];
              THERE >				if(CrossBelow(RedLine[1], TrendBack[0], 1) && BuyLimit == false) 
              					{
              						EnterShort(DefaultQuantity,"");
              						BuyLimit = true;
              					}
              					#endregion 										// przyjrzeć się na close w IF
              					
              					#region Follow Trend
              						if(Close[0] > High[1] && BuyLimit == false)
              						{
              							EnterLong(DefaultQuantity,"");
              							BuyLimit = true;
              							
              						}
              					#endregion
              					
              				}
              				
              			#endregion
              			
              				
              			#region Open < Close (short) pusty
              			#endregion 				
              		}
              			#region Props
              		[NinjaScriptProperty]
              		[Range(1, int.MaxValue)]
              		[Display(Name="Target", Order=2, GroupName="Parameters")]
              		public int Target
              		{ get; set; }
              		#endregion
              		
              		
              		
              		
              	}
              }
              I have to use there TrendBack[0], but NT returns errors. Why i can't use just Close[0] ?

              Comment


                #8
                Hello,

                Thank you for the reply.

                Yes in this case you need to refer to the help guide to see how CrossAbove can be used, you are not using any valid use.

                You are trying to use two doubles because you are specifying a BarsAgo for each series:

                Code:
                if(CrossBelow(RedLine[B][1][/B], TrendBack[B][0][/B], 1)
                You can instead use a series and a double
                Code:
                if(CrossBelow(RedLine, TrendBack[0], 1)
                Or you could use two series as well:
                Code:
                if(CrossBelow(RedLine, TrendBack, 1)
                You can use Close if you wanted as well because that is a series, it would just depend on what you are trying to accomplish.

                Code:
                if(CrossBelow(RedLine, Close, 1)

                I look forward to being of further assistance.
                JesseNinjaTrader Customer Service

                Comment


                  #9
                  Ok I used to RedLine, TrendBack[0] but now NT returns an error in output :
                  Error on calling 'OnStateChange' method: You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.

                  I'm not sure what is wrong, because I used to
                  BarsRequiredToTrade =2 and (BarsInProgress !=0).
                  Thans for help, again
                  Last edited by kamix265; 10-02-2018, 05:26 AM.

                  Comment


                    #10
                    Hello kamix265,

                    Thank you for the reply.

                    The error states the problem is coming from OnStateChange. Have you tried to use CrossAbove or any other price logic in OnStateChange?

                    All logic that uses Series or BarsAgo should go in OnBarUpdate in case you currently have any other logic in OnStateChange. Can you provide a sample of OnStateChange how you have it when the error is presented?

                    I look forward to being of further assistance.
                    JesseNinjaTrader Customer Service

                    Comment


                      #11
                      I found a mistake.
                      I wanted to draw lines firstly so I add syntax under state.Configure.
                      Now its working under OnBarUpdate and it resolves all problems.
                      Thanks, but I think it's not last post there

                      Comment


                        #12
                        Welcome again,
                        You have to tell me what is going on there, I made Horizontal Lines on high and low on the last bar, calculation is on each tick, and now look at picture.
                        Any Ideas?
                        Attached Files

                        Comment


                          #13
                          Hello kamix265,

                          From the image alone I would be unsure what may be happening.

                          In the script you provided, it looks like you have the lines in OnBarUpdate being drawn for each tick. I tested this on my end and see the prices lining up with the prior bars prices. Have you tried using Prints in the script to confirm the values being seen by the drawing objects?

                          I also see you have BarsInProgress in the script, did you at one point have multiple series in this script? If so, you may need to remove it from the chart and re-add it to have those changes reflected.

                          I look forward to being of further assistance.
                          Last edited by NinjaTrader_Jesse; 10-09-2018, 12:45 PM.
                          JesseNinjaTrader Customer Service

                          Comment


                            #14
                            No, only one series, its look like not enough data in playback connection. For example 5.10 trading day was ended at 10 PM, but next (6.10) day was started by 2 PM. What should I do to fix it? I don't have to tell how important is it, right?

                            Comment


                              #15
                              Hello kamix265,

                              Thank you for the reply.

                              I wanted to clarify, you are saying that in this specific case it is caused because the data is not available, is this correct?

                              Is this an instrument you have recorded playback data for, or is this one that is available for download? You may try redownloading the data if there is missing data from the period of time you are testing. If you are recorded the data but this part is missing, there is not really anything that could be done to recreate that data if you had not been recording it.

                              I look forward to being of further assistance.
                              JesseNinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by quantismo, 04-17-2024, 05:13 PM
                              4 responses
                              30 views
                              0 likes
                              Last Post quantismo  
                              Started by love2code2trade, 04-17-2024, 01:45 PM
                              4 responses
                              31 views
                              0 likes
                              Last Post love2code2trade  
                              Started by cls71, Today, 04:45 AM
                              2 responses
                              10 views
                              0 likes
                              Last Post eDanny
                              by eDanny
                               
                              Started by proptrade13, Today, 11:06 AM
                              0 responses
                              5 views
                              0 likes
                              Last Post proptrade13  
                              Started by kulwinder73, Today, 10:31 AM
                              1 response
                              10 views
                              0 likes
                              Last Post NinjaTrader_Erick  
                              Working...
                              X