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

Output to file not working inside OnBarUpdate

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

    Output to file not working inside OnBarUpdate

    Hi,

    Under Initialize() I am creating two files a .csv and a .txt and adding headers using File.WriteAllText. This works fine. However when I try to append lines of information to these files inside OnBarUpdate() I get no data being written. The Output window is populated just fine with the information I am using. Is there a general reason for this?

    Initialize() // This works
    {
    File.WriteAllText(dataFile,string.Empty); // Create/clear contents of dataFile to start
    File.WriteAllText(dataFile,dataFileHeader); // Header for dataFile
    }

    OnBarUpdate() // This does not work
    {
    File.AppendAllText(dataFile,"Test line from inside OnBarUpdate");
    }

    Cheers,
    darmbk.

    #2
    You could be running into an access issue since Initialize() can be called at times when you might not expect. (it can be called when starting the script, opening indicator window, reloading NinjaScript, etc)

    If you haven't done so already you will want to take a look at this script for writing to a file: http://www.ninjatrader.com/support/f...ead.php?t=3475

    It's a good idea to use the try catch statement to ensure you're not getting an access error

    Let me know if I can be of further assistance.
    LanceNinjaTrader Customer Service

    Comment


      #3
      Originally posted by darmbk View Post
      Hi,

      Under Initialize() I am creating two files a .csv and a .txt and adding headers using File.WriteAllText. This works fine. However when I try to append lines of information to these files inside OnBarUpdate() I get no data being written. The Output window is populated just fine with the information I am using. Is there a general reason for this?

      Initialize() // This works
      {
      File.WriteAllText(dataFile,string.Empty); // Create/clear contents of dataFile to start
      File.WriteAllText(dataFile,dataFileHeader); // Header for dataFile
      }

      OnBarUpdate() // This does not work
      {
      File.AppendAllText(dataFile,"Test line from inside OnBarUpdate");
      }

      Cheers,
      darmbk.
      Are there any errors in your log?

      Comment


        #4
        Hi Lance and koganam,

        Thank you both for your input. Firstly, no there was no lines related to this in the Log tab in Control Center. Secondly, I added the Try Catch statement (shown below) but I am not getting any Exception messages in Log?

        // Within OnBarUpdate()
        Print("Test line from inside OnBarUpdate"); // This works
        try
        {
        File.AppendAllText(logFile,"Test line from inside OnBarUpdate"); //Nothing
        File.AppendAllText(dataFile,"Test line from inside OnBarUpdate"); //Nothing
        }
        catch (Exception e)
        {
        Log("Failed to write to log files within OnBarUpdate",NinjaTrader.Cbi.LogLevel.Error);
        throw;
        }

        Thoughts?
        darmbk.

        Comment


          #5
          Update:

          I added the StreamWriter code below and DID get an error message. What might this mean? Thanks.

          Strategy Error on calling 'OnBarUpdate' method for strategy 'XXX'. Object reference not set to an instance of an object.
          Default SW Error


          try
          {
          if(CurrentBar == 0)
          sw = File.AppendText(logFile);
          sw.WriteLine("SW test line");
          }
          catch(Exception f)
          {
          Log("SW Error", NinjaTrader.Cbi.LogLevel.Error);
          throw;
          }

          Comment


            #6
            Originally posted by darmbk View Post
            Update:

            I added the StreamWriter code below and DID get an error message. What might this mean? Thanks.

            Strategy Error on calling 'OnBarUpdate' method for strategy 'XXX'. Object reference not set to an instance of an object.
            Default SW Error


            try
            {
            if(CurrentBar == 0)
            sw = File.AppendText(logFile);
            sw.WriteLine("SW test line");
            }
            catch(Exception f)
            {
            Log("SW Error", NinjaTrader.Cbi.LogLevel.Error);
            throw;
            }
            Where and how did you declare and initialize the StreamWriter object?

            Comment


              #7
              I declared it with my other Variables at the start of my strategy and I initialized it within OnBarUpdate...

              public class XXX : Strategy
              {
              private StreamWriter sw;


              protected override void OnBarUpdate()
              {
              try
              {
              if(CurrentBar == 0)
              sw = File.AppendText(logFile);

              Comment


                #8
                What path are you using for logFile?

                If you still get the error when using
                private string logFile = Cbi.Core.UserDataDir.ToString() + "MyTestFile.txt";

                would you be able to post the source for your script that causes the error?
                LanceNinjaTrader Customer Service

                Comment


                  #9
                  Originally posted by darmbk View Post
                  I declared it with my other Variables at the start of my strategy and I initialized it within OnBarUpdate...

                  public class XXX : Strategy
                  {
                  private StreamWriter sw;


                  protected override void OnBarUpdate()
                  {
                  try
                  {
                  if(CurrentBar == 0)
                  sw = File.AppendText(logFile);
                  What about logFile?

                  If this is just test code, maybe you could post the entire code? At least all parts that involve writing data, while you keep your secret sauce out of view?

                  Comment


                    #10
                    Hi folks,

                    The altered logFile path did not change things I think. I attach the output part of the strategy which has gotten a little messy with my temporary changes in there. Thanks for taking a look.

                    Cheers,
                    darmbk.
                    Attached Files

                    Comment


                      #11
                      Hello,

                      Because this is a strategy and not an indicator your barsrequired setting is preventing the appendtext

                      if (CurrentBar == 0)
                      sw = File.AppendText(logFile);

                      is never being called because OnBarUpdate() never gets called until bar 20 (by default)

                      You will need to change this current bar check or change the BarsRequired



                      Let me know if I can be of further assistance.
                      LanceNinjaTrader Customer Service

                      Comment


                        #12
                        Hi Lance,

                        Not there yet I'm afraid! When I change to 'CurrentBar == 20' outputting to the file works so thanks for that. However I get the error quoted below even though the file is not open. When I do open and then try to save changes I am told I can't create this file even though it already exists!


                        **NT** Failed to call method 'Initialize' for strategy...
                        The process cannot access the file 'C:\Documents and Settings\...\MyTestFile.txt' because it is being used by another process.

                        Comment


                          #13
                          Please first Restart NinjaTrader and ensure you don't have multiple instances of the strategy (or other indicator) referencing this file.

                          Additionally you may want to change the text file name such that it creates a new named file and you can be sure that new file will not be in use.



                          Let me know if I can be of further assistance.
                          LanceNinjaTrader Customer Service

                          Comment


                            #14
                            Hi Lance,

                            After closing NT7 and deleting the files I get the same error. The only change I have made to the previously attached code is to replace 0 with 20 for CurrentBar. Are you able to replicate this error with that code?

                            Thanks,
                            darmbk.

                            Comment


                              #15
                              This is occurring because the writer is not being disposed of when the script is terminated.

                              Please ensure previously created files are removed and the following is used in your script

                              Code:
                              		// Necessary to call in order to clean up resources used by the StreamWriter object
                              		protected override void OnTermination() 
                              		{
                              			// Disposes resources used by the StreamWriter
                              			if (sw != null)
                              			{
                              				sw.Dispose();
                              				sw = null;
                              			}
                              		}
                              LanceNinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by funk10101, Today, 09:43 PM
                              0 responses
                              6 views
                              0 likes
                              Last Post funk10101  
                              Started by pkefal, 04-11-2024, 07:39 AM
                              11 responses
                              37 views
                              0 likes
                              Last Post jeronymite  
                              Started by bill2023, Yesterday, 08:51 AM
                              8 responses
                              44 views
                              0 likes
                              Last Post bill2023  
                              Started by yertle, Today, 08:38 AM
                              6 responses
                              26 views
                              0 likes
                              Last Post ryjoga
                              by ryjoga
                               
                              Started by algospoke, Yesterday, 06:40 PM
                              2 responses
                              24 views
                              0 likes
                              Last Post algospoke  
                              Working...
                              X