Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Creating Order from chart trader indicator

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

    Creating Order from chart trader indicator

    Hello,


    I found the ChartTraderCustomButtonsExample and I am trying to modify it, but for some reason I fail.
    If I press a button, I get the error : Error on Calling OnBarUpdate method on bar x : Object reference not set to an instance of an object.



    Would someone be so kind and check my code and help me fix the error?

    Thank you

    Code:
    #region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Gui.SuperDom;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion
    
    
    namespace NinjaTrader.NinjaScript.Indicators
    {
        
        public class ChartTraderCustomButtonsExample : Indicator
        {
            System.Windows.Controls.Grid    chartTraderGrid;
            System.Windows.Controls.Grid    chartTraderButtonsGrid;
            System.Windows.Controls.Grid    myButtonsGrid;
            System.Windows.Controls.Button    newButton1;
            System.Windows.Controls.Button    newButton2;
            System.Windows.Controls.Button    newButton3;
            System.Windows.Controls.Button    newButton4;
            
            private string  atmStrategyId            = string.Empty;
            private string  orderId                    = string.Empty;
            private bool    isAtmStrategyCreated    = false;
            private string[] entryOrder;
            
            private bool enterlon  = false;
            private bool entershor  = false;
            
            
            private Account myAccount;
            
            
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description = @"";
                    Name = "ChartTraderCustomButtonsExample";
                    Calculate = Calculate.OnEachTick;
                    IsOverlay = true;
                    DisplayInDataBox = true;
                    DrawOnPricePanel = true;
                    DrawHorizontalGridLines = true;
                    DrawVerticalGridLines = true;
                    PaintPriceMarkers = true;
                    ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
                    IsSuspendedWhileInactive = true;
                }
                else if (State == State.Historical)
                {
                    if (ChartControl != null)
                    {
                        ChartControl.Dispatcher.InvokeAsync((Action)(() =>
                        {
                            InsertWPFControls();
                        }));
                    }
                }
                else if (State == State.Terminated)
                {
                    if (ChartControl != null)
                    {
                        ChartControl.Dispatcher.InvokeAsync((Action)(() =>
                        {
                            RemoveWPFControls();
                        }));
                    }
                }
            }
    
            protected override void OnBarUpdate()
            {
                if(State == State.Historical)
                    return;
            if ( State != State.Historical )
            {
                
                    if (BarsInProgress != 0)
                    return;
    
                if (CurrentBars[0] < 3)
                    return;
                
                Print(Instrument+ "   "+ enterlon+"   "+entershor);
                
                if ( enterlon )
                {
                Order stopOrder;
                double high = Math.Max(Open[1], Close[1]);
                double low = Math.Min(Open[1], Close[1]);
                double stopprice = high + (high-low)/2;
                stopOrder = myAccount.CreateOrder(Instrument, OrderAction.Buy, OrderType.StopMarket, OrderEntry.Automated, TimeInForce.Day, 1, 0, stopprice, "myOCO", "stopOrder", Core.Globals.MaxDate, null);
    
     
    
                myAccount.Submit(new[] { stopOrder });    
                    
                enterlon = false;
                }
                
                
                
            }
            }
    
            protected void Button1Click(object sender, RoutedEventArgs e)
            {
                Draw.TextFixed(this, "infobox", "Button 1 Clicked", TextPosition.BottomLeft, Brushes.Green, new Gui.Tools.SimpleFont("Arial", 25), Brushes.Transparent, Brushes.Transparent, 100);
                enterlon = true;
                
                
            
                ChartControl.InvalidateVisual();
                
            }
    
            protected void Button2Click(object sender, RoutedEventArgs e)
            {
                Draw.TextFixed(this, "infobox", "Button 2 Clicked", TextPosition.BottomLeft, Brushes.DarkRed, new Gui.Tools.SimpleFont("Arial", 25), Brushes.Transparent, Brushes.Transparent, 100);
                ChartControl.InvalidateVisual();
            }
    
            protected void Button3Click(object sender, RoutedEventArgs e)
            {
                Draw.TextFixed(this, "infobox", "Button 3 Clicked", TextPosition.BottomLeft, Brushes.DarkOrange, new Gui.Tools.SimpleFont("Arial", 25), Brushes.Transparent, Brushes.Transparent, 100);
                ChartControl.InvalidateVisual();
            }
    
            protected void Button4Click(object sender, RoutedEventArgs e)
            {
                Draw.TextFixed(this, "infobox", "Button 4 Clicked", TextPosition.BottomLeft, Brushes.CadetBlue, new Gui.Tools.SimpleFont("Arial", 25), Brushes.Transparent, Brushes.Transparent, 100);
                ChartControl.InvalidateVisual();
            }
    
            protected void InsertWPFControls()
            {
                chartTraderGrid = (Window.GetWindow(ChartControl.Parent).FindFirst("ChartWindowChartTraderControl") as ChartTrader).Content as System.Windows.Controls.Grid;
                chartTraderButtonsGrid = chartTraderGrid.Children[0] as System.Windows.Controls.Grid;
                myButtonsGrid = new System.Windows.Controls.Grid();
    
                chartTraderGrid.Children.Add(myButtonsGrid);
    
                chartTraderGrid.RowDefinitions.Add(new System.Windows.Controls.RowDefinition() { Height = new GridLength(45) });
    
                System.Windows.Controls.Grid.SetRow(myButtonsGrid, 7);
    
                chartTraderButtonsGrid.RowDefinitions.Add(new System.Windows.Controls.RowDefinition() { Height = new GridLength(31)    });
           
                myButtonsGrid.RowDefinitions.Add(new System.Windows.Controls.RowDefinition() { Height = new GridLength(3) });
                myButtonsGrid.RowDefinitions.Add(new System.Windows.Controls.RowDefinition() { Height = new GridLength(31) });
                myButtonsGrid.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition() { Width = new GridLength(100) });
                // spacer column
                myButtonsGrid.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition() { Width = new GridLength(6) });
                myButtonsGrid.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition() { Width = new GridLength(100) });
    
                newButton1 = new System.Windows.Controls.Button()
                {
                    Background = Brushes.Gray,
                    BorderBrush = Brushes.DimGray,
                    Content = "MyButton1",
                    Height = 30
                };
    
                newButton2 = new System.Windows.Controls.Button()
                {
                    Background = Brushes.Gray,
                    BorderBrush = Brushes.DimGray,
                    Content = "MyButton2",
                    Height = 30
                };
    
                newButton3 = new System.Windows.Controls.Button()
                {
                    Background = Brushes.Gray,
                    BorderBrush = Brushes.DimGray,
                    Content = "MyButton3",
                    Height = 30
                };
    
                newButton4 = new System.Windows.Controls.Button()
                {
                    Background = Brushes.Gray,
                    BorderBrush = Brushes.DimGray,
                    Content = "MyButton4",
                    Height = 30
                };
    
                newButton1.Click += Button1Click;
                System.Windows.Automation.AutomationProperties.SetAutomationId(newButton1, "newButton1");
                chartTraderButtonsGrid.Children.Add(newButton1);
                System.Windows.Controls.Grid.SetRow(newButton1, 12);
    
                newButton2.Click += Button2Click;
                System.Windows.Automation.AutomationProperties.SetAutomationId(newButton2, "newButton2");
                chartTraderButtonsGrid.Children.Add(newButton2);
                System.Windows.Controls.Grid.SetRow(newButton2, 12);
                System.Windows.Controls.Grid.SetColumn(newButton2, 2);
    
                newButton3.Click += Button3Click;
                System.Windows.Automation.AutomationProperties.SetAutomationId(newButton3, "newButton3");
                myButtonsGrid.Children.Add(newButton3);
                System.Windows.Controls.Grid.SetColumn(newButton3, 0);
                System.Windows.Controls.Grid.SetRow(newButton3, 1);
    
                newButton4.Click += Button4Click;
                System.Windows.Automation.AutomationProperties.SetAutomationId(newButton4, "newButton4");
                myButtonsGrid.Children.Add(newButton4);
                System.Windows.Controls.Grid.SetColumn(newButton4, 2);
                System.Windows.Controls.Grid.SetRow(newButton4, 1);
            }
    
            protected void RemoveWPFControls()
            {
                if (newButton1 != null)
                {
                    newButton1.Click -= Button1Click;
                    chartTraderButtonsGrid.Children.Remove(newButton1);
                }
    
                if (newButton2 != null)
                {
                    newButton2.Click -= Button2Click;
                    chartTraderButtonsGrid.Children.Remove(newButton2);
                }
    
                if (newButton3 != null)
                {
                    newButton3.Click -= Button3Click;
                    myButtonsGrid.Children.Remove(newButton3);
                }
    
                if (newButton4 != null)
                {
                    newButton4.Click -= Button4Click;
                    myButtonsGrid.Children.Remove(newButton4);
                }
    
                if (chartTraderButtonsGrid != null)
                    chartTraderButtonsGrid.RowDefinitions.RemoveAt(chartTraderButtonsGrid.RowDefinitions.Count - 1);
    
                if (chartTraderGrid != null && myButtonsGrid != null)
                {
                    chartTraderGrid.Children.Remove(myButtonsGrid);
                    chartTraderGrid.RowDefinitions.RemoveAt(chartTraderGrid.RowDefinitions.Count - 1);
                }
            }
        }
    }
    
    #region NinjaScript generated code. Neither change nor remove.
    
    namespace NinjaTrader.NinjaScript.Indicators
    {
        public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
        {
            private ChartTraderCustomButtonsExample[] cacheChartTraderCustomButtonsExample;
            public ChartTraderCustomButtonsExample ChartTraderCustomButtonsExample()
            {
                return ChartTraderCustomButtonsExample(Input);
            }
    
            public ChartTraderCustomButtonsExample ChartTraderCustomButtonsExample(ISeries<double> input)
            {
                if (cacheChartTraderCustomButtonsExample != null)
                    for (int idx = 0; idx < cacheChartTraderCustomButtonsExample.Length; idx++)
                        if (cacheChartTraderCustomButtonsExample[idx] != null &&  cacheChartTraderCustomButtonsExample[idx].EqualsInput(input))
                            return cacheChartTraderCustomButtonsExample[idx];
                return CacheIndicator<ChartTraderCustomButtonsExample>(new ChartTraderCustomButtonsExample(), input, ref cacheChartTraderCustomButtonsExample);
            }
        }
    }
    
    namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
    {
        public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
        {
            public Indicators.ChartTraderCustomButtonsExample ChartTraderCustomButtonsExample()
            {
                return indicator.ChartTraderCustomButtonsExample(Input);
            }
    
            public Indicators.ChartTraderCustomButtonsExample ChartTraderCustomButtonsExample(ISeries<double> input )
            {
                return indicator.ChartTraderCustomButtonsExample(input);
            }
        }
    }
    
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
        {
            public Indicators.ChartTraderCustomButtonsExample ChartTraderCustomButtonsExample()
            {
                return indicator.ChartTraderCustomButtonsExample(Input);
            }
    
            public Indicators.ChartTraderCustomButtonsExample ChartTraderCustomButtonsExample(ISeries<double> input )
            {
                return indicator.ChartTraderCustomButtonsExample(input);
            }
        }
    }
    
    #endregion
    ​

    #2
    Hello gyilaoliver,

    Thank you for your post.

    This error is indicating a variable was used that is null (meaning it has no value assigned). The variable is an object reference, in that when the variable is used, the object it is pointed to is returned.

    Checking for Null References - https://ninjatrader.com/support/help...references.htm

    To determine what the source of the error is you will need to debug your strategy using print statements.

    It's not clear to me from the script which variable could be leading to the object reference error, so I suggest you add a print statement every few lines of code and then observe the output window when you apply the strategy.

    The last print statement shown in the output window would indicate the error occurs after that print statement, you can then add further print statements to zero in on the offending code. After you find the exact object returning null, you could add a condition check in the script to check that the value is not null.

    Below is a link to a forum post that demonstrates how to use prints to understand behavior.
    ​https://support.ninjatrader.com/s/article/Developer-Guide-Debugging-using-Print-and-TraceOrders

    Comment


      #3
      Hi Gaby, thanks for the reply.

      I added Print functions to the code, now it looks like this :
      Code:
      protected override void OnBarUpdate()
              {
                  if(State == State.Historical)
                      return;
              if ( State != State.Historical )
              {
                  
                  
      
                  if (CurrentBars[0] < 3)
                      return;
                  
                  Print(Instrument+ "   "+ enterlon+"   "+entershor);
                  
                  if ( enterlon )
                  {
                  //private Order stopOrder = null;
                  //    Order xOrder;
                  double high = Math.Max(Open[1], Close[1]);
                  double low = Math.Min(Open[1], Close[1]);
                  double stopprice = high + (high-low)/2;
                      Print(stopprice);
                   //if (stopOrder == null )
                       xOrder = myAccount.CreateOrder(Instrument, OrderAction.Buy, OrderType.StopMarket, OrderEntry.Automated, TimeInForce.Gtc, 1, 0, stopprice, "myOCO", "mystopOrder", Core.Globals.MaxDate, null);
                  
                   Print(xOrder);
       
      
                  myAccount.Submit(new[] { xOrder });    
                      
                  enterlon = false;
                  }
                  
                  
                  
              }
              }​
      The last print is the stopprice value, the xOrder value does not print, after that the above mentioned error prints.
      Click image for larger version

Name:	image.png
Views:	89
Size:	61.2 KB
ID:	1313958

      Comment


        #4
        Hello gyilaoliver,

        Comment out that line after the print, then test again. Are you still getting the error? Uncomment the line, and see if the error returns. If it does, then we can confirm this is the line of code throwing the error.

        I recommend using prints to determine exactly which value in that line is returning null, by printing out each value being used.

        Comment


          #5
          Hi Gaby,

          I found the problem, the myAccount value was null.
          Now I fixed the probem, but ran into another one.

          If I press Button 1, the indicator places the prder exactly as I want it, but if I cancel it and want to place another order, I get the following error:
          Click image for larger version

Name:	image.png
Views:	89
Size:	29.0 KB
ID:	1313962

          What can I do to set another OCO ID?​

          Comment


            #6
            Update : fixed this one as well by disabling the OCO mode ( ctrl + z ) and changing the OCO ID from the code to "".
            Now one last thing would be great if you could help me, right now buttons 3 and 4 are located below the ATM part of the chart trader, how can i fix it to be right below buttons 1 and 2 ?
            Click image for larger version

Name:	image.png
Views:	113
Size:	125.0 KB
ID:	1313964

            Comment


              #7
              Hello gyilaoliver,

              I'm glad to hear you were able to fix the error.

              If you have a new inquiry, we kindly ask that you please post a new thread.

              Please note, any time you reply to a post, this will go to the person you are working with. Reply instead of starting a new post when you would like to continue investigating an existing inquiry.

              Any time you start a new thread, this will create a new inquiry and a new case ticket, which will be answered by the first person available and may not be the person you are previously working with. Start a new thread instead of a reply when you have a new question that is unrelated to a previous inquiry. This will allow us to properly track each issue.

              We appreciate your cooperation in this regard.

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
              0 responses
              649 views
              0 likes
              Last Post Geovanny Suaza  
              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
              0 responses
              370 views
              1 like
              Last Post Geovanny Suaza  
              Started by Mindset, 02-09-2026, 11:44 AM
              0 responses
              109 views
              0 likes
              Last Post Mindset
              by Mindset
               
              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
              0 responses
              574 views
              1 like
              Last Post Geovanny Suaza  
              Started by RFrosty, 01-28-2026, 06:49 PM
              0 responses
              576 views
              1 like
              Last Post RFrosty
              by RFrosty
               
              Working...
              X