Add Buttons to NinjaTrader Chart Window

,
NinjaTrader Logo

If you are planning to run your strategy within a chart window and your strategy requires an asynchronous execution or event, you can trigger this via dynamic buttons in the tool bar of the chart window.

In the code below the creation of the buttons and the event handler is implemented in a separate class. CStripButton is created in the OnStartUp context and disposed in the OnTermination context. A button click calls a callback implemented in the strategy class.

public class CStripButton
{
    private ToolStrip           toolStrip           = null;
    private ToolStripButton     toolStripBtnA       = null;
    private ToolStripButton     toolStripBtnB       = null;
    private ToolStripSeparator  toolStripSeparator  = null;

    private Strategy            clStrategy;
    private StripButtonCallback fnCallback;        

    public CStripButton( Strategy _clStrategy, StripButtonCallback _fnCallback )
    {
        clStrategy = _clStrategy;
        fnCallback = _fnCallback;
 
        System.Windows.Forms.Control[] control =
  _clStrategy.ChartControl.Controls.Find( "tsrTool", false );
 
        if( control.Length > 0 )
        {
            toolStrip = (ToolStrip)control[0];

            toolStripSeparator              = new ToolStripSeparator();
            toolStrip.Items.Add( toolStripSeparator );

            toolStripBtnA                = new ToolStripButton( "btnA" );
            toolStripBtnA.Text           = "Button A";
            toolStripBtnA.Click         += btnClick;
            toolStrip.Items.Add( toolStripBtnA );

            toolStripBtnB                = new ToolStripButton( "btnB" );
            toolStripBtnB.Text           = "Button B";
            toolStripBtnB.Click         += btnClick;
            toolStrip.Items.Add( toolStripBtnB );
        }
    }

    /// <summary>
    /// Destructor.
    /// </summary>
    public void Dispose()
    {
        if( toolStrip != null )
        {
            toolStrip.Items.Remove( toolStripSeparator );
            toolStrip.Items.Remove( toolStripBtnA );
            toolStrip.Items.Remove( toolStripBtnB );
        }
    }
 
    /// <summary>
    /// Button click handler.
    /// </summary>
    private void btnClick( object sender, EventArgs e )
    {            
        if( MessageBox.Show( 
             "Are you sure you want to continue?", 
             "Button pressed", 
             MessageBoxButtons.YesNo, 
             MessageBoxIcon.Question ) != DialogResult.Yes )
            return;

        var _bak = toolStripBtnTrain.BackColor;
        toolStripBtnTrain.BackColor = Color.Green;

        fnCallback( sender.ToString() );
 
        toolStripBtnTrain.BackColor = _bak;
    }
}
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *