Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

StreamWriter from a Strategy

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

    StreamWriter from a Strategy

    Hi all,

    I want to write the PnL of my strategy into a file (.txt) and wanted to do so through the StreamWriter.
    As adviced in another post, I plainly copied and pasted the SampleStreamWrite into the strategy: it doesn't work!
    I get in the log: Error in OnBarUpdata: reference to an object not set as an object.
    I took the simplest strategy possible and tried to copy and paste, yet it doesn't work!
    I'm attaching the strategy below:

    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;
    #endregion
    using System.IO;
    
    // This namespace holds all strategies and is required. Do not change it.
    namespace NinjaTrader.Strategy
    {
        /// <summary>
        /// Enter the description of your strategy here
        /// </summary>
        [Description("Enter the description of your strategy here")]
        public class StreamWriterInStrategy : Strategy
        {
            #region Variables
            // Wizard generated variables
            // User defined variables (add any user defined variables below)
    		private string path = Cbi.Core.UserDataDir.ToString();
    		private System.IO.StreamWriter sw;
            #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;
            }
    
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
    		    // Condition set 1
                if (Close[0] > Close[1])
                {
                    EnterLong(DefaultQuantity, "");
                }
    
                // Condition set 2
                if (Close[0] < Close[1])
                {
                    ExitLong("", "");
                }
    			
    			try
    			{
    				// If file at 'path' doesn't exist it will create the file. If it does exist it will append the file.
    				if (CurrentBar == 0)
    					sw = File.AppendText(path + Instrument.MasterInstrument.Name + "_PNL" + ".txt");
    				
    				// This is the output of all lines.	The output format is as follows: Date Open High Low Close
    				//sw.WriteLine(ToDay(Time[0]) + " " + Open[0] + " " + High[0] + " " + Low[0] + " " + Close[0]);
    				sw.WriteLine(ToDay(Time[0]) + " " + Performance.AllTrades.TradesPerformance.Currency.CumProfit);
    			}
    			
    			catch (Exception e)
    			{
    				// Outputs the error to the log
    				Log("You cannot write and read from the same file at the same time. Please remove SampleStreamReader.", NinjaTrader.Cbi.LogLevel.Error);
    				throw;
    			}
            }
    Thank you

    #2
    First. Try just using the sample and see if that works for you. Next step if that works would be to use try-catch on every single one of your lines in OnBarUpdate() to find which one is giving you problems. Then you will know which line to address.
    Josh P.NinjaTrader Customer Service

    Comment


      #3
      The sample work for me fine.
      How am I supposes to use try and catch on any single line?
      I have two lines practically:
      Code:
      try
      			{
      				// If file at 'path' doesn't exist it will create the file. If it does exist it will append the file.
      				if (CurrentBar == 0)
      					sw = File.AppendText(path + Instrument.MasterInstrument.Name + "_PNL" + ".txt");
      				
      				// This is the output of all lines.	The output format is as follows: Date Open High Low Close
      				//sw.WriteLine(ToDay(Time[0]) + " " + Open[0] + " " + High[0] + " " + Low[0] + " " + Close[0]);
      				sw.WriteLine(ToDay(Time[0]) + " " + Performance.AllTrades.TradesPerformance.Currency.CumProfit);
      			}
      			
      			catch (Exception e)
      			{
      				// Outputs the error to the log
      				Log("You cannot write and read from the same file at the same time. Please remove SampleStreamReader.", NinjaTrader.Cbi.LogLevel.Error);
      				throw;
      			}
      Both lines
      sw = File.AppendText(path + Instrument.MasterInstrument.Name + "_PNL" + ".txt");
      and
      sw.WriteLine(ToDay(Time[0]) + " " + Performance.AllTrades.TradesPerformance.Currency.C umProfit);

      work fine running StreamWriter outside the strategy (just as in indicator).

      Comment


        #4
        If you want to find the source of the issues you need to isolate the problem. To do so you need to find which line does not work and that means try-catching everything till you find it.

        Code:
        try
        {
             one line
        }
        catch (Exception e)
        {
            Print("line 1: " + e);
        }
        
        try
        {
            another line
        }
        catch (Exception e)
        {
            Print("line 2: " + e);
        }
        Josh P.NinjaTrader Customer Service

        Comment


          #5
          OK, the problem is in the first line (the path): the process cannot access the file because it's already in use by another process.
          How can I fix it ?

          Comment


            #6
            You cannot have the file open. Make sure the file is closed. Also, make sure you are releasing the resources to make it available. This means you need to dispose the object or else once the indicator opens it it will remain open until you restart NT.
            Josh P.NinjaTrader Customer Service

            Comment


              #7
              OK, I'm doing that, but I have two problems:

              1) when I try to close my streamwriter sw, I do sw.Close(), but NT offers me the extensions of Close like Close of a price, not the function close!
              2) another problem with sw: when I try to access the function sw.Write, the compiler doesn't recognize it.

              I stated in Variables
              private StreamWriter sw;
              and in OnBarUpdate
              sw = new StreamWriter();

              Comment


                #8
                You need to be using sw.Dispose(). Please see the reference sample's Dispose() method.

                Use WriteLine.
                Josh P.NinjaTrader Customer Service

                Comment


                  #9
                  Log File

                  Hi, I have a very basic understanding of C# and would like to know;

                  1) is it possible to insert some code in a indicator like the stochastic that when a condition occours (eg: K crossers over D), the indicator then records the Date, time & price of the event to a CSV file. And it should record all occurances for the currently loaded chart date range so i can perform some analysis on it in Excel?

                  2) if such code is possible could someone provide a sample that i can work with. I can understand the basics of code but i dont have enough knowledge to compose it from scratch?


                  Thank you for any help in advance
                  Last edited by bologc; 08-28-2009, 12:24 AM.

                  Comment


                    #10
                    All,

                    I responded to stefy's post about using StreamWriter yesterday with a class / code walk through on how to use it. Its for a strategy, but it can be adapted to an indicator with little effort.

                    Here is the link
                    mrlogik
                    NinjaTrader Ecosystem Vendor - Purelogik Trading

                    Comment


                      #11
                      thanks alot

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                      0 responses
                      649 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
                      576 views
                      1 like
                      Last Post RFrosty
                      by RFrosty
                       
                      Working...
                      X