# D06-F05-A01 — Unified Candlestick Pattern Registry

> **Domain:** D06 — Price Action and Candlesticks  
> **Family:** D06-F05 — Candlestick Scanning and Context  
> **Difficulty:** 2  
> **Canonical scope:** deterministic, point-in-time scanner infrastructure

## Executive summary

Which detector definition is allowed to run, under which stable identifier and version? This topic answers that question with a dependency-free reference algorithm that can construct a deterministic, versioned registry that rejects duplicate identities and ambiguous detector metadata. The output is descriptive scanner evidence. It is not a trading recommendation, calibrated probability, or claim that candlestick patterns predict returns.

TA-Lib documents pattern recognition as a programmatic function group and exposes batch, streaming, and dynamic-dispatch APIs ([TA-Lib functions](https://ta-lib.org/functions/), [core API](https://ta-lib.org/api/)). That establishes the engineering relevance of consistent dispatch and array processing; it does not make TA-Lib’s internal candle settings or integer outputs a universal market definition. This package therefore names every threshold and tie-break as a Fintech Builder implementation choice.

## Problem and financial relevance

Candlestick geometry can be correct while scanner output is operationally unreliable: identifiers drift, live bars masquerade as final, context arrives after the fact, overlapping labels flood a result set, or ranking hides its weights. A registry is a controlled dispatch table. It freezes identity, direction, window length, implementation entry point, priority, version, and enabled state before a scan begins.

The practical outcome is an auditable component that research, alerting, and educational systems can reproduce across Python and TypeScript. Passing implementation tests establishes contract correctness only. Lo, Mamaysky, and Wang show why subjective chart recognition benefits from systematic rules, while their empirical design also illustrates that usefulness is a separate question ([NBER Working Paper 7613](https://doi.org/10.3386/w7613)).

## Learning contract

After this topic, a reader can:

- explain the exact decision boundary and its causality;
- validate the topic-specific input and output contract;
- calculate the canonical synthetic example independently;
- reproduce matching Python and TypeScript outputs;
- distinguish geometry detection, context fit, confirmation, ranking, and trading performance.

Prerequisites are Candle Anatomy, Scale-Aware Body Classification, closed-bar OHLCV semantics, arrays, sorting, and basic finite-number validation. The topic excludes order execution, portfolio sizing, backtested profitability, vendor parity, discretionary pattern interpretation, and model calibration.

## Definition and scope

The canonical variant is repository-selected and causal: only facts available at the declared `as_of` or bar index may affect output. Comparisons at thresholds are inclusive. Stable text IDs break remaining ties. Missing evidence produces an explicit null, warm-up, skip, or invalid state; it is never silently imputed.

| Classification | Treatment |
|---|---|
| Sourced fact | OHLC/kline and API-organization claims are cited to official documentation. |
| Implementation choice | Formula weights, windows, precedence, level mapping, and state transitions are declared here. |
| Synthetic teaching input | Every `SYNTH:*` record and numeric fixture is invented for reproducible teaching. |
| Author-derived calculation | Worked values follow the displayed formula and fixture. |
| Empirical claim | None. Detector correctness does not establish predictive or economic value. |

## Input data contract

| Field | Type | Meaning and policy |
|---|---|---|
| `patterns` | array | Detector specifications; IDs and case-folded names must be unique. |
| `pattern_id` | string | A D06-F02 through D06-F04 catalog ID. |
| `window` | integer | One through five terminal bars. |
| `version` | string | Immutable detector-contract version. |

All timestamps use RFC 3339 UTC strings in the fixtures. Production ingestion must preserve instrument/venue identity, interval/session calendar, raw or adjusted price basis, source ownership, observation time, availability time, and finality. Binance’s provider-specific stream is evidence that a kline payload may carry OHLCV, time bounds, and an explicit closed flag; it is not imposed as a universal schema ([official stream schema](https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#klinecandlestick-streams-for-utc)). Arrays are ordered, finite, and not deduplicated or imputed by this topic.

## Output contract

| Field | Type | Meaning and invariant |
|---|---|---|
| `registry_id` | string | Stable ordered ID/version manifest. |
| `patterns` | array | Specifications sorted by pattern ID. |
| `max_window` | integer | Largest required causal window. |
| `enabled_count` | integer | Detectors eligible for dispatch. |

Successful output is deterministic for identical inputs. Invalid structural inputs raise an error in both languages. Warm-up or unavailable evidence that is part of normal operation returns a reason-coded state where this topic defines one.

## Mathematical formulation

The canonical definition is:

\[
R=\operatorname{sort}_{pattern\_id}(S),\qquad R_{id}=\operatorname{join}(pattern\_id@version)
\]

Every symbol is topic-local: arrays and sets are the supplied records; weights are non-negative configuration; times and indexes are knowledge cut-offs; scores are dimensionless. No formula estimates expected return. Floating-point outputs use IEEE-754 binary numbers with test tolerance `1e-9`; identity and state outputs require exact equality.

## Algorithm

1. Validate each specification.
2. Reject duplicate ID or name.
3. Sort by stable catalog ID.
4. Freeze ID/version manifest.
5. Expose enabled dispatch set.

See [executable pseudocode](./examples/PSEUDOCODE.md) and the shared [canonical fixture](./datasets/fixtures.json).

## Worked synthetic example

Two specifications arrive out of order. Sorting yields D06-F02-A01 before D06-F03-A01; one disabled detector leaves enabled_count = 1 and max_window = 2.

The calculation is independently frozen in `datasets/fixtures.json`; Python and TypeScript both compare against those stored values. The static diagram below shows where the topic acts in the family pipeline.

![Unified Candlestick Pattern Registry decision pipeline](./visuals/static/decision.svg)

[Open the full-size SVG](./visuals/static/decision.svg) or use the self-contained [guided playground](./visuals/animated/playground.html) to inspect canonical, boundary, and failure states.

## Implementation guide

- [Python reference](./implementations/python/pattern_registry.py)
- [TypeScript reference](./implementations/typescript/pattern_registry.ts)
- [Python tests](./tests/test_pattern_registry.py)
- [TypeScript tests](./tests/pattern_registry.test.ts)

The small topic modules deliberately delegate to one family core so the nine tutorials cannot drift on shared validation semantics. The public topic function remains independently discoverable. Typical time is O(n) for validation; sorting or component construction is O(n log n). Returned arrays require O(n) space.

## Testing, edge cases, and failure modes

The suite checks the canonical fixture, an invalid empty input, exact state/value parity, numeric tolerance, stable ordering, and the family’s causal boundary. Topic-specific risks include threshold equality, missing history, zero scales, duplicate IDs, provisional bars, future-confirmed levels, transitive overlap, contradictory levels, expiry, and duplicate windows.

- A valid output can still inherit wrong bars, sessions, adjustments, identifiers, or provider revisions.
- A context score can be reproducible yet empirically useless.
- Cross-sectional ranking can favor liquid or recent instruments because the declared weights ask it to; that is policy, not truth.
- Support and resistance remain rule-dependent concepts. CME describes their common chart role but does not prescribe this algorithm ([CME technical-analysis lesson](https://www.cmegroup.com/education/courses/technical-analysis/support-and-resistance)).
- Production systems need calendar governance, observability, capacity limits, version migration, and out-of-sample evaluation beyond this teaching reference.

## Historical-example decision

**Not useful.** A named market event would add narrative without strengthening this infrastructure contract and could introduce provider-basis, licensing, and hindsight ambiguity. The synthetic case makes identity, clocks, thresholds, exact arithmetic, and redistribution permission explicit. A future historical case should be included only with verified symbol/venue identity, interval/session, raw or adjusted basis, provider and retrieval time, revision state, detector version, public redistribution rights, and a claim limited to detection—not causation or profitability.

## Visual explanations and derivatives

The [visual plan](./visuals/VISUAL-PLAN.md) maps the Mermaid flow, static SVG, and interactive lab to the learning obstacles. The [article](./article/ARTICLE.md) is a standalone tutorial; the [video script](./video/VIDEO-SCRIPT.md) is scene-based and uses the exact same formula, fixture, limitations, and next-topic titles.

## Related catalog topics

- D06-F02-A01 — Doji
- D06-F03-A01 — Bullish Engulfing
- D06-F05-A02 — Candlestick Pattern Occurrence Contract

## References

See [REFERENCES.md](./REFERENCES.md) for source roles, applicability, and limitations.
