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

'OnBarUpdate' method: Object reference not set to an instance of an object.

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

    'OnBarUpdate' method: Object reference not set to an instance of an object.

    I am trying to develop a multi-timeframe strategy and get the following error as soon as I try to enable the strategy. I have the print(), but I cannot start the strategy before it disables. I was trying to use BarsSinceEntryExecution(), and I changed to BarsSinceEntryExecution(0, "LE01", 0) to fix the initial message (You must use the overload that has barinprogess parameter when calling the BarsSinceEntryExecution().

    Would you please help me?

    Code:
    protected override void OnBarUpdate()
            {
                
               
                //Make sure we have enough bars to stablize strategy
                if(CurrentBar < BarsRequiredToTrade || CurrentBars[0] < 100 || CurrentBars[1] < 100)
                    return;
                
                //Process primary data series only, secondary bars for refernce only
                if (BarsInProgress != 0)
                    return;
                
    
                // at the start of a new exchange session, reset the currentPnL and maximum favorable excursion for a new day of trading
                if (Bars.IsFirstBarOfSession)
                {
                    SessionReset(false);                
                }
                
             
                
                //Cancel any long open entry orders at timeout, reset entry bar
                if (barNumberOfLongEntries != 0)
                    if ( CurrentBars[0] > barNumberOfLongEntries + OrderActiveBars )
                        CancelOpenOrders();
                    
                //Cancel any short open entry orders at timeout, reset entry bar
                if (barNumberOfShortEntries != 0)
                    if ( CurrentBars[0] > barNumberOfShortEntries + OrderActiveBars )
                        CancelOpenOrders();    
                
              
                if ( Position.MarketPosition == MarketPosition.Flat && (BarsSinceEntryExecution(0, "SE11", 0) > 1 || BarsSinceEntryExecution(0, "SE11", 0) == -1))
                {    
                    
                    Compra1                 = RangodeOperacionCompra(Closes[0]);
                    Venta1                     = RangodeOperacionVenta(Closes[0]);
                    Range1                    = Range(Closes[0]);
                    largoEMA1                = SMA(Lows[0], 5);
                    cortoEMA1                = SMA(Highs[0], 5);
                    Range1SMA                = SMA(Range1, 100);
                    Range2SMA                = SMA(Range1, 50);
                    
                    //If we are already long, return
                    if ( Position.MarketPosition == MarketPosition.Short )
                    {
                        shortSignalOriginal = false;
                    }
                    
                    if (///CONFIDENTIAL)
                    
                                {
                                        Print(string.Format("Short: {0} > {1}; {2} < {3}; {4} > {5}; {6} > {7}; {8} < {9}", sma[0], Volumes[0][0], Volumes[0][1]*1.2, Volumes[0][0], smaD[20], smaD[1], smaD[0], smaD[1], Closes[1][0], smaD[0]));
                                        barNumberOfShortEntries = CurrentBars[0];
                                        shortSignalOriginal = true;
                                        Draw.VerticalLine(this, CurrentBar.ToString(), 0, Brushes.Red, DashStyleHelper.Solid, 4, true);
                                        if(entryOrder01 != null)
                                        CancelOrder(entryOrder01);
                                        
                                        EnterShortLimit(0, true, Convert.ToInt32(Order01LotSize), Closes[0][0] + (Range2SMA[1] / TickSize) * 0.5, "SE11");    
                                        SetTrailStop("SE11", CalculationMode.Ticks, (Range2SMA[1] / TickSize) * 1, false);
                                        
                                }
                    
                    shortSignalOriginal =false;
                }
                    
                    //Check for signals and fire orders if we have a new signal, no open entry orders, in our time window, and not at max loss
                if ( TimeToTrade() && barNumberOfLongEntries == 0 && okToEnter )
                {
                    if (LongSignal())
                     {
                        //Reverse if we are short or have open short orders
                        if (Position.MarketPosition == MarketPosition.Short || barNumberOfShortEntries > 0)
                        {
                            ShortReverse();
                        }
    
                                        
                     }
                            
                    if (ShortSignal())
                     {
                        //Reverse if we are long or have open long orders
                        if ( Position.MarketPosition == MarketPosition.Long || barNumberOfLongEntries > 0 )
                        {
                            LongReverse();
                        }
                                                            
                                        
                     }
                }
                
                // Resets the stop loss to the original value when all positions are closed
                if (Position.MarketPosition == MarketPosition.Flat)
                {
                    
                    SetTrailStop("LE01", CalculationMode.Ticks, (Range2SMA[1] / TickSize) * 1, false);
                    SetTrailStop("SE11", CalculationMode.Ticks, (Range2SMA[1] / TickSize) * 1, false);
                    
                    maximumTI = 0;
                    minimumTI = 0;
                }
                
                
                if (Position.MarketPosition == MarketPosition.Short && (BarsSinceEntryExecution(0, "SE11", 0) > 1 || BarsSinceEntryExecution(0, "SE11", 0) == -1))
                {
                    // Once the price is smaller than entry price-20 ticks, set trailingstop
                    if (Closes[0][0] > Position.AveragePrice - (Range2SMA[1] / TickSize) * 0.3)
                    {
                        
                        SetTrailStop("SE11", CalculationMode.Ticks, (Range2SMA[1] / TickSize) * 0.9, false); Print(string.Format("{0} | Cambio1C", Time[0] ));
                        //Draw.VerticalLine(this, CurrentBar.ToString(), 0, Brushes.White, DashStyleHelper.Dash, 1, true);
                        // match the text brush to what the user has configured on their chart        
                        Draw.TextFixed(this, "myTextFixed", "First Stop Change!", TextPosition.BottomRight, ChartControl.Properties.ChartText,
                          ChartControl.Properties.LabelFont, Brushes.Blue, Brushes.Transparent, 0);
                    }
                    
                    if (Closes[0][0] > Position.AveragePrice - (Range2SMA[1] / TickSize) * 0.5)
                    {
                        
                        SetTrailStop("SE11", CalculationMode.Ticks, (Range2SMA[1] / TickSize) * 0.8, false); Print(string.Format("{0} | Cambio1C", Time[0] ));
                        //Draw.VerticalLine(this, CurrentBar.ToString(), 0, Brushes.Gray, DashStyleHelper.Dash, 1, true);
                        // match the text brush to what the user has configured on their chart        
                        Draw.TextFixed(this, "myTextFixed", "Second Stop Change!", TextPosition.BottomRight, ChartControl.Properties.ChartText,
                          ChartControl.Properties.LabelFont, Brushes.Blue, Brushes.Transparent, 0);
                    }
                    if (Closes[0][0] > Position.AveragePrice - (Range2SMA[1] / TickSize) * 0.7)
                    {
                        
                        SetTrailStop("SE11", CalculationMode.Ticks, (Range2SMA[1] / TickSize) * 0.7, false); Print(string.Format("{0} | Cambio2C", Time[0] ));
                        //Draw.VerticalLine(this, CurrentBar.ToString(), 0, Brushes.Pink, DashStyleHelper.Dash, 1, true);
                        // match the text brush to what the user has configured on their chart        
                        Draw.TextFixed(this, "myTextFixed", "Third Stop Change!", TextPosition.BottomRight, ChartControl.Properties.ChartText,
                          ChartControl.Properties.LabelFont, Brushes.Blue, Brushes.Transparent, 0);
                        }
                    if (Closes[0][0] > Position.AveragePrice - (Range2SMA[1] / TickSize) * 0.9)
                    {
                        
                        SetTrailStop("SE11", CalculationMode.Ticks, (Range2SMA[1] / TickSize) * 0.6, false);
                        //Draw.VerticalLine(this, CurrentBar.ToString(), 0, Brushes.Brown, DashStyleHelper.Dash, 1, true);
                        // match the text brush to what the user has configured on their chart        
                        Draw.TextFixed(this, "myTextFixed", "Fourth Stop Change!", TextPosition.BottomRight, ChartControl.Properties.ChartText,
                          ChartControl.Properties.LabelFont, Brushes.Blue, Brushes.Transparent, 0);
                    }
                }
                
                //evita que se devuelva
                            
                if ((Position.MarketPosition != MarketPosition.Flat) && (Position.GetUnrealizedProfitLoss(PerformanceUnit.Ticks, Closes[0][0]) > (Range2SMA[1] / TickSize) * 0.8))
                {
                    if (Position.GetUnrealizedProfitLoss(PerformanceUnit.Ticks, Closes[0][0]) > maximumTI)
                    {
                        maximumTI = Position.GetUnrealizedProfitLoss(PerformanceUnit.Ticks);
                    }
                    
                    if (maximumTI - Position.GetUnrealizedProfitLoss(PerformanceUnit.Ticks) >= (Range2SMA[1] / TickSize) * 0.3)
                        {
                            
                            ExitLong();
                            ExitShort();
                            //Draw.VerticalLine(this, CurrentBar.ToString(), 0, Brushes.White, DashStyleHelper.Dash, 2, true);
                            // match the text brush to what the user has configured on their chart        
                            Draw.TextFixed(this, "myTextFixed", "First Profit Protection Activated!", TextPosition.BottomRight, ChartControl.Properties.ChartText,
                              ChartControl.Properties.LabelFont, Brushes.Blue, Brushes.Transparent, 0);
                        }
                }
                
                if ((Position.MarketPosition != MarketPosition.Flat) && (Position.GetUnrealizedProfitLoss(PerformanceUnit.Ticks, Closes[0][0]) > (Range2SMA[1] / TickSize) * 1))
                {
                    if (Position.GetUnrealizedProfitLoss(PerformanceUnit.Ticks, Closes[0][0]) > maximumTI)
                    {
                        maximumTI = Position.GetUnrealizedProfitLoss(PerformanceUnit.Ticks);
                    }
                    
                    if (maximumTI - Position.GetUnrealizedProfitLoss(PerformanceUnit.Ticks) >= (Range2SMA[1] / TickSize) * 0.2)
                        {
                            
                            ExitLong();
                            ExitShort();
                          
                            Draw.TextFixed(this, "myTextFixed", "Second Profit Protection Activated!", TextPosition.BottomRight, ChartControl.Properties.ChartText,
                              ChartControl.Properties.LabelFont, Brushes.Blue, Brushes.Transparent, 0);
                        }
                }
                
                if ((Position.MarketPosition != MarketPosition.Flat) && (Position.GetUnrealizedProfitLoss(PerformanceUnit.Ticks, Closes[0][0]) > (Range2SMA[1] / TickSize) * 1.2))
                {
                    if (Position.GetUnrealizedProfitLoss(PerformanceUnit.Ticks, Closes[0][0]) > maximumTI)
                    {
                        maximumTI = Position.GetUnrealizedProfitLoss(PerformanceUnit.Ticks);
                    }
                    
                    if (maximumTI - Position.GetUnrealizedProfitLoss(PerformanceUnit.Ticks) >= (Range2SMA[1] / TickSize) * 0.1)
                        {
                            
                            ExitLong();
                            ExitShort();
                            //Draw.VerticalLine(this, CurrentBar.ToString(), 0, Brushes.Gray, DashStyleHelper.Dash, 2, true);
                            Draw.TextFixed(this, "myTextFixed", "Third Profit Protection Activated!", TextPosition.BottomRight, ChartControl.Properties.ChartText,
                              ChartControl.Properties.LabelFont, Brushes.Blue, Brushes.Transparent, 0);
                        }
                }
                    
                                              
            } //End of OnBarUpdate​

    #2
    Hello Jorge.andres.o,

    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.



    Please let me know if I can assist further.
    Gaby V.NinjaTrader Customer Service

    Comment


      #3
      Gaby,

      thank you for the help. I got it

      Comment

      Latest Posts

      Collapse

      Topics Statistics Last Post
      Started by ageeholdings, Today, 07:43 AM
      0 responses
      3 views
      0 likes
      Last Post ageeholdings  
      Started by pibrew, Today, 06:37 AM
      0 responses
      4 views
      0 likes
      Last Post pibrew
      by pibrew
       
      Started by rbeckmann05, Yesterday, 06:48 PM
      1 response
      14 views
      0 likes
      Last Post bltdavid  
      Started by llanqui, Today, 03:53 AM
      0 responses
      6 views
      0 likes
      Last Post llanqui
      by llanqui
       
      Started by burtoninlondon, Today, 12:38 AM
      0 responses
      12 views
      0 likes
      Last Post burtoninlondon  
      Working...
      X