ContextScore

martinmr777_ · library · 731 行 · 点赞 0 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
 
// @description 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.
library("ContextScore")
 
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Exported types
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// @type        One labeled sub-component readout (F4 detail). Populated by the library, read
//              by the host for the compact/full breakdown surfaces. Exported because it is a
//              field type of the exported `ScoreOutput`.
// @field label Short human tag ("close strength", "POC→VAH", "wk-H", …).
// @field value Signed contribution: positive for a positive readout, negative for a deduction.
export type ScoreDetail
    string label
    float  value
 
// @type            Context for one evaluation — every value is supplied by the host.
// @field direction "bull" | "bear" — trade direction.
// @field entry     Trade entry price (reference for all positional scoring).
// @field tp1       First R-multiple target; corridor for Path Obstruction is entry -> tp1, and
//                  R is derived as |entry - tp1| for the Remaining-Room normalization.
// @field sigOpen   Signal candle open  (Signal Quality, computed in-library).
// @field sigHigh   Signal candle high.
// @field sigLow    Signal candle low.
// @field sigClose  Signal candle close.
// @field orh       Current-session OR high.
// @field orl       Current-session OR low.
// @field vah       Current-session value-area high.
// @field val       Current-session value-area low.
// @field poc       Current-session point of control.
// @field pOrh      Previous-session OR high.
// @field pOrl      Previous-session OR low.
// @field pVah      Previous-session value-area high.
// @field pVal      Previous-session value-area low.
// @field pPoc      Previous-session point of control.
// @field cVah      5-OR composite value-area high.
// @field cPoc      5-OR composite point of control.
// @field cVal      5-OR composite value-area low.
// @field histPrice     Flattened historical level prices (Remaining Room).
// @field histBaseCost  Per-level base cost, index-aligned with `histPrice`.
// @field histAge       Per-level age (1 = newest); sessions for session/composite, weeks for weekly.
// @field histLabel     Per-level short type tag ("ORH", "VAH", "C-POC", "wk-H", …).
export type ScoreInput
    string direction
    float  entry
    float  tp1
    float  sigOpen
    float  sigHigh
    float  sigLow
    float  sigClose
    float  orh
    float  orl
    float  vah
    float  val
    float  poc
    float  pOrh
    float  pOrl
    float  pVah
    float  pVal
    float  pPoc
    float  cVah
    float  cPoc
    float  cVal
    array<float>  histPrice
    array<float>  histBaseCost
    array<float>  histAge
    array<string> histLabel
 
// @type              Tunables — host populates from inputs once per call. Defaults shown are the
//                    plan's starting points; all remain host-tunable.
// @field wQuality    Signal-Quality weight (fraction; the six weights are normalized internally).
// @field wPath       Path-Obstruction weight.
// @field wComp       Composite-Alignment weight.
// @field wPrev       Previous-Session weight.
// @field wCurr       Current-Session weight.
// @field wRoom       Remaining-Room weight.
// @field qwClose     Quality sub-weight — close strength.
// @field qwBody      Quality sub-weight — body dominance.
// @field bcCPoc      Obstruction baseCost — composite POC.
// @field bcCVa       Obstruction baseCost — composite VAH / VAL.
// @field bcPoc       Obstruction baseCost — current POC.
// @field bcVa        Obstruction baseCost — current VAH / VAL.
// @field bcOr        Obstruction baseCost — current ORH / ORL.
// @field bcPPoc      Obstruction baseCost — previous POC.
// @field bcPVa       Obstruction baseCost — previous VAH / VAL.
// @field bcPOr       Obstruction baseCost — previous ORH / ORL.
// @field bcWeek      Room base cost — weekly H / L.
// @field ageDecayRate Room age-decay rate in [0,1] (0 = no decay; per-session/week geometric).
// @field strongCut   explain(): a group is a strength when its score >= strongCut (default 70).
// @field weakCut     explain(): a group is a weakness when its score <  weakCut  (default 50).
// @field threshA     Grade-A threshold (total >= threshA -> "A").
// @field threshB     Grade-B threshold.
// @field threshC     Grade-C threshold (below -> "Reject").
export type ScoreParams
    float wQuality = 0.20
    float wPath    = 0.30
    float wComp    = 0.20
    float wPrev    = 0.15
    float wCurr    = 0.15
    float wRoom    = 0.15
    float qwClose  = 0.7
    float qwBody   = 0.3
    float bcCPoc   = 25.0
    float bcCVa    = 16.0
    float bcPoc    = 20.0
    float bcVa     = 12.0
    float bcOr     = 8.0
    float bcPPoc   = 16.0
    float bcPVa    = 10.0
    float bcPOr    = 6.0
    float bcWeek   = 20.0
    float ageDecayRate = 0.15
    float strongCut = 70.0
    float weakCut   = 50.0
    float threshA  = 85.0
    float threshB  = 70.0
    float threshC  = 60.0
 
// @type          Frozen scoring result for one evaluation.
// @field total   Composite Context Score, 0-100.
// @field quality Signal-Quality component, 0-100.
// @field path    Path-Obstruction component, 0-100.
// @field comp    Composite-Alignment component, 0-100.
// @field prev    Previous-Session component, 0-100.
// @field curr    Current-Session component, 0-100.
// @field room    Remaining-Room component, 0-100.
// @field grade   "A" | "B" | "C" | "Reject".
// @field qDetail Signal-Quality sub-components (close strength, body dominance).
// @field pDetail Path obstruction contributors ({level tag, -deduction}).
// @field cDetail Composite-Alignment band readout ({band label, position %}).
// @field vDetail Previous-Session band readout.
// @field uDetail Current-Session band readout.
// @field rDetail Remaining-Room contributors ({level tag, -deduction}).
// @field currBand           Direction-aware current-session band tag:
//                           "escaping" | "rejected" | "rotational" | "edge".
// @field nearestOppDistEntry Nearest opposing historical level distance from entry, in R
//                           (na when none). Drives the "Historical resistance/support ahead" phrase.
// @field nearestOppLabel     Tag of that nearest opposing level ("wk-H", "P-ORH", …); na when none.
// @field bull                Trade direction (true = long), carried so `explain()` can word its
//                           phrases direction-aware. Every score is already directional; this only
//                           lets the TEXT say so. See the note at the phrase in `explain()`.
export type ScoreOutput
    float  total
    float  quality
    float  path
    float  comp
    float  prev
    float  curr
    float  room
    string grade
    array<ScoreDetail> qDetail
    array<ScoreDetail> pDetail
    array<ScoreDetail> cDetail
    array<ScoreDetail> vDetail
    array<ScoreDetail> uDetail
    array<ScoreDetail> rDetail
    string currBand
    float  nearestOppDistEntry
    string nearestOppLabel
    bool   bull
 
// @type            Plain-language explanation (F3) — ranked strengths and weaknesses.
// @field strengths Phrases for components/signals scoring above the neutral 50, best first.
// @field weaknesses Phrases for components/signals scoring below 50, worst first.
export type Explanation
    array<string> strengths
    array<string> weaknesses
 
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Internal helpers (not exported — reused by `score()`)
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// @function       Path-Obstruction aggregator (Component 2). Starts at a clean 100 and deducts
//                 a proximity-weighted penalty for every valid structural level strictly inside
//                 the entry -> tp1 corridor. `pos` is corridor-relative (self-normalizing) and
//                 `prox` is linear, so a wall at the entry costs full freight while one near TP1
//                 costs ~0. Levels coinciding within one `syminfo.mintick` are de-duplicated,
//                 counting once and keeping the strongest obstacle (its price, cost, and label).
// @param entry    Trade entry.
// @param tp1      First-R target.
// @param prices   Candidate level prices (na entries are ignored).
// @param costs    Per-level baseCost, index-aligned with `prices`.
// @param labels   Per-level short tag, index-aligned with `prices`.
// @returns        [score 0-100 (100 = clean corridor), detail array of {tag, -deduction}].
obstruction(float entry, float tp1, array<float> prices, array<float> costs, array<string> labels) =>
    float corridor = math.abs(tp1 - entry)
    float sc = 100.0
    array<ScoreDetail> detail = array.new<ScoreDetail>()
    if corridor > 0
        float lo = math.min(entry, tp1)
        float hi = math.max(entry, tp1)
        array<float>  accP = array.new<float>()
        array<float>  accC = array.new<float>()
        array<string> accL = array.new<string>()
        int n = array.size(prices)
        for i = 0 to n - 1
            float L = array.get(prices, i)
            float c = array.get(costs, i)
            if not na(L) and L > lo and L < hi
                bool merged = false
                int m = array.size(accP)
                if m > 0
                    for k = 0 to m - 1
                        if math.abs(L - array.get(accP, k)) <= syminfo.mintick
                            if c > array.get(accC, k)   // stronger obstacle wins outright (price + cost + tag)
                                array.set(accC, k, c)
                                array.set(accP, k, L)
                                array.set(accL, k, array.get(labels, i))
                            merged := true
                            break
                if not merged
                    array.push(accP, L)
                    array.push(accC, c)
                    array.push(accL, array.get(labels, i))
        int a = array.size(accP)
        if a > 0
            for k = 0 to a - 1
                float L    = array.get(accP, k)
                float c    = array.get(accC, k)
                float pos  = math.abs(L - entry) / corridor   // 0 at entry -> 1 at TP1
                float prox = 1.0 - pos                         // LINEAR proximity weight
                float ded  = c * prox
                sc := sc - ded
                array.push(detail, ScoreDetail.new(array.get(accL, k), -ded))
    [math.max(0.0, sc), detail]
 
// @function        Unified zone evaluator (Components 3-5) — the single source of truth for
//                  banding (replaces the former zoneScore / zoneDetail / bandOf trio). One
//                  band-location pass yields the zone score, the F4 {band label, position %}
//                  detail, and the raw band index. The entry is the reference; the sorted
//                  `levels` (ascending) define N+1 bands spanning the full 0-100, ordered by
//                  favourability for the direction (bull: higher = better; bear: mirrored).
//                  Interior bands use a LINEAR `frac`; the two open outer bands use a QUADRATIC
//                  ease-out reaching 0/100 exactly one adjacent-band-width beyond the edge. The
//                  score is continuous across every boundary. Detail position is the interior
//                  fraction (0-100) or, in an outer band, the overshoot beyond the edge in
//                  adjacent-band-widths.
// @param direction "bull" | "bear".
// @param entry     Reference price.
// @param levels    Ascending level set (3 for composite -> 4 bands; 5 for session -> 6 bands).
// @param names     Level tags, index-aligned with `levels`.
// @returns         [score 0-100, one-element detail array {band label, position %},
//                  band index in [0, n] (0 = below first level, n = at/above last)].
zoneEval(string direction, float entry, array<float> levels, array<string> names) =>
    int    n = array.size(levels)
    int    k = n + 1                 // band count
    float  w = 100.0 / k             // band width in score space
    float  psc = na                  // ascending "position score" (high price -> high psc)
    string lbl = ""
    float  posPct = na
    int    band = 0
    float  first = array.get(levels, 0)
    float  last  = array.get(levels, n - 1)
    if entry < first
        // Bottom outer band [0, w]: psc falls from w (at edge) to 0, one band-width below.
        band := 0
        float adj = array.get(levels, 1) - first
        float r = adj > 0 ? (first - entry) / adj : 1.0
        float e = 1.0 - math.min(r, 1.0)
        float factor = 1.0 - e * e
        psc := w - w * factor
        lbl := "<" + array.get(names, 0)
        posPct := r * 100.0
    else if entry >= last
        // Top outer band [100-w, 100]: psc rises from 100-w (at edge) to 100, one width above.
        band := n
        float adj = last - array.get(levels, n - 2)
        float r = adj > 0 ? (entry - last) / adj : 1.0
        float e = 1.0 - math.min(r, 1.0)
        float factor = 1.0 - e * e
        psc := (100.0 - w) + w * factor
        lbl := ">" + array.get(names, n - 1)
        posPct := r * 100.0
    else
        // Interior band: right-exclusive [lower, upper); linear within the band.
        int bi = 0
        for i = 0 to n - 2
            if entry >= array.get(levels, i) and entry < array.get(levels, i + 1)
                bi := i
                break
        band := bi + 1
        float lower    = array.get(levels, bi)
        float upper    = array.get(levels, bi + 1)
        float bandLow  = (bi + 1) * w
        float bandHigh = (bi + 2) * w
        float frac = upper > lower ? (entry - lower) / (upper - lower) : 0.0
        psc := bandLow + (bandHigh - bandLow) * frac
        lbl := array.get(names, bi) + "→" + array.get(names, bi + 1)
        posPct := frac * 100.0
    float score = direction == "bull" ? psc : 100.0 - psc
    [score, array.from(ScoreDetail.new(lbl, posPct)), band]
 
// @function        Remaining-Room aggregator (Component 6). Obstruction-shaped but pointed
//                  OUTWARD from TP1: starts at 100 and deducts, for every opposing historical
//                  level at or beyond the target, an age-decayed `exp(-d)` penalty where d is the
//                  distance from TP1 in R-units. As a byproduct it tracks the nearest opposing
//                  level measured from ENTRY (for the "Historical resistance/support ahead" phrase).
// @param bull      Direction flag (true = long).
// @param entry     Trade entry.
// @param tp1       First-R target.
// @param R         Risk unit (|entry - stop| = |entry - tp1|); <=0 disables scoring.
// @param prices    Historical level prices.
// @param costs     Per-level base cost, index-aligned.
// @param ages      Per-level age (1 = newest), index-aligned.
// @param labels    Per-level tag, index-aligned.
// @param ageDecayRate Geometric decay per age unit, [0,1].
// @returns         [score 0-100 (na when no real level examined), nearestOppDistEntry (na if
//                  none), nearestOppLabel (tag of that level), detail {tag, -deduction}].
roomScore(bool bull, float entry, float tp1, float R, array<float> prices,
     array<float> costs, array<float> ages, array<string> labels,
     float ageDecayRate) =>
    float  sc = 100.0
    float  nearestOpp = na
    string nearestOppLabel = na
    int    considered = 0                 // count of real (non-na) levels actually examined
    // Room-deduction detail is aggregated by level tag (first-seen order): parallel arrays of
    // tag, summed deduction, and count → one "N× tag" ScoreDetail per type at the end.
    array<string> aggLbl = array.new<string>()
    array<float>  aggDed = array.new<float>()
    array<int>    aggCnt = array.new<int>()
    int n = R > 0 ? array.size(prices) : 0
    if n > 0
        for i = 0 to n - 1
            float L = array.get(prices, i)
            if not na(L)
                considered := considered + 1
                // Nearest opposing level vs ENTRY (phrase byproduct; keeps its tag).
                bool oppEntry = bull ? L > entry : L < entry
                if oppEntry
                    float dE = math.abs(L - entry) / R
                    if na(nearestOpp) or dE < nearestOpp
                        nearestOpp := dE
                        nearestOppLabel := array.get(labels, i)
                // Room deduction: opposing level AT OR BEYOND TP1 (a wall at the target caps runway).
                bool oppTp1 = bull ? L >= tp1 : L <= tp1
                if oppTp1
                    float d          = math.abs(L - tp1) / R
                    float distFactor = math.exp(-d)
                    float ageFactor  = math.pow(1.0 - ageDecayRate, array.get(ages, i) - 1.0)
                    float ded        = array.get(costs, i) * ageFactor * distFactor
                    sc := sc - ded
                    string lbl = array.get(labels, i)
                    int    k   = -1
                    int    m   = array.size(aggLbl)
                    if m > 0
                        for j = 0 to m - 1
                            if array.get(aggLbl, j) == lbl
                                k := j
                                break
                    if k >= 0
                        array.set(aggDed, k, array.get(aggDed, k) + ded)
                        array.set(aggCnt, k, array.get(aggCnt, k) + 1)
                    else
                        array.push(aggLbl, lbl)
                        array.push(aggDed, ded)
                        array.push(aggCnt, 1)
    array<ScoreDetail> detail = array.new<ScoreDetail>()
    int a = array.size(aggLbl)
    if a > 0
        for j = 0 to a - 1
            int    c    = array.get(aggCnt, j)
            string tag  = c > 1 ? str.tostring(c) + "× " + array.get(aggLbl, j) : array.get(aggLbl, j)
            array.push(detail, ScoreDetail.new(tag, -array.get(aggDed, j)))
    // na when NO real level was examined (empty/all-na history, or R<=0) — the caller then drops
    // Room from the weighted average so it neither inflates nor deflates the total. A meaningful
    // 100 (history exists but nothing opposing beyond TP1) is preserved.
    float room = considered > 0 ? math.max(0.0, sc) : na
    [room, nearestOpp, nearestOppLabel, detail]
 
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Exported scoring functions
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// @function   Computes the composite Context Score for one trade location.
// @param s     Evaluation context (levels, entry, tp1, signal candle OHLC, historical memory).
// @param p     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.
export score(ScoreInput s, ScoreParams p) =>
    bool bull = s.direction == "bull"
 
    // Component 1 — Signal Quality (computed in-library from the signal candle's OHLC).
    float rng = s.sigHigh - s.sigLow
    float cs  = rng > 0 ? (bull ? (s.sigClose - s.sigLow) / rng : (s.sigHigh - s.sigClose) / rng) : 0.0
    float bd  = rng > 0 ? math.abs(s.sigClose - s.sigOpen) / rng : 0.0
    float quality = math.max(0.0, math.min(100.0, 100.0 * (p.qwClose * cs + p.qwBody * bd)))
    array<ScoreDetail> qDetail = array.from(ScoreDetail.new("close strength", cs * p.qwClose * 100.0), ScoreDetail.new("body dominance", bd * p.qwBody * 100.0))
 
    // Component 2 — Path Obstruction over the 13-level set.
    array<float>  obsP = array.from(s.cPoc, s.cVah, s.cVal, s.poc, s.vah, s.val, s.orh, s.orl, s.pPoc, s.pVah, s.pVal, s.pOrh, s.pOrl)
    array<float>  obsC = array.from(p.bcCPoc, p.bcCVa, p.bcCVa, p.bcPoc, p.bcVa, p.bcVa, p.bcOr, p.bcOr, p.bcPPoc, p.bcPVa, p.bcPVa, p.bcPOr, p.bcPOr)
    array<string> obsN = array.from("C-POC", "C-VAH", "C-VAL", "POC", "VAH", "VAL", "ORH", "ORL", "P-POC", "P-VAH", "P-VAL", "P-ORH", "P-ORL")
    [path, pDetail] = obstruction(s.entry, s.tp1, obsP, obsC, obsN)
 
    // Components 3-5 — Zone evaluator (score + F4 detail + band index in one pass per set;
    // level ordering is host-guaranteed). Only curr's band index (cbi) is consumed, for currBand;
    // cBand / pBand are intentionally unused.
    array<float>  compLevels = array.from(s.cVal, s.cPoc, s.cVah)
    array<float>  prevLevels = array.from(s.pOrl, s.pVal, s.pPoc, s.pVah, s.pOrh)
    array<float>  currLevels = array.from(s.orl, s.val, s.poc, s.vah, s.orh)
    array<string> compNames  = array.from("C-VAL", "C-POC", "C-VAH")
    array<string> prevNames  = array.from("P-ORL", "P-VAL", "P-POC", "P-VAH", "P-ORH")
    array<string> currNames  = array.from("ORL", "VAL", "POC", "VAH", "ORH")
    [comp, cDetail, cBand] = zoneEval(s.direction, s.entry, compLevels, compNames)
    [prev, vDetail, pBand] = zoneEval(s.direction, s.entry, prevLevels, prevNames)
    [curr, uDetail, cbi]   = zoneEval(s.direction, s.entry, currLevels, currNames)
 
    // Component 6 — Remaining Room (R = |entry - tp1|, since tp1 = entry ± R).
    float R = math.abs(s.entry - s.tp1)
    [room, nearestOpp, nearestOppLbl, rDetail] = roomScore(bull, s.entry, s.tp1, R, s.histPrice, s.histBaseCost, s.histAge, s.histLabel, p.ageDecayRate)
 
    // Composite — weighted average over the applicable components (normalized by the summed
    // weights). Room is dropped entirely (weight + term = 0) when it returned na — i.e. no
    // historical level was available to assess — so it neither inflates nor deflates the total.
    float wRoomEff = na(room) ? 0.0 : p.wRoom
    float roomTerm = na(room) ? 0.0 : p.wRoom * room
    float wsum  = p.wQuality + p.wPath + p.wComp + p.wPrev + p.wCurr + wRoomEff
    float total = wsum > 0 ? (p.wQuality * quality + p.wPath * path + p.wComp * comp + p.wPrev * prev + p.wCurr * curr + roomTerm) / wsum : 0.0
 
    // Classification.
    string grade = total >= p.threshA ? "A" : total >= p.threshB ? "B" : total >= p.threshC ? "C" : "Reject"
 
    // Current-session band tag (direction-aware) from the curr zoneEval band index
    // (cbi: 0 = below ORL … 5 = at/above ORH). Drives the derived explanation phrases.
    string currBand = bull ? (cbi == 5 ? "escaping" : cbi == 0 ? "rejected" : (cbi == 2 or cbi == 3) ? "rotational" : "edge")
         : (cbi == 0 ? "escaping" : cbi == 5 ? "rejected" : (cbi == 2 or cbi == 3) ? "rotational" : "edge")
 
    ScoreOutput.new(
         total    = total,    quality = quality, path = path,
         comp     = comp,     prev    = prev,    curr = curr,   room = room,
         grade    = grade,
         qDetail  = qDetail,  pDetail = pDetail, cDetail = cDetail,
         vDetail  = vDetail,  uDetail = uDetail, rDetail = rDetail,
         currBand = currBand, nearestOppDistEntry = nearestOpp, nearestOppLabel = nearestOppLbl,
         bull     = bull)
 
// @function   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).
// @param o     A `ScoreOutput` from `score()`.
// @param p     The same `ScoreParams` used for the score (for the grouping weights).
// @returns     `Explanation` with ranked `strengths` and `weaknesses`.
export explain(ScoreOutput o, ScoreParams p) =>
    array<string> strengths  = array.new<string>()
    array<string> weaknesses = array.new<string>()
 
    // Ranking candidates, kept as parallel key/phrase arrays per side.
    array<float>  sKey = array.new<float>()
    array<string> sPhr = array.new<string>()
    array<float>  wKey = array.new<float>()
    array<string> wPhr = array.new<string>()
 
    // A group speaks only outside the neutral zone: strength when score >= p.strongCut, weakness
    // when score < p.weakCut (both host-exposed, constrained so weakCut <= 50 <= strongCut). NEUTRAL
    // (50) is the fixed ranking midpoint — keys are weighted distance from it, so the most impactful
    // item ranks first on each side, and it stays non-negative given the cut ranges.
    float NEUTRAL = 50.0
 
    // Group 1 — Acceptance (weighted mean of the three zone components).
    float accW = p.wComp + p.wCurr + p.wPrev
    float accS = accW > 0 ? (p.wComp * o.comp + p.wCurr * o.curr + p.wPrev * o.prev) / accW : NEUTRAL
    if accS >= p.strongCut
        array.push(sKey, accW * (accS - NEUTRAL))
        array.push(sPhr, "Strong acceptance")
    else if accS < p.weakCut
        array.push(wKey, accW * (NEUTRAL - accS))
        array.push(wPhr, "Poor location")
 
    // Group 2 — Path.
    if o.path >= p.strongCut
        array.push(sKey, p.wPath * (o.path - NEUTRAL))
        array.push(sPhr, "Excellent path")
    else if o.path < p.weakCut
        array.push(wKey, p.wPath * (NEUTRAL - o.path))
        array.push(wPhr, "Obstructed path")
 
    // Group 3 — Room.
    if o.room >= p.strongCut
        array.push(sKey, p.wRoom * (o.room - NEUTRAL))
        array.push(sPhr, "Ample room")
    else if o.room < p.weakCut
        array.push(wKey, p.wRoom * (NEUTRAL - o.room))
        array.push(wPhr, "Capped runway")
 
    // Group 4 — Quality.
    if o.quality >= p.strongCut
        array.push(sKey, p.wQuality * (o.quality - NEUTRAL))
        array.push(sPhr, "Strong signal")
    else if o.quality < p.weakCut
        array.push(wKey, p.wQuality * (NEUTRAL - o.quality))
        array.push(wPhr, "Weak signal")
 
    // Rank each side descending by key, then emit phrases in that order.
    if array.size(sKey) > 0
        array<int> si = array.sort_indices(sKey, order.descending)
        for j = 0 to array.size(si) - 1
            array.push(strengths, array.get(sPhr, array.get(si, j)))
    if array.size(wKey) > 0
        array<int> wi = array.sort_indices(wKey, order.descending)
        for j = 0 to array.size(wi) - 1
            array.push(weaknesses, array.get(wPhr, array.get(wi, j)))
 
    // Derived categorical phrases (appended after the ranked group phrases).
    if o.currBand == "escaping"
        array.push(strengths, "Escaping value")
    if o.currBand == "rotational"
        array.push(weaknesses, "Rotational")
    if o.currBand == "rejected"
        array.push(weaknesses, "Against OR")
    // ⚠️ THE NOUN FLIPS WITH DIRECTION AND MUST STAY THAT WAY. `roomScore` picks this level with
    // `bull ? L > entry : L < entry`, so it always sits AHEAD of the trade — above entry on a long,
    // below it on a short. "resistance" was hardcoded here for both until 2026-08-14, when the client
    // read it on a short and reasonably concluded the directional logic was inverted. It never was:
    // the scores were always directional, only this word was not.
    if not na(o.nearestOppDistEntry) and o.nearestOppDistEntry < 1
        array.push(weaknesses, "Historical " + (o.bull ? "resistance" : "support") + " ahead" + (na(o.nearestOppLabel) ? "" : " (" + o.nearestOppLabel + ")"))
 
    Explanation.new(strengths = strengths, weaknesses = weaknesses)
 
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Presentation layer (exported) — pure formatters over ScoreOutput / ScoreParams. Moved here
// from the host (Milestone 10) to relieve the host's compiled-token budget (CE10117): a library's
// compiled tokens count against its OWN separate budget, so these bodies no longer weigh on the
// host. The host keeps thin wrappers for the many-call-site display functions (labelText / tooltip
// / alertMsg) so its call sites stay unchanged, and calls the pure utilities (detailStr / joinWrap)
// directly as ctx.*.
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// @function     Join a ScoreDetail array into "label val · label val" (values via `fmt`). Empty → "—".
// @param d      Per-component F4 detail array (e.g. `ScoreOutput.qDetail`).
// @param fmt    `str.tostring` number format for each value.
// @returns      Formatted single-line detail string, or "—" when empty.
export detailStr(array<ScoreDetail> d, string fmt) =>
    string _r = ""
    int    _n = array.size(d)
    if _n > 0
        for _i = 0 to _n - 1
            ScoreDetail _e = array.get(d, _i)
            _r := _r + (_i > 0 ? " · " : "") + _e.label + " " + str.tostring(_e.value, fmt)
    _n > 0 ? _r : "—"
 
// @function     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.
// @param a      Strings to join (e.g. an `Explanation` side).
// @returns      Wrapped multi-line string, or "—" when empty.
export joinWrap(array<string> a) =>
    string _r = ""
    int    _n = array.size(a)
    if _n > 0
        for _i = 0 to _n - 1
            _r := _r + (_i > 0 ? (_i % 2 == 0 ? "\n" : ", ") : "") + array.get(a, _i)
    _n > 0 ? _r : "—"
 
// Internal — join a string array with `_sep`; empty → "—". Used by `tooltip()`.
joinStr(array<string> _a, string _sep) =>
    string _r = ""
    int    _n = array.size(_a)
    if _n > 0
        for _i = 0 to _n - 1
            _r := _r + (_i > 0 ? _sep : "") + array.get(_a, _i)
    _n > 0 ? _r : "—"
 
// Internal — the six normalized grouping weights. Extracted 2026-08-12 when the breakdown split into
// a label formatter and a tooltip formatter: both need this arithmetic, and two copies of it would
// eventually disagree about a number that is visibly summed in front of the user.
// Room is dropped from the normalizer when na so the weighted points still sum to total. Reads the
// grouping weights from `p` (stored as fractions; the /100 scale cancels in the ratio).
normWeights(ScoreOutput o, ScoreParams p) =>
    float _ws = p.wQuality + p.wPath + p.wComp + p.wPrev + p.wCurr + (na(o.room) ? 0.0 : p.wRoom)
    [_ws > 0 ? p.wQuality / _ws : 0.0, _ws > 0 ? p.wPath / _ws : 0.0,
     _ws > 0 ? p.wComp    / _ws : 0.0, _ws > 0 ? p.wPrev / _ws : 0.0,
     _ws > 0 ? p.wCurr    / _ws : 0.0, _ws > 0 ? p.wRoom / _ws : 0.0]
 
// Internal — compact detail join for the TOOLTIP: "label:val, label:val".
// detailStr() is exported and its " · label val" shape is what the LABEL uses; this is a separate
// function rather than a parameter on it so no existing consumer's output can shift underneath it.
detailTip(array<ScoreDetail> _d, string _fmt) =>
    string _r = ""
    int    _n = array.size(_d)
    if _n > 0
        for _i = 0 to _n - 1
            ScoreDetail _e = array.get(_d, _i)
            _r := _r + (_i > 0 ? ", " : "") + _e.label + ":" + str.tostring(_e.value, _fmt)
    _n > 0 ? _r : "—"
 
// Internal — multi-line component breakdown (raw → weighted points, summing to total; F4 sub-detail
// per component in brackets).
//
// ⚠️ THIS IS THE LABEL FORMATTER ONLY. Its column padding ("\nQuality ", "\nPath    ") and its
// double space before each bracket exist to align columns in MONOSPACE, which is the label's font
// (see the host's sigLabelFont). The tooltip renders in TradingView's own proportional font, where
// that padding aligns nothing and costs width on every row — so the tooltip has its own formatter,
// breakdownTip(). Do not re-merge them: the two surfaces have opposite constraints, the label being
// width-controlled and clutter-limited while the tooltip is wrapped and height-limited.
breakdown(ScoreOutput o, ScoreParams p) =>
    string _r = ""
    if not na(o)
        [_nq, _np, _nc, _nv, _nu, _nr] = normWeights(o, p)
        // This header KEEPS its decimal, unlike the compact label tag in labelText() — deliberately, and
        // do not "harmonize" the two. The six weighted-point rows below sum to this number in plain sight,
        // so a rounded header would routinely disagree with its own arithmetic by a point or two.
        _r := "Context Score: " + o.grade + " (" + str.tostring(o.total, "#0.0") + ")"
        _r := _r + "\nQuality " + str.tostring(o.quality, "#0") + " -> " + str.tostring(o.quality * _nq, "#0.0") + "  [" + detailStr(o.qDetail, "#0") + "]"
        _r := _r + "\nPath    " + str.tostring(o.path,    "#0") + " -> " + str.tostring(o.path    * _np, "#0.0") + "  [" + detailStr(o.pDetail, "#0") + "]"
        _r := _r + "\nComp    " + str.tostring(o.comp,    "#0") + " -> " + str.tostring(o.comp    * _nc, "#0.0") + "  [" + detailStr(o.cDetail, "#0") + "]"
        _r := _r + "\nPrev    " + str.tostring(o.prev,    "#0") + " -> " + str.tostring(o.prev    * _nv, "#0.0") + "  [" + detailStr(o.vDetail, "#0") + "]"
        _r := _r + "\nCurr    " + str.tostring(o.curr,    "#0") + " -> " + str.tostring(o.curr    * _nu, "#0.0") + "  [" + detailStr(o.uDetail, "#0") + "]"
        _r := _r + "\nRoom    " + (na(o.room) ? "n/a (no history)" : str.tostring(o.room, "#0") + " -> " + str.tostring(o.room * _nr, "#0.0") + "  [" + detailStr(o.rDetail, "#0") + "]")
    _r
 
// Internal — the TOOLTIP's component breakdown. Same numbers as breakdown(), same arithmetic (both
// go through normWeights), one row's worth of text instead of six.
//
// WHY IT IS ONE RUN-ON STRING. TradingView gives no control over tooltip text size or wrap width,
// and force-breaks at roughly 53 characters per row — measured, not assumed. Height is whatever the
// content needs, and once it exceeds the visible chart area the overflow is simply clipped. So the
// only lever is rendered rows, and joining short components lets several share a row instead of
// each claiming one. Padding is dropped for the same reason: it aligned nothing here.
//
// ⚠️ THE SEPARATOR KEEPS ITS SPACES (" · ", not "·"). Force-breaking means a space-less run cannot
// overflow, but it would break mid-value — "strongest:C-PO" / "C(0.61R)". With spaces present the
// renderer prefers whitespace breaks and only force-breaks a token that exceeds a whole row.
// An em dash was considered and rejected: it is one of the widest glyphs available.
//
// Path and Room are the two lines that can still grow without bound — both enumerate level tags,
// one per contributor — so they are where a future overflow will come from. Quality is fixed at two
// sub-components; Comp, Prev and Curr are one band each.
breakdownTip(ScoreOutput o, ScoreParams p) =>
    string _r = ""
    if not na(o)
        [_nq, _np, _nc, _nv, _nu, _nr] = normWeights(o, p)
        _r := "Context Score:" + o.grade + "(" + str.tostring(o.total, "#0.0") + ")"
        _r := _r + " · Quality:" + str.tostring(o.quality, "#0") + "->" + str.tostring(o.quality * _nq, "#0.0") + "[" + detailTip(o.qDetail, "#0") + "]"
        _r := _r + " · Path:"    + str.tostring(o.path,    "#0") + "->" + str.tostring(o.path    * _np, "#0.0") + "[" + detailTip(o.pDetail, "#0") + "]"
        _r := _r + " · Comp:"    + str.tostring(o.comp,    "#0") + "->" + str.tostring(o.comp    * _nc, "#0.0") + "[" + detailTip(o.cDetail, "#0") + "]"
        _r := _r + " · Prev:"    + str.tostring(o.prev,    "#0") + "->" + str.tostring(o.prev    * _nv, "#0.0") + "[" + detailTip(o.vDetail, "#0") + "]"
        _r := _r + " · Curr:"    + str.tostring(o.curr,    "#0") + "->" + str.tostring(o.curr    * _nu, "#0.0") + "[" + detailTip(o.uDetail, "#0") + "]"
        _r := _r + " · Room:"    + (na(o.room) ? "n/a (no history)" : str.tostring(o.room, "#0") + "->" + str.tostring(o.room * _nr, "#0.0") + "[" + detailTip(o.rDetail, "#0") + "]")
    _r
 
// @function      Label text: base only, base + full verbose breakdown, or base + compact "B (80)"
//                grade tag. The host passes its display toggles in.
// @param base    The signal's base label text.
// @param o       `ScoreOutput` (na → base returned unchanged).
// @param p       `ScoreParams` (grouping weights for the verbose breakdown).
// @param onLabel  Host `i_scoreOnLabel` — master "annotate labels" toggle.
// @param verbose  Host `i_scoreVerboseLabels` — full breakdown vs compact grade tag.
// @returns       The composed label text.
export labelText(string base, ScoreOutput o, ScoreParams p, bool onLabel, bool verbose) =>
    string _r = base
    if not na(o) and onLabel
        // THE ONE SURFACE THAT ROUNDS. The compact tag is the always-on-chart reading, and the client
        // asked for a whole number there (2026-08-10) as part of reducing what the labels carry.
        // `o.total` is untouched — this is a display format, not a precision change; every consumer that
        // does arithmetic reads the float. Everywhere else deliberately keeps the decimal: the verbose
        // breakdown (see the note in breakdown() — its header has to agree with the rows beneath it),
        // the tooltip, the host's status panel, and alertMsg(), which is a machine payload for the
        // external execution layer and not a display choice at all.
        _r := base + "\n" + (verbose ? breakdown(o, p) : o.grade + " (" + str.tostring(o.total, "#0") + ")")
    _r
 
// @function   Hover tooltip: full breakdown + F4 detail + F3 strengths / weaknesses.
// @param o    `ScoreOutput` (na → "").
// @param p    The same `ScoreParams` used for the score.
// @returns    The multi-line tooltip string.
export tooltip(ScoreOutput o, ScoreParams p) =>
    string _r = ""
    if not na(o)
        Explanation _ex = explain(o, p)
        // breakdownTip, not breakdown — see its comment for why the tooltip has its own formatter.
        // Strengths/Weaknesses join into the same run rather than taking a row each.
        _r := breakdownTip(o, p) + " · Strengths:" + joinStr(_ex.strengths, ", ") +
             " · Weaknesses:" + joinStr(_ex.weaknesses, ", ")
    _r
 
// @function      Execution-bar alert message (grade / score suffix appended when enabled).
// @param base    The signal's base alert text.
// @param o       `ScoreOutput` (na → no suffix).
// @param inAlerts  Host `i_scoreInAlerts` — append the grade suffix.
// @param tz      Host timezone (e.g. `TZ_NY`) for the `HH:mm` stamp.
// @returns       "HH:mm base[ — GRADE …]".
export alertMsg(string base, ScoreOutput o, bool inAlerts, string tz) =>
    string _sfx = (inAlerts and not na(o)) ? " — GRADE " + o.grade + " (S:" + str.tostring(o.total, "#0.0") + ")" : ""
    str.format_time(time, "HH:mm", tz) + " " + base + _sfx

← 返回列表