OPEN-SOURCE SCRIPT

Chart Patterns Auto Detection, Measured Targets & Entry Signals

552
CHART PATTERNS — AUTO DETECTION, MEASURED TARGETS & ENTRY SIGNALS

OVERVIEW

Chart patterns are the oldest idea in technical analysis and the least tested. "Head and shoulders works." "The measured move is the target." Everyone repeats it. Nobody checks.

This tool detects seventeen classical patterns using a published, peer-reviewed algorithm — and then forward-tests every one of them separately, on your instrument, and tells you which ones actually carry an edge and which do not.

The panel ends up saying things like:

Double bottom +0.31R n=44 PROVEN
Head & shoulders -0.08R n=19 (not proven)
Symmetric triangle -0.15R n=13 (thin)

That table does not exist anywhere else. It is the entire point of this script.

It is a research and framing tool. It is not a strategy, not a signal service, and not a validated edge.


THE ENGINE (Lo, Mamaysky & Wang, Journal of Finance, 2000)

The problem with pattern detection is stated best by the authors themselves: the presence of geometric shapes in price charts is often in the eyes of the beholder. Their solution, and the one used here:

1. Smooth the price with nonparametric kernel regression (Nadaraya-Watson, Gaussian kernel). This is the crucial step. Raw pivots are noise; the smoothed series is the shape. Every other pattern script hunts pivots on raw price and then argues about the pivot length.
2. Take the local extrema of the smoothed series.
3. Define each pattern as inequality conditions on five consecutive extrema.

Every tolerance is ATR-normalised so the same rule travels across instruments and timeframes. The original paper used fixed percentages tuned to US equities.


THE TAXONOMY IS A PARTITION, NOT A PILE OF RULES

The peaks and the troughs are each classified FLAT / RISING / FALLING — three states, mutually exclusive and exhaustive — and the resulting 3x3 grid names every shape exactly once.

troughs FLAT troughs RISING troughs FALLING
peaks FLAT Rectangle * Ascending triangle R-A broadening, desc *
(or Triple top)
peaks RISING R-A broadening, Rising wedge / Broadening formation *
asc * Asc broadening wedge
peaks FALLING Descending Symmetric triangle * Falling wedge /
triangle Desc broadening wedge

* = bilateral (no directional claim)

Convergence versus divergence splits the two same-slope cells. Head-and-shoulders and double tops/bottoms sit outside the grid — they are defined by the EQUALITY of specific extrema, not by the slope of the envelope — so they are tested separately.

This matters more than it sounds. A pile of independent rules leaks. Three level peaks with FALLING troughs is a right-angled descending broadening formation; with no rule to catch it, the shape drops through to the nearest match and gets logged as a TRIPLE TOP, quietly poisoning that pattern's statistics with a different pattern. Bulkowski's own identification quiz for the right-angled broadening formation opens by warning the reader that they may think they are looking at a triple top. Meanwhile a shape with higher highs AND higher lows that is WIDENING matched nothing at all and was thrown away. Both are now named. The grid is the reason the numbers in the panel mean what they say.


DIRECTIONAL VERSUS BILATERAL — WHY FIVE PATTERNS HAVE NO DIRECTION

A head-and-shoulders makes a claim: it breaks down. A symmetric triangle makes no such claim. Nobody, including Bulkowski, says which way it goes; he publishes statistics for BOTH breakout directions.

So a bilateral pattern arms BOTH boundaries and lets price pick the side. The five are: symmetric triangle, rectangle, broadening formation, and the two right-angled broadening formations. They are drawn in amber, and the trigger logic agrees with the paint.

This is not a cosmetic point. Splitting a symmetric triangle into a "triangle top" and a "triangle bottom" — where the only difference is whether the first extremum happened to be a high or a low — and then trading one short and the other long, is trading a phase accident of where the extremum series began. It is not a forecast, and it halves the sample size for nothing.


THE BOUNDARIES ARE TRENDLINES, NOT HORIZONTAL LINES

A triangle's boundary slopes. Testing a break against a horizontal line drawn at the last extremum is a different test — and it is wrong in a DIFFERENT DIRECTION for different patterns. A converging boundary sits below its last extremum, so a horizontal proxy triggers late. A diverging one sits above it, so the proxy triggers early, on breaks that never happened.

Since the entire purpose of this script is to COMPARE patterns against each other, a bias that flips sign depending on which pattern you are looking at is fatal. Every boundary here carries a slope, is projected to the current bar, and the measured move is projected from the boundary AT THE BAR IT BROKE — which is what the textbook actually says.


THE TWO THINGS IT MEASURES (they are different questions, and both are reported)

A. TRADABILITY. From the trigger bar, with identical geometry for every pattern and for the control, what is the expectancy in R? This is the question "does this pattern predict a favourable move?" It is compared against an unconditional, direction-matched control.

B. THE MEASURED MOVE — and, crucially, HOW FAR AWAY IT IS. Does the classical projected target actually get reached before the pattern's own stop? This is the number every pattern trader assumes and nobody has checked. It is a descriptive statistic, clearly labelled as such, with no control.

Mixing these two makes both meaningless, so they are kept apart. The trade uses a fixed R multiple so that every pattern — and the control — is measured on identical geometry. The measured move is drawn and tested separately.


A HIT RATE WITHOUT A DISTANCE IS NOT A FACT ABOUT THE PATTERN

The panel reports the measured-move hit rate NEXT TO the measured move's distance in R, because the first number is uninterpretable without the second.

On NIFTY futures, live:

Double bottom MM sits 0.6R away reached 73% of the time
Symmetric triangle MM sits 5.7R away reached 0% of the time

Those two rows say the SAME thing. A projection sitting half a unit of risk away being reached three times in four is not evidence that double bottoms work; a projection sitting nearly six units of risk away being reached never is not evidence that symmetric triangles fail. Report the hit rate alone and a reader will draw exactly the wrong conclusion from both.

It also explains a result that looks paradoxical at first: a double bottom can reach its textbook target 73% of the time and still LOSE money, because that target is worth about 0.6R and the trade is being held for 2R. The measured move being reached and the trade being profitable are different events. Almost nobody separates them. This script does.


HOW TO USE

1. A pattern is DETECTED when its fifth extremum confirms. It is not a trade yet.
2. It becomes a TRADE only when price TRIGGERS it: a boundary breaks. The engine never front-runs the pattern.
3. Read the per-pattern calibration BEFORE you weight any of it. A pattern with no proven edge on this instrument is a shape, not a probability.
4. Entry, stop, target and the R multiple are drawn. They are arithmetic, not advice.

BANDWIDTH is the one input that matters. Small = many small patterns; large = few large ones. There is no correct value. There is only the one whose patterns the calibration says work.


NON-REPAINT, AND THE HONEST COST OF IT

A centred kernel looks into the future. Lo, Mamaysky and Wang could use one because they were studying history. We cannot. So the smoother is evaluated only where the whole window already exists, which means an extremum is confirmed roughly one half-window AFTER it occurred, and a pattern therefore prints with that lag.

That lag is the price of not repainting, and it is paid deliberately. Any pattern tool that marks a head-and-shoulders the instant the head forms is either repainting or using a shorter window than it admits.

Everything — extrema, patterns, triggers, calibration — is computed on confirmed bars only.


WHAT IS DELIBERATELY ABSENT

FLAGS AND PENNANTS cannot be detected by this engine and are not faked. Their defining feature is a small consolidation after a sharp pole. Bulkowski puts a flag at a few days to three weeks and calls anything longer a rectangle. But the kernel smoother and the ATR prominence filter exist precisely to destroy small wiggles, and a flag's entire body is often under one ATR. To find flags you need pole detection and channel regression on raw price: a different engine. A pennant, in any case, IS a symmetric triangle that happens to follow a pole.

ELLIOTT WAVE is absent because it is not objectively definable. The wave count is degree-dependent and non-unique. Encoding it would test the encoding, not the theory, and reporting "no edge" against a definition its own proponents would disown is a strawman. This script attacks folklore by testing it fairly, or it does not attack it at all.


WHY THESE PARTS ARE ONE TOOL

A pattern without a smoother is a subjective drawing. A smoother without pattern rules is just a moving average. Rules without a measured target give you nothing to trade. A target without an entry, a stop and an R multiple is not a trade. And all of it, without a per-pattern calibration, is exactly the folklore this script was built to test. Remove any one piece and you have another pattern-drawing tool that asserts an edge it has never measured.


DATA AND SCOPE

Any symbol, any timeframe. ATR-normalised throughout. No volume required.


EXPORTS (Data Window — consume from other scripts via input.source())

EXP_Smooth, EXP_Pattern, EXP_Dir, EXP_Trigger, EXP_Entry, EXP_Stop, EXP_Target, EXP_RR, EXP_PatternEdge, EXP_TargetHitRate


CONCEPT CREDIT

The kernel-regression pattern-recognition algorithm and the core pattern definitions are from Andrew W. Lo, Harry Mamaysky and Jiang Wang, "Foundations of Technical Analysis: Computational Algorithms, Statistical Inference, and Empirical Implementation", Journal of Finance 55(4), 2000. The Nadaraya-Watson estimator is due to E. A. Nadaraya and G. S. Watson (1964). The patterns themselves long predate all of us; the modern written tradition runs through Edwards & Magee. The right-angled broadening formations, the broadening wedges, the ascending and descending triangles and the triple tops and bottoms are documented in Thomas Bulkowski, "Encyclopedia of Chart Patterns"; his published success rates are claims measured on US daily stocks, and testing them on YOUR instrument is the purpose of this tool. ATR — J. Welles Wilder. Triple-barrier forward labelling — Marcos Lopez de Prado. Welch's t-test — B. L. Welch.

The exhaustive peak/trough partition, the bilateral trigger, the sloping-boundary trigger, the per-pattern calibration, the measured-move test and the direction-matched control are the author's own. Clean-room implementation; no third-party Pine code is reused. Not affiliated with, nor endorsed by, any of the above.


HONESTY AND LIMITATIONS

Lo, Mamaysky and Wang's own conclusion deserves to be read before anyone trades this: several patterns DO carry incremental information, but patterns that are optimal for detecting statistical anomalies need not be optimal for indicating trading profits, and vice versa. A pattern can be statistically real and still not pay after costs.

Calibration here is IN-SAMPLE, with no costs or slippage, and uses overlapping windows. A proven in-sample edge is NOT a guarantee out-of-sample.

Pattern counts are small by nature. A rare pattern may never reach a usable sample size, and the panel will keep saying so — "thin", "warming" — rather than pretend. Nothing is marked PROVEN below t = 1.96 against the control, and nothing is rated at all below the minimum sample.

Entry is the CLOSE of the trigger bar, for the pattern and for the control alike. Entering at the boundary — a better price — while the control enters at the close would hand every pattern a free head start and manufacture an edge out of nothing.

When both barriers are touched on the same bar, the stop is assumed first. Unresolved trades at the horizon are marked to market rather than counted as wins.

A different bandwidth gives different patterns. If a pattern shows no edge, the honest conclusion is that it has none here. Nothing in this script predicts price.


DISCLAIMER

Research and educational tool only. Not financial advice, not a recommendation, and no guarantee of results. Entry, stop and target output is arithmetic, not advice. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use.

Отказ от ответственности

Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.