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

2 entry orders help!

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

    2 entry orders help!

    Hello,
    I'm trying to test some trading ideas and I solved most of the problems I found...
    But I cannot code a system with 2 entry orders: for example in this code, I'd like that will be active both entry orders, but in the report short trades are significally lower than long trades and sometimes it seems an open long position is not reverted into a short position by a short entry order...
    In trying to convert some system from Multicharts to NinjaTrader and apart from this problem with different entry orders, everything else seems to be very fine in NinjaTrader 8...

    I read somewhere there's the possibility to use another approach to manage orders but it seems too much complicated, then if you can help me I'd edit this file for the nexts strategies!

    Thanks for your help!
    Have a nice day!

    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 Test2Orders : Strategy
    	{
    		private double MyAtr;
    		private bool OkLong;
    		private bool OkShort;
    		private double highd1;
    		private double lowd1;
    		private double closed1;
    		private double opend1;
    		private double highd2;
    		private double lowd2;
    		private double closed2;
    		private double opend2;
    
    		protected override void OnStateChange()
    		{
    			if (State == State.SetDefaults)
    			{
    				Description									= @"Test to place 2 opposite entry orders: 1 long on High of Yesterday, 1 short on Low of Yesterday";
    				Name										= "Test2Orders";
    				Calculate									= Calculate.OnEachTick;
    				EntriesPerDirection							= 1;
    				EntryHandling								= EntryHandling.UniqueEntries;
    				IsExitOnSessionCloseStrategy				= true;
    				ExitOnSessionCloseSeconds					= 30;
    				IsFillLimitOnTouch							= true;
    				MaximumBarsLookBack							= MaximumBarsLookBack.TwoHundredFiftySix;
    				OrderFillResolution							= OrderFillResolution.Standard;
    				Slippage									= 0;
    				StartBehavior								= StartBehavior.WaitUntilFlatSynchronizeAccount;
    				TimeInForce									= TimeInForce.Day;
    				TraceOrders									= true;
    				RealtimeErrorHandling						= RealtimeErrorHandling.StopCancelClose;
    				StopTargetHandling							= StopTargetHandling.ByStrategyPosition;
    				BarsRequiredToTrade							= 20;
    				// Disable this property for performance gains in Strategy Analyzer optimizations
    				// See the Help Guide for additional information
    				IsInstantiatedOnEachOptimizationIteration	= true;
    				OffsetBrk					= 0;
    				MyContracts					= 1;
    				StopATR						= 1;
    				BegTime 					= DateTime.Parse("08:00");
    				EndTime						= DateTime.Parse("16:00");
    				CloseTime					= DateTime.Parse("16:15");
    				MyStopTicks					= 120;
    				OkLong						= true;
    				OkShort						= true;
    			}
    			else if (State == State.Configure)
    			{
    				AddDataSeries(BarsPeriodType.Minute, 15);		// Added to calculate ATR on 15 min chart
    				AddDataSeries(BarsPeriodType.Minute, 1440);		// Added to calculate previous days OHLC values
    				SetStopLoss(CalculationMode.Ticks, MyStopTicks);
    			}
    		}
    
    		protected override void OnBarUpdate()
    		{
    		if (CurrentBars[0] < 1 || CurrentBars[2] < 2)
    			return;
    			
    		if (ToDay(Times[0][0]) != ToDay(Times[0][1]))		// Do something when changes Day...
    		{
    			highd1 = Highs[2][0];	// Calculate previous days OHLC values from intraday data (1440 mins) => Data Index [2]
    			lowd1 = Lows[2][0];
    			closed1 = Closes[2][0];
    			opend1 = Opens[2][0];
    			highd2 = Highs[2][1];
    			lowd2 = Lows[2][1];
    			closed2 = Closes[2][1];
    			opend2 = Opens[2][1];
    			OkLong = true;		// 1 long trade per day
    			OkShort = true;		// 1 short trade per day
    		}
    
    		MyAtr = ATR(BarsArray[1], 20)[0];	//ATR based on 15 mins chart => Data Index [1]
    
    		if (Times[0][0].TimeOfDay >= BegTime.TimeOfDay && Times[0][0].TimeOfDay < EndTime.TimeOfDay)
    		{
    			if (OkLong)		//Send order only if it would be the first long trade of the day
    			{
    				EnterLongStopMarket(MyContracts, highd1+OffsetBrk, @"LE");
    			}
    			
    			if (OkShort)	//Send order only if it would be the first short trade of the day
    			{
    				EnterShortStopMarket(MyContracts, lowd1-OffsetBrk, @"SE");
    			}
    		}
    		
    		if (Position.MarketPosition == MarketPosition.Long)
    		{
    			OkLong = false;		// No more Long trades for today!
    			if (StopATR>0)
    			{
    				ExitLongStopMarket(Position.AveragePrice - StopATR*MyAtr, @"LE", @"LXx");
    			}
    			if (Times[0][0].TimeOfDay >= CloseTime.TimeOfDay)		// Time to close open long position
    			{
    				ExitLong(@"LX", @"LE");
    			}
    		}
    		
    		if (Position.MarketPosition == MarketPosition.Short)
    		{
    			OkShort = false;	// No more Short trades for today!
    			if (StopATR>0)
    			{
    				ExitShortStopMarket(Position.AveragePrice + StopATR*MyAtr, @"SE", @"SXx");
    			}
    			if (Times[0][0].TimeOfDay >= CloseTime.TimeOfDay)		// Time to close open short position
    			{
    				ExitShort(@"SX", @"SE");
    			}
    		}
    
    		}
    
    		#region Properties
    		[NinjaScriptProperty]
    		[Range(-100, double.MaxValue)]
    		[Display(ResourceType = typeof(Custom.Resource), Name="OffsetBrk", Description="Offset Breakout Levels: <0 anticipate >0 posticipate by X points", Order=1, GroupName="NinjaScriptStrategyParameters")]
    		public double OffsetBrk
    		{ get; set; }
    
    		[NinjaScriptProperty]
    		[Range(1, int.MaxValue)]
    		[Display(ResourceType = typeof(Custom.Resource), Name="MyContracts", Description="Contracts", Order=2, GroupName="NinjaScriptStrategyParameters")]
    		public int MyContracts
    		{ get; set; }
    
    		[NinjaScriptProperty]
    		[Range(1, double.MaxValue)]
    		[Display(ResourceType = typeof(Custom.Resource), Name="StopATR", Description="ATR Multiplier", Order=3, GroupName="NinjaScriptStrategyParameters")]
    		public double StopATR
    		{ get; set; }
    
    		[NinjaScriptProperty]
    		[PropertyEditor("NinjaTrader.Gui.Tools.TimeEditorKey")]
    		[Display(ResourceType = typeof(Custom.Resource), Name="BegTime", Description="Begin Time: when start placing orders", Order=4, GroupName="NinjaScriptStrategyParameters")]
    		public DateTime BegTime
    		{ get; set; }
    		
    		[NinjaScriptProperty]
    		[PropertyEditor("NinjaTrader.Gui.Tools.TimeEditorKey")]
    		[Display(ResourceType = typeof(Custom.Resource), Name="EndTime", Description="End Time: when stop entering the market", Order=5, GroupName="NinjaScriptStrategyParameters")]
    		public DateTime EndTime
    		{ get; set; }
    		
    		
    		[NinjaScriptProperty]
    		[PropertyEditor("NinjaTrader.Gui.Tools.TimeEditorKey")]
    		[Display(ResourceType = typeof(Custom.Resource), Name="CloseTime", Description="Close Time: When to Flat Positions", Order=6, GroupName="NinjaScriptStrategyParameters")]
    		public DateTime CloseTime
    		{ get; set; }
    
    		[NinjaScriptProperty]
    		[Range(1, int.MaxValue)]
    		[Display(ResourceType = typeof(Custom.Resource), Name="MyStopTicks", Description="StopLoss Ticks: Maximum amount of ticks for stoploss value", Order=7, GroupName="NinjaScriptStrategyParameters")]
    		public int MyStopTicks
    		{ get; set; }
    		#endregion
    
    	}
    }
    Attached Files

    #2
    Hello endystrike, and thank you for your question.

    It will be easier to answer questions about strategies not producing expected results if we could answer as many of the following questions as possible. Could you take a few minutes to review these questions? I am happy to explain further any of the below questions and the rationale behind asking them.


    • Do you see expected results when running the same test environment on the SampleMaCrossOver strategy in NinjaTrader with as many of the same settings as your strategy as possible?
      • By expected results, I mean that the SampleMACrossover places trades whenever two SMAs with the specified periods cross.
    • Who are you connected to? This is displayed in green on lower left corner of the Control Center window.
    • Are you connected to your data feed provider when running this test?
    • What instrument(s) (and expiry if applicable) have you selected?
    • What Data Series Type have you selected? Example: Tick, Minute, Day
    • What From and To date is selected?
    • Is your strategy a multi instrument or multi time frame strategy?
    • Do you receive an error on screen? Are there errors on the Log tab of the Control Center? If so, what do these errors report?
    Jessica P.NinjaTrader Customer Service

    Comment


      #3
      Hello,
      thanks for your reply, I tried to give you all the informations required to solve the problem (probably I'm not ablecode 2 pending stop orders...)

      Thanks!

      Andrea


      Do you see expected results when running the same test environment on the SampleMaCrossOver strategy in NinjaTrader with as many of the same settings as your strategy as possible?

      How can I use this code that uses market orders while my strategy use different stop pending orders for this purpose? Anyway Sample SMA Crossover has no problem tested...

      By expected results, I mean that the SampleMACrossover places trades whenever two SMAs with the specified periods cross.
      Who are you connected to? This is displayed in green on lower left corner of the Control Center window.

      I'm connected to CQG

      Are you connected to your data feed provider when running this test?

      Yes

      What instrument(s) (and expiry if applicable) have you selected?

      FDAX 12-16... Tested also on GC 02-17

      What Data Series Type have you selected? Example: Tick, Minute, Day

      Primary data series is 5 minute chart

      What From and To date is selected?

      To Today: 5000 days back

      Is your strategy a multi instrument or multi time frame strategy?

      Multitimeframe:
      - primary data is 5 minutes
      - 2nd (from code) is 15 minutes
      - 3rd (from code) is 1440 minutes = 1 day from intraday data



      Do you receive an error on screen?

      No error on screen, but hundreads of thousands lines of this output

      06/12/2016 15:59:00 Strategy 'Test2Orders/92501471': Ignored SubmitOrderManaged() method at 06/12/2016 15:59:00: BarsInProgress=0 Action=Buy OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=1190,2 SignalName='LE' FromEntrySignal='' Reason='Order already has this stop price/limit price/quantity'
      06/12/2016 15:59:00 Strategy 'Test2Orders/92501471': Entered internal SubmitOrderManaged() method at 06/12/2016 15:59:00: BarsInProgress=0 Action=SellShort OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=1158,6 SignalName='SE' FromEntrySignal=''
      06/12/2016 16:00:00 Strategy 'Test2Orders/92501471': Cancelled expired order: BarsInProgress=0, orderId='NT-61376-73' account='Sim101' name='LE' orderState=Working instrument='GC 02-17' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=1190.2 quantity=1 tif=Day oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2016-12-06 15:46:00' gtd='2099-12-01' statementDate='2016-12-06'
      Enabling NinjaScript strategy 'Test2Orders/92501471' : On starting a real-time strategy - StartBehavior=WaitUntilFlatSynchronizeAccount EntryHandling=Unique 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 each tick IsUnmanaged=False MaxRestarts=4 in 5 minutes
      Are there errors on the Log tab of the Control Center? If so, what do these errors report?
      Time Category Message
      06/12/2016 17:47:29 Default Strategy 'Test2Orders/92501471': An Enter() method to submit an entry order at '17/01/2008 08:00:00' has been ignored. Please search on the term 'Internal Order Handling Rules' in the Help Guide for detailed explanation.
      Last edited by endystrike; 12-06-2016, 11:35 AM.

      Comment


        #4
        Thank you endystrike. It looks like we were able to narrow down what is occurring to, at some point, your strategy attempting to go long and short at the same time. To determine why this is the case, please use the visual studio debugging instructions here,



        , setting breakpoints on the lines containing all Enter and Exit methods. You may also want to review the Internal Order Handling rules here,



        We are happy to help with any questions we may.
        Jessica P.NinjaTrader Customer Service

        Comment


          #5
          Originally posted by NinjaTrader_JessicaP View Post
          Thank you endystrike. It looks like we were able to narrow down what is occurring to, at some point, your strategy attempting to go long and short at the same time. To determine why this is the case, please use the visual studio debugging instructions here,



          , setting breakpoints on the lines containing all Enter and Exit methods. You may also want to review the Internal Order Handling rules here,



          We are happy to help with any questions we may.
          It's correct, I'd like to place at the same time 2 orders at different levels: 1 long on Yest high + 1 short order on Yest low but it seems not possible with Managed Approach, correct?
          Can you please help me to convert this code to work in Unmanaged Approach if it's necessary to manage 2 orders?

          It seems strange in any case you cannot send 2 orders at the same time, maybe I'm doing some mistakes...

          Thanks a lot!

          Comment


            #6
            Hello endystrike,


            You can search our extensive library of NinjaScript consultants through the link below to assist with any conversions of NinjaScript orders to the unmanaged approach.

            Simply enter a consultant name or search by using our filter categories. Once you have identified your consultants of choice, please visit each consultant's site for more information or contact them directly to learn more!





            This NinjaTrader Ecosystem website is for educational and informational purposes only and should not be considered a solicitation to buy or sell a futures contract or make any other type of investment decision. The companies and services listed on this website are not to be considered a recommendation and it is the reader's responsibility to evaluate any product, service, or company. NinjaTrader Ecosystem LLC is not responsible for the accuracy or content of any product, service or company linked to on this website.



            Please let me know if you have any questions, concerns or if I can provide any further assistance by responding to this thread at your convenience.
            Ryan L.NinjaTrader Customer Service

            Comment


              #7
              Originally posted by NinjaTrader_RyanL View Post
              Hello endystrike,


              You can search our extensive library of NinjaScript consultants through the link below to assist with any conversions of NinjaScript orders to the unmanaged approach.

              Simply enter a consultant name or search by using our filter categories. Once you have identified your consultants of choice, please visit each consultant's site for more information or contact them directly to learn more!





              This NinjaTrader Ecosystem website is for educational and informational purposes only and should not be considered a solicitation to buy or sell a futures contract or make any other type of investment decision. The companies and services listed on this website are not to be considered a recommendation and it is the reader's responsibility to evaluate any product, service, or company. NinjaTrader Ecosystem LLC is not responsible for the accuracy or content of any product, service or company linked to on this website.



              Please let me know if you have any questions, concerns or if I can provide any further assistance by responding to this thread at your convenience.
              Hello,
              thanks for your reply!
              Isn't it available a tutorial to use "Unmanaged Approach" or a sample file for NinjaTrader 8?

              Thanks a lot

              Comment


                #8
                Hello Andrea,

                To clarify your original question, you are wanting to have opposing orders working at the same time, is this correct?

                I have an example that you may find helpful that uses the unmanaged approach to submit a pair of opposing orders using oco (One Cancels Other) I've made for NinjaTrader 7.

                I've ported this to NT8 for you and I'm attaching both versions so you can compare.

                Below are links to the help guide on using the unmanaged approach.
                https://ninjatrader.com/support/help...d_approach.htm
                https://ninjatrader.com/support/help...runmanaged.htm

                These examples are designed to place orders in real-time so that you can see the orders appear and try and cancel one to see the behavior.
                Unmanaged orders can also be submitted in historical data and be backtested by removing the check for real-time.

                (Updated July 17th, 2018 - corrected assigning the variables to null when the exit on close occurs. Also corrected preventing orders after the exit on close until the new session)

                UnmanagedOCOBracketExample_NT8.zip
                UnmanagedOCOBracketExample_NT7.zip
                Attached Files
                Last edited by NinjaTrader_ChelseaB; 01-04-2023, 08:36 AM.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Originally posted by NinjaTrader_ChelseaB View Post
                  Hello Andrea,

                  To clarify your original question, you are wanting to have opposing orders working at the same time, is this correct?

                  I have an example that you may find helpful that uses the unmanaged approach to submit a pair of opposing orders using oco (One Cancels Other) I've made for NinjaTrader 7.


                  I've ported this to NT8 for you and I'm attaching both versions so you can compare.
                  Thanks a lot, I'll have a look as soon!

                  Comment


                    #10
                    Originally posted by NinjaTrader_ChelseaB View Post
                    Hello Andrea,

                    To clarify your original question, you are wanting to have opposing orders working at the same time, is this correct?

                    I have an example that you may find helpful that uses the unmanaged approach to submit a pair of opposing orders using oco (One Cancels Other) I've made for NinjaTrader 7.


                    I've ported this to NT8 for you and I'm attaching both versions so you can compare.

                    Great example, thanks!

                    I looked carefully and have a questions:

                    1. "No IOrder variable is used as a handle to track the stop loss and profit target".
                    What if position will be closed not by stop loss or profit target - say, position reversed by some opposite order.

                    In that case do stop loss or profit target orders will keeping alive and fully "unmanaged"?

                    2. In Managed approach IOrder object should be assigned in OnOrderUpdate() method only, after Order object created.

                    Otherwise, in Your example
                    PHP Code:
                    OnBarUpdate()
                    {
                    longStopEntry SubmitOrderUnmanaged();

                    Why? Isn't it unsafe?
                    Last edited by fx.practic; 05-22-2018, 11:36 AM.
                    fx.practic
                    NinjaTrader Ecosystem Vendor - fx.practic

                    Comment


                      #11
                      Hello fx.practic,

                      The UnmanagedOCOBracketExample_NT7 does not assign the longProfitTarget/longStopLoss/shortProfitTarget/shortStopLoss to IOrder objects, because there isn't any need to. I'm not needing to reference these orders at a later time. You could if you wanted to. But the script doesn't need to assign these to IOrder objects to function.

                      If trade was closed from an order that is not one of these orders, no, the script would not cancel these. (But the script is coded to only allow these orders to close the position, cancel the opposing order with OCO, or with the ExitOnClose which would cancel all working orders anyway)

                      With NinjaTrader 7 assigning orders to IOrder objects should be done in OnOrderUpdate, because OnOrderUpdate can run for the order before the order submission method returns the IOrder object.

                      From the help guide:
                      "If you are relying on the OnOrderUpdate() method to trigger actions such as the submission of a stop loss order when your entry order is filled ALWAYS reference the properties on the IOrder object passed into the OnOrderUpdate() method."

                      Below is a public link.
                      https://ninjatrader.com/support/help...rderupdate.htm

                      However, in practice I've never run into this issue personally with NinjaTrader 7.
                      (So I'm being lazy with the code. It would be better practice to assign the IOrder from OnOrderUpdate())

                      (corrected)
                      This is definitely an issue with NinjaTrader 8. With NinjaTrader 8, the order object returned isn't updated when OnBarUpdate() runs and will definitely cause issues if the Order object is assigned from OnBarUpdate().
                      Last edited by NinjaTrader_ChelseaB; 12-26-2021, 03:35 PM.
                      Chelsea B.NinjaTrader Customer Service

                      Comment


                        #12
                        Dear Chelsea,

                        Thank you very much for your great sample codes!

                        But when I tried to run your code, the whole thing stopped at Exit on session close! All the bars after that have absolutely no trades!!!

                        Could you teach me how to fix that, please!? Appreciated!
                        Last edited by YoutingChu; 07-16-2018, 08:23 PM.

                        Comment


                          #13
                          Hello YoutingChu,

                          This post appears to be a duplicate of https://ninjatrader.com/support/foru...426#post547426.

                          I will respond in the other thread.
                          Chelsea B.NinjaTrader Customer Service

                          Comment


                            #14
                            Strategy Builder OCO implant

                            @NinjaTrader_ChelseaB, Great example for the OCO's needed for NT8....=>
                            Any chance you can devise a method to implement that for Strategy Builder?

                            I.e... Person builds their strategy logic and then has a method through an indicator or method to place the order(s) with OCO? This would allow for continuing to build the logic further while in Strategy Builder.

                            I already assume the main answer is no, but it projects the essence of the request. Would there be some method to then use the unlock the code (in a copy) and insert a standard code set regions for the OCOs?

                            This way the Strategy Builder could go on building out further logic, save to a temporary version, unlock that versions code and insert the regions for the OCO. And of course then redo for future logic additions to the original file.

                            This may be best if there was a method in Strategy Builder to sort of make an easy place holder for where the OCO region(s) would paste in. Perhaps he a single order entry in the Strategy Builder where the OCO regions are just placed.

                            This would expand the benefits of Strategy Builder OCO greatly.

                            ANY OTHER CODERS SUGGESTIONS ARE EAGERLY APPRECIATED.

                            Comment


                              #15
                              Hello JMont1,

                              The Strategy Builder uses the Managed approach.

                              The Managed approach does not allow for OCO.
                              Chelsea B.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by maybeimnotrader, Yesterday, 05:46 PM
                              2 responses
                              21 views
                              0 likes
                              Last Post maybeimnotrader  
                              Started by adeelshahzad, Today, 03:54 AM
                              5 responses
                              32 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Started by stafe, 04-15-2024, 08:34 PM
                              7 responses
                              32 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Started by merzo, 06-25-2023, 02:19 AM
                              10 responses
                              823 views
                              1 like
                              Last Post NinjaTrader_ChristopherJ  
                              Started by frankthearm, Today, 09:08 AM
                              5 responses
                              22 views
                              0 likes
                              Last Post NinjaTrader_Clayton  
                              Working...
                              X