GatedStats

jabez4jc · library · 293 行 · 点赞 1 · 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/
// © jabez4jc
 
//@version=6
 
// @description Gated statistics: sums, means, event counts and a rolling VWAP that only sample bars where a `gate`
//              condition is true and the value is not `na`. Windows can span the whole history, the last N samples,
//              the last N bars, the time since a reset, or a rolling span of time. `gatedMa()` adds a selectable
//              moving-average type (SMA, EMA, RMA, WMA, SWMA, VWMA) that advances only on sampled bars.
//              Every function keeps internal state, so call each one once per bar, unconditionally.
library("GatedStats")
 
//#region ———————————————————— Private engine
 
// Shared queue behind the last-N-samples and rolling-time functions.
// Samples are pushed only when `gate` is true, but expired samples are evicted on EVERY bar so a time window keeps
// sliding while the gate is false.
// A sample is evicted when the queue holds more than `cap` samples, or when it is at least `ms` old and the queue
// still holds more than `minBars` samples. Pass `ms = na` to disable time-based eviction.
// The running total is rebuilt from the queue every 1000 evictions so float add/subtract drift cannot accumulate.
// Returns [sum, sample count].
windowStats(float source, bool gate, int cap, int ms, int minBars) =>
    var array<float> values  = array.new<float>()
    var array<int>   stamps  = array.new<int>()
    var float        total   = 0.0
    var int          evicted = 0
    int keep = math.max(minBars, 0)
    if gate and not na(source)
        values.push(source)
        stamps.push(time)
        total += source
    while values.size() > cap or (values.size() > keep and not na(ms) and time - stamps.first() >= ms)
        total -= values.shift()
        stamps.shift()
        evicted += 1
    if evicted >= 1000
        total   := values.sum()
        evicted := 0
    [total, values.size()]
 
// Linearly weighted mean of an array, oldest element weight 1, newest element weight `size`.
weightedAvg(array<float> arr) =>
    int   size = arr.size()
    float num  = 0.0
    for i = 0 to size - 1
        num += arr.get(i) * (i + 1)
    num / (size * (size + 1) / 2.0)
 
// Mean of `values` weighted by `wts` (same size arrays). `na` when the weights sum to zero.
weightedByAvg(array<float> values, array<float> wts) =>
    float num = 0.0
    for i = 0 to values.size() - 1
        num += values.get(i) * wts.get(i)
    float den = wts.sum()
    den == 0.0 ? na : num / den
 
//#endregion
 
//#region ———————————————————— Whole-history and anchored averages
 
// @function Mean of `source` over the entire history, sampling only bars where `gate` is true and `source` is not `na`.
// @param source (series float) Values to average.
// @param gate (series bool) Only bars where this is `true` are sampled. Optional. Default is `true`.
// @returns (float) The mean, or `na` until the first sampled bar.
export gatedMean(series float source, series bool gate = true) =>
    var float total = 0.0
    var int   n     = 0
    if gate and not na(source)
        total += source
        n     += 1
    n == 0 ? na : total / n
 
// @function Mean of `source` over all bars (with a non-`na` value) since the latest bar where `reset` is true. The
//           reset bar is included in the new average. Useful for session- or day-anchored averages.
// @param source (series float) Values to average.
// @param reset (series bool) `true` restarts the average on that bar.
// @returns (float) The mean, or `na` before the first reset.
export gatedMeanSince(series float source, series bool reset) =>
    var float total   = 0.0
    var int   n       = 0
    var bool  started = false
    if reset
        total   := 0.0
        n       := 0
        started := true
    if not na(source)
        total += source
        n     += 1
    started and n > 0 ? total / n : na
 
//#endregion
 
//#region ———————————————————— Count- and bar-based windows
 
// @function Mean of the most recent `count` sampled values (bars where `gate` is true and `source` is not `na`).
//           The window always holds exactly `count` samples, however far back they are.
// @param source (series float) Values to average.
// @param gate (series bool) Only bars where this is `true` are sampled.
// @param count (series int) Number of sampled values to average.
// @returns (float) The mean, or `na` until `count` samples exist (or if `count` < 1).
export gatedMeanLast(series float source, series bool gate, series int count) =>
    [total, n] = windowStats(source, gate, count, na, 0)
    count < 1 or n < count ? na : total / n
 
// @function Mean of the sampled values inside the most recent `length` bars. Unlike `gatedMeanLast()`, the window
//           is measured in bars, so it can hold fewer than `length` samples. Use `minSamples` to suppress thin,
//           noisy readings when the gate is rarely true.
// @param source (series float) Values to average.
// @param gate (series bool) Only bars where this is `true` are sampled.
// @param length (series int) Window size, in bars.
// @param minSamples (series int) Minimum sampled bars the window must hold. Optional. Default is 1.
// @returns (float) The mean, or `na` while the window holds fewer than `minSamples` sampled bars.
export gatedMeanInBars(series float source, series bool gate, series int length, series int minSamples = 1) =>
    bool  sampled = gate and not na(source)
    float n       = math.sum(sampled ? 1 : 0, length)
    float total   = math.sum(sampled ? source : 0.0, length)
    n < math.max(minSamples, 1) ? na : total / n
 
// @enum Moving-average types for `gatedMa()`.
// @field sma Simple: equal-weighted mean of the last `length` samples.
// @field ema Exponential: smoothing factor 2 / (length + 1).
// @field rma Wilder's: smoothing factor 1 / length.
// @field wma Linearly weighted: the newest sample has the largest weight.
// @field swma Symmetrically weighted over the last 4 samples (weights 1, 2, 2, 1). Ignores `length`.
// @field vwma Weighted by `weight` (volume by default) over the last `length` samples.
export enum MaType
    sma  = "SMA"
    ema  = "EMA"
    rma  = "RMA"
    wma  = "WMA"
    swma = "SWMA"
    vwma = "VWMA"
 
// @function Moving average that advances only on sampled bars (where `gate` is true and `source` is not `na`) and
//           holds its last value in between. Its `length` counts samples, not bars, so it behaves like `gatedMeanLast()`
//           with a selectable smoothing type. `ema` and `rma` are seeded with the SMA of the first `length` samples.
// @param source (series float) Values to average.
// @param gate (series bool) Only bars where this is `true` are sampled.
// @param length (series int) Number of samples in the average (the smoothing period for `ema` and `rma`). Ignored by
//        `swma`, which always uses 4 samples.
// @param maType (MaType) Moving-average type. Optional. Default is `MaType.ema`.
// @param weight (series float) Weights for `vwma`. Optional. Default is `volume`. Ignored by the other types.
// @returns (float) The moving average, or `na` until enough samples exist (`length`, or 4 for `swma`).
export gatedMa(series float source, series bool gate, series int length, MaType maType = MaType.ema, series float weight = na) =>
    var array<float> window  = array.new<float>()
    var array<float> weights = array.new<float>()
    var float        result  = na
    float w       = na(weight) ? volume : weight
    int   span    = maType == MaType.swma ? 4 : length
    bool  sampled = gate and not na(source) and span >= 1 and (maType != MaType.vwma or not na(w))
    if sampled
        window.push(source)
        weights.push(w)
        while window.size() > span
            window.shift()
            weights.shift()
        if window.size() == span
            result := switch maType
                MaType.sma  => window.avg()
                MaType.wma  => weightedAvg(window)
                MaType.swma => (window.get(0) + 2 * window.get(1) + 2 * window.get(2) + window.get(3)) / 6
                MaType.vwma => weightedByAvg(window, weights)
                MaType.ema  => na(result) ? window.avg() : result + (source - result) * 2.0 / (length + 1)
                MaType.rma  => na(result) ? window.avg() : result + (source - result) / length
    result
 
//#endregion
 
//#region ———————————————————— Rolling time windows
 
// @function Sum of sampled values (bars where `gate` is true and `source` is not `na`) whose opening time is less
//           than `ms` milliseconds before the current bar. The window always keeps at least `minBars` samples.
// @param source (series float) Values to sum.
// @param ms (simple int) Window span, in milliseconds.
// @param gate (series bool) Only bars where this is `true` are sampled. Optional. Default is `true`.
// @param minBars (simple int) Minimum samples to retain regardless of age. Optional. Default is 1.
// @returns (float) The sum, or `na` while fewer than `minBars` samples exist.
export gatedSumTime(series float source, simple int ms, series bool gate = true, simple int minBars = 1) =>
    [total, n] = windowStats(source, gate, 2147483647, ms, minBars)
    n < minBars ? na : total
 
// @function Mean of sampled values over the same rolling time window as `gatedSumTime()`. Useful as a baseline,
//           e.g. relative volume = `volume / gatedMeanTime(volume, ms)`.
// @param source (series float) Values to average.
// @param ms (simple int) Window span, in milliseconds.
// @param gate (series bool) Only bars where this is `true` are sampled. Optional. Default is `true`.
// @param minBars (simple int) Minimum samples to retain regardless of age. Optional. Default is 1.
// @returns (float) The mean, or `na` while fewer than `minBars` samples exist.
export gatedMeanTime(series float source, simple int ms, series bool gate = true, simple int minBars = 1) =>
    [total, n] = windowStats(source, gate, 2147483647, ms, minBars)
    n < minBars or n == 0 ? na : total / n
 
// @function Number of bars where `gate` is true inside the rolling time window. Useful for counting signals, e.g.
//           "no more than 3 buy signals per hour".
// @param gate (series bool) The event to count.
// @param ms (simple int) Window span, in milliseconds.
// @returns (float) The number of `true` bars whose opening time is less than `ms` milliseconds before this bar.
export gatedCountTime(series bool gate, simple int ms) =>
    [total, n] = windowStats(1.0, gate, 2147483647, ms, 0)
    total
 
// @function Rolling volume-weighted average price and weighted standard deviation over a time window.
//           The deviation is measured against the CURRENT window VWAP for every sample in the window, so it is the
//           true weighted standard deviation of the window (a per-bar running estimate would measure each bar
//           against the VWAP that prevailed when it arrived). Both passes run over the window on every bar, so cost
//           grows with the number of bars in the window.
// @param price (series float) Price source, e.g. `hlc3`.
// @param weight (series float) Non-negative weights, e.g. `volume`.
// @param ms (simple int) Window span, in milliseconds.
// @param gate (series bool) Only bars where this is `true` are sampled. Optional. Default is `true`.
// @param minBars (simple int) Minimum samples to retain regardless of age. Optional. Default is 1.
// @returns ([float, float]) The VWAP and the weighted standard deviation, or `[na, na]` while fewer than `minBars`
//          samples exist or the total weight is zero.
export gatedVwapTime(series float price, series float weight, simple int ms, series bool gate = true, simple int minBars = 1) =>
    var array<float> prices  = array.new<float>()
    var array<float> weights = array.new<float>()
    var array<int>   stamps  = array.new<int>()
    int keep = math.max(minBars, 0)
    if gate and not na(price) and not na(weight)
        prices.push(price)
        weights.push(weight)
        stamps.push(time)
    while prices.size() > keep and time - stamps.first() >= ms
        prices.shift()
        weights.shift()
        stamps.shift()
    int   n     = prices.size()
    float sumW  = 0.0
    float sumWP = 0.0
    for i = 0 to n - 1
        float w = weights.get(i)
        sumW  += w
        sumWP += w * prices.get(i)
    float vwap     = sumW > 0.0 ? sumWP / sumW : na
    float sumWDev2 = 0.0
    if not na(vwap)
        for i = 0 to n - 1
            sumWDev2 += weights.get(i) * math.pow(prices.get(i) - vwap, 2)
    bool ready = n >= minBars and not na(vwap)
    [ready ? vwap : na, ready ? math.sqrt(sumWDev2 / sumW) : na]
 
//#endregion
 
//#region ———————————————————— Demo
 
int  MS_30m    = 60 * 1000 * 30
int  MS_1H    = 60 * 60 * 1000
int  MS_1D    = 24 * MS_1H
bool upBar    = close > open
bool downBar  = close < open
bool newDay   = timeframe.change("D")
 
// Plot titles are the function names, so with "Indicator name labels" and "Labels on price scale" enabled in the
// chart settings, each line gets a colored tag with its name and value on the price scale.
 
// Volume histogram, colored by bar direction.
plot(volume, "volume", color.new(upBar ? color.teal : downBar ? color.red : color.gray, 65), 4, plot.style_histogram)
 
// Whole-history and anchored averages.
plot(gatedMean(volume, upBar), "gatedMean()", color.navy)
plot(gatedMeanSince(volume, newDay), "gatedMeanSince()", color.fuchsia)
 
// Count- and bar-based windows.
plot(gatedMeanLast(volume, upBar, 20), "gatedMeanLast() up", color.teal)
plot(gatedMeanLast(volume, downBar, 20), "gatedMeanLast() down", color.red)
plot(gatedMeanInBars(volume, upBar, 20, 3), "gatedMeanInBars()", color.aqua)
 
// Moving average of up-bar volume; pick the type in the script settings.
MaType maTypeInput = input.enum(MaType.ema, "gatedMa() type")
plot(gatedMa(volume, upBar, 20, maTypeInput), "gatedMa()", color.purple)
// SWMA always uses 4 samples, so its length argument is ignored.
plot(gatedMa(volume, upBar, 20, MaType.swma), "gatedMa() SWMA", color.maroon)
 
// Rolling time windows.
plot(gatedMeanTime(volume, MS_1D, true, 10), "gatedMeanTime()", color.lime)
 
// The sum and the count are on a different scale than volume, so they are plotted as characters at the top of the
// pane, which does not stretch the price scale. Read their values in the Data Window.
plotchar(gatedSumTime(volume, MS_1D, true, 10), "gatedSumTime()", "", location.top, color.orange, size = size.tiny)
plotchar(gatedCountTime(upBar, MS_1H), "gatedCountTime()", "", location.top, color.yellow, size = size.tiny)
 
// The VWAP is on the price scale, so it is forced onto the main chart, where it gets its own price-scale tags.
[vwapHi, sdHi] = gatedVwapTime(high, volume, MS_1H, true, 10)
[vwapLo, sdLo] = gatedVwapTime(low, volume, MS_1H, true, 10)
[vwap, sd] = gatedVwapTime(hlc3, volume, MS_30m, true, 10)
 
plot(vwap, "gatedVwapTime()", color.gray, 2, force_overlay = true)
plot(vwapHi, "gatedVwapTime() High", color.new(color.blue, 40), force_overlay = true)
plot(vwapLo, "gatedVwapTime() Low", color.new(color.red, 40), force_overlay = true)
plot(vwapHi + sdHi, "gatedVwapTime() +1 SD", color.new(color.blue, 20), force_overlay = true)
plot(vwapLo - sdLo, "gatedVwapTime() -1 SD", color.new(color.red, 20), force_overlay = true)
 
//#endregion

← 返回列表