YURI Pullback Ledger Engine

yuri_zyt · study · 378 行 · 点赞 5 · 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/
// © yuri_zyt
 
//@version=6
indicator("YURI Pullback Ledger Engine", "YURI PLE", overlay = false, precision = 1)
 
// This file counts declines. Not trends, not regimes, not the recoveries that
// follow one: the down-legs themselves, each measured from the peak it started
// at to the weakest close it reached.
//
// Two facts about a finished decline stop being legible once price moves on.
// How far down it travelled, and how many bars it spent getting to the bottom.
// Both are appended to a list here, for every decline the loaded history holds,
// and the decline currently running is then ranked against those lists. The
// lists are accumulated as the chart is walked and are not obtainable from the
// price on any single bar.
//
//   delimiting   One threshold does both edges. A decline opens once the close
//                sits that percentage under the running peak and closes once the
//                close recovers that percentage above the weakest close it made.
//                The next peak is then the strongest close since that floor, not
//                whichever bar tripped the recovery, so the machine cannot close
//                a decline and immediately reopen one a bar later.
//   reporting    Each percentile is printed with the size of the list behind it
//                and a binomial standard error in percentile points, and the
//                drop percentile carries a one-error band.
//
// Keeping two numbers rather than one has to be earned, and it was tested three
// ways before either was plotted. Rank correlation over the 487 ledgered
// declines of a 24796 bar S&P 500 index history: +0.33. Over the 7520 bars of
// that history where both print: +0.41. The level at which one of the two would
// have been deleted was fixed at 0.8 beforehand.
//
// Rank correlation alone would not settle it, because a folded relation such as
// the absolute value of twice x minus a hundred ranks near zero while still
// being an exact formula. So the pair was attacked algebraically as well: of
// four candidate closed forms, the best still fails to reproduce one percentile
// from the other by 94 points somewhere on the history. Then a shape-free test:
// sort the bars into twenty groups by one percentile and about 90% of the
// other's spread survives inside those groups, in both directions. Run that
// same test on a genuine near-identity, a percentile against the raw number it
// ranks, and only 18% survives, which is the control that makes the 90% mean
// something.
//
// Ranking is a relabelling and this file says so rather than dressing it up.
// Each percentile ranks against its own raw input at +0.99 and +0.96. Nothing
// is reordered; what is added is the reference list. Against the comparison a
// price chart already supplies, the distance below the highest close loaded,
// the two come out at -0.24 and -0.06.
//
// One conditioning was tried and failed its own test, which is worth more than
// the conditioning would have been. Sort the declines by whether the peak they
// began at was the strongest close loaded so far. On the S&P history the split
// looks solid: 103 declines from a high-water peak drop 6.2% over 16 bars
// against 384 from a lower peak at 7.7% over 13, p = 4.4e-05 on drop and 0.008
// on duration.
//
// Nearly all of it is volatility. A threshold in percent trips more slowly when
// daily moves are small, and high-water declines occur in quieter tape, 14.4%
// annualised against 17.4%. Split the declines into three volatility bands and
// the duration difference is absent from every one, worst p 0.28; the drop
// difference falls to 0.021, failing a correction for three tests, so a residual
// is possible but unestablished. Since the mechanism is volatility, the two
// differences should run opposite, and they do on all five instruments whose
// volatility difference reaches a point. The one instrument with an inverted
// volatility ordering is correspondingly the one whose declines reach their
// floor sooner. A sixth has a 0.9 point volatility difference and a duration
// difference of exactly zero, so it settles nothing and is claimed for nothing.
//
// The ledger is therefore undivided and every percentile is read against all
// finished declines. The label is still shown for the running decline, because
// which peak a decline began at is an observation, and printing a fact while
// refusing to condition on it is not the same as concealing it.
//
// The first decline to finish is discarded rather than kept. Its peak is merely
// the strongest close since the chart's opening bar with no confirmed floor in
// front of it, so on a history beginning mid-decline that peak belongs to the
// start date. One per chart, and both the discard and the tally are on screen.
//
// On sample size and on the ceiling. Twenty observations do not support what
// five hundred support: the error near the middle is 11.2 points at twenty and
// 2.3 at the 487 that index history yields. The list also has a ceiling, and a
// ceiling nobody is told about would be worse than none, so the number evicted
// is reported in the table and not only in the data panel. At the default it
// does not engage on any history tested. Tighten the threshold and it does: at 3%
// that history finishes 694 declines and evicts the oldest 193, after which the
// list describes recent history instead of all of it.
//
// On timing. Only closes count, and only from bars that have finished. The live
// bar moves while it trades and fixes at its close; bars behind it are not
// revised. Within one decline both quantities only increase, since the weakest
// close cannot recover and the bar holding it cannot move earlier, so a
// percentile printed mid-decline is a floor on the final one. It rises, does
// not retreat, and holds steady once the weakest close stops making new lows while
// the recovery runs. Nothing outside this symbol is requested and no windowed
// statistic is computed, so no second trading calendar can drift out of step.
//
// What this does not do is say anything about what follows a decline of any
// depth or age. There is no signal, no entry, no exit, no filter and no alert.
 
// Falls ------------------------------------------------------------------------
// Sweeping the threshold in tenths, 4 percent is the tightest value at which
// the list ceiling below stays out of the way on the longest history tested;
// every value from 3.0 to 3.9 evicts something. That criterion is blind to any
// result this file produces, touching no correlation, no p value and no median,
// and it is relative to the ceiling setting rather than a fact about markets:
// raise the ceiling and a tighter value would qualify. The range is wide and the
// description tabulates what moving it does.
dipPct = input.float(4.0, "A fall is a drop of, percent", minval = 0.5, maxval = 50.0, step = 0.5, group = "Falls", tooltip = "One threshold, both edges. The decline closes when the close recovers this same percentage above the weakest close the decline produced, which keeps the definition symmetric.")
 
// Ledger -----------------------------------------------------------------------
maxEvents = input.int(500, "Falls the ledger holds", minval = 20, maxval = 2000, group = "Ledger", tooltip = "When the list fills, the oldest entry leaves. How many have left is shown in the table as well as the data panel, since a ceiling nobody is told about would be worse than none. If this is set under the minimum below, the minimum gives way to it.")
minEvents = input.int(20, "Completed falls before the ledger reads", minval = 5, maxval = 250, group = "Ledger", tooltip = "Under twenty observations a percentile can only land on coarse steps, while its error around the middle already spans eleven points.")
 
// Display ----------------------------------------------------------------------
showTable = input.bool(true, "Show readout", group = "Display")
showDepth = input.bool(true, "Draw the depth percentile", group = "Display")
showBars  = input.bool(true, "Draw the length percentile", group = "Display")
showBand  = input.bool(true, "Draw the sampling error band on the depth percentile", group = "Display")
showBg    = input.bool(true, "Tint the pane while a fall is open", group = "Display")
 
// How much of a list falls at or beneath a given value, in percent. The size
// test wrapping the loop is not tidiness. Pine reads "for i = 0 to n - 1" on an
// empty array as a descending loop from 0 down to -1, so it executes twice and
// the second pass indexes -1. The test is what stops that.
f_share(array<float> a, float v) =>
    int n = array.size(a)
    int c = 0
    if n > 0
        for i = 0 to n - 1
            if array.get(a, i) <= v
                c += 1
    n > 0 ? c * 100.0 / n : na
 
// The middle value, obtained by sorting a duplicate of the list. A builtin
// would hide how ties and even counts are handled; written out, both are on the
// page and can be reproduced exactly by anything checking this file.
f_median(array<float> a) =>
    int n = array.size(a)
    float out = na
    if n > 0
        array<float> tmp = array.copy(a)
        array.sort(tmp, order.ascending)
        int h = int(math.floor(n / 2.0))
        out := n % 2 == 1 ? array.get(tmp, h) : (array.get(tmp, h - 1) + array.get(tmp, h)) / 2.0
    out
 
// Standard error of a proportion, expressed in percentile points. At exactly 0
// or exactly 100 it returns nothing instead of returning zero. Those two values
// mean the whole list fell on one side of the reading, which describes where the
// list ran out rather than an observation that happens to be perfectly precise.
f_se(float p, int n) =>
    float out = na
    if n > 0 and not na(p) and p > 0.0 and p < 100.0
        out := math.sqrt(p / 100.0 * (1.0 - p / 100.0) / n) * 100.0
    out
 
// Durations are counted in bars, so a bar has to mean something stable and has
// to cover a session at minimum. Drop below that and the running peak becomes an
// intraday print, turning the list into a record of intraday noise; that is a
// decision about what this file is for, not an assertion about what arithmetic
// can manage, and it is declined by name rather than answered with a number.
// Charts of two, three or five days per bar are fine, since everything is
// expressed in bars and such a chart is compared against a list assembled from
// bars of identical size.
//
// Synthetic-price charts are declined ahead of everything else. On Heikin Ashi,
// Renko, Kagi, Line Break, Point and Figure and Range charts the close is a
// manufactured figure rather than a price that changed hands. The danger is that
// this failure is silent: every other condition would be met, the status line
// would report normally, and the lists would accumulate declines belonging to
// price action that did not happen. Heikin Ashi is the worst of them, since an
// average suppresses exactly the extremes being counted here.
bool stdOk   = chart.is_standard
bool tfOk    = not timeframe.isseconds and not timeframe.isticks and not timeframe.isintraday
bool priceOk = not na(close) and close > 0.0
bool dataOk  = stdOk and tfOk and priceOk
 
// The machine. runMax is the highest close the chart has loaded and exists only
// to label a fall's peak; pk is the peak of the current segment and is seeded
// from the previous fall's recovery high, so the two are different quantities and
// are deliberately not shared.
var float runMax    = na
var float pk        = na
var int   pkB       = 0
var bool  dOpen     = false
var float tro       = na
var int   troB      = 0
var float pHi       = na
var int   pHiB      = 0
var bool  curHw     = false
var bool  firstDone = false
var int   evCount   = 0
var int   dropFirst = 0
var int   capDrops  = 0
var int   totBars   = 0
var int   heldBars  = 0
 
var array<float> lgDepth = array.new<float>()
var array<float> lgBars  = array.new<float>()
 
if dataOk
    totBars += 1
    if na(runMax)
        runMax := close
        pk     := close
        pkB    := bar_index
    if close > runMax
        runMax := close
    if not dOpen
        if close > pk
            pk  := close
            pkB := bar_index
        if close <= pk * (1.0 - dipPct / 100.0)
            dOpen := true
            tro   := close
            troB  := bar_index
            pHi   := close
            pHiB  := bar_index
            // The label is read here, on the bar the fall is confirmed, and is
            // not revisited afterwards. pk is a close that has already been seen and the
            // running high cannot have moved while price was falling, so this is
            // an exact equality rather than a comparison of two near numbers.
            curHw   := pk >= runMax
            evCount += 1
    else
        // The post-low high is tracked separately from the low so that the next
        // peak is the highest close since that low rather than wherever the
        // recovery happened to be confirmed.
        if close < tro
            tro  := close
            troB := bar_index
            pHi  := close
            pHiB := bar_index
        else if close > pHi
            pHi  := close
            pHiB := bar_index
        if close >= tro * (1.0 + dipPct / 100.0)
            if not firstDone
                firstDone := true
                dropFirst += 1
            else
                array.push(lgDepth, (1.0 - tro / pk) * 100.0)
                array.push(lgBars, (troB - pkB) * 1.0)
                if array.size(lgDepth) > maxEvents
                    array.shift(lgDepth)
                    array.shift(lgBars)
                    capDrops += 1
            dOpen := false
            pk    := pHi
            pkB   := pHiB
else if stdOk and tfOk
    heldBars += 1
 
// This bar's reading. Neither quantity can decrease inside a decline: the
// weakest close cannot recover, and the bar carrying it cannot move earlier.
int  nLedger  = array.size(lgDepth)
bool hasDip   = dataOk and dOpen
// The two list settings can be set against each other: demand 210 finished
// declines while capping the list at 20 and the requirement outruns the list, so
// nothing would ever print and the status line would claim to be filling for
// ever. The requirement therefore yields to the ceiling. Both figures belong to
// the user; this only resolves the combination that otherwise has no outcome.
int  minEff   = math.min(minEvents, maxEvents)
bool ledgerOk = hasDip and nLedger >= minEff
 
float curDepth = hasDip ? (1.0 - tro / pk) * 100.0 : na
float curBars  = hasDip ? (troB - pkB) * 1.0 : na
 
// A single sweep of each list, performed only when something will be displayed.
// f_share touches an array and computes nothing windowed, so placing the call
// behind a condition costs it no history. Putting a windowed builtin behind a
// condition would be a different matter entirely, and none is used here.
float depthShare = na
float barsShare  = na
if ledgerOk
    depthShare := f_share(lgDepth, curDepth)
    barsShare  := f_share(lgBars, curBars)
 
float depthSe = f_se(depthShare, nLedger)
float barsSe  = f_se(barsShare, nLedger)
 
float depthLo = not na(depthSe) ? math.max(depthShare - depthSe, 0.0) : na
float depthHi = not na(depthSe) ? math.min(depthShare + depthSe, 100.0) : na
 
// Three distances, for the readout. Measured respectively against the strongest
// close the chart has loaded, against the peak the current stretch started from,
// and against the weakest close of the decline now running.
float offHigh = dataOk and not na(runMax) ? (close / runMax - 1.0) * 100.0 : na
float offPeak = dataOk and not na(pk) ? (close / pk - 1.0) * 100.0 : na
float offTro  = hasDip and not na(tro) ? (close / tro - 1.0) * 100.0 : na
int   dipAge  = hasDip ? bar_index - pkB : 0
 
// Each reason for the absence of a reading is spelled out, in test order. The
// three declines come first, then the ordinary condition of having no decline
// running, which is not a failure of anything. Insufficient list size is last,
// since it only becomes relevant once there is something to rank.
string statusText = not stdOk ? "needs a standard chart, this one is built from synthetic prices" : not tfOk ? "needs a chart of one day a bar or longer" : not priceOk ? "needs a series whose close is above zero" : not dOpen ? "no fall of " + str.tostring(dipPct, "0.#") + "% in progress, " + str.tostring(offPeak, "0.0") + "% off the last peak" : nLedger < minEff ? "a fall is in progress, the ledger holds " + str.tostring(nLedger) + " of " + str.tostring(minEff) + " completed falls" : "ok"
 
// The pane. Drop is drawn heavy because depth is the question this file is put
// to; the line rises while the decline extends, levels off once the weakest close
// stops falling, and ends with the decline, which is why its stepped and broken
// appearance is correct rather than a rendering fault. Its band spans one
// standard error either way, clipped to the pane. Duration is drawn thin but is
// not ornament: of the two it is the harder to infer from the distance below the
// highest close, which the chart shows for nothing.
plBandLo = plot(showBand and showDepth ? depthLo : na, "Depth percentile, one SE below", color.new(color.purple, 70), 1)
plBandHi = plot(showBand and showDepth ? depthHi : na, "Depth percentile, one SE above", color.new(color.purple, 70), 1)
fill(plBandLo, plBandHi, dataOk and showBand and showDepth ? color.new(color.purple, 85) : na)
 
plot(showDepth ? depthShare : na, "Fall depth percentile", color.new(color.purple, 0), 2)
plot(showBars ? barsShare : na, "Fall length percentile", color.new(color.orange, 0), 1)
 
hline(50, "Middle", color.new(color.gray, 80), hline.style_dotted)
hline(100, "Top", color.new(color.gray, 90))
hline(0, "Bottom", color.new(color.gray, 90))
 
bgcolor(showBg and hasDip ? color.new(color.blue, 92) : na)
 
// Each of these carries its own condition explicitly. Several are nothing but
// arithmetic over a counter and would otherwise come through a declined chart
// looking entirely plausible, which is the sort of failure worth spelling out
// instead of trusting to luck. What survives a declined chart is the three fixed
// guides above, which take constants, plus the caption column of the table.
// Every reported value becomes a dash.
plot(offHigh, "Percent off the high in view", display = display.data_window)
plot(offPeak, "Percent off the last peak", display = display.data_window)
plot(offTro, "Percent off this fall's low", display = display.data_window)
plot(curDepth, "This fall, percent", display = display.data_window)
plot(curBars, "This fall, bars to its low", display = display.data_window)
plot(hasDip ? dipAge * 1.0 : na, "Bars since this fall's peak", display = display.data_window)
plot(hasDip ? (curHw ? 1.0 : 0.0) : na, "This fall began at a high in view", display = display.data_window)
plot(hasDip ? nLedger * 1.0 : na, "Completed falls in the ledger", display = display.data_window)
plot(dataOk ? evCount * 1.0 : na, "Falls seen", display = display.data_window)
plot(dataOk ? dropFirst * 1.0 : na, "Falls dropped as the first on the chart", display = display.data_window)
plot(dataOk ? capDrops * 1.0 : na, "Falls pushed out by the ledger cap", display = display.data_window)
plot(dataOk ? totBars * 1.0 : na, "Bars read", display = display.data_window)
plot(dataOk ? heldBars * 1.0 : na, "Bars skipped for a bad close", display = display.data_window)
plot(depthSe, "Depth percentile, standard error", display = display.data_window)
plot(barsSe, "Length percentile, standard error", display = display.data_window)
 
// The format specifiers are "0" and "0.0" instead of "#". A "#" drops a solitary
// zero, which would leave a cell showing a bare percent sign with no figure in
// front of it. Zero is a value both percentiles genuinely reach, whenever the
// running decline is shallower or briefer than every finished one on record.
string hiTxt    = not dataOk ? "-" : str.tostring(offHigh, "0.0") + "% off the high in view"
string curTxt   = not hasDip ? "-" : "-" + str.tostring(curDepth, "0.0") + "% over " + str.tostring(curBars, "0") + " bars, " + (curHw ? "from a high in view" : "from a peak under an earlier high")
string depthTxt = not hasDip ? "-" : not ledgerOk ? "ledger holds " + str.tostring(nLedger) + " of " + str.tostring(minEff) : na(depthSe) ? "deeper than " + str.tostring(depthShare, "0") + "% of " + str.tostring(nLedger) : "deeper than " + str.tostring(depthShare, "0") + "% of " + str.tostring(nLedger) + ", +/- " + str.tostring(depthSe, "0.0")
string barsTxt  = not hasDip ? "-" : not ledgerOk ? "ledger holds " + str.tostring(nLedger) + " of " + str.tostring(minEff) : na(barsSe) ? "longer than " + str.tostring(barsShare, "0") + "% of " + str.tostring(nLedger) : "longer than " + str.tostring(barsShare, "0") + "% of " + str.tostring(nLedger) + ", +/- " + str.tostring(barsSe, "0.0")
string seenTxt  = not dataOk ? "-" : str.tostring(evCount) + " falls seen, " + str.tostring(dropFirst) + " dropped, " + (capDrops > 0 ? str.tostring(capDrops) + " pushed out by the cap, " : "") + str.tostring(totBars) + " bars read"
 
if showTable and barstate.islast
    // Both medians are computed a single time, on the final bar, instead of on
    // every one. Each sorts a duplicate of a list running to hundreds of entries,
    // and no plotted series depends on either.
    float medDepth = f_median(lgDepth)
    float medBars  = f_median(lgBars)
    // Conditioned on the data being usable, not only on the list being empty. A
    // declined chart leaves the list empty regardless, since nothing ran, but a
    // cell that is blank by coincidence will stop being blank the day the
    // coincidence does.
    string pastTxt = not dataOk or nLedger == 0 or na(medDepth) ? "-" : "median -" + str.tostring(medDepth, "0.0") + "% over " + str.tostring(medBars, "0.#") + " bars, from " + str.tostring(nLedger)
 
    var table t = table.new(position.top_right, 2, 7, border_width = 1)
    table.cell(t, 0, 0, "Off the high", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 0, hiTxt, text_color = color.white, text_size = size.small)
    table.cell(t, 0, 1, "This fall", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 1, curTxt, text_color = color.white, bgcolor = hasDip ? color.new(color.blue, 80) : color.new(color.gray, 90), text_size = size.small)
    table.cell(t, 0, 2, "Depth against past", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 2, depthTxt, text_color = color.white, bgcolor = color.new(color.purple, 80), text_size = size.small)
    table.cell(t, 0, 3, "Length against past", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 3, barsTxt, text_color = color.white, text_size = size.small)
    table.cell(t, 0, 4, "Those past falls", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 4, pastTxt, text_color = color.white, text_size = size.small)
    table.cell(t, 0, 5, "Seen so far", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 5, seenTxt, text_color = color.gray, text_size = size.small)
    table.cell(t, 0, 6, "Status", text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 6, statusText, text_color = statusText == "ok" ? color.gray : color.orange, text_size = size.small)

← 返回列表