TradeMgmt

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

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

Pine Script

//@version=6
 
// @description Trade-management primitives for the opening-range indicator family.
//
//              ⚠️ WHAT IS IN HERE TODAY IS STOP RESOLUTION ONLY — the six functions that turn a
//              stop-mode selection into a stop price and a cascade start index. TRAILING, CASCADE
//              PROGRESSION, POSITION SIZING, THE TP LADDER AND tmBuildTrade ALL REMAIN HOST-SIDE.
//              The name is broader than the contents on purpose: the playbook's "Trade Management
//              externalization" roadmap entry has further slices, and a generic name gives them a
//              home instead of forcing a second library and a rename. The cost of that choice is
//              this paragraph — do not come looking here for a trailing bug.
//
//              Moved out of the host for CE10295: Pine instantiates a host function at every call
//              site, so this tree was counted eight times against the main body (6,784 inlined
//              tokens, measured 2026-08-11). Library code is exempt from that budget entirely.
//              Full record: plans/REFACTOR_trade_management_externalization.md.
library("TradeMgmt", overlay = true)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Hierarchy constants
// ═══════════════════════════════════════════════════════════════════════════════════════════
//
// ⚠️ DUPLICATED FROM THE HOST ON PURPOSE, AND BOTH COPIES MUST AGREE. The host keeps its own
// TM_IDX_* / TM_CASCADE_DONE_* because its cascade walk still needs them; this library cannot read
// them across the boundary. Two invariants make the duplication safe, and BOTH FAIL SILENTLY:
//
//   1. ORDER IS MEANING. IDX_ORH=0 … IDX_ORL=4 is a DESCENDING PRICE hierarchy. The resolvers walk
//      it with `for _k = startIdx to IDX_ORL` (bull: descending price) and `to IDX_ORH` (bear:
//      ascending price). Renumber these and the traversal resolves the wrong level, with no error.
//   2. THE DONE SENTINELS MUST STAY OUTSIDE 0-4. Both compute* functions route the sweep/fallback
//      case by falling past `_ri > IDX_ORH` / `_ri < IDX_ORL` and the `==` test. That only works
//      because -1 and 5 lie outside the hierarchy range. Move either inside it and the fallback
//      cascade scan is silently skipped.
//
// Declared `const` explicitly: a library function may read the library's globals ONLY when they are
// const-qualified.
const int IDX_ORH   = 0
const int IDX_VAH   = 1
const int IDX_POC   = 2
const int IDX_VAL   = 3
const int IDX_ORL   = 4
const int IDX_FIXED = 5  // Fixed Points mode — bypasses the hierarchy
const int IDX_SWEEP = 6  // Sweep Low/High mode — bypasses the hierarchy
 
const int CASCADE_DONE_BULL = -1  // bull cascade cleared all levels
const int CASCADE_DONE_BEAR =  5  // bear cascade cleared all levels
 
// ⚠️ THE STOP-MODE STRINGS (TM_STOP_*) ARE DELIBERATELY ABSENT FROM THIS LIBRARY, AND MUST STAY
// ABSENT. In the host they do double duty: they populate the stop-mode input option lists AND they
// are what tmModeToIndex switches on. Moving that converter here would put the same seven string
// literals in two files, and rewording an option label without updating the copy would make the
// switch fall through to its default (VAL) — a wrong stop, on one signal type, with no compile
// error and no runtime error. So the host resolves the mode to an int and passes THAT; the strings
// cannot cross the boundary because there is nothing here to compare them to.
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Per-bar context
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// @type          Per-bar stop-resolution context: everything this tree used to read from host
//                globals. EVERY FIELD IS CALL-SITE-INVARIANT WITHIN A BAR, which is the whole
//                point — the host builds one of these per bar and hands it to all eight call
//                sites, instead of binding twelve arguments eight times.
//                ⚠️ Build it ONCE PER BAR, never inside the caller's per-signal wrapper: doing
//                the latter relocates the marshalling cost into eight inlined copies and undoes
//                the entire reason this library exists.
// @field entry    Execution-candle open — the trade entry price.
// @field atrBuf   Structural-anchor buffer (raw ATR × the host's ATR multiplier).
// @field fixedPts Host's Fixed Points input, used by FIXED mode and by hybrid.
// @field orh      Opening-range high.
// @field vah      Value-area high.
// @field poc      Point of control.
// @field val      Value-area low.
// @field orl      Opening-range low.
export type StopCtx
    float entry
    float atrBuf
    float fixedPts
    float orh
    float vah
    float poc
    float val
    float orl
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Internal
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// @function  Returns the structural level price for a hierarchy index.
//            Covers indices 0-4 (ORH→ORL). Returns na for FIXED and SWEEP (5-6), which are
//            handled as special cases in the resolvers.
//
//            ⚠️ THE SWITCH AND THE FIVE NAMED FIELDS STAY. Collapsing them into an array<float>
//            indexed by IDX_* looks like a free win — it deletes this body — but it buys the HOST
//            nothing, because library-internal size does not weigh on either host budget, and it
//            would make element order a silent correctness dependency of exactly the kind the
//            constant block above warns about. Library-internal code is not worth optimizing;
//            only the interface is.
//
//            This is the single point of contact with the level prices in the whole tree — the
//            resolvers and the cascade scan reach them only through here. Keep it that way.
levelByIndex(StopCtx c, int idx) =>
    switch idx
        IDX_ORH => c.orh
        IDX_VAH => c.vah
        IDX_POC => c.poc
        IDX_VAL => c.val
        IDX_ORL => c.orl
        =>         na
 
// @function  Unified bull stop resolver.
//
//            Three execution paths based on startIdx:
//
//            FIXED (IDX_FIXED):
//              Not handled here — the caller computes stop = entry − fixedPts − atrBuf directly
//              and must NOT invoke this function for Fixed Points mode.
//
//            SWEEP (IDX_SWEEP):
//              Returns sweepRef − totalBuf when sweepRef is valid (< entry). Falls through to the
//              ultimate failsafe if sweepRef is na.
//
//            Structural (IDX_ORH … IDX_ORL):
//              Descends ORH → VAH → POC → VAL → ORL from startIdx. Each candidate is validated
//              strictly < entry BEFORE any buffer is applied. The first passing candidate yields
//              the stop. If the chain exhausts, falls back to sweepRef, then candleRef, then na.
//
// @param  c          Per-bar context; supplies the entry and the level prices.
// @param  startIdx   IDX_* start of traversal. Must not be IDX_FIXED.
// @param  totalBuf   Buffer to subtract: atrBuf alone, or atrBuf + fixedPts in hybrid mode.
//                    The caller computes it.
// @param  sweepRef   Sweep candle low; na for signal types without a sweep.
// @param  candleRef  Signal candle low; na for signal types that already supply a valid sweepRef
//                    (retest, inflection, AC+Retest).
// @returns           Tuple [stopPrice, resolvedIdx]. Stop strictly below entry, or na when all
//                    fallbacks are exhausted (degenerate edge case). resolvedIdx is the IDX_* of
//                    the structural level the stop landed on, or CASCADE_DONE_BULL (-1) when the
//                    stop used a sweep / candle fallback rather than a structural level.
resolveStopBull(StopCtx c, int startIdx, float totalBuf, float sweepRef, float candleRef) =>
    float _s  = na
    int   _ri = CASCADE_DONE_BULL  // -1: no structural level resolved
    if startIdx == IDX_SWEEP
        // Direct sweep mode — bypass hierarchy entirely
        _s := not na(sweepRef) and sweepRef < c.entry ? sweepRef - totalBuf : na
    else
        // Structural hierarchy: descend from startIdx to IDX_ORL
        for _k = startIdx to IDX_ORL
            float _c = levelByIndex(c, _k)
            if not na(_c) and _c < c.entry  // validate level BEFORE buffer
                _s  := _c - totalBuf
                _ri := _k
                break
        // Fallback 1: sweep extreme (available for retest and inflection only)
        if na(_s) and not na(sweepRef) and sweepRef < c.entry
            _s := sweepRef - totalBuf
    // Failsafe: signal candle extreme (momentum / AC-only; sweepRef = na there)
    // Try sweepRef first in case SWEEP mode returned na (sweepRef >= entry).
    if na(_s) or _s >= c.entry
        float _ref = not na(sweepRef) and sweepRef - totalBuf < c.entry ?
             sweepRef - totalBuf :
             not na(candleRef) and candleRef - totalBuf < c.entry ?
             candleRef - totalBuf :
             na
        _s := _ref
    [_s, _ri]
 
// @function  Unified bear stop resolver. Mirror of resolveStopBull.
//
//            FIXED (IDX_FIXED): not handled here — the caller computes directly.
//
//            SWEEP (IDX_SWEEP): returns sweepRef + totalBuf when valid (> entry).
//
//            Structural: ASCENDS from startIdx toward IDX_ORH (index 0).
//            ORL(4) → VAL(3) → POC(2) → VAH(1) → ORH(0).
//            Each candidate validated strictly > entry before buffer.
//
// @param  c          Per-bar context; supplies the entry and the level prices.
// @param  startIdx   IDX_* start of traversal. Must not be IDX_FIXED.
// @param  totalBuf   Buffer to add; the caller computes it.
// @param  sweepRef   Sweep candle high; na for signal types without a sweep.
// @param  candleRef  Signal candle high; na for retest, inflection, AC+Retest.
// @returns           Tuple [stopPrice, resolvedIdx]. Stop strictly above entry, or na when all
//                    fallbacks are exhausted. resolvedIdx is the IDX_* of the structural level the
//                    stop landed on, or CASCADE_DONE_BEAR (5) for a sweep / candle fallback.
resolveStopBear(StopCtx c, int startIdx, float totalBuf, float sweepRef, float candleRef) =>
    float _s  = na
    int   _ri = CASCADE_DONE_BEAR  // 5: no structural level resolved
    if startIdx == IDX_SWEEP
        _s := not na(sweepRef) and sweepRef > c.entry ? sweepRef + totalBuf : na
    else
        // Structural hierarchy: ascend from startIdx to IDX_ORH (= 0)
        for _k = startIdx to IDX_ORH
            float _c = levelByIndex(c, _k)
            if not na(_c) and _c > c.entry  // validate level BEFORE buffer
                _s  := _c + totalBuf
                _ri := _k
                break
        if na(_s) and not na(sweepRef) and sweepRef > c.entry
            _s := sweepRef + totalBuf
    if na(_s) or _s <= c.entry
        float _ref = not na(sweepRef) and sweepRef + totalBuf > c.entry ?
             sweepRef + totalBuf :
             not na(candleRef) and candleRef + totalBuf > c.entry ?
             candleRef + totalBuf :
             na
        _s := _ref
    [_s, _ri]
 
// @function  Finds the first structural cascade target for a trade whose stop was placed without a
//            hierarchy-resolved level (Fixed Points or Sweep). Scans the hierarchy from the extreme
//            toward the center, returning the lowest structural level (bull) or highest structural
//            level (bear) that lies strictly between stopPrice and the entry.
//
//            The `direction` string is internal to this library — both callers are below and pass a
//            literal — so it carries none of the cross-boundary drift risk that keeps the stop-mode
//            strings host-side.
//
// @param  c          Per-bar context.
// @param  direction  "bull" | "bear"
// @param  stopPrice  The resolved stop price.
// @returns           IDX_* of the first valid cascade target, or CASCADE_DONE_BULL /
//                    CASCADE_DONE_BEAR when none exists.
findFirstCascadeIdx(StopCtx c, string direction, float stopPrice) =>
    int _r = direction == "bull" ? CASCADE_DONE_BULL : CASCADE_DONE_BEAR
    if direction == "bull"
        // Scan lowest-to-highest: ORL(4)→VAL(3)→POC(2)→VAH(1)→ORH(0)
        float _orl = levelByIndex(c, IDX_ORL)
        float _val = levelByIndex(c, IDX_VAL)
        float _poc = levelByIndex(c, IDX_POC)
        float _vah = levelByIndex(c, IDX_VAH)
        float _orh = levelByIndex(c, IDX_ORH)
        if not na(_orl) and _orl > stopPrice and _orl < c.entry
            _r := IDX_ORL
        else if not na(_val) and _val > stopPrice and _val < c.entry
            _r := IDX_VAL
        else if not na(_poc) and _poc > stopPrice and _poc < c.entry
            _r := IDX_POC
        else if not na(_vah) and _vah > stopPrice and _vah < c.entry
            _r := IDX_VAH
        else if not na(_orh) and _orh > stopPrice and _orh < c.entry
            _r := IDX_ORH
    else
        // Scan highest-to-lowest: ORH(0)→VAH(1)→POC(2)→VAL(3)→ORL(4)
        float _orh = levelByIndex(c, IDX_ORH)
        float _vah = levelByIndex(c, IDX_VAH)
        float _poc = levelByIndex(c, IDX_POC)
        float _val = levelByIndex(c, IDX_VAL)
        float _orl = levelByIndex(c, IDX_ORL)
        if not na(_orh) and _orh < stopPrice and _orh > c.entry
            _r := IDX_ORH
        else if not na(_vah) and _vah < stopPrice and _vah > c.entry
            _r := IDX_VAH
        else if not na(_poc) and _poc < stopPrice and _poc > c.entry
            _r := IDX_POC
        else if not na(_val) and _val < stopPrice and _val > c.entry
            _r := IDX_VAL
        else if not na(_orl) and _orl < stopPrice and _orl > c.entry
            _r := IDX_ORL
    _r
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Exported
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// @function  Resolve the bull stop and its cascade start index. Resolves the effective buffer
//            (accounting for hybrid and the Fixed Points interaction), then delegates to
//            resolveStopBull or computes the Fixed Points stop inline.
//
//            ⚠️ Hybrid is silently ignored when Fixed Points mode is selected — preserved
//            behavior, not an oversight: the fixed offset is already the whole stop there.
//
// @param  c          Per-bar context, built once per bar by the host.
// @param  startIdx   IDX_* resolved from the host's stop-mode input. The host owns that
//                    conversion; see the note on TM_STOP_* above.
// @param  hybrid     True when the hybrid checkbox for this signal type is on.
// @param  sweepRef   Sweep low for the signal; na when not applicable.
// @param  candleRef  Signal candle low; na when sweepRef already covers it.
// @returns           Tuple [stopPrice, cascadeStartIdx]. Stop price, or na (degenerate edge case).
//                    cascadeStartIdx is the first cascade target index — one level above the
//                    resolved structural stop, or the first structural level above a Fixed/Sweep
//                    stop.
export computeStopBull(StopCtx c, int startIdx, bool hybrid, float sweepRef, float candleRef) =>
    bool  _isFix  = startIdx == IDX_FIXED
    float _totBuf = c.atrBuf + (hybrid ? c.fixedPts : 0.0)
    float _stop   = na
    int   _ci     = CASCADE_DONE_BULL
 
    if _isFix
        _stop := c.entry - c.fixedPts - c.atrBuf
        _ci   := findFirstCascadeIdx(c, "bull", _stop)
    else
        [_s, _ri] = resolveStopBull(c, startIdx, _totBuf, sweepRef, candleRef)
        _stop := _s
        _ci := _ri > IDX_ORH ? _ri - 1                        // structural: next level up
             : _ri == IDX_ORH ? CASCADE_DONE_BULL             // stop at ORH → exhausted
             : findFirstCascadeIdx(c, "bull", _stop)          // sweep/fallback: scan
    [_stop, _ci]
 
// @function  Resolve the bear stop and its cascade start index. Mirror of computeStopBull.
//
// @param  c          Per-bar context, built once per bar by the host.
// @param  startIdx   IDX_* resolved from the host's stop-mode input.
// @param  hybrid     True when the hybrid checkbox for this signal type is on.
// @param  sweepRef   Sweep high for the signal; na when not applicable.
// @param  candleRef  Signal candle high; na when sweepRef already covers it.
// @returns           Tuple [stopPrice, cascadeStartIdx].
export computeStopBear(StopCtx c, int startIdx, bool hybrid, float sweepRef, float candleRef) =>
    bool  _isFix  = startIdx == IDX_FIXED
    float _totBuf = c.atrBuf + (hybrid ? c.fixedPts : 0.0)
    float _stop   = na
    int   _ci     = CASCADE_DONE_BEAR
 
    if _isFix
        _stop := c.entry + c.fixedPts + c.atrBuf
        _ci   := findFirstCascadeIdx(c, "bear", _stop)
    else
        [_s, _ri] = resolveStopBear(c, startIdx, _totBuf, sweepRef, candleRef)
        _stop := _s
        _ci := _ri < IDX_ORL ? _ri + 1                        // structural: next level down
             : _ri == IDX_ORL ? CASCADE_DONE_BEAR             // stop at ORL → exhausted
             : findFirstCascadeIdx(c, "bear", _stop)          // sweep/fallback: scan
    [_stop, _ci]

← 返回列表