# D06-F05-A08 — Candlestick Confirmation and Invalidation State Machine

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

## Executive summary

After geometry matches, when does a candidate become confirmed, invalidated, or expired? This topic answers that question with a dependency-free reference algorithm that can advance directional candidates through closed-bar transitions with ordered levels, finite expiry, and complete reason-coded history. 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. Detection and confirmation are different events. Provisional bars do not transition state, and a candidate cannot wait forever for a favorable close.

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 |
|---|---|---|
| `detection_index` | integer | Closed bar where geometry becomes knowable. |
| `confirmation_level` | number | Inclusive terminal-close boundary. |
| `invalidation_level` | number | Opposite inclusive boundary. |
| `events` | array | Strictly increasing later bars with closure state and close. |

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 |
|---|---|---|
| `state` | enum | Awaiting, confirmed, invalidated, or expired. |
| `transitions` | array | Complete from/to/reason audit. |
| `terminal` | boolean | Whether monitoring can stop. |

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:

\[
bullish:\ confirmed\iff C_t\ge L_c,\ invalidated\iff C_t\le L_i;\quad t\le t_0+N
\]

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. Detect geometry.
2. Arm ordered levels.
3. Ignore provisional update.
4. Evaluate closed-bar boundaries.
5. Confirm, invalidate, or expire.

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

## Worked synthetic example

A bullish candidate detected at bar 10 waits after close 102, then confirms at bar 12 when the closed-bar close reaches 106, above the inclusive 105 level.

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.

![Candlestick Confirmation and Invalidation State Machine 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/confirmation_state_machine.py)
- [TypeScript reference](./implementations/typescript/confirmation_state_machine.ts)
- [Python tests](./tests/test_confirmation_state_machine.py)
- [TypeScript tests](./tests/confirmation_state_machine.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-F05-A02 — Candlestick Pattern Occurrence Contract
- D06-F05-A04 — Contextual Candlestick Confidence Score
- D06-F05-A09 — Candlestick Scanner Ranking and Deduplication

## References

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