I am working on a script to track opening range values. The script is a backtest that will run from some start date to some end date. At the end of the backtest (on the final day), I want to print some results to the output window. However, the results I am trying to print are all zero, any idea what's going on? I'm getting an error that I am attempting to divide by zero in OnStateChange. I'm updating these values as each bar is processed, so at the end of the script, they shouldn't be zero but all of them are. Any thoughts?
Here's the script:
namespace NinjaTrader.NinjaScript.Strategies.JBAlgos
{
public class OpeningRange : Strategy
{
private double ORLow, ORHigh;
private bool hasConfirmedLong, hasConfirmedShort;
private int occurrenceCount, confirmationCount, shortConfirmationCount, longConfirmationCount, violationCount;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Enter the description for your new custom Strategy here.";
Name = "OpeningRange";
Calculate = Calculate.OnBarClose;
EntriesPerDirection = 1;
EntryHandling = EntryHandling.AllEntries;
IsExitOnSessionCloseStrategy = true;
ExitOnSessionCloseSeconds = 30;
IsFillLimitOnTouch = false;
MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
OrderFillResolution = OrderFillResolution.Standard;
Slippage = 0;
StartBehavior = StartBehavior.WaitUntilFlat;
TimeInForce = TimeInForce.Gtc;
TraceOrders = false;
RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
StopTargetHandling = StopTargetHandling.PerEntryExecution;
BarsRequiredToTrade = 1;
// Disable this property for performance gains in Strategy Analyzer optimizations
// See the Help Guide for additional information
IsInstantiatedOnEachOptimizationIteration = true;
}
else if (State == State.Terminated)
{
if(confirmationCount > 0 && shortConfirmationCount > 0 && longConfirmationCount > 0 && violationCount > 0){
Print(string.Format("Found {0} confirmations total, {1} were short and {2} were long. Success {3}%, violation {4}%", confirmationCount, shortConfirmationCount,
longConfirmationCount, (confirmationCount / occurrenceCount ) * 100, (violationCount / occurrenceCount) * 100));
}
}
}
protected override void OnBarUpdate()
{
if(Bars.IsFirstBarOfSession){
ORLow = Low[0];
ORHigh = High[0];
}
if(ToTime(Time[0]) > 93000 && ToTime(Time[0]) < 103500){
if(Low[0] < ORLow){
ORLow = Low[0];
}
if(High[0] > ORHigh){
ORHigh = High[0];
}
}
if(ToTime(Time[0]) == 103500){
Print(string.Format("ORHigh is {0}, ORLow is {1}, Date: {2}", ORHigh, ORLow, Time[0]));
occurrenceCount++;
}
if(!hasConfirmedShort && Close[0] > ORHigh){
hasConfirmedLong = true;
longConfirmationCount++;
confirmationCount++;
}
if(!hasConfirmedLong && Close[0] < ORLow){
hasConfirmedShort = true;
longConfirmationCount++;
confirmationCount++;
}
if(hasConfirmedLong && Low[0] < ORLow)
violationCount++;
if(hasConfirmedShort && High[0] > ORHigh)
violationCount++;
if(Bars.IsLastBarOfSession)
return;
}
}
}

Comment