Implementing it in MQL5
The crossover is the easy part. The engineering work is deciding when to read it, which position belongs to the strategy, and what happens when an order fails.
Our baseline remains EURUSD, H1, 20/50 simple moving averages of closing prices, and a fixed 0.1-lot position. It exits and reverses on the opposite crossover. There is no protective stop in this teaching version, so exposure is not capped at a known loss.
Implementation walkthrough: the snippets below explain the core logic; they are not a complete downloadable EA. They have not been compiled or executed here, and this article does not claim a tested trading result.
Create the indicators once
Use inputs for the two periods and volume. In OnInit(), reject non-positive periods, a fast period greater than or equal to the slow period, and volume outside the symbol’s permitted minimum, maximum or step. Create the indicator handles once, rather than recreating them on every tick.
int fastHandle = INVALID_HANDLE;
int slowHandle = INVALID_HANDLE;
// Inside OnInit(), after validating inputs:
fastHandle = iMA(_Symbol, PERIOD_H1, 20, 0,
MODE_SMA, PRICE_CLOSE);
slowHandle = iMA(_Symbol, PERIOD_H1, 50, 0,
MODE_SMA, PRICE_CLOSE);
if(fastHandle == INVALID_HANDLE || slowHandle == INVALID_HANDLE)
return INIT_FAILED;
iMA() returns a handle, not a moving-average value. Read values through CopyBuffer(), and release valid handles in OnDeinit(). See the official iMA reference.
Read only completed bars
Bar zero is still forming. Compare bars two and one to detect a completed crossover. With the fixed-size arrays below, CopyBuffer places the older value first: element zero is bar two and element one is bar one. Reversing this interpretation reverses the signal.
// Inside the new-H1-bar processing block:
double fast[2], slow[2];
if(CopyBuffer(fastHandle, 0, 1, 2, fast) != 2 ||
CopyBuffer(slowHandle, 0, 1, 2, slow) != 2)
return; // Data not ready: no decision yet.
bool crossUp = fast[0] <= slow[0] && fast[1] > slow[1];
bool crossDown = fast[0] >= slow[0] && fast[1] < slow[1];
The equality rule is deliberate: touching the slow average is not itself an entry. A subsequent strict crossing is. The indexing and copy order are documented in the CopyBuffer reference.
One decision per bar, with explicit state
Track the H1 opening timestamp from iTime(_Symbol, PERIOD_H1, 0). On startup, initialise it to the current bar and wait for the next bar; do not replay an old crossover midway through an hour. If data is temporarily unavailable, retry reading within that bar. Once a valid decision is made, mark it processed before submitting orders so subsequent ticks cannot duplicate the request.
On a bullish signal, stay put if already long; otherwise close the strategy’s short, confirm the close, then request a long. Mirror this for a bearish signal. With neither signal, do nothing. If a close fails or is partial, do not open the reverse leg. If entry fails, log the failure and remain flat until a future signal under this baseline policy.
Use a magic number and symbol checks to identify ownership. On hedging accounts, inspect positions and close the intended ticket. On netting accounts, other strategies can share the same symbol position: use an isolated test account rather than assuming a magic number separates exposure. A successful CTrade method return alone is insufficient; inspect the server return code and resulting position. See PositionClose.
Make behaviour observable
Log the signal bar, both pairs of averages, intended action, ticket, requested volume, actual fill and return code. The order is submitted on an available tick of the new bar, not at a guaranteed candle-open price. A deviation setting does not impose the one-pip adverse fill assumption from the specification; model that separately.
Before judging profitability, verify no crossover produces no trade, a valid crossover produces one decision, repeated ticks produce no duplicates, and a failed close prevents reversal. Next, use the tester to inspect those behaviours against historical prices.
Building or reviewing your own trading system?
I can help turn the specification, implementation and testing into a coherent engineering process. Discuss your project.
