I have wrote a separate class called DataSniffer. This class is being used to store a bunch of methods that look for anomalies in market data. For example, the current method in the class
findOutlier()
SO - The problem I am having is - I am getting a NullReferenceException when I try to call the
findOutlier()
Bars.GetHigh(0)
findOutlier()
Bars
Error on calling 'OnBarUpdate' method on Bar 150: Object reference not set to an instance of an object.
Bars
Below are the scripts - I have also attached the .cs files.
DataSniffer:
namespace NinjaTrader.NinjaScript.Strategies
{
public class DataSniffer : Strategy
{
public bool isOutlier {get; private set;}
public bool outlierIsUpBar {get; private set;}
/// <summary>
/// Checks to see if the most recent bar is x percent larger in range compared to the past y bars
/// </summary>
/// <param name="outlierPercent">Checks to see if the most recent bar is x percent greater than the dataset average</param>
/// <param name="dataSize">Number of bars to calculate average range for</param>
public void findOutlier(double outlierPercent, int dataSize)
{
// the sum of every bar range
double currentBarRange = Bars.GetHigh(0) - Bars.GetLow(0);
double barRangeTotal = 0;
//the average range of each bar ran through
double barRangeAverage = 0;
//A list that populates with the range of each bar. Bar range is defined by dataSize parameter
List<double> barRange = new List<double>();
//iterate through x bars (besides the most recent bar) and calculate the range. Append range to list.
for(int x = 1; x < dataSize; x++)
{
double range = 0;
range = Bars.GetHigh(x) - Bars.GetLow(x);
barRange.Append(range);
}
//iterate through the barRange list, add up all the values
for(int i = 0; i < barRange.Count; i++)
{
barRangeTotal = barRangeTotal + barRange[i];
}
//divide the sum of the barRange list by its size to find the average bar range.
barRangeAverage = barRangeTotal / barRange.Count;
//compare the average range to the most recent bar range and decide whether or not it is an outlier.
if(barRangeAverage * ((outlierPercent/100) + 1) < currentBarRange)
{
this.isOutlier = true;
Print("The most recent closed bar is an outlier");
}
else
{
this.isOutlier = false;
Print("The most recent closed bar is not an outlier");
}
//Clears the bar range list for the next use.
barRange.Clear();
}
}
}
namespace NinjaTrader.NinjaScript.Strategies
{
public class fxTesting : Strategy
{
DataSniffer mySniffer = new DataSniffer();
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Enter the description for your new custom Strategy here.";
Name = "fxTesting";
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 = 150;
// Disable this property for performance gains in Strategy Analyzer optimizations
// See the Help Guide for additional information
IsInstantiatedOnEachOptimizationIteration = true;
}
else if (State == State.Configure)
{
}
}
protected override void OnAccountItemUpdate(Cbi.Account account, Cbi.AccountItem accountItem, double value)
{
}
protected override void OnConnectionStatusUpdate(ConnectionStatusEventArgs connectionStatusUpdate)
{
}
protected override void OnExecutionUpdate(Cbi.Execution execution, string executionId, double price, int quantity,
Cbi.MarketPosition marketPosition, string orderId, DateTime time)
{
}
protected override void OnFundamentalData(FundamentalDataEventArgs fundamentalDataUpdate)
{
}
protected override void OnMarketData(MarketDataEventArgs marketDataUpdate)
{
}
protected override void OnMarketDepth(MarketDepthEventArgs marketDepthUpdate)
{
}
protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice,
int quantity, int filled, double averageFillPrice,
Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
{
}
protected override void OnPositionUpdate(Cbi.Position position, double averagePrice,
int quantity, Cbi.MarketPosition marketPosition)
{
}
protected override void OnBarUpdate()
{
if(CurrentBars[0] < BarsRequiredToTrade) return;
mySniffer.findOutlier(20, 100);
if(mySniffer.isOutlier && Position.MarketPosition == MarketPosition.Flat)
{
EnterLong("outlier");
SetStopLoss(CalculationMode.Pips, 25);
SetProfitTarget(CalculationMode.Pips, 25);
}
}
}
}

Comment