19/04/2010 22:01:13 Default File write error for file name 'C:\Automation Data\2010419 2153 SGMACrossover View360Report.csv' Error 'The process cannot access the file 'C:\Automation Data\2010419 2153 SGMACrossover View360Report.csv' because it is being used by another process.'
I've used sections of code found on the forums to handle the writing to file and I've tried to experiment with the Dispose() method, as mentioned on the forums, to clean up resources but nothing seems to help, the file is always in use 'by another process'.
The results I'd like to achieve are;
1. During an optimisation basket test, when the last bar of an instrument is reached then a single line summary of performance for that instrument & parameter set is written to file. (Optimisation Performance Summary)
2. During an optimisation basket test the details of every trade are written to a different file, with data formatted for use in Brute View360 walk forward software.
3. Implement a buffer to improve write efficiency (Not sure how to do this though!)
Can you see what I'm doing wrong in the code / help to get it working?
Many thanks
Riskybiz
#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.Strategy; using System.IO; #endregion // This namespace holds all strategies and is required. Do not change it. namespace NinjaTrader.Strategy { /// <summary> /// Simple moving average cross over strategy. /// </summary> [Description("Simple moving average cross over strategy, with View360 Export code.")] public class SGMACrossOver : Strategy { #region Variables private int fast = 10; private int slow = 25; private bool view360Export = false; private string optimisationFile; private bool performanceReport; private string performanceReportFile;// = "PerformanceFile.csv"; private string dateString; private string perfHeadString; private string perfString; private double np; private DateTime timeStamp = DateTime.Now; #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() { SMA(Fast).Plots[0].Pen.Color = Color.Orange; SMA(Slow).Plots[0].Pen.Color = Color.Green; Add(SMA(Fast)); Add(SMA(Slow)); CalculateOnBarClose = true; } //last bar on chart [Browsable(false)] public bool LastBarOnChart { get { if (!CalculateOnBarClose && CurrentBar == Bars.Count - 1) return true; else if (CalculateOnBarClose && CurrentBar == Bars.Count - 2) return true; return false; } } //write to file private void WriteFile(string fileName, string line) { // Creates the file path string file = /*NinjaTrader.Cbi.Core.UserDataDir + @"log" +*/ fileName; // Writes out a line to the specified file name try { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(file)) { writer.WriteLine(line); //writer.Flush(); //writer.Close(); //writer.Dispose(); } } catch (System.Exception exp) { Log("File write error for file name '" + fileName + "' Error '" + exp.Message + "'", LogLevel.Warning); } } //on bar update protected override void OnBarUpdate() { // strategy { if (CrossAbove(SMA(Fast), SMA(Slow), 1)) EnterLong(); else if (CrossBelow(SMA(Fast), SMA(Slow), 1)) EnterShort(); } try { //view360 export if (Performance.AllTrades.Count > 0 && CurrentBar == Bars.Count-2 && view360Export == true) { if(optimisationFile == null)//create filename if it doesn't exist already { dateString = timeStamp.Year.ToString() + timeStamp.Month.ToString() + timeStamp.Day.ToString() + " " + timeStamp.Hour.ToString() + timeStamp.Minute.ToString();//date & time stamp the file to make it unique optimisationFile = @"C:\Automation Data\" + dateString + "hrs SGMACrossover View360 Data.csv"; } for (int i = 0; i < Performance.AllTrades.Count; i++) { Trade lastTrade = Performance.AllTrades[i]; double lastProfit = lastTrade.ProfitCurrency * lastTrade.Quantity; lastProfit = Math.Round(lastProfit,2); int MP = 0; if (lastTrade.Entry.MarketPosition == MarketPosition.Short) { MP = -1; } else if (lastTrade.Entry.MarketPosition == MarketPosition.Long) { MP = 1; } string input1 = fast.ToString(); string input2 = slow.ToString(); string input3 = " "; string input4 = " "; string input5 = " "; string input6 = " "; string input7 = " "; string input8 = " "; string input9 = " "; string input10 = " "; WriteFile(optimisationFile, lastTrade.Entry.Instrument.ToString() + "," + input1 + "," + input2 + "," + input3 + "," + input4 + "," + input5 + "," + input6 + "," + input7 + "," + input8 + "," + input9 + "," + input10 + "," + lastTrade.Quantity.ToString() + "," + MP.ToString() + "," + lastTrade.Entry.Time.ToShortDateString() + "," + lastTrade.Entry.Price.ToString() + "," + lastTrade.Exit.Time.ToShortDateString() + "," + lastTrade.Exit.Price.ToString() + "," + lastProfit.ToString()); } } }//view360report catch (Exception e) { Log("Error: View 360 Export Code Error" , NinjaTrader.Cbi.LogLevel.Error); throw(e); } //performance report try { if(LastBarOnChart == true && performanceReport == true) { if(performanceReportFile == null)//create filename if it doesn't exist already { dateString = timeStamp.Year.ToString() + timeStamp.Month.ToString() + timeStamp.Day.ToString() + " " + timeStamp.Hour.ToString() + timeStamp.Minute.ToString();//date & time stamp the file to make it unique performanceReportFile = @"C:\Automation Data\" + dateString + "hrs SGMACrossover Optimisation Performance Summary.csv"; perfHeadString = "Instrument Name, Fast MA, Slow MA, NetProfit"; WriteFile(performanceReportFile, perfHeadString); } np = (Performance.AllTrades.TradesPerformance.GrossProfit - Performance.AllTrades.TradesPerformance.GrossLoss); perfString = Instrument.FullName + "," + fast.ToString() + "," + slow.ToString() + "," + np.ToString(); WriteFile(performanceReportFile, perfString); }//performance report }//try catch (Exception e) { Log("Error: Optimisation Performance Report Error" , NinjaTrader.Cbi.LogLevel.Error); throw(e); }//catch }//on bar update #region Properties /// <summary> /// </summary> [Description("Period for fast MA")] [Category("Parameters")] public int Fast { get { return fast; } set { fast = Math.Max(1, value); } } /// <summary> /// </summary> [Description("Period for slow MA")] [Category("Parameters")] public int Slow { get { return slow; } set { slow = Math.Max(1, value); } } //View360 addition [Description("Enable View360 Data Export; Use During Optimisations")] [Category("Parameters")] public bool Export_View360_Report { get { return view360Export; } set { view360Export = value; } } //Performance Summary [Description("Enable Performance Summary Report; Use During Optimisations")] [Category("Parameters")] public bool Export_Performance_Summary { get { return performanceReport; } set { performanceReport = value; } } //File Date & Time Stamp [ReadOnlyAttribute(true)] [Description("Date & Time Stamp For Output Files")] [Category("Parameters")] public DateTime Time_Stamp { get { return timeStamp; } set { timeStamp = value; } } #endregion } }
Comment