Handling MetaTrader 4 Trade Context Conflicts and Error 146
Summary
The article explains why MetaTrader 4 can return Error 146 when multiple experts attempt trade operations through the terminal’s shared trade context. It recommends checking whether trading is allowed immediately before sending an order, since an earlier check may become stale while the expert calculates entry conditions, stops, and position size.
For a busy context, it presents bounded polling that checks for user termination, waits briefly, and stops after a configured limit. If access becomes available, the expert should refresh quotes and recalculate price-dependent levels before placing the order. The article also describes coordinating experts through a terminal global variable used as a lock, with separate acquire and release functions. These approaches reduce conflicts but do not guarantee error-free concurrency: checks can race, waiting can delay execution as prices move, and a lock may remain set if an expert or terminal exits unexpectedly. The examples are legacy MQL4 guidance and require careful integration and cleanup.
Key ideas
- Check trade availability immediately before sending an order because another expert may occupy the shared context during calculations.
- Bound any wait for access and stop polling if the expert is removed or the time limit expires.
- Refresh market quotes and recalculate price-dependent order levels after waiting.
- A shared terminal variable can coordinate expert access, but a stale lock can prevent further trading.
- The described safeguards reduce the chance of Error 146 but cannot eliminate race conditions.
Tags
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.