Avoid race conditions when using event listeners

As NinjaTrader is a multi-threaded software, I wonder:

  1. Could the same event listener been executed on different threads? For example, at the time the thread1 is executing `OnBarUpdate()`, is it possible for thread2 also trying to execute `OnBarUpdate()`? (It could be horrible if “yes”, but I still want to confirm)
  2. If the answer is “no” for the above question, which event listeners are on the same threads? This is important since this tells me if sharing a object between two event listeners are safe. For example, are “OnBarUpdate()” and “OnOrderUpdate()” on the same thread? If yes, then we can safely get the order object from “OnOrderUpdate()” and assign it to a global variable, and “OnBarUpdate()” can make trading decisions (such as avoid double orders) based on the state of this order object.

1 Like

I wouldn’t build anything on “these two are on the same thread”. NinjaTrader’s own Best Practices page says to always assume any of the methods you implement could be called from another thread, and that market data events run on the instrument thread pool shared by all instruments. The Multi-Threading page’s OnOrderUpdate example is the clearest case: the broker events arrive on one thread and your OnOrderUpdate runs on another.

So for the avoid-double-orders case, treat the order reference you keep from OnOrderUpdate as shared state: read and write it under one small lock, or keep it in a field you only replace whole. That same page also points out that the order object always shows the current state, while the OnOrderUpdate parameters give you the sequence of changes, so check order.OrderState when you need “is it still working right now”.

On your first question, whether one handler like OnBarUpdate can run twice at once for the same instance: I couldn’t find the docs stating either way, which is another reason to code as if it could.