Skip to content
All library documents

Detecting Position and Order Changes with MQL5 OnTrade Events

Article MQL5 articles

Summary

This article explains how an MQL5 Expert Advisor can use OnTrade events to detect changes to positions and pending orders and generate reports or notifications. Its implementation tracks prior and current counts of active orders and positions, then examines order and deal history to distinguish events such as opening, adding to, reversing, partially closing, or fully closing a position. It also compares previous and current stop-loss and take-profit values to identify modifications.

The examples show why a single trade operation can trigger several OnTrade calls as orders, deals, and positions change through their lifecycle. The author also notes that history updates may not align with the event callback, so a handler cannot assume all relevant records are immediately available. The method is presented as a framework for event processing, with substantial example code, rather than a complete or guaranteed event classifier; careful state tracking and testing against account behavior are needed.

Key ideas

  • OnTrade is called when trade activity changes the active order or position lists.
  • A single market order may produce multiple callbacks as its lifecycle progresses.
  • Comparing current and saved order and position state helps identify openings, closures, and other changes.
  • Order and deal history can provide details for classifying trade events, but updates may be delayed.
  • Comparing saved and current stop-loss and take-profit values can reveal modifications.

Tags

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.