Foreach loop being ignored

Can anyone help me figure out why this foreach loop isn’t iterating?

	private void OnAccountItemUpdate(object sender, AccountItemEventArgs aie)
	{
		if (aie.AccountItem != AccountItem.UnrealizedProfitLoss)
		{ return; }

		Print(aie.Account.ToString());
		
		if (aie.Account.Orders != null)
		{
			Print("Orders found.");
				
			foreach (Order theOrder in aie.Account.Orders)
			{
				Print("Account: " + aie.Account.Name.ToString() + " - Order Name = " + theOrder.Name.ToString() + ", ExitLine[1] = " + ExitLine[1].ToString());
		
				if (theOrder.Name.Contains("Exit")
					&& theOrder.OrderState == OrderState.Working
					|| theOrder.OrderState == OrderState.Accepted)
				{
					if (ExitLine[1] > theOrder.StopPrice)
					{
						theOrder.StopPriceChanged	= ExitLine[1];
												
						aie.Account.Change(new[] { theOrder } );
									
						Print("Order changed; qty = " + qty.ToString() + ", Stop Price = " + ExitLine[1].ToString());
					}
				}
			}
		}
		
	}

The foreach that isn’t executing is the Order one. I see the Prints for the Account and the “Orders found,” but the Print inside the Order loop never shows up.

Sim102
Orders found.
Sim101
Orders found.
Sim102
Orders found.
Sim101
Orders found.
Sim101
Orders found.
Sim102
Orders found.
Sim101
Sim102
Orders found.
Orders found.
Sim101
Orders found.

All of this is happening while I am in an active Position with stop and target orders in place, which were themselves placed by this same Indicator in OnExecutionUpdate.

This code was copied/pasted from another Indicator which works just fine.

Any ideas?

Thanks in advance!

“Orders found.” doesn’t tell you there are orders. Account.Orders is a collection object that exists even when it’s empty, so the null check passes either way. With nothing printing inside the loop, there are two possibilities: the collection is empty for that account, or the first line inside the loop throws and the handler exits before the Print runs.

My bet is the second, and the suspect is ExitLine[1]. The barsAgo indexer is only guaranteed in sync during core data events such as OnBarUpdate and a strategy’s own order events (OnOrderUpdate, OnExecutionUpdate, OnPositionUpdate). An account event handler like your AccountItemUpdate is not one of them, and the help guide’s Series page says reading barsAgo outside those events “may result in errors”. Your Output shows the handler being called again and again, so whatever fails inside it doesn’t stop the indicator, which is why an exception there is easy to miss. If ExitLine is a plain array or variable in the indicator you copied from, rather than a plot or Series, that would be the difference.

To know for sure, run this once in place of the loop:

int seen = 0;
try
{
	foreach (Order theOrder in aie.Account.Orders)
	{
		seen++;
		Print(aie.Account.Name + ": " + theOrder.Name + " " + theOrder.OrderType + " " + theOrder.OrderState + " stop " + theOrder.StopPrice);
		Print("ExitLine[1] = " + ExitLine[1]);
	}
}
catch (Exception ex)
{
	Print(aie.Account.Name + ": " + ex);
}
Print(aie.Account.Name + ": " + seen + " orders");

What the Output tells you:

  • An order line, then an exception. ExitLine[1] is the cause. Stop reading the series from the account event: copy the value into a field at the end of OnBarUpdate and use the field in the handler (code below). ExitLine.GetValueAt(CurrentBar - 1) also works; the docs recommend absolute-index reads outside the data events.
  • “0 orders”. The collection really is empty for that account, so the stop and target sit on another one. The Orders tab of the Control Center shows which.
  • Order lines and ExitLine values, no exception. Then your original line failed on a .ToString() of something null, most likely an order with no name. String concatenation handles null, so drop the .ToString() calls.

The field version:

private double exitLevel;   // written in OnBarUpdate, read by the account handler

// last lines of OnBarUpdate
if (CurrentBar > 0)
	exitLevel = ExitLine[1];

Then use exitLevel wherever the handler reads ExitLine[1].

One more you will hit as soon as the loop runs: && binds tighter than ||, so your condition reads as (Name.Contains("Exit") && Working) || Accepted, and any order in the Accepted state passes, whatever its name. Put the two states in parentheses:

if (theOrder.Name.Contains("Exit")
	&& (theOrder.OrderState == OrderState.Working || theOrder.OrderState == OrderState.Accepted))

That also keeps out an order whose change is still in flight (ChangePending, then ChangeSubmitted), so the next update doesn’t send the same change again before the first one lands. Your Output shows how often this handler fires while you’re in a position.

I didn’t spot the problem with the missing parentheses in the conditional. Thanks for pointing that out!

I eventually realized that I was really only expecting the order to move on the close of a bar when ExitLine[0] has a valid value, so I went ahead and moved all of that code into OnBarUpdate, and used ExitLine[0] instead of ExitLine[1]. And, of course, I updated the conditional with the parentheses. Now, it works perfectly.

Thank you!

1 Like