ContextScore

278
Library "ContextScore"
Universal Market Context & Composite Scoring Engine for the opening-range
indicator family. Rates the *quality of a trade's location* (not the validity
of the signal logic) and returns one normalized Context Score (0-100) with a
letter grade, broken into six independent 0-100 components:
1. Signal Quality (computed in-library from the signal candle's OHLC)
2. Path Obstruction (auction friction in the entry -> TP1 corridor)
3. Composite Alignment (position vs the 5-OR composite value area)
4. Previous Session (position vs the prior session's levels)
5. Current Session (position vs the current session's levels)
6. Remaining Room (runway beyond TP1 before significant historical structure)
The engine is PURE: per Pine's library rules exported functions cannot read
host globals or inputs, so the host computes every level/tunable and passes
them in via `ScoreInput` / `ScoreParams`; the library returns `ScoreOutput`.
It is family-independent and stateless, so future real-time/continuous
scoring is an extension (call `score()` continuously), not a redesign.

Usage (host):
import <username>/ContextScore/<version> as ctx
ctx.ScoreInput si = ctx.ScoreInput.new(direction = dir, entry = e, tp1 = t1, ...)
ctx.ScoreParams sp = ctx.ScoreParams.new(wQuality = ..., threshA = ..., ...)
ctx.ScoreOutput so = ctx.score(si, sp)
ctx.Explanation ex = ctx.explain(so, sp) // plain-language strengths / weaknesses

Note on `ScoreParams`: the development-plan sketch lists weights + obstruction baseCosts;
the grade thresholds (`threshA/B/C`) and quality sub-weights (`qwClose/qwBody`) are here
because the corresponding components are produced inside the library, so their tunables
must arrive as parameters too. The host populates them from its inputs. Zone band edges
default to even splits and are kept internal for this milestone (exposable later).

Remaining Room (Component 6): the host flattens its per-type historical level memory
(past ORH/ORL, VAH/VAL, composite POCs, weekly H/L) into four index-aligned arrays on
`ScoreInput` — `histPrice`, `histBaseCost`, `histAge`, `histLabel`. `histLabel` (a small
extension beyond the plan's three arrays) carries a short type tag per level so the Room
F4 detail can name its contributors. The host MUST pass initialized (possibly empty)
arrays; an empty set yields a clean Room score of 100.

score(s, p)
  Computes the composite Context Score for one trade location.
  Parameters:
    s (ScoreInput): Evaluation context (levels, entry, tp1, signal candle OHLC, historical memory).
    p (ScoreParams): Tunables (component weights, sub-weights, baseCosts, decay, grade thresholds).
  Returns: `ScoreOutput` carrying the total, six component scores, letter grade, F4 detail,
the current-session band tag, and the nearest-opposing distance.

explain(o, p)
  Derives plain-language strengths and weaknesses (F3) from a `ScoreOutput`.
Four signal groups (Acceptance = weighted mean of Comp/Curr/Prev; Path; Room;
Quality) each speak ONLY outside the neutral zone — strength at score >= p.strongCut
(default 70), weakness at score < p.weakCut (default 50, i.e. below average).
Middling groups stay silent so the explanation surfaces genuine extremes rather
than restating every component score (those are already reported elsewhere).
Firing groups are ranked by weighted distance from neutral (`weight·|score-50|`,
descending, uncapped) — i.e. their pull on the total — then mapped to a phrase and
augmented with categorical phrases from the band tag and nearest-opposing distance.
Both lists may legitimately come back empty (a balanced, unremarkable setup).
  Parameters:
    o (ScoreOutput): A `ScoreOutput` from `score()`.
    p (ScoreParams): The same `ScoreParams` used for the score (for the grouping weights).
  Returns: `Explanation` with ranked `strengths` and `weaknesses`.

detailStr(d, fmt)
  Join a ScoreDetail array into "label val · label val" (values via `fmt`). Empty → "—".
  Parameters:
    d (array<ScoreDetail>): Per-component F4 detail array (e.g. `ScoreOutput.qDetail`).
    fmt (string): `str.tostring` number format for each value.
  Returns: Formatted single-line detail string, or "—" when empty.

joinWrap(a)
  Join a string array with ", " but wrap to a new line every 2 items; empty → "—".
For narrow cells (status S/W): pairs items per line rather than one long row.
  Parameters:
    a (array<string>): Strings to join (e.g. an `Explanation` side).
  Returns: Wrapped multi-line string, or "—" when empty.

labelText(base, o, p, onLabel, verbose)
  Label text: base only, base + full verbose breakdown, or base + compact "B (80)"
grade tag. The host passes its display toggles in.
  Parameters:
    base (string): The signal's base label text.
    o (ScoreOutput): `ScoreOutput` (na → base returned unchanged).
    p (ScoreParams): `ScoreParams` (grouping weights for the verbose breakdown).
    onLabel (bool): Host `i_scoreOnLabel` — master "annotate labels" toggle.
    verbose (bool): Host `i_scoreVerboseLabels` — full breakdown vs compact grade tag.
  Returns: The composed label text.

tooltip(o, p)
  Hover tooltip: full breakdown + F4 detail + F3 strengths / weaknesses.
  Parameters:
    o (ScoreOutput): `ScoreOutput` (na → "").
    p (ScoreParams): The same `ScoreParams` used for the score.
  Returns: The multi-line tooltip string.

alertMsg(base, o, inAlerts, tz)
  Execution-bar alert message (grade / score suffix appended when enabled).
  Parameters:
    base (string): The signal's base alert text.
    o (ScoreOutput): `ScoreOutput` (na → no suffix).
    inAlerts (bool): Host `i_scoreInAlerts` — append the grade suffix.
    tz (string): Host timezone (e.g. `TZ_NY`) for the `HH:mm` stamp.
  Returns: "HH:mm base[ — GRADE …]".

ScoreDetail
  One labeled sub-component readout (F4 detail). Populated by the library, read
  Fields:
    label (series string): Short human tag ("close strength", "POC→VAH", "wk-H", …).
    value (series float): Signed contribution: positive for a positive readout, negative for a deduction.

ScoreInput
  Context for one evaluation — every value is supplied by the host.
  Fields:
    direction (series string): "bull" | "bear" — trade direction.
    entry (series float): Trade entry price (reference for all positional scoring).
    tp1 (series float): First R-multiple target; corridor for Path Obstruction is entry -> tp1, and
    sigOpen (series float): Signal candle open (Signal Quality, computed in-library).
    sigHigh (series float): Signal candle high.
    sigLow (series float): Signal candle low.
    sigClose (series float): Signal candle close.
    orh (series float): Current-session OR high.
    orl (series float): Current-session OR low.
    vah (series float): Current-session value-area high.
    val (series float): Current-session value-area low.
    poc (series float): Current-session point of control.
    pOrh (series float): Previous-session OR high.
    pOrl (series float): Previous-session OR low.
    pVah (series float): Previous-session value-area high.
    pVal (series float): Previous-session value-area low.
    pPoc (series float): Previous-session point of control.
    cVah (series float): 5-OR composite value-area high.
    cPoc (series float): 5-OR composite point of control.
    cVal (series float): 5-OR composite value-area low.
    histPrice (array<float>): Flattened historical level prices (Remaining Room).
    histBaseCost (array<float>): Per-level base cost, index-aligned with `histPrice`.
    histAge (array<float>): Per-level age (1 = newest); sessions for session/composite, weeks for weekly.
    histLabel (array<string>): Per-level short type tag ("ORH", "VAH", "C-POC", "wk-H", …).

ScoreParams
  Tunables — host populates from inputs once per call. Defaults shown are the
  Fields:
    wQuality (series float): Signal-Quality weight (fraction; the six weights are normalized internally).
    wPath (series float): Path-Obstruction weight.
    wComp (series float): Composite-Alignment weight.
    wPrev (series float): Previous-Session weight.
    wCurr (series float): Current-Session weight.
    wRoom (series float): Remaining-Room weight.
    qwClose (series float): Quality sub-weight — close strength.
    qwBody (series float): Quality sub-weight — body dominance.
    bcCPoc (series float): Obstruction baseCost — composite POC.
    bcCVa (series float): Obstruction baseCost — composite VAH / VAL.
    bcPoc (series float): Obstruction baseCost — current POC.
    bcVa (series float): Obstruction baseCost — current VAH / VAL.
    bcOr (series float): Obstruction baseCost — current ORH / ORL.
    bcPPoc (series float): Obstruction baseCost — previous POC.
    bcPVa (series float): Obstruction baseCost — previous VAH / VAL.
    bcPOr (series float): Obstruction baseCost — previous ORH / ORL.
    bcWeek (series float): Room base cost — weekly H / L.
    ageDecayRate (series float): Room age-decay rate in [0,1] (0 = no decay; per-session/week geometric).
    strongCut (series float): explain(): a group is a strength when its score >= strongCut (default 70).
    weakCut (series float): explain(): a group is a weakness when its score < weakCut (default 50).
    threshA (series float): Grade-A threshold (total >= threshA -> "A").
    threshB (series float): Grade-B threshold.
    threshC (series float): Grade-C threshold (below -> "Reject").

ScoreOutput
  Frozen scoring result for one evaluation.
  Fields:
    total (series float): Composite Context Score, 0-100.
    quality (series float): Signal-Quality component, 0-100.
    path (series float): Path-Obstruction component, 0-100.
    comp (series float): Composite-Alignment component, 0-100.
    prev (series float): Previous-Session component, 0-100.
    curr (series float): Current-Session component, 0-100.
    room (series float): Remaining-Room component, 0-100.
    grade (series string): "A" | "B" | "C" | "Reject".
    qDetail (array<ScoreDetail>): Signal-Quality sub-components (close strength, body dominance).
    pDetail (array<ScoreDetail>): Path obstruction contributors ({level tag, -deduction}).
    cDetail (array<ScoreDetail>): Composite-Alignment band readout ({band label, position %}).
    vDetail (array<ScoreDetail>): Previous-Session band readout.
    uDetail (array<ScoreDetail>): Current-Session band readout.
    rDetail (array<ScoreDetail>): Remaining-Room contributors ({level tag, -deduction}).
    currBand (series string): Direction-aware current-session band tag:
    nearestOppDistEntry (series float): Nearest opposing historical level distance from entry, in R
    nearestOppLabel (series string): Tag of that nearest opposing level ("wk-H", "P-ORH", …); na when none.
    bull (series bool): Trade direction (true = long), carried so `explain()` can word its

Explanation
  Plain-language explanation (F3) — ranked strengths and weaknesses.
  Fields:
    strengths (array<string>): Phrases for components/signals scoring above the neutral 50, best first.
    weaknesses (array<string>): Phrases for components/signals scoring below 50, worst first.

Wyłączenie odpowiedzialności

Informacje i publikacje nie stanowią i nie powinny być traktowane jako porady finansowe, inwestycyjne, tradingowe ani jakiekolwiek inne rekomendacje dostarczane lub zatwierdzone przez TradingView. Więcej informacji znajduje się w Warunkach użytkowania.