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

I can't have EnterLong() working.

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

    I can't have EnterLong() working.

    Hello all

    I have coded a simple Strategy in order to send a simple EnterLong() but it never opens any position.

    What am I doing wrong ? The order id is always -1. No opened positions on the GUI.


    Thanks

    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 DVStrategy : Strategy
    	{
    		protected override void OnStateChange()
    		{
    			if (State == State.SetDefaults)
    			{
    				Description									= @"Enter the description for your new custom Strategy here.";
    				Name										= "DVStrategy";
    				Calculate									= Calculate.OnEachTick;
    				EntriesPerDirection							= 1;
    				EntryHandling								= EntryHandling.AllEntries;
    				IsExitOnSessionCloseStrategy				= true;
    				ExitOnSessionCloseSeconds					= 30;
    				IsFillLimitOnTouch							= false;
    				MaximumBarsLookBack							= MaximumBarsLookBack.TwoHundredFiftySix;
    				OrderFillResolution							= OrderFillResolution.Standard;
    				Slippage									= 0;
    				StartBehavior								= StartBehavior.ImmediatelySubmit;
    				TimeInForce									= TimeInForce.Gtc;
    				TraceOrders									= false;
    				RealtimeErrorHandling						= RealtimeErrorHandling.StopCancelClose;
    				StopTargetHandling							= StopTargetHandling.PerEntryExecution;
    				BarsRequiredToTrade							= 1;
    				// Disable this property for performance gains in Strategy Analyzer optimizations
    				// See the Help Guide for additional information
    				IsInstantiatedOnEachOptimizationIteration	= true;
    			}
    			else if (State == State.Configure)
    			{
    			}
    		}
    
    		bool done = false;
    		protected override void OnBarUpdate()
    		{
    			if (this.CurrentBar>this.BarsRequiredToTrade)
    			{
    				if (done == false) 
    				{
    					Print("Conditions ok"); // Well written on output
    					Order order = EnterLong();
    					Print("order id = " + order.Id.ToString());
    					done = true;
    				}
    			}
    			
    		}
    	}
    }

    #2
    Hello investdatasystems,

    Welcome to the forums!

    Your code will enter a position. It is likely that the position was exited on a session close. If you scroll your chart to the beginning, you should see where this entry had occurred.

    If you assign an entry signal to EnterLong(), you will be able to see it printed back from the Order object. For example:
    Code:
    private bool done = false;
    private Order myOrder = null;
    protected override void OnBarUpdate()
    {
    	if (this.CurrentBar>this.BarsRequiredToTrade)
    	{
    		if (done == false) 
    		{
    			Print("Conditions ok"); // Well written on output
    			myOrder = EnterLong("entryOrder");
    			Print("order name = " + myOrder.Name);
    			done = true;
    		}
    	}
    }
    I would also advise to use Order.OrderId to get the order ID instead of Order.Id.

    Please let me know if I can be of further assistance.
    JimNinjaTrader Customer Service

    Comment


      #3
      Hello !
      Thank you for your reply.
      Ok I will check these points.
      But one thing I noticed is that there is nothing in the list of positions after execution of the code I posted.

      Comment


        #4
        I have just tested and now I get the name and an Id with OrderId as you suggested :

        I find strange that the position is not listed in the main Positions window of NT8... How to follow a position after emitting it ?

        Thanks

        Code:
        Conditions ok
        order name = Buy
        order id = NT-00000-18
        (Default name seems to be "Buy" when no name passed in argument to EnterLong).

        Code:
        		bool done = false;
        		protected override void OnBarUpdate()
        		{
        			if (this.CurrentBar>this.BarsRequiredToTrade)
        			{
        				if (done == false) 
        				{
        					Print("Conditions ok");
        					Order order = EnterLong();
        					Print("order name = " + order.Name);
        					Print("order id = " + order.OrderId);
        					done = true;
        				}
        			}
        			
        		}

        Comment


          #5
          1.
          Another thing :

          I exit Ninjatrader 8
          I restart NinjaTrader 8
          I don't execute any EnterLong()

          I execute the following code :

          Code:
          			for (int i=0;i<this.Positions.Count();i++)
          			{
          				Print("Position #" + i + " [" + Positions[i].Instrument + "] [" + Positions[i].Quantity + "]");	
          				Print("Position #" + i + " [MarketPosition=" + Positions[i].MarketPosition.ToString() + "]");
          			}
          I have the following output :

          Code:
          Position #0 [AUDUSD Default] [0]
          Position #0 [MarketPosition=Flat]
          There is well a AUDUSD chart on the screen.
          I think that this means that there is no positions on AUDUSD (Flat = neither Long nor Short). Am I true ? Thanks

          2.
          Another point :
          When I try to send 2 orders then the output above is still the same (only one position, always flat).

          Code:
          					Print("Conditions ok");
          					Order order1 = EnterLong();
          					Print("order name = " + order1.Name);
          					Print("order id = " + order1.OrderId);
          					Order order2 = EnterLong();
          					Print("order name = " + order2.Name);
          					Print("order id = " + order2.OrderId);
          					done = true;
          And the 2 orders have the same ids :

          Conditions ok
          order name = Buy
          order id = NT-00000-4
          order name = Buy
          order id = NT-00000-4
          I think that this may be due to the fact (?) that only one position can be opened on an instrument. Am I right ?
          Last edited by investdatasystems; 03-08-2018, 03:36 AM.

          Comment


            #6
            I have imported the "Golden Cross" strategy from this website (March2017SCNT8.zip) and it opens positions correctly, with informations well printed in the Positions tab and in the Orders tab...

            So I have copied the code inside the "State == State.SetDefaults" from "Golden Cross" code to my code but my code still does not trade...

            I'll make further tests and will let you know.

            Anyway thanks for the support

            Comment


              #7
              Hello investdatasystems,

              Thanks for your additional questions.

              The Positions tab of the Control Center will list actual positions on the account. It will not show strategy "virtual" positions that are made with historical data.

              The Positions object will tell you about the virtual position the strategy has on any instruments that are added to the strategy. Positions is used for multi series NinjaScripts when the Position object should be used for strategies with one instrument.

              For the output that you see with OrderId's there are two things that stick out. The first is your EntriesPerDirection property which would be limiting you from making multiple entries and taking multiple positions. If you increase this value, you will allow additional entries. For the order submission for the second entry, we would advise using overloads with Entry Signals so you can differentiate each entry.

              For example:

              Code:
              private bool done = false;
              private Order myOrder = null;
              private Order myOrder2 = null;
              protected override void OnBarUpdate()
              {
              	if (this.CurrentBar>this.BarsRequiredToTrade)
              	{
              		if (done == false) 
              		{
              			myOrder = EnterLong("entryOrder");
              			Print("order name = " + myOrder.Name);
              			Print("order id = " + myOrder.OrderId);
              			myOrder2 = EnterLong("entryOrder2");
              			Print("order2 name = " + myOrder2.Name);
              			Print("order2 id = " + myOrder2.OrderId);
              			done = true;
              		}
              	}
              }
              The syntax above with the appropriate EntriesPerDirection set will give you the output seen below. EntriesPerDirection can also be set in the UI when enabling a strategy.

              order name = entryOrder
              order id = NT-00000-31
              order2 name = entryOrder2
              order2 id = NT-00001-31
              I've included publicly available documentation on the items discussed.


              For further direction using Order objects, I recommend referencing the SampleOnOrderUpdate strategy found here: https://ninjatrader.com/support/foru...ead.php?t=7499

              Please let us know if we can be of additional help.
              JimNinjaTrader Customer Service

              Comment


                #8
                I increased the EntriesPerDirection parameter but that changed nothing.

                I'll try further tests and will let you know.

                I'm not working on historical data but on live feed from FXCM (and Golden Strategy works well with that).

                Thank you !

                Comment


                  #9
                  Please could you try this script and tell me if you have the same behaviour than me ?

                  (In 1s timeframe and 5s timeframe AUDUSD chart from FXCM)

                  Thanks in advance.
                  = No position opened and following output :

                  Output :
                  Code:
                  EnterLong()
                  Enabling NinjaScript strategy 'DVStrategy/131966327' : On starting a real-time strategy - StartBehavior=WaitUntilFlat EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On bar close IsUnmanaged=False MaxRestarts=4 in 5 minutes



                  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 DVStrategy : Strategy
                  	{		
                  		protected override void OnStateChange()
                  		{
                  			if (State == State.SetDefaults)
                  			{
                  				Description									= @"DVStrategy";
                  				Name										= "DVStrategy";
                  				Calculate									= Calculate.OnBarClose;
                  				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)
                  			{
                  				this.ClearOutputWindow();
                  			}
                  		}
                  
                  		bool done = false;
                  		protected override void OnBarUpdate()
                  		{			
                  			if (Position.MarketPosition == MarketPosition.Flat)
                  			{
                  				if (this.CurrentBar>this.BarsRequiredToTrade)
                  				{
                  					if (done==false)
                  					{
                  						Print("EnterLong()");
                  						EnterLong();
                  						done = true;
                  					}
                  				}
                  			}
                  		}
                  		
                  	}
                  }

                  Comment


                    #10
                    Hello investdatasystems,

                    You have a print that shows that the logic had met the EnterLong() method. This gets called only once when the strategy is processing historical data and does not get called again. This is a virtual position that likely got closed later on historically because the strategy is set to use ExitOnSessionClose.

                    You will also see historical prints before the strategy transitions to realtime and you see the print for Enabling Strategy.

                    The steps you should take to debug your strategy will be to:
                    1. Add Prints to the strategy to monitor if and why your logic is becoming true or not (You have already done this)
                    2. Enable TraceOrders to see the order submissions in the Output window
                    3. Check the chart that you applied the strategy to so you can observe the orders.


                    I would also suggest to check the Strategy Performance report by right clicking on the chart where you enabled the strategy and select Strategy Performance > Historical or Strategy Performance > Historical & Realtime.

                    Finally, I would also suggest testing your code with and without a check for State.Historical so you can see the difference between historical and realtime processing.

                    Code:
                    private override void OnBarUpdate()
                    {
                        if (State == State.Historical) return;
                    ...
                    I've included a link for using TraceOrders below:
                    TraceOrders — http://ninjatrader.com/support/forum...ead.php?t=3627

                    Please let me know if you have any questions.
                    JimNinjaTrader Customer Service

                    Comment


                      #11
                      Yeah ! State.Historical test did the trick ! Thank you !!!!

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by alifarahani, Today, 09:40 AM
                      6 responses
                      23 views
                      0 likes
                      Last Post alifarahani  
                      Started by Waxavi, Today, 02:10 AM
                      1 response
                      17 views
                      0 likes
                      Last Post NinjaTrader_LuisH  
                      Started by Kaledus, Today, 01:29 PM
                      5 responses
                      13 views
                      0 likes
                      Last Post NinjaTrader_Jesse  
                      Started by Waxavi, Today, 02:00 AM
                      1 response
                      12 views
                      0 likes
                      Last Post NinjaTrader_LuisH  
                      Started by gentlebenthebear, Today, 01:30 AM
                      3 responses
                      17 views
                      0 likes
                      Last Post NinjaTrader_Jesse  
                      Working...
                      X