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

Set QuantityUpDown value from keyboard

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

    Set QuantityUpDown value from keyboard

    Hello.
    I add QuantityUpDown on ChartWindow.MainMenu.
    Up \ down arrows input work great.
    But when I select the text element and try to edit it using keyboard, if I type any key NT takes over and thinks I'm trying to load a new data series or Instrument.

    I found this thread, but can't imagine nothing working: http://ninjatrader.com/support/forum...QuantityUpDown

    For example, this way not work properly:
    PHP Code:
    private void On_Quantity_Selector_KeyDown(object senderKeyEventArgs e)
    {
        
    e.Handled true;
        
    NinjaTrader.Gui.Tools.QuantityUpDown qs sender as NinjaTrader.Gui.Tools.QuantityUpDown;
                
        if( 
    e.Key >= Key.D0 && e.Key <= Key.D9qs.Content = (string)qs.Content e.Key;



    What is the right way?
    May be, just need to invoke base event handler? But how to do it?
    Last edited by fx.practic; 09-04-2017, 02:28 AM.
    fx.practic
    NinjaTrader Ecosystem Vendor - fx.practic

    #2
    Hello,

    Thank you for the post.

    What you have now would mostly work if you were using the PreviewKeyDown event rather than just the KeyDown event.

    Here is a simple example, this would only work for values 0-9, anything over this would require that you form some logic to combine input into a correct number value. This control does not take a string so you will need to use logic to form an int:


    Code:
    myQuantityUpDown.PreviewKeyDown += (o, e) =>
    {
    	if ((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
    	{
    		e.Handled = true;
    		string number = e.Key.ToString();
    		number =  number.Replace("NumPad", "");
    		number = number.Replace("D", "");
    		int num = int.Parse(number);
    		NinjaTrader.Gui.Tools.QuantityUpDown qs = o as NinjaTrader.Gui.Tools.QuantityUpDown;
    		if (qs != null) qs.Value = num;
    	}
    };


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

    Comment


      #3
      Hello _Jesse thank you for the code. i just added it to my script and it works fine. however, i wonder what the code should look like if instead of just one number, you enter several numbers in a row? unfortunately only single-digit numbers are possible.
      sidlercom80
      NinjaTrader Ecosystem Vendor - Sidi Trading

      Comment


        #4
        Hello sidlercom80,

        That would be difficult to do with this control. You could potentially append the strings together to parse a new value but this control is a int value so you could not enter 01 as an example it would just parse as 1. You could in theory enter other values like 10 which would parse as 10. This would likely be fairly buggy and would require adding more conditions to handle the specific entries you needed.

        I don't have a script offhand to test this with but the idea would be if the box started with a value and you typed a 1 it would take the existing string and 1 string and combine them to form a new value.

        Code:
        string number = "1";
        string newVal = "2;
        int num = int.Parse(number + newVal);  // comes out to 12
        or

        Code:
        string number= qs.Value.ToString();
        string newVal= e.Key.ToString();
        newVal =  number.Replace("NumPad", "");
        newVal = number.Replace("D", "");
        
        int num = int.Parse(number + newVal);
        You would have to handle other keys like delete or backspace and I am unsure if the cursor would be able to work with this use case. If you need a entry which supports more than one number a text entry may be a better choice however that would not have the numeric up/down.

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

        Comment


          #5
          thank you _Jesse for your answer. I've solved it this way:

          Code:
           
           spQtySelector1.PreviewKeyDown += (o, e) =>         {             if (e.Key == Key.Delete || e.Key == Key.Back)             {                 e.Handled = true;                 spQtySelector1.Value = 0;                   if (PrintDetails)                     Print(DateTime.Now + " PositionSize1 changed to " + spQtySelector1.Value);             }             if ((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))             {                 e.Handled = true;                 string number = e.Key.ToString();                 string newnumber = spQtySelector1.Value.ToString();                 number = number.Replace("NumPad", "");                 number = number.Replace("D", "");                 int num = int.Parse(newnumber + number);                 spQtySelector1.Value = num;                   if (PrintDetails)                     Print(DateTime.Now + " PositionSize1 changed to " + spQtySelector1.Value);             }         };
          Attached Files
          Last edited by sidlercom80; 04-02-2020, 05:09 AM.
          sidlercom80
          NinjaTrader Ecosystem Vendor - Sidi Trading

          Comment


            #6
            Originally posted by NinjaTrader_Jesse View Post
            Hello sidlercom80,

            That would be difficult to do with this control. You could potentially append the strings together to parse a new value but this control is a int value so you could not enter 01 as an example it would just parse as 1. You could in theory enter other values like 10 which would parse as 10. This would likely be fairly buggy and would require adding more conditions to handle the specific entries you needed.

            I don't have a script offhand to test this with but the idea would be if the box started with a value and you typed a 1 it would take the existing string and 1 string and combine them to form a new value.

            Code:
            string number = "1";
            string newVal = "2;
            int num = int.Parse(number + newVal); // comes out to 12
            or

            Code:
            string number= qs.Value.ToString();
            string newVal= e.Key.ToString();
            newVal = number.Replace("NumPad", "");
            newVal = number.Replace("D", "");
            
            int num = int.Parse(number + newVal);
            You would have to handle other keys like delete or backspace and I am unsure if the cursor would be able to work with this use case. If you need a entry which supports more than one number a text entry may be a better choice however that would not have the numeric up/down.

            I look forward to being of further assistance.
            Hello Jesse.
            What will be the best way to type digits anywhere inside a string?
            Not at the end only.
            I believe we need some cursor position index to create substrings.
            But I couldn't find any related parameter for QuantityUpDown control.

            Comment


              #7
              Hello rare312,

              Unfortunately I am not aware of a way to control that with the given control. That would very likely need to be implemented into the control its self, to make the control work in that way in general. I am not certain the preview key events would be able to be used in that use case. You could try research controlling the cursor in a standard WPF textbox as a starting point, you could then try applying that to the NinjaTrader control to see if a similar situation can be accomplished.

              Please let me know if I may be of further assistance.

              JesseNinjaTrader Customer Service

              Comment


                #8
                Originally posted by NinjaTrader_Jesse View Post
                Hello,

                Thank you for the post.

                What you have now would mostly work if you were using the PreviewKeyDown event rather than just the KeyDown event.

                Here is a simple example, this would only work for values 0-9, anything over this would require that you form some logic to combine input into a correct number value. This control does not take a string so you will need to use logic to form an int:


                Code:
                myQuantityUpDown.PreviewKeyDown += (o, e) =>
                {
                if ((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
                {
                e.Handled = true;
                string number = e.Key.ToString();
                number = number.Replace("NumPad", "");
                number = number.Replace("D", "");
                int num = int.Parse(number);
                NinjaTrader.Gui.Tools.QuantityUpDown qs = o as NinjaTrader.Gui.Tools.QuantityUpDown;
                if (qs != null) qs.Value = num;
                }
                };


                I look forward to being of further assistance.

                Hello Jesse, I've completed your hardcoded quantity solution successfully to related thread ( https://ninjatrader.com/support/foru...26#post1189426 ) with shared app
                https://ninjatraderecosystem.com/use...ellmkthotkeys/

                I've got some questions about the advanced method you showed above.
                Can you please explain how you went from

                PHP Code:
                private void On_Quantity_Selector_KeyDown(object senderKeyEventArgs e)
                {
                    
                e.Handled true;
                    
                NinjaTrader.Gui.Tools.QuantityUpDown qs send er as NinjaTrader.Gui.Tools.QuantityUpDown;

                    if( 
                e.Key >= Key.D0 && e.Key <= Key.D9qs.Con tent = (string)qs.Content e.Key;


                to (Taking the expanded version from fx.practice below (post #5)
                PHP Code:
                     myQuantityUpDown.PreviewKeyDown += (oe) =>
                     {
                          if (
                e.Key == Key.Delete || e.Key == Key.Back)
                          {
                               
                e.Handled true;
                               
                spQtySelector1.Value 0;

                          }

                          if ((
                e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
                          {
                               
                e.Handled true;

                               
                string number e.Key.ToString();
                               
                string newnumber myQuantityUpDown.Value.ToString();
                               
                number number.Replace("NumPad""");
                               
                number number.Replace("D""");
                               
                int num int.Parse(newnumber number);
                               
                myQuantityUpDown.Value num;
                               
                NinjaTrader.Gui.Tools.QuantityUpDown qs as NinjaTrader.Gui.Tools.QuantityUpDown;
                               if (
                qs != nullqs.Value num;

                          }
                     }; 

                It is the first time I see that structure and I'm not sure what to make of it.

                I understand the functional part of the code:
                Delete or Back key pressed sets the Quantity to zero.
                0-9 (main keys or numpad keys) single key or double keys sets the quantity to the typed number.

                But I don't understand the use of myQuantityUpDown/spQtySelector1. What does it come from? A custom class or something else?


                From comparisons to snippets #1 and #2 below, here's what I've tried to reconstruct from it (with no compile errors).
                From snippet #2 example, I added a variable (private QuantityUpDown myQuantityUpDown; ) to assign the "myQuantityUpDown" "method" to.
                And i embedded it in the private void On_Quantity_Selector_PreviewKeyDown(object sender, KeyEventArgs e){} method (to test if that was what was needed).
                But it seem to be an unusual method. And the Quantity Selector Field is not populated when I type numbers (the Dataseries picker is prompted instead).
                the indicator scipt avaiable at

                PHP Code:

                namespace NinjaTrader.NinjaScript.Indicators
                {
                     public class 
                BuyMktSellMktHotkeysQS Indicator
                     
                {
                     ...

                     
                // QS
                     
                private QuantityUpDown myQuantityUpDown;
                     ...

                     private 
                void On_Quantity_Selector_PreviewKeyDown(object senderKeyEventArgs e)
                     {
                          
                myQuantityUpDown.PreviewKeyDown += (op) =>
                          {
                               if (
                e.Key == Key.Delete || e.Key == Key.Back)
                               {
                                    
                e.Handled true;
                                    
                myQuantityUpDown.Value 0;

                               }

                               if ((
                e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
                               {
                                    
                e.Handled true;

                                    
                string number e.Key.ToString();
                                    
                string newnumber myQuantityUpDown.Value.ToString();
                                    
                number number.Replace("NumPad""");
                                    
                number number.Replace("D""");
                                    
                int num int.Parse(newnumber number);
                                    
                myQuantityUpDown.Value num;
                               }
                          };
                     } 


                Snippet #1 (from https://ninjatraderecosystem.com/use...ellmkthotkeys/ )
                PHP Code:
                protected void ChartControl_PreviewKeyDown(object senderKeyEventArgs e)
                {
                     
                TriggerCustomEvent(=>
                     {
                          
                Order buyMktOrder null;

                          if (
                Keyboard.IsKeyDown(Key.NumPad7))
                          {
                               
                buyMktOrder myAccount.CreateOrder(InstrumentOrderAction.BuyOrderType.MarketOrderEntry.ManualTimeInForce.Day100"""buyMktOrder"+DateTime.Now.ToString(),                     DateTime.MaxValuenull);
                          }

                          
                myAccount.Submit(new[] { buyMktOrder });
                     }, 
                null);
                     
                e.Handled true;

                     
                TriggerCustomEvent(=>
                     {
                          
                Order sellMktOrder null;

                          if (
                Keyboard.IsKeyDown(Key.NumPad8))
                          {
                               
                sellMktOrder myAccount.CreateOrder(InstrumentOrderAction.SellOrderType.MarketOrderEntry.ManualTimeInForce.Day100"""sellMktOrder"+DateTime.Now.ToString(), DateTime.MaxValuenull);
                          }

                          
                myAccount.Submit(new[] { sellMktOrder });
                     }, 
                null);
                     
                e.Handled true;



                Snipper #2 ( from this doc: https://ninjatrader.com/support/help...tityupdown.htm )
                PHP Code:
                private AtmStrategy.AtmStrategySelector atmStrategySelector;

                ...

                private 
                DependencyObject LoadXAML()

                {
                    ...

                    
                // When our ATM selector's selection changes

                    
                atmStrategySelector.SelectionChanged += (oargs) =>

                    {

                        if (
                atmStrategySelector.SelectedItem == null)

                              return;

                        if (
                args.AddedItems.Count 0)

                         {

                              
                // Change the selected TIF in our TIF selector too

                              
                AtmStrategy selectedAtmStrategy args.AddedItems[0] as AtmStrategy;

                              if (
                selectedAtmStrategy != null)

                                   
                tifSelector.SelectedTif selectedAtmStrategy.TimeInForce;

                         }

                 };




                Comment


                  #9
                  Hello PaulMohn,

                  But I don't understand the use of myQuantityUpDown/spQtySelector1. What does it come from? A custom class or something else?
                  Those are variables, myQuantityUpDown is defined in the script you linked to near the top, spQtySelector1 was not in the linked file but that was included in this post as it was relevant to the original posters script.

                  Code:
                  private QuantityUpDown [B]myQuantityUpDown[/B];

                  But it seem to be an unusual method. And the Quantity Selector Field is not populated when I type numbers (the Dataseries picker is prompted instead).
                  That means the PreviewKeys event was not called or the e.Handled = true; was never hit. The e.Handled is how you control the instrument selector by letting the chart know the event was already used. Because the event is on the quantity selector that also needs to be in focus by clicking in the text field.

                  To debug what you have you would first want to make sure the subscription to your preview event happened, the easiest way would be to add a print for all keys and handle all keys:

                  Code:
                  private void On_Quantity_Selector_PreviewKeyDown(object sender, KeyEventArgs e)
                  {
                  Print("here");
                  If you see the print but don't see the event handled then the condition around e.Handled was not true.


                  JesseNinjaTrader Customer Service

                  Comment


                    #10
                    Hello Jesse, got the print test results in demo
                    https://drive.google.com/file/d/1K0E...ew?usp=sharing

                    0. Pressing D0/ '1' key Test

                    Test 0 Resutl

                    e.Handled False
                    Key.D0 D0 D1
                    Key.D9 D9 D1


                    1. Pressing the D9/'9' key Test

                    Test 1 Resutl

                    e.Handled False
                    Key.D0 D0 D9
                    Key.D9 D9 D9


                    2. Pressing the D0 & D9/ '1' & '9' keys Test

                    Test 2 Resutl

                    e.Handled False
                    Key.D0 D0 D1
                    Key.D9 D9 D1


                    3. The Unhandled exception: Object reference not set to an instance of an object.
                    As you can see in the short demo, the prints show the keystrokes events are detected but not the e.handled event (false).
                    Also, it throws the "The Unhandled exception: Object reference not set to an instance of an object." error pop up windows each time.
                    What's preventing the e.handled event detection?
                    And what's causing theUnhandled exception?

                    The new script


                    I just tested the Delete and back keystrokes and got the same result

                    e.Handled False
                    Key.D0 D0 Back
                    Key.D9 D9 Back

                    e.Handled False
                    Key.D0 D0 Delete
                    Key.D9 D9 Delete

                    And also the NumPad1 and Numpad9 keystrokes with same result

                    e.Handled False
                    Key.D0 D0 NumPad1
                    Key.D9 D9 NumPad1

                    e.Handled False
                    Key.D0 D0 NumPad9
                    Key.D9 D9 NumPad9
                    Last edited by PaulMohn; 02-16-2022, 04:14 PM.

                    Comment


                      #11
                      Hello PaulMohn,

                      The e.Handled should be false, you would need to set it to true for the keys which you wanted to handle.

                      The The Unhandled exception: Object reference not set to an instance of an object means an object was null when you tried to use it.

                      I do see a problem in the code you linked, you have added a subscription within your event handler:

                      Code:
                      private void On_Quantity_Selector_PreviewKeyDown(object sender, KeyEventArgs e)
                      {
                      Print("e.Handled " + e.Handled);
                      Print("Key.D0 " + Key.D0 + " " + e.Key);
                      Print("Key.D9 " + Key.D9 + " " + e.Key);
                      
                      [B]myQuantityUpDown.PreviewKeyDown += (o, p) =>[/B]
                      [B]{[/B]
                      
                      
                      [B]};[/B]
                      }
                      If On_Quantity_Selector_PreviewKeyDown is being called for the selector you wanted then you just need to delete the above bold code and make sure the key handling code is working as you expected. If you otherwise needed to make a subscription to PreviewKeyDown for the variable myQuantityUpDown then the bold code needs to go on line 139 in your file.

                      JesseNinjaTrader Customer Service

                      Comment


                        #12
                        The e.Handled should be false, you would need to set it to true for the keys which you wanted to handle.
                        It is detected as false when I press the keys despite being set to true within the if statements. And the keys are detected as. (please see the demo)

                        The The Unhandled exception: Object reference not set to an instance of an object means an object was null when you tried to use it.
                        What object? e.handled?

                        I do see a problem in the code you linked, you have added a subscription within your event handler:

                        Code:
                        private void On_Quantity_Selector_PreviewKeyDown(object sender, KeyEventArgs e)
                        {
                        Print("e.Handled " + e.Handled);
                        Print("Key.D0 " + Key.D0 + " " + e.Key);
                        Print("Key.D9 " + Key.D9 + " " + e.Key);

                        myQuantityUpDown.PreviewKeyDown += (o, p) =>
                        {


                        };
                        }

                        If On_Quantity_Selector_PreviewKeyDown is being called for the selector you wanted then you just need to delete the above bold code and make sure the key handling code is working as you expected.
                        You mean as such?
                        PHP Code:
                        namespace NinjaTrader.NinjaScript.Indicators
                        {
                             public class 
                        BuyMktSellMktHotkeysQS Indicator
                             
                        {
                             ...

                             
                        // QS
                             
                        private QuantityUpDown myQuantityUpDown;
                             ...

                             private 
                        void On_Quantity_Selector_PreviewKeyD own(object senderKeyEventArgs e)
                             {

                                       if (
                        e.Key == Key.Delete || e.Key ==  Key.Back)
                                       {
                                            
                        e.Handled true;
                                            
                        myQuantityUpDown.Value 0;

                                       }

                                       if ((
                        e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
                                       {
                                            
                        e.Handled true;

                                            
                        string number e.Key.ToString ();
                                            
                        string newnumber myQuantityU pDown.Value.ToString();
                                            
                        number number.Replace("NumPa d""");
                                            
                        number number.Replace("D"" ");
                                            
                        int num int.Parse(newnumber  number);
                                            
                        myQuantityUpDown.Value num;
                                       }

                             } 

                        new script (please see lines 170-197)


                        If so I tested it and it still does return the unhandled exception and the keystrokes still don't input their values into the Quantity Selector.

                        If you otherwise needed to make a subscription to PreviewKeyDown for the variable myQuantityUpDown then the bold code needs to go on line 139 in your file.
                        To be honest I don't know at this point which of the 2 is needed as I couldn't derive it from the OP answer.

                        I'm not sure I understand what you suggest by putting the bold cod at line 139.

                        Here's the code at lines 121-145 (The Add Controls To ToolBar region snippet)

                        PHP Code:
                         #region Add Controls To Tollbar
                        private void Add_Controls_To_Toolbar()
                        {
                             
                        // Use this.Dispatcher to ensure code is executed on the proper thread
                             
                        ChartControl.Dispatcher.InvokeAsync((Action)(() =>
                             {

                                  
                        //Obtain the Chart on which the indicator is configured
                                  
                        chartWindow Window.GetWindow(this.ChartControl.Parent) as Chart;
                                  if (
                        chartWindow == null)
                                  {
                                       Print(
                        "chartWindow == null");
                                       return;
                                  }

                                  
                        Quantity_Selector = new NinjaTrader.Gui.Tools.QuantityUpDown();
                                  
                        //Quantity_Selector.ValueChanged += On_Quantity_Selector_ValueChanged;
                                  
                        Quantity_Selector.PreviewKeyDown += On_Quantity_Selector_PreviewKeyDown;

                                  
                        chartWindow.MainMenu.Add(Quantity_Selector);

                                  
                        Is_ToolBar_Controls_Added true;
                             }));
                        }
                        #endregion 

                        Do you mean (please see "line 139" comment below)

                        PHP Code:
                        #region Add Controls To Tollbar
                        private void Add_Controls_To_Toolbar()
                        {
                             
                        // Use this.Dispatcher to ensure code is executed on the proper thread
                             
                        ChartControl.Dispatcher.InvokeAsync((Action)(() =>
                             {

                                  
                        //Obtain the Chart on which the indicator is configured
                                  
                        chartWindow Window.GetWindow(this.ChartControl.Parent) as Chart;
                                  if (
                        chartWindow == null)
                                  {
                                       Print(
                        "chartWindow == null");
                                       return;
                                  }

                                  
                        Quantity_Selector = new NinjaTrader.Gui.Tools.QuantityUpDown();
                                  
                        //Quantity_Selector.ValueChanged += On_Quantity_Selector_ValueChanged;
                                  
                        Quantity_Selector.PreviewKeyDown += On_Quantity_Selector_PreviewKeyDown;

                                  
                        // Line 139
                                  
                        myQuantityUpDown.PreviewKeyDown += (oe) =>;
                                   {
                                        if (
                        e.Key == Key.Delete || e.Key == Key.Back)
                                        {
                                             
                        e.Handled true;
                                             
                        myQuantityUpDown.Value 0;

                                        }

                                        if ((
                        e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
                                        {
                                             
                        e.Handled true;

                                             
                        string number e.Key.ToString();
                                             
                        string newnumber myQuantityUpDown.Value.ToString();
                                             
                        number number.Replace("NumPad""");
                                             
                        number number.Replace("D""");
                                             
                        int num int.Parse(newnumber number);
                                             
                        myQuantityUpDown.Value num;

                                        }
                                   };

                                  
                        chartWindow.MainMenu.Add(Quantity_Selector);

                                  
                        Is_ToolBar_Controls_Added true;
                             }));
                        }
                        #endregion 

                        I also tested that code at line 140-161, but now the Quantity Selector is no more present on the Toolbar.
                        The new script (please see lines 121-167, and 192-199)

                        Comment


                          #13
                          Hello PaulMohn,

                          It is detected as false when I press the keys despite being set to true within the if statements. And the keys are detected as. (please see the demo)
                          Your print was before where it was set in the last script, the set to true also was not happening because you had an event handler within an event handler. The code in bold from the previous post was invalid in that location. The code within the code in bold's { } was not being evaluated. You also shouldn't need to print that value at all, if the instrument selector is still appearing then e.Handled was not set to true, you would instead want to print the variables being used in the conditions for keys you have to see why e.Handled was not set to true.

                          What object? e.handled?
                          I don't know, you would need to debug the script in that use case. You can comment out code or put more prints in to find the specific line which has that error.

                          You mean as such?
                          Yes, removing the code which I had shown as bold will be one step forward. That code in bold is subscribing to the event, its the alternate way of doing += myEventVoidName. That code should not have been inside the other event handler method.

                          Do you mean (please see "line 139" comment below)
                          If you have a second selector then yes, that is subscribing to an additional event for the myQuantityUpDown variable. If you did not have two selectors then using the myQuantityUpDown variable in any way will throw a object reference error. The event handler you have been working with points to the varaible Quantity_Selector:

                          Quantity_Selector.PreviewKeyDown += On_Quantity_Selector_PreviewKeyDown;

                          I see in the attached script that you moved the key handling logic to the line 139 area, if you no longer want to use Quantity_Selector then you have done that, you can remove that control and its event subscriptions. If you want to use Quantity_Selector then your key handling logic needs to go inside On_Quantity_Selector_PreviewKeyDown.

                          The myQuantityUpDown is a second control with its own events however I don't see you ever created the control so using it will cause an error. If you plan to use two controls then you will have two preview events and you also need to create the myQuantityUpDown control similar to how the other control was created. You would need to add key handling code into each event to handle the keys for that specific control.



                          JesseNinjaTrader Customer Service

                          Comment


                            #14
                            Originally posted by NinjaTrader_Jesse View Post
                            Hello,

                            Thank you for the post.

                            What you have now would mostly work if you were using the PreviewKeyDown event rather than just the KeyDown event.

                            Here is a simple example, this would only work for values 0-9, anything over this would require that you form some logic to combine input into a correct number value. This control does not take a string so you will need to use logic to form an int:


                            Code:
                            myQuantityUpDown.PreviewKeyDown += (o, e) =>
                            {
                            if ((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
                            {
                            e.Handled = true;
                            string number = e.Key.ToString();
                            number = number.Replace("NumPad", "");
                            number = number.Replace("D", "");
                            int num = int.Parse(number);
                            NinjaTrader.Gui.Tools.QuantityUpDown qs = o as NinjaTrader.Gui.Tools.QuantityUpDown;
                            if (qs != null) qs.Value = num;
                            }
                            };


                            I look forward to being of further assistance.
                            Ok, I've found a new example to draw from (and learned about anonymous methods in C# by the same occasion, which is what I believe to be the unusual new (to me) method construct you used)

                            NinjaTrader.Gui.Tools.QuantityUpDown
                            https://ninjatrader.com/support/foru...34#post1134134
                            @Text.cs code (from local path C:\Users\<YOUR User Name>\Documents\NinjaTrader 8\bin\Custom\DrawingTools)
                            C:\Users\\Documents\NinjaTrader 8\bin\Custom\DrawingTools reference: https://ninjatrader.com/support/forum/forum/ninjatrader-8/strategy-development/1133348-ninjatrader-gui-tools-quantityupdown?p=1134134#post1134134


                            @Text.cs Snippet
                            PHP Code:
                            public override void OnMouseDown(ChartControl chartControlChartPanel chartPanelChartScale chartScaleChartAnchor dataPoint)
                            {
                                 if (
                            DrawingState == DrawingState.Building)
                                 {
                                      ...
                                      
                            TextBox tb            = new TextBox // line 357
                                      
                            {
                                           ...
                                      };

                                      
                            popup = new Popup
                                      
                            {
                                           ...
                                           
                            Child                tb // line 382
                                           
                            ...
                                      };

                                      
                            tb.PreviewKeyDown += (senderargs) => // lines 385 - 401
                                      
                            {
                                           if (
                            args.Key == Key.System && args.SystemKey == Key.Enter)
                                           {
                                                
                            int oldIdx tb.CaretIndex;
                                                
                            string text1 tb.Text.Substring(0oldIdx);
                                                
                            string text2 tb.Text.Substring(oldIdx);
                                                
                            tb.Text string.Format("{0}{1}{2}"text1Environment.NewLinetext2);
                                                
                            tb.CaretIndex oldIdx Environment.NewLine.Length;
                                                
                            args.Handled true;
                                           }
                                           if (
                            args.Key == Key.Enter)
                                           {
                                                
                            popup.IsOpen false;
                                                
                            args.Handled true;
                                           }
                                 }; 

                            Considering the above @Text.cs snippet, I believe I understand now your method need to be embedded in an other method without "sender and args"/a "non-event" method.

                            Is that right?

                            You post #2 code in my script with the "non-event" encapsulating method
                            PHP Code:
                            public class BuyMktSellMktHotkeysQS Indicator
                            {
                            ...

                                 
                            // QS
                                 
                            private QuantityUpDown myQuantityUpDown;

                            ...

                                 private 
                            void On_Quantity_Selector_PreviewKeyDown()
                                 {
                                      
                            myQuantityUpDown.PreviewKeyDown += (oe) =>
                                     {
                                          if ((
                            e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
                                          {
                                               
                            e.Handled true;
                                               
                            string number e.Key.ToString();
                                               
                            number number.Replace("NumPad""");
                                               
                            number number.Replace("D""");
                                               
                            int num int.Parse(number);
                                               
                            NinjaTrader.Gui.Tools.QuantityUpDown qs as NinjaTrader.Gui.Tools.QuantityUpDown;
                                               if (
                            qs != nullqs.Value num;
                                          }
                                     };
                                 } 

                            If that's the right way to go, now I get that compile error

                            NinjaScript File Error Code Line Column
                            BuyMktSellMktHotkeysQS.cs No overload for 'On_Quantity_Selector_PreviewKeyDown' matches delegate 'System.Windows.Input.KeyEventHandler' CS0123 138 47
                            New Script
                            https://ninjatrader.com/support/forum/forum/ninjatrader-8/indicator-development/101315-set-quantityupdown-value-from-keyboard


                            Can you please confirm that the "non-event method" i'm going for is the right way to go?

                            If no, can you please explain what other way you had in mind when answering post #2 to use your method?

                            If yes, can you please explain what I would need to do to solve the compile error?

                            Thanks.


                            Other Related Threads and research:

                            NinjaTrader.Gui.Tools.QuantityUpDown
                            https://ninjatrader.com/support/foru...34#post1134134

                            Chart intercepting AddOn Input
                            https://ninjatrader.com/support/foru...406#post787406

                            KeyDown Event?
                            https://ninjatrader.com/support/foru...830#post669830

                            Control.KeyDown Event
                            https://docs.microsoft.com/en-us/dot...owsdesktop-6.0



                            KeyPressEventArgs.Handled Property
                            https://docs.microsoft.com/en-us/dot...owsdesktop-6.0

                            KeyPressEventArgs.Handled Property
                            https://docs.microsoft.com/en-us/dot...owsdesktop-6.0

                            Control.KeyPress Event
                            https://docs.microsoft.com/en-us/dot...owsdesktop-6.0

                            Control.KeyUp Event
                            https://docs.microsoft.com/en-us/dot...owsdesktop-6.0



                            Event handlers in C#
                            https://www.c-sharpcorner.com/articl...20the%20event.

                            C# Tutorial: Events/Event Handlers
                            In this lesson I go over events/event handlers and how to use them.




                            Lambda expressions (C# reference)
                            https://docs.microsoft.com/en-us/dot...da-expressions

                            Capture of outer variables and variable scope in lambda expressions



                            Part 98 Anonymous methods in c#
                            Text version of the videohttp://csharp-video-tutorials.blogspot.com/2014/03/part-98-anonymous-methods-in-c_22.htmlHealthy diet is very important both for the...


                            Anonymous methods can be used as event handlers:
                            https://www.tutorialsteacher.com/csh...a%20parameter.



                            Delegates (C# Programming Guide)
                            https://docs.microsoft.com/en-us/dot...ide/delegates/
                            Last edited by PaulMohn; 02-18-2022, 02:07 AM.

                            Comment


                              #15
                              Hello Jesse,

                              I think I got it working for the single digit typing input
                              Demo



                              New Snippet
                              PHP Code:
                              private void On_Quantity_Selector_PreviewKeyDown(object senderKeyEventArgs p)
                              {
                                   
                              // myQuantityUpDown.PreviewKeyDown += (o, p) =>
                                   // {
                                             
                              if ((p.Key >= Key.D0 && p.Key <= Key.D9) || (p.Key >= Key.NumPad0 && p.Key <= Key.NumPad9))
                                             {
                                                  
                              p.Handled true;
                                                  
                              string number p.Key.ToString();
                                                  
                              number number.Replace("NumPad""");
                                                  
                              number number.Replace("D""");
                                                  
                              int num int.Parse(number);
                                                  
                              NinjaTrader.Gui.Tools.QuantityUpDown qs sender as NinjaTrader.Gui.Tools.QuantityUpDown;
                                                  if (
                              qs != nullqs.Value num;
                                             }
                                   
                              // };

                              New Script
                              lines 148-163 Ref. https://ninjatrader.com/support/forum/forum/ninjatrader-8/indicator-development/101315-set-quantityupdown-value-from-keyboard


                              I'll tackle the multiple digits next. Thanks!

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by frankthearm, Today, 09:08 AM
                              7 responses
                              30 views
                              0 likes
                              Last Post NinjaTrader_Clayton  
                              Started by NRITV, Today, 01:15 PM
                              1 response
                              5 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Started by maybeimnotrader, Yesterday, 05:46 PM
                              5 responses
                              25 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Started by quantismo, Yesterday, 05:13 PM
                              2 responses
                              18 views
                              0 likes
                              Last Post quantismo  
                              Started by adeelshahzad, Today, 03:54 AM
                              5 responses
                              33 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Working...
                              X