• If this is your first visit, you will have to register before you can post. To view messages, please scroll below and select the forum that you would like to visits. Questions? Be sure to check out the Forum FAQ.

Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Managing Multiple Orders

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

    Managing Multiple Orders

    Hi,

    I am working on a strategy to manage multiple orders each with multiple stops and targets. Stops move up to break even in 3 steps as the market move in the right direction.

    I have reviewed the help files and using OnExecutionUpdate and OnOrderUpdate could become very clumsy way to manage the trades with unique identifiers for all the orders, stops and targets.

    Is there an example of how this can be done using arrays to try to streamline the process?

    Thanks

    Ian

    #2
    Hello IanC28,

    Thanks for your post.

    We do not have a specific premade multi position example strategy that uses OnOrderUpdate and OnExecutionUpdate to manage Order objects for the strategy which also uses arrays or Lists to contain the Order objects. However, our SampleOnOrderUpdate strategy can demonstrate how the Order handling should be done and our SamplePriceModification example demonstrates tracking Order objects for Targets and Stops in a List. This strategy could be used as inspiration to use Lists to contain the Order objects for your Entries, Targets, and Stops to make your strategy more organized.

    Links to these examples are below.

    SampleOnOrderUpdate - https://ninjatrader.com/support/help...and_onexec.htm

    SamplePriceModification - https://ninjatrader.com/support/help..._and_profi.htm

    Please let us know if there is anything else we can do to help.
    JimNinjaTrader Customer Service

    Comment


      #3
      Jim,

      Thanks for the pointers.

      I have been working on the routines, but have an issue you could perhaps assist with.

      When I change instrument on the chart that the strategy is running on the original orders and positions remain in place . . . that's what I want. When I return to the original instrument the strategy syncs with the account position. Depending on the strategy the position may be closed, but the associated stops and targets remain 'working'.

      Can you please advise how to detect the change of instrument and how to identify and cancel any orphan stop and target orders.

      Thanks

      Ian

      Comment


        #4
        Hello Ian,

        Changing the Instrument will effectively change the data series and reload the strategy so it is running against that data series. I may suggest adding the Strategy from the Control Center to be able to freely change charts while keeping your strategy running.

        To answer your question directly, you will want to use a Start Behavior to have the strategy cancel any other previously working orders. Using Wait Until Flat, all previously submitted orders that are live will be cancelled and the strategy will wait until it is flat.

        Using Immediately Submit, the strategy will attempt to match the orders calculated from historical data against the live working orders and resume them if they match. If historical data processing is skipped ( I.E. using if (State == State.Historical) return; ) then Immediately Submit will not have any historical orders to match against the live orders and the live orders will cancel. Please be aware that the strategy may be out sync in this type of situation as the strategy will calculate as a flat position after processing historical data when a previous run of a strategy may be in a position.

        It is also important to note that Synchronize Account is an additional behavior that syncs the account position to the strategy position (not the other way around.) Synchronize Account will submit an order to the account after enabling the strategy so it matches the calculated strategy position.

        Our documentation on Start Behaviors (Syncing Account Positions) can provide more explicit detail on these Start Behaviors.

        Syncing Account Positions - https://ninjatrader.com/support/help..._positions.htm

        Strategy Position vs. Account Position - https://ninjatrader.com/support/help..._account_p.htm

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

        Comment


          #5
          Jim thanks for the pointers.

          I have tried controlling the strategy from the control panel, but have an issue that I cannot enable a new strategy from the panel as there is no 'enable' check box. Also, when a strategy is disabled it disappears off the panel. Not sure what's going on. I have tried reinstalling, but that makes no difference. Also noticed I can't save any strategy templates.

          Not sure if I have changed a setting to cause this . . . I have been able to do both these things a few weeks ago.

          I seem to be getting some timing errors.

          "System.NullReferenceException: Object reference not set to an instance of an object"

          The code causing the error is:

          if (Position.MarketPosition == MarketPosition.Short && Close[0] <= TriggerShort)
          {
          // Checks to see if our Stop Order has been submitted already

          if (stopOrder[k].StopPrice > Position.AveragePrice - MoveStopAboveEntryTicks * TickSize)
          {
          // Modifies stop-loss to breakeven
          stopOrder[k] = ExitLongStopMarket(0, true, stopOrder[k].Quantity,
          Position.AveragePrice - MoveStopAboveEntryTicks * TickSize, "St-" + MyEntry, MyEntry);




          Print("Stop Order " + MyEntry + " at line 945: " + stopOrder[k].ToString());

          }.

          stopOrder[k] is checked for null before entering this code. It contains the order as the ExitLongStopMarket is executed successfully, but the Print triggers the NullReferenceException.

          Any idea whats going on?

          Thanks

          Ian


          Comment


            #6
            Hello IanC28,

            When adding from the Control Center, the Enabled box will be on the right hand side of the Control Center when the Strategies tab is selected. If you do not see this option, please right click on the background of the Strategies grid to open the Properties menu and check the Enabled tick box.

            For saving strategy templates, do you see this issue with the SampleMACrossover strategy or see any errors in the log tab of the Control Center?

            For the strategy disappearing from the chart, I may suggest trying to close NinjaTrader and renaming the database file. (Documents/NinjaTrader 8/db/NinjaTrader.sdf) A new database file will be created when you restart NinjaTrader. If you continue to see this issue, could you write to me at platformsupport [at] ninjatrader [dot] com so we can arrange a call where we can investigate further? Please include the text "ATTN Jim" and include a link to this thread if that is the case.

            In the snippet provided, I do not see a null check protecting that code and it is not clear that that line would be throwing the error. You may be running an older instance of that strategy that does not have the null check compiled in or the error is getting thrown elsewhere. I would suggest placing a null check directly on that line that you have determined to be throwing the error and testing again. After that you can follow the logic back up to verify that you have the code protected. By adding prints on each line, you can identify where exactly the error is getting thrown.

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

            Comment


              #7
              Thanks for your patience Jim. I had clicked on the option to show only active strategies so they disappeared when inactive.

              I am using ExitShort to close positions and specify both signal names so that I know which conditions were met to close the trade i.e ExitShort(int quantity, string signalName, string fromEntrySignal)

              I would expect to see these signal names in the list of trades, but this does not seem to be the case, and I am concerned that my code is not working as expected.

              I have included the code used and appended a 'd' onto a test order that can only be generated from this code snippet.

              Do you know why the Entry names don't tie in with the Exit name?

              Thanks

              private void ExitShortTrade(int i, int j, int id)
              {

              string S1;
              S1 = @"ExS" + i + "-" + j + "-" + id;

              string S2;
              S2 = @"S" + i + "-" + j;

              if( S2 == "S3-2" ) S1 = "Ex" + S2 + "-" + id + "d";

              ExitShort(Convert.ToInt32(aTrade[i].ShortQuantity), S1, S2);

              Click image for larger version

Name:	Capture.PNG
Views:	2
Size:	131.8 KB
ID:	1048870




              Attached Files

              Comment


                #8
                Hello IanC28,

                The signal names are tying the entries and exits together in the Managed Approach to managed the position opened by that entry, but the pairing for trades like we see in Performance Reports is going to be tied together in a FIFO fashion.

                We have a feature request tracking interest behind improving Trade pairing for performance reports and I will add a vote on your behalf. The ticket ID is SFT-2928. As with other feature requests, we cannot offer an ETA or promise of fulfillment, but your interest is tracked.

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

                Comment


                  #9
                  Hi Jim,

                  I am getting the following error in the log file.

                  "2019-03-06 16:42:04:601|3|524288|Error on executing DB command: System.Data.SqlServerCe.SqlCeException (0x80004005): A duplicate value cannot be inserted into a unique index. [ Table name = Orders,Constraint name = PK__Orders__000000000000033E ]"

                  Is this to do with the label names I am using for orders? They are unique within the strategy, but not for multiple instances of the strategy.

                  Not really sure how to track this down. I am using Microsoft Visual Studio to debug my code, but it does not pick up on the error.

                  I have to continually delete my NinjaTrader.sdf file . . which is a pain.

                  Thanks for any pointer you can provide.

                  Ian

                  Comment


                    #10
                    Hello IanC28,

                    Database errors would be generated from bad writes to the database which could involve Orders, Executions and Trades. Instruments are also included with the database, but we should narrow the issue down to what is causing the errors to troubleshoot further.

                    Can you confirm that these errors are encountered only with using this strategy and can you reproduce these errors in a consistent fashion?

                    If you can confirm the issue is isolated to this script, I would suggest commenting sections of code until the issue is no longer seen. I would start commenting Order object handling code and then to look into order submission code if that is creating issue.

                    After a section of code that is causing the issue is identified, it may be clearer what the issue is that needs to get fixed. If it is not clear, please post a barebones example script describing what you are doing to hit the issue without any other code related to the matter. We could then give some further recommendations for handling that case.

                    Instructions for exporting a NinjaScript in source code format can be found here - https://ninjatrader.com/support/help...tAsSourceFiles

                    Using the Playback Connection can help to repeat scenarios that have happened with Realtime data.

                    Playback - https://ninjatrader.com/support/help...connection.htm

                    I look forward to being of further assistance.
                    Last edited by NinjaTrader_Jim; 03-06-2019, 11:52 AM.
                    JimNinjaTrader Customer Service

                    Comment


                      #11
                      Thanks for the pointers Jim,

                      I have been checking out the error and found that once triggered the system will continually send a message to the log file even when Playback is sitting doing nothing (on pause). A new log entry occurs every 10 seconds. So not sure if it has anything to do with the orders.

                      I did notice that there was another error which occurs prior to the one above. It is:

                      2019-03-07 01:05:12:524|3|524288|Error on executing DB command: System.InvalidOperationException: There was an error reflecting type 'NinjaTrader.NinjaScript.Strategies.aRenko8'. ---> System.InvalidOperationException: There was an error reflecting field 'CSMFTPro1'. ---> System.InvalidOperationException: There was an error reflecting type 'NinjaTrader.NinjaScript.Indicators.CSMFTPro'. ---> System.InvalidOperationException: Types 'NinjaTrader.NinjaScript.Indicators.Indicator' and 'NinjaTrader.NinjaScript.Indicators.Indicator' both use the XML type name, 'Indicator', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type.

                      CSMFTPro is a third party indicator loaded by the strategy, and may also be on the chart. Could this be the cause of the error? How would I resolve the XML issue?

                      Thanks

                      Ian



                      Comment


                        #12
                        Hello Ian,

                        I would suggest removing the indicator from the equation by commenting and disabling the code that uses it in your strategy and to make sure the indicator is not running in your tests to confirm if it is the cause of the database errors.

                        The XML/Reflecting type errors likely have to do with a public property that is being serialized improperly. I would first suggest to remove the script from the equation to verify if it is causing the issue. If it is and you have its source code, you may check its public properties to see if there are any exotic public properties (other than serializable types likes strings, ints, doubles, etc) that either have improper attributes, or if they can be corrected with [XmlIgnore] . More information on these attributed is linked below.

                        Attributes - https://ninjatrader.com/support/help...attributes.htm

                        I may also suggest reaching out to the developer to advise of this error if you have confirmed that it is the cause of the errors you are receiving to get further direction to use that indicator.

                        Let me know if there is anything else I can do to help.
                        JimNinjaTrader Customer Service

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by rickyblah12, Today, 06:19 PM
                        0 responses
                        3 views
                        0 likes
                        Last Post rickyblah12  
                        Started by ballboy11, Today, 05:22 PM
                        0 responses
                        3 views
                        0 likes
                        Last Post ballboy11  
                        Started by ballboy11, Today, 04:33 PM
                        2 responses
                        3 views
                        0 likes
                        Last Post ballboy11  
                        Started by dedouglas, Today, 03:16 PM
                        1 response
                        7 views
                        0 likes
                        Last Post NinjaTrader_ChelseaB  
                        Started by TradeMyth, Today, 02:45 PM
                        3 responses
                        24 views
                        0 likes
                        Last Post NinjaTrader_ChelseaB  
                        Working...
                        X