Public_Library_Divergences

SimpleCryptoLife · library · 740 行 · 点赞 85 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © SimpleCryptoLife
//@version=6
 
// @description Detects regular and hidden divergences and directional convergences from momentum pivots, with sampled price endpoints and continuous strength scores.
library(title="Public_Library_Divergences", overlay=false)
 
import SimpleCryptoLife/MomentumResets/3 as MR
 
//#region 🟢🟢🟢🟢🟢🟢 PAIRING TYPES 🟢🟢🟢🟢🟢🟢
 
// @enum Price/momentum classification. Returned signals never contain none.
export enum DivergenceKind
    none = "None"                   // Internal: no qualifying pattern. Excluded from returned results.
    bullishRegular = "Bull regular" // Lower/equal price low with higher/equal momentum low; at least one changes.
    bearishRegular = "Bear regular" // Higher/equal price high with lower/equal momentum high; at least one changes.
    bullishHidden = "Bull hidden"   // Strictly higher price low with strictly lower momentum low.
    bearishHidden = "Bear hidden"   // Strictly lower price high with strictly higher momentum high.
 
    bullishConvergence = "Bull convergence" // Strictly higher price and momentum lows.
    bearishConvergence = "Bear convergence" // Strictly lower price and momentum highs.
 
// @enum Units used for all four shoulder settings.
export enum ShoulderMode
    absolute = "Absolute"  // Shoulders are distances in momentum units.
    percentOfRange = "Percent Of Range"  // Shoulders are percentages of the shared momentum range.
 
// @enum Price series sampled over each qualifying pivot's shoulder interval.
export enum PriceReference
    bodyEdge = "Body Edge"  // Directional open/close edge.
    closePrice = "Close"   // Closing price for both directions.
    wick = "Wick"          // Low for lows, high for highs.
 
//  One bar in the current execution context. The caller supplies current OHLC and identity.
// @type Current candle data supplied by the caller.
// @field open Opening price.
// @field high Highest price.
// @field low Lowest price.
// @field close Current closing price.
// @field time Candle opening time in UNIX milliseconds.
// @field barIndex Current execution bar index.
export type o_barData
    float open
    float high
    float low
    float close
    int time
    int barIndex
 
//  A momentum turn need not coincide with the price extreme. Keep both locations so the caller can draw either leg.
//  The same momentum pivot may have different sampled prices in its first and second roles.
// @type One endpoint with separate momentum and price locations.
// @field momentumValue Value at the momentum extreme.
// @field momentumBarIndex Actual bar of the momentum extreme.
// @field priceValue Selected price extreme over this role's shoulder interval.
// @field priceBarIndex Actual bar of the selected price.
export type o_endpoint
    float momentumValue
    int momentumBarIndex
    float priceValue
    int priceBarIndex
 
//  Returned only for classified patterns. Strength can be unavailable during range warmup.
// @type One classified result. Endpoint objects are detached from internal state.
// @field kind Regular, hidden or convergence direction.
// @field first First endpoint.
// @field second Second endpoint.
// @field strength Weighted percent of reference range per bar; na when the basis is unavailable.
export type o_divergence
    DivergenceKind kind
    o_endpoint first
    o_endpoint second
    float strength
 
//  Freeze the measuring scale when the second role confirms. A delayed first qualification must not change the score.
type o_strengthBasis
    float priceRange
    float momentumRange
    int confirmationBarIndex
 
//  This price belongs to one role-qualified event. It is frozen on that event's confirmation bar.
type o_priceEndpoint
    bool valid = false
    float value
    int priceBarIndex
    o_strengthBasis strengthBasis
 
//  A bounded history of the chosen reference; it is independent of pivot and drawing retention.
type o_priceBar
    int barIndex
    int barTime
    float lowReference
    float highReference
 
//  Sampling and classification accompany the momentum pair; neither decides which momentum pivots pair.
type o_pivotPair
    MR.Signal direction
    MR.o_pivotEvent firstPivot
    MR.o_pivotEvent secondPivot
    o_priceEndpoint firstPrice
    o_priceEndpoint secondPrice
 
//  One pivot can qualify for either role or both. Its actual bar is its identity within this side.
//  For example, low 120 can arrive as a second at 125 and as a first at 128; both update one record.
type o_qualifiedPivot
    int pivotBarIndex
    MR.o_pivotEvent firstEvent
    MR.o_pivotEvent secondEvent
    o_priceEndpoint firstPrice
    o_priceEndpoint secondPrice
 
//#endregion PAIRING TYPES
 
//#region 🔵🔵🔵🔵🔵🔵 PAIRING STATE AND HELPERS 🔵🔵🔵🔵🔵🔵
 
//  Each side owns an ordered collection of qualifications, independent of its drawings.
//  Completing A-B removes A and everything before B. B stays eligible for its own first-role test.
//  Each imported stream advances in pivot order; an older qualification cannot arrive after a newer one in that stream.
type o_pairingTrack
    MR.Signal direction
    array<o_qualifiedPivot> a_pivots
    MR.o_pivotEvent firstPivot
    o_priceEndpoint firstPrice
    int minimumFirstBarIndex = 0
    int latestFirstBarIndex
    int latestSecondBarIndex
    int lastProcessedBarIndex
 
//  The second detector runs continuously. Once its current extreme qualifies as a
//  first, keep its incoming second candidacy until confirmation or a new left shoulder.
//  Multiplying lows by -1 lets both directions use the same rising-extreme logic. Returned values keep their original sign.
type o_secondSearch
    MR.Signal direction
    bool tracking = false
    float reference
    float extreme
    int extremeBarIndex
    float savedLeft
    float savedRight
    MR.o_pivotEvent pendingFirst
    float turnReference
    int lastProcessedBarIndex
 
//  State and the latest 201 momentum values are supplied by the caller.
//  A first qualification alone does not reset anything. A later turn must meet the
//  live second left shoulder before it replaces the unfinished second candidate.
//  Return that first's bar with the replacement so pairing retires its incoming setup.
method m_findSecond(o_secondSearch _o_search, float _value, float _left, float _right, MR.o_pivotEvent _o_first, array<float> _a_history, int _barIndex) =>
    MR.o_pivotEvent _o_second = na
    int _replacementFirstBar = na
    //  Ordinary rollback restores this state before each realtime update. This is a duplicate-call guard, not a close gate.
    if (na(_o_search.lastProcessedBarIndex) or _barIndex > _o_search.lastProcessedBarIndex)
        _o_search.lastProcessedBarIndex := _barIndex
        float _sign = _o_search.direction == MR.Signal.bearish ? 1.0 : -1.0
        float _signedValue = _value * _sign
        bool _ready = not na(_value) and not na(_left) and _left > 0 and not na(_right) and _right > 0
        if not _o_search.tracking
            if not _ready
                _o_search.reference := na
            else
                _o_search.reference := na(_o_search.reference) ? _signedValue : math.min(_o_search.reference, _signedValue)
                if _signedValue >= _o_search.reference + _left
                    _o_search.tracking := true
                    _o_search.extreme := _signedValue
                    _o_search.extremeBarIndex := _barIndex
                    _o_search.savedLeft := _left
                    _o_search.savedRight := _right
        else if not na(_value)
            bool _newTurn = false
            if not na(_o_search.pendingFirst)
                _o_search.turnReference := math.min(_o_search.turnReference, _signedValue)
                _newTurn := _ready and _signedValue >= _o_search.turnReference + _left
            if _newTurn
                //  The previous extreme becomes the first of this new setup. Its
                //  unfinished second role is cancelled, not emitted or backdated.
                _replacementFirstBar := _o_search.pendingFirst.pivotBarIndex
                _o_search.extreme := _signedValue
                _o_search.extremeBarIndex := _barIndex
                _o_search.savedLeft := _left
                _o_search.savedRight := _right
                _o_search.pendingFirst := na
                _o_search.turnReference := na
            else
                if _signedValue > _o_search.extreme
                    _o_search.extreme := _signedValue
                    _o_search.extremeBarIndex := _barIndex
                    //  If live shoulders prevented replacement, this is now a different
                    //  pivot. It must earn its own first qualification before replacement.
                    _o_search.pendingFirst := na
                    _o_search.turnReference := na
                if _o_search.extreme - _signedValue >= _o_search.savedRight
                    int _startBarIndex = na
                    int _offset = _barIndex - _o_search.extremeBarIndex + 1
                    while _offset < _a_history.size() and na(_startBarIndex)
                        float _candidate = _a_history.get(index=_a_history.size() - 1 - _offset) * _sign
                        if not na(_candidate) and _candidate <= _o_search.extreme - _o_search.savedLeft
                            _startBarIndex := _barIndex - _offset
                        _offset += 1
                    _o_second := MR.o_pivotEvent.new(
                      direction=_o_search.direction,
                      pivotValue=_o_search.extreme * _sign,
                      pivotBarIndex=_o_search.extremeBarIndex,
                      confirmationBarIndex=_barIndex,
                      startBarIndex=_startBarIndex)
                    _o_search.tracking := false
                    _o_search.reference := _ready ? _signedValue : na
                    _o_search.pendingFirst := na
                    _o_search.turnReference := na
        //  Match by actual pivot identity. A first on another pivot or direction
        //  cannot give this candidate permission to start a new pairing cycle.
        if _o_search.tracking and not na(_o_first) and _o_first.direction == _o_search.direction and _o_first.confirmationBarIndex == _barIndex and _o_first.pivotBarIndex == _o_search.extremeBarIndex
            _o_search.pendingFirst := _o_first
            _o_search.turnReference := _signedValue
    [_o_second, _replacementFirstBar]
 
//  The MomentumResets v3 start search is bounded at 200 bars from confirmation. Retain 201 bars,
//  including the current bar, so every recoverable start has its complete price interval available.
//  This storage bound does not choose the scan interval. The event's two shoulders do that.
f_samplePrice(MR.o_pivotEvent _o_event, array<o_priceBar> _a_history) =>
    o_priceEndpoint _o_price = na
    if not na(_o_event)
        _o_price := o_priceEndpoint.new()
        if not na(_o_event.startBarIndex)
            int _startIndex = _o_event.startBarIndex
            int _endIndex = _o_event.confirmationBarIndex
            bool _validInterval = not na(_endIndex) and _startIndex >= 0 and _startIndex <= _o_event.pivotBarIndex and _o_event.pivotBarIndex <= _endIndex
            if _validInterval
                int _count = 0
                int _expectedIndex = _startIndex
                bool _complete = true
                for _o_bar in _a_history
                    if _o_bar.barIndex >= _startIndex and _o_bar.barIndex <= _endIndex
                        float _candidate = _o_event.direction == MR.Signal.bullish ? _o_bar.lowReference : _o_event.direction == MR.Signal.bearish ? _o_bar.highReference : na
                        //  A gap would let us mistake a partial interval for its true extreme. Reject the whole sample instead.
                        _complete := _complete and _o_bar.barIndex == _expectedIndex and not na(_candidate) and not na(_o_bar.barTime)
                        _expectedIndex := _o_bar.barIndex + 1
                        _count += 1
                        //  Strict comparison keeps the earliest occurrence when extrema tie.
                        bool _moreExtreme = not na(_candidate) and (na(_o_price.value) or (_o_event.direction == MR.Signal.bullish and _candidate < _o_price.value) or (_o_event.direction == MR.Signal.bearish and _candidate > _o_price.value))
                        if not na(_candidate) and _moreExtreme
                            _o_price.value := _candidate
                            _o_price.priceBarIndex := _o_bar.barIndex
                _o_price.valid := _complete and _count == _endIndex - _startIndex + 1 and not na(_o_price.value)
                if not _o_price.valid
                    _o_price.value := na
                    _o_price.priceBarIndex := na
    _o_price
 
f_isCurrentEvent(MR.o_pivotEvent _o_event, MR.Signal _direction, int _barIndex) =>
    not na(_o_event) and _o_event.direction == _direction and
      not na(_o_event.pivotValue) and not na(_o_event.pivotBarIndex) and
      _o_event.pivotBarIndex >= 0 and _o_event.pivotBarIndex <= _barIndex and
      _o_event.confirmationBarIndex == _barIndex
 
//  Merge by pivot bar, not arrival bar: the two roles can confirm at different times.
//  Records stay in pivot order so an early second qualification can wait for its first.
method m_recordQualification(o_pairingTrack _o_track, MR.o_pivotEvent _o_event, o_priceEndpoint _o_price, bool _firstRole) =>
    int _pivotBarIndex = _o_event.pivotBarIndex
    int _latestBarIndex = _firstRole ? _o_track.latestFirstBarIndex : _o_track.latestSecondBarIndex
    bool _isNewEvent = na(_latestBarIndex) or _pivotBarIndex > _latestBarIndex
    if _isNewEvent
        if _firstRole
            _o_track.latestFirstBarIndex := _pivotBarIndex
        else
            _o_track.latestSecondBarIndex := _pivotBarIndex
        if _pivotBarIndex >= _o_track.minimumFirstBarIndex
            int _insertionIndex = 0
            while _insertionIndex < _o_track.a_pivots.size() and _o_track.a_pivots.get(index=_insertionIndex).pivotBarIndex < _pivotBarIndex
                _insertionIndex += 1
            o_qualifiedPivot _o_pivot = na
            if _insertionIndex < _o_track.a_pivots.size() and _o_track.a_pivots.get(index=_insertionIndex).pivotBarIndex == _pivotBarIndex
                _o_pivot := _o_track.a_pivots.get(index=_insertionIndex)
            else
                //  Never silently drop an unresolved qualification to fit a storage limit.
                if _o_track.a_pivots.size() >= 4096
                    runtime.error("Divergences: 4096 unresolved pivots on one side. Reduce the mismatch between first- and second-pivot settings.")
                _o_pivot := o_qualifiedPivot.new(pivotBarIndex=_pivotBarIndex)
                _o_track.a_pivots.insert(index=_insertionIndex, value=_o_pivot)
            if _firstRole
                _o_pivot.firstEvent := _o_event
                _o_pivot.firstPrice := _o_price
            else
                _o_pivot.secondEvent := _o_event
                _o_pivot.secondPrice := _o_price
    _isNewEvent
 
//  Only discard pivots the rolling track has passed. Elapsed time alone cannot rule out a late confirmation.
method m_trimPivots(o_pairingTrack _o_track) =>
    while _o_track.a_pivots.size() > 0 and _o_track.a_pivots.first().pivotBarIndex < _o_track.minimumFirstBarIndex
        _o_track.a_pivots.shift()
    _o_track.a_pivots.size()
 
//  Select the next momentum pair before asking whether price diverges. Otherwise an unclassified B could be
//  skipped and A joined to C, which would quietly turn rolling pairs into retained-anchor comparisons.
method m_step(o_pairingTrack _o_track, MR.o_pivotEvent _o_first, MR.o_pivotEvent _o_second, o_priceEndpoint _o_firstPrice, o_priceEndpoint _o_secondPrice, int _windowBars, int _barIndex, int _replacementFirstBar = na) =>
    array<o_pivotPair> _a_pairs = array.new<o_pivotPair>()
    bool _hasFirst = f_isCurrentEvent(_o_event=_o_first, _direction=_o_track.direction, _barIndex=_barIndex)
    bool _hasSecond = f_isCurrentEvent(_o_event=_o_second, _direction=_o_track.direction, _barIndex=_barIndex)
 
    if (na(_o_track.lastProcessedBarIndex) or _barIndex > _o_track.lastProcessedBarIndex)
        _o_track.lastProcessedBarIndex := _barIndex
        //  A distinct next turn has cancelled an unfinished second role. Move to
        //  that pivot's already-qualified first role before considering new events.
        if not na(_replacementFirstBar) and _replacementFirstBar >= _o_track.minimumFirstBarIndex
            if not na(_o_track.firstPivot) and _o_track.firstPivot.pivotBarIndex < _replacementFirstBar
                _o_track.firstPivot := na
                _o_track.firstPrice := na
            _o_track.minimumFirstBarIndex := _replacementFirstBar
            _o_track.m_trimPivots()
        //  Store both roles before pairing. Confirmation order never changes the identity of a pivot.
        if _hasFirst
            _o_track.m_recordQualification(_o_event=_o_first, _o_price=_o_firstPrice, _firstRole=true)
        if _hasSecond
            _o_track.m_recordQualification(_o_event=_o_second, _o_price=_o_secondPrice, _firstRole=false)
 
        bool _canAdvance = _hasFirst or _hasSecond or not na(_replacementFirstBar)
        //  One new qualification can resolve several waiting pairs. Each pass retires an earlier first or stops.
        while _canAdvance
            _canAdvance := false
            if na(_o_track.firstPivot)
                for _o_pivot in _o_track.a_pivots
                    if not na(_o_pivot.firstEvent)
                        _o_track.firstPivot := _o_pivot.firstEvent
                        _o_track.firstPrice := _o_pivot.firstPrice
                        _o_track.minimumFirstBarIndex := _o_pivot.pivotBarIndex
                        break
                _o_track.m_trimPivots()
 
            if not na(_o_track.firstPivot)
                MR.o_pivotEvent _o_nextSecond = na
                o_priceEndpoint _o_nextSecondPrice = na
                for _o_pivot in _o_track.a_pivots
                    if _o_pivot.pivotBarIndex > _o_track.firstPivot.pivotBarIndex and not na(_o_pivot.secondEvent)
                        _o_nextSecond := _o_pivot.secondEvent
                        _o_nextSecondPrice := _o_pivot.secondPrice
                        break
                if not na(_o_nextSecond)
                    //  With a window of 21, a first at 100 can pair through 121, even if that second confirms at 125.
                    int _deadlineBarIndex = _o_track.firstPivot.pivotBarIndex + _windowBars
                    if _o_nextSecond.pivotBarIndex <= _deadlineBarIndex
                        _a_pairs.push(value=o_pivotPair.new(
                          direction=_o_track.direction,
                          firstPivot=_o_track.firstPivot,
                          secondPivot=_o_nextSecond,
                          firstPrice=_o_track.firstPrice,
                          secondPrice=_o_nextSecondPrice))
                        //  Geometry completes this pair regardless of the later price classification.
                        _o_track.minimumFirstBarIndex := _o_nextSecond.pivotBarIndex
                    else
                        //  The second stream has passed this window. Keep later first qualifications for the next setup.
                        _o_track.minimumFirstBarIndex := _o_track.firstPivot.pivotBarIndex + 1
                    _o_track.firstPivot := na
                    _o_track.firstPrice := na
                    _o_track.m_trimPivots()
                    _canAdvance := true
 
    _a_pairs
 
//#endregion PAIRING STATE AND HELPERS
 
//#region 🟢🟢🟢🟢🟢🟢 PAIRING CALCULATIONS 🟢🟢🟢🟢🟢🟢
 
// @function Uses an explicit positive window, or selects the next strictly greater Fibonacci number above the oscillator period.
// @param _windowBars Positive explicit window; zero selects automatic resolution.
// @param _oscPeriod Positive oscillator period required when the explicit window is zero.
// @returns Window length in bars. Invalid window configuration stops the caller.
f_resolveWindowBars(simple int _windowBars, simple int _oscPeriod) =>
    if na(_windowBars) or _windowBars < 0
        runtime.error("Divergences.f_resolveWindowBars(): Window Bars must be zero or positive.")
    int _resolvedWindowBars = _windowBars
    if _windowBars == 0
        if na(_oscPeriod) or _oscPeriod < 1 or _oscPeriod > 1000000
            runtime.error("Divergences.f_resolveWindowBars(): Auto mode requires an oscillator period from 1 to 1,000,000.")
        int _previousFib = 1
        int _currentFib = 2
        while _currentFib <= _oscPeriod
            int _nextFib = _previousFib + _currentFib
            _previousFib := _currentFib
            _currentFib := _nextFib
        _resolvedWindowBars := _currentFib
    _resolvedWindowBars
 
// @function Classifies a completed momentum pair without changing it or either endpoint.
// @param _o_pair Pair with frozen, role-specific price endpoints.
// @returns Regular, hidden or convergence direction, or none for unmatched geometry, missing data or unordered price candles.
//  One flat leg still shows regular divergence if the other moves against it. Two flat legs tell us nothing.
//  Hidden divergence and convergence require a strict move in both legs.
//  Compare stored values directly. No display rounding, tolerance or strength threshold is applied.
f_classifyPair(o_pivotPair _o_pair) =>
    DivergenceKind _kind = DivergenceKind.none
    bool _hasEndpoints = not na(_o_pair) and not na(_o_pair.firstPivot) and not na(_o_pair.secondPivot) and not na(_o_pair.firstPrice) and not na(_o_pair.secondPrice)
    if _hasEndpoints
        o_priceEndpoint _o_firstPrice = _o_pair.firstPrice
        o_priceEndpoint _o_secondPrice = _o_pair.secondPrice
        float _firstMomentum = _o_pair.firstPivot.pivotValue
        float _secondMomentum = _o_pair.secondPivot.pivotValue
        bool _hasValues = _o_firstPrice.valid and _o_secondPrice.valid and not na(_o_firstPrice.value) and not na(_o_secondPrice.value) and not na(_firstMomentum) and not na(_secondMomentum)
        //  Overlapping shoulder intervals can select the same candle, or reverse the price endpoints. Neither makes a usable pair.
        bool _orderedPrices = not na(_o_firstPrice.priceBarIndex) and not na(_o_secondPrice.priceBarIndex) and _o_secondPrice.priceBarIndex > _o_firstPrice.priceBarIndex
        if _hasValues and _orderedPrices
            float _firstPrice = _o_firstPrice.value
            float _secondPrice = _o_secondPrice.value
            bool _hasChange = _secondPrice != _firstPrice or _secondMomentum != _firstMomentum
            if _o_pair.direction == MR.Signal.bullish
                if _secondPrice <= _firstPrice and _secondMomentum >= _firstMomentum and _hasChange
                    _kind := DivergenceKind.bullishRegular
                else if _secondPrice > _firstPrice and _secondMomentum < _firstMomentum
                    _kind := DivergenceKind.bullishHidden
                else if _secondPrice > _firstPrice and _secondMomentum > _firstMomentum
                    _kind := DivergenceKind.bullishConvergence
            else if _o_pair.direction == MR.Signal.bearish
                if _secondPrice >= _firstPrice and _secondMomentum <= _firstMomentum and _hasChange
                    _kind := DivergenceKind.bearishRegular
                else if _secondPrice < _firstPrice and _secondMomentum > _firstMomentum
                    _kind := DivergenceKind.bearishHidden
                else if _secondPrice < _firstPrice and _secondMomentum < _firstMomentum
                    _kind := DivergenceKind.bearishConvergence
    _kind
 
// @function Measures the source's characteristic range using the same basis as MomentumResets.
// @param _source Selected price reference or momentum series, updated on every bar.
// @returns Smoothed upper percentile minus smoothed lower percentile, without clipping.
//  Not loop-safe: percentile and RMA history belong to each written call. Call once per source on every update.
f_smoothedPercentileRange(float _source, simple int _length, simple int _smoothingLength, simple float _lowerPercentile, simple float _upperPercentile) =>
    if _length < 1 or _smoothingLength < 1 or _lowerPercentile < 0 or _upperPercentile > 100 or _lowerPercentile >= _upperPercentile
        runtime.error("Divergences: range lengths must be positive and percentiles ordered within 0 to 100.")
    float _lowerBoundary = ta.percentile_linear_interpolation(source=_source, length=_length, percentage=_lowerPercentile)
    float _upperBoundary = ta.percentile_linear_interpolation(source=_source, length=_length, percentage=_upperPercentile)
    float _smoothedLowerBoundary = ta.rma(source=_lowerBoundary, length=_smoothingLength)
    float _smoothedUpperBoundary = ta.rma(source=_upperBoundary, length=_smoothingLength)
    _smoothedUpperBoundary - _smoothedLowerBoundary
 
//  Percentage shoulders use the same momentum range as strength. For example, 5% of a range of 40 is a distance of 2.
//  Each detector saves that distance when it arms; a changing range must not move its confirmation target.
f_resolveShoulders(ShoulderMode _mode, float _momentumRange, float _firstLeft, float _firstRight, float _secondLeft, float _secondRight) =>
    if na(_firstLeft) or _firstLeft <= 0 or na(_firstRight) or _firstRight <= 0 or na(_secondLeft) or _secondLeft <= 0 or na(_secondRight) or _secondRight <= 0
        runtime.error("Divergences: shoulder settings must be positive.")
    float _basis = _mode == ShoulderMode.absolute ? 1.0 : not na(_momentumRange) and _momentumRange > 0 ? _momentumRange / 100.0 : na
    [_firstLeft * _basis, _firstRight * _basis, _secondLeft * _basis, _secondRight * _basis]
 
// @function Scores a classified pair from its second role's frozen reference ranges; never changes the pair.
// @param _momentumWeight Momentum's share from zero to one; price receives the remainder.
// @returns Strength in percent of reference range per chart bar, or na when its basis is unavailable.
//  Each duration follows that leg's actual endpoints. Confirmation lag is excluded.
//  Missing/nonpositive ranges leave the score unavailable; classification and pairing remain valid.
f_scorePair(o_pivotPair _o_pair, float _momentumWeight) =>
    float _score = na
    bool _hasEndpoints = not na(_o_pair) and not na(_o_pair.firstPivot) and not na(_o_pair.secondPivot) and not na(_o_pair.firstPrice) and not na(_o_pair.secondPrice)
    if _hasEndpoints
        o_priceEndpoint _o_firstPrice = _o_pair.firstPrice
        o_priceEndpoint _o_secondPrice = _o_pair.secondPrice
        o_strengthBasis _o_basis = _o_secondPrice.strengthBasis
        bool _hasValues = _o_firstPrice.valid and _o_secondPrice.valid and not na(_o_firstPrice.value) and not na(_o_secondPrice.value) and not na(_o_pair.firstPivot.pivotValue) and not na(_o_pair.secondPivot.pivotValue)
        if _hasValues
            int _priceBars = _o_secondPrice.priceBarIndex - _o_firstPrice.priceBarIndex
            int _momentumBars = _o_pair.secondPivot.pivotBarIndex - _o_pair.firstPivot.pivotBarIndex
            bool _orderedEndpoints = not na(_priceBars) and _priceBars > 0 and not na(_momentumBars) and _momentumBars > 0
            bool _validWeight = not na(_momentumWeight) and _momentumWeight >= 0 and _momentumWeight <= 1
            if _orderedEndpoints and _validWeight and not na(_o_basis)
                bool _matchingConfirmation = not na(_o_basis.confirmationBarIndex) and _o_basis.confirmationBarIndex == _o_pair.secondPivot.confirmationBarIndex
                bool _positiveRanges = not na(_o_basis.priceRange) and _o_basis.priceRange > 0 and not na(_o_basis.momentumRange) and _o_basis.momentumRange > 0
                if _matchingConfirmation and _positiveRanges
                    float _priceMagnitude = 100.0 * math.abs(number=_o_secondPrice.value - _o_firstPrice.value) / _o_basis.priceRange
                    float _momentumMagnitude = 100.0 * math.abs(number=_o_pair.secondPivot.pivotValue - _o_pair.firstPivot.pivotValue) / _o_basis.momentumRange
                    //  Price and momentum can span different numbers of bars. Measure each leg at its own speed.
                    float _priceRate = _priceMagnitude / _priceBars
                    float _momentumRate = _momentumMagnitude / _momentumBars
                    _score := _momentumWeight * _momentumRate + (1.0 - _momentumWeight) * _priceRate
    _score
 
//  Copy only the public data into fresh endpoint objects. A caller may keep or edit a result without changing our tracks.
f_appendDivergences(array<o_pivotPair> _a_pairs, array<o_divergence> _a_results, float _momentumWeight) =>
    for _o_pair in _a_pairs
        DivergenceKind _kind = f_classifyPair(_o_pair=_o_pair)
        if _kind != DivergenceKind.none
            o_endpoint _o_first = o_endpoint.new(
              momentumValue=_o_pair.firstPivot.pivotValue,
              momentumBarIndex=_o_pair.firstPivot.pivotBarIndex,
              priceValue=_o_pair.firstPrice.value,
              priceBarIndex=_o_pair.firstPrice.priceBarIndex)
            o_endpoint _o_second = o_endpoint.new(
              momentumValue=_o_pair.secondPivot.pivotValue,
              momentumBarIndex=_o_pair.secondPivot.pivotBarIndex,
              priceValue=_o_pair.secondPrice.value,
              priceBarIndex=_o_pair.secondPrice.priceBarIndex)
            _a_results.push(value=o_divergence.new(
              kind=_kind,
              first=_o_first,
              second=_o_second,
              strength=f_scorePair(_o_pair=_o_pair, _momentumWeight=_momentumWeight)))
    _a_results
 
// @function Returns newly recognised regular, hidden and convergence signals with momentum/price endpoints and strength.
// @param _momentum Momentum series. Bounded and unbounded sources are supported.
// @param _o_barData Current OHLC, opening time and bar index from the same execution context as momentum.
// @param _momentumPeriod Positive source period. Auto window uses the next strictly greater Fibonacci number.
// @param _firstLeftShoulder Movement needed to arm a first pivot, in the selected shoulder units.
// @param _firstRightShoulder Movement away from the extreme needed to confirm a first pivot.
// @param _secondLeftShoulder Movement needed to arm a second pivot, independently of first qualification.
// @param _secondRightShoulder Movement away from the extreme needed to confirm a second pivot.
// @param _windowBars Maximum distance between momentum pivot bars, inclusive. Zero selects the auto window.
// @param _shoulderMode Absolute momentum units or percent of the smoothed momentum range. Distances freeze on arming.
// @param _priceReference Body edge, close or wick, shared by both endpoints. Each role samples its own shoulder interval.
// @param _momentumWeight Momentum's share of strength, from zero to one. Price receives the remainder.
// @param _rangeLength Lookback for source-value percentiles, shared by price and momentum.
// @param _rangeSmoothing RMA length for each percentile boundary before calculating the reference range.
// @param _lowerPercentile Lower boundary from zero to 100, strictly below the upper boundary.
// @param _upperPercentile Upper boundary from zero to 100, strictly above the lower boundary.
// @returns A fresh array, empty when no classified signal exists. Each result contains kind, two endpoints and strength.
//  Strength is a weighted percentage of reference range per bar, using each leg's own duration.
//  It is unbounded and is not a probability. Missing or zero reference ranges leave strength unavailable.
//  Prices are frozen over each role's left-shoulder start through confirmation, inclusive; ties keep the earliest candle.
//  Same-candle or reverse-ordered price endpoints are excluded. Price selection never changes momentum pairing.
//  Call on every execution. Signals appear when both qualifications are known, not on the earlier pivot candle.
//  Open-bar results are provisional; the caller decides when to draw or alert. Several results can arrive together.
//  Not loop-safe or multi-feed-safe: use one stable call site per source in its own execution context.
export getDivergences(float _momentum, o_barData _o_barData, simple int _momentumPeriod, simple float _firstLeftShoulder = 5.0, simple float _firstRightShoulder = 3.0, simple float _secondLeftShoulder = 3.0, simple float _secondRightShoulder = 5.0, simple int _windowBars = 0, simple ShoulderMode _shoulderMode = ShoulderMode.percentOfRange, simple PriceReference _priceReference = PriceReference.bodyEdge, simple float _momentumWeight = 0.70, simple int _rangeLength = 200, simple int _rangeSmoothing = 50, simple float _lowerPercentile = 5.0, simple float _upperPercentile = 95.0) =>
    if na(_o_barData) or na(_o_barData.barIndex) or _o_barData.barIndex < 0 or _o_barData.barIndex != bar_index
        runtime.error("Divergences: bar data must belong to the current execution context.")
    if _momentumPeriod < 1 or _windowBars < 0 or na(_momentumWeight) or _momentumWeight < 0 or _momentumWeight > 1
        runtime.error("Divergences: period must be positive, window nonnegative and momentum weight within zero to one.")
    int _effectiveWindowBars = f_resolveWindowBars(_windowBars=_windowBars, _oscPeriod=_momentumPeriod)
    float _lowPriceReference = switch _priceReference
        PriceReference.bodyEdge => not na(_o_barData.open) and not na(_o_barData.close) ? math.min(_o_barData.open, _o_barData.close) : na
        PriceReference.closePrice => _o_barData.close
        PriceReference.wick => _o_barData.low
    float _highPriceReference = switch _priceReference
        PriceReference.bodyEdge => not na(_o_barData.open) and not na(_o_barData.close) ? math.max(_o_barData.open, _o_barData.close) : na
        PriceReference.closePrice => _o_barData.close
        PriceReference.wick => _o_barData.high
    //  These three written calls need their own history on every update, including bars with no pivot.
    //  Low-side and high-side price ranges follow the same reference that will supply their endpoints.
    float _lowPriceRange = f_smoothedPercentileRange(
      _source=_lowPriceReference,
      _length=_rangeLength,
      _smoothingLength=_rangeSmoothing,
      _lowerPercentile=_lowerPercentile,
      _upperPercentile=_upperPercentile)
    float _highPriceRange = f_smoothedPercentileRange(
      _source=_highPriceReference,
      _length=_rangeLength,
      _smoothingLength=_rangeSmoothing,
      _lowerPercentile=_lowerPercentile,
      _upperPercentile=_upperPercentile)
    float _momentumRange = f_smoothedPercentileRange(
      _source=_momentum,
      _length=_rangeLength,
      _smoothingLength=_rangeSmoothing,
      _lowerPercentile=_lowerPercentile,
      _upperPercentile=_upperPercentile)
    [_firstLeftShoulderResolved, _firstRightShoulderResolved, _secondLeftShoulderResolved, _secondRightShoulderResolved] = f_resolveShoulders(
      _mode=_shoulderMode,
      _momentumRange=_momentumRange,
      _firstLeft=_firstLeftShoulder,
      _firstRight=_firstRightShoulder,
      _secondLeft=_secondLeftShoulder,
      _secondRight=_secondRightShoulder)
 
    //  First detection retains the published MomentumResets behaviour. The local second
    //  search adds cancellation only when a qualified first is followed by a new turn.
    [_o_firstBullish, _o_firstBearish] = MR.getPivotReset(
      _value=_momentum,
      _leftShoulder=_firstLeftShoulderResolved,
      _rightShoulder=_firstRightShoulderResolved)
    var array<float> _a_momentumHistory = array.new<float>()
    _a_momentumHistory.push(value=_momentum)
    while _a_momentumHistory.size() > 201
        _a_momentumHistory.shift()
    var o_secondSearch _o_lowSecondSearch = o_secondSearch.new(direction=MR.Signal.bullish)
    var o_secondSearch _o_highSecondSearch = o_secondSearch.new(direction=MR.Signal.bearish)
    [_o_secondBullish, _bullishReplacementFirstBar] = _o_lowSecondSearch.m_findSecond(
      _value=_momentum,
      _left=_secondLeftShoulderResolved,
      _right=_secondRightShoulderResolved,
      _o_first=_o_firstBullish,
      _a_history=_a_momentumHistory,
      _barIndex=_o_barData.barIndex)
    [_o_secondBearish, _bearishReplacementFirstBar] = _o_highSecondSearch.m_findSecond(
      _value=_momentum,
      _left=_secondLeftShoulderResolved,
      _right=_secondRightShoulderResolved,
      _o_first=_o_firstBearish,
      _a_history=_a_momentumHistory,
      _barIndex=_o_barData.barIndex)
 
    //  Include the current candle in sampling; ordinary state rolls back on each open-bar update.
    var array<o_priceBar> _a_priceHistory = array.new<o_priceBar>()
    o_priceEndpoint _o_firstBullishPrice = na
    o_priceEndpoint _o_firstBearishPrice = na
    o_priceEndpoint _o_secondBullishPrice = na
    o_priceEndpoint _o_secondBearishPrice = na
    _a_priceHistory.push(value=o_priceBar.new(
      barIndex=_o_barData.barIndex,
      barTime=_o_barData.time,
      lowReference=_lowPriceReference,
      highReference=_highPriceReference))
    while _a_priceHistory.size() > 201
        _a_priceHistory.shift()
    _o_firstBullishPrice := f_samplePrice(_o_event=_o_firstBullish, _a_history=_a_priceHistory)
    _o_firstBearishPrice := f_samplePrice(_o_event=_o_firstBearish, _a_history=_a_priceHistory)
    _o_secondBullishPrice := f_samplePrice(_o_event=_o_secondBullish, _a_history=_a_priceHistory)
    _o_secondBearishPrice := f_samplePrice(_o_event=_o_secondBearish, _a_history=_a_priceHistory)
    //  Store new basis objects with the second-role snapshots. Later first-role confirmations cannot revise them.
    if not na(_o_secondBullishPrice)
        _o_secondBullishPrice.strengthBasis := o_strengthBasis.new(
          priceRange=_lowPriceRange,
          momentumRange=_momentumRange,
          confirmationBarIndex=_o_secondBullish.confirmationBarIndex)
    if not na(_o_secondBearishPrice)
        _o_secondBearishPrice.strengthBasis := o_strengthBasis.new(
          priceRange=_highPriceRange,
          momentumRange=_momentumRange,
          confirmationBarIndex=_o_secondBearish.confirmationBarIndex)
 
    var o_pairingTrack _o_lowTrack = o_pairingTrack.new(direction=MR.Signal.bullish, a_pivots=array.new<o_qualifiedPivot>())
    var o_pairingTrack _o_highTrack = o_pairingTrack.new(direction=MR.Signal.bearish, a_pivots=array.new<o_qualifiedPivot>())
    array<o_pivotPair> _a_bullishPairs = _o_lowTrack.m_step(
      _o_first=_o_firstBullish,
      _o_second=_o_secondBullish,
      _o_firstPrice=_o_firstBullishPrice,
      _o_secondPrice=_o_secondBullishPrice,
      _windowBars=_effectiveWindowBars,
      _barIndex=_o_barData.barIndex,
      _replacementFirstBar=_bullishReplacementFirstBar)
    array<o_pivotPair> _a_bearishPairs = _o_highTrack.m_step(
      _o_first=_o_firstBearish,
      _o_second=_o_secondBearish,
      _o_firstPrice=_o_firstBearishPrice,
      _o_secondPrice=_o_secondBearishPrice,
      _windowBars=_effectiveWindowBars,
      _barIndex=_o_barData.barIndex,
      _replacementFirstBar=_bearishReplacementFirstBar)
    //  Classification cannot change which pivots pair. Copy only admitted patterns into detached public results.
    //  A delayed qualification can release several pairs; keep all of them, with lows before highs.
    array<o_divergence> _a_results = array.new<o_divergence>()
    f_appendDivergences(_a_pairs=_a_bullishPairs, _a_results=_a_results, _momentumWeight=_momentumWeight)
    f_appendDivergences(_a_pairs=_a_bearishPairs, _a_results=_a_results, _momentumWeight=_momentumWeight)
    _a_results
 
//#endregion PAIRING CALCULATIONS
 
//#region 🟪🟪🟪🟪🟪🟪 CLASSIC RSI EXAMPLE INPUTS 🟪🟪🟪🟪🟪🟪
 
const string G_SOURCE = "Classic RSI"
const string G_SHOULDERS = "Pivot Shoulders"
const string G_PRICE = "Price Sampling"
const string G_PAIRING = "Pairing"
const string G_STRENGTH = "Strength"
const string TT_SHOULDERS = "Absolute uses momentum units; Percent Of Range uses percentages of the shared smoothed momentum range. Left arms the turn; right confirms the bounce or retracement. A pivot that qualifies as first can still complete its incoming second role. That pending role is cancelled only when a later turn meets the second left shoulder."
 
int in_rsiLength = input.int(defval=14, title="RSI Length", minval=1, maxval=300, group=G_SOURCE)
int in_smoothingLength = input.int(defval=3, title="RSI SMA Length", minval=1, group=G_SOURCE)
ShoulderMode in_shoulderMode = input.enum(defval=ShoulderMode.absolute, title="Shoulder Mode", group=G_SHOULDERS, tooltip="Percent Of Range shares the momentum reference range used for strength. Distances freeze when a candidate arms. An unavailable range cannot arm a new candidate.")
float in_firstLeftShoulder = input.float(defval=5.0, title="First Pivot Left Shoulder", minval=0.1, step=0.1, tooltip="A larger left shoulder selects a broader initial momentum turn. " + TT_SHOULDERS, group=G_SHOULDERS)
float in_firstRightShoulder = input.float(defval=3.0, title="First Pivot Right Shoulder", minval=0.1, step=0.1, tooltip="A smaller right shoulder confirms the first leg sooner. " + TT_SHOULDERS, group=G_SHOULDERS)
float in_secondLeftShoulder = input.float(defval=3.0, title="Second Pivot Left Shoulder", minval=0.1, step=0.1, tooltip="A smaller left shoulder lets the second pivot qualify on tighter turns. " + TT_SHOULDERS, group=G_SHOULDERS)
float in_secondRightShoulder = input.float(defval=5.0, title="Second Pivot Right Shoulder", minval=0.1, step=0.1, tooltip="The second leg needs this much bounce or retracement to confirm. " + TT_SHOULDERS, group=G_SHOULDERS)
int in_windowBars = input.int(defval=0, title="Window Bars (0 = Auto)", minval=0, maxval=500, tooltip="Maximum distance between the actual momentum pivot bars, including the last bar. Auto selects the next strictly greater Fibonacci number above RSI Length: 14 gives 21; 21 gives 34.", group=G_PAIRING)
PriceReference in_priceReference = input.enum(defval=PriceReference.bodyEdge, title="Price Reference", tooltip="Selects the lowest reference for a momentum low and the highest for a high, from each role's left-shoulder start through its confirmation bar, inclusive. Body Edge uses min/max of open and close; Wick uses low/high. Equal extremes keep the earliest candle. Momentum pairing is unchanged.", group=G_PRICE)
int in_rangeLength = input.int(defval=200, title="Percentile Window", minval=1, group=G_STRENGTH, tooltip="Bars used for each source's percentiles. Price follows Price Reference; momentum uses smoothed RSI. Both ranges are frozen when the second pivot confirms.")
int in_rangeSmoothingLength = input.int(defval=50, title="Range Smoothing", minval=1, group=G_STRENGTH, tooltip="RMA length applied separately to each percentile boundary before subtracting lower from upper.")
float in_lowerRangePercentile = input.float(defval=5.0, title="Lower Percentile", minval=0, maxval=100, group=G_STRENGTH, tooltip="Lower boundary of each reference range. Must be below Upper Percentile.")
float in_upperRangePercentile = input.float(defval=95.0, title="Upper Percentile", minval=0, maxval=100, group=G_STRENGTH, tooltip="Upper boundary of each reference range. Five and 95 describe the central 90% before smoothing; scores can exceed 100.")
float in_momentumWeightPercent = input.float(defval=70.0, title="Momentum Weight (%)", minval=0, maxval=100, group=G_STRENGTH, tooltip="Momentum's share of the strength score. Price receives the remainder. Strength combines absolute endpoint movements as percentages of their frozen ranges per bar, using each leg's own duration. It is not a probability.")
float momentumWeight = in_momentumWeightPercent / 100.0
 
 
//#endregion CLASSIC RSI EXAMPLE INPUTS
 
 
 
//#region 🟪🟪🟪🟪🟪🟪 CLASSIC RSI EXAMPLE 🟪🟪🟪🟪🟪🟪
 
//  The example uses Absolute shoulders because RSI has familiar units. The exported function defaults to Percent Of Range.
//  This example uses the same public entry point as a consuming script.
//  Drawings belong to the example. Imported calculations create no drawings.
float classicRsi = ta.rsi(source=close, length=in_rsiLength)
float exampleMomentum = ta.sma(source=classicRsi, length=in_smoothingLength)
o_barData o_currentBarData = o_barData.new(
  open=open,
  high=high,
  low=low,
  close=close,
  time=time,
  barIndex=bar_index)
array<o_divergence> a_divergences = getDivergences(
  _momentum=exampleMomentum,
  _o_barData=o_currentBarData,
  _momentumPeriod=in_rsiLength,
  _firstLeftShoulder=in_firstLeftShoulder,
  _firstRightShoulder=in_firstRightShoulder,
  _secondLeftShoulder=in_secondLeftShoulder,
  _secondRightShoulder=in_secondRightShoulder,
  _windowBars=in_windowBars,
  _shoulderMode=in_shoulderMode,
  _priceReference=in_priceReference,
  _momentumWeight=momentumWeight,
  _rangeLength=in_rangeLength,
  _rangeSmoothing=in_rangeSmoothingLength,
  _lowerPercentile=in_lowerRangePercentile,
  _upperPercentile=in_upperRangePercentile)
 
plot(series=exampleMomentum, title="Smoothed RSI", color=color.aqua, precision=2)
hline(price=70, title="Upper RSI Level", color=color.gray)
hline(price=30, title="Lower RSI Level", color=color.gray)
 
//  Keep 40 classified signals within the library's default drawing allowance.
//  The label sits on the second pivot; its tooltip identifies when the result became known.
var array<line> a_exampleLines = array.new<line>()
var array<label> a_exampleLabels = array.new<label>()
for _o_signal in a_divergences
    bool _isBullish = _o_signal.kind == DivergenceKind.bullishRegular or _o_signal.kind == DivergenceKind.bullishHidden or _o_signal.kind == DivergenceKind.bullishConvergence
    color _c_signal = _isBullish ? color.lime : color.red
    color _c_label = _isBullish ? #008844 : #C62828
    string _scoreText = na(_o_signal.strength) ? "n/a" : str.tostring(value=_o_signal.strength, format="0.00")
    //  Very late confirmations may place a pivot beyond the drawing API's bar-index history limit.
    if _o_signal.first.momentumBarIndex >= bar_index - 9999
        while a_exampleLines.size() >= 40
            line.delete(id=a_exampleLines.shift())
            label.delete(id=a_exampleLabels.shift())
        a_exampleLines.push(value=line.new(
          x1=_o_signal.first.momentumBarIndex,
          y1=_o_signal.first.momentumValue,
          x2=_o_signal.second.momentumBarIndex,
          y2=_o_signal.second.momentumValue,
          color=_c_signal,
          width=2))
        a_exampleLabels.push(value=label.new(
          x=_o_signal.second.momentumBarIndex,
          y=_o_signal.second.momentumValue,
          text=str.tostring(value=_o_signal.kind) + " | " + _scoreText,
          style=_isBullish ? label.style_label_up : label.style_label_down,
          color=_c_label,
          textcolor=chart.fg_color,
          size=size.normal,
          tooltip="Strength: " + _scoreText + " % of reference range/bar" +
          "\nResult available on bar " + str.tostring(value=bar_index) +
          "\nSignals on the open candle can change before it closes."))
 
//#endregion CLASSIC RSI EXAMPLE

← 返回列表