FindHeadAndShoulders
Background
Head and shoulders is one of the best-known reversal patterns. It is three peaks in a row: a middle peak (the head) that is higher than the two on either side (the shoulders), with the troughs between them roughly level forming a "neckline". When the price breaks below that neckline, traders read it as the uptrend running out of steam. The upside-down version, with three troughs, is an inverse head and shoulders and signals the opposite.
FindHeadAndShoulders checks whether the recent peaks and troughs form this
shape at the bar you specify, including that the two shoulders are reasonably even and that
the price has broken the neckline. It returns 0 if there is no pattern, 1 for a bullish
(inverse) pattern and 2 for a bearish (standard top) pattern. This is the scriptable version
of the Head & Shoulders pattern scanner.
Included formula
The toolbox ships a ready-made Head and Shoulders scanner built on this function, so you can use it without writing any code. It runs as an Exploration: in AmiBroker open the Analysis window, pick Head and Shoulders from the WiseTraderToolbox formulas, choose a watchlist and click Explore to list every symbol currently forming a head-and-shoulders (or its inverse). Applied to a chart, the same formula draws the pattern and its neckline. The trend size and distance threshold are set from its parameters.
The exported function
If you would rather build your own scan, the toolbox exports the calculation as a single AFL function you can call directly — it is the engine inside that scanner.
FindHeadAndShoulders(TrendSize, Bar, Distance)
Parameters
| Parameter | Description |
|---|---|
| TrendSize | The amount in percent a price has to move for a point to be counted as a peak or trough. |
| Bar | Which price bar to test for a completed pattern. The current last bar is the total number of bars minus 1. |
| Distance | The maximum percentage difference allowed between the two shoulders for the pattern to count. A smaller value insists the shoulders be more even and symmetrical. Must be between 0 and 100. |
Return Value
The function returns 0 if no pattern was found, 1 if a bullish (inverse head and shoulders) pattern was found, and 2 if a bearish (standard head and shoulders top) pattern was found. It also sets AFL variables describing the three peaks, three troughs and their bar positions.
Usage
result = FindHeadAndShoulders( 5, BarCount - 1, 20 );
Filter = result > 0;
AddColumn( IIf( result == 1, 1, 0 ), "Inverse (Bullish)" );
AddColumn( IIf( result == 2, 1, 0 ), "Top (Bearish)" );
This tests a single bar, so scan history by calling it in a loop over the bars you want to check. If you allow too large a Distance the shoulders can be very uneven and the matches become less reliable.