Prevent exceeding max. cash for multiple orders when multithreading

Hello! I use multithreaded Exploration to place orders with ibc.PlaceOrder() when signals are generated. The Exploration is on Auto-Repeat and I only place LONG orders. There is a limited amount of cash available such as 100,000 USD for example for all positions.

Every time before an order is placed, Amibroker checks that there is enough available cash to place an order if a signal is generated - if not enough cash, no order is placed.

However, sometimes several signals are generated for different tickers at the same time in Exploration, which results in several orders being placed together exceeding the total available cash. Is there a way or process to make sure this does not happen?

Use critical section as described in

Iā€™m not sure how it will help in this particular situation.

One thing is that critical section ensures that only ONE thread is doing protected section at a time.

Second thing to watch, is that TWS reports account state with great delay. There is 1 or 2 seconds delay for TWS to adjust the Cash amount. This is how TWS API works. Essentially Cash is the figure that gets displayed by TWS in "Portfolio" window and it is updated not more than once per 1-2 seconds at most.

Therefore you should not rely on that figure in your formulas. Instead you should use static variables to calculate remaining cash yourself.

There is lot of information on User KB like this

1 Like