Diupdate
GatedStats

GatedStats
Overview
GatedStats is a Pine Script v6 library of gated statistics: sums, means, event counts, moving averages and a rolling VWAP that sample only the bars where a condition you choose (the gate) is true and the value is not na.
Built-in functions such as ta.sma() or ta.vwap() treat every bar equally. Most real questions are conditional: "what is the average volume on up bars?", "what is the mean range of bars inside the session?", "how many buy signals fired in the last hour?", "what is the VWAP of the last 30 minutes?". Answering them normally means writing var counters, arrays, eviction logic and drift handling by hand, and the window logic is easy to get subtly wrong. This library packages that logic once, with the window defined in the way you actually need it.
What makes it different
1. Core concepts
Gate
A series bool you supply. On bars where it is true (and the value is not na) the bar is a sample. On all other bars the value is ignored. Pass the literal true, or leave the default where one exists, to sample every bar.
Sample
A bar that passed the gate. Statistics are computed from samples only. Many functions behave differently depending on whether the window counts samples or bars, so the distinction matters:
Window
The set of samples a result is computed from. The library supports these window types:
2. Choosing a function
3. Quick start
Pine Script®
Replace the version number in the import statement with the version you want to use. TradingView requires an explicit version and never upgrades an import automatically.
4. Function reference
Parameter qualifiers are shown in parentheses. series values may change on every bar. simple values must be known on the first bar (a literal, an input, or a constant expression); they cannot depend on bar data.
gatedMean(source, gate)
Pine Script®
Mean of source over the entire history, sampling only bars where gate is true and source is not na.
gatedMeanSince(source, reset)
Pine Script®
Mean of source over all bars with a non-na value since the latest bar where reset is true. The reset bar itself is included in the new average. Note that this function has no gate: every bar since the reset with a non-na value counts. To gate it, pass na for the bars you want to skip, for example (upBar ? volume : na).
gatedMeanLast(source, gate, count)
Pine Script®
Mean of the most recent count sampled values. The window always holds exactly count samples, however far back they are.
gatedMeanInBars(source, gate, length, minSamples)
Pine Script®
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.
gatedMa(source, gate, length, maType, weight)
Pine Script®
A moving average that advances only on sampled bars and holds its last value in between. Its length counts samples, not bars, so it behaves like gatedMeanLast() with a selectable smoothing type.
gatedSumTime(source, ms, gate, minBars)
Pine Script®
Sum of sampled values whose opening time is less than ms milliseconds before the current bar. The window always keeps at least minBars samples.
gatedMeanTime(source, ms, gate, minBars)
Pine Script®
Mean of sampled values over the same rolling time window as gatedSumTime(). Useful as a baseline, for example relative volume = volume / gatedMeanTime(volume, ms).
gatedCountTime(gate, ms)
Pine Script®
Number of bars where gate is true inside the rolling time window. Useful for counting signals, for example "no more than 3 buy signals per hour".
gatedVwapTime(price, weight, ms, gate, minBars)
Pine Script®
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 instead measure each bar against whatever VWAP prevailed when that bar arrived, which understates dispersion after the VWAP drifts. The formula used is:
Typical use, with bands:
Pine Script®
5. MaType enum
Passed to gatedMa(). Because it is an enum, the type can be exposed directly as a dropdown with input.enum().
Pine Script®
6. Recipes
Relative volume against a time-based baseline
Pine Script®
Comparing to the last 24 hours, rather than the last N bars, keeps the baseline meaningful when you change timeframe.
Up-bar and down-bar volume pressure
Pine Script®
Session-anchored average of a rolling measure
Pine Script®
Signal throttle (at most 3 per hour)
Pine Script®
The count includes the current bar, so test with a less-than-or-equal comparison to allow exactly three.
Average of a rare event with a thin-data guard
Pine Script®
Returns na unless at least 3 breakouts occurred in the last 200 bars.
Chart-timeframe independent window
Pine Script®
Rolling VWAP with standard deviation bands
Pine Script®
7. Behavior and best practices
Call every function once per bar, unconditionally
These functions store state between bars. Pine runs each function call with its own independent state and history, and that state only updates when the call executes. If you place a call inside an if block, a ternary branch, a loop or a switch case, it will skip bars and its windows will be wrong. Always assign the result to a variable at the top level of the script, then use the variable inside your conditions.
Pine Script®
Each call is independent
Two calls to the same function with different arguments keep separate states. You can freely compute an up-bar and a down-bar average side by side.
Gate, na and sampling
A bar is a sample only when the gate is true and the value is not na. A gate that is itself na is treated as false. Bars with an na value are skipped silently, which also means a window can contain older data than you expect when your source frequently returns na.
Time windows
minBars retains stale samples on purpose
The time functions always keep at least minBars of the most recent samples, even if they are older than ms. This prevents the result from collapsing to na or zero on a quiet stretch. The consequence is that, with a rarely true gate, the result can reflect samples older than the nominal window. If you want strict expiry, set minBars to 0 for gatedSumTime() and gatedMeanTime(), which then return 0 and na respectively when the window is empty. gatedCountTime() always uses a minimum of 0, so it expires strictly.
Realtime bars
On the realtime bar, Pine recalculates the script on every tick and rolls state back to the last confirmed bar before each recalculation. The library works within this model: the values on a realtime bar update tick by tick, and they settle on the closing tick. Closed bars never change, so the library does not repaint historical results. If you use a source that itself changes intrabar (for example close), results on the open bar will naturally move until it closes.
Numerical stability
The sums behind the time and count windows are maintained by adding new samples and subtracting evicted ones. To stop floating-point error from accumulating over long histories, the total is rebuilt exactly from the stored samples after every 1000 evictions.
8. Limits and performance
9. Frequently asked questions
What is the difference between gatedMeanLast() and gatedMeanInBars()?
gatedMeanLast(volume, upBar, 20) always averages exactly 20 up bars, however far back it must go to find them. gatedMeanInBars(volume, upBar, 20) averages the up bars inside the last 20 bars, which could be 3 or 17. The first is better for a stable sample size, the second is better when recency in bars matters.
Why is my result na?
The usual reasons: not enough samples yet (count or minBars not reached), the gate has not been true yet, the source is na on the gated bars, or the total weight in gatedVwapTime() is zero.
Why did my window keep an old value when nothing qualified?
With the default minBars = 1, time windows retain the most recent sample regardless of age. Pass minBars = 0 for strict expiry (see the minBars section).
Can I use a changing length or time span?
Count and bar lengths (count, length, minSamples) are series values and can change, although window contents only adjust as new bars arrive. Time spans (ms) and minBars are simple and fixed after the first bar.
Does the library work on any timeframe, symbol and chart type?
Yes. Time windows depend on bar opening times, so they work on any time-based timeframe. On non-time-based charts (Renko, range bars, Point and Figure) bar timestamps are irregular, so interpret time windows with care.
Does it use request.security() or any external data?
No. Everything is computed from the data the calling script already has. Nothing here can introduce lookahead.
Can I use it in a strategy?
Yes. Calls are pure calculations and work in indicators, strategies and other libraries. As always, avoid placing calls inside conditional branches.
Is the library open source?
Yes. All TradingView libraries are open source, and the source is released under the Mozilla Public License 2.0. You may reuse the functions as the House Rules for libraries allow.
10. About the demo
The published script includes a demo indicator that exercises every function on volume, so you can see exactly how each window behaves. Add the library to a clean chart to view it.
Tip: turn on "Indicator name labels" and "Labels on price scale" in the chart settings. Each plot is titled with its function name, so every line gets a colored tag showing its name and value.
11. Version notes
Version 1: first release. Nine functions (gatedMean, gatedMeanSince, gatedMeanLast, gatedMeanInBars, gatedMa, gatedSumTime, gatedMeanTime, gatedCountTime, gatedVwapTime) and the MaType enum.
Disclaimer
This library is a calculation toolkit for educational and analytical use. It is not financial advice, and nothing it outputs is a trading signal on its own. Past values do not predict future results.
Library function list
(The publish dialog appends the list generated from the Function annotations in the source. Keep it, because it is what users see when they hover a function in the Pine Editor.)
Overview
GatedStats is a Pine Script v6 library of gated statistics: sums, means, event counts, moving averages and a rolling VWAP that sample only the bars where a condition you choose (the gate) is true and the value is not na.
Built-in functions such as ta.sma() or ta.vwap() treat every bar equally. Most real questions are conditional: "what is the average volume on up bars?", "what is the mean range of bars inside the session?", "how many buy signals fired in the last hour?", "what is the VWAP of the last 30 minutes?". Answering them normally means writing var counters, arrays, eviction logic and drift handling by hand, and the window logic is easy to get subtly wrong. This library packages that logic once, with the window defined in the way you actually need it.
What makes it different
- Five window types: the whole history, since a reset, the last N samples, the last N bars, and a rolling span of time.
- Gate and na aware: a bar is a sample only if the gate is true AND the value is not na. Missing data never pollutes a result and never shifts a window.
- Time windows keep sliding: expired samples are evicted on every bar, including bars where the gate is false, so a "last hour" window really is the last hour.
- Drift-safe: running totals are rebuilt from the stored samples periodically, so add/subtract float error cannot accumulate over long histories.
- Gated moving averages: gatedMa() offers SMA, EMA, RMA, WMA, SWMA and VWMA whose length counts samples, not bars.
- Weighted standard deviation: gatedVwapTime() returns a true window-wide VWAP and weighted standard deviation, not a per-bar running estimate.
- No repainting of closed bars: every function depends only on the current and past bars.
1. Core concepts
Gate
A series bool you supply. On bars where it is true (and the value is not na) the bar is a sample. On all other bars the value is ignored. Pass the literal true, or leave the default where one exists, to sample every bar.
Sample
A bar that passed the gate. Statistics are computed from samples only. Many functions behave differently depending on whether the window counts samples or bars, so the distinction matters:
- A window of N samples always contains exactly N values, however many bars back the oldest one is.
- A window of N bars covers a fixed stretch of the chart and may contain anywhere from zero to N samples.
- A window of time covers a fixed span of clock time, measured from each sample's bar opening time to the current bar's opening time.
Window
The set of samples a result is computed from. The library supports these window types:
- Whole history: everything since the first bar.
- Anchored: everything since the most recent reset bar (new day, new session, your own event).
- Last N samples: count-based.
- Last N bars: bar-based, with a minimum-sample guard.
- Rolling time: a span in milliseconds, with a minimum-sample guard.
2. Choosing a function
- I want one running average of everything that qualifies: gatedMean()
- I want an average that restarts each day, session or event: gatedMeanSince()
- I want the average of the most recent N qualifying bars: gatedMeanLast()
- I want the average of qualifying bars inside the last N bars: gatedMeanInBars()
- I want a smoothed average of qualifying bars (EMA, RMA, WMA...): gatedMa()
- I want a total over the last hour, day or week: gatedSumTime()
- I want an average over the last hour, day or week: gatedMeanTime()
- I want to count events per hour, day or week: gatedCountTime()
- I want a VWAP and standard deviation over a rolling time span: gatedVwapTime()
3. Quick start
Replace the version number in the import statement with the version you want to use. TradingView requires an explicit version and never upgrades an import automatically.
4. Function reference
Parameter qualifiers are shown in parentheses. series values may change on every bar. simple values must be known on the first bar (a literal, an input, or a constant expression); they cannot depend on bar data.
gatedMean(source, gate)
Mean of source over the entire history, sampling only bars where gate is true and source is not na.
- source: values to average.
- gate: optional, default true. Only bars where this is true are sampled.
- Returns: the mean, or na until the first sampled bar.
- Memory: constant. Keeps only a running total and a count.
- Use for: long-run baselines, such as the lifetime average volume of up bars.
gatedMeanSince(source, reset)
Mean of source over all bars with a non-na value since the latest bar where reset is true. The reset bar itself is included in the new average. Note that this function has no gate: every bar since the reset with a non-na value counts. To gate it, pass na for the bars you want to skip, for example (upBar ? volume : na).
- source: values to average.
- reset: true restarts the average on that bar.
- Returns: the mean, or na before the first reset (and while no non-na value has arrived since it).
- Memory: constant.
- Use for: session-anchored or day-anchored averages. Example: reset = timeframe.change("D").
gatedMeanLast(source, gate, count)
Mean of the most recent count sampled values. The window always holds exactly count samples, however far back they are.
- source: values to average.
- gate: only bars where this is true are sampled.
- count: number of sampled values to average.
- Returns: the mean, or na until count samples exist, or if count is below 1.
- Memory: stores up to count samples.
- Use for: "average of the last 20 up bars", "mean of the last 50 breakouts". Because the window is count-based, it can reach far back on rare events.
gatedMeanInBars(source, gate, length, minSamples)
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.
- source: values to average.
- gate: only bars where this is true are sampled.
- length: window size, in bars.
- minSamples: optional, default 1. Minimum sampled bars the window must hold.
- Returns: the mean, or na while the window holds fewer than minSamples sampled bars.
- Memory: none beyond Pine's own rolling sums. No arrays.
- Use for: "average volume on up bars over the last 20 bars, but only if at least 5 of them were up bars".
gatedMa(source, gate, length, maType, weight)
A moving average that advances only on sampled bars and holds its last value in between. Its length counts samples, not bars, so it behaves like gatedMeanLast() with a selectable smoothing type.
- source: values to average.
- gate: only bars where this is true are sampled.
- length: number of samples in the average, or the smoothing period for ema and rma. Ignored by swma, which always uses 4 samples.
- maType: optional, default MaType.ema. See the MaType section.
- weight: optional, default volume. Weights for vwma. Ignored by all other types.
- Returns: the moving average, or na until enough samples exist (length, or 4 for swma).
- Seeding: ema and rma are seeded with the SMA of the first length samples, then continue recursively. This matches the standard seeding convention and avoids a long warm-up skew.
- Memory: stores up to length samples (and their weights).
gatedSumTime(source, ms, gate, minBars)
Sum of sampled values whose opening time is less than ms milliseconds before the current bar. The window always keeps at least minBars samples.
- source: values to sum.
- ms: window span in milliseconds.
- gate: optional, default true.
- minBars: optional, default 1. Minimum samples to retain regardless of age.
- Returns: the sum, or na while fewer than minBars samples exist. With minBars = 0 an empty window returns 0.
- Use for: rolling traded volume over the last hour or day, rolling P&L-style sums, rolling range totals.
gatedMeanTime(source, ms, gate, minBars)
Mean of sampled values over the same rolling time window as gatedSumTime(). Useful as a baseline, for example relative volume = volume / gatedMeanTime(volume, ms).
- source, ms, gate, minBars: as for gatedSumTime().
- Returns: the mean, or na while fewer than minBars samples exist.
gatedCountTime(gate, ms)
Number of bars where gate is true inside the rolling time window. Useful for counting signals, for example "no more than 3 buy signals per hour".
- gate: the event to count.
- ms: window span in milliseconds.
- Returns: the number of true bars whose opening time is less than ms milliseconds before this bar. It returns 0 (not na) when there are none. The result is a float so it can be plotted directly.
gatedVwapTime(price, weight, ms, gate, minBars)
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 instead measure each bar against whatever VWAP prevailed when that bar arrived, which understates dispersion after the VWAP drifts. The formula used is:
vwap = sum(w * p) / sum(w), sd = sqrt(sum(w * (p - vwap)^2) / sum(w))
- price: price source, for example hlc3.
- weight: non-negative weights, for example volume.
- ms: window span in milliseconds.
- gate: optional, default true.
- minBars: optional, default 1.
- Returns: a tuple [vwap, standard deviation], or [na, na] while fewer than minBars samples exist or the total weight is zero.
- Cost: both passes loop over the window on every bar, so cost grows with the number of bars in the window.
Typical use, with bands:
5. MaType enum
Passed to gatedMa(). Because it is an enum, the type can be exposed directly as a dropdown with input.enum().
- MaType.sma: simple. Equal-weighted mean of the last length samples.
- MaType.ema: exponential. Smoothing factor 2 / (length + 1).
- MaType.rma: Wilder's. Smoothing factor 1 / length.
- MaType.wma: linearly weighted. The newest sample has the largest weight.
- MaType.swma: symmetrically weighted over the last 4 samples (weights 1, 2, 2, 1). Ignores length.
- MaType.vwma: weighted by the weight argument (volume by default) over the last length samples.
6. Recipes
Relative volume against a time-based baseline
Comparing to the last 24 hours, rather than the last N bars, keeps the baseline meaningful when you change timeframe.
Up-bar and down-bar volume pressure
Session-anchored average of a rolling measure
Signal throttle (at most 3 per hour)
The count includes the current bar, so test with a less-than-or-equal comparison to allow exactly three.
Average of a rare event with a thin-data guard
Returns na unless at least 3 breakouts occurred in the last 200 bars.
Chart-timeframe independent window
Rolling VWAP with standard deviation bands
7. Behavior and best practices
Call every function once per bar, unconditionally
These functions store state between bars. Pine runs each function call with its own independent state and history, and that state only updates when the call executes. If you place a call inside an if block, a ternary branch, a loop or a switch case, it will skip bars and its windows will be wrong. Always assign the result to a variable at the top level of the script, then use the variable inside your conditions.
Each call is independent
Two calls to the same function with different arguments keep separate states. You can freely compute an up-bar and a down-bar average side by side.
Gate, na and sampling
A bar is a sample only when the gate is true and the value is not na. A gate that is itself na is treated as false. Bars with an na value are skipped silently, which also means a window can contain older data than you expect when your source frequently returns na.
Time windows
- Windows use bar opening times, and a sample is evicted when it is at least ms old. A one-hour window therefore covers the half-open span (now - 1 hour, now], and always includes the current bar.
- Eviction runs on every bar, including bars where the gate is false, so a time window keeps sliding while the gate is inactive.
- Windows measure wall-clock time, not trading time. On a symbol with sessions, a 24-hour window on a 1-hour chart will include the overnight gap, so it may hold fewer samples than 24 bars. Use a count-based function if you need "the last N bars".
- ms is a simple int. It must be known on the first bar: use a literal, an input, or an expression built from constants and timeframe.in_seconds(). It cannot change from bar to bar.
minBars retains stale samples on purpose
The time functions always keep at least minBars of the most recent samples, even if they are older than ms. This prevents the result from collapsing to na or zero on a quiet stretch. The consequence is that, with a rarely true gate, the result can reflect samples older than the nominal window. If you want strict expiry, set minBars to 0 for gatedSumTime() and gatedMeanTime(), which then return 0 and na respectively when the window is empty. gatedCountTime() always uses a minimum of 0, so it expires strictly.
Realtime bars
On the realtime bar, Pine recalculates the script on every tick and rolls state back to the last confirmed bar before each recalculation. The library works within this model: the values on a realtime bar update tick by tick, and they settle on the closing tick. Closed bars never change, so the library does not repaint historical results. If you use a source that itself changes intrabar (for example close), results on the open bar will naturally move until it closes.
Numerical stability
The sums behind the time and count windows are maintained by adding new samples and subtracting evicted ones. To stop floating-point error from accumulating over long histories, the total is rebuilt exactly from the stored samples after every 1000 evictions.
8. Limits and performance
- Array size: Pine arrays cannot hold more than 100,000 elements. The time-window functions store one entry per sample, so a window that would hold more than that many samples will produce a runtime error. This only matters for very long spans on very small timeframes (for example weeks of one-second bars). Shorten the span or raise the timeframe.
- gatedVwapTime() cost: it runs two passes over the whole window on every bar. For typical spans (minutes to a day) this is fine. For very large windows on low timeframes, expect noticeably longer calculation time.
- Constant-memory functions: gatedMean(), gatedMeanSince() and gatedMeanInBars() do not store arrays, so they are the cheapest choice when they fit your need.
- Execution budget: every call contributes to your script's loop and time limits. Use only the functions you need, and avoid duplicating identical calls: compute once, reuse the variable.
- History and warm-up: results are na until a window has enough samples. The amount of history needed depends on how rarely the gate is true.
9. Frequently asked questions
What is the difference between gatedMeanLast() and gatedMeanInBars()?
gatedMeanLast(volume, upBar, 20) always averages exactly 20 up bars, however far back it must go to find them. gatedMeanInBars(volume, upBar, 20) averages the up bars inside the last 20 bars, which could be 3 or 17. The first is better for a stable sample size, the second is better when recency in bars matters.
Why is my result na?
The usual reasons: not enough samples yet (count or minBars not reached), the gate has not been true yet, the source is na on the gated bars, or the total weight in gatedVwapTime() is zero.
Why did my window keep an old value when nothing qualified?
With the default minBars = 1, time windows retain the most recent sample regardless of age. Pass minBars = 0 for strict expiry (see the minBars section).
Can I use a changing length or time span?
Count and bar lengths (count, length, minSamples) are series values and can change, although window contents only adjust as new bars arrive. Time spans (ms) and minBars are simple and fixed after the first bar.
Does the library work on any timeframe, symbol and chart type?
Yes. Time windows depend on bar opening times, so they work on any time-based timeframe. On non-time-based charts (Renko, range bars, Point and Figure) bar timestamps are irregular, so interpret time windows with care.
Does it use request.security() or any external data?
No. Everything is computed from the data the calling script already has. Nothing here can introduce lookahead.
Can I use it in a strategy?
Yes. Calls are pure calculations and work in indicators, strategies and other libraries. As always, avoid placing calls inside conditional branches.
Is the library open source?
Yes. All TradingView libraries are open source, and the source is released under the Mozilla Public License 2.0. You may reuse the functions as the House Rules for libraries allow.
10. About the demo
The published script includes a demo indicator that exercises every function on volume, so you can see exactly how each window behaves. Add the library to a clean chart to view it.
- A volume histogram, colored by bar direction (teal for up bars, red for down bars, gray for flat bars).
- Whole-history and anchored lines: gatedMean() and gatedMeanSince() (reset each day).
- Count and bar windows: gatedMeanLast() for up and for down bars, and gatedMeanInBars().
- Moving averages: gatedMa() with a type selector in the script settings, and an SWMA line that always uses 4 samples.
- Time windows: gatedMeanTime() over one day.
- gatedSumTime() and gatedCountTime() plot at the top of the pane as characters, because their scale differs from volume and would stretch the price axis. Read their values in the Data Window.
- gatedVwapTime() draws on the main chart: a 30-minute VWAP, 1-hour VWAPs of highs and lows, and standard-deviation bands.
Tip: turn on "Indicator name labels" and "Labels on price scale" in the chart settings. Each plot is titled with its function name, so every line gets a colored tag showing its name and value.
11. Version notes
Version 1: first release. Nine functions (gatedMean, gatedMeanSince, gatedMeanLast, gatedMeanInBars, gatedMa, gatedSumTime, gatedMeanTime, gatedCountTime, gatedVwapTime) and the MaType enum.
Disclaimer
This library is a calculation toolkit for educational and analytical use. It is not financial advice, and nothing it outputs is a trading signal on its own. Past values do not predict future results.
Library function list
(The publish dialog appends the list generated from the Function annotations in the source. Keep it, because it is what users see when they hover a function in the Pine Editor.)
Catatan Rilis
Library "GatedStat"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.
gatedMean(source, gate)
Mean of `source` over the entire history, sampling only bars where `gate` is true and `source` is not `na`.
Parameters:
source (float): (series float) Values to average.
gate (bool): (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.
gatedMeanSince(source, reset)
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.
Parameters:
source (float): (series float) Values to average.
reset (bool): (series bool) `true` restarts the average on that bar.
Returns: (float) The mean, or `na` before the first reset.
gatedMeanLast(source, gate, count)
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.
Parameters:
source (float): (series float) Values to average.
gate (bool): (series bool) Only bars where this is `true` are sampled.
count (int): (series int) Number of sampled values to average.
Returns: (float) The mean, or `na` until `count` samples exist (or if `count` < 1).
gatedMeanInBars(source, gate, length, minSamples)
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.
Parameters:
source (float): (series float) Values to average.
gate (bool): (series bool) Only bars where this is `true` are sampled.
length (int): (series int) Window size, in bars.
minSamples (int): (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.
gatedMa(source, gate, length, maType, weight)
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.
Parameters:
source (float): (series float) Values to average.
gate (bool): (series bool) Only bars where this is `true` are sampled.
length (int): (series int) Number of samples in the average (the smoothing period for `ema` and `rma`). Ignored by
`swma`, which always uses 4 samples.
maType (series MaType): (MaType) Moving-average type. Optional. Default is `MaType.ema`.
weight (float): (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`).
gatedSumTime(source, ms, gate, minBars)
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.
Parameters:
source (float): (series float) Values to sum.
ms (simple int): (simple int) Window span, in milliseconds.
gate (bool): (series bool) Only bars where this is `true` are sampled. Optional. Default is `true`.
minBars (simple int): (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.
gatedMeanTime(source, ms, gate, minBars)
Mean of sampled values over the same rolling time window as `gatedSumTime()`. Useful as a baseline,
e.g. relative volume = `volume / gatedMeanTime(volume, ms)`.
Parameters:
source (float): (series float) Values to average.
ms (simple int): (simple int) Window span, in milliseconds.
gate (bool): (series bool) Only bars where this is `true` are sampled. Optional. Default is `true`.
minBars (simple int): (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.
gatedCountTime(gate, ms)
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".
Parameters:
gate (bool): (series bool) The event to count.
ms (simple int): (simple int) Window span, in milliseconds.
Returns: (float) The number of `true` bars whose opening time is less than `ms` milliseconds before this bar.
gatedVwapTime(price, weight, ms, gate, minBars)
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.
Parameters:
price (float): (series float) Price source, e.g. `hlc3`.
weight (float): (series float) Non-negative weights, e.g. `volume`.
ms (simple int): (simple int) Window span, in milliseconds.
gate (bool): (series bool) Only bars where this is `true` are sampled. Optional. Default is `true`.
minBars (simple int): (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.
Catatan Rilis
Version 3Two bug fixes. No function signatures or results change for valid inputs, so updating your import from /2 to /3 needs no other code changes.
- gatedVwapTime(): an empty window (for example a first bar without volume, or minBars = 0 after every sample expired) could stop the script with an array index error. An empty window now returns [na, na], as documented.
- gatedMeanLast(): a negative count no longer stalls the calculation. Any count below 1 returns na, as documented.
To update: import jabez4jc/GatedStats/3 as gs
Pernyataan Penyangkalan
Informasi dan publikasi ini tidak dimaksudkan, dan bukan merupakan, saran atau rekomendasi keuangan, investasi, trading, atau jenis lainnya yang diberikan atau didukung oleh TradingView. Baca selengkapnya di Ketentuan Penggunaan.
Pernyataan Penyangkalan
Informasi dan publikasi ini tidak dimaksudkan, dan bukan merupakan, saran atau rekomendasi keuangan, investasi, trading, atau jenis lainnya yang diberikan atau didukung oleh TradingView. Baca selengkapnya di Ketentuan Penggunaan.