Wick Reclaim Stats

Morat · study · 426 行 · 点赞 12 · TradingView 原页

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

Pine Script

//@version=6
indicator("Wick Reclaim Stats", "WickReclaim", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// =====================================================================================
//  WICK RECLAIM STATS
//  1. Builds candles of the chosen wick timeframe (default 4H) from the chart's bars.
//  2. Measures every upper/lower wick in ATR multiples and puts it in a size bucket.
//  3. Tracks how many candles it takes price to trade back to the reclaim level.
//  4. Table: reclaim rate per size bucket within each test horizon + median time.
//  5. Chart: every still-open wick is boxed and labelled with the chance it is
//     reclaimed (given how long it has already survived) and the typical time left.
//  Run on the wick timeframe or any lower timeframe (lower = finer reclaim detection).
// =====================================================================================
 
// ---------- Inputs -------------------------------------------------------------------
gW = "Wick definition"
tfIn     = input.timeframe("240", "Wick timeframe", group = gW)
atrLen   = input.int(14, "ATR length (wick timeframe)", minval = 2, group = gW)
fillPct  = input.float(100, "Reclaim depth (% of wick retraced)", minval = 1, maxval = 100, group = gW, tooltip = "100 = price must trade back to the wick tip. 50 = half the wick must be filled.")
sideIn   = input.string("Both", "Wicks to analyse", options = ["Both", "Upper only", "Lower only"], group = gW)
splitIn  = input.bool(false, "Separate stats for upper and lower wicks", group = gW)
 
gV = "PVSRA volume filter"
candleIn = input.string("All candles", "Candles to analyse", options = ["All candles", "Vector candles (150% + 200%)", "200% vectors only", "150% vectors only"], group = gV, tooltip = "PVSRA is calculated on the wick timeframe candles: 200% = volume at least 2x the average of the previous 10 candles, or the highest spread x volume of the previous 10. 150% = volume at least 1.5x that average.")
usePerp  = input.bool(true, "Use volume of the equivalent BINANCE PERP chart (crypto, if available)", group = gV)
forceSym = input.bool(false, "Force volume symbol", inline = "fs", group = gV)
symIn    = input.symbol("BINANCE:BTCUSDT.P", "", inline = "fs", group = gV)
 
gB = "Size buckets (wick length in ATR multiples)"
e1 = input.float(0.25, "Bucket 1 starts at (smaller wicks are ignored)", step = 0.05, group = gB)
e2 = input.float(0.50, "Bucket 2 starts at", step = 0.05, group = gB)
e3 = input.float(0.75, "Bucket 3 starts at", step = 0.05, group = gB)
e4 = input.float(1.00, "Bucket 4 starts at", step = 0.05, group = gB)
e5 = input.float(1.50, "Bucket 5 starts at", step = 0.05, group = gB)
 
gH = "Test horizons (candles of the wick timeframe)"
h1 = input.int(3,  "Horizon 1", minval = 1, maxval = 300, group = gH)
h2 = input.int(6,  "Horizon 2", minval = 1, maxval = 300, group = gH)
h3 = input.int(12, "Horizon 3", minval = 1, maxval = 300, group = gH)
h4 = input.int(24, "Horizon 4", minval = 1, maxval = 300, group = gH)
h5 = input.int(48, "Horizon 5", minval = 1, maxval = 300, group = gH)
 
gS = "Sample"
sampleIn  = input.string("All loaded history", "Stats sample", options = ["All loaded history", "Visible range only"], group = gS)
minSample = input.int(20, "Min sample per bucket (else use all-sizes stats, marked *)", minval = 1, group = gS)
 
gD = "Display"
showOpen  = input.bool(true, "Mark open (unreclaimed) wicks", group = gD)
maxShow   = input.int(30, "Max open wicks shown", minval = 1, maxval = 150, group = gD)
staleKeep = input.int(0, "Keep unreclaimed wicks on chart for N extra candles past the longest horizon", minval = 0, maxval = 2000, group = gD)
lblOffset = input.int(4, "Label offset (bars to the right)", minval = 0, group = gD)
showHist  = input.bool(true, "Mark past outcomes (tick = reclaimed, number = candles taken, x = not reclaimed)", group = gD)
showTable = input.bool(true, "Show stats table", group = gD)
tblPosIn  = input.string("Top right", "Table position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = gD)
tblSizeIn = input.string("Small", "Table text", options = ["Tiny", "Small", "Normal"], group = gD)
upCol     = input.color(#26a69a, "Upper wick (upside target)", group = gD)
dnCol     = input.color(#ef5350, "Lower wick (downside target)", group = gD)
 
// ---------- Constants / guards -------------------------------------------------------
int NB     = 5
int maxH   = math.max(h1, h2, h3, h4, h5)
int expire = maxH + staleKeep
int tfSec  = timeframe.in_seconds(tfIn)
 
if timeframe.in_seconds() > tfSec
    runtime.error("Chart timeframe must be equal to or lower than the wick timeframe.")
 
// ---------- Types --------------------------------------------------------------------
type Wick
    int   t                 // open time of the wick candle
    int   idx               // index of the wick candle on the wick timeframe
    bool  isUp
    float tip
    float base
    float level             // price that counts as "reclaimed"
    float sizeAtr
    int   bucket
    bool  inSample
    int   reclaimAge = 0    // candles taken to reclaim; 0 = still open
    bool  isVec = false     // wick candle was a PVSRA vector candle
 
type Dist
    array<int> h            // h[n] = wicks reclaimed on candle n after the wick candle
    int        n = 0        // wicks that have lived through the longest horizon
 
method cum(Dist d, int a) =>
    int s = 0
    int top = math.min(a, d.h.size() - 1)
    if top >= 1
        for i = 1 to top
            s += d.h.get(i)
    s
 
method pct(Dist d, int a) =>
    d.n > 0 ? 100.0 * d.cum(a) / d.n : na
 
// Chance of reclaim by candle H, given the wick is still open after a full candles
method condPct(Dist d, int a, int H) =>
    int surv = d.n - d.cum(a)
    surv > 0 ? 100.0 * (d.cum(H) - d.cum(a)) / surv : na
 
// Median reclaim candle among wicks reclaimed after candle a (and by H)
method medAfter(Dist d, int a, int H) =>
    int res = na
    int tot = d.cum(H) - d.cum(a)
    if tot > 0 and a < H
        int run = 0
        for i = a + 1 to H
            run += d.h.get(i)
            if na(res) and run * 2 >= tot
                res := i
    res
 
// ---------- State --------------------------------------------------------------------
var array<Wick> wicks = array.new<Wick>()
var array<Dist> dists = array.new<Dist>()
if barstate.isfirst
    for i = 0 to 2 * NB - 1
        dists.push(Dist.new(array.new_int(maxH + 1, 0)))
 
var float hO = na
var float hH = na
var float hL = na
var float hC = na
var int   hT = na
var int   htfIdx = 0
var float atr = na
var int   atrN = 0
var float prevC = na
 
// PVSRA state (volume source mirrors the PVSRA Candles Auto Override indicator)
var Dist vecD  = Dist.new(array.new_int(maxH + 1, 0))
var Dist normD = Dist.new(array.new_int(maxH + 1, 0))
var array<float> volHist = array.new_float()
var array<float> wvHist  = array.new_float()
var float hV = na
var float pH = na
var float pL = na
 
string perpSym = "BINANCE:" + syminfo.basecurrency + syminfo.currency + ".P"
string volSym  = forceSym ? symIn : (usePerp and syminfo.type == "crypto") ? perpSym : syminfo.tickerid
[vS, hS, lS] = request.security(volSym, timeframe.period, [volume, high, low], ignore_invalid_symbol = true)
float vBar = na(vS) ? nz(volume) : vS
float hBar = na(vS) ? high : hS
float lBar = na(vS) ? low : lS
 
// ---------- Helpers ------------------------------------------------------------------
bucketOf(float s) =>
    s >= e5 ? 4 : s >= e4 ? 3 : s >= e3 ? 2 : s >= e2 ? 1 : s >= e1 ? 0 : -1
 
bucketName(int b) =>
    switch b
        0 => str.tostring(e1) + " - " + str.tostring(e2)
        1 => str.tostring(e2) + " - " + str.tostring(e3)
        2 => str.tostring(e3) + " - " + str.tostring(e4)
        3 => str.tostring(e4) + " - " + str.tostring(e5)
        => str.tostring(e5) + " +"
 
bucketLetter(int b) =>
    switch b
        0 => "A"
        1 => "B"
        2 => "C"
        3 => "D"
        => "E"
 
keyOf(Wick w) =>
    (splitIn and not w.isUp ? NB : 0) + w.bucket
 
fmtDur(int candles) =>
    float hrs = candles * tfSec / 3600.0
    hrs < 48 ? str.tostring(hrs, "#.#") + "h" : str.tostring(hrs / 24, "#.#") + "d"
 
markHist(Wick w, string txt, color c) =>
    if showHist and w.inSample
        label.new(w.t, w.tip, txt, xloc = xloc.bar_time, style = w.isUp ? label.style_label_down : label.style_label_up, color = color.new(c, 100), textcolor = c, size = size.tiny)
 
register(bool isUp, float tip, float base, float atrRef, int t, int idx, bool vec) =>
    float sz = math.abs(tip - base) / atrRef
    int b = bucketOf(sz)
    bool sideOk = sideIn == "Both" or (isUp and sideIn == "Upper only") or (not isUp and sideIn == "Lower only")
    if b >= 0 and sideOk
        bool inS = sampleIn == "All loaded history" or (t >= chart.left_visible_bar_time and t <= chart.right_visible_bar_time)
        wicks.push(Wick.new(t, idx, isUp, tip, base, base + (tip - base) * fillPct / 100, sz, b, inS, isVec = vec))
 
pool(array<int> keys) =>
    Dist p = Dist.new(array.new_int(maxH + 1, 0))
    for k in keys
        Dist d = dists.get(k)
        p.n += d.n
        for i = 1 to maxH
            p.h.set(i, p.h.get(i) + d.h.get(i))
    p
 
// ---------- Build wick-timeframe candles, score matured wicks, register new wicks -----
bool newHtf = timeframe.change(tfIn) or na(hO)
 
if newHtf
    if not na(hO)
        // Candle number htfIdx has just completed.
        // 1) Wicks reaching the longest horizon go into the stats; old ones are dropped.
        int i = wicks.size() - 1
        while i >= 0
            Wick w = wicks.get(i)
            int done = htfIdx - w.idx
            if done == maxH
                if w.inSample
                    Dist d = dists.get(keyOf(w))
                    d.n += 1
                    if w.reclaimAge > 0
                        d.h.set(w.reclaimAge, d.h.get(w.reclaimAge) + 1)
                    Dist cd = w.isVec ? vecD : normD
                    cd.n += 1
                    if w.reclaimAge > 0
                        cd.h.set(w.reclaimAge, cd.h.get(w.reclaimAge) + 1)
                if w.reclaimAge == 0
                    markHist(w, bucketLetter(w.bucket) + "|x", color.gray)
            if (w.reclaimAge > 0 and done >= maxH) or done >= expire
                wicks.remove(i)
            i -= 1
 
        // 2) ATR of the wick timeframe (wick is measured against ATR before its own candle)
        float tr = na(prevC) ? hH - hL : math.max(hH - hL, math.abs(hH - prevC), math.abs(hL - prevC))
        float atrPrev = atr
        atr := na(atr) ? tr : (atr * (atrLen - 1) + tr) / atrLen
        atrN += 1
 
        // 3) PVSRA class of this candle (0 = normal, 150, 200)
        float wv = hV * (pH - pL)
        int va = 0
        if volHist.size() >= 10 and hV > 0
            float avgV = volHist.avg()
            va := (hV >= avgV * 2 or wv >= wvHist.max()) ? 200 : hV >= avgV * 1.5 ? 150 : 0
        volHist.push(hV)
        wvHist.push(wv)
        if volHist.size() > 10
            volHist.shift()
            wvHist.shift()
        bool pass = candleIn == "All candles" or (candleIn == "Vector candles (150% + 200%)" and va >= 150) or (candleIn == "200% vectors only" and va == 200) or (candleIn == "150% vectors only" and va == 150)
 
        // 4) Register this candle's wicks
        if atrN > atrLen and atrPrev > 0 and pass
            float bodyTop = math.max(hO, hC)
            float bodyBot = math.min(hO, hC)
            register(true,  hH, bodyTop, atrPrev, hT, htfIdx, va >= 150)
            register(false, hL, bodyBot, atrPrev, hT, htfIdx, va >= 150)
 
        prevC := hC
        htfIdx += 1
 
    hO := open
    hH := high
    hL := low
    hT := time
    hV := vBar
    pH := hBar
    pL := lBar
else
    hH := math.max(hH, high)
    hL := math.min(hL, low)
    hV += vBar
    pH := math.max(pH, hBar)
    pL := math.min(pL, lBar)
hC := close
 
// ---------- Reclaim check on every chart bar -----------------------------------------
if wicks.size() > 0
    for w in wicks
        if w.reclaimAge == 0
            bool hit = w.isUp ? high >= w.level : low <= w.level
            if hit
                w.reclaimAge := htfIdx - w.idx
                if w.reclaimAge <= maxH
                    int med = dists.get(keyOf(w)).medAfter(0, maxH)
                    bool onTime = na(med) or w.reclaimAge <= med
                    markHist(w, bucketLetter(w.bucket) + "|✓" + str.tostring(w.reclaimAge), onTime ? color.new(#26a69a, 0) : color.new(#ffb74d, 0))
 
// ---------- Drawing (last bar only) --------------------------------------------------
var array<box>   bxs = array.new<box>()
var array<line>  lns = array.new<line>()
var array<label> lbs = array.new<label>()
var table tbl = na
 
heat(float p) =>
    na(p) ? color.new(color.gray, 70) : color.from_gradient(p, 30, 90, color.new(#ef5350, 45), color.new(#26a69a, 25))
 
if barstate.islast
    // Pooled distributions
    array<int> allKeys = array.new_int()
    for k = 0 to 2 * NB - 1
        allKeys.push(k)
    Dist allD = pool(allKeys)
    Dist upAll = pool(array.from(0, 1, 2, 3, 4))
    Dist dnAll = pool(array.from(5, 6, 7, 8, 9))
 
    array<int> openCnt = array.new_int(2 * NB, 0)
 
    // ----- open wick markup -----
    for b in bxs
        b.delete()
    for l in lns
        l.delete()
    for l in lbs
        l.delete()
    bxs.clear()
    lns.clear()
    lbs.clear()
 
    int xR = time + lblOffset * timeframe.in_seconds() * 1000
    int shown = 0
    int j = wicks.size() - 1
    while j >= 0
        Wick w = wicks.get(j)
        j -= 1
        if w.reclaimAge != 0
            continue
        int k = keyOf(w)
        int survived = htfIdx - w.idx - 1           // full candles survived unreclaimed
        bool stale = survived >= maxH
        if not stale
            openCnt.set(k, openCnt.get(k) + 1)
        if not showOpen or shown >= maxShow
            continue
        shown += 1
 
        Dist d = dists.get(k)
        bool fallback = d.n < minSample
        if fallback
            d := splitIn ? (w.isUp ? upAll : dnAll) : allD
        float chance = stale ? na : d.condPct(survived, maxH)
        int   med    = stale ? na : d.medAfter(survived, maxH)
        int   left   = maxH - survived
 
        color base = w.isUp ? upCol : dnCol
        color c = stale or na(chance) ? color.gray : color.from_gradient(chance, 15, 85, color.new(base, 65), color.new(base, 0))
 
        string arrow = (w.isUp ? "▲ " : "▼ ") + bucketLetter(w.bucket) + "|"
        string txt = stale ? arrow + str.tostring(w.sizeAtr, "#.##") + "x  stale" : arrow + str.tostring(w.sizeAtr, "#.##") + "x  " + (na(chance) ? "n/a" : str.tostring(chance, "#") + "%" + (fallback ? "*" : "")) + (na(med) ? "" : "  ~" + fmtDur(med - survived))
        string tip = "Wick size: " + str.tostring(w.sizeAtr, "#.##") + " ATR (bucket " + bucketName(w.bucket) + ")" + "\nReclaim level: " + str.tostring(w.level, format.mintick) + "\nOpen for " + str.tostring(survived) + " full candles" + (stale ? "\nPast the longest horizon (" + str.tostring(maxH) + " candles)" : "\nChance of reclaim within the next " + str.tostring(left) + " candles: " + (na(chance) ? "n/a" : str.tostring(chance, "#.#") + "%") + (na(med) ? "" : "\nTypical time left when it does reclaim: " + str.tostring(med - survived) + " candles (" + fmtDur(med - survived) + ")") + "\nBased on " + str.tostring(d.n) + " past wicks" + (fallback ? " (all sizes, bucket sample too small)" : ""))
 
        bxs.push(box.new(w.t, math.max(w.tip, w.base), xR, math.min(w.tip, w.base), xloc = xloc.bar_time, border_color = color.new(c, 30), border_width = 1, bgcolor = color.new(base, 88)))
        lns.push(line.new(w.t, w.level, xR, w.level, xloc = xloc.bar_time, color = c, width = 1, style = line.style_dashed))
        lbs.push(label.new(xR, w.level, txt, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(c, 20), textcolor = color.white, size = size.small, tooltip = tip))
 
    // ----- stats table -----
    if showTable
        string pos = switch tblPosIn
            "Top right"    => position.top_right
            "Bottom right" => position.bottom_right
            "Top left"     => position.top_left
            => position.bottom_left
        string ts = tblSizeIn == "Tiny" ? size.tiny : tblSizeIn == "Small" ? size.small : size.normal
        array<int> hz = array.from(h1, h2, h3, h4, h5)
        int nRows = (splitIn ? 2 * NB : NB) + 5
        int nCols = 9
        if not na(tbl)
            tbl.delete()
        tbl := table.new(pos, nCols, nRows, bgcolor = color.new(#131722, 10), border_color = color.new(color.gray, 70), border_width = 1, frame_color = color.gray, frame_width = 1)
 
        color hdrBg = color.new(#2a2e39, 0)
        color txC = color.white
        string tfLbl = str.tostring(tfSec / 3600.0, "#.##") + "h"
 
        tbl.cell(0, 0, "Wick reclaim | " + syminfo.ticker + " | " + tfLbl + " wicks | " + candleIn + " | depth " + str.tostring(fillPct) + "% | % reclaimed within N candles", text_color = txC, bgcolor = hdrBg, text_size = ts, text_halign = text.align_left)
        tbl.merge_cells(0, 0, nCols - 1, 0)
 
        tbl.cell(0, 1, "Wick / ATR", text_color = txC, bgcolor = hdrBg, text_size = ts)
        tbl.cell(1, 1, "n", text_color = txC, bgcolor = hdrBg, text_size = ts)
        for c = 0 to 4
            tbl.cell(2 + c, 1, "≤" + str.tostring(hz.get(c)) + " (" + fmtDur(hz.get(c)) + ")", text_color = txC, bgcolor = hdrBg, text_size = ts)
        tbl.cell(7, 1, "Median", text_color = txC, bgcolor = hdrBg, text_size = ts)
        tbl.cell(8, 1, "Open", text_color = txC, bgcolor = hdrBg, text_size = ts)
 
        int r = 2
        int nKeys = splitIn ? 2 * NB : NB
        for k = 0 to nKeys - 1
            Dist d = dists.get(k)
            string nm = (splitIn ? (k < NB ? "▲ " : "▼ ") : "") + bucketLetter(k % NB) + " | " + bucketName(k % NB)
            tbl.cell(0, r, nm, text_color = txC, text_size = ts, text_halign = text.align_left)
            tbl.cell(1, r, str.tostring(d.n), text_color = d.n < minSample ? color.gray : txC, text_size = ts)
            for c = 0 to 4
                float p = d.pct(hz.get(c))
                tbl.cell(2 + c, r, na(p) ? "-" : str.tostring(p, "#") + "%", text_color = txC, bgcolor = heat(p), text_size = ts)
            int m = d.medAfter(0, maxH)
            tbl.cell(7, r, na(m) ? "-" : str.tostring(m) + "c / " + fmtDur(m), text_color = txC, text_size = ts)
            tbl.cell(8, r, str.tostring(openCnt.get(k)), text_color = txC, text_size = ts)
            r += 1
 
        // All sizes row (the asset's baseline)
        tbl.cell(0, r, "All sizes", text_color = txC, bgcolor = hdrBg, text_size = ts, text_halign = text.align_left)
        tbl.cell(1, r, str.tostring(allD.n), text_color = txC, bgcolor = hdrBg, text_size = ts)
        for c = 0 to 4
            float p = allD.pct(hz.get(c))
            tbl.cell(2 + c, r, na(p) ? "-" : str.tostring(p, "#") + "%", text_color = txC, bgcolor = heat(p), text_size = ts)
        int mAll = allD.medAfter(0, maxH)
        tbl.cell(7, r, na(mAll) ? "-" : str.tostring(mAll) + "c / " + fmtDur(mAll), text_color = txC, bgcolor = hdrBg, text_size = ts)
        tbl.cell(8, r, str.tostring(openCnt.sum()), text_color = txC, bgcolor = hdrBg, text_size = ts)
        r += 1
 
        // Verdict row: do big wicks really get reclaimed more often than small ones?
        Dist small = pool(array.from(0, 1, NB, NB + 1))
        Dist big   = pool(array.from(3, 4, NB + 3, NB + 4))
        float pS = small.pct(h3)
        float pB = big.pct(h3)
        string verdict = "Not enough data for a big vs small comparison"
        color vCol = color.gray
        if not na(pS) and not na(pB) and small.n >= minSample and big.n >= minSample
            float diff = pB - pS
            verdict := "Big (≥" + str.tostring(e4) + " ATR, n=" + str.tostring(big.n) + ") vs small (<" + str.tostring(e3) + " ATR, n=" + str.tostring(small.n) + ") within " + str.tostring(h3) + " candles: " + str.tostring(pB, "#") + "% vs " + str.tostring(pS, "#") + "% (" + (diff >= 0 ? "+" : "") + str.tostring(diff, "#.#") + " pts) = " + (diff > 5 ? "bigger wicks ARE reclaimed more often here" : diff < -5 ? "bigger wicks are reclaimed LESS often here" : "no real size effect here")
            vCol := diff > 5 ? color.new(#26a69a, 30) : diff < -5 ? color.new(#ef5350, 30) : color.new(color.gray, 40)
        tbl.cell(0, r, verdict, text_color = txC, bgcolor = vCol, text_size = ts, text_halign = text.align_left)
        tbl.merge_cells(0, r, nCols - 1, r)
        r += 1
 
        // Volume row: do wicks on PVSRA vector candles get reclaimed more often than on normal candles?
        if candleIn == "All candles"
            float pV = vecD.pct(h3)
            float pN = normD.pct(h3)
            string vTxt = "Not enough data for a vector vs normal candle comparison"
            color vc2 = color.gray
            if not na(pV) and not na(pN) and vecD.n >= minSample and normD.n >= minSample
                float df = pV - pN
                vTxt := "Vector candles (n=" + str.tostring(vecD.n) + ") vs normal candles (n=" + str.tostring(normD.n) + ") within " + str.tostring(h3) + " candles: " + str.tostring(pV, "#") + "% vs " + str.tostring(pN, "#") + "% (" + (df >= 0 ? "+" : "") + str.tostring(df, "#.#") + " pts) = " + (df > 5 ? "vector wicks ARE reclaimed more often here" : df < -5 ? "vector wicks are reclaimed LESS often here" : "no real volume effect here")
                vc2 := df > 5 ? color.new(#26a69a, 30) : df < -5 ? color.new(#ef5350, 30) : color.new(color.gray, 40)
            tbl.cell(0, r, vTxt, text_color = txC, bgcolor = vc2, text_size = ts, text_halign = text.align_left)
            tbl.merge_cells(0, r, nCols - 1, r)

← 返回列表