Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Writing to a text file via Strategy Analyzer only works sometimes

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

    Writing to a text file via Strategy Analyzer only works sometimes

    I've attached a piece of code I'm using. I am trying to export tick data to a txt (1 tick interval) file in batches via the strategy analyzer (in 5-15 day increments). It works sometimes, then at other times, it just blows through the symbol list and does nothing.

    I've even tried an adaption of the StreamWriter (using the GlobalStrategy.cs), and I get the exact same results. Sometimes it works, then other times it doesn't.

    I've tried it on multiple machines, all with the same results.

    What am I doing wrong?


    Code:
    #region Using declarations
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Data;
    using NinjaTrader.Indicator;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Strategy;
    using System.IO;
    #endregion
    
    // This namespace holds all strategies and is required. Do not change it.
    namespace NinjaTrader.Strategy
    {
        [Description("Enter the description of your strategy here")]
        public class TextFileWriter : Strategy
    {
            #region Variables
    		private int		date = 0;
    		private string	path	= Cbi.Core.UserDataDir.ToString()  ;
            #endregion
    
            protected override void Initialize()
            {
                CalculateOnBarClose	= true;
            }
    
    		public virtual string GetSymbol()
    		{
    			return base.Bars.Instrument.FullName;
    		}
    		
            protected override void OnBarUpdate()
            {
    			string myWriteString = ToDay(Time[0]) + " " + Time[0].TimeOfDay + " " + Close[0] + " " + Volume[0] + Environment.NewLine;
    			
    			File.AppendAllText(path + GetSymbol() +  ".txt", myWriteString);
    
            }
    
            #region Properties
    
            #endregion
        }
    }

    #2
    Hi vjsworld,

    I am testing your code out, and comparing to the StreamWriter indicator.

    I will be back with you in a short while.

    I appreciate your patience.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hello vjsworld,

      Thanks for your patience.

      I was getting errors running your script due to it being locked and not released.

      Attached is your script modified. This modified version seems to work pretty well. I haven't gotten an error with it yet.

      Follow these steps to import the NinjaScript:
      1. Download the script to your desktop, keep it in the compressed .zip file.
      2. From the Control Center window select the menu File > Utilities > Import NinjaScript
      3. Select the downloaded .zip file
      4. NinjaTrader will then confirm if the import has been successful.


      Note that on any files that say "File already exists on your PC" that start with an "@" symbol are the ones that came preloaded inside of NinjaTrader so you would say "No" so that you do not override those files.

      Please let me know if I can be of any further assistance.
      Attached Files
      Chelsea B.NinjaTrader Customer Service

      Comment


        #4
        Object reference not set to an instance of an object.

        Chelsea,

        Thank you for you help. When I run your mod I get that error. See snapshot.
        Attached Files

        Comment


          #5
          found it!

          The code checks for if (CurrentBar == 0), and the strategy was starting on bar 20. Changed that setting to 0 and it works now.

          Thanks Chelsea!

          Comment


            #6
            Hi vjsworld,

            You beat me to it.

            I had been running this with BarsRequired 0 in the parameters.

            I should just have checked to see if it is null and then set it so that it can be on any bar.

            Please replace:

            if (CurrentBar == 0)

            with:

            if (sw == null)

            That should make it work for any BarsRequired amount.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              vjsworld,

              Also you will need to change:

              private System.IO.StreamWriter sw;

              To:
              private System.IO.StreamWriter sw = null;
              Chelsea B.NinjaTrader Customer Service

              Comment


                #8
                thnx

                OK,

                Thanks again!

                Comment


                  #9
                  one more question

                  you said, "I was getting errors running your script due to it being locked and not released."

                  How do I check to see if it is locked, and unlock it?

                  Comment


                    #10
                    Hello

                    The error I was receiving is this:
                    6/19/2013 2:29:25 PM|3|128|Error on calling 'OnBarUpdate' method for strategy 'TextFileWriter/1dee42ad508646b2ad55131e32b049a9': The process cannot access the file 'C:\Users\CBell\Documents\NinjaTrader 7\ES 09-13.txt' because it is being used by another process.

                    Using a try and catch on this can tell you if the file is locked.

                    To close it, run the Dispose method on the variable that is the streaming object.
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      got it

                      thnx again

                      Comment


                        #12
                        Blowing through symbols again, no print statements, nor text files

                        Yesterday I was able to get this to work, but today it just blows through the symbol lists again with no outputs... Print statements, nor text files created. I have not adjusted the code, except a while ago to expose the print statements to at least see if those were outputting, which they are not. I have tried it on my two machines with the same results.

                        Here is the exact code again. Does it work on your end?

                        Code:
                        #region Using declarations
                        using System;
                        using System.ComponentModel;
                        using System.Diagnostics;
                        using System.Drawing;
                        using System.Drawing.Drawing2D;
                        using System.Xml.Serialization;
                        using NinjaTrader.Cbi;
                        using NinjaTrader.Data;
                        using NinjaTrader.Indicator;
                        using NinjaTrader.Gui.Chart;
                        using NinjaTrader.Strategy;
                        using System.IO;
                        #endregion
                        
                        // This namespace holds all strategies and is required. Do not change it.
                        namespace NinjaTrader.Strategy
                        {
                            /// <summary>
                            /// 
                            /// </summary>
                            [Description("")]
                            public class TextFileWriterMod : Strategy
                            {
                                #region Variables
                                private int		date	= 0;
                        		private string	path	= Cbi.Core.UserDataDir.ToString();
                        		private System.IO.StreamWriter	sw = null;
                                #endregion
                        
                                /// <summary>
                                /// This method is used to configure the strategy and is called once before any strategy method is called.
                                /// </summary>
                                protected override void Initialize()
                                {
                                    CalculateOnBarClose = true;
                        			ClearOutputWindow();
                                }
                        
                                public virtual string GetSymbol()
                        		{
                        			return base.Bars.Instrument.FullName;
                        		}
                        		
                                protected override void OnBarUpdate()
                                {
                        Print(CurrentBar);
                        			string myWriteString = ToDay(Time[0]) + " " + Time[0].TimeOfDay + " " + Close[0] + " " + Volume[0];// + Environment.NewLine;
                        Print(myWriteString);
                        			try
                        			{
                        				if (sw == null)
                        					sw = File.AppendText(path + GetSymbol() +  ".txt");
                        				
                        				sw.WriteLine(myWriteString);
                        			}
                        			catch(Exception e)
                        			{
                        				Log("cannot write to file", NinjaTrader.Cbi.LogLevel.Error);
                        				throw;
                        			}
                                }
                        		
                        		protected override void OnTermination()
                        		{
                        			if (sw != null)
                        			{
                        				sw.Dispose();
                        				sw = null;
                        			}
                        		}
                        
                                #region Properties
                                #endregion
                            }
                        }

                        Comment


                          #13
                          Hi vjsworld,

                          I am testing this now and will let you know what I find.

                          Thank you for your patience.
                          Chelsea B.NinjaTrader Customer Service

                          Comment


                            #14
                            vjsworld,

                            I am able to run this successfully. May I confirm that you are connected to your data provider as you run this?

                            I have also tested running the backtest over a list of instruments which has also worked correctly.

                            I am unable to find anything wrong with this code.

                            Try restarting NinjaTrader and running the backtest again. Be sure you are connected to a data provider that supports the instrument you are backtesting.

                            Let me know if you are unable to get the script working.
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #15
                              Cache?

                              I am connected to Kinetick. Yes, it's on.

                              Yesterday I noticed that when I do the Nasdaq 100 list, it maxed out my processors and shut off my machine. Then when I rebooted, I had to put my NT license key back in and re-setup Kinetick.

                              When it wouldn't work today, I uninstalled NT. Deleted the NT folder in Documents, then reinstalled NT, imported my strategies and tried again...

                              Still no go- it just blows through the symbol list when I run the strategy analysis.

                              Is there a cache I need to delete? Is NT corrupt somewhere that uninstall doesn't get to?

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                              0 responses
                              651 views
                              0 likes
                              Last Post Geovanny Suaza  
                              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                              0 responses
                              370 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by Mindset, 02-09-2026, 11:44 AM
                              0 responses
                              109 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                              0 responses
                              574 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by RFrosty, 01-28-2026, 06:49 PM
                              0 responses
                              577 views
                              1 like
                              Last Post RFrosty
                              by RFrosty
                               
                              Working...
                              X