The function is called in EAs when the Trade event occurs. The function is meant for processing changes in order, position and trade lists.
No return value
OnTrade() is called only for Expert Advisors. It is not used in indicators and scripts even if you add there a function with the same name and type.
For any trade action (placing a pending order, opening/closing a position, placing stops, activating pending orders, etc.), the history of orders and trades and/or the list of positions and current orders is changed appropriately.
When handling an order, a trade server sends the terminal a message about the incoming Trade event. To retrieve relevant data on orders and trades from history, it is necessary to perform a trading history request using HistorySelect() first.
The trade events are generated by the server in case of:
Each Trade event may appear as a result of one or several trade requests. Trade requests are sent to the server using OrderSend() or OrderSendAsync(). Each request can lead to several trade events. You cannot rely on the statement "One request - one Trade event", since the processing of events may be performed in several stages, and each operation may change the state of orders, positions and the trade history.
OnTrade() handler is called after the appropriate OnTradeTransaction() calls. In general, there is no exact correlation in the number of OnTrade () and OnTradeTransaction () calls. One OnTrade() call corresponds to one or several OnTradeTransaction calls.
Sample EA with OnTrade() handler