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

Using hotkeys to run custom strategies and/or scripts

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

    Using hotkeys to run custom strategies and/or scripts

    Hi there!

    I'm wondering if NT8 has the ability to map a key combination to a small script for order entry. It would go something like:
    1. Hit key combination "Shift"+"CTRL"+"8" (just an example)
    2. A NT8 strategy or Ninjascript file is executed that puts a buy limit order in the market and waits for it to be filled.
    3. Once filled, the strategy/Ninjascript monitors price action to submit additional buy orders when the market moves up X in price
    4. Exits once pre-determined price target is hit or stopped out at predetermined level.
    Let me know if that makes sense.

    #2
    Hello Spiderbird,

    This would be possible using undocumented code.

    Below are links to examples that listen for keypresses.

    This is a conversion of the a1ChartNotes indicator by monpere. Chart Notes v3 Add notes to your chart. For example, identify a chart template, or put specific notes on how to trade a particular chart, or instrument, etc. – Added selectable fonts and text color – Control Shift toggles compact/expanded visibility (number of lines shown) […]
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Yeah, I kind of figured that I'd have to go the "code my own way" route, but wasn't sure if Hot Keys could help bridge anything.
      Thanks for the links and the attention!

      Comment


        #4
        Originally posted by NinjaTrader_ChelseaB View Post
        Hello Spiderbird,

        This would be possible using undocumented code.

        Below are links to examples that listen for keypresses.
        https://ninjatrader.com/support/foru...756#post831756
        https://ninjatraderecosystem.com/use.../a1chartnotes/
        Okay, I'm back! And I have a question about the first link you sent.

        I tried doing a simple test of a keystroke to see it would load in a strategy. Something like:
        Code:
        protected override void OnBarUpdate()
                {
                    if (BarsInProgress != 0)
                        return;
                    if (Keyboard.IsKeyDown(Key.Enter))
                    {    Print("Enter!");}
                }​
        And I got an error (which I figured would happen) with "The calling thread must be STA, because many UI components require this."

        -----

        When I looked back at the example you linked to, the indicator code in the ZIP file had this:

        Code:
                private TextBox textBox;
        
                protected override void OnStateChange()
                {
                    if (State == State.SetDefaults)
                    {
                        Name = "PreventInstrumentOverlaySelectorWithTextBoxExample";
                        Description = "Adds a custom textbox to the chart";
                        IsOverlay = false;
                    }
                    else if (State == State.Configure)
                    {
                    }
        
                        // Once the NinjaScript object has reached State.Historical, our custom control can now be added to the chart
                    else if (State == State.Historical)
                    {
                        // Because we're dealing with UI elements, we need to use the Dispatcher which created the object
                        // in order for us to update the contents that are created on the main UI thread
                        Dispatcher.InvokeAsync((() =>
                        {
                            textBox = new TextBox();
        
                            textBox.PreviewKeyDown += TextBox_PreviewKeyDown;
        
                            UserControlCollection.Add(textBox);
                        }));
                    }
        
                    else if (State == State.Terminated)
                    {
                        if (textBox != null)
                        {
                            textBox.PreviewKeyDown -= TextBox_PreviewKeyDown;
                        }
                        if (textBox != null && UserControlCollection.Contains(textBox))
                            UserControlCollection.Remove(textBox);
                    }
                }
        
                private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
                {
                    // this is pretty dumb, but should get you started
                    // might want to validate this by using SHIFT or something
                    // so Overlay Instrument Selector isn't unusable...
                    TextBox textBoxSender = (TextBox) sender;
                    textBoxSender.Text += e.Key.ToString();
                    // handle the keydown event for the text box
                    e.Handled = true;
                }​
        .... which is all fine and well! However, I'm not connecting how to get a simple keystroke to generate output in the NT output window versus what the example seems to be doing here... which is creative a UI element based on a keystroke?

        I don't mind doing the heavy lifting on the code side, but I think I need a bridge between the pithy attempt I did and the bulk of code that was included in the example.
        For reference, I also looked at this NT8 help page as well:



        ... but I really don't know how it maps/aligns with what I'm trying to do.

        Can you point me in the right direction?
        Thanks in advance for whatever time you give this.

        Comment


          #5
          Hello Spiderbird,

          You are wanting to check to see if a key is being held down when the bar updates in OnBarUpdate()?

          You would want to use a bool. In the key down event set the bool to true, in the key up event set the bool back to false. Then if the bool is true when a bar updates, then you know the key is being held down.

          The UI thread where buttons and keypresses and mouse events are occuring is a different thread than the NinjaScript thread or instrument thread where data is processed so a dispatcher must be used.
          Chelsea B.NinjaTrader Customer Service

          Comment


            #6
            Originally posted by NinjaTrader_ChelseaB View Post
            Hello Spiderbird,

            You are wanting to check to see if a key is being held down when the bar updates in OnBarUpdate()?
            I apologize. It was just where I had placed it as an example. I'd like the script to act whenever the key is pressed, rather than it being held down. The idea being that whenever a particular key or key combo is pressed, the script would act accordingly.

            If a strategy script isn't the right place for it, do let me know. I just wasn't sure where it should be kept (in an indicator or a strategy script, or neither/both)

            Comment


              #7
              Hello Spiderbird,

              A strategy, an indicator, a custom addon window, any place would be fine to add event handlers.

              These are assigned in a strategy or indicator in State.DataLoaded with a dispatcher invoking into the UI thread to make modifications to the UI.

              The method handler is within the scope of the class (not in OnBarUpdate()).

              The event handler method is triggered the moment the event fires when the key is pressed.

              If you want to detect the key is pressed from OnBarUpdate() when the bar updates, you will need to set a bool when the key pressed that can be read in the Instrument thread updating OnBarUpdate().
              Chelsea B.NinjaTrader Customer Service

              Comment


                #8
                Hello Chelsea!

                Originally posted by NinjaTrader_ChelseaB View Post
                Hello Spiderbird,
                A strategy, an indicator, a custom addon window, any place would be fine to add event handlers.
                These are assigned in a strategy or indicator in State.DataLoaded with a dispatcher invoking into the UI thread to make modifications to the UI.
                (...)
                If you want to detect the key is pressed from OnBarUpdate() when the bar updates, you will need to set a bool when the key pressed that can be read in the Instrument thread updating OnBarUpdate().
                Got it on the event handlers bit. And I also did some reading on UserControlCollection​ and Dispatch.Invoke etc. to better understand the examples that were posted earlier.

                But let me clarify... I'm not looking to update any element in a chart or a UI component when pressing a key. I'm trying to build out a script that will eventually submit sophisticated market and limit orders based on keystrokes that 'Hot Keys' in NT8 doesn't properly configure.

                My original example was just to get an idea of how to code the proper script that a) reacts to a key press, b) can submit something to the NT output window and c) send a customized order to my broker based on market conditions. I wasn't attempting to alter a text box or a chart when pressing a keystroke.

                Let me know if that makes sense or if it's more gibberish to add to the pile.

                Comment


                  #9
                  Hello Spiderbird,

                  Yes, you can submit orders from event handlers. You will need to use TriggerCustomEvent if you plan to use any series information.

                  Below is a link to an example that sends orders from a button click event handler, but the code can be adapted to any event.
                  I need some guidance. I need to create a script that has 3 plots that are public and they plot either a 1 or 0. But I need to create another indicator that has 3 chart buttons that sets these variables. The first indicator needs to get those values from the second indicator depending on the button clicks. Because of using
                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    Hi Chelsea!

                    I actually figured out a way to do it, but I have to stick with NT's insistence on using at least one modifier (CTRL/SHIFT/ALT) unless it is a function key so it can be a legitimate hotkey. I used another person's code here and just modified it slightly:

                    Code:
                    protected override void OnStateChange()
                            {
                               (...)
                    
                              if (State == State.DataLoaded)
                                {
                                    this.ChartPanel.KeyDown += new System.Windows.Input.KeyEventHandler(OnKeyDown);
                                    this.ChartPanel.KeyUp += new System.Windows.Input.KeyEventHandler(OnKeyUp);
                                }
                    
                    
                                 else if (State == State.Terminated)
                                {
                                    if (ChartPanel != null)
                                    {
                                        ChartPanel.KeyDown -= OnKeyDown;
                                        ChartPanel.KeyUp -= OnKeyUp;
                                    }
                                }
                            }​
                    
                          public void OnKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
                            {
                                if (e.Key == Key.LeftCtrl)
                                {
                                    ctrl = true;
                                }
                    
                                if (e.Key == Key.B)
                                {
                                    one = true;
                                }
                    
                                if (ctrl && one)
                                {
                                    Print("Both pressed");
                                    // Do something here
                                }
                            }
                    
                            public void OnKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
                            {
                                if (e.Key == Key.LeftCtrl)
                                {
                                    ctrl = false;
                                }
                    
                                if (e.Key == Key.B)
                                {
                                    one = false;
                                }
                            }​
                    Now that this works, I can go about coding the hotkeys to do particular scripts and look to put those into chart buttons (eventually).
                    I'm also running with the assumption that if I hit *ANY* key while a NT chart is selected, I'm going to get a prompt that asks me to change the security I'm looking at.

                    Btw, is there any way to bypass/override that in a NT chart? Where pressing a regular key while a chart is active is not going to bring up a box that asks for a security?
                    My thought is no, but please verify when you have a moment.

                    Thanks again for your help Chelsea.​

                    Comment


                      #11
                      Hello Spiderbird,

                      Yes, you can suppress the Instrument Overlay Selector.

                      The e.Handled = true; on line 83 in the PreventInstrumentOverlaySelectorWithTextBoxExample _NT8 linked from post # 2 does just that.
                      Chelsea B.NinjaTrader Customer Service

                      Comment


                        #12
                        Worked like a charm. Thanks Chelsea!

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by DanielTynera, Today, 01:14 AM
                        0 responses
                        2 views
                        0 likes
                        Last Post DanielTynera  
                        Started by yertle, 04-18-2024, 08:38 AM
                        9 responses
                        40 views
                        0 likes
                        Last Post yertle
                        by yertle
                         
                        Started by techgetgame, Yesterday, 11:42 PM
                        0 responses
                        11 views
                        0 likes
                        Last Post techgetgame  
                        Started by sephichapdson, Yesterday, 11:36 PM
                        0 responses
                        2 views
                        0 likes
                        Last Post sephichapdson  
                        Started by bortz, 11-06-2023, 08:04 AM
                        47 responses
                        1,615 views
                        0 likes
                        Last Post aligator  
                        Working...
                        X