Skip to content
All library documents

Structuring an MQL5 Trading Strategy with a Finite State Machine

Article MQL5 articles

Summary

The article shows how to replace scattered conditional logic in an Expert Advisor with a finite state machine. A context object delegates each tick to one active state, while separate states handle idle signal scanning, order submission, open-position management, and exit processing. State changes follow explicit event and guard conditions, such as confirming a fill, detecting an exit signal, or handling a rejected order. Lifecycle methods separate setup, per-tick evaluation, and cleanup.

It also explains how to organize MQL5 interface, context, implementation, and state files to resolve circular dependencies with forward declarations and include guards. The article provides a transition matrix, class structure, and example implementation details, but no measured execution or reliability comparison. The design is an architectural pattern: it can make strategy phases easier to isolate and debug, while trading behavior still depends on correctly specified transitions and order-handling logic.

Key ideas

  • A strategy context delegates each tick to its single active state.
  • Separate states isolate entry, trade management, exit, and idle behavior.
  • Explicit transition triggers and guard conditions make strategy flow easier to inspect.
  • Lifecycle methods distinguish state initialization, evaluation, and cleanup.
  • Forward declarations and a separate implementation include resolve MQL5 type dependencies.

Tags

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