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

Cannot apply indexing with [] to an expression of type "double"

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

    Cannot apply indexing with [] to an expression of type "double"

    Hey guys,

    In my trading strategy, Im running multiple time frames and instruments on "On each tick" settings. Im trying to compare previous opens and closes referring to only my primary time frame. Originally I had Open[3] < Close[2] but I was getting values from the other instrument. I used information from the link below and changed it to Open[0][3] < Close[0][2] but now im getting the error, Cannot apply indexing with [] to an expression of type "double". What can i do to get this to work?

    #2
    Originally posted by Tmaninc View Post
    Hey guys,

    In my trading strategy, Im running multiple time frames and instruments on "On each tick" settings. Im trying to compare previous opens and closes referring to only my primary time frame. Originally I had Open[3] < Close[2] but I was getting values from the other instrument. I used information from the link below and changed it to Open[0][3] < Close[0][2] but now im getting the error, Cannot apply indexing with [] to an expression of type "double". What can i do to get this to work?
    That should be,

    Code:
    [COLOR=#000000]Open[/COLOR][COLOR=#FF0000]s[/COLOR][COLOR=#000000][0][3] < Close[/COLOR][COLOR=#FF0000]s[/COLOR][COLOR=#000000][0][2][/COLOR]

    The 's' is missing in your code.


    Comment


      #3
      Btw, that error message is correct, and deserves deeper attention.

      You coded 'Open[0][3]' and got an error.

      Why?
      The compiler knows 'Open[0]' resolves to a double, so applying '[3]' to this
      double is illegal code -- so, the error message is spot on and well-worded.

      When you use 'Opens[0][3]', it works.

      Why?
      The compiler knows 'Opens[0]' resolves to a DataSeries, so applying '[3]' to
      this DataSeries is correct code.

      All error messages should be analyzed and understood, learn to trust them
      as completely correct -- they are worthy of being deciphered -- study them
      vigorously until you can 'see' why the compiler is complaining.

      What about compiler error messages you've never encountered?
      Copy & paste the entire message into Google ... trust me, it will be found.

      Why is this useful?
      Solo programming (aka, alone, esp after midnight) requires a deeper set
      of programmer/detective skills -- 'knowing' your compiler is extremely key.

      Just some extra 2˘.
      Last edited by bltdavid; 08-11-2020, 03:46 AM.

      Comment


        #4
        Thanks for your help and appreciate the extra tip, anything helps. I just started learning how to code so I can edit my strategy outside of NinjaTraders Strategy Builder. Thanks again

        Comment


          #5
          I have two data series added in my strategy. I wan to add a condition if the volume on the current bar is greater than the Max Volume in the last 5 bars. How would I code this working with multiple time frames or multiple insruemnts.

          My current code works when I apply it to instrument in the chart window: (Volume[0] > Max(Volume, 5)[1].
          I am getting error message: "Cannot Apply indexing with ][ to an expression of type double" when I enter the following code: (Volumes[1][0] > Max(Volume, 5)[1][0]

          Comment


            #6
            Try this,

            Volumes[1][0] > Max(Volumes[1], 5)[0]

            Comment


              #7
              Thanks, that works.

              Comment


                #8
                Hi David,

                I am still getting a few errors: I am hoping if more guidance and I am hoping you or someone can me with this.
                My objective is to read from a file containing list of symbols then I want an output which prints a list of stocks that are gaping.

                Output will be something like this:
                "Symbol | NetChange | Price | Volume"

                My current code is able to read symbols from a file but it is giving me an error that "Object Reference not set to an instance of an object".
                This error is coming from line: double NetChange = CDOHL.Opens[1][0] - PDOHLC.Closes[1][0]; // Get Net Change fom Prev Day.

                Here is the code for method I am writing:
                private void SymsList()
                {
                string symbolName = null;
                if(!File.Exists(filepath1))
                {
                Print("Symbols List was not found. Creating a New Symbol List");
                }
                else
                {
                string[] symbolsList= File.ReadAllLines(filepath1);
                int i = 0;
                foreach(string symbol in symbolsList)
                {
                symbolName = symbolsList[i];
                Print("Adding Data Series for this symbol "+symbolName.ToString());
                AddDataSeries(symbolName, BarsPeriodType.Minute, 1);
                AddDataSeries(symbolName, BarsPeriodType.Day, 1);
                double NetChange = CDOHL.Opens[1][0] - PDOHLC.Closes[1][0]; // Get Net Change fom Prev Day.
                if((NetChange > 1 || NetChange < -1)&& (Volumes[1][0] > MAX(Volumes[1], 60)[0]))
                {
                string GappingUp = symbolName + "|" + NetChange + "|" + Volumes[1][0] + "|" + Environment.NewLine;
                Print(GappingUp);
                }
                i++;
                }
                }


                Thanks,

                Comment


                  #9
                  Hello bjunaid,

                  Thank you for your post.

                  When receiving the error message "Object Reference not set to an instance of an object" for a line of code, each individual object should be checked within that line to make sure those objects are not returning null. You could check if an object is null or not by using a Print to print out the values for your method to a NinjaScript Output window.

                  Also, I see that you are using AddDataSeries for that method in your script. Are you calling that method within State.SetDefaults or State.Configured? If this is the case, values would return null since the script has not started processing data at this point. Please note that accessing an indexed series should not be done before the script reaches a data processing state. You could, for example, print Close[0] in State.Realtime.

                  Here is a help guide link with more information about AddDataSeries - https://ninjatrader.com/support/help...dataseries.htm

                  And, here is a help guide link about OnStateChange - https://ninjatrader.com/support/help...tatechange.htm

                  Let us know if we may further assist
                  Brandon H.NinjaTrader Customer Service

                  Comment


                    #10
                    I think I am getting the error because AddDataSeries is not loading. How do I check if the symbol was added to the DataSeries and DataSeries was loaded.

                    I having tried running this code from State: Configured, Default, Historical, DataLoaded, Realtime.

                    I have tried changing the code to:
                    private void SymsList()
                    {
                    string symbolName = null;
                    if(!File.Exists(filepath1))
                    {
                    Print("Symbols List was not found. Creating a New Symbol List");
                    }
                    else
                    {
                    string[] symbolsList= File.ReadAllLines(filepath1);
                    int i = 0;
                    foreach(string symbol in symbolsList)
                    {
                    symbolName = symbolsList[i];

                    if(State == State.Configure)
                    {
                    AddDataSeries(symbolName, BarsPeriodType.Minute, 1);
                    //AddDataSeries(symbolName, BarsPeriodType.Day, 1);
                    Print("Adding Data Series for: "+symbolName.ToString() + " | " + Close[1].ToString("$#,###.##"));
                    if(State == State.DataLoaded)
                    {

                    double NetChange = CDOHL.Opens[1][0] - PDOHLC.Closes[1][0]; // Get Net Change fom Prev Day.
                    if(NetChange > 1 && (Volumes[1][0] > MAX(Volumes[1], 60)[0]))
                    {
                    string GappingUp = symbolName + "|" + NetChange + "|" + Volumes[1][0] + "|" + Environment.NewLine;
                    Print(GappingUp);
                    }
                    }
                    }
                    i++;
                    }
                    }
                    }



                    Comment


                      #11
                      Hello bjunaid,

                      Thank you for that information.

                      I see in your code that you are calling your method in OnStateChange(). The way Multi-TimeFrame/Multi-Instrument scripts work is as follows:

                      AddDataSeries is used in OnStateChange when the State reaches State.Configure. Then in OnBarUpdate, you would reference the added series to get information from that series. Please see the example script I have attached that demonstrates how to add a data series for a Multi-TimeFrame/Multi-Instrument script. The script also demonstrates how to reference the added data series to get volume and max volume at 60 bars for the added series.

                      To understand why these Multi-TimeFrame/Multi-Instrument errors are occurring in your script, please review the help guide documentation linked below. The SampleMultiTimeFrame and SampleMultiInstrument strategies that come with NinjaTrader may be used alongside the help guide link for learning about Multi-Timeframe/Instrument scripts.

                      Multi-Timeframe and Instruments - https://ninjatrader.com/support/help...nstruments.htm

                      Please let us know if we may further assist.
                      Attached Files
                      Brandon H.NinjaTrader Customer Service

                      Comment


                        #12
                        Please diregard
                        Last edited by bjunaid; 09-20-2020, 08:37 PM.

                        Comment


                          #13
                          Hi Brandon

                          I was able to get rewrite the code and get it to work however I am running into another error:

                          1. I am giving my list the entire S&P 500 stock symbols. Is there a limitation to the number of data series I can add because my scrip works when I give it 30 stocks names and throw an error when I add the entire S&P 500 list. The error I get is Error on calling 'OnStateChange' method: Object reference not set to an instance of an object.

                          I tried the print function by placing it right before adding symbols to the dataseries in State.Configure and it prints all 500 names.
                          I tried the print function by placing it in OnBarUpdate function and that is where it goes in a limbo. I don't know what is causing it.

                          protected override void OnBarUpdate()
                          {
                          int di = 1; //Data Sereies Index
                          int i = 0; //symbole index
                          foreach(string symbol in symbolsList)
                          {
                          Print("Processing symbol: " + symbolsList[i].ToString());
                          if(State == State.Historical
                          && BarsInProgress == di
                          && Times[di][0] == currDateTime)
                          {
                          prevdayClose = PriorDayOHLC(BarsArray[di]).Close[0];
                          currdayOpen = CurrentDayOHL(BarsArray[di]).Open[0];
                          currdayVolume = Volumes[di][0];
                          double NetChange = currdayOpen - prevdayClose;
                          string Gappers = Time[0].ToString()
                          + " | " + symbolsList[i].ToString()
                          + " | " + NetChange.ToString("$#,###.##")
                          + " | " + currdayOpen.ToString()
                          + " | " + prevdayClose.ToString()
                          + " | " + currdayVolume.ToString("#,####");
                          Print("Gapper: " + Gappers);
                          }
                          i++;
                          di++;
                          }//end loop
                          }endonbarupdate.



                          2. How do I handle the error message when stock symbol is not found?

                          Thanks,

                          Comment


                            #14
                            Hello bjunaid,

                            Thank you for that information.

                            According to the error message, you have a null reference within OnStateChange(). I recommend adding prints to each line in OnStateChange(), not just State.Configure, in order to locate which reference is returning null in your script.

                            Another option would be to comment out segments of code in your script until you reach a point where you know the code works as expected. From there you can then add more layers of complexity. With each additional layer, you want to ensure it works as expected before adding more layers.

                            Please review the debugging tips linked below for more information.

                            Debugging Tips - https://ninjatrader.com/support/help...script_cod.htm

                            Debugging Demo - https://drive.google.com/file/d/1rOz...w?usp=drivesdk

                            Please let us know if we may further assist.
                            Brandon H.NinjaTrader Customer Service

                            Comment


                              #15
                              I'm getting the same error. Can't index a double....
                              I'm trying to reference Hist[2] or priotHistog[1] whichever will give the hist bar drawn two bars ago. So that I can create logic for a pivot.

                              As a rough example
                              IF bar[0] > bar[1] && bar[1] < bar[2]
                              draw pivotdown
                              else
                              IF bar[0] < bar[1] && bar[1] > bar[2]
                              draw pivotup


                              here's the part of the code I need help with, I tried umpteen different ways. It either won't compile, or if I can get it to compile, it won't draw anything.
                              THANKS!


                              protected override void OnBarUpdate()
                              {
                              if (CurrentBar == 0)
                              return;

                              double Macd = MACD(Fast, Slow, Smooth)[0];
                              double Signal = MACD(Fast, Slow, Smooth).Avg[0];
                              double Histog = Macd - Signal;
                              //double Histog2 = 0; // Macd - Signal; // HELP HERE? <<<<<<<<<<<<


                              Value[0] = Macd;
                              Avg[0] = Signal;
                              Hist[0] = Histog;
                              //Hist[2] = Histog2; // HELP HERE ? <<<<<<<<<<<<

                              double priorMacd = Value[1];
                              double priorHistog = Hist[1];
                              double priorSignal = Avg[1];
                              //double priorHistog2 = priorHistog[1]; // HELP HERE ? <<<<<<<<<<<<

                              (.....(removed a bunch of lines here to make it easier to post. )

                              if ( ShowPivots)
                              {
                              if (Histog < priorHistog && priorHistog > .35)// && priorHistog > priorHistog[1]) // (Hist[0] < Hist[1] && Hist[1] > Hist[2]) // HELP HERE? <<<<<<<<<<<<<<
                              Draw.Diamond(this, "MyDiamond" + CurrentBar, true, 0, High[0] + 3 * TickSize, PivotDownColor);

                              else if (Histog > priorHistog && priorHistog < -.35)// && priorHistog < priorHistog[1]) // HELP HERE? <<<<<<<<<<<<
                              Draw.Diamond(this, "MyDiamond" + CurrentBar, true, 0, Low[0] - 3 * TickSize, PivotUpColor);
                              }

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by algospoke, Today, 06:40 PM
                              0 responses
                              5 views
                              0 likes
                              Last Post algospoke  
                              Started by maybeimnotrader, Today, 05:46 PM
                              0 responses
                              7 views
                              0 likes
                              Last Post maybeimnotrader  
                              Started by quantismo, Today, 05:13 PM
                              0 responses
                              6 views
                              0 likes
                              Last Post quantismo  
                              Started by AttiM, 02-14-2024, 05:20 PM
                              8 responses
                              168 views
                              0 likes
                              Last Post jeronymite  
                              Started by cre8able, Today, 04:22 PM
                              0 responses
                              9 views
                              0 likes
                              Last Post cre8able  
                              Working...
                              X