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:
#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;
}
}

Comment