TrendRegime

Holtermorter99 · library · 177 行 · 点赞 1 · 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/
// © Holtermorter99
//
// @description Trend regime engine of Trend Regime Filter [Holtermorter99]: one function returns the regime (Bullish / Bearish / Undefined), score, strength, trend quality, consensus, state line and a ready flag, with the same calculations and defaults as the published indicator. The regime only changes on confirmed bars (no repainting).
 
//@version=6
library("TrendRegime", overlay = true)
 
// ─────────────────────────────── Engine helpers ───────────────────────────────
clamp(float value, float minValue, float maxValue) =>
    math.max(minValue, math.min(maxValue, value))
 
safeDiv(float numerator, float denominator) =>
    not na(numerator) and not na(denominator) and denominator != 0 ? numerator / denominator : 0.0
 
normalize01(float value, float minValue, float maxValue) =>
    clamp(safeDiv(value - minValue, maxValue - minValue), 0.0, 1.0)
 
scoreLogit(float score) =>
    float p = clamp(0.5 + 0.5 * nz(score, 0.0), 0.001, 0.999)
    math.log(p / (1.0 - p))
 
tanhSafe(float value) =>
    float clipped = clamp(value, -10.0, 10.0)
    float expTerm = math.exp(2.0 * clipped)
    (expTerm - 1.0) / (expTerm + 1.0)
 
efficiencyRatio(float src, int length) =>
    float directionalMove = math.abs(src - src[length])
    float noise = math.sum(math.abs(ta.change(src)), length)
    safeDiv(directionalMove, noise)
 
choppinessIndex(int length) =>
    float rangeSpan = ta.highest(high, length) - ta.lowest(low, length)
    rangeSpan > 0 ? 100.0 * math.log10(math.sum(ta.tr(true), length) / rangeSpan) / math.log10(length) : 100.0
 
// @function Trend regime engine of Trend Regime Filter [Holtermorter99]: five views of trend (adaptive alpha-beta state filter, log-regression slope weighted by R², DMI/ADX, position inside the recent range, candle flow) combined into one score, with hysteresis. Call it on every bar (not inside a conditional block). With confirmedOnly = true (default, as in the indicator) the filter and the regime only advance on confirmed bars, so on an open realtime bar they keep the last confirmed values while the scores move. Inside request.security() barstate.isconfirmed is not reliable: there, pass confirmedOnly = false and read only the previous bar's values ([1]) with lookahead on.
// @param source Price series fed to the adaptive state filter (TRF default: hlc3).
// @param stateLength Lookback of the efficiency ratio that adapts the state filter (34).
// @param regressionLength Bars for the log-price regression slope and its R² (55).
// @param structureLength Bars for the recent range and the choppiness index (34).
// @param dmiLength Directional Movement length (14).
// @param adxSmoothing ADX smoothing length (14).
// @param volumeLength Volume baseline; ignored automatically on symbols without volume (20).
// @param velocityDamping Fraction of the filter's velocity kept each bar (0.90).
// @param enterThreshold Minimum absolute score to start a Bullish/Bearish regime (0.32).
// @param exitThreshold Absolute score below which the regime returns to Undefined (0.15).
// @param minStrength Minimum strength, |score| × (0.5 + 0.5 × quality) × (0.4 + 0.6 × consensus), to enter a regime (0.35).
// @param minConsensus Minimum consensus, |bullish − bearish components| / 5, to enter a regime (0.60: e.g. 4 bullish vs 1 bearish, or 3 bullish and 2 neutral).
// @param confirmBars Consecutive closed bars meeting the conditions before a Bullish/Bearish regime starts or reverses (2). A return to Undefined needs one bar.
// @param confirmedOnly true (default): advance only on confirmed bars. false: advance on every execution (for use inside request.security() with [1]).
// @returns [regime (1 Bullish, -1 Bearish, 0 Undefined), score (-1..1), strength = |score| × (0.5 + 0.5 × quality) × (0.4 + 0.6 × consensus) (0..1), quality (0..1), consensus = |bullish − bearish components| / 5 (0..1), state line, ready (enough history)]
export trendRegime(float source = hlc3, simple int stateLength = 34, simple int regressionLength = 55, simple int structureLength = 34, simple int dmiLength = 14, simple int adxSmoothing = 14, simple int volumeLength = 20, float velocityDamping = 0.90, float enterThreshold = 0.32, float exitThreshold = 0.15, float minStrength = 0.35, float minConsensus = 0.60, int confirmBars = 2, bool confirmedOnly = true) =>
    // 1. Adaptive alpha-beta state filter
    int atrLength = math.max(math.max(stateLength, dmiLength), 14)
    float atrValue = ta.atr(atrLength)
    float adaptiveER = nz(efficiencyRatio(source, stateLength), 0.0)
    float fastGain = 2.0 / (4.0 + 1.0)
    float slowGain = 2.0 / (30.0 + 1.0)
    float adaptiveAlpha = clamp(math.pow(adaptiveER * (fastGain - slowGain) + slowGain, 2) * 1.80, 0.06, 0.85)
    float adaptiveBeta = clamp(adaptiveAlpha * adaptiveAlpha * 0.45, 0.002, 0.35)
    var float stateEstimate = na
    var float velocityEstimate = 0.0
    if barstate.isfirst
        stateEstimate := source
        velocityEstimate := 0.0
    else if barstate.isconfirmed or not confirmedOnly
        float prevState = nz(stateEstimate[1], source[1])
        float prevVelocity = nz(velocityEstimate[1], 0.0) * velocityDamping
        float predictedState = prevState + prevVelocity
        float residual = source - predictedState
        stateEstimate := predictedState + adaptiveAlpha * residual
        velocityEstimate := prevVelocity + adaptiveBeta * residual
    else
        stateEstimate := nz(stateEstimate[1], source)
        velocityEstimate := nz(velocityEstimate[1], 0.0)
    float stateStep = safeDiv(stateEstimate - nz(stateEstimate[1], stateEstimate), atrValue)
    float velocityStep = safeDiv(velocityEstimate, atrValue)
    float stateScore = clamp(0.55 * tanhSafe(stateStep * 2.6) + 0.45 * tanhSafe(velocityStep * 2.0), -1.0, 1.0)
    // 2. Log-regression slope × R²
    float logPrice = math.log(math.max(close, syminfo.mintick))
    float regressionNow = ta.linreg(logPrice, regressionLength, 0)
    float regressionPrev = ta.linreg(logPrice, regressionLength, 1)
    float regressionSlope = regressionNow - regressionPrev
    float regressionVol = ta.stdev(ta.change(logPrice), regressionLength)
    float timeAxis = bar_index * 1.0
    float regressionCorr = nz(ta.correlation(logPrice, timeAxis, regressionLength), 0.0)
    float regressionRSquared = clamp(math.pow(regressionCorr, 2), 0.0, 1.0)
    float regressionZ = safeDiv(regressionSlope, regressionVol)
    float regressionScore = clamp(tanhSafe(regressionZ * (0.80 + 1.20 * regressionRSquared)), -1.0, 1.0)
    // 3. DMI / ADX
    [plusDI, minusDI, adxValue] = ta.dmi(dmiLength, adxSmoothing)
    float dmiImbalance = safeDiv(plusDI - minusDI, plusDI + minusDI)
    float adxStrength = normalize01(adxValue, 18.0, 45.0)
    float dmiScore = clamp(dmiImbalance * (0.35 + 0.65 * adxStrength), -1.0, 1.0)
    // 4. Range structure
    float priorHigh = ta.highest(high[1], structureLength)
    float priorLow = ta.lowest(low[1], structureLength)
    float priorRangeSpan = priorHigh - priorLow
    float rangeMid = (priorHigh + priorLow) * 0.5
    float rangePosition = not na(priorRangeSpan) and priorRangeSpan > 0 ? clamp((close - rangeMid) / (priorRangeSpan * 0.5), -1.0, 1.0) : 0.0
    float breakoutBias = not na(priorHigh) and close > priorHigh ? 1.0 : not na(priorLow) and close < priorLow ? -1.0 : 0.0
    float stateDistance = safeDiv(close - stateEstimate, atrValue * 1.75)
    float structureScore = clamp(0.40 * rangePosition + 0.35 * breakoutBias + 0.25 * clamp(stateDistance, -1.0, 1.0), -1.0, 1.0)
    // 5. Candle flow (volume optional)
    float bodyImpulse = tanhSafe(safeDiv(close - open, atrValue))
    float closeLocation = high != low ? clamp(((close - low) - (high - close)) / (high - low), -1.0, 1.0) : 0.0
    float volumeMean = ta.sma(volume, volumeLength)
    float volumeDev = ta.stdev(volume, volumeLength)
    bool hasVolume = not na(volume) and not na(volumeMean) and volumeMean > 0 and not na(volumeDev)
    float volumeZ = hasVolume and volumeDev > 0 ? (volume - volumeMean) / volumeDev : 0.0
    float volumeScore = hasVolume ? tanhSafe(volumeZ * 0.60) : 0.0
    float flowScore = clamp(0.45 * bodyImpulse + 0.35 * closeLocation + 0.20 * volumeScore, -1.0, 1.0)
    // Combination
    float choppiness = nz(choppinessIndex(structureLength), 100.0)
    float trendCleanliness = 1.0 - normalize01(choppiness, 38.0, 62.0)
    float trendQuality = clamp(0.30 * adaptiveER + 0.25 * trendCleanliness + 0.25 * adxStrength + 0.20 * regressionRSquared, 0.0, 1.0)
    int bullVotes = (stateScore > 0 ? 1 : 0) + (regressionScore > 0 ? 1 : 0) + (dmiScore > 0 ? 1 : 0) + (structureScore > 0 ? 1 : 0) + (flowScore > 0 ? 1 : 0)
    int bearVotes = (stateScore < 0 ? 1 : 0) + (regressionScore < 0 ? 1 : 0) + (dmiScore < 0 ? 1 : 0) + (structureScore < 0 ? 1 : 0) + (flowScore < 0 ? 1 : 0)
    float alignment = math.abs(bullVotes - bearVotes) / 5.0
    float evidence = 1.25 * scoreLogit(stateScore) + 1.10 * scoreLogit(regressionScore) + 1.00 * scoreLogit(dmiScore) + 0.90 * scoreLogit(structureScore) + 0.70 * scoreLogit(flowScore)
    float evidenceScale = 0.22 + 0.45 * trendQuality + 0.33 * alignment
    float posteriorBull = 1.0 / (1.0 + math.exp(-evidence * evidenceScale))
    float regimeScore = clamp(2.0 * posteriorBull - 1.0, -1.0, 1.0)
    float confidence = clamp(math.abs(regimeScore) * (0.50 + 0.50 * trendQuality) * (0.40 + 0.60 * alignment), 0.0, 1.0)
    int historyNeeded = math.max(math.max(math.max(math.max(stateLength + 2, regressionLength + 2), structureLength + 2), volumeLength + 2), dmiLength + adxSmoothing + 2)
    bool modelReady = bar_index >= historyNeeded and not na(atrValue) and not na(priorHigh) and not na(priorLow) and not na(regressionNow) and not na(regressionPrev)
    bool bullSetup = modelReady and regimeScore >= enterThreshold and confidence >= minStrength and alignment >= minConsensus
    bool bearSetup = modelReady and regimeScore <= -enterThreshold and confidence >= minStrength and alignment >= minConsensus
    bool neutralSetup = not modelReady or math.abs(regimeScore) <= exitThreshold or confidence < minStrength * 0.85 or alignment < minConsensus * 0.85
    // Regime state machine (closed bars only)
    var int regime = 0
    var int bullCount = 0
    var int bearCount = 0
    if barstate.isfirst
        regime := 0
        bullCount := 0
        bearCount := 0
    else if barstate.isconfirmed or not confirmedOnly
        int prevBullCount = nz(bullCount[1], 0)
        int prevBearCount = nz(bearCount[1], 0)
        int prevRegime = nz(regime[1], 0)
        bullCount := bullSetup ? prevBullCount + 1 : 0
        bearCount := bearSetup ? prevBearCount + 1 : 0
        regime := prevRegime
        if prevRegime == 1
            if bearCount >= confirmBars
                regime := -1
            else if neutralSetup
                regime := 0
        else if prevRegime == -1
            if bullCount >= confirmBars
                regime := 1
            else if neutralSetup
                regime := 0
        else
            if bullCount >= confirmBars
                regime := 1
            else if bearCount >= confirmBars
                regime := -1
            else
                regime := 0
    else
        regime := nz(regime[1], 0)
        bullCount := nz(bullCount[1], 0)
        bearCount := nz(bearCount[1], 0)
    [regime, regimeScore, confidence, trendQuality, alignment, stateEstimate, modelReady]
 
// ─────────────────────────────── Demo (shown when the library is added to a chart) ───────────────────────────────
[demoRegime, demoScore, demoStrength, demoQuality, demoConsensus, demoState, demoReady] = trendRegime()
color demoColor = not demoReady ? #787B86 : demoRegime == 1 ? #26A69A : demoRegime == -1 ? #EF5350 : #787B86
plot(demoState, "State Line", color = demoColor, linewidth = 2)
plot(demoRegime, "Regime", display = display.data_window)
plot(demoScore, "Score", display = display.data_window)
plot(demoStrength, "Strength", display = display.data_window)
plot(demoQuality, "Quality", display = display.data_window)
plot(demoConsensus, "Consensus", display = display.data_window)

← 返回列表