Automatically Detecting an M-Top with XScript: Swing Highs, Neckline and Multiple Filter Conditions
TL;DR: An M-top can be detected automatically with code: define the lookback range, two highs, the neckline and the starting low, then find the highs with a swing high function and stack several filter conditions so the result stays close to the standard pattern.
Key ideas
- Before writing code, break the pattern into measurable elements: the length of the observation range, the two highs and their positions, the low between the two highs (the neckline), the starting low, and the head height and base amplitude. Once these are clearly defined, the code is easier to write.
- The highs are obtained with the custom c swing height and c swing height bar, which give the value and the position. They differ from the built-in swing height by only one parameter; without the custom functions you can use swing height instead, though the result is less good.
- The neckline is the lowest point between the two highs, and the starting low is searched backward from the second high. The higher of the two highs is set as top; head height is top minus the neckline, and base amplitude is the neckline minus the bottom.
- Detection works by stacking conditions one by one: the second high must exist, both highs must be 10% above the neckline, head height must be greater than base amplitude, there must be no higher point between the two highs, and one of the highs must be the highest point in the range. Every threshold can be adjusted to personal needs.
- After backtesting, several M-tops can be marked on the chart. Most are quite standard, but in one case the two highs are not as clear.
Ask AI about this episode
Copy the prompt, paste it into an AI service, and add the question. The AI reads the notes on this site and links to the page and the video timestamps.
Or open directly:ChatGPTClaudeGrokPerplexity
Section summaries
0:05M-Top Definition and the Functions Needed
Defines the M-top's range, two highs, neckline and starting low, and introduces the functions that will be used, such as swing height, max list and the ifs conditional.
▶ Watch from here2:55Writing the M-Top Code Step by Step and Backtesting
Use the custom c swing height and c swing height bar to get the two highs and their positions, then use an ifs conditional to find the lowest point between the two highs as the neckline, and search backward from the second high for the starting low. Next, add conditions one by one: the second high must exist, both highs must be 10% above the neckline, head height must be greater than base amplitude, there must be no higher point between the two highs, and one of the highs must be the highest point in the range. In the backtest, several M-tops are marked on the chart, and one of them is not as clear.
▶ Watch from here

