# D06-F05-A05 — Support/Resistance Pattern Context

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

## Executive summary

Was a directional candlestick occurrence close to the relevant level that was already knowable? This topic answers that question with a dependency-free reference algorithm that can select the nearest causally confirmed directional level and turn ATR-normalized distance into a transparent [0,1] context feature. 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. Bullish occurrences are compared with support and bearish occurrences with resistance. Levels confirmed after the occurrence are excluded to prevent hindsight.

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 |
|---|---|---|
| `pattern_price` | number | Declared anchor price for the occurrence. |
| `atr` | positive number | Prior-data distance scale. |
| `levels` | array | Price, kind, strength, and confirmation index. |
| `occurrence_index` | integer | Point-in-time cut-off. |

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 |
|---|---|---|
| `matched_level` | object or null | Nearest causally eligible level. |
| `distance_atr` | number | Absolute normalized distance. |
| `context_score` | number or null | Linear proximity feature. |
| `state` | enum | Ready, no causal level, or unsupported direction. |

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:

\[
d=\frac{|P-L^*|}{ATR},\qquad context=\max(0,\min(1,1-d/d_{max}))
\]

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. Choose direction-relevant level kind.
2. Remove future-confirmed levels.
3. Normalize distance by prior ATR.
4. Use strength as deterministic tie-break.
5. Map distance to context score.

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

## Worked synthetic example

A bullish occurrence at 100 is 1 point above support 99. With ATR 2, distance is 0.5 ATR; a 2 ATR limit gives context score 0.75.

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.

![Support/Resistance Pattern Context 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/support_resistance_context.py)
- [TypeScript reference](./implementations/typescript/support_resistance_context.ts)
- [Python tests](./tests/test_support_resistance_context.py)
- [TypeScript tests](./tests/support_resistance_context.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-A04 — Contextual Candlestick Confidence Score
- D07-F04-A01 — ATR
- D08 — Chart Patterns

## References

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