Move Maturity Meter: Trend Exhaustion & Swing Size Percentiles

thescalpeltrader · study · 340 行 · 点赞 177 · TradingView 原页

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

Pine Script

//@version=6
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thescalpeltrader
indicator("Move Maturity Meter: Trend Exhaustion & Swing Size Percentiles", shorttitle = "Move Maturity", overlay = true, max_lines_count = 500, max_labels_count = 100, max_boxes_count = 20)
 
// ═════════════ INPUTS ═════════════
const string GM = "Move detection"
atrLen   = input.int(14, "ATR length", minval = 1, group = GM, display = display.none)
revK     = input.float(3.0, "Move ends after a pullback of (× ATR)", minval = 0.5, step = 0.25, group = GM, display = display.none, tooltip = "A move is considered over once price pulls back this many ATRs from its extreme. Smaller = more, shorter moves. Larger = fewer, bigger swings.")
sizeMode = input.string("ATR units", "Measure size in", options = ["ATR units", "Percent"], group = GM, display = display.none, tooltip = "ATR units compare moves fairly across calm and volatile periods. Percent is easier to read.")
extStep  = input.float(1.0, "'Went further' = at least another", minval = 0.1, step = 0.1, group = GM, display = display.none, tooltip = "In the size unit chosen above (ATR or %).")
maxMoves = input.int(500, "Past moves kept per direction", minval = 30, maxval = 3000, group = GM, display = display.none)
minSmp   = input.int(20, "Minimum sample for statistics", minval = 5, group = GM, display = display.none)
 
const string GD = "Display"
showZig  = input.bool(true, "Colour past moves by how big they were", group = GD, display = display.none)
zigN     = input.int(80, "Past moves drawn", minval = 0, maxval = 300, group = GD, display = display.none)
showZone = input.bool(true, "Typical end zone", group = GD, display = display.none)
showRev  = input.bool(true, "Move-end trigger line", group = GD, display = display.none)
lblOff   = input.float(1.0, "Move label distance from price (× ATR)", minval = 0, step = 0.25, group = GD, display = display.none, tooltip = "Lifts the move label clear of the candles. 0 = touching the extreme.")
tblPos   = input.string("Top right", "Table position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = GD, display = display.none)
txtOpt   = input.string("Normal", "Table text", options = ["Small", "Normal", "Large"], group = GD, display = display.none)
 
const string GG = "Meter"
showG    = input.bool(true, "Show meter", group = GG, display = display.none)
gPosS    = input.string("Bottom right", "Meter position", options = ["Bottom right", "Middle right", "Bottom left", "Top left"], group = GG, display = display.none)
gSize    = input.string("Medium", "Meter size", options = ["Small", "Medium", "Large"], group = GG, display = display.none)
gRound   = input.float(1.0, "Meter height", minval = 0.5, maxval = 2.0, step = 0.05, group = GG, display = display.none, tooltip = "If the bars look too flat or too tall on your screen, adjust this.")
 
// ═════════════ COLOURS ═════════════
const color C_BG    = #0E1117
const color C_HEAD  = #1C2A4D
const color C_LABEL = #FFD54F
const color C_VAL   = #FFFFFF
const color C_SKY   = #40C4FF
const color C_YOUNG = #00E676
const color C_MID   = #FFD54F
const color C_MAT   = #FF9100
const color C_OLD   = #FF5252
const color C_EXT   = #EA80FC
 
txtSz = txtOpt == "Small" ? size.small : txtOpt == "Large" ? size.large : size.normal
 
// ═════════════ HELPERS ═════════════
f_size(float fromP, float toP, float a) =>
    sizeMode == "ATR units" ? math.abs(toP - fromP) / a : math.abs(toP / fromP - 1) * 100
 
f_pctF(array<float> arr, float x) =>
    int c = 0
    for v in arr
        if v < x
            c += 1
    arr.size() > 0 ? c * 100.0 / arr.size() : na
 
f_pctI(array<int> arr, int x) =>
    int c = 0
    for v in arr
        if v < x
            c += 1
    arr.size() > 0 ? c * 100.0 / arr.size() : na
 
f_col(float p) =>
    na(p) ? C_SKY : p < 40 ? C_YOUNG : p < 70 ? C_MID : p < 90 ? C_MAT : p < 97 ? C_OLD : C_EXT
 
f_word(float p) =>
    na(p) ? "Not enough history" : p < 40 ? "Young" : p < 70 ? "Maturing" : p < 90 ? "Mature" : p < 97 ? "Stretched" : "Extreme"
 
f_unit(float v) =>
    sizeMode == "ATR units" ? str.tostring(v, "0.0") + " ATR" : str.tostring(v, "0.0") + "%"
 
f_ord(float p) =>
    int r = int(math.round(p))
    string suf = (r % 100 >= 11 and r % 100 <= 13) ? "th" : r % 10 == 1 ? "st" : r % 10 == 2 ? "nd" : r % 10 == 3 ? "rd" : "th"
    str.tostring(r) + suf
 
// ═════════════ MOVE ENGINE ═════════════
atr = ta.atr(atrLen)
 
var int   dir     = 0
var float sPrice  = na
var int   sBar    = na
var int   sTime   = na
var float sAtr    = na
var float ext     = na
var int   extBar  = na
var float extAtr  = na
var int   firstT  = na
 
var array<float> upSz = array.new_float()
var array<int>   upBr = array.new_int()
var array<float> dnSz = array.new_float()
var array<int>   dnBr = array.new_int()
var array<line>  zig  = array.new_line()
 
newMove = false
 
f_record(array<float> szArr, array<int> brArr, float sz, int bs, float fromP, int fromB, float toP, int toB) =>
    float pAt = szArr.size() >= minSmp ? f_pctF(szArr, sz) : na
    szArr.push(sz)
    brArr.push(bs)
    if szArr.size() > maxMoves
        szArr.shift()
        brArr.shift()
    if showZig and zigN > 0
        zig.push(line.new(fromB, fromP, toB, toP, color = color.new(f_col(pAt), 15), width = 2))
        while zig.size() > zigN
            zig.shift().delete()
 
if not na(atr)
    if dir == 0
        dir    := close >= open ? 1 : -1
        sPrice := dir == 1 ? low : high
        sBar   := bar_index
        sTime  := time
        sAtr   := atr
        ext    := dir == 1 ? high : low
        extBar := bar_index
        extAtr := atr
        firstT := time
    else if dir == 1
        if high > ext
            ext    := high
            extBar := bar_index
            extAtr := atr
        if low <= ext - revK * atr
            f_record(upSz, upBr, f_size(sPrice, ext, sAtr), extBar - sBar, sPrice, sBar, ext, extBar)
            dir    := -1
            sPrice := ext
            sBar   := extBar
            sTime  := time[bar_index - extBar]
            sAtr   := extAtr
            ext    := low
            extBar := bar_index
            extAtr := atr
            newMove := true
    else
        if low < ext
            ext    := low
            extBar := bar_index
            extAtr := atr
        if high >= ext + revK * atr
            f_record(dnSz, dnBr, f_size(sPrice, ext, sAtr), extBar - sBar, sPrice, sBar, ext, extBar)
            dir    := 1
            sPrice := ext
            sBar   := extBar
            sTime  := time[bar_index - extBar]
            sAtr   := extAtr
            ext    := high
            extBar := bar_index
            extAtr := atr
            newMove := true
 
// ═════════════ CURRENT MOVE vs ITS OWN HISTORY ═════════════
array<float> szA = dir == 1 ? upSz : dnSz
array<int>   brA = dir == 1 ? upBr : dnBr
int   nAll  = szA.size()
bool  ready = nAll >= minSmp and not na(sPrice)
float curSz = na(sPrice) ? na : f_size(sPrice, ext, sAtr)
int   curAg = na(sBar) ? na : bar_index - sBar
float curPc = na(sPrice) ? na : math.abs(ext / sPrice - 1) * 100
float pSize = ready ? f_pctF(szA, curSz) : na
float pAge  = ready ? f_pctI(brA, curAg) : na
float mat   = ready ? (pSize + pAge) / 2 : na
 
plot(mat, "Maturity score (0-100)", display = display.data_window)
plot(pSize, "Size percentile", display = display.data_window)
plot(pAge, "Age percentile", display = display.data_window)
 
alertcondition(ta.crossover(mat, 90), "Move turned Stretched", "Move Maturity: the current move is now larger and older than 90% of past moves on this chart.")
alertcondition(newMove, "New move started", "Move Maturity: the previous move ended and a new one started.")
 
// ═════════════ DRAWING & TABLE (last bar) ═════════════
pos = tblPos == "Top right" ? position.top_right : tblPos == "Bottom right" ? position.bottom_right : tblPos == "Top left" ? position.top_left : position.bottom_left
var table tb = table.new(pos, 10, 16, bgcolor = C_BG, frame_color = C_HEAD, frame_width = 2, border_color = C_HEAD, border_width = 1)
 
var line  lMove = na
var line  lRev  = na
var line  lConn = na
var box   bZone = na
var label lbS   = na
var label lbE   = na
var label lbZ   = na
var label lbR   = na
 
f_row(int r, string k, string v, color vc) =>
    tb.cell(0, r, k, text_color = C_LABEL, text_halign = text.align_left, text_size = txtSz, bgcolor = C_BG)
    tb.cell(4, r, v, text_color = vc, text_halign = text.align_right, text_size = txtSz, bgcolor = C_BG)
    tb.merge_cells(0, r, 3, r)
    tb.merge_cells(4, r, 9, r)
 
gPos = gPosS == "Bottom right" ? position.bottom_right : gPosS == "Middle right" ? position.middle_right : gPosS == "Bottom left" ? position.bottom_left : position.top_left
var table gt = table.new(gPos, 50, 22, bgcolor = C_BG, frame_color = C_HEAD, frame_width = 2, border_color = C_BG, border_width = 1)
 
f_grad(float p) =>
    p < 40 ? color.from_gradient(p, 0, 40, #00E676, #B2FF59) : p < 70 ? color.from_gradient(p, 40, 70, #FFEB3B, #FFC400) : p < 90 ? color.from_gradient(p, 70, 90, #FF9100, #FF6D00) : p < 97 ? color.from_gradient(p, 90, 97, #FF5252, #FF1744) : C_EXT
 
f_px(float sz) =>
    sizeMode == "ATR units" ? sPrice + dir * sz * sAtr : sPrice * (1 + dir * sz / 100)
 
if barstate.islast and not na(sPrice)
    line.delete(lMove), line.delete(lRev), line.delete(lConn), box.delete(bZone)
    label.delete(lbS), label.delete(lbE), label.delete(lbZ), label.delete(lbR)
 
    color mc  = f_col(mat)
    bool  up  = dir == 1
    string dn = up ? "UP ▲" : "DOWN ▼"
 
    // conditional record: past moves that got at least this big
    array<float> ge = array.new_float()
    for v in szA
        if v >= curSz
            ge.push(v)
    int   nGe   = ge.size()
    int   nFur  = 0
    for v in ge
        if v >= curSz + extStep
            nFur += 1
    float pFur  = nGe > 0 ? nFur * 100.0 / nGe : na
    float medF  = nGe > 0 ? ge.median() : na
    float p75F  = nGe > 0 ? ge.percentile_linear_interpolation(75) : na
 
    // speed
    float curSp = curSz / math.max(curAg, 1)
    int   fastr = 0
    for i = 0 to nAll - 1
        if nAll > 0 and szA.get(i) / math.max(brA.get(i), 1) < curSp
            fastr += 1
    float pSpd  = ready ? fastr * 100.0 / nAll : na
 
    // chart: the live move
    lMove := line.new(sBar, sPrice, extBar, ext, color = mc, width = 4)
    lbS   := label.new(sBar, sPrice, "Move start\n" + str.format_time(sTime, "dd MMM yy", syminfo.timezone), style = up ? label.style_label_up : label.style_label_down, color = #283593, textcolor = C_VAL, size = size.normal, text_formatting = text.format_bold)
    string eTxt = dn + "  " + str.tostring(curAg) + " bars · " + f_unit(curSz) + "\n" + f_word(mat) + (ready ? " · " + str.tostring(mat, "0") : "")
    float lblY = ext + dir * lblOff * atr
    if lblOff > 0
        lConn := line.new(extBar, ext, extBar, lblY, color = mc, style = line.style_dotted, width = 2)
    lbE   := label.new(extBar, lblY, eTxt, style = up ? label.style_label_down : label.style_label_up, color = mc, textcolor = #000000, size = size.normal, text_formatting = text.format_bold)
 
    if showZone and ready and nGe >= 5
        float zA  = f_px(medF)
        float zB  = f_px(p75F)
        float zHi = math.max(zA, zB)
        float zLo = math.min(zA, zB)
        float dNear = math.abs((up ? zLo : zHi) - close)
        float dFar  = math.abs((up ? zHi : zLo) - close)
        string zTxt = "Typical end zone\n" + str.tostring(zLo, format.mintick) + " – " + str.tostring(zHi, format.mintick) + "\n" + (up ? "+" : "−") + str.tostring(dNear, "#,##0") + " to " + (up ? "+" : "−") + str.tostring(dFar, "#,##0") + " pts from here"
        bZone := box.new(bar_index + 2, zHi, bar_index + 30, zLo, border_color = C_SKY, bgcolor = color.new(C_SKY, 80), border_style = line.style_dashed)
        lbZ   := label.new(bar_index + 30, up ? zHi : zLo, zTxt, style = label.style_label_left, color = C_SKY, textcolor = #000000, size = size.normal, text_formatting = text.format_bold)
 
    float trig = up ? ext - revK * atr : ext + revK * atr
    if showRev
        lRev := line.new(bar_index - 10, trig, bar_index + 30, trig, color = C_OLD, style = line.style_dashed, width = 2)
        lbR  := label.new(bar_index + 30, trig, "Move ends " + (up ? "below " : "above ") + str.tostring(trig, format.mintick), style = label.style_label_left, color = #C62828, textcolor = C_VAL, size = size.normal, text_formatting = text.format_bold)
 
    // table
    tb.clear(0, 0, 9, 15)
    int r = 0
    tb.cell(0, r, "MOVE MATURITY · " + syminfo.ticker + " · " + timeframe.period, bgcolor = C_HEAD, text_color = C_VAL, text_size = txtSz)
    tb.merge_cells(0, r, 9, r)
    r += 1
    f_row(r, "Move", dn + " since " + str.format_time(sTime, "dd MMM", syminfo.timezone), up ? C_YOUNG : C_OLD)
    r += 1
    f_row(r, "Age", str.tostring(curAg) + " bars" + (ready ? " · " + f_ord(pAge) + " pct" : ""), C_VAL)
    r += 1
    f_row(r, "Size", f_unit(curSz) + (sizeMode == "ATR units" ? " (" + str.tostring(curPc, "0.0") + "%)" : "") + (ready ? " · " + f_ord(pSize) + " pct" : ""), C_VAL)
    r += 1
    f_row(r, "Speed", (ready ? f_ord(pSpd) + " pct" : "—"), C_VAL)
    r += 1
    if ready
        string furTxt = nGe >= 5 ? str.tostring(pFur, "0") + "% went +" + f_unit(extStep) + " more" : "Bigger than all but " + str.tostring(nGe) + " moves"
        f_row(r, "From here", furTxt, nGe >= 5 ? (pFur >= 50 ? C_YOUNG : C_OLD) : C_EXT)
        r += 1
        if nGe >= 5
            f_row(r, "Like-sized moves", str.tostring(nGe) + " of " + str.tostring(nAll), C_VAL)
            r += 1
            f_row(r, "Typical end", f_unit(medF) + " – " + f_unit(p75F), C_SKY)
            r += 1
    f_row(r, "Ends " + (up ? "below" : "above"), str.tostring(trig, format.mintick), C_OLD)
    r += 1
    f_row(r, "Sample", str.tostring(nAll) + (up ? " up" : " down") + " moves since " + str.format_time(firstT, "yyyy", syminfo.timezone), C_VAL)
    r += 1
    tb.cell(0, r, "Past behaviour on this chart · not a forecast", text_color = C_LABEL, text_size = size.small, bgcolor = C_BG)
    tb.merge_cells(0, r, 9, r)
 
    // ═════════════ MATURITY PANEL ═════════════
    gt.clear(0, 0, 49, 21)
    if showG and ready
        float cw = gSize == "Small" ? 0.24 : gSize == "Large" ? 0.38 : 0.3
        float ch = cw * 1.8 * gRound
        bSz = gSize == "Small" ? size.large : size.huge
        mSz = gSize == "Small" ? size.small : gSize == "Large" ? size.large : size.normal
        // header
        gt.cell(0, 0, "MOVE MATURITY · " + syminfo.ticker + " " + timeframe.period, text_color = C_LABEL, text_size = size.small, bgcolor = C_HEAD, text_halign = text.align_left, text_formatting = text.format_bold)
        gt.merge_cells(0, 0, 49, 0)
        gt.cell(0, 1, str.tostring(mat, "0"), text_color = mc, text_size = bSz, bgcolor = C_BG, text_formatting = text.format_bold)
        gt.merge_cells(0, 1, 11, 2)
        gt.cell(12, 1, str.upper(f_word(mat)) + "  " + (up ? "▲" : "▼"), text_color = mc, text_size = mSz, bgcolor = C_BG, text_halign = text.align_left, text_formatting = text.format_bold)
        gt.merge_cells(12, 1, 49, 1)
        gt.cell(12, 2, "bigger than " + str.tostring(pSize, "0") + "% · older than " + str.tostring(pAge, "0") + "%", text_color = C_VAL, text_size = size.small, bgcolor = C_BG, text_halign = text.align_left, text_formatting = text.format_bold)
        gt.merge_cells(12, 2, 49, 2)
        // histogram of past move sizes (same direction)
        int   NB  = 25
        int   HR  = 14
        float mx  = szA.percentile_nearest_rank(98)
        float bw  = math.max(mx, curSz) / NB
        array<int> cnt = array.new_int(NB, 0)
        for v in szA
            int b = math.min(int(v / bw), NB - 1)
            cnt.set(b, cnt.get(b) + 1)
        int cb = math.min(int(curSz / bw), NB - 1)
        int mxc = cnt.max()
        for b = 0 to NB - 1
            int   hgt = cnt.get(b) > 0 ? math.max(int(math.round(cnt.get(b) * HR / mxc)), 1) : 0
            color zc  = f_grad(f_pctF(szA, (b + 0.5) * bw))
            color bc  = b == cb ? C_VAL : b < cb ? zc : color.new(zc, 75)
            if b == cb
                hgt := math.max(hgt, 1)
            for rr = 0 to HR - 1
                color cc = rr >= HR - hgt ? bc : C_BG
                gt.cell(b * 2, 3 + rr, "", bgcolor = cc, width = cw, height = ch)
                gt.cell(b * 2 + 1, 3 + rr, "", bgcolor = cc, width = cw, height = ch)
            color pc = b == cb ? C_VAL : C_BG
            gt.cell(b * 2, 17, "", bgcolor = pc, width = cw, height = ch * 0.6)
            gt.cell(b * 2 + 1, 17, "", bgcolor = pc, width = cw, height = ch * 0.6)
        gt.cell(0, 18, "past " + (up ? "up" : "down") + "-moves by size  ▲ this move", text_color = C_LABEL, text_size = size.small, bgcolor = C_BG, text_halign = text.align_left, text_formatting = text.format_bold)
        gt.merge_cells(0, 18, 49, 18)
        // maturity bar
        int ms = math.min(int(mat / 2), 49)
        for s = 0 to 49
            color zc = f_grad(s * 2 + 1)
            gt.cell(s, 19, "", bgcolor = s * 2 + 1 <= mat ? zc : color.new(zc, 75), width = cw, height = ch * 1.8)
            gt.cell(s, 20, "", bgcolor = s == ms ? C_VAL : C_BG, width = cw, height = ch * 0.6)
        gt.cell(0, 21, "YOUNG", text_color = C_YOUNG, text_size = size.small, bgcolor = C_BG, text_halign = text.align_left, text_formatting = text.format_bold)
        gt.merge_cells(0, 21, 19, 21)
        gt.cell(20, 21, "MATURING", text_color = C_MID, text_size = size.small, bgcolor = C_BG, text_halign = text.align_left, text_formatting = text.format_bold)
        gt.merge_cells(20, 21, 34, 21)
        gt.cell(35, 21, "MATURE", text_color = C_MAT, text_size = size.small, bgcolor = C_BG, text_halign = text.align_left, text_formatting = text.format_bold)
        gt.merge_cells(35, 21, 44, 21)
        gt.cell(45, 21, "LATE", text_color = C_OLD, text_size = size.small, bgcolor = C_BG, text_halign = text.align_left, text_formatting = text.format_bold)
        gt.merge_cells(45, 21, 49, 21)

← 返回列表