Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

StreamWriter with Live Strategy

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

    StreamWriter with Live Strategy

    I have my strategy set to send text to a file using streamwriter. It creates a new file for each day and the backtest performed as intended. However, when I am running the strategy live, no text is sent to the file. Is there a solution or am I missing something?

    #2
    You may want to check for errors in opening/closing the file? http://www.ninjatrader-support.com/v...ead.php?t=3475
    Josh P.NinjaTrader Customer Service

    Comment


      #3
      I tried to follow the example and here's my output from a few ticks and code. There is no output to the file. Where do I go from here?

      Output Window
      Check1
      Check2
      E
      Check2
      E
      Check2
      E
      Check2


      public class SW : Strategy
      {
      #region Variables

      private System.IO.StreamWriter sw;
      private string path = Cbi.Core.UserDataDir.ToString() + "Test15.txt";

      #endregion
      protected override void Initialize()
      {

      TraceOrders = false;
      ExitOnClose = false;
      BarsRequired = 1;
      EntryHandling = EntryHandling.UniqueEntries;
      TimeInForce = Cbi.TimeInForce.Gtc;
      Add(PeriodType.Minute, 240);
      Add(PeriodType.Tick, 1);
      CalculateOnBarClose = true;
      }
      protected override void OnBarUpdate()
      {

      if (Historical)
      {
      return;
      }
      try
      {
      sw = File.AppendText(path);
      sw.WriteLine("Opening...");
      Print("Check1");
      }
      catch (Exception e)
      {
      Print("E");
      }
      Print("Check2");
      }

      Comment


        #4
        From your output it is evident you are running into errors. Instead of Print("E") please just print out the exception so you know the error you are running into:
        Print(e.ToString());
        Josh P.NinjaTrader Customer Service

        Comment


          #5
          e.ToString() makes more sense. Thanks for the tip. Here's my output. The code prints out Check1 and Check2 the first time. Why is nothing written to the file since there is no error on the first run?

          Check1
          Check2
          System.IO.IOException: The process cannot access the file 'C:\Documents and Settings\yuhasm\My Documents\NinjaTrader 6.5\Test15.txt' because it is being used by another process.
          at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
          at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
          at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
          at System.IO.StreamWriter.CreateFile(String path, Boolean append)
          at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
          at System.IO.StreamWriter..ctor(String path, Boolean append)
          at System.IO.File.AppendText(String path)
          at NinjaTrader.Strategy.SW.OnBarUpdate()
          Check2

          Comment


            #6
            The error suggests that the file has has a lock on it since some other application/process is using it. Maybe another strategy that writes to the same file? Maybe you have the file open in MS Notepad? Just some ideas. In any case, we are outside the bounds fo what we can support since this is C# programming and not NinjaScript.
            RayNinjaTrader Customer Service

            Comment


              #7
              I understand. Would you be able to answer why the streamwriter works during a backtest, but not for a live strategy? The code below produces that while running a live strategy. There are no errors and Live is printed to the output window. If not, I understand and appreciate your help.

              #region Variables

              private System.IO.StreamWriter sw;
              private string path = Cbi.Core.UserDataDir.ToString() + "Test.txt";
              bool file = false;

              #endregion
              protected override void Initialize()
              {

              TraceOrders = false;
              ExitOnClose = false;
              BarsRequired = 1;
              EntryHandling = EntryHandling.UniqueEntries;
              TimeInForce = Cbi.TimeInForce.Gtc;
              Add(PeriodType.Minute, 240);
              Add(PeriodType.Tick, 1);
              CalculateOnBarClose = true;
              }
              protected override void OnBarUpdate()
              {

              if (file == false)
              {
              sw = File.AppendText(path);
              file = true;
              }

              try
              {
              if (Historical)
              {
              sw.WriteLine("Opening...");
              Print("Check1");
              }
              else
              {
              sw.WriteLine("Live");
              Print("Live");
              }

              }
              catch (Exception e)
              {
              Print(e.ToString());
              }
              Print("Check2");
              }

              Comment


                #8
                Unfortunately not.
                RayNinjaTrader Customer Service

                Comment


                  #9
                  tony,

                  where do you close the file?

                  if you don't close it, it will only work once upon the first time of opening it. After it will be in use by the indicator (in theory) and will not be accessible until you remove the strategy and probably close the chart.

                  maybe you can close it in the dispose method?

                  just a quick thought.
                  mrlogik
                  NinjaTrader Ecosystem Vendor - Purelogik Trading

                  Comment


                    #10
                    Thanks for the suggestion. I was trying to avoid to opening the file for every tick, but it seems to be working now that I open and close the file on each tick.

                    Comment


                      #11
                      Opening / Closing the file for each tick is CPU intensive. If you have processing problems with this you may want to continue to look for a way to open / close only once.
                      mrlogik
                      NinjaTrader Ecosystem Vendor - Purelogik Trading

                      Comment


                        #12
                        Right. I'm using multiple time frames and I only need output every 15 minutes, so I'll try opening and closing the file in the specific BarsInProgress section for the 15 min dataseries. Thanks for your help.

                        Comment


                          #13
                          Hawk,

                          I have found the following works for me.

                          Code:
                          //Variables
                          private bool logFileInit = false;
                          private FileStream file;
                          private StreamWriter sw;
                          
                          //OnBarUpdate method
                          //*******************************
                          //          CREATE LOG FILE
                          //*******************************
                          if(!logFileInit)
                          {
                                  logFileInit = true;
                          
                                  try
                                  {
                                      if(file == null)
                                          file = new FileStream("C:\\test.txt", FileMode.OpenOrCreate, FileAccess.Write);
                                      if(sw == null)
                                          sw = new StreamWriter(file);
                                   }
                                   catch(Exception ex)
                                   {
                                       Print(ex.ToString());
                                   }                
                          }
                          
                          //To use it
                          sw.Write("your text");
                          
                          
                          //********************************
                          //   DISPOSE METHOD -- CLEAN UP OBJECTS
                          //   To Properly dispose of it when finished to 
                          //   prevent file locking, etc
                          //********************************
                          public override void Dispose()
                          {
                               //******************
                               //  Clean up resources 
                               //******************            
                                      
                               try
                               {
                                  if(sw != null)
                                  {
                                       // Close the stream writer
                                      sw.Close();
                                  }
                                          
                                  if(file != null)
                                  {
                                      // Close the file writer
                                      file.Close();
                                  }
                                }
                                catch (Exception e)
                                {
                                   Print(e.ToString());
                                }
                          
                                //Removes all draw objects
                                RemoveDrawObjects();
                          
                                //call base
                                base.Dispose();
                          }
                          This code will only open / close a file once per strategy application.
                          - Make sure you use different file names per strategy

                          good luck
                          mrlogik
                          NinjaTrader Ecosystem Vendor - Purelogik Trading

                          Comment


                            #14
                            mrlogik,

                            Thank you very much. I will take a look.

                            Comment


                              #15
                              Originally posted by mrlogik View Post
                              Hawk,

                              I have found the following works for me.
                              Excellent. This worked for me. Thank you very much for sharing your code.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                              0 responses
                              633 views
                              0 likes
                              Last Post Geovanny Suaza  
                              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                              0 responses
                              364 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by Mindset, 02-09-2026, 11:44 AM
                              0 responses
                              105 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                              0 responses
                              567 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by RFrosty, 01-28-2026, 06:49 PM
                              0 responses
                              568 views
                              1 like
                              Last Post RFrosty
                              by RFrosty
                               
                              Working...
                              X