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

enforce self discipline -- Flatten inside AddOn

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

    enforce self discipline -- Flatten inside AddOn

    I scalp ES and NQ. Primarily NQ.

    Sometimes the ES chart has focus and I accidently place a trade there (with a hot key) when I really wanted to place it on NQ, which does not have the focus.

    So, I would like an AddOn that immediately Flattens any trade on any chart, that does not match my intended Instrument (NQ). I will be able to change the intended instrument with a toggle.

    I could make an indicator to do this, but then I would have to put it on each trader chart.

    I would like to use an AddOn, but the Flatten command is just for one Account

    How can I Flatten one account / instrument with an AddOn

    I am using OnOrderUpdate to get the Account and Instrument from the Order object...

    When an order is placed that I did not intend I want to flatten it right away, and if there is already a position, flatten that too.

    Thx


    (yes, I can disable Chart Trader, but I would prefer this idea...I'll toggle the enabled Instrument with a button)


    #2
    Hello llanqui,

    Thank you for your post.

    Whether you are using an AddOn or an Indicator, this would be done via the Account class:


    You would set the desired conditions (such as checking for order objects in OnOrderUpdate() and gathering that information) then you could call Account.Flatten() for the desired account/instruments:


    Please let us know if we may be of further assistance.
    Emily C.NinjaTrader Customer Service

    Comment


      #3
      Ok, I have the code working...

      have this question

      I have the Account.Flatten inside the OnOrderUpdate()....but perhaps that is not best?

      this is in an AddOn

      I've tried to use TriggerCustomEvent or Dispatcher.InvokeAsynch to to the Flatten....but it won't compile...not available in the namespace?

      what do you suggest?

      Comment


        #4
        Hello llanqui,

        Thank you for your reply.

        What is the full text of the "not available in the namespace" error?

        If you are flattening a list of instruments as shown in the second example on the Flatten() help guide page, you will need to add the using statement as shown in the code comments. Here is that second example:
        Code:
        // Please note that your 'Using declarations' section needs to have
        //
        // using System.Collections.ObjectModel;
        //
        // added in order for this example to compile correctly
        
        
        
        // instantiate a list of instruments
        Collection<Cbi.Instrument> instrumentsToClose = new Collection<Instrument>();        
        
        // add instruments to the collection
        instrumentsToClose.Add(Instrument.GetInstrument("AAPL"));        
        instrumentsToClose.Add(Instrument.GetInstrument("MSFT"));
        
        // pass the instrument collection to the Flatten() method to be flattened
        Account.Flatten(instrumentsToClose);
        ​
        If this is similar to what you are trying to do, please be sure to add using System.Collections.ObjectModel; to your using statements at the top of the script.

        Please let me know if I may be of further assistance.
        Emily C.NinjaTrader Customer Service

        Comment


          #5
          I'm using this....it does not give me a compile error


          e.Order.Account.Flatten (new [] { e.Order.Instrument });

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

          I use this

          using System.Collections.ObjectModel​

          using System.Windows.Threading; // for dispatcher

          Dispatcher.InvokeAsync((Action)(() =>
          {
          e.Order.Account.Flatten (new [] { e.Order.Instrument });
          }));​

          and get a compile error --
          An object reference is required for the non-static field, method, or property 'System.Windows.Threading.Dispatcher.InvokeAsync(S ystem.Action)'

          ​---------------------------------------------------------------------------------------------------------------------------------

          TriggerCustomEvent (doit);
          The name 'TriggerCustomEvent' does not exist in the current context

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

          CancelOrder also gives me a compile error -- does not exist in the current context

          Attached Files

          Comment


            #6
            Originally posted by llanqui View Post
            I'm using this....it does not give me a compile error


            e.Order.Account.Flatten (new [] { e.Order.Instrument });

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

            I use this

            using System.Collections.ObjectModel​

            using System.Windows.Threading; // for dispatcher

            Dispatcher.InvokeAsync((Action)(() =>
            {
            e.Order.Account.Flatten (new [] { e.Order.Instrument });
            }));​

            and get a compile error --
            An object reference is required for the non-static field, method, or property 'System.Windows.Threading.Dispatcher.InvokeAsync(S ystem.Action)'

            ​---------------------------------------------------------------------------------------------------------------------------------

            TriggerCustomEvent (doit);
            The name 'TriggerCustomEvent' does not exist in the current context

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

            CancelOrder also gives me a compile error -- does not exist in the current context

            Where are you using TriggerCustomEvent() in your script? This is not shown in your snippet. We have a page about multi-threading consideration for NinjaScript here:
            https://ninjatrader.com/support/help...-threading.htm

            I look forward to assisting you further.
            Last edited by NinjaTrader_Emily; 10-17-2023, 10:47 AM.
            Emily C.NinjaTrader Customer Service

            Comment


              #7
              Hello llanqui,

              Thanks for your patience.

              I would like to add additional context. You should not need a dispatcher or TriggerCustomEvent for the use of Account.Flatten(). I do not understand why you are trying to use one or both of these in your script. Ultimately, blocking orders from being placed starts to teeter into the realm of unsupported items; our support team is not able to offer assistance with any items that would block the basic functionality of the platform, such as placing orders. I won't be able to provide an example of exactly what you are looking for, though as you said the following line compiles without errors:
              Code:
              e.Order.Account.Flatten (new [] { e.Order.Instrument });
              I understand your initial issue is caused by having the wrong window in focus when using order entry hotkeys. You could consider enabling order confirmation to get a pop-up window prior to submitting an order. This would add an extra key press to confirm/deny an order, though it offers an extra step that allows you to double-check that your hot keys are sending orders to the desired instrument. "Confirm order placement" may be toggled at Control Center > Tools > Options > Trading:
              https://ninjatrader.com/support/help...ns_trading.htm

              Another option would be to disable order entry hot keys in that same Tools > Options > Trading window and instead use an indicator to detect key presses and perform order actions based on which keys are pressed. You could then apply this indicator only to charts where you wish to use your custom order entry key presses. If that particular chart with the indicator applied doesn't have the focus, no orders will be placed when you press the keys. This could prevent the scenario where you accidentally place orders by using hot keys while the wrong window is in focus. The following forum post has some helpful information related to detecting key presses and also how to submit orders from the Account class in an indicator:
              https://forum.ninjatrader.com/forum/...78#post1137778

              Edit to add the following:
              I understand you mentioned "I could make an indicator to do this, but then I would have to put it on each trader chart." With that in mind, you could consider having whichever charts open that you'd like to view data, indicators, etc for yet keep chart trader disabled on those windows. Then, only have one window open with a chart and Chart Trader enabled. You could open a new tab for each instrument that you'd like to trade with hot keys, then use the keyboard shortcut of CTRL + Tab to toggle between the different tabs in that chart window to select the tab of the desired instrument for hot key order placement. If that particular window does not have focus, the other charts should not result in trades from hot keys because they do not have chart trader enabled.

              Please let us know if we may be of further assistance.
              Last edited by NinjaTrader_Emily; 10-17-2023, 11:01 AM.
              Emily C.NinjaTrader Customer Service

              Comment


                #8
                Ok, it seems that if I can Flatten inside of OnOrderUpdate that this will be OK. I just didn't want to break any internals.

                The reason I wanted to use Dispatcher or TriggerCustomEvent was to move the Flatten outside of the OnOrderUpdate and execute it asychronsously, thinking this might be better


                This is how I need to implement it....because I'm a scalper and pressing / navigating multiple confirmations does not work for my trading style

                so, any error like what I mention needs to be fixed immediately, in milliseconds ... and Flatten is the correct method...because it totally sets the instrument to no positions and no orders

                Comment


                  #9
                  I've attached the code...

                  the statement if (e.Order.Instrument.MasterInstrument.Name != Common.InstrumentEnabledForTrading.ToString())

                  is comparing the order Instrument to a public/global Enum that is converted to a string... for example "NQ" or "ES"

                  I have two ways to place orders.

                  for an order at a fixed price I use Submit in Ninjascript

                  for "jump in" orders, Buy Ask, Sell Bid, I use Ninja Hot Key order entry.

                  when I use Submit in Ninjascript I get a pop up error message (order can't be submitted because order status is CanclePending). I have to manually clear/ close the popup.

                  when I submit via a Ninja Hotkey, there is no popup, and the order is cancelled, but Ninja does not take the cancellation to the final state. There remains on the chart an Orange Order and in the Order Tab on the Control Center, the order remains in a light blue "Cancel Pending" status.

                  this I tested in Sim mode, probably it is the same on a live account (didn't want to waste the ticks to test it there).

                  the only way this clears is to reset the SIM account, even across multiple logins...

                  The first problem is just a reminder to me that I placed a trade on the wrong chart (ie. a different chart had focus than what I thought)

                  (the mouse cursor can be on the correct chart but that does not mean it has focus)

                  The second problem I would like to solve....so that my charts and order tab don't have these cancelled orders, is there something I can do to fix this, so that Ninja brings the order to a completed (ie. finished) state?

                  thx


                  Attached Files

                  Comment


                    #10
                    also the print statement does not work inside the onorderupdate

                    Comment


                      #11
                      Hello Ilanqui,

                      Thank you for your reply.

                      What are the results if you add the following as the first line inside of OnOrderUpdate()? I would expect this print statement to work in OnOrderUpdate() without issues.
                      Code:
                      Print("OnOrderUpdate triggered + " + e.Order.ToString());
                      You may be getting errors and orders in a state of cancel pending if you are attempting to cancel them before they are in an active/working state. It seems that you are just detecting the instrument name from the order update and if it is not one of your instruments for trading, you are calling Account.Flatten. You could instead consider calling Cancel() to cancel an order if it is in a working/accepted state or, in the case that it is a market order which likely wouldn't be able to cancel and instead would get filled, you could detect if there is an open position on the account for one of the undesired instruments and in that case call Account.Flatten() to flatten the open position.

                      As I previously mentioned, our support team is not able to offer assistance with any items that would block the basic functionality of the platform, such as placing orders. Ultimately, if you require further assistance from here, this thread is open to the forum community if they would like to assist you or you could consider reaching out to a third-party programmer for assistance with your script.

                      Thank you for using NinjaTrader.
                      Emily C.NinjaTrader Customer Service

                      Comment


                        #12
                        yes, that is why I use Flatten, to cancel a position also if by chance the order was filled....

                        Comment


                          #13
                          Originally posted by llanqui View Post
                          yes, that is why I use Flatten, to cancel a position also if by chance the order was filled....
                          If you attempt to cancel an order while it is still only in a "Submitted" state, the order could become stuck in the database. You should check for the order state and only attempt to flatten/cancel if the order is in a working/accepted state. This has been discussed in the following thread:
                          I have a strategy running in unmanaged mode. On occasion, the order state on an order which is being cancelled gets stuck at &quot;Cancelled Pending&quot;. If I look at the orders tab in the control center that status of the order stays at &quot;Cancelled Pending&quot;. When I disconnect the connection and reconnected the order


                          Please let us know if we may be of further assistance.
                          Emily C.NinjaTrader Customer Service

                          Comment


                            #14
                            Ok I issue a Cancel then a Flatten and now don't have the phantom orders hanging around after....just the pop up, which is ok

                            and I get output with this

                            NinjaTrader.Code.Output.Process(msg, PrintTo.OutputTab1);

                            Comment


                              #15
                              this works, so far no popups or hanging orders
                              Attached Files

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Balage0922, Today, 07:38 AM
                              0 responses
                              5 views
                              0 likes
                              Last Post Balage0922  
                              Started by JoMoon2024, Today, 06:56 AM
                              0 responses
                              6 views
                              0 likes
                              Last Post JoMoon2024  
                              Started by Haiasi, 04-25-2024, 06:53 PM
                              2 responses
                              19 views
                              0 likes
                              Last Post Massinisa  
                              Started by Creamers, Today, 05:32 AM
                              0 responses
                              6 views
                              0 likes
                              Last Post Creamers  
                              Started by Segwin, 05-07-2018, 02:15 PM
                              12 responses
                              1,786 views
                              0 likes
                              Last Post Leafcutter  
                              Working...
                              X