JurikJMA

ZurvanEG · library · 260 行 · 点赞 3 · 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/
// © ZurvanEG
// @version=6
 
// In the Name of God of Infinite Time and Space
// ────────────────────────────────────────────────────────────────── ─── ─
//    Title : 𝗝𝗠𝗔 - 𝗝urik 𝗠oving 𝗔verage (Durkin Reconstruction) - library
//            a faithful port of Igor Durkin's complete reverse-engineered
//            Jurik algorithm (the MQL4 'JJMA' port by Nikolay Kositsin) -
//            the most complete public reconstruction of the original JMA.
//    Usage : import ZurvanEG/JurikJMA/1 as jurik
//            float j = jurik.jma(close, len, ph)
//   Params : src ▸ length (min 2, clamped) ▸ phase (-100...+100, clamped)
//    Notes : each call keeps its own state, so call jma() once per bar in
//            the global scope; never within if / for / while or a ternary
//  Credits : Mark Jurik ▸ Igor Durkin (rev-eng) ▸ Nikolay Kositsin (MQL4)
// Language : TradingView's Pine Script® v6
// ────────────────────────────────────────────────────────────────── ─── ─
 
// #startRegion
// ▾▾▾▾▾▾▾▾▾▾▾▾
library("JurikJMA", overlay = true)
 
//@function calculates the Jurik Moving Average (JMA).
//@param    src        source price series.
//@param    length     base smoothing length.
//@param    phase      lag / overshoot trade-off in [-100, 100].
//@returns  JMA value  returns na during the first 30 valid bars (warm-up) and on bars where src is na.
export jma(series float src, simple int length, simple float phase) =>
    // >input sanitization (no runtime errors possible)
    int   len = math.max(length, 2)   // length < 2 would make log(0) undefined
    float ph  = math.max(-100.0, math.min(100.0, nz(phase)))
 
    // >constants (derived from Length and Phase only)
    float phaseParam    = ph / 100.0 + 1.5   // 0.5 .. 2.5
    float lengthParam   = (len - 1) / 2.0
    float logParam      = math.log(math.sqrt(lengthParam)) / math.log(2.0)
    logParam           := logParam + 2.0 < 0 ? 0.0 : logParam + 2.0       // upper limit of adaptive power
    float sqrtParam     = math.sqrt(lengthParam) * logParam
    float lengthDivider = lengthParam * 0.9 / (lengthParam * 0.9 + 2.0)   // beta
    float sqrtDivider   = sqrtParam / (sqrtParam + 1.0)                   // base band decay
 
    // >persistent state
    var array<float> vlist  = array.new_float(129, 0.0)   // sorted volatility history (+1 guard slot)
    var array<float> ring1  = array.new_float(128, 0.0)   // circular buffer of 10-bar volatility means
    var array<float> ring2  = array.new_float(11, 0.0)    // circular buffer of raw volatility (10 bars)
    var array<float> buffer = array.new_float(62, 0.0)    // first 61 prices, used for bootstrap
    var bool  listReady    = false
    var bool  initFlag     = true
    var int   limitValue   = 63
    var int   startValue   = 64
    var int   loopParam    = 0
    var int   loopCriteria = 0
    var int   cycleLimit   = 0
    var int   counterA     = 0
    var int   counterB     = 0
    var int   s38          = 0      // upper index of trimmed window
    var int   s40          = 0      // lower index of trimmed window
    var int   s58          = 0      // index of value leaving the sorted list
    var int   s60          = 0      // insertion index of new value
    var float cycleDelta   = 0.0    // running sum of last 10 raw volatilities
    var float lowDValue    = 0.0    // running sum of trimmed window
    var float paramA       = 0.0    // upper Jurik band
    var float paramB       = 0.0    // lower Jurik band
    var float dValue       = 0.0    // adaptive power
    var float fC0          = 0.0    // stage 1: adaptive EMA
    var float fC8          = 0.0    // stage 2: detrender
    var float fA8          = 0.0    // stage 3: Kalman-style accumulator
    var float jmaPrev      = na
 
    // >sorted list starts filled with sentinels around the middle.
    if not listReady
        for i = 0 to 63
            vlist.set(i, -1000000.0)
        for i = 64 to 127
            vlist.set(i, 1000000.0)
        listReady := true
 
    float price  = src
    float jmaOut = na
 
    // >a missing source value must never enter the state (it would poison every later bar)
    if not na(price)
        // >collect bootstrap prices ──
        if loopParam < 61
            loopParam += 1
            buffer.set(loopParam, price)
 
        if loopParam > 30
            // >one-time initialization: replay the first 30 bars
            int highLimit = 0
            if initFlag
                initFlag := false
                int diffFlag = 0
                for i = 1 to 29
                    if buffer.get(i + 1) != buffer.get(i)
                        diffFlag := 1
                highLimit := diffFlag * 30
                paramB    := highLimit == 0 ? price : buffer.get(1)
                paramA    := paramB
                if highLimit > 29
                    highLimit := 29
 
            float jmaTemp  = price
            float sValue   = price
            float absValue = 0.0
 
            for i = highLimit to 0
                sValue := i == 0 ? price : buffer.get(31 - i)
 
                // >raw volatility: distance of price from the Jurik bands
                absValue := math.max(math.abs(sValue - paramA), math.abs(sValue - paramB))
                dValue   := absValue + 0.0000000001
 
                // >10-bar mean of raw volatility
                counterA := counterA <= 1 ? 127 : counterA - 1
                counterB := counterB <= 1 ? 10 : counterB - 1
                if cycleLimit < 128
                    cycleLimit += 1
                cycleDelta += dValue - ring2.get(counterB)
                ring2.set(counterB, dValue)
                float highDValue = cycleLimit > 10 ? cycleDelta / 10.0 : cycleDelta / cycleLimit
 
                // >locate the value leaving the 128-sample sorted history
                if cycleLimit > 127
                    dValue := ring1.get(counterA)
                    ring1.set(counterA, highDValue)
                    int s68 = 64
                    s58 := s68
                    while s68 > 1
                        if vlist.get(s58) < dValue
                            s68 := int(s68 / 2)
                            s58 += s68
                        else if vlist.get(s58) <= dValue
                            s68 := 1
                        else
                            s68 := int(s68 / 2)
                            s58 -= s68
                else
                    ring1.set(counterA, highDValue)
                    if limitValue + startValue > 127
                        startValue -= 1
                        s58 := startValue
                    else
                        limitValue += 1
                        s58 := limitValue
                    s38 := limitValue > 96 ? 96 : limitValue
                    s40 := startValue < 32 ? 32 : startValue
 
                // >binary search for the insertion point of the new value
                int s68b = 64
                s60 := s68b
                while s68b > 1
                    if vlist.get(s60) >= highDValue
                        if vlist.get(s60 - 1) <= highDValue
                            s68b := 1
                        else
                            s68b := int(s68b / 2)
                            s60 -= s68b
                    else
                        s68b := int(s68b / 2)
                        s60 += s68b
                    if s60 == 127 and highDValue > vlist.get(127)
                        s60 := 128
 
                // >incrementally update the trimmed-window sum
                if cycleLimit > 127
                    if s58 >= s60
                        if s38 + 1 > s60 and s40 - 1 < s60
                            lowDValue += highDValue
                        else if s40 > s60 and s40 - 1 < s58
                            lowDValue += vlist.get(s40 - 1)
                    else if s40 >= s60
                        if s38 + 1 < s60 and s38 + 1 > s58
                            lowDValue += vlist.get(s38 + 1)
                    else if s38 + 2 > s60
                        lowDValue += highDValue
                    else if s38 + 1 < s60 and s38 + 1 > s58
                        lowDValue += vlist.get(s38 + 1)
 
                    if s58 > s60
                        if s40 - 1 < s58 and s38 + 1 > s58
                            lowDValue -= vlist.get(s58)
                        else if s38 < s58 and s38 + 1 > s60
                            lowDValue -= vlist.get(s38)
                    else
                        if s38 + 1 > s58 and s40 - 1 < s58
                            lowDValue -= vlist.get(s58)
                        else if s40 > s58 and s40 < s60
                            lowDValue -= vlist.get(s40)
 
                // >shift elements and insert the new value (keeps list sorted)
                if s58 <= s60
                    if s58 >= s60
                        vlist.set(s60, highDValue)
                    else
                        if s58 + 1 <= s60 - 1   // guard: Pine loops run in reverse when from > to
                            for j = s58 + 1 to s60 - 1
                                vlist.set(j - 1, vlist.get(j))
                        vlist.set(s60 - 1, highDValue)
                else
                    for j = s58 - 1 to s60
                        vlist.set(j + 1, vlist.get(j))
                    vlist.set(s60, highDValue)
 
                // >while history is not yet full, recompute the trimmed sum directly.
                if cycleLimit <= 127
                    lowDValue := 0.0
                    for j = s40 to s38
                        lowDValue += vlist.get(j)
 
                loopCriteria := loopCriteria + 1 > 31 ? 31 : loopCriteria + 1
 
                if loopCriteria <= 30
                    // >warm-up: bands decay at base rate
                    paramA  := sValue - paramA > 0 ? sValue : sValue - (sValue - paramA) * sqrtDivider
                    paramB  := sValue - paramB < 0 ? sValue : sValue - (sValue - paramB) * sqrtDivider
                    jmaTemp := price
                    if loopCriteria == 30
                        // >seed the filter: stage 1 = price, stage 3 = interpolated initial slope.
                        fC0 := price
                        int leftInt   = math.ceil(sqrtParam) >= 1 ? int(math.ceil(sqrtParam)) : 1
                        int rightPart = math.floor(sqrtParam) >= 1 ? int(math.floor(sqrtParam)) : 1
                        float dv      = leftInt == rightPart ? 1.0 : (sqrtParam - rightPart) / (leftInt - rightPart)
                        int upShift   = rightPart <= 29 ? rightPart : 29
                        int dnShift   = leftInt <= 29 ? leftInt : 29
                        fA8 := (price - buffer.get(loopParam - upShift)) * (1 - dv) / rightPart + (price - buffer.get(loopParam - dnShift)) * dv / leftInt
                else
                    // >adaptive power from relative volatility ──
                    float avgV       = lowDValue / (s38 - s40 + 1)
                    float powerValue = 0.5 <= logParam - 2.0 ? logParam - 2.0 : 0.5
                    float ratio      = math.pow(absValue / avgV, powerValue)
                    dValue := logParam >= ratio ? ratio : logParam   // cap at logParam
                    if dValue < 1
                        dValue := 1.0                                // floor at 1
                    // >bands decay faster when volatility is high.
                    powerValue := math.pow(sqrtDivider, math.sqrt(dValue))
                    paramA := sValue - paramA > 0 ? sValue : sValue - (sValue - paramA) * powerValue
                    paramB := sValue - paramB < 0 ? sValue : sValue - (sValue - paramB) * powerValue
 
            // >three-stage JMA filter
            if loopCriteria > 30
                jmaTemp := nz(jmaPrev, price)
                float alpha  = math.pow(lengthDivider, dValue)   // adaptive smoothing factor
                float alpha2 = alpha * alpha
                fC0 := (1.0 - alpha) * price + alpha * fC0                                                   // stage 1
                fC8 := (price - fC0) * (1.0 - lengthDivider) + lengthDivider * fC8                           // stage 2
                fA8 := (phaseParam * fC8 + fC0 - jmaTemp) * (alpha * -2.0 + alpha2 + 1) + alpha2 * fA8       // stage 3
                jmaTemp += fA8
 
            jmaOut  := jmaTemp
            jmaPrev := jmaOut
 
    jmaOut
 
// >demo (visible only when the library itself is added to a chart)
float demoJma = jma(close, 14, 0)
plot(demoJma, "JMA (14, 0)", demoJma >= nz(demoJma[1], demoJma) ? color.teal : color.red, 2)
// ▴▴▴▴▴▴▴▴▴▴
// #endRegion

← 返回列表