Disclaimer: This article is for educational and informational purposes only. It does not constitute financial or investment advice. Trading forex and CFDs carries significant risk of loss. Past performance of any strategy – including backtests – does not guarantee future results. Never trade with money you cannot afford to lose.
What Is This Strategy?
Head And Shoulders Pattern is a rules-based head and shoulders pattern strategy for MetaTrader 5 that uses pure price action (no moving averages, RSI, MACD, ATR or volume) to identify potential swing-trading reversals. Instead of reading an indicator, the expert advisor (EA) reads market structure: the sequence of swing highs and lows price prints as it moves. When those swings form a left shoulder, a higher head and a lower right shoulder, and price then closes through the "neckline" joining the two troughs between them, the strategy signals a possible change in trend.
The head and shoulders chart pattern is one of the oldest formations in technical analysis. It is designed for a trend that is losing momentum: the head is the final push to a new extreme, and the right shoulder is a rally that fails to reach it. A close through the neckline may indicate that the dominant side has lost control. The EA also trades the mirror image, the inverse head and shoulders, as a potential bottom after a downtrend.
As a learning tool, it suits anyone who has spotted this pattern on a chart and wondered how to define it objectively. Discretionary head and shoulders pattern trading is notoriously subjective. This EA turns every part of the pattern into a measurable rule, so you can study how the formation behaves in the Strategy Tester. Think of it as a way to analyse the pattern, not a shortcut to results.
How It Works
The EA evaluates only completed bars on your chart's timeframe, once per new bar.
How the Head and Shoulders Pattern Strategy Reads Price Structure
- Swing detection: A swing high is a bar whose high tops the previous
SwingStrengthbars (default 3) and is not exceeded by the next ones; swing lows mirror this. Waiting for those later bars means swings do not repaint, but they are confirmed with a lag. - Zig-zag clean-up: Swings must alternate high, low, high, low. If two highs appear in a row, the more extreme one replaces the earlier one.
- Five-swing template: For a bearish top, the last five swings must run left shoulder (high), trough 1 (low), head (high), trough 2 (low), right shoulder (high).
Geometry Rules
The neckline is a straight line through trough 1 and trough 2, extended forward, so it can slope. Each peak's height is measured vertically from that line. A setup is "armed" only if:
- The head is higher than both shoulders.
- The head's height is at least
HeadToShoulderRatio(1.2x) the taller shoulder's height. - The shorter shoulder is at least
ShoulderSymmetry(50%) of the taller one. - The troughs differ by no more than
MaxNecklineTilt(50%) of the head height, filtering out steep necklines. - The bar count from left shoulder to head versus head to right shoulder is balanced to at least
MinTimeSymmetry(30%).
Entry, Invalidation and Expiry
- Entry: The strategy signals a sell on the first bar that closes below the projected neckline. Wicks through it are ignored, and the market order is sent as the next bar opens.
- Invalidation: Any bar trading above the right shoulder cancels the setup. A new, higher right shoulder that still fits the geometry can re-arm it.
- Expiry: With no neckline close within
BreakExpiryBars(30) bars, the setup expires. - One trade at a time: One position per magic number, and each right shoulder can trigger only once.
Stop-Loss and Take-Profit Logic
- Stop-loss: Above the right-shoulder high, plus
StopBufferPct(10%) of the pattern height. - Take-profit: The classic "measured move": the head's height above the neckline, multiplied by
TargetMultiple, projected from the neckline at the breakout bar. - Reward-to-risk filter: If reward divided by risk is below
MinRewardRisk(1.0), or either distance falls inside the broker's stop level or spread, the trade is skipped and logged. - Exit: There is no trailing stop or time exit; each trade closes at its stop or target.
The buy side is an exact mirror: a low left shoulder, a lower head, a higher right shoulder and a neckline through the two peaks. The strategy signals a buy on a close above that neckline, with the stop below the right shoulder.

Strategy Parameters
| Parameter | Default | Min | Max | Description |
|---|---|---|---|---|
| SwingStrength | 3 | 2 | 8 | Bars on each side used to confirm a swing. Higher values find larger patterns with more lag. |
| HeadToShoulderRatio | 1.20 | 1.0 | 2.5 | Minimum head height above the neckline as a multiple of the taller shoulder. |
| ShoulderSymmetry | 0.50 | 0.2 | 0.9 | Minimum ratio of the shorter shoulder's height to the taller one's. |
| MaxNecklineTilt | 0.50 | 0.0 | 1.0 | Maximum gap between the two neckline points as a fraction of head height. |
| MinTimeSymmetry | 0.30 | 0.1 | 0.9 | Minimum ratio between the bar lengths of the pattern's left and right halves. |
| StopBufferPct | 0.10 | 0.0 | 0.5 | Extra stop distance beyond the right shoulder as a fraction of pattern height. |
| TargetMultiple | 1.00 | 0.5 | 2.0 | Multiple of pattern height projected from the neckline for the take-profit. |
| MinRewardRisk | 1.00 | 0.3 | 3.0 | Minimum reward-to-risk ratio required before an order is sent. |
| BreakExpiryBars | 30 | 5 | 150 | Bars an armed pattern waits for a neckline close before expiring. |
| Lots | 0.10 | 0.01 | 1.0 | Fixed order volume, adjusted to broker lot limits. |
| Magic | 7311 | 0 | 9,999,999 | ID that tags the EA's trades and enforces one position at a time. |

Recommended Chart Settings
The source code suggests EURUSD, GBPUSD or XAUUSD (gold) on H1 to H4, or the US500 index on H1. These liquid markets tend to produce swing structure clean enough for the geometry rules. The EA is single-timeframe: every calculation uses the chart it is attached to.
Higher timeframes generally produce fewer, more significant formations; lower ones may add noise and spread costs. Behaviour differs between trending, ranging and news-driven conditions, and between brokers, so results will vary. The EA only tracks swings from bars that close after it is attached, so it needs time before recognising a first pattern, and a restart resets that memory.
How to Install on MetaTrader 5
- Download the .ex5 file from the link below
- Copy it to your MT5
MQL5\Expertsfolder - Restart MetaTrader 5 or refresh the Navigator panel
- Drag the EA onto a chart matching the recommended symbol and timeframe
- Configure the input parameters and enable Algo Trading
The file is HeadAndShouldersPattern.ex5. In the Strategy Tester, the Journal tab logs every pattern the EA armed, traded or skipped.
What to Consider Before Using This EA
Strengths. The main advantage is objectivity. Every element of the head and shoulders price pattern is defined numerically, so results are repeatable and testable. There are no lagging indicators, the right shoulder provides a built-in invalidation point, and the stop and target are known before entry.
Limitations:
- Low trade frequency. Valid patterns are rare, especially on H4. A backtest may contain only a handful of trades, making statistics such as win rate unreliable.
- Confirmation lag. By the time the right shoulder is confirmed, price may be near the neckline already, so many setups fail the reward-to-risk check.
- False breakouts. Price can close beyond a widely watched neckline and then snap back.
- Strong trends. This is a counter-trend method; persistent trends often overrun potential tops and bottoms.
- Choppy ranges. Sideways markets create small swings that can loosely fit the geometry without a real shift in sentiment.
- Fixed lot size. Stop distance depends on pattern size, so the amount at risk varies from trade to trade.
- No trade management. There is no trailing stop, break-even, session or news filter, and weekend gaps can cause slippage past the stop.
- Overfitting risk. With nine tunable pattern settings, it is easy to optimise a backtest that fits the past but not the future.
A head and shoulders pattern strategy is best treated as one tool for studying reversals, not a complete trading plan.
Risk Management Tips
- Size from the stop. Since
Lotsis fixed, choose a volume so a typical stop represents no more than 1-2% of your account, and consider sizing for the widest stops you see in testing. - Start on a demo account. Forward-test for several months to compare live spreads, slippage and execution with the Strategy Tester.
- Understand drawdown. Drawdown is the decline from an account's peak to its lowest point. Losing streaks are normal, and a backtest's maximum drawdown is not a ceiling for the future.
- Test realistically. Use real-tick modelling where available, include spreads and commissions, and check different years and market regimes.
- Watch correlation. Running the EA on EURUSD and GBPUSD together can create two similar positions, effectively doubling exposure.
- Keep a journal. Recording each pattern and outcome may help you learn when head and shoulders pattern forex setups behave as expected, and when they do not.
Risk Warning
Trading foreign exchange, CFDs, and other leveraged financial instruments involves substantial risk of loss and is not suitable for all investors. The strategies and tools discussed on this page are provided for educational purposes only and do not constitute financial advice, investment recommendations, or solicitation to trade. Always consult a qualified financial adviser before making trading decisions. Past backtest performance is not indicative of future results.
Downloads
- Expert Advisor: HeadAndShouldersPattern.ex5 (0 downloads)
- Source Code: HeadAndShouldersPattern.mq5 (0 downloads)
- Documentation: HeadAndShouldersPattern.pdf (0 downloads)