Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Long/Short Button click through Code

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

    Long/Short Button click through Code

    Hello,

    First post here. Not sure if this is something I'm able to get help with but figured I'll try anyways.
    Using the Long/Short button found in the ecosystem: https://ninjatraderecosystem.com/use...bar-buttons-2/

    Was able to modify to make a Scalp/Price action entry order button. Everything is done and seems to be working. But there is one thing with the button that I've been having trouble figuring out.

    Right now the button, once clicked. Stays live until it is manually clicked again. I'm trying to figure out a way to automatically revert the button back to the "Non-Live" Position once my account is no longer flat/ in a trade(3rd Picture)

    I don't have much experience coding. Been trying to teach myself these last few months. Any help with this will be greatly appreciated!

    Thankyou!

    Click image for larger version

Name:	TSLA BeforeTrade.png
Views:	924
Size:	74.7 KB
ID:	1207432​​​​​​
    Click image for larger version

Name:	TSLA LIVE.png
Views:	815
Size:	89.9 KB
ID:	1207433
    Click image for larger version

Name:	TSLA inTrade.png
Views:	789
Size:	117.5 KB
ID:	1207434





    Attached Files

    #2
    Hello TradeSimple(Dre),

    Thanks for your post.

    You will want to change the Content property of the button to change the displayed text. You will need to use a dispatcher here, because the buttons will reside on the UI thread and your trigger will need to come from another NinjaScript event on a different thread.

    I would recommend using OnExecutionUpdate, and checking when Position.MarketPosition becomes MarketPosition.Flat to set the test to something that reflects that you are flat.

    Below is an example:

    Code:
    protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
    {
        if (Position.MarketPosition == MarketPosition.Flat)
        {
            ChartControl.Dispatcher.InvokeAsync(new Action(() => {
                longButton.Content = "Test - Flat";
            }));
        }
    }
    We look forward to assisting.

    Comment


      #3
      Hi Jim,

      Thank you so much for the reply, your help is greatly appreciated!

      I was able to successfully change the name of the button and turn off the "Live" part of it using the example above.
      However, now I'm trying to work out how to make the button useable again once the position is Flat.

      What I'm trying to do is:

      1. User Pushes button - Button changes to "Live" until conditions to enter are met or button is pushed again.
      2. Conditions are met, Enters Long - Button becomes disabled ("Test - Flat")
      3. Once Position is Flat - Return button back so user can push it again. ("Long" position)

      I got the first 2 steps down. Just been having trouble figuring out how to make the last step happen. I switched it back so it says "LONG" but the button stops working once the initial position exits.

      Not sure if I'm on the right track here but this is what I got so far. Any suggestions on how to get the button to work again would be amazing.

      Thank you again for your help!

      Code:
      protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
      {
      if (Position.MarketPosition != MarketPosition.Flat)
      {
      ChartControl.Dispatcher.InvokeAsync(new Action(() => {
      longButton.Content = "Test - Flat";
      longButtonClicked = false;
      }));
      }
      
      if (Position.MarketPosition == MarketPosition.Flat)
      {
      ChartControl.Dispatcher.InvokeAsync(new Action(() => {
      longButton.Content = "LONG";
      }));
      }
      }

      Comment


        #4
        Hello TradeSimple(Dre)

        Checking when Position.MarketPosition becomes MarketPosition.Flat in OnExecutionUpdate will be the first place you can check when the strategy sees it is in a flat position.

        Prints can be used to verify that you code has reached these sections and can also be used to check various conditions in your code.

        For example, a print could tell you that the code has reached X point where some actions take place, and if that print is not seen, check the conditions used to control that action - What are the variable values and what do they need to be in order for those conditions to become true and have the action take place?

        Debugging tips — https://ninjatrader.com/support/help...script_cod.htm

        Comment


          #5
          Hi NinjaTrader_Jim,

          Just wanted to thank you for your help with this. This helped tremendously and led me in the right direction!

          In case anyone finds themselves googling this specific question. What I ended up doing is using the OnExecutionUpdate above and using the dispatcher to bring back the same buttons.
          Not sure if this is the proper method to do this, but ended up working exactly how I needed it to.

          This is the code I used to solve the issue I was having.

          Code:
          protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
          {
          if (Position.MarketPosition != MarketPosition.Flat)
          
          {
          
          ChartControl.Dispatcher.InvokeAsync(new Action(() =>
          {
          longButton.Content = "Disabled L";
          longButtonClicked = false;
          
          
          shortButton.Content = "Disabled S";
          shortButtonClicked = false;
          
          }));
          
          }
          
          if (Position.MarketPosition == MarketPosition.Flat)
          
          {
          
          Dispatcher.InvokeAsync((() =>
          {
          myGrid = new System.Windows.Controls.Grid
          {
          Name = "MyCustomGrid", HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top
          };
          
          System.Windows.Controls.ColumnDefinition column1 = new System.Windows.Controls.ColumnDefinition();
          System.Windows.Controls.ColumnDefinition column2 = new System.Windows.Controls.ColumnDefinition();
          
          myGrid.ColumnDefinitions.Add(column1);
          myGrid.ColumnDefinitions.Add(column2);
          
          longButton = new System.Windows.Controls.Button
          {
          Name = "LongButton", Content = "LONG", Foreground = Brushes.White, Background = Brushes.Green
          };
          
          shortButton = new System.Windows.Controls.Button
          {
          Name = "ShortButton", Content = "SHORT", Foreground = Brushes.Black, Background = Brushes.Red
          };
          
          longButton.Click += OnButtonClick;
          shortButton.Click += OnButtonClick;
          
          System.Windows.Controls.Grid.SetColumn(longButton, 0);
          System.Windows.Controls.Grid.SetColumn(shortButton , 1);
          
          myGrid.Children.Add(longButton);
          myGrid.Children.Add(shortButton);
          
          UserControlCollection.Add(myGrid);
          }));
          
          }
          
          else if (State == State.Terminated)
          {
          Dispatcher.InvokeAsync((() =>
          {
          if (myGrid != null)
          {
          if (longButton != null)
          {
          myGrid.Children.Remove(longButton);
          longButton.Click -= OnButtonClick;
          longButton = null;
          }
          if (shortButton != null)
          {
          myGrid.Children.Remove(shortButton);
          shortButton.Click -= OnButtonClick;
          shortButton = null;
          }
          }
          }));
          }
          }
          If anyone is interested in the full source code for this order Entry button/trade management system. You can now download it from the ecosystem:
          These order entry buttons are how I enter trades quickly and ensure correct share size/contract size. Made this using NinjaTrader_ZacharyG Button template found here. Enter trade options: -At the break of the High or Low of the previous candle, -At the break of the Close of the previous candle, -Submit Market Order. Uses the last […]

          Comment


            #6
            Hi TradeSimple(Dre),

            I also want to provide a better example that is available on the forums.

            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


              #7
              This is how I find the chart trader buttons in my addon:

              Code:
              Button buyMktButton = parentWindow.FindFirst("ChartTraderControlQuickBuyMarketButton") as Button;
              Button sellMktButton = parentWindow.FindFirst("ChartTraderControlQuickSellMarketButton") as Button;​
              Then I use WPF automation Ids to invoke them like this:
              Code:
              using System.Windows.Automation;
              using System.Windows.Automation.Peers;
              using System.Windows.Automation.Provider;​
              
              ...
              ...
              ButtonAutomationPeer buyMktButtonPeer = new ButtonAutomationPeer(buyMktButton);
              IInvokeProvider buyMktButtonInvokeP = buyMktButtonPeer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
              buyMktButtonInvokeP.Invoke();​
              ...


              See here for reference: https://stackoverflow.com/a/728444/2877168

              Comment


                #8


                ​​Hi there.
                Currently the LongShortButton example creates the buttons in chart panel. Is there a way to modify it to have them placed just in side panel just under those Chart Trader buttons?
                FYI, I include the related codes below.

                Dispatcher.InvokeAsync((() =>
                {
                myGrid = new System.Windows.Controls.Grid
                {
                Name = "MyCustomGrid", HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Top
                };

                System.Windows.Controls.ColumnDefinition column1 = new System.Windows.Controls.ColumnDefinition();
                System.Windows.Controls.ColumnDefinition column2 = new System.Windows.Controls.ColumnDefinition();
                System.Windows.Controls.ColumnDefinition column3 = new System.Windows.Controls.ColumnDefinition();

                myGrid.ColumnDefinitions.Add(column1);
                myGrid.ColumnDefinitions.Add(column2);
                myGrid.ColumnDefinitions.Add(column3);

                longButton = new System.Windows.Controls.Button
                {
                Name = "LongButton", Content = "LONG", Foreground = Brushes.White, Background = Brushes.Green
                };

                shortButton = new System.Windows.Controls.Button
                {
                Name = "ShortButton", Content = "SHORT", Foreground = Brushes.Black, Background = Brushes.Red
                };

                flattenButton = new System.Windows.Controls.Button
                {
                Name = "FlattenButton", Content = "FLATTEN", Foreground = Brushes.Blue, Background = Brushes.Yellow
                };

                longButton.Click += OnButtonClick;
                shortButton.Click += OnButtonClick;
                flattenButton.Click += OnButtonClick;

                System.Windows.Controls.Grid.SetColumn(longButton, 0);
                System.Windows.Controls.Grid.SetColumn(shortButton , 1);
                System.Windows.Controls.Grid.SetColumn(flattenButt on, 2);

                myGrid.Children.Add(longButton);
                myGrid.Children.Add(shortButton);
                myGrid.Children.Add(flattenButton);

                UserControlCollection.Add(myGrid);
                }));

                Comment


                  #9
                  Hello judysamnt7,

                  See the SampleWPFModifications reference sample.

                  Typically this would be found with the link below.
                  Join the official NinjaScript Developer Community for comprehensive resources, documentation, and community support. Build custom indicators and automated strategies for the NinjaTrader platforms with our extensive guides and APIs.


                  However, as our teams are transition to this site, the file download is temporarily unavailable.
                  Please follow the link below to the help guide where this was previously hosted.

                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    thanks Chelsea.
                    another of my observations was after installing these indicator buttons, looks like computer response getting slower than before, particularly for mouse movement and chart refresh.
                    is it as expected? I suspect this is caused by a number of ChartControl.Dispatcher.InvokeAsync methods being called. What do you think?


                    private void OnButtonClick(object sender, RoutedEventArgs rea)
                    {
                    System.Windows.Controls.Button button = sender as System.Windows.Controls.Button;


                    region Use case 1, Long ES-RTY

                    if (button == longMarketButton)
                    {


                    {
                    ChartControl.Dispatcher.InvokeAsync((Action)(() => {

                    Account a = ChartControl.OwnerChart.ChartTrader.Account;
                    int quantity = ChartControl.OwnerChart.ChartTrader.Quantity;
                    AtmStrategy atm = ChartControl.OwnerChart.ChartTrader.AtmStrategy;
                    Instrument instr = ChartControl.OwnerChart.ChartTrader.Instrument;
                    Order order1 = a.CreateOrder(instr, OrderAction.Buy,
                    OrderType.Market, OrderEntry.Automated, TimeInForce.Day, quantity, 0, 0, "", "Entry",
                    Core.Globals.MaxDate, null);


                    Order order2 = a.CreateOrder(Cbi.Instrument.GetInstrument ("M2K 12-24"), OrderAction.SellShort,
                    OrderType.Market, OrderEntry.Automated, TimeInForce.Day, quantity, 0, 0, "", "Entry",
                    Core.Globals.MaxDate, null);

                    if (atm == null)
                    // was set to 'None'
                    a.Submit(new[] { order1,order2 });

                    Comment


                      #11
                      Hello judysamnt7,

                      That would not be expected behavior and I would be suspect of something else being the cause.

                      Are you testing with all workspaces closed in a new blank workspace with one new chart and just this one script?

                      Are you reproducing with the SampleWPFModifications or ChartOrderButtonsIndicatorExample? (Tested alone with no other scripts running and all workspaces closed as well)

                      Chelsea B.NinjaTrader Customer Service

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by NullPointStrategies, Today, 05:17 AM
                      0 responses
                      41 views
                      0 likes
                      Last Post NullPointStrategies  
                      Started by argusthome, 03-08-2026, 10:06 AM
                      0 responses
                      124 views
                      0 likes
                      Last Post argusthome  
                      Started by NabilKhattabi, 03-06-2026, 11:18 AM
                      0 responses
                      64 views
                      0 likes
                      Last Post NabilKhattabi  
                      Started by Deep42, 03-06-2026, 12:28 AM
                      0 responses
                      41 views
                      0 likes
                      Last Post Deep42
                      by Deep42
                       
                      Started by TheRealMorford, 03-05-2026, 06:15 PM
                      0 responses
                      46 views
                      0 likes
                      Last Post TheRealMorford  
                      Working...
                      X