Hey, all. I need a little bit of help, here.
I have an Indicator that creates an order when certain conditions are met, then cancels it if it doesn’t trigger within a certain amount of time, and then immediately begins scanning for the next entry. That part works just fine.
It’s also supposed to return to looking for new entries after a previously entered order is triggered, and then that position is ultimately exited. That part does not work. It gives me the “Object reference not set to an instance of an object” error.
Here is the relevant code:
private void OnPositionUpdate(object sender, PositionEventArgs e)
{
if (e.MarketPosition == MarketPosition.Flat)
{
Print("No open positions.");
p = "Flat";
}
else if (p == null)
{ p = e.Position.ToString(); }
}
..........................
[inside OnBarUpdate]
if (o != null)
{
if (myAccount != null && subbed == false)
{
myAccount.PositionUpdate += OnPositionUpdate;
subbed = true;
}
Print("Order " + o.Name.ToString() + " = " + o.OrderState.ToString());
// Check if it was cancelled by the user, by your code, or rejected by the broker
if (o.OrderState == OrderState.Cancelled || o.OrderState == OrderState.Rejected)
{
orderPlaced = false;
// Clean up the reference
o = null;
}
if (p != null)
{
Print("Position = " + p);
if (o.OrderState == OrderState.Filled && p == "Flat")
{
orderPlaced = false;
o = null;
p = null;
}
}
}
I can’t see anything in here that would cause the error. It has to be in these pieces of code, though, because nothing else in the Indicator is affected by the position state. Only o and p are changing.
The goal is to get the Indicator to return to basically State.Configure without having to F5 the whole chart, because NinjaTrader has a tendency to crash whenever I do that mid-session. Looking at my code, however, it seems to me that it should work.
When the position is updated, p, a string variable, is set to whatever the current position is. It starts out as null, and should stay that way until OnPositionUpdate triggers, at which point it is set to the current position, represented in string form.
When the position is ultimately exited, p is then set to “Flat.” When p is “Flat” and OrderState is Filled, p then gets set back to null, which is the default state. So, everything should work fine.
No references to p or o are made while they are null. At least, not that I can see.
One curiosity, which I still don’t see as being anything that would cause this error, is that the problem only seems to happen after the Indicator has caused an entered-and-exited position, and then has had to cancel an order due to a non-trigger situation.
At that point, OrderState is Cancelled, but that is still a non-null value, so it should not cause the “Object reference” error.
Any ideas?
Thanks in advance!
