Add Buttons to Toolbar Explained


Hello guys!


This is a very popular topic. We can add buttons to pretty much anything in NinjaTrader using the same principles. Buttons can be added from AddOn, Indicator or Strategy class doesn’t really matter. The approach is almost the same for all of them. In this article, I will go through the main principles that you need to understand when adding buttons.


You are going to need the example code for this article.


Download files


So step 1 is that you need a global button object to work with. This can be anything, buttons, combo box, text input etc.


private System.Windows.Controls.Button _button;


You will also need a global chart window object.


private Chart _chartWindow;


Now since we are using an Indicator class we are going to initialize the button inside the OnState.Historical.


if (ChartControl != null && !_isToolBarButtonAdded)

{

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

      {

            AddButtonToToolbar();

      }));

      }

}


You are going to have to use Dispatcher to start the process in a new thread otherwise you will get an error. Also, I add an extra _isToolBarButtonAdded boolean variable that I set to true after my button is added just in case to protect myself from multiple buttons getting added.


So next inside the AddButtonToToolBar() method we first need to initialize the _chartWindow object. Also, don’t forget to check it for null before proceeding further down the code.


_chartWindow = Window.GetWindow(this.ChartControl.Parent) as Chart;


if (_chartWindow == null)

{

       Print("chartWindow == null");

       return;

}


Once you got the chart window object initialized you can add a button to it. First, create a button, subscribe to a click event and add the button to the chart window. Easy as that. You can see I am using a custom method for creating a button where I am passing the text, object name, button text colour and background colour. You will find that method in the example code provided with the article. As you can see here is the part where we have to make our safety boolean true to avoid multiple additions.


_button = CreateButton("BUY", "buybutton", Brushes.White, Brushes.DarkRed);

_button.Click += OnButtonBuyClick;

_chartWindow.MainMenu.Add(_button);

            


_isToolBarButtonAdded = true;


Finally, the last step is to destroy the button and unsubscribe from the click even we have created in the OnState.Terminated.


Your button is ready. Please subscribe to the blog!


Download files