本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © evawpd141
//@version=6
indicator("YURI Squeeze Ledger Engine", "YURI SLE", overlay = false)
// Bollinger BandWidth is (upper - lower) / basis, and John Bollinger's Squeeze is
// that width sitting at a low of its own recent range. Both are his, from
// Bollinger on Bollinger Bands. John Carter's TTM Squeeze is the other well known
// reading of the same idea and works by testing whether the Bollinger bands have
// moved inside a Keltner channel; this script does not do that and no Keltner
// channel appears in it. The compression test here is the percentile one: the
// width is compressed when it sits below a chosen percentile of its own last N
// bars.
//
// What this adds to that test is a record. A width reading tells you how tight
// the bands are now. It says nothing about how long this symbol has historically
// stayed tight once it got there, which is the other half of looking at a
// compressed chart and the half that needs something kept rather than computed.
//
// So the script keeps a ledger. Every time a run of compressed bars ends, the
// length of that run in bars goes into a tally, and the run that is open right
// now is read against it: this squeeze is N bars old, and N bars is at or above
// P percent of the runs this symbol has completed on the history this chart has
// loaded. The ledger is built from that history and from nothing else.
//
// The second thing it keeps is what the width did after each run ended. For the
// chosen number of bars following a release it records the highest width reached,
// as a multiple of the width on the last compressed bar, and reports the
// distribution of those multiples. That is a size and it carries no direction.
// Nothing here says which way price went, because the width is a two sided
// measure and the script does not look at the sign of anything.
//
// Four things about the ledger decide how much it is worth, and all four are on
// screen:
//
// The open run is right censored. It has not finished, so its final length can
// only be longer than it is now, and the percentile printed for it can only
// move up. It is a lower bound and the table says so.
//
// A run already in progress when the percentile threshold first becomes valid
// has an unknown true start, so it is thrown away rather than counted short.
// The count of discarded runs is printed.
//
// The ledger is built bar by bar from the left edge of whatever history the
// chart has loaded. Load more history and the ledger grows and the percentile
// moves. Two charts of the same symbol with different amounts of history
// loaded do not hold the same ledger.
//
// Runs are disjoint in bars, so unlike a rolling window count these are
// separate observations rather than overlapping ones. They are still not
// independent draws: runs close together in time sit in the same volatility
// regime and resemble each other, so the effective sample is smaller than the
// printed count. The count is printed because it is the ceiling on what the
// reading can be worth, not because it is the effective sample size.
//
// The bar that is forming can enter and leave the ledger as it forms: if it
// closes compressed the open run continues, and if it closes wide the run ends
// and its length is tallied on that bar. Once a bar has closed, what it
// contributed is fixed and no later bar rewrites it.
//
// There is no entry rule here, no exit rule, no direction and no alert. A
// squeeze that is old relative to this symbol's history is a description of the
// present bar, not a statement about the next one.
// Compression ------------------------------------------------------------------
bbLen = input.int(20, "Bollinger length", minval = 5, maxval = 100, group = "Compression", tooltip = "The published Bollinger default. The basis is a simple moving average of close and the width is measured against it.")
bbMult = input.float(2.0, "Bollinger standard deviations", minval = 0.5, maxval = 5.0, step = 0.5, group = "Compression", tooltip = "Scales both bands, so it scales the width and its own percentile threshold by the same factor. Moving it changes the printed width and leaves every bar's compression state exactly where it was, which is checked rather than assumed.")
bwPctile = input.int(15, "Percentile of its own width that counts as compressed", minval = 1, maxval = 50, group = "Compression", tooltip = "15 means the width has to sit below the 15th percentile of the lookback window. Lower makes runs rarer and shorter. This and the shortest run setting are the two that move the tally most; the lookback moves it least.")
bwLookback = input.int(180, "Bars the percentile is taken over", minval = 30, maxval = 1000, group = "Compression", tooltip = "The window the width is ranked against. It includes the current bar, so a bar takes part in setting the threshold it is tested against.")
minRun = input.int(2, "Shortest run that enters the ledger, bars", minval = 1, maxval = 20, group = "Compression", tooltip = "Single bar dips below the threshold are common and are mostly noise. Runs shorter than this are not tallied and do not open a release window.")
// Ledger -----------------------------------------------------------------------
minEpisodes = input.int(10, "Completed runs needed before a percentile is shown", minval = 3, maxval = 200, group = "Ledger", tooltip = "Below this the age percentile and the release row stay empty and the status line says how far along the tally is. A percentile taken over four runs is a number with nothing behind it.")
expWin = input.int(10, "Bars after a release the expansion is measured over", minval = 1, maxval = 60, group = "Ledger", tooltip = "The highest width reached inside this many bars of a release, divided by the width on the last compressed bar. A release arriving while one of these windows is still open is skipped and counted.")
// Display ----------------------------------------------------------------------
showTable = input.bool(true, "Show readout", group = "Display")
showDepth = input.bool(true, "Draw the depth line", group = "Display")
// The compression test, kept as it was written. basis, dev, upper, lower, the
// width and the percentile threshold are the same six lines they were before the
// ledger was put behind them, and the comparison is the same strict one: a bar is
// compressed when its width is below the threshold, not when it equals it. That
// matters at one bar in the window. The threshold is the nearest rank value, so
// it is one of the widths actually observed, and a bar that is itself that
// value is not compressed.
float basis = ta.sma(close, bbLen)
float dev = bbMult * ta.stdev(close, bbLen)
float upper = basis + dev
float lower = basis - dev
float bw = basis != 0.0 ? (upper - lower) / basis : na
float bwThresh = ta.percentile_nearest_rank(bw, bwLookback, bwPctile)
// Two charts are refused, and the first one is the dangerous one.
//
// A non standard chart type, Heikin Ashi, Renko, Kagi, Line Break, Point and
// Figure or Range, hands this script a close that is a construction rather than a
// traded price. Every other test here would pass on one: the timeframe is set, the
// symbol is ordinary, the bars arrive in order. The standard deviation, the width,
// the percentile and the whole tally would be computed on prices at which nothing
// changed hands, and the status line would read ok. That is the failure worth
// refusing loudest, because nothing on screen would look wrong.
//
// A seconds chart is the second, and a tick chart falls to the same line. Everything
// below is counted in bars and carries no calendar conversion, so there is no multi
// day trap here, and a 2D or 3D chart is a legitimate if unusual basis rather than a
// silent error. Sub minute bars are different, and a tick bar has no length at all.
// the width there is dominated by the tick grid and the quote process rather than
// by anything the tally describes, and such a ledger would print full looking numbers.
bool stdOk = chart.is_standard
bool tfOk = not timeframe.isseconds and not timeframe.isticks
// An explicit bar count rather than a test on the threshold being non na. The
// percentile over a partly filled window is a number, and a compression test run
// against it would produce runs that look exactly like finished ones. Nothing
// enters the ledger before the window behind it is full.
bool warm = bar_index >= bbLen - 1 + bwLookback
bool ready = stdOk and tfOk and warm
// The refusal is applied here at the source rather than only at the plots, so a
// refused chart produces no numbers anywhere rather than a table of plausible
// ones under a status line saying it is refused.
float bwR = ready ? bw : na
float bwThreshR = ready ? bwThresh : na
bool isSqBar = ready and not na(bw) and not na(bwThresh) and bw < bwThresh
// Ledger state -----------------------------------------------------------------
// Durations are whole numbers of bars, so the tally is a histogram indexed by
// length rather than a list. Reading the share of runs at or below the open one
// is then a sum over the first few cells instead of a pass over every run ever
// recorded, which is what makes it cheap enough to compute on every compressed
// bar. Runs longer than 300 bars land in the last cell and are counted
// separately; at a 15th percentile threshold such a run would mean the width
// stayed near its own floor for more than a year of daily bars.
var array<int> durHist = array.new_int(301, 0)
var int sqCount = 0
var int nEpisodes = 0
var int longestRun = 0
var int overflowRuns = 0
var int countedBars = 0
var int truncDropped = 0
var int sinceRel = na
var bool priorGap = false
var bool runClean = false
// The release windows. One is open at a time. A release that arrives while a
// window is still open does not start a second one and is counted instead, which
// biases the expansion sample away from rapid re compression: the releases it
// drops are exactly the ones followed quickly by another run. The count is in the
// table for that reason.
var array<float> exps = array.new_float()
var int pendLeft = 0
var float pendBase = na
var float pendMax = na
var int expSkipped = 0
var int expDropped = 0
int prevRun = sqCount
sqCount := isSqBar ? sqCount + 1 : 0
bool released = not isSqBar and prevRun > 0
bool longEnough = released and prevRun >= minRun
bool episodeDone = longEnough and runClean
if longEnough and not runClean
truncDropped := truncDropped + 1
if episodeDone
int b = math.min(prevRun, 300)
array.set(durHist, b, array.get(durHist, b) + 1)
nEpisodes := nEpisodes + 1
if prevRun > longestRun
longestRun := prevRun
if prevRun > 300
overflowRuns := overflowRuns + 1
// Open, then advance, then close, in that order. Advancing first would let a
// release landing on the last bar of an open window overwrite the base before the
// finished window was recorded.
if episodeDone
if pendLeft > 0
expSkipped := expSkipped + 1
else
pendBase := bwR[1]
pendMax := na
pendLeft := expWin
if pendLeft > 0
pendMax := na(pendMax) ? bwR : na(bwR) ? pendMax : math.max(pendMax, bwR)
pendLeft := pendLeft - 1
if pendLeft == 0 and not na(pendBase)
if pendBase > 0.0 and not na(pendMax)
if array.size(exps) < 2000
array.push(exps, pendMax / pendBase)
else
expDropped := expDropped + 1
pendBase := na
pendMax := na
if longEnough
sinceRel := 0
else if not na(sinceRel)
sinceRel := sinceRel + 1
// Housekeeping last, so that the run which ended on this bar was judged against
// the flags as they stood while it was running.
if ready
countedBars := countedBars + 1
if not isSqBar
priorGap := true
if isSqBar and prevRun == 0
runClean := priorGap
// Readings ---------------------------------------------------------------------
bool ledgerOk = ready and nEpisodes >= minEpisodes
// The share of completed runs that were no longer than the open one. This is the
// empirical distribution function evaluated at the current length, and because
// the open run has not finished it can only rise from here.
int durLE = 0
if ledgerOk and isSqBar
int hiBin = math.min(sqCount, 300)
for i = 0 to hiBin
durLE := durLE + array.get(durHist, i)
float durPct = ledgerOk and isSqBar and nEpisodes > 0 ? durLE * 100.0 / nEpisodes : na
// How far the width sits below the threshold, as a percent of the threshold. On a
// compressed bar the width is below the threshold and the width has a floor of
// zero, so this lands between 0 and 100 and shares the axis with the
// percentile above it. It is a ratio rescaled, not a percentile, and the two
// lines are not the same kind of number even though they sit on one scale.
float ratio = na(bwR) or na(bwThreshR) or bwThreshR <= 0.0 ? na : bwR / bwThreshR
float depthPct = isSqBar and not na(ratio) ? (1.0 - ratio) * 100.0 : na
// Ledger summaries, on the last bar only. Quartiles come out of the histogram, so
// they are exact rather than interpolated, and they are whole bars because the
// thing being measured is.
int medDur = na
int q1Dur = na
int q3Dur = na
if barstate.islast and nEpisodes > 0
int cum = 0
for i = 0 to 300
cum := cum + array.get(durHist, i)
if na(q1Dur) and cum * 4 >= nEpisodes
q1Dur := i
if na(medDur) and cum * 2 >= nEpisodes
medDur := i
if na(q3Dur) and cum * 4 >= nEpisodes * 3
q3Dur := i
float expMed = na
float expQ1 = na
float expQ3 = na
float expAvg = na
float expSE = na
int expN = array.size(exps)
if barstate.islast and ledgerOk
if expN >= minEpisodes
expMed := array.percentile_nearest_rank(exps, 50)
expQ1 := array.percentile_nearest_rank(exps, 25)
expQ3 := array.percentile_nearest_rank(exps, 75)
expAvg := array.avg(exps)
expSE := array.stdev(exps) / math.sqrt(expN)
// Plots ------------------------------------------------------------------------
// Both series are drawn only on compressed bars, so the pane is empty between
// runs. That is the shape of the thing: there is no squeeze to describe when
// there is no squeeze. style_linebr keeps the gaps as gaps rather than joining
// the end of one run to the start of the next with a straight line, which would
// invent a reading for every bar in between.
plot(durPct, "Age of the open run, percentile of completed runs", color.new(color.orange, 0), 2, plot.style_linebr)
plot(showDepth ? depthPct : na, "Depth below the threshold, percent of it", color.new(color.aqua, 0), 1, plot.style_linebr)
// Fixed reference. It stays drawn on a chart the script refuses, where every
// series and every value cell is empty, and the description says so.
hline(50, "Median completed run", color = color.new(color.gray, 60), linestyle = hline.style_dotted)
bgcolor(isSqBar ? color.new(color.fuchsia, 90) : na, title = "Compressed bars")
plot(bwR, "Bandwidth", display = display.data_window)
plot(bwThreshR, "Compression threshold", display = display.data_window)
plot(ratio, "Bandwidth over threshold", display = display.data_window)
plot(ready ? sqCount : na, "Bars in the open run", display = display.data_window)
plot(ready ? nEpisodes : na, "Completed runs tallied", display = display.data_window)
plot(ready ? countedBars : na, "Bars the ledger has seen", display = display.data_window)
// Table ------------------------------------------------------------------------
// Every cell carries its own na guard, so a refused chart, a warming chart and a
// thin ledger each blank exactly the cells they invalidate and no others.
string basisTxt = ready ? timeframe.period + " bars, " + str.tostring(countedBars) + " counted since warmup" : "-"
string stateTxt = not ready ? "-" : isSqBar ? "compressed, bar " + str.tostring(sqCount) + " of this run" : na(sinceRel) ? "not compressed, no run recorded yet" : "not compressed, " + str.tostring(sinceRel) + " bars since the last release"
string ageTxt = na(durPct) ? "-" : str.tostring(sqCount) + " bars, at or above " + str.tostring(durPct, "0.0") + "% of " + str.tostring(nEpisodes) + " completed runs, a lower bound"
string widthTxt = na(ratio) ? "-" : str.tostring(bwR, "0.00000") + " against a threshold of " + str.tostring(bwThreshR, "0.00000") + ", " + str.tostring((ratio - 1.0) * 100.0, "0.0") + "% of it"
string ledgeTxt = not ledgerOk or na(medDur) ? "-" : str.tostring(nEpisodes) + " runs, median " + str.tostring(medDur) + " bars, quartiles " + str.tostring(q1Dur) + " and " + str.tostring(q3Dur) + ", longest " + str.tostring(longestRun)
string expTxt = na(expMed) ? "-" : "widest " + str.tostring(expMed, "0.00") + "x the last compressed bar, quartiles " + str.tostring(expQ1, "0.00") + " and " + str.tostring(expQ3, "0.00") + ", mean " + str.tostring(expAvg, "0.00") + " +/- " + str.tostring(expSE, "0.00") + ", n " + str.tostring(expN)
string outTxt = not ready ? "-" : str.tostring(truncDropped) + " runs open before the ledger started, " + str.tostring(expSkipped) + " releases inside an open window, " + str.tostring(overflowRuns) + " runs past 300 bars, " + str.tostring(expDropped) + " releases past the 2000 the sample holds"
string statusText = not stdOk ? "needs a standard chart, this one is built from synthetic prices" : not tfOk ? "needs a chart of one minute or longer" : not warm ? "warming up, " + str.tostring(bar_index) + " of " + str.tostring(bbLen - 1 + bwLookback) + " bars" : na(bw) or na(bwThresh) ? "no width reading on this bar" : nEpisodes < minEpisodes ? "ledger thin, " + str.tostring(nEpisodes) + " of " + str.tostring(minEpisodes) + " completed runs" : "ok"
if showTable and barstate.islast
var table t = table.new(position.top_right, 2, 8, border_width = 1)
table.cell(t, 0, 0, "Ledger basis", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 0, basisTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 1, "Right now", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 1, stateTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 2, "Age against the ledger", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 2, ageTxt, text_color = color.white, bgcolor = color.new(color.orange, 82), text_size = size.small)
table.cell(t, 0, 3, "Width and threshold", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 3, widthTxt, text_color = color.white, bgcolor = color.new(color.aqua, 82), text_size = size.small)
table.cell(t, 0, 4, "Completed runs", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 4, ledgeTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 5, "In the bars after a release", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 5, expTxt, text_color = color.white, text_size = size.small)
table.cell(t, 0, 6, "Left out of the counts", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 6, outTxt, text_color = color.gray, text_size = size.small)
table.cell(t, 0, 7, "Status", text_color = color.gray, text_size = size.small)
table.cell(t, 1, 7, statusText, text_color = statusText == "ok" ? color.gray : color.orange, text_size = size.small)