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

Resume Historical Orders in Unmanaged Approach

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

    Resume Historical Orders in Unmanaged Approach

    Hi Jim,

    thank you for your example regarding the following discussion "Resume Historical Orders in Strategy- Unmanaged Approach" here:

    Hi all, I have a strategy based on unmanaged approach to submit manual orders when certain conditions are met. I would like to resume my historical orders via the strategy after any connection loss or PC restart. I have the following options in State.SetDefaults: Calculate = Calculate.OnEachTick; EntriesPerDirection = 1;


    I open a new Thread since it is not possible to post any reply in the previous one.

    I am not sure I can apply your example to my strategy. If I understand it correclty you are submitting orders using the following commands in the OnBarUpdate() method:

    if (shortEntry == null)
    SubmitOrderUnmanaged(0, OrderAction.SellShort, OrderType.Limit, 100, High[0]+EntryDistance*TickSize, 0, oco, "Short limit entry");
    if (longEntry == null)
    SubmitOrderUnmanaged(0, OrderAction.Buy, OrderType.Limit, 100, Low[0]-EntryDistance*TickSize, 0, oco, "Long limit entry");

    while being in Historical state. As soon the state becomes Realtime you check that the last orders placed in OnBarUpdate() are matching with the one provided by GetRealtimeOrder(Order) in state Realtime in OnStateChange() method. If they match they are assigned to the respective variables. Correct?

    Now, my approach is a little bit different since I hava a semiautomated strategy. The strategy is only placing TPs and SLs (i.e. 1 SL and 3 TPs). I decide when to place a Buy/Sell order based on some conditions.

    There is not historical Buy/Sell order placed by the strategy. So, when I place the order and then I disable the strategy and re-enable it again there will be no historical order and the strategy cancels my order as soon as it restarts as expected.

    So, I would like to be able to "read" the orders available on the chart and implement a logic to match them with my orders in strategy. Is that possible?

    Thank you.

    #2
    Hello Peppo,

    Thank you for your note.

    You'd likely want to set the strategy to only calculate on real time data, and use Add-On code to access the Account. You can then find an open position on the account and use the Unmanaged approach to create protective orders for the position:



    I'd take a look at this version of the UnmanagedOnOrderUpdate that tracks the position for the strategy internally - you could combine this with logic to check the position of the account, track that as your current position, then update that calculated position as you manually enter further trades.

    Please let us know if we may be of further assistance to you.
    Attached Files
    Kate W.NinjaTrader Customer Service

    Comment


      #3
      HI Kate,

      thanks for your answer.

      Your solution would put in place a recalculation of all TP and SL by scratch taking into account, while the position was running, the orders that have been triggered and the ones that are still in place.

      Would it be easier to store them in a file? I mean updating the file everytime some SL/TP are triggered. Restore the orders by reading the file only when the market position is long/short but no protective orders are in place. Is it feasible?

      Thanks.

      Comment


        #4
        Just for clarification. In my strategy I do not submit orders in the OnBarUpdate() method but I use a shortcut recognised by the strategy that submit the order. Once the order is filled the TP and SL are placed. Is it really the case that we cannot retrieve those TP/SL orders once the strategy is stopped and restarted? There is no access to historical orders?

        Comment


          #5
          Originally posted by Peppo View Post
          There is no access to historical orders?
          Hi Peppo,

          Yes there is. Write a loop to cycle through the last 20, 50, or 300 orders to gather all the details you need and current state of each recent order from Account.Orders


          In short..



          First clarify the account you want to use with the code at the bottom of this page..

          https://ninjatrader.com/support/help...ount_class.htm



          Code:
          Note: I would ask Kate if you can lock on something narrower than "lock (Account.All);" to reduce likelihood of deadlocks.
          
          
          private Account myAccount;
          
          protected override void OnStateChange()
          {
          if (State == State.SetDefaults)
          {
          // Find our Sim101 account
          lock (Account.All)
          myAccount = Account.All.FirstOrDefault(a => a.Na me == "Sim101");


          Then cycle through the orders, an example below from the Account.Orders page.

          I would limit to just the more recent orders. The foreach example below is likely to pull back too many orders, take long, etc. Limiting the loop by the last 20, 50, 200 .. orders might be a good idea.


          Code:
          
          private void OnAccountItemUpdate(object sender, Ac countItemEventArgs e)
          {
            // Print the name and order action of each order processed on the account
            foreach (Order order in myAccount.Orders)
            {
                Print(String.Format("Order placed: {0} - {1}", order.Name, order.OrderAction));
            }
          }




          Just quick hints ... of course Kate is a far better resource to guide and answer your question.
          Last edited by hedgeplay; 12-15-2020, 02:23 PM.

          Comment


            #6
            Hello Peppo,

            Thank you for your reply.

            Hedgeplay's on the right track here. I'd also suggest taking a look at this forum post that goes into some considerations for tracking the orders:



            Please let us know if we may be of further assistance to you.
            Kate W.NinjaTrader Customer Service

            Comment


              #7
              Hi,

              thanks for all your answers.

              I have experienced that the the following code returns the open positions an all the account as expected:

              foreach (Position position in myAccount.Positions)
              {
              Print(String.Format("Position: {0} at {1}", position.MarketPosition, position.AveragePrice));
              }

              How can I get only the open position on the chart where the strategy is running?

              Regards

              Comment


                #8
                Originally posted by Peppo View Post
                Hi,

                thanks for all your answers.

                I have experienced that the the following code returns the open positions an all the account as expected:

                foreach (Position position in myAccount.Positions)

                ...
                How can I get only the open position on the chart where the strategy is running?
                Hi Peppo,

                Congrats on making progress!

                " foreach (Position position in myAccount.Positions) .. How can I get only the open position on the chart where the strategy is running?"

                Cant get there from here... specific orders are just not available properties or methods within the Position object.

                https://ninjatrader.com/support/help...?positions.htm
                https://ninjatrader.com/support/help.../?position.htm


                Look at all the goodness in available properties under the Orders object. This is what you seek.

                https://ninjatrader.com/support/help...nt8/?order.htm

                Good detail lie in those posts above. In the example I posted above

                ===================

                within
                "foreach (Order order in myAccount.Orders)"
                {
                // Instead of .." Print(String.Format("Order placed: {0} - {1}", order.Name, order.OrderAction));

                // Use code something like this to identify all existing active, live, working orders

                if( order.OrderState == OrderState.Accepted || order.OrderState == OrderState.Working || order.OrderState == OrderState.PartFilled /* || and if you broker returns orders with a state of Unknown potentially order.OrderState == OrderState.Unknown */ )
                {


                // for each order that passes that if() grab the details you seek from the properties of order. Look again at all the available properties you have access to on each order as it passes through your loop. https://ninjatrader.com/support/help...nt8/?order.htm

                For Example, you might decide to do this if you just want the use the detail from one of the order's properties.
                if(order.OrderType == OrderType.StopLimit)
                {
                stopLossOrder == order;
                string relatedEntryOrder = order.FromEntrySignal;
                }

                or to identify the entryOrder to then pull

                if(order.OrderType == OrderType.StopLimit)
                {
                stopLossOrder == order;
                }



                or, if you want to manage the order going forward into the RealTime statem, before the loop (like in the example Kate posted) create an object at the class level "private Order stopLossOrder;" and then load it with the appropriate order as it passes through the loop.

                if(order.Name == "stopOrder")
                {
                stopLossOrder == order; // now in the loop and after it you can manage the historic order by managing "stopLossOrder"
                }

                }
                } // End of foreach loop




                --------------------------------------------------------

                ~"but that includes loop now includes open orders for all charts, what about orders for just this one chart"

                Once you get that capabilities discussed above sorted out ...

                ... if you follow guidance and only trade that one instrument through one strategy then add another filter to the if above .. something like

                if( this.InstrumentFullName == order.Instrument.FullName && ( if( order.OrderState == OrderState.Accepted || ...


                Now you have restricted to just active orders on the Instrument managed by this chart, answering the question "How can I get only the open position on the chart where the strategy is running?"


                ---------------------------------------------------

                Circling back to the beginning...

                Kate attached great sample code in her first post to use as a foundation to build your solution.
                UnmanagedOnOrderUpdate.zip (3.2 KB, 0 views)

                Personally I would start with that sample and lightly add the other concepts discussed in the thread to get the solution you seek.

                Have fun!
                HedgePlay
                Last edited by hedgeplay; 12-16-2020, 11:20 AM.

                Comment


                  #9
                  Hi,

                  thanks for your suggestion. This is definitely a possible way to proceed.

                  I also found out that with ATM strategy the problem does not exist. I mean while an ATM strategy is running if you lose the connection the orders are retrieved correclty without any issue.

                  Just for my understanding would it be possible with ATM strategy to change the order quantity programmatically? I have seen in this post a discussion about that:



                  Would it possible to have access to the attached file?

                  Thanks & Regards

                  Comment


                    #10
                    Hello Peppo,

                    Thank you for your reply.

                    Since ATMs are managed by the ATM template and not the strategy itself, yes, the orders would be maintained when the strategy is restarted. However, it would not be possible to change the quantity of the entry order, only the stops and targets, since the entry quantities are preset in the ATM template. You'd have to use different templates for different quantities if you wanted to go that route.

                    We're actually wondering where you got the link to that post regarding changing the ATM order quantity? Here's the correct link to that page that should allow you to download:



                    Please let us know if we may be of further assistance to you.

                    Kate W.NinjaTrader Customer Service

                    Comment


                      #11
                      Hello,

                      I came across a new issue regarding the resuming of historical orders.

                      Originally, the problem was that, after the strategy has been stopped/restarted, the previous orders present on the chart were cancelled completely. To avoid this issue I implemented the solution proposed above that consists in reading the Accepted/Working TP/SL orders in the Account for a specific instrument and submit them again once the strategy has deleted them (at restart).

                      This solution works perfectly except for the fact that I have an open position since some days and, when I restarted my strategy, the orders are incredibily not cancelled anymore! I thought because of some NT updates done recently, so I tried again in a paper account to open a new position with TP and SL and, after disabling/renabling the strategy, the orders are cancelled as expected.

                      Now, could you please explain me which is the logic used by the strategy to cancel orders when it is restarted? It sounds a bit confusing at the moment.

                      Thank you.

                      Comment


                        #12
                        Hello Peppo,

                        Thank you for your reply.

                        What happens when a Strategy is restarted would depend on the Start Behavior chosen for the strategy.

                        If using "Wait until Flat" or "Wait until Flat, Synchronize Account", when your strategy starts it will check for any active orders previously generated by the strategy on your account and cancel those first. Should the strategy be unable to cancel and receive confirmation on the cancellation of these orders within 40 seconds the strategy will not start and an alert will be issued.

                        If using "Immediately Submit" or "Immediately Submit, Synchronize Account", any active orders on the account previously generated by the strategy that does not match* an active strategy order will be cancelled. Should the strategy be unable to cancel and receive confirmation on the cancellation of these orders within 40 seconds the strategy will not start and an alert will be issued.

                        * A previously generated order is considered to match an active strategy order when the order action, order type, quantity, limit price, and stop price are exactly identical.

                        I suspect in this case when it didn't cancel the orders that it likely was able to match the active orders to the where the strategy was able to recognize them, so they were not cancelled.

                        You can read more about start behaviors in the help guide here:



                        Please let us know if we may be of further assistance to you.
                        Kate W.NinjaTrader Customer Service

                        Comment


                          #13
                          Hi Kate,

                          thanks for your answer. I understand but my problem now is that within my strategy I check for active orders Accepted/Working and resubmit them as soon the strategy is restarted assuming that the orders will be cancelled.

                          The Start behavior I used was always "Wait until flat". I did not change it in both test cases.

                          Now the strategy could recognise the existing orders (if they match) or not. How do I know if I have to re-submit the orders or not? What is happening now is that I have double orders (in quantity) since the previous orders were not cancelled.

                          Thanks.

                          Comment


                            #14
                            Hello Peppo,

                            Thank you for your reply.

                            Wait until flat would not leave orders in place when re-started - wait until flat will start by cancelling any active orders generated by the strategy on your account as mentioned in my prior post:

                            If using "Wait until Flat" or "Wait until Flat, Synchronize Account", when your strategy starts it will check for any active orders previously generated by the strategy on your account and cancel those first. Should the strategy be unable to cancel and receive confirmation on the cancellation of these orders within 40 seconds the strategy will not start and an alert will be issued.
                            I'd double check that you are using Wait Until Flat, and not adding a completely new instance of the strategy but simply re-enabling the old one. Can you confirm if this occurs when ensuring these two things?

                            Thanks in advance; I look forward to assisting you further.
                            Kate W.NinjaTrader Customer Service

                            Comment


                              #15
                              Hi Kate,

                              thanks for your answer. I think I understood the problem.

                              I found out that the orders are not cancelled when placed manually, for example, via the chart trader. This is in line with the definition of "Wait until Flat" is doing.

                              What I have done, to avoid adding more orders (in quantity) than needed, is to CancelAllOrders for my account for that instrument. In that way I am sure there is no order placed even if it's a bit drastic solution.

                              Do you have any other suggestion?

                              Thanks for your time and sorry for the drawback.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Haiasi, 04-25-2024, 06:53 PM
                              2 responses
                              16 views
                              0 likes
                              Last Post Massinisa  
                              Started by Creamers, Today, 05:32 AM
                              0 responses
                              4 views
                              0 likes
                              Last Post Creamers  
                              Started by Segwin, 05-07-2018, 02:15 PM
                              12 responses
                              1,785 views
                              0 likes
                              Last Post Leafcutter  
                              Started by poplagelu, Today, 05:00 AM
                              0 responses
                              3 views
                              0 likes
                              Last Post poplagelu  
                              Started by fx.practic, 10-15-2013, 12:53 AM
                              5 responses
                              5,407 views
                              0 likes
                              Last Post Bidder
                              by Bidder
                               
                              Working...
                              X