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

How to cancel a manual order but not in a strategy class

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

    How to cancel a manual order but not in a strategy class

    I am doing a method to make the left click safe from mistakes of Limit orders in the money in the DOM sell or buy columns. I can identify the bad order at OrderState.Initialized before it is submitted and correct it in code to a StopLimit order.

    I cannot figure out how to cancel or modify the bad order unless called from a strategy addon. But this call has to come from a SuperDOM add on.

    Code:
    void AutoCorrectManualLimitOrderInadvertentlyPlacedInTheMoneyInTheSuperDOM()
    {
    	[COLOR="SeaGreen"]//code simplified in anonymous event handlers; try-catch blocks omitted;[/COLOR]
    	Account myAccount = Account.All.FirstOrDefault(a => a.Name == "Sim101");
    	int slippage = 2;
    
    	myAccount.OrderUpdate += (o, e) =>
    	{
    		if (e == null)
    			return;
    
    		bool isInadvertentLimitOrder = 
    		(
    			(e.Order.OrderEntry == OrderEntry.Manual) &&
    			(e.Order.OrderType == OrderType.Limit) &&
    			(e.Order.LimitPrice > 0) &&
    			(e.Order.LimitPrice != e.Order.StopPrice) &&
    			(
    				(
    					(e.Order.OrderAction == OrderAction.Buy) &&
    					(e.Order.Instrument.MarketData.Last.Ask > 0) &&
    					(e.Order.LimitPrice > (e.Order.Instrument.MarketData.Last.Ask + slippage * e.Order.Instrument.MasterInstrument.TickSize))
    				)
    				||
    				(
    					(e.Order.OrderAction == OrderAction.Sell) &&
    					(e.Order.Instrument.MarketData.Last.Bid > 0) &&
    					(e.Order.LimitPrice < (e.Order.Instrument.MarketData.Last.Bid - slippage * e.Order.Instrument.MasterInstrument.TickSize))
    				)
    			)
    		);
    
    		//there is still time to intercept the order before it is submitted
    		if ((e.OrderState == OrderState.Initialized) && (e.Order.Filled==0))
    		{
    			if (isInadvertentLimitOrder) {
    				Dispatcher.InvokeAsync(() =>
    				{
    					[COLOR="SeaGreen"][B]//How can the inadvertent order be cancelled or modified?
    					//CancelOrder() is a method only of the Strategies.Strategy class
    					//but I want to cancel a MANUAL order[/B][/COLOR]
    					myAccount.Submit(new[] { myAccount.CreateOrder (
    						e.Order.Instrument, 
    						e.Order.OrderAction,
    						OrderType.StopLimit, // only this param changed from OrderType.Limit
    						e.Order.OrderEntry,
    						e.Order.TimeInForce,
    						e.Order.Quantity,
    						e.Order.LimitPrice,
    						e.Order.StopPrice,
    						e.Order.Oco,
    						e.Order.Name,
    						e.Order.Gtd,
    						null
    					)});
    				});
    			}
    		}
    	};
    }
    Last edited by xcondor; 04-09-2018, 11:09 AM.

    #2
    Hello xcondor,

    Thanks for opening the thread.

    It is possible to cancel account orders from an AddOn with the Account.Cancel() method.

    Code:
    myAccount.Cancel(new[] {e.Order});
    Account.Cancel - https://ninjatrader.com/support/help...-us/cancel.htm

    In my tests in an AddOn subscribing to OrderUpdate events, when I submit a sell limit order beneath the market price, I receive a rejection when I try to "intercept" this order stating the order status is CancelPending. The order gets cancelled and the new order does submit. Overriding order submissions this way works, but may not be ideal without having full control over the components that submit these orders.

    If there is anything else we can do to help, please let us know.
    JimNinjaTrader Customer Service

    Comment


      #3
      Thanks abunch Jim. I must have missed that.
      Originally posted by NinjaTrader_Jim View Post
      In my tests in an AddOn subscribing to OrderUpdate events, when I submit a sell limit order beneath the market price, I receive a rejection when I try to "intercept" this order stating the order status is CancelPending. The order gets cancelled and the new order does submit.
      I am glad you brought that up. The Help Guide says that OrderState.CancelPending is still in NT. But OrderState.Cancelled comes from the exchange presumably for an order that previously did get submitted.

      In this case is OrderState.CancelPending the end of it?

      OrderState.Rejected is not documented who the rejection comes from. I am trying to do the same "interception" auto-correction with StopLimits out of the money. The rejection msg box is real annoying, steals my mouse, requires an extra click and causes a delay. My code must beat the platform before it rejects the order. I doubt I'll succeed. Do you have a suggestion how to prevent these notifications?

      Originally posted by NinjaTrader_Jim View Post
      Overriding order submissions this way works, but may not be ideal without having full control over the components that submit these orders.
      I agree but what choice do we have for this key protection? A middle mouse click is just not intuitive enough. So I get into many unintended trades.

      Why does not the platform offer this auto-rejection as a user preference?

      This is the best way to guarantee that it will be done right, not us hacking into the GUI half blind all the time. I am surprised after 15 years this platform is pretty mature, yet this key feature is not there.

      Comment


        #4
        Hello xcondor,

        For the CancelPending, we see this after the SuperDOM submits an order, it gets captured in the OrderUpdate event, cancelled, and then the SuperDOM attempts to process this order further. The order is terminal at this point.

        Intercepting orders isn't exactly a supported item, and we wouldn't be able to give further direction for suppressing the generated warning messages from taking this approach.

        A feature to change the order submission behaviors was considered previously but it was deemed that modifying this behavior would go against what the user would expect. We are still tracking interest to change this behavior for submitting orders on the other side of the market so they can be auto corrected. I'll submit a vote on your behalf.

        The ticket ID is SFT-535. As with other feature requests, we cannot present an ETA as they are fulfilled based on the development team's schedule and priorities. Upon implementation the ticket ID can be found publicly on the Release Notes page of the help guide. I'll provide a link below.

        Release Notes: https://ninjatrader.com/support/help...ease_notes.htm

        This behavior could still be implemented in a custom Order Submission window to achieve the desired result.

        If there is anything else I can do to help, please let me know.
        Last edited by NinjaTrader_Jim; 04-10-2018, 08:51 AM.
        JimNinjaTrader Customer Service

        Comment


          #5
          Originally posted by NinjaTrader_Jim View Post
          A feature to change the order submission behaviors was considered previously but it was deemed that modifying this behavior would go against what the user would expect.
          That is what preferences are for — to let the user decide. What's the big deal if a few lines of code get it done, and much more predictably than my hack.

          MultiCharts and many brokers greatly emphasize this auto-detect feature and rightly poo-poo other platforms that do not offer it. I absolutely agree with Johnny Khek from AMP Futures:
          see 3:09 to 5:09
          https://www.youtube.com/watch?v=hJBo...nel=AMPFutures

          If I couldn't code and could not implement it myself, the lack of this feature would be a deal breaker for me and many others I know. But we shouldn't have to hack for such basic functionality. So maybe try to escalate its dev priority. SFT-535

          Another quick fix is to just change the confirmation suppression option from being global to more granular set of checkboxes for each order type and scenarios like this — Limits in the money and StopLimits out of the money. I know non-developers do not understand what goes into code changes but this feature is so fundamental. Just my $0.02.

          Thanks
          Last edited by xcondor; 04-09-2018, 04:17 PM.

          Comment


            #6
            OrderType auto-correction related feature requests

            Originally posted by NinjaTrader_Jim View Post
            A feature to change the order submission behaviors was considered previously but it was deemed that modifying this behavior would go against what the user would expect. We are still tracking interest so a power user option could be used to change this rejection behavior for submitting orders on the other side of the market. I'll submit a vote on your behalf.

            The ticket ID is SFT-535.
            The market was moving yesterday and I did not have time to reflect that you misunderstood my feature request. I cannot find ticket SFT-535 to compare it to.

            Originally posted by NinjaTrader_Jim View Post
            This behavior could still be implemented in a custom Order Submission window to achieve the desired result.
            I absolutely do not propose to globally change the order submission behaviors. If the submission originated from any order entry dialog like the Order Ticket window, where the user first explicitly sets all params of the order, and then clicks some static button like "Buy" or "Sell" to submit, then let that baby rip as is. The user is responsible to understand what she is explicitly submitting. I am making a feature request to add validation messages for newbies to the Order Ticket Window and a property preference to suppress validation for expert users. I never use this window. So I don't care if this feature request is implemented but validation is always a good idea in form entry windows.

            My issue is specifically with orders initiated by unconfirmed single click inside the SuperDOM buy or sell columns.
            So it is rather a GUI related request for the click handler to implement the OrderType modification only if auto-correction mode is the user's preference.

            However, I could not externally hook into the Click event (or even better, public BeforeMouseDown event if one such existed) for real estate inside the SuperDOM buy and sell columns and implement the auto correcting logic there and ONLY there.

            So my workaround is unfortunately to access the orders much higher up in scope by hooking into the MyAccount.OrderUpdate event for all orders in the account. This is exactly what I am not proposing because this almost global scope for changing the order submission behavior is way too wide and prone to all sorts of undesired results.

            To clarify this point I am actually making another feature request which has exactly this use case to in mind — add a few more items to the OrderEntry enum like:

            Code:
            OrderEntry.[B]ManualSuperDOMBuyColumn[/B]
            OrderEntry.[B]ManualSuperDOMSellColumn[/B]
            Then I could limit the scope of the behavior:
            Code:
            void OnOrderUpdate(object sender, OrderEventArgs e){
                  If(e.Order.OrderEntry == OrderEntry.[B]ManualSuperDOMBuyColumn[/B]){
                       //code to modify the OrderType here
                  }
            }
            To prevent breaking existing code a new enum as an added property to the OrderEventArgs class would probably be better. For example:
            Code:
            public enum ManualOrderEntryOrigin {
                 OrderTicketButton=1,
                 SuperDOMBuyColumn=2,
                 SuperDOMSellColumn=3
                 //etc 
            }
            Then just add overloads to a few methods like CreateOrder()

            If the discussion for ticket SFT-535 does not consider changes much more limited in scope like I describe, then should I post new feature request in the forum?
            Last edited by xcondor; 04-10-2018, 09:23 AM.

            Comment


              #7
              Hello xcondor,

              Feature Request ticket ID's are internal tickets that we report back to our clients and note in our help guide when a feature gets implemented in a new release. We do not have an external feature request system.

              SFT-535 has a general aim to be able to change the behavior for submitting orders so they can be auto-corrected. It does not suggest changing the behavior all together and only serves to track interest in the ability to auto correct orders. I've updated my previous message to be clearer. This thread is also included in the ticket so your feedback can be referenced by the development team.

              So I understand correctly, you want me to submit 2 more feature requests?

              The first would be to add order confirmations to the Order Ticket window. There is already an Order Confirmations feature implemented in NinjaTrader that is on by default and can be disabled in the options menu. Are requesting an additional check for order confirmations in the Order Ticket Window?

              The second would be to create a supported way to override order submissions from NinjaTrader's Order Submission Windows through NinjaScript? The OrderEntry enum is specifically for AddOn's so you can specify to the broker that the orders are automated or manual submissions. I am confident that SFT-535 will aim to satisfy your end goal, but if you would like, we can also request that a supported approach for overriding order submissions.

              Please let me know how I can assist you further.
              JimNinjaTrader Customer Service

              Comment


                #8
                Crucial importance of Auto-Correction of Limit Orders in the money

                Originally posted by NinjaTrader_Jim View Post
                So I understand correctly, you want me to submit 2 more feature requests?

                The first would be to add order confirmations to the Order Ticket window. There is already an Order Confirmations feature implemented in NinjaTrader that is on by default and can be disabled in the options menu. Are requesting an additional check for order confirmations in the Order Ticket Window?
                Actually, I was requesting validation at the time of input, whereas a confirmation occurs after the attempt to submit the order. But I do not want to hijack this thread. So, I posted separate feature request threads here:

                https://ninjatrader.com/support/foru...190#post538190
                https://ninjatrader.com/support/foru...186#post538186
                You can assign whatever internal ticket reference is necessary.

                Originally posted by NinjaTrader_Jim View Post
                The second would be to create a supported way to override order submissions from NinjaTrader's Order Submission Windows through NinjaScript?
                Yes. But my original request was to implement native auto-correct logic and preference out of the box.

                I had to mess with a NinjaScript workaround only because this essential feature is not offered. And for that project, my suggestions were to add an overload to the CreateOrder and Account.Cancel() method with more parameters that specify the origin of the order and correspondingly more properties to the OrderEventArgs class and an enum for strongly typed coding of these params in an OnOrderUpdate event handler that consumes the OrderEventArgs argument.

                The SuperDOM Buy and Sell columns are vastly different from all the other form-like or worksheet like order submission windows. NinjaScript really needs a way to specify and differentiate those orders for the reasons debated in this thread, but in general because the orders in those columns are usually initiated by single click, in the heat of the battle, often for scalping, so there are many of them, and often would present the highest amount of human errors. So I can think of several more routines to prevent such errors besides the use case in this thread.

                It bothered me that so many people have been requesting this feature for the past 15 years and your response made me think the Dev Team maybe misunderstood their requests. There was another thread on exactly the same topic:
                https://ninjatrader.com/support/foru...ead.php?t=9170
                Originally posted by NinjaTrader_Jessica View Post
                This is because limit orders can be placed above the Market they just become what are referred to as a marketable Limit orders. It is a valid order type and therefore would not trigger an error.
                So is chewing on razor blades. But it is bad for one's health. It does not mean the platform should not provide protection against such stupid behavior. There is absolutely no reason why any trader would EVER intentionally buy limit above market.

                I trade in size and this could be disastrous. It happens to me most often when I try to move an existing target for which I have to left click to move it, but I forget to click only in the price column. And boom! Instead of moving my target I am in a whole new trade.eek! s**t!

                And the PnL PositionDisplay control does not even show it because it calculates only from the point of entry but the mistake occurred before the position started. To add salt to the wound, if the market was moving in the same direction, the PnL even shows profit when, in fact, it's 20+ ticks loss already locked as realized.

                If there was auto-correction from Limit to StopLimit, I would still have a new order submitted but there is still time to remove the unintentional new StopLimit order because, by definition, a StopLimit is away from the market and plenty of time to cancel it. No harm done. Except some annoyance. Intercepting it with a confirmation reduce that further. But not making me suffer with confirmations for everything else with that unusable global confirmation preference.

                I hope the Dev Team takes these requests seriously. It's a huge shortcoming. It is high time this feature got some attention.

                Thank a bunch

                Comment


                  #9
                  Hello xcondor,

                  Your original request is being tracked with SFT-535.

                  I've added a new feature request for a supported means to intercept and change orders submitted from NinjaTrader order submission windows. This ticket ID is SFT-3149.

                  As a reminder, we cannot offer an ETA or promise of fulfillment as feature requests are implemented based on our development teams tasks and priorities. Once implemented, you can reference this ticket number in the Release Notes of the version of NinjaTrader 8 that includes this feature.

                  Release Notes can be found here: https://ninjatrader.com/support/help...ease_notes.htm

                  We will handle the other feature requests in those threads that you have opened.

                  If there is anything else we can do to assist, please let us know.
                  JimNinjaTrader Customer Service

                  Comment


                    #10
                    legal considerations for auto-correction

                    Reply to post from another thread the topic of which belongs to this thread.
                    https://ninjatrader.com/support/foru...258#post538258

                    Originally posted by NinjaTrader_PatrickG View Post
                    I suppose one thing I didn't consider in that feature request is having the platform choose when an order is a good idea or not. At that point, we're toeing the line of trading advice (which would be very illegal for the platform to provide),
                    Patrick, your concern is absolutely unfounded. Based on that logic, all the AtmStrategy features are way more intrusive "trading advice" than this Auto Correction would ever be. But even if there was a shred of basis, the explicit opt-out extinguishes any such concerns. All the platform needs to protect itself is to leave it unchecked by default. It is the user who chooses how to trade when she opts in and checks that feature explicitly. Not even an update to the EULA is needed. But don't take my word for it. NinjaTrader has counsel who will tell you the same.

                    Several other leading platforms have had this feature for years and I know of no lawsuit being brought over it.

                    Comment


                      #11
                      It's important to provide the rest of my statement which immediately followed the quote you pulled for more context:
                      Originally posted by NinjaTrader_PatrickG View Post
                      However, off the top of my head I know that Chart Trader prevents you from submitting a buy limit order on the 'wrong side' of the market, so why couldn't other order entry windows provide the same? This is what I'll be forwarding to the Development Team along with the entire text you've provided.

                      I'll update this post when I receive a tracking number. EDIT - the tracking number is SFT-3153

                      Comment


                        #12
                        Originally posted by NinjaTrader_PatrickG View Post
                        It's important to provide the rest of my statement which immediately followed the quote you pulled for more context:
                        I did not mean to misquote you. You are right. This sure is one instance demonstrating the feature is already at least partly implemented, unfortunately not where it matters the most.

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by Perr0Grande, Today, 08:16 PM
                        0 responses
                        2 views
                        0 likes
                        Last Post Perr0Grande  
                        Started by elderan, Today, 08:03 PM
                        0 responses
                        4 views
                        0 likes
                        Last Post elderan
                        by elderan
                         
                        Started by algospoke, Today, 06:40 PM
                        0 responses
                        10 views
                        0 likes
                        Last Post algospoke  
                        Started by maybeimnotrader, Today, 05:46 PM
                        0 responses
                        9 views
                        0 likes
                        Last Post maybeimnotrader  
                        Started by quantismo, Today, 05:13 PM
                        0 responses
                        7 views
                        0 likes
                        Last Post quantismo  
                        Working...
                        X