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

NullReferenceException

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

    NullReferenceException

    I am getting a NullReferenceException in my code. I know why, but do not know the solution to fix it.
    I have wrote a separate class called DataSniffer. This class is being used to store a bunch of methods that look for anomalies in market data. For example, the current method in the class
    Code:
    findOutlier()
    checks to see if the range of the most recent bar is x percent greater than the average range of the past y bars. It will then set a boolean to either true or false depending on if the most recent bar is an anomaly or not. I want to keep these types of calculations in the DataSniffer class as it really tidies up the code in the main strategy. All I have to do in the main strategy is create a new DataSniffer object, call the method I want, and get my results. It really reduces the amount of code in the main strat.

    SO - The problem I am having is - I am getting a NullReferenceException when I try to call the
    Code:
    findOutlier()
    method in my main script. I used Debug Mode and found that the code breaks when I call
    Code:
    Bars.GetHigh(0)
    in the DataSniffer
    Code:
    findOutlier()
    method. I am assuming this is because the DataSniffer class has not initialized a BarsArray or something. Basically, the script is trying to call
    Code:
    Bars
    but has no bars to reference. So when I run my strategy I am getting the all too common error of
    Code:
    Error on calling 'OnBarUpdate' method on Bar 150: Object reference not set to an instance of an object.
    I think the solution here is to load a main instrument in the DataSniffer class so it can reference a
    Code:
    Bars
    object, but I don't know how to do that.

    Below are the scripts - I have also attached the .cs files.

    DataSniffer:
    Code:
    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class DataSniffer : Strategy
    {
    public bool isOutlier {get; private set;}
    public bool outlierIsUpBar {get; private set;}
    
    /// <summary>
    /// Checks to see if the most recent bar is x percent larger in range compared to the past y bars
    /// </summary>
    /// <param name="outlierPercent">Checks to see if the most recent bar is x percent greater than the dataset average</param>
    /// <param name="dataSize">Number of bars to calculate average range for</param>
    public void findOutlier(double outlierPercent, int dataSize)
    {
    // the sum of every bar range
    double currentBarRange = Bars.GetHigh(0) - Bars.GetLow(0);
    double barRangeTotal = 0;
    //the average range of each bar ran through
    double barRangeAverage = 0;
    //A list that populates with the range of each bar. Bar range is defined by dataSize parameter
    List<double> barRange = new List<double>();
    //iterate through x bars (besides the most recent bar) and calculate the range. Append range to list.
    for(int x = 1; x < dataSize; x++)
    {
    double range = 0;
    range = Bars.GetHigh(x) - Bars.GetLow(x);
    barRange.Append(range);
    }
    //iterate through the barRange list, add up all the values
    for(int i = 0; i < barRange.Count; i++)
    {
    barRangeTotal = barRangeTotal + barRange[i];
    }
    //divide the sum of the barRange list by its size to find the average bar range.
    barRangeAverage = barRangeTotal / barRange.Count;
    
    //compare the average range to the most recent bar range and decide whether or not it is an outlier.
    if(barRangeAverage * ((outlierPercent/100) + 1) < currentBarRange)
    {
    this.isOutlier = true;
    Print("The most recent closed bar is an outlier");
    }
    else
    {
    this.isOutlier = false;
    Print("The most recent closed bar is not an outlier");
    }
    //Clears the bar range list for the next use.
    barRange.Clear();
    }
    }
    }
    Here is the Main Strategy Code:
    Code:
    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class fxTesting : Strategy
    {
    DataSniffer mySniffer = new DataSniffer();
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "fxTesting";
    Calculate = Calculate.OnBarClose;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = true;
    ExitOnSessionCloseSeconds = 30;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 0;
    StartBehavior = StartBehavior.WaitUntilFlat;
    TimeInForce = TimeInForce.Gtc;
    TraceOrders = false;
    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
    StopTargetHandling = StopTargetHandling.PerEntryExecution;
    BarsRequiredToTrade = 150;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    }
    else if (State == State.Configure)
    {
    }
    }
    
    protected override void OnAccountItemUpdate(Cbi.Account account, Cbi.AccountItem accountItem, double value)
    {
    
    }
    
    protected override void OnConnectionStatusUpdate(ConnectionStatusEventArgs connectionStatusUpdate)
    {
    
    }
    
    protected override void OnExecutionUpdate(Cbi.Execution execution, string executionId, double price, int quantity,
    Cbi.MarketPosition marketPosition, string orderId, DateTime time)
    {
    
    }
    
    protected override void OnFundamentalData(FundamentalDataEventArgs fundamentalDataUpdate)
    {
    
    }
    
    protected override void OnMarketData(MarketDataEventArgs marketDataUpdate)
    {
    
    }
    
    protected override void OnMarketDepth(MarketDepthEventArgs marketDepthUpdate)
    {
    
    }
    
    protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice,
    int quantity, int filled, double averageFillPrice,
    Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
    {
    
    }
    
    protected override void OnPositionUpdate(Cbi.Position position, double averagePrice,
    int quantity, Cbi.MarketPosition marketPosition)
    {
    
    }
    
    protected override void OnBarUpdate()
    {
    if(CurrentBars[0] < BarsRequiredToTrade) return;
    mySniffer.findOutlier(20, 100);
    if(mySniffer.isOutlier && Position.MarketPosition == MarketPosition.Flat)
    {
    EnterLong("outlier");
    SetStopLoss(CalculationMode.Pips, 25);
    SetProfitTarget(CalculationMode.Pips, 25);
    }
    }
    }
    }
    Attached Files

    #2
    Hi, thanks for writing in. The Sniffer class is trying to use its own Bars object which is null because it's not being instantiated from a chart. You would need to pass in the host strategies Bars object into the findOutlier() method and use that instead.

    Kind regards,
    -ChrisL
    Chris L.NinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_ChrisL View Post
      Hi, thanks for writing in. The Sniffer class is trying to use its own Bars object which is null because it's not being instantiated from a chart. You would need to pass in the host strategies Bars object into the findOutlier() method and use that instead.

      Kind regards,
      -ChrisL
      Hey Chris, how would I do this? I read through the NinjaScript resources but don't know how to do this. Would I need to put a parameter for it in the findOutlier such as ISeries<double> input and then call the method in the main script with findOutlier(BarsArray[0])?

      Comment


        #4
        Hi Void, you can do it like this:

        Code:
        //method definition
        findOutlier(Bars _bars, double outlierPercent, int dataSize) //use _bars instead of Bars object
        
        //calling the method
        mySniffer.findOutlier(BarsArray[0], 20, 100);
        The sniffer class also doesn't/should not need to inherit the Strategy class either. This can be a standalone class in the Strategies namespace.

        Kind regards,
        -ChrisL
        Chris L.NinjaTrader Customer Service

        Comment


          #5
          Originally posted by NinjaTrader_ChrisL View Post
          Hi Void, you can do it like this:

          Code:
          //method definition
          findOutlier(Bars _bars, double outlierPercent, int dataSize) //use _bars instead of Bars object
          
          //calling the method
          mySniffer.findOutlier(BarsArray[0], 20, 100);
          The sniffer class also doesn't/should not need to inherit the Strategy class either. This can be a standalone class in the Strategies namespace.

          Kind regards,
          -ChrisL
          Hey Chris, your fix worked. However, I tried making the Sniffer class as a standalone class in Visual Studio using the NinjaTrader Custom project. I included the ninjascript using declarations but it would not let me access methods like Bars.GetHigh. I could only access a few of Ninjas methods. I created the Sniffer file as a Strategy as a workaround this problem.

          Comment


            #6
            Originally posted by NinjaTrader_ChrisL View Post
            H
            The sniffer class also doesn't/should not need to inherit the Strategy class either. This can be a standalone class in the Strategies namespace.
            Even better, just make findOutlier a standalone private method inside
            your strategy, then access to 'Bars' is readily available.

            By putting findOutlier in its own class, and then adding extra arguments,
            and trying to place it in a separate file -- are you adding complexity for no reason?

            Comment


              #7
              Originally posted by bltdavid View Post

              Even better, just make findOutlier a standalone private method inside
              your strategy, then access to 'Bars' is readily available.

              By putting findOutlier in its own class, and then adding extra arguments,
              and trying to place it in a separate file -- are you adding complexity for no reason?
              I wanted to continue to add more methods to the class, and also make it it's own class so I could easily call it into other strategies.

              Comment


                #8
                Good idea.

                Try looking at this example.

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by DayTradingDEMON, Today, 09:28 AM
                3 responses
                19 views
                0 likes
                Last Post NinjaTrader_ChelseaB  
                Started by Stanfillirenfro, Today, 07:23 AM
                9 responses
                23 views
                0 likes
                Last Post NinjaTrader_ChelseaB  
                Started by George21, Today, 10:07 AM
                0 responses
                8 views
                0 likes
                Last Post George21  
                Started by navyguy06, Today, 09:28 AM
                1 response
                7 views
                0 likes
                Last Post NinjaTrader_Gaby  
                Started by cmtjoancolmenero, Yesterday, 03:58 PM
                8 responses
                33 views
                0 likes
                Last Post NinjaTrader_ChelseaB  
                Working...
                X