Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

How to cause strings to retain values outside of the scope?

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

    How to cause strings to retain values outside of the scope?

    Hi,

    I have a very complicated indicator, but I've boiled down my problem to a simple example.
    I want to update a string in the following code and have it preserve its value throughout the various scopes, unless it is being updated,
    then I want it to keep the updated value. In order words to work like a double does, but with text:

    Code:
    private string currentDayValue = ""; // Declare the variable at the class level
    
    void OnBarUpdate()
    {
    if (Time[0].TimeOfDay == new TimeSpan(8, 0, 0))
    {
    currentDayValue = "Morning value"; // Change the value for morning
    }
    // Access the currentDayValue based on the set time ranges
    if (Time[0].TimeOfDay > new TimeSpan(8, 0, 0) && Time[0].TimeOfDay <= new TimeSpan(12, 0, 0))
    {
    // Code that needs to remember that the string was set to at 8am is currently "Morning value".
    // I can set a double outside the scope and it will retain the value, but strings don't work like that.
    // Is there any way to get around this?
    }​
    else if (Time[0].TimeOfDay == new TimeSpan(18, 0, 0))
    {
    currentDayValue = "Evening value"; // Change the value for evening
    }
    else if (Time[0].TimeOfDay > new TimeSpan(18, 0, 0) && Time[0].TimeOfDay <= new TimeSpan(22, 0, 0))
    {
    // Code that needs to remember that the string was set to at 6pm which is "Evening value".
    }
    Thank you for advice in advance!

    #2
    Hello davydhnz,

    Thank you for your post.

    I'm not sure I fully understand what you are looking for in these comments:
    // Code that needs to remember that the string was set to at 8am is currently "Morning value".
    &
    // Code that needs to remember that the string was set to at 6pm which is "Evening value".

    You may compare strings in C# as described on the following publicly available page:
    Learn how to compare and order string values, with or without case, with or without culture specific ordering.


    To better understand the value of currentDayValue and when it is being updated, I suggest adding print statements throughout your script, such as the following examples after you change its value:

    Code:
    if (Time[0].TimeOfDay == new TimeSpan(8, 0, 0))
    {
    currentDayValue = "Morning value"; // Change the value for morning
    Print(Time[0] + " currentDayValue updated: " + currentDayValue);
    }
    Code:
    else if (Time[0].TimeOfDay == new TimeSpan(18, 0, 0))
    {
    currentDayValue = "Evening value"; // Change the value for evening
    Print(Time[0] + " currentDayValue updated: " + currentDayValue);
    }
    You can also print the value of currentDayValue throughout other portions of your code to understand what value is being kept and when the value is changing. For more information about using prints to debug a script:


    Please let us know if we may be of further assistance.​

    Comment


      #3
      I want the string to be available outside of the scope. If I set the string in if (Time[0].TimeOfDay == new TimeSpan(8, 0, 0))
      as soon as I close the nested brackets, whatever I set it to gets lost and is not available in
      if (Time[0].TimeOfDay > new TimeSpan(8, 0, 0) && Time[0].TimeOfDay <= new TimeSpan(12, 0, 0))

      like it would be if it were a double or an int. Make sense?

      Comment


        #4
        Originally posted by davydhnz View Post
        I want the string to be available outside of the scope. If I set the string in if (Time[0].TimeOfDay == new TimeSpan(8, 0, 0))
        as soon as I close the nested brackets, whatever I set it to gets lost and is not available in
        if (Time[0].TimeOfDay > new TimeSpan(8, 0, 0) && Time[0].TimeOfDay <= new TimeSpan(12, 0, 0))

        like it would be if it were a double or an int. Make sense?
        No, it doesn't make sense.

        I'm not sure you fully understand how C# works.

        Your variable currentDayValue is always in scope inside
        OnBarUpdate(), because you've defined currentDayValue
        as a class level private variable.

        Going out of scope when you 'close the nested brackets', well,
        that shouldn't be happening.

        You need to show us a lot more code, because from what I
        see, your code does not reflect the issue you're complaining
        about.

        Comment


          #5
          You made this comment in your code,

          // I can set a double outside the scope and it will
          // retain the value, but strings don't work like that.


          You need explain what you mean by this, because strings and doubles
          work exactly the same way in this regard.

          [EDIT: Read Emily's reply carefully, she is offering great
          advice on how to find the bug yourself.]

          Add this code,

          Print(currentDayValue);

          everywhere you are assigning to currentDayValue.

          I think you have a different bug, and I think you're confused
          as to probable cause.

          How to find that cause?

          Adding Print statements to your code is the Gold standard
          in finding bugs -- with using a heavy weight debugger like
          Visual Studio is a close second.

          For people who are really adept using VS, it may even be
          their number one choice -- but I prefer Print myself, adding
          Print statements is very fast.

          Last edited by bltdavid; 08-14-2023, 09:52 AM. Reason: Seriously, follow Emily's advice

          Comment


            #6
            Hello davydhnz,

            Thank you for your reply.

            The string will retain its value once updated. I have created a sample script similar to your snippet. At 8am, the string changes to "Morning" and at 6pm it changes to "Evening." The sample is attached. Perhaps the root of the behavior is the use of "if" and "else if" statements and you are not seeing the string being updated when expected. This could be confirmed with print statements such as the ones I previously suggested and the ones included in the attached example. When using if, else if, and else statements then the conditions are only evaluated depending on whether the preceding condition is true/false. For more details, please see the following publicly available resource regarding else if statements:
            W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.


            Please let me know if I may be of further assistance.
            Attached Files

            Comment


              #7
              Thank you both for your feedback.

              My indicator is over 2000 lines of code and I'm not ready to release it yet,
              but here is something you can verify that exhibits the same behaviour.

              Code:
              [HASHTAG="t3322"]region[/HASHTAG] 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.Gui.Tools;
              using NinjaTrader.Data;
              using NinjaTrader.NinjaScript;
              using NinjaTrader.Core.FloatingPoint;
              using NinjaTrader.NinjaScript.DrawingTools;
              #endregion
              
              //This namespace holds Indicators in this folder and is required. Do not change it.
              namespace NinjaTrader.NinjaScript.Indicators.DavidsIndicator s
              {
              
              public class StringsSaved : Indicator
              {
              
              int BiasNumber;
              string BiasArrow;
              Brush OutlineBrush;
              
              private NinjaTrader.Gui.Tools.SimpleFont CornerFont;
              private Brush Bullish_Signal_Brush;
              private Brush Bearish_Signal_Brush;
              private Brush Neutral_Brush;
              
              
              protected override void OnStateChange()
              {
              
              if (State == State.SetDefaults)
              {
              Description = "StringsSaved";
              Name = "StringsSaved";
              Calculate = Calculate.OnBarClose;
              IsOverlay = true;
              IsSuspendedWhileInactive = false;
              
              BiasNumber = 3;
              
              }
              else if (State == State.Configure)
              {
              CornerFont = new NinjaTrader.Gui.Tools.SimpleFont("AcheFont", 18) { Size = 40, Bold = true};
              }
              
              else if (State == State.DataLoaded)
              {
              DateTime dt = Time[0];
              TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
              
              Bullish_Signal_Brush = (SolidColorBrush)(new BrushConverter().ConvertFrom("#60258D25"));
              Bullish_Signal_Brush.Freeze();
              
              Neutral_Brush = (SolidColorBrush)(new BrushConverter().ConvertFrom("#60808080"));
              Neutral_Brush.Freeze();
              
              Bearish_Signal_Brush = (SolidColorBrush)(new BrushConverter().ConvertFrom("#60FF0000"));
              Bearish_Signal_Brush.Freeze();
              
              }
              }
              
              protected override void OnBarUpdate()
              { // Level 1
              
              
                              if (Time[0].TimeOfDay == new TimeSpan(8, 0, 0))
                              {
                              BiasNumber            = Math.Sign(Close[0] - Open[0]);
                              BiasArrow             = (BiasNumber == 1) ? "" : (BiasNumber == -1) ? "" : "Error - should only be up or down";
                              Brush OutlineBrush     = (BiasNumber == 1) ? Bullish_Signal_Brush : Bearish_Signal_Brush;
                              Print(BiasArrow + Time[0]);
                              }
                              // End of dt == dtEndTime​
              
              
                              if (Time[0].TimeOfDay > new TimeSpan(8, 0, 0))    
                              {    
                              Draw.TextFixed(this,
                              "Corner", " " + "Updated" + "\n" +
                              BiasArrow + " \b", TextPosition.TopLeft, Brushes.PeachPuff, CornerFont,
                              OutlineBrush, Brushes.Black, 83, DashStyleHelper.Solid, 3, false, "");
                              Print(BiasArrow + Time[0]);
                              }​
              }
              }
              }
              Thanks.​​
              Last edited by davydhnz; 08-14-2023, 08:22 PM. Reason: typos

              Comment


                #8
                Originally posted by davydhnz View Post
                Thank you both for your feedback.

                My indicator is over 2000 lines of code and I'm not ready to release it yet,
                but here is something you can verify that exhibits the same behaviour.

                Thanks.​​
                What behavior are you seeing from the script you posted here? I see you have some print statements that print BiasArrow + Time[0]. What are the results in the NinjaScript Output window? If you add these prints outside of your conditions, do you see when BiasArrow is changing values? Is the change occurring at 8:00am as expected or not? If not, please point out the prints that show the update is not happening as expected.

                I appreciate your time and patience.

                Comment


                  #9
                  NinjaTrader_Emily & bltdavid

                  You're both right. This experiment code runs as you said it should which means my problem is something else.
                  I tried a rewrite on large chucks of my indicator and the problem disappeared, so it was probably one line that I lost sight of causing the problems.
                  ​I had tried for days to find the problem before posting here, but thank you both for trying regardless. It is much appreciated.

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                  0 responses
                  648 views
                  0 likes
                  Last Post Geovanny Suaza  
                  Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                  0 responses
                  369 views
                  1 like
                  Last Post Geovanny Suaza  
                  Started by Mindset, 02-09-2026, 11:44 AM
                  0 responses
                  108 views
                  0 likes
                  Last Post Mindset
                  by Mindset
                   
                  Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                  0 responses
                  572 views
                  1 like
                  Last Post Geovanny Suaza  
                  Started by RFrosty, 01-28-2026, 06:49 PM
                  0 responses
                  573 views
                  1 like
                  Last Post RFrosty
                  by RFrosty
                   
                  Working...
                  X