SlopeUtilsLibrary "SlopeUtils"
calcSlope(src, atr_series, length)
โโCalculates a normalized slope based on price change relative to ATR.
โโParameters:
โโโโ src (float) : (series float) The source input (e.g., close).
โโโโ atr_series (float) : (series float) The ATR value for normalization.
โโโโ length (simple int) : (simple int) The lookback period for the slope calculation.
โโReturns: (float) The normalized slope value.
Techindicator
LuxyEnergyIndexThe Luxy Energy Index (LEI) library provides functions to measure price movement exhaustion by analyzing three dimensions: Extension (distance from fair value), Velocity (speed of movement), and Volume (confirmation level).
LEI answers a different question than traditional momentum indicators: instead of "how far has price gone?" (like RSI), LEI asks "how tired is this move?"
This library allows Pine Script developers to integrate LEI calculations into their own indicators and strategies.
How to Import
//@version=6
indicator("My Indicator")
import OrenLuxy/LuxyEnergyIndex/1 as LEI
Main Functions
`lei(src)` โ float
Returns the LEI value on a 0-100 scale.
src (optional): Price source, default is `close`
Returns : LEI value (0-100) or `na` if insufficient data (first 50 bars)
leiValue = LEI.lei()
leiValue = LEI.lei(hlc3) // custom source
`leiDetailed(src)` โ tuple
Returns LEI with all component values for detailed analysis.
= LEI.leiDetailed()
Returns:
`lei` - Final LEI value (0-100)
`extension` - Distance from VWAP in ATR units
`velocity` - 5-bar price change in ATR units
`volumeZ` - Volume Z-Score
`volumeModifier` - Applied modifier (1.0 = neutral)
`vwap` - VWAP value used
Component Functions
| Function | Description | Returns |
|-----------------------------------|---------------------------------|---------------|
| `calcExtension(src, vwap)` | Distance from VWAP / ATR | float |
| `calcVelocity(src)` | 5-bar price change / ATR | float |
| `calcVolumeZ()` | Volume Z-Score | float |
| `calcVolumeModifier(volZ)` | Volume modifier | float (โฅ1.0) |
| `getVWAP()` | Auto-detects asset type | float |
Signal Functions
| Function | Description | Returns |
|---------------------------------------------|----------------------------------|-----------|
| `isExhausted(lei, threshold)` | LEI โฅ threshold (default 70) | bool |
| `isSafe(lei, threshold)` | LEI โค threshold (default 30) | bool |
| `crossedExhaustion(lei, threshold)` | Crossed into exhaustion | bool |
| `crossedSafe(lei, threshold)` | Crossed into safe zone | bool |
Utility Functions
| Function | Description | Returns |
|----------------------------|-------------------------|-----------|
| `getZone(lei)` | Zone name | string |
| `getColor(lei)` | Recommended color | color |
| `hasEnoughHistory()` | Data check | bool |
| `minBarsRequired()` | Required bars | int (50) |
| `version()` | Library version | string |
Interpretation Guide
| LEI Range | Zone | Meaning |
|-------------|--------------|--------------------------------------------------|
| 0-30 | Safe | Low exhaustion, move may continue |
| 30-50 | Caution | Moderate exhaustion |
| 50-70 | Warning | Elevated exhaustion |
| 70-100 | Exhaustion | High exhaustion, increased reversal risk |
Example: Basic Usage
//@version=6
indicator("LEI Example", overlay=false)
import OrenLuxy/LuxyEnergyIndex/1 as LEI
// Get LEI value
leiValue = LEI.lei()
// Plot with dynamic color
plot(leiValue, "LEI", LEI.getColor(leiValue), 2)
// Reference lines
hline(70, "High", color.red)
hline(30, "Low", color.green)
// Alert on exhaustion
if LEI.crossedExhaustion(leiValue) and barstate.isconfirmed
alert("LEI crossed into exhaustion zone")
Technical Details
Fixed Parameters (by design):
Velocity Period: 5 bars
Volume Period: 20 bars
Z-Score Period: 50 bars
ATR Period: 14
Extension/Velocity Weights: 50/50
Asset Support:
Stocks/Forex: Uses Session VWAP (daily reset)
Crypto: Uses Rolling VWAP (50-bar window) - auto-detected
Edge Cases:
Returns `na` until 50 bars of history
Zero volume: Volume modifier defaults to 1.0 (neutral)
Credits and Acknowledgments
This library builds upon established technical analysis concepts:
VWAP - Industry standard volume-weighted price measure
ATR by J. Welles Wilder Jr. (1978) - Volatility normalization
Z-Score - Statistical normalization method
Volume analysis principles from Volume Spread Analysis (VSA) methodology
Disclaimer
This library is provided for **educational and informational purposes only**. It does not constitute financial advice. Past performance does not guarantee future results. The exhaustion readings are probabilistic indicators, not guarantees of price reversal. Always conduct your own research and use proper risk management when trading.
MLExtensionsLibrary "MLExtensions"
A set of extension methods for a novel implementation of a Approximate Nearest Neighbors (ANN) algorithm in Lorentzian space.
normalizeDeriv(src, quadraticMeanLength)
โโReturns the smoothed hyperbolic tangent of the input series.
โโParameters:
โโโโ src (float) : The input series (i.e., the first-order derivative for price).
โโโโ quadraticMeanLength (int) : The length of the quadratic mean (RMS).
โโReturns: nDeriv The normalized derivative of the input series.
normalize(src, min, max)
โโRescales a source value with an unbounded range to a target range.
โโParameters:
โโโโ src (float) : The input series
โโโโ min (float) : The minimum value of the unbounded range
โโโโ max (float) : The maximum value of the unbounded range
โโReturns: The normalized series
rescale(src, oldMin, oldMax, newMin, newMax)
โโRescales a source value with a bounded range to anther bounded range
โโParameters:
โโโโ src (float) : The input series
โโโโ oldMin (float) : The minimum value of the range to rescale from
โโโโ oldMax (float) : The maximum value of the range to rescale from
โโโโ newMin (float) : The minimum value of the range to rescale to
โโโโ newMax (float) : The maximum value of the range to rescale to
โโReturns: The rescaled series
getColorShades(color)
โโCreates an array of colors with varying shades of the input color
โโParameters:
โโโโ color (color) : The color to create shades of
โโReturns: An array of colors with varying shades of the input color
getPredictionColor(prediction, neighborsCount, shadesArr)
โโDetermines the color shade based on prediction percentile
โโParameters:
โโโโ prediction (float) : Value of the prediction
โโโโ neighborsCount (int) : The number of neighbors used in a nearest neighbors classification
โโโโ shadesArr (array) : An array of colors with varying shades of the input color
โโReturns: shade Color shade based on prediction percentile
color_green(prediction)
โโAssigns varying shades of the color green based on the KNN classification
โโParameters:
โโโโ prediction (float) : Value (int|float) of the prediction
โโReturns: color
color_red(prediction)
โโAssigns varying shades of the color red based on the KNN classification
โโParameters:
โโโโ prediction (float) : Value of the prediction
โโReturns: color
tanh(src)
โโReturns the the hyperbolic tangent of the input series. The sigmoid-like hyperbolic tangent function is used to compress the input to a value between -1 and 1.
โโParameters:
โโโโ src (float) : The input series (i.e., the normalized derivative).
โโReturns: tanh The hyperbolic tangent of the input series.
dualPoleFilter(src, lookback)
โโReturns the smoothed hyperbolic tangent of the input series.
โโParameters:
โโโโ src (float) : The input series (i.e., the hyperbolic tangent).
โโโโ lookback (int) : The lookback window for the smoothing.
โโReturns: filter The smoothed hyperbolic tangent of the input series.
tanhTransform(src, smoothingFrequency, quadraticMeanLength)
โโReturns the tanh transform of the input series.
โโParameters:
โโโโ src (float) : The input series (i.e., the result of the tanh calculation).
โโโโ smoothingFrequency (int)
โโโโ quadraticMeanLength (int)
โโReturns: signal The smoothed hyperbolic tangent transform of the input series.
n_rsi(src, n1, n2)
โโReturns the normalized RSI ideal for use in ML algorithms.
โโParameters:
โโโโ src (float) : The input series (i.e., the result of the RSI calculation).
โโโโ n1 (simple int) : The length of the RSI.
โโโโ n2 (simple int) : The smoothing length of the RSI.
โโReturns: signal The normalized RSI.
n_cci(src, n1, n2)
โโReturns the normalized CCI ideal for use in ML algorithms.
โโParameters:
โโโโ src (float) : The input series (i.e., the result of the CCI calculation).
โโโโ n1 (simple int) : The length of the CCI.
โโโโ n2 (simple int) : The smoothing length of the CCI.
โโReturns: signal The normalized CCI.
n_wt(src, n1, n2)
โโReturns the normalized WaveTrend Classic series ideal for use in ML algorithms.
โโParameters:
โโโโ src (float) : The input series (i.e., the result of the WaveTrend Classic calculation).
โโโโ n1 (simple int)
โโโโ n2 (simple int)
โโReturns: signal The normalized WaveTrend Classic series.
n_adx(highSrc, lowSrc, closeSrc, n1)
โโReturns the normalized ADX ideal for use in ML algorithms.
โโParameters:
โโโโ highSrc (float) : The input series for the high price.
โโโโ lowSrc (float) : The input series for the low price.
โโโโ closeSrc (float) : The input series for the close price.
โโโโ n1 (simple int) : The length of the ADX.
regime_filter(src, threshold, useRegimeFilter)
โโParameters:
โโโโ src (float)
โโโโ threshold (float)
โโโโ useRegimeFilter (bool)
filter_adx(src, length, adxThreshold, useAdxFilter)
โโfilter_adx
โโParameters:
โโโโ src (float) : The source series.
โโโโ length (simple int) : The length of the ADX.
โโโโ adxThreshold (int) : The ADX threshold.
โโโโ useAdxFilter (bool) : Whether to use the ADX filter.
โโReturns: The ADX.
filter_volatility(minLength, maxLength, useVolatilityFilter)
โโfilter_volatility
โโParameters:
โโโโ minLength (simple int) : The minimum length of the ATR.
โโโโ maxLength (simple int) : The maximum length of the ATR.
โโโโ useVolatilityFilter (bool) : Whether to use the volatility filter.
โโReturns: Boolean indicating whether or not to let the signal pass through the filter.
backtest(high, low, open, startLongTrade, endLongTrade, startShortTrade, endShortTrade, isEarlySignalFlip, maxBarsBackIndex, thisBarIndex, src, useWorstCase)
โโPerforms a basic backtest using the specified parameters and conditions.
โโParameters:
โโโโ high (float) : The input series for the high price.
โโโโ low (float) : The input series for the low price.
โโโโ open (float) : The input series for the open price.
โโโโ startLongTrade (bool) : The series of conditions that indicate the start of a long trade.
โโโโ endLongTrade (bool) : The series of conditions that indicate the end of a long trade.
โโโโ startShortTrade (bool) : The series of conditions that indicate the start of a short trade.
โโโโ endShortTrade (bool) : The series of conditions that indicate the end of a short trade.
โโโโ isEarlySignalFlip (bool) : Whether or not the signal flip is early.
โโโโ maxBarsBackIndex (int) : The maximum number of bars to go back in the backtest.
โโโโ thisBarIndex (int) : The current bar index.
โโโโ src (float) : The source series.
โโโโ useWorstCase (bool) : Whether to use the worst case scenario for the backtest.
โโReturns: A tuple containing backtest values
init_table()
โโinit_table()
โโReturns: tbl The backtest results.
update_table(tbl, tradeStatsHeader, totalTrades, totalWins, totalLosses, winLossRatio, winrate, earlySignalFlips)
โโupdate_table(tbl, tradeStats)
โโParameters:
โโโโ tbl (table) : The backtest results table.
โโโโ tradeStatsHeader (string) : The trade stats header.
โโโโ totalTrades (float) : The total number of trades.
โโโโ totalWins (float) : The total number of wins.
โโโโ totalLosses (float) : The total number of losses.
โโโโ winLossRatio (float) : The win loss ratio.
โโโโ winrate (float) : The winrate.
โโโโ earlySignalFlips (float) : The total number of early signal flips.
โโReturns: Updated backtest results table.
ZigZagCoreZigZagCore
ZigZagCore is a generic ZigZag engine that works with any user-defined threshold (ATR-based, volatility-based, fixed ticks, etc.).
API
import ReflexSignals/ZigZagCore/ as zz
var zz.ZzState state = zz.zz_new()
float thr = ... // your threshold in price units
state := zz.zz_update(state, thr)
zz_update(state, thr)
โโParameters:
โโโโ state (ZzState)
โโโโ thr (float)
ZzState
โโFields:
โโโโ dir (series int)
โโโโ highSinceLow (series float)
โโโโ lowSinceHigh (series float)
โโโโ lastHighLevel (series float)
โโโโ lastLowLevel (series float)
โโโโ lastHighIndex (series int)
โโโโ lastLowIndex (series int)
โโโโ highSinceLowIndex (series int)
โโโโ lowSinceHighIndex (series int)
โโโโ isNewHigh (series bool)
โโโโ isNewLow (series bool)
Directional State
dir = 1 โ market is in an upswing
dir = -1 โ market is in a downswing
dir = na โ initial undecided state
Live Swing Tracking (Unconfirmed Leg)
Continuously updated swing extremes:
highSinceLow โ highest price since the last confirmed low
lowSinceHigh โ lowest price since the last confirmed high
Their corresponding bar indices
These fields describe the current active swing leg, which updates every bar until a pivot is confirmed.
Pivot Detection
A pivot confirms only when price moves beyond the prior swing extreme by more than threshold. When this occurs, the library sets:
isNewHigh = true (on the detection bar only) and updates lastHighLevel, lastHighIndex
isNewLow = true and updates lastLowLevel, lastLowIndex
CoreMACDHTF [CHE]Library "CoreMACDHTF"
calc_macd_htf(src, preset_str, smooth_len)
โโParameters:
โโโโ src (float)
โโโโ preset_str (simple string)
โโโโ smooth_len (int)
is_hist_rising(src, preset_str, smooth_len)
โโParameters:
โโโโ src (float)
โโโโ preset_str (simple string)
โโโโ smooth_len (int)
hist_rising_01(src, preset_str, smooth_len)
โโParameters:
โโโโ src (float)
โโโโ preset_str (simple string)
โโโโ smooth_len (int)
CoreMACDHTF โ Hardcoded HTF MACD Presets with Smoothed Histogram Regime Flags
Summary
CoreMACDHTF provides a reusable MACD engine that approximates higher-timeframe behavior by selecting hardcoded EMA lengths based on the current chart timeframe, then optionally smoothing the resulting histogram with a stateful filter. It is published as a Pine v6 library but intentionally includes a minimal demo plot so you can validate behavior directly on a chart. The primary exported outputs are MACD, signal, a smoothed histogram, and the resolved lengths plus a timeframe tag. In addition, it exposes a histogram rising condition so importing scripts can reuse the same regime logic instead of re-implementing it.
Motivation: Why this design?
Classic MACD settings are often tuned to one timeframe. When you apply the same parameters to very different chart intervals, the histogram can become either too noisy or too sluggish. This script addresses that by using a fixed mapping from the chart timeframe into a precomputed set of EMA lengths, aiming for more consistent โtempoโ across intervals. A second problem is histogram micro-chop around turning points; the included smoother reduces short-run flips so regime-style conditions can be more stable for alerts and filters.
Whatโs different vs. standard approaches?
Reference baseline: a standard MACD using fixed fast, slow, and signal lengths on the current chart timeframe.
Architecture differences:
Automatic timeframe bucketing that selects a hardcoded length set for the chosen preset.
Two preset families: one labeled A with lengths three, ten, sixteen; one labeled B with lengths twelve, twenty-six, nine.
A custom, stateful histogram smoother intended to damp noisy transitions.
Library exports that return both signals and metadata, plus a dedicated โhistogram risingโ boolean.
Practical effect:
The MACD lengths change when the chart timeframe changes, so the oscillatorโs responsiveness is not constant across intervals by design.
The rising-flag logic is based on the smoothed histogram, which typically reduces single-bar flip noise compared to using the raw histogram directly.
How it works (technical)
1. The script reads the chart timeframe and converts it into milliseconds using built-in timeframe helpers.
2. It assigns the timeframe into a bucket label, such as an intraday bucket or a daily-and-above bucket, using fixed thresholds.
3. It resolves a hardcoded fast, slow, and signal length triplet based on:
The selected preset family.
The bucket label.
In some cases, the current minute multiplier for finer mapping.
4. It computes fast and slow EMAs on the selected source and subtracts them to obtain MACD, then computes an EMA of MACD for the signal line.
5. The histogram is derived from the difference between MACD and signal, then passed through a custom smoother.
6. The smoother uses persistent internal state to carry forward its intermediate values from bar to bar. This is intentional and means the smoothing output depends on contiguous bar history.
7. The histogram rising flag compares the current smoothed histogram to its prior value. On the first comparable bar it defaults to โrisingโ to avoid a missing prior reference.
8. Exports:
A function that returns MACD, signal, smoothed histogram, the resolved lengths, and a text tag.
A function that returns the boolean rising state.
A function that returns a numeric one-or-zero series for direct plotting or downstream numeric logic.
HTF note: this is not a true higher-timeframe request. It does not fetch higher-timeframe candles. It approximates HTF feel by selecting different lengths on the current timeframe.
Parameter Guide
Source โ Input price series used for EMA calculations โ Default close โ Trade-offs/Tips
Preset โ Selects the hardcoded mapping family โ Default preset A โ Preset A is more reactive than preset B in typical use
Table Position โ Anchor for an information table โ Default top right โ Present but not wired in the provided code (Unknown/Optional)
Table Size โ Text size for the information table โ Default normal โ Present but not wired in the provided code (Unknown/Optional)
Dark Mode โ Theme toggle for the table โ Default enabled โ Present but not wired in the provided code (Unknown/Optional)
Show Table โ Visibility toggle for the table โ Default enabled โ Present but not wired in the provided code (Unknown/Optional)
Zero dead-band (epsilon) โ Intended neutral band around zero for regime classification โ Default zero โ Present but not used in the provided code (Unknown/Optional)
Acceptance bars (n) โ Intended debounce count for regime confirmation โ Default three โ Present but not used in the provided code (Unknown/Optional)
Smoothing length โ Length controlling the histogram smootherโs responsiveness โ Default nine โ Smaller values react faster but can reintroduce flip noise
Reading & Interpretation
Smoothed histogram: use it as the momentum core. A positive value implies MACD is above signal, a negative value implies the opposite.
Histogram rising flag:
True means the smoothed histogram increased compared to the prior bar.
False means it did not increase compared to the prior bar.
Demo plot:
The included plot outputs one when rising is true and zero otherwise. It is a diagnostic-style signal line, not a scaled oscillator display.
Practical Workflows & Combinations
Trend following:
Use rising as a momentum confirmation filter after structural direction is established by higher highs and higher lows, or lower highs and lower lows.
Combine with a simple trend filter such as a higher-timeframe moving average from your main script (Unknown/Optional).
Exits and risk management:
If you use rising to stay in trends, consider exiting or reducing exposure when rising turns false for multiple consecutive bars rather than reacting to a single flip.
If you build alerts, evaluate on closed bars to avoid intra-bar flicker in live candles.
Multi-asset and multi-timeframe:
Because the mapping is hardcoded, validate on each asset class you trade. Volatility regimes differ and the perceived โequivalenceโ across timeframes is not guaranteed.
For consistent behavior, keep the smoothing length aligned across assets and adjust only when flip frequency becomes problematic.
Behavior, Constraints & Performance
Repaint and confirmation:
There is no forward-looking indexing. The logic uses current and prior values only.
Live-bar values can change until the bar closes, so rising can flicker intra-bar if you evaluate it in real time.
security and HTF:
No higher-timeframe candle requests are used. Length mapping is internal and deterministic per chart timeframe.
Resources:
No loops and no arrays in the core calculation path.
The smoother maintains persistent state, which is lightweight but means results depend on uninterrupted history.
Known limits:
Length mappings are fixed. If your chart timeframe is unusual, the bucket choice may not represent what you expect.
Several table and regime-related inputs are declared but not used in the provided code (Unknown/Optional).
The smoother is stateful; resetting chart history or changing symbol can alter early bars until state settles.
Sensible Defaults & Quick Tuning
S tarting point:
Preset A
Smoothing length nine
Source close
Tuning recipes:
Too many flips: increase smoothing length and evaluate rising only on closed bars.
Too sluggish: reduce smoothing length, but expect more short-run reversals.
Different timeframe feel after switching intervals: keep preset fixed and adjust smoothing length first before changing preset.
Want a clean plot signal: use the exported numeric rising series and apply your own display rules in the importing script.
What this indicator isโand isnโt
This is a momentum and regime utility layer built around a MACD-style backbone with hardcoded timeframe-dependent parameters and an optional smoother. It is not a complete trading system, not a risk model, and not predictive. Use it in context with market structure, execution rules, and risk controls.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
CoreTFRSIMD CoreTFRSIMD library โ Reusable TFRSI core for consistent momentum inputs across scripts
The library provides a reusable exported function such as calcTfrsi(src, len, signalLen) so you can compute TFRSI in your own indicators or strategies, e.g. tfrsi = CoreTFRSIMD.calcTfrsi(close, 6, 2)
Summary
CoreTFRSIMD is a Pine Script v6 library that implements a TFRSI-style oscillator core and exposes it as a reusable exported function. It is designed for authors who want the same TFRSI calculation across multiple indicators or strategies without duplicating logic. The library includes a simple demo plot and band styling so you can visually sanity-check the output. No higher-timeframe sampling is used, and there are no loops or arrays, so runtime cost is minimal for typical chart usage.
Motivation: Why this design?
When you reuse an oscillator across different tools, small implementation differences create inconsistent signals and hard-to-debug results. This library isolates the signal path into one exported function so that every dependent script consumes the exact same oscillator output. The design combines filtering, normalization, and a final smoothing pass to produce a stable, RSI-like readout intended for momentum and regime context.
Whatโs different vs. standard approaches?
Baseline: Traditional RSI computed directly from gains and losses with standard smoothing.
Architecture differences:
A high-pass stage to attenuate slower components before the main smoothing.
A multi-pole smoothing stage implemented with persistent state to reduce noise.
A running peak-tracker style normalization that adapts to changing signal amplitude.
A final signal smoothing layer using a simple moving average.
Practical effect:
The oscillator output tends to be less dominated by raw volatility spikes and more consistent across changing conditions.
The normalization step helps keep the output in an RSI-like reading space without relying on fixed scaling.
How it works (technical)
1. Input source: The exported function accepts a source series and two integer parameters controlling responsiveness and final smoothing.
2. High-pass stage: A recursive filter is applied to the source to emphasize shorter-term movement. This stage uses persistent storage so it can reference prior internal states across bars.
3. Smoothing stage: The filtered stream is passed through a SuperSmoother-like recursive smoother derived from the chosen length. This again uses persistent state and prior values for continuity.
4. Adaptive normalization: The absolute magnitude of the smoothed stream is compared to a slowly decaying reference level. If the current magnitude exceeds the reference, the reference is updated. This acts like a โpeak hold with decayโ so the oscillator scales relative to recent conditions.
5. Oscillator mapping: The normalized value is mapped into an RSI-like reading range.
6. Signal smoothing: A simple moving average is applied over the requested signal length to reduce bar-to-bar chatter.
7. Demo rendering: The library script plots the oscillator, draws horizontal guide levels, and applies background plus gradient fills for overbought and oversold regions.
Parameter Guide
Parameter โ Effect โ Default โ Trade-offs/Tips
src โ Input series used by the oscillator โ close in demo โ Use close for general momentum, or a derived series if you want to emphasize a specific behavior.
len โ Controls the responsiveness of internal filtering and smoothing โ six in demo โ Smaller values react faster but can increase short-term noise; larger values smooth more but can lag turns.
signalLen โ Controls the final smoothing of the mapped oscillator โ two in demo โ Smaller values preserve detail but can flicker; larger values reduce flicker but can delay transitions.
Reading & Interpretation
The plot is an oscillator intended to be read similarly to an RSI-style momentum gauge.
The demo includes three reference levels: upper at one hundred, mid at fifty, and lower at zero.
The fills visually emphasize zones above the midline and below the midline. Treat these as context, not as standalone entries.
If the oscillator appears unusually compressed or unusually jumpy, the normalization reference may be adapting to an abrupt change in amplitude. That is expected behavior for adaptive normalization.
Practical Workflows & Combinations
Trend following:
Use structure first, then confirm with oscillator behavior around the midline.
Prefer signals aligned with higher-high higher-low or lower-low lower-high context from price.
Exits/Stops:
Use oscillator loss of momentum as a caution flag rather than an automatic exit trigger.
In strong trends, consider keeping risk rules price-based and use the oscillator mainly to avoid adding into exhaustion.
Multi-asset/Multi-timeframe:
Start with the demo defaults when you want a responsive oscillator.
If an asset is noisier, increase the main length or the signal smoothing length to reduce false flips.
Behavior, Constraints & Performance
Repaint/confirmation: No higher-timeframe sampling is used. Output updates on the live bar like any normal series. There is no explicit closed-bar gating in the library.
security or HTF: Not used, so there is no HTF synchronization risk.
Resources: No loops, no arrays, no large history buffers. Persistent variables are used for filter state.
Known limits: Like any filtered oscillator, sharp gaps and extreme one-bar events can produce transient distortions. The adaptive normalization can also make early bars unstable until enough history has accumulated.
Sensible Defaults & Quick Tuning
Starting values: length six, signal smoothing two.
Too many flips: Increase signal smoothing length, or increase the main length.
Too sluggish: Reduce the main length, or reduce signal smoothing length.
Choppy around midline: Increase signal smoothing length slightly and rely more on price structure filters.
What this indicator isโand isnโt
This library is a reusable signal component and visualization aid. It is not a complete trading system, not predictive, and not a substitute for market structure, execution rules, and risk controls. Use it as a momentum and regime context layer, and validate behavior per asset and timeframe before relying on it.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
reversalLibrary "reversals"
psar(af_start, af_increment, af_max)
โโCalculates Parabolic Stop And Reverse (SAR)
โโParameters:
โโโโ af_start (simple float) : Initial acceleration factor (Wilder's original: 0.02)
โโโโ af_increment (simple float) : Acceleration factor increment per new extreme (Wilder's original: 0.02)
โโโโ af_max (simple float) : Maximum acceleration factor (Wilder's original: 0.20)
โโReturns: SAR value (stop level for current trend)
fractals()
โโDetects Williams Fractal patterns (5-bar pattern)
โโReturns: Tuple with fractal values (na if no fractal)
swings(lookback, source_high, source_low)
โโDetects swing highs and swing lows using lookback period
โโParameters:
โโโโ lookback (simple int) : Number of bars on each side to confirm swing point
โโโโ source_high (float) : Price series for swing high detection (typically high)
โโโโ source_low (float) : Price series for swing low detection (typically low)
โโReturns: Tuple with swing point values (na if no swing)
pivot(tf)
โโCalculates classic/standard/floor pivot points
โโParameters:
โโโโ tf (simple string) : Timeframe for pivot calculation ("D", "W", "M")
โโReturns: Tuple with pivot levels
pivotcam(tf)
โโCalculates Camarilla pivot points with 8 levels for short-term trading
โโParameters:
โโโโ tf (simple string) : Timeframe for pivot calculation ("D", "W", "M")
โโReturns: Tuple with pivot levels
pivotdem(tf)
โโCalculates d-mark pivot points with conditional open/close logic
โโParameters:
โโโโ tf (simple string) : Timeframe for pivot calculation ("D", "W", "M")
โโReturns: Tuple with pivot levels (only 3 levels)
pivotext(tf)
โโCalculates extended traditional pivot points with R4-R5 and S4-S5 levels
โโParameters:
โโโโ tf (simple string) : Timeframe for pivot calculation ("D", "W", "M")
โโReturns: Tuple with pivot levels
pivotfib(tf)
โโCalculates Fibonacci pivot points using Fibonacci ratios
โโParameters:
โโโโ tf (simple string) : Timeframe for pivot calculation ("D", "W", "M")
โโReturns: Tuple with pivot levels
pivotwood(tf)
โโCalculates Woodie's pivot points with weighted closing price
โโParameters:
โโโโ tf (simple string) : Timeframe for pivot calculation ("D", "W", "M")
โโReturns: Tuple with pivot levels
libpublicLibrary "libpublic"
sma(src, len)
โโSimple Moving Average
โโParameters:
โโโโ src (float) : Series to use
โโโโ len (int) : Filtering length
โโReturns: Filtered series
ema(src, len)
โโExponential Moving Average
โโParameters:
โโโโ src (float) : Series to use
โโโโ len (int) : Filtering length
โโReturns: Filtered series
rma(src, len)
โโWilder's Smoothing (Running Moving Average)
โโParameters:
โโโโ src (float) : Series to use
โโโโ len (int) : Filtering length
โโReturns: Filtered series
hma(src, len)
โโHull Moving Average
โโParameters:
โโโโ src (float) : Series to use
โโโโ len (int) : Filtering length
โโReturns: Filtered series
vwma(src, len)
โโVolume Weighted Moving Average
โโParameters:
โโโโ src (float) : Series to use
โโโโ len (int) : Filtering length
โโReturns: Filtered series
jma(src, len, phase)
โโJurik MA
โโParameters:
โโโโ src (float) : Series to use
โโโโ len (int) : Filtering length
โโโโ phase (int) : JMA Phase
โโReturns: Filtered series
c_Ema(_src, _length)
โโParameters:
โโโโ _src (float)
โโโโ _length (int)
c_zlema(_src, _length)
โโParameters:
โโโโ _src (float)
โโโโ _length (int)
to_pips(_v)
โโConvert price to pips.
โโParameters:
โโโโ _v (float) : Price
โโReturns: Pips
toPips(_v)
โโParameters:
โโโโ _v (float)
get_day(_n)
โโGet the day of the week
โโParameters:
โโโโ _n (int) : Number of day of week
clear_lines(_arr, _min)
โโDeletes the lines included in the array.
โโParameters:
โโโโ _arr (array) : Array of lines
โโโโ _min (int) : Deletes the lines included in the array.
clear_labels(_arr, _min)
โโDeletes the labels included in the array.
โโParameters:
โโโโ _arr (array) : Array of labels
โโโโ _min (int) : Deletes the labels included in the array.
clear_boxes(_arr, _min)
โโDeletes the boxes included in the array.
โโParameters:
โโโโ _arr (array) : Array of boxes
โโโโ _min (int) : Deletes the boxes included in the array.
tfToInt(_timeframe)
โโParameters:
โโโโ _timeframe (string)
tfCurrentView(_tf)
โโParameters:
โโโโ _tf (float)
f_round(_val, _decimals)
โโParameters:
โโโโ _val (float)
โโโโ _decimals (int)
getTablePos(_switch)
โโParameters:
โโโโ _switch (string)
getTxtSize(_switch)
โโParameters:
โโโโ _switch (string)
getTendChar(_trendChar)
โโParameters:
โโโโ _trendChar (string)
blueWaves(src, chlLen, avgLen)
โโParameters:
โโโโ src (float)
โโโโ chlLen (int)
โโโโ avgLen (int)
candleType(_candle)
โโParameters:
โโโโ _candle (int)
normalizeVolume(_vol, _precision)
โโParameters:
โโโโ _vol (float)
โโโโ _precision (string)
InSession(sessionTime, sessionTimeZone)
โโParameters:
โโโโ sessionTime (string)
โโโโ sessionTimeZone (string)
IsSessionStart(sessionTime, sessionTimeZone)
โโParameters:
โโโโ sessionTime (string)
โโโโ sessionTimeZone (string)
createSessionTime(_timeOffsetStart, _timeOffsetEnd, _offsetTypeStart, _offsetTypeEnd, sessionTimeZone)
โโParameters:
โโโโ _timeOffsetStart (int)
โโโโ _timeOffsetEnd (int)
โโโโ _offsetTypeStart (string)
โโโโ _offsetTypeEnd (string)
โโโโ sessionTimeZone (string)
oct25libLibrary of technical indicators for use in scripts.
1) salmav3(src, length, smooth, mult, sd_len)
โโParameters:
โ src (float)
โโโโ length (int)
โโโโ smooth (simple int)
โ mult(float)
โโโโ sd_len(int)
2) boltzman(src, length, T, alpha, smoothLen)
โโParameters:
โ src (float)
โโโโ length (int)
โ T(float)
โ Alpha(float)
โโโโ smoothLen (simple int)
3) shannon(src, vol, len, bc, vc, smooth)
โโParameters:
โโโโ src (float)
โโโโ vol (float)
โโโโ len (int)
โโโโ bc (bool)
โโโโ vc (bool)
โโโโ smooth (simple int)
4) vama(src, baseLen, volLen, beta)
โโParameters:
โโโโ src (float)
โโโโ baseLen (int)
โโโโ volLen (int)
โโโโ beta (float)
5) fwma(src, period, lambda, smooth)
โโParameters:
โโโโ src (float)
โโโโ period (int)
โโโโ lambda (float)
โโโโ smooth (simple int)
6) savitzky(srcc, srch, srcl, length)
โโParameters:
โโโโ srcc (float)
โโโโ srch (float)
โโโโ srcl (float)
โโโโ length (int)
7) butterworth(src, length, poles, smooth)
โโParameters:
โโโโ src (float)
โโโโ length (int)
โโโโ poles (int)
โโโโ smooth (simple int)
8) rti(src, trend_data_count, trend_sensitivity_percentage, midline, smooth)
โโParameters:
โโโโ src (float)
โโโโ trend_data_count (int)
โโโโ trend_sensitivity_percentage (int)
โโโโ midline (int)
โโโโ smooth (simple int)
9) chandemo(src, length, smooth)
โโParameters:
โโโโ src (float)
โโโโ length (int)
โโโโ smooth (simple int)
10) hsma(assetClose, length, emalen, midline)
โโParameters:
โโโโ assetClose (float)
โโโโ length (int)
โโโโ emalen (simple int)
โโโโ midline (float)
11) rsi(src, rsiLengthInput, rsiemalen, midline)
โโParameters:
โโโโ src (float)
โโโโ rsiLengthInput (simple int)
โโโโ rsiemalen (simple int)
โโโโ midline (float)
12) lacoca(src, lookback, malen, matype)
โโParameters:
โโโโ src (float)
โโโโ lookback (int)
โโโโ malen (simple int)
โโโโ matype (string)
LibVeloLibrary "LibVelo"
This library provides a sophisticated framework for **Velocity
Profile (Flow Rate)** analysis. It measures the physical
speed of trading at specific price levels by relating volume
to the time spent at those levels.
## Core Concept: Market Velocity
Unlike Volume Profiles, which only answer "how much" traded,
Velocity Profiles answer "how fast" it traded.
It is calculated as:
`Velocity = Volume / Duration`
This metric (contracts per second) reveals hidden market
dynamics invisible to pure Volume or TPO profiles:
1. **High Velocity (Fast Flow):**
* **Aggression:** Initiative buyers/sellers hitting market
orders rapidly.
* **Liquidity Vacuum:** Price slips through a level because
order book depth is thin (low resistance).
2. **Low Velocity (Slow Flow):**
* **Absorption:** High volume but very slow price movement.
Indicates massive passive limit orders ("Icebergs").
* **Apathy:** Little volume over a long time. Lack of
interest from major participants.
## Architecture: Triple-Engine Composition
To ensure maximum performance while offering full statistical
depth for all metrics, this library utilises **object
composition** with a lazy evaluation strategy:
#### Engine A: The Master (`vpVol`)
* **Role:** Standard Volume Profile.
* **Purpose:** Maintains the "ground truth" of volume distribution,
price buckets, and ranges.
#### Engine B: The Time Container (`vpTime`)
* **Role:** specialized container for time duration (in ms).
* **Hack:** It repurposes standard volume arrays (specifically
`aBuy`) to accumulate time duration for each bucket.
#### Engine C: The Calculator (`vpVelo`)
* **Role:** Temporary scratchpad for derived metrics.
* **Purpose:** When complex statistics (like Value Area or Skewness)
are requested for **Velocity**, this engine is assembled
on-demand to leverage the full statistical power of `LibVPrf`
without rewriting complex algorithms.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
create(buckets, rangeUp, rangeLo, dynamic, valueArea, allot, estimator, cdfSteps, split, trendLen)
โโConstruct a new `Velo` controller, initializing its engines.
โโParameters:
โโโโ buckets (int) : series int Number of price buckets โฅ 1.
โโโโ rangeUp (float) : series float Upper price bound (absolute).
โโโโ rangeLo (float) : series float Lower price bound (absolute).
โโโโ dynamic (bool) : series bool Flag for dynamic adaption of profile ranges.
โโโโ valueArea (int) : series int Percentage for Value Area (1..100).
โโโโ allot (series AllotMode) : series AllotMode Allocation mode `Classic` or `PDF` (default `PDF`).
โโโโ estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : series PriceEst PDF model for distribution attribution (default `Uniform`).
โโโโ cdfSteps (int) : series int Resolution for PDF integration (default 20).
โโโโ split (series SplitMode) : series SplitMode Buy/Sell split for the master volume engine (default `Classic`).
โโโโ trendLen (int) : series int Lookโback for trend factor in dynamic split (default 3).
โโReturns: Velo Freshly initialised velocity profile.
method clone(self)
โโCreate a deep copy of the composite profile.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo Profile object to copy.
โโReturns: Velo A completely independent clone.
method clear(self)
โโReset all engines and accumulators.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo Profile object to clear.
โโReturns: Velo Cleared profile (chaining).
method merge(self, srcVolBuy, srcVolSell, srcTime, srcRangeUp, srcRangeLo, srcVolCvd, srcVolCvdHi, srcVolCvdLo)
โโMerges external data (Volume and Time) into the current profile.
Automatically handles resizing and re-bucketing if ranges differ.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ srcVolBuy (array) : array Source Buy Volume bucket array.
โโโโ srcVolSell (array) : array Source Sell Volume bucket array.
โโโโ srcTime (array) : array Source Time bucket array (ms).
โโโโ srcRangeUp (float) : series float Upper price bound of the source data.
โโโโ srcRangeLo (float) : series float Lower price bound of the source data.
โโโโ srcVolCvd (float) : series float Source Volume CVD final value.
โโโโ srcVolCvdHi (float) : series float Source Volume CVD High watermark.
โโโโ srcVolCvdLo (float) : series float Source Volume CVD Low watermark.
โโReturns: Velo `self` (chaining).
method addBar(self, offset)
โโMain data ingestion. Distributes Volume and Time to buckets.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ offset (int) : series int Offset of the bar to add (default 0).
โโReturns: Velo `self` (chaining).
method setBuckets(self, buckets)
โโSets the number of buckets for the profile.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ buckets (int) : series int New number of buckets.
โโReturns: Velo `self` (chaining).
method setRanges(self, rangeUp, rangeLo)
โโSets the price range for the profile.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ rangeUp (float) : series float New upper price bound.
โโโโ rangeLo (float) : series float New lower price bound.
โโReturns: Velo `self` (chaining).
method setValueArea(self, va)
โโSet the percentage of volume/time for the Value Area.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ va (int) : series int New Value Area percentage (0..100).
โโReturns: Velo `self` (chaining).
method getBuckets(self)
โโReturns the current number of buckets in the profile.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโReturns: series int The number of buckets.
method getRanges(self)
โโReturns the current price range of the profile.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโReturns:
rangeUp series float The upper price bound of the profile.
rangeLo series float The lower price bound of the profile.
method getArrayBuyVol(self)
โโReturns the internal raw data array for **Buy Volume** directly.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโReturns: array The internal array for buy volume.
method getArraySellVol(self)
โโReturns the internal raw data array for **Sell Volume** directly.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโReturns: array The internal array for sell volume.
method getArrayTime(self)
โโReturns the internal raw data array for **Time** (in ms) directly.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโReturns: array The internal array for time duration.
method getArrayBuyVelo(self)
โโReturns the internal raw data array for **Buy Velocity** directly.
Automatically executes _assemble() if data is dirty.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโReturns: array The internal array for buy velocity.
method getArraySellVelo(self)
โโReturns the internal raw data array for **Sell Velocity** directly.
Automatically executes _assemble() if data is dirty.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโReturns: array The internal array for sell velocity.
method getBucketBuyVol(self, idx)
โโReturns the **Buy Volume** of a specific bucket.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ idx (int) : series int The index of the bucket.
โโReturns: series float The buy volume.
method getBucketSellVol(self, idx)
โโReturns the **Sell Volume** of a specific bucket.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ idx (int) : series int The index of the bucket.
โโReturns: series float The sell volume.
method getBucketTime(self, idx)
โโReturns the raw accumulated time (in ms) spent in a specific bucket.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ idx (int) : series int The index of the bucket.
โโReturns: series float The time in milliseconds.
method getBucketBuyVelo(self, idx)
โโReturns the **Buy Velocity** (Aggressive Buy Flow) of a bucket.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ idx (int) : series int The index of the bucket.
โโReturns: series float The buy velocity in .
method getBucketSellVelo(self, idx)
โโReturns the **Sell Velocity** (Aggressive Sell Flow) of a bucket.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ idx (int) : series int The index of the bucket.
โโReturns: series float The sell velocity in .
method getBktBnds(self, idx)
โโReturns the price boundaries of a specific bucket.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ idx (int) : series int The index of the bucket.
โโReturns:
up series float The upper price bound of the bucket.
lo series float The lower price bound of the bucket.
method getPoc(self, target)
โโReturns Point of Control (POC) information for the specified target metric.
Calculates on-demand if the target is 'Velocity' and data changed.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ target (series Metric) : Metric The data aspect to analyse (Volume, Time, Velocity).
โโReturns:
pocIdx series int The index of the POC bucket.
pocPrice series float The mid-price of the POC bucket.
method getVA(self, target)
โโReturns Value Area (VA) information for the specified target metric.
Calculates on-demand if the target is 'Velocity' and data changed.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ target (series Metric) : Metric The data aspect to analyse (Volume, Time, Velocity).
โโReturns:
vaUpIdx series int The index of the upper VA bucket.
vaUpPrice series float The upper price bound of the VA.
vaLoIdx series int The index of the lower VA bucket.
vaLoPrice series float The lower price bound of the VA.
method getMedian(self, target)
โโReturns the Median price for the specified target metric distribution.
Calculates on-demand if the target is 'Velocity' and data changed.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ target (series Metric) : Metric The data aspect to analyse (Volume, Time, Velocity).
โโReturns:
medianIdx series int The index of the bucket containing the median.
medianPrice series float The median price.
method getAverage(self, target)
โโReturns the weighted average price (VWAP/TWAP) for the specified target.
Calculates on-demand if the target is 'Velocity' and data changed.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ target (series Metric) : Metric The data aspect to analyse (Volume, Time, Velocity).
โโReturns:
avgIdx series int The index of the bucket containing the average.
avgPrice series float The weighted average price.
method getStdDev(self, target)
โโReturns the standard deviation for the specified target distribution.
Calculates on-demand if the target is 'Velocity' and data changed.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ target (series Metric) : Metric The data aspect to analyse (Volume, Time, Velocity).
โโReturns: series float The standard deviation.
method getSkewness(self, target)
โโReturns the skewness for the specified target distribution.
Calculates on-demand if the target is 'Velocity' and data changed.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ target (series Metric) : Metric The data aspect to analyse (Volume, Time, Velocity).
โโReturns: series float The skewness.
method getKurtosis(self, target)
โโReturns the excess kurtosis for the specified target distribution.
Calculates on-demand if the target is 'Velocity' and data changed.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ target (series Metric) : Metric The data aspect to analyse (Volume, Time, Velocity).
โโReturns: series float The excess kurtosis.
method getSegments(self, target)
โโReturns the fundamental unimodal segments for the specified target metric.
Calculates on-demand if the target is 'Velocity' and data changed.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ target (series Metric) : Metric The data aspect to analyse (Volume, Time, Velocity).
โโReturns: matrix A 2-column matrix where each row is an pair.
method getCvd(self, target)
โโReturns Cumulative Volume/Velo Delta (CVD) information for the target metric.
โโNamespace types: Velo
โโParameters:
โโโโ self (Velo) : Velo The profile object.
โโโโ target (series Metric) : Metric The data aspect to analyse (Volume, Time, Velocity).
โโReturns:
cvd series float The final delta value.
cvdHi series float The historical high-water mark of the delta.
cvdLo series float The historical low-water mark of the delta.
Velo
โโVelo Composite Velocity Profile Controller.
โโFields:
โโโโ _vpVol (VPrf type from AustrianTradingMachine/LibVPrf/2) : LibVPrf.VPrf Engine A: Master Volume source.
โโโโ _vpTime (VPrf type from AustrianTradingMachine/LibVPrf/2) : LibVPrf.VPrf Engine B: Time duration container (ms).
โโโโ _vpVelo (VPrf type from AustrianTradingMachine/LibVPrf/2) : LibVPrf.VPrf Engine C: Scratchpad for velocity stats.
โโโโ _aTime (array) : array Pointer alias to `vpTime.aBuy` (Time storage).
โโโโ _valueArea (series float) : int Percentage of total volume to include in the Value Area (1..100)
โโโโ _estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : LibBrSt.PriceEst PDF model for distribution attribution.
โโโโ _allot (series AllotMode) : AllotMode Attribution model (Classic or PDF).
โโโโ _cdfSteps (series int) : int Integration resolution for PDF.
โโโโ _isDirty (series bool) : bool Lazy evaluation flag for vpVelo.
TraderMathLibrary "TraderMath"
A collection of essential trading utilities and mathematical functions used for technical analysis,
including DEMA, Fisher Transform, directional movement, and ADX calculations.
dema(source, length)
โโCalculates the value of the Double Exponential Moving Average (DEMA).
โโParameters:
โโโโ source (float) : (series int/float) Series of values to process.
โโโโ length (simple int) : (simple int) Length for the smoothing parameter calculation.
โโReturns: (float) The double exponentially weighted moving average of the `source`.
roundVal(val)
โโConstrains a value to the range .
โโParameters:
โโโโ val (float) : (float) Value to constrain.
โโReturns: (float) Value limited to the range .
fisherTransform(length)
โโComputes the Fisher Transform oscillator, enhancing turning point sensitivity.
โโParameters:
โโโโ length (int) : (int) Lookback length used to normalize price within the high-low range.
โโReturns: (float) Fisher Transform value.
dirmov(len)
โโCalculates the Plus and Minus Directional Movement components (DI+ and DIโ).
โโParameters:
โโโโ len (simple int) : (int) Lookback length for directional movement.
โโReturns: (float ) Array containing .
adx(dilen, adxlen)
โโComputes the Average Directional Index (ADX) based on DI+ and DIโ.
โโParameters:
โโโโ dilen (simple int) : (int) Lookback length for directional movement calculation.
โโโโ adxlen (simple int) : (int) Smoothing length for ADX computation.
โโReturns: (float) Average Directional Index value (0โ100).
LibVPrfLibrary "LibVPrf"
This library provides an object-oriented framework for volume
profile analysis in Pine Scriptยฎ. It is built around the `VProf`
User-Defined Type (UDT), which encapsulates all data, settings,
and statistical metrics for a single profile, enabling stateful
analysis with on-demand calculations.
Key Features:
1. **Object-Oriented Design (UDT):** The library is built around
the `VProf` UDT. This object encapsulates all profile data
and provides methods for its full lifecycle management,
including creation, cloning, clearing, and merging of profiles.
2. **Volume Allocation (`AllotMode`):** Offers two methods for
allocating a bar's volume:
- **Classic:** Assigns the entire bar's volume to the close
price bucket.
- **PDF:** Distributes volume across the bar's range using a
statistical price distribution model from the `LibBrSt` library.
3. **Buy/Sell Volume Splitting (`SplitMode`):** Provides methods
for classifying volume into buying and selling pressure:
- **Classic:** Classifies volume based on the bar's color (Close vs. Open).
- **Dynamic:** A specific model that analyzes candle structure
(body vs. wicks) and a short-term trend factor to
estimate the buy/sell share at each price level.
4. **Statistical Analysis (On-Demand):** Offers a suite of
statistical metrics calculated using a "Lazy Evaluation"
pattern (computed only when requested via `get...` methods):
- **Central Tendency:** Point of Control (POC), VWAP, and Median.
- **Dispersion:** Value Area (VA) and Population Standard Deviation.
- **Shape:** Skewness and Excess Kurtosis.
- **Delta:** Cumulative Volume Delta, including its
historical high/low watermarks.
5. **Structural Analysis:** Includes a parameter-free method
(`getSegments`) to decompose a profile into its fundamental
unimodal segments, allowing for modality detection (e.g.,
identifying bimodal profiles).
6. **Dynamic Profile Management:**
- **Auto-Fitting:** Profiles set to `dynamic = true` will
automatically expand their price range to fit new data.
- **Manipulation:** The resolution, price range, and Value Area
of a dynamic profile can be changed at any time. This
triggers a resampling process that uses a **linear
interpolation model** to re-bucket existing volume.
- **Assumption:** Non-dynamic profiles are fixed and will throw
a `runtime.error` if `addBar` is called with data
outside their initial range.
7. **Bucket-Level Access:** Provides getter methods for direct
iteration and analysis of the raw buy/sell volume and price
boundaries of each individual price bucket.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
create(buckets, rangeUp, rangeLo, dynamic, valueArea, allot, estimator, cdfSteps, split, trendLen)
โโConstruct a new `VProf` object with fixed bucket count & range.
โโParameters:
โโโโ buckets (int) : series int number of price buckets โฅ 1
โโโโ rangeUp (float) : series float upper price bound (absolute)
โโโโ rangeLo (float) : series float lower price bound (absolute)
โโโโ dynamic (bool) : series bool Flag for dynamic adaption of profile ranges
โโโโ valueArea (int) : series int Percentage of total volume to include in the Value Area (1..100)
โโโโ allot (series AllotMode) : series AllotMode Allocation mode `classic` or `pdf` (default `classic`)
โโโโ estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : series LibBrSt.PriceEst PDF model when `model == PDF`. (deflault = 'uniform')
โโโโ cdfSteps (int) : series int even #sub-intervals for Simpson rule (default 20)
โโโโ split (series SplitMode) : series SplitMode Buy/Sell determination (default `classic`)
โโโโ trendLen (int) : series int Lookโback bars for trend factor (defaultย 3)
โโReturns: VProf freshly initialised profile
method clone(self)
โโCreate a deep copy of the volume profile.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object to copy
โโReturns: VProf A new, independent copy of the profile
method clear(self)
โโReset all bucket tallies while keeping configuration intact.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf profile object
โโReturns: VProf cleared profile (chaining)
method merge(self, srcABuy, srcASell, srcRangeUp, srcRangeLo, srcCvd, srcCvdHi, srcCvdLo)
โโMerges volume data from a source profile into the current profile.
If resizing is needed, it performs a high-fidelity re-bucketing of existing
volume using a linear interpolation model inferred from neighboring buckets,
preventing aliasing artifacts and ensuring accurate volume preservation.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf The target profile object to merge into.
โโโโ srcABuy (array) : array The source profile's buy volume bucket array.
โโโโ srcASell (array) : array The source profile's sell volume bucket array.
โโโโ srcRangeUp (float) : series float The upper price bound of the source profile.
โโโโ srcRangeLo (float) : series float The lower price bound of the source profile.
โโโโ srcCvd (float) : series float The final Cumulative Volume Delta (CVD) value of the source profile.
โโโโ srcCvdHi (float) : series float The historical high-water mark of the CVD from the source profile.
โโโโ srcCvdLo (float) : series float The historical low-water mark of the CVD from the source profile.
โโReturns: VProf `self` (chaining), now containing the merged data.
method addBar(self, offset)
โโAdd current barโs volume to the profile (call once per realtime bar).
classic mode: allocates all volume to the close bucket and classifies
by `close >= open`. PDF mode: distributes volume across buckets by the
estimatorโs CDF mass. For `split = dynamic`, the buy/sell share per
price is computed via context-driven piecewise s(u).
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object
โโโโ offset (int) : series int To offset the calculated bar
โโReturns: VProf `self` (method chaining)
method setBuckets(self, buckets)
โโSets the number of buckets for the volume profile.
Behavior depends on the `isDynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-bucketing to a new resolution.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object
โโโโ buckets (int) : series int The new number of buckets
โโReturns: VProf `self` (chaining)
method setRanges(self, rangeUp, rangeLo)
โโSets the price range for the volume profile.
Behavior depends on the `dynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-bucketing existing volume.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object
โโโโ rangeUp (float) : series float The new upper price bound
โโโโ rangeLo (float) : series float The new lower price bound
โโReturns: VProf `self` (chaining)
method setValueArea(self, valueArea)
โโSet the percentage of volume for the Value Area. If the value
changes, the profile is finalized again.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object
โโโโ valueArea (int) : series int The new Value Area percentage (0..100)
โโReturns: VProf `self` (chaining)
method getBktBuyVol(self, idx)
โโGet Buy volume of a bucket.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object
โโโโ idx (int) : series int Bucket index
โโReturns: series float Buy volume โฅ 0
method getBktSellVol(self, idx)
โโGet Sell volume of a bucket.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object
โโโโ idx (int) : series int Bucket index
โโReturns: series float Sell volume โฅ 0
method getBktBnds(self, idx)
โโGet Bounds of a bucket.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object
โโโโ idx (int) : series int Bucket index
โโReturns:
up series float The upper price bound of the bucket.
lo series float The lower price bound of the bucket.
method getPoc(self)
โโGet POC information.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object
โโReturns:
pocIndex series int The index of the Point of Control (POC) bucket.
pocPrice. series float The mid-price of the Point of Control (POC) bucket.
method getVA(self)
โโGet Value Area (VA) information.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object
โโReturns:
vaUpIndex series int The index of the upper bound bucket of the Value Area.
vaUpPrice series float The upper price bound of the Value Area.
vaLoIndex series int The index of the lower bound bucket of the Value Area.
vaLoPrice series float The lower price bound of the Value Area.
method getMedian(self)
โโGet the profile's median price and its bucket index. Calculates the value on-demand if stale.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object.
โโReturns:
medianIndex series int The index of the bucket containing the Median.
medianPrice series float The Median price of the profile.
method getVwap(self)
โโGet the profile's VWAP and its bucket index. Calculates the value on-demand if stale.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object.
โโReturns:
vwapIndex series int The index of the bucket containing the VWAP.
vwapPrice series float The Volume Weighted Average Price of the profile.
method getStdDev(self)
โโGet the profile's volume-weighted standard deviation. Calculates the value on-demand if stale.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object.
โโReturns: series float The Standard deviation of the profile.
method getSkewness(self)
โโGet the profile's skewness. Calculates the value on-demand if stale.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object.
โโReturns: series float The Skewness of the profile.
method getKurtosis(self)
โโGet the profile's excess kurtosis. Calculates the value on-demand if stale.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object.
โโReturns: series float The Kurtosis of the profile.
method getSegments(self)
โโGet the profile's fundamental unimodal segments. Calculates on-demand if stale.
Uses a parameter-free, pivot-based recursive algorithm.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf The profile object.
โโReturns: matrix A 2-column matrix where each row is an pair.
method getCvd(self)
โโCumulative Volume Delta (CVD) like metric over all buckets.
โโNamespace types: VProf
โโParameters:
โโโโ self (VProf) : VProf Profile object.
โโReturns:
cvd series float The final Cumulative Volume Delta (Total Buy Vol - Total Sell Vol).
cvdHi series float The running high-water mark of the CVD as volume was added.
cvdLo series float The running low-water mark of the CVD as volume was added.
VProf
โโVProf Bucketed Buy/Sell volume profile plus meta information.
โโFields:
โโโโ buckets (series int) : int Number of price buckets (granularity โฅ1)
โโโโ rangeUp (series float) : float Upper price range (absolute)
โโโโ rangeLo (series float) : float Lower price range (absolute)
โโโโ dynamic (series bool) : bool Flag for dynamic adaption of profile ranges
โโโโ valueArea (series int) : int Percentage of total volume to include in the Value Area (1..100)
โโโโ allot (series AllotMode) : AllotMode Allocation mode `classic` or `pdf`
โโโโ estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : LibBrSt.PriceEst Price density model when `model == PDF`
โโโโ cdfSteps (series int) : int Simpson integration resolution (even โฅ2)
โโโโ split (series SplitMode) : SplitMode Buy/Sell split strategy per bar
โโโโ trendLen (series int) : int Lookโback length for trend factor (โฅ1)
โโโโ maxBkt (series int) : int User-defined number of buckets (unclamped)
โโโโ aBuy (array) : array Buy volume per bucket
โโโโ aSell (array) : array Sell volume per bucket
โโโโ cvd (series float) : float Final Cumulative Volume Delta (Total Buy Vol - Total Sell Vol).
โโโโ cvdHi (series float) : float Running high-water mark of the CVD as volume was added.
โโโโ cvdLo (series float) : float Running low-water mark of the CVD as volume was added.
โโโโ poc (series int) : int Index of maxโvolume bucket (POC). Is `na` until calculated.
โโโโ vaUp (series int) : int Index of upper ValueโArea bound. Is `na` until calculated.
โโโโ vaLo (series int) : int Index of lower valueโArea bound. Is `na` until calculated.
โโโโ median (series float) : float Median price of the volume distribution. Is `na` until calculated.
โโโโ vwap (series float) : float Profile VWAP (Volume Weighted Average Price). Is `na` until calculated.
โโโโ stdDev (series float) : float Standard Deviation of volume around the VWAP. Is `na` until calculated.
โโโโ skewness (series float) : float Skewness of the volume distribution. Is `na` until calculated.
โโโโ kurtosis (series float) : float Excess Kurtosis of the volume distribution. Is `na` until calculated.
โโโโ segments (matrix) : matrix A 2-column matrix where each row is an pair. Is `na` until calculated.
LibPvotLibrary "LibPvot"
This is a library for advanced technical analysis, specializing
in two core areas: the detection of price-oscillator
divergences and the analysis of market structure. It provides
a back-end engine for signal detection and a toolkit for
indicator plotting.
Key Features:
1. **Complete Divergence Suite (Class A, B, C):** The engine detects
all three major types of divergences, providing a full spectrum of
analytical signals:
- **Regular (A):** For potential trend reversals.
- **Hidden (B):** For potential trend continuations.
- **Exaggerated (C):** For identifying weakness at double tops/bottoms.
2. **Advanced Signal Filtering:** The detection logic uses a
percentage-based price tolerance (`prcTol`). This feature
enables the practical detection of Exaggerated divergences
(which rarely occur at the exact same price) and creates a
"dead zone" to filter insignificant noise from triggering
Regular divergences.
3. **Pivot Synchronization:** A bar tolerance (`barTol`) is used
to reliably match price and oscillator pivots that do not
align perfectly on the same bar, preventing missed signals.
4. **Signal Invalidation Logic:** Features two built-in invalidation
rules:
- An optional `invalidate` parameter automatically terminates
active divergences if the price or the oscillator breaks
the level of the confirming pivot.
- The engine also discards 'half-pivots' (e.g., a price pivot)
if a corresponding oscillator pivot does not appear within
the `barTol` window.
5. **Stateful Plotting Helpers:** Provides helper functions
(`bullDivPos` and `bearDivPos`) that abstract away the
state management issues of visualizing persistent signals.
They generate gap-free, accurately anchored data series
ready to be used in `plotshape` functions, simplifying
indicator-side code.
6. **Rich Data Output:** The core detection functions (`bullDiv`, `bearDiv`)
return a comprehensive 9-field data tuple. This includes the
boolean flags for each divergence type and the precise
coordinates (price, oscillator value, bar index) of both the
starting and the confirming pivots.
7. **Market Structure & Trend Analysis:** Includes a
`marketStructure` function to automatically identify pivot
highs/lows, classify their relationship (HH, LH, LL, HL),
detect structure breaks, and determine the current trend
state (Up, Down, Neutral) based on pivot sequences.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
bullDiv(priceSrc, oscSrc, leftLen, rightLen, depth, barTol, prcTol, persist, invalidate)
โโDetects bullish divergences (Regular, Hidden, Exaggerated) based on pivot lows.
โโParameters:
โโโโ priceSrc (float) : series float Price series to check for pivots (e.g., `low`).
โโโโ oscSrc (float) : series float Oscillator series to check for pivots.
โโโโ leftLen (int) : series int Number of bars to the left of a pivot (default 5).
โโโโ rightLen (int) : series int Number of bars to the right of a pivot (default 5).
โโโโ depth (int) : series int Maximum number of stored pivot pairs to check against (default 2).
โโโโ barTol (int) : series int Maximum bar distance allowed between the price pivot and the oscillator pivot (default 3).
โโโโ prcTol (float) : series float The percentage tolerance for comparing pivot prices. Used to detect Exaggerated
divergences and filter out market noise (default 0.05%).
โโโโ persist (bool) : series bool If `true` (default), the divergence flag stays active for the entire duration of the signal.
If `false`, it returns a single-bar pulse on detection.
โโโโ invalidate (bool) : series bool If `true` (default), terminates an active divergence if price or oscillator break
below the confirming pivot low.
โโReturns: A tuple containing comprehensive data for a detected bullish divergence.
regBull series bool `true` if a Regular bullish divergence (Class A) is active.
hidBull series bool `true` if a Hidden bullish divergence (Class B) is active.
exgBull series bool `true` if an Exaggerated bullish divergence (Class C) is active.
initPivotPrc series float Price value of the initial (older) pivot low.
initPivotOsz series float Oscillator value of the initial pivot low.
initPivotBar series int Bar index of the initial pivot low.
lastPivotPrc series float Price value of the last (confirming) pivot low.
lastPivotOsz series float Oscillator value of the last pivot low.
lastPivotBar series int Bar index of the last pivot low.
bearDiv(priceSrc, oscSrc, leftLen, rightLen, depth, barTol, prcTol, persist, invalidate)
โโDetects bearish divergences (Regular, Hidden, Exaggerated) based on pivot highs.
โโParameters:
โโโโ priceSrc (float) : series float Price series to check for pivots (e.g., `high`).
โโโโ oscSrc (float) : series float Oscillator series to check for pivots.
โโโโ leftLen (int) : series int Number of bars to the left of a pivot (default 5).
โโโโ rightLen (int) : series int Number of bars to the right of a pivot (default 5).
โโโโ depth (int) : series int Maximum number of stored pivot pairs to check against (default 2).
โโโโ barTol (int) : series int Maximum bar distance allowed between the price pivot and the oscillator pivot (default 3).
โโโโ prcTol (float) : series float The percentage tolerance for comparing pivot prices. Used to detect Exaggerated
divergences and filter out market noise (default 0.05%).
โโโโ persist (bool) : series bool If `true` (default), the divergence flag stays active for the entire duration of the signal.
If `false`, it returns a single-bar pulse on detection.
โโโโ invalidate (bool) : series bool If `true` (default), terminates an active divergence if price or oscillator break
above the confirming pivot high.
โโReturns: A tuple containing comprehensive data for a detected bearish divergence.
regBear series bool `true` if a Regular bearish divergence (Class A) is active.
hidBear series bool `true` if a Hidden bearish divergence (Class B) is active.
exgBear series bool `true` if an Exaggerated bearish divergence (Class C) is active.
initPivotPrc series float Price value of the initial (older) pivot high.
initPivotOsz series float Oscillator value of the initial pivot high.
initPivotBar series int Bar index of the initial pivot high.
lastPivotPrc series float Price value of the last (confirming) pivot high.
lastPivotOsz series float Oscillator value of the last pivot high.
lastPivotBar series int Bar index of the last pivot high.
bullDivPos(regBull, hidBull, exgBull, rightLen, yPos)
โโCalculates the plottable data series for bullish divergences. It manages
the complex state of a persistent signal's plotting window to ensure
gap-free and accurately anchored visualization.
โโParameters:
โโโโ regBull (bool) : series bool The regular bullish divergence flag from `bullDiv`.
โโโโ hidBull (bool) : series bool The hidden bullish divergence flag from `bullDiv`.
โโโโ exgBull (bool) : series bool The exaggerated bullish divergence flag from `bullDiv`.
โโโโ rightLen (int) : series int The same `rightLen` value used in `bullDiv` for correct timing.
โโโโ yPos (float) : series float The series providing the base Y-coordinate for the shapes (e.g., `low`).
โโReturns: A tuple of three `series float` for plotting bullish divergences.
regBullPosY series float Contains the static anchor Y-value for Regular divergences where a shape should be plotted; `na` otherwise.
hidBullPosY series float Contains the static anchor Y-value for Hidden divergences where a shape should be plotted; `na` otherwise.
exgBullPosY series float Contains the static anchor Y-value for Exaggerated divergences where a shape should be plotted; `na` otherwise.
bearDivPos(regBear, hidBear, exgBear, rightLen, yPos)
โโCalculates the plottable data series for bearish divergences. It manages
the complex state of a persistent signal's plotting window to ensure
gap-free and accurately anchored visualization.
โโParameters:
โโโโ regBear (bool) : series bool The regular bearish divergence flag from `bearDiv`.
โโโโ hidBear (bool) : series bool The hidden bearish divergence flag from `bearDiv`.
โโโโ exgBear (bool) : series bool The exaggerated bearish divergence flag from `bearDiv`.
โโโโ rightLen (int) : series int The same `rightLen` value used in `bearDiv` for correct timing.
โโโโ yPos (float) : series float The series providing the base Y-coordinate for the shapes (e.g., `high`).
โโReturns: A tuple of three `series float` for plotting bearish divergences.
regBearPosY series float Contains the static anchor Y-value for Regular divergences where a shape should be plotted; `na` otherwise.
hidBearPosY series float Contains the static anchor Y-value for Hidden divergences where a shape should be plotted; `na` otherwise.
exgBearPosY series float Contains the static anchor Y-value for Exaggerated divergences where a shape should be plotted; `na` otherwise.
marketStructure(highSrc, lowSrc, leftLen, rightLen, srcTol)
โโAnalyzes the market structure by identifying pivot points, classifying
their sequence (e.g., Higher Highs, Lower Lows), and determining the
prevailing trend state.
โโParameters:
โโโโ highSrc (float) : series float Price series for pivot high detection (e.g., `high`).
โโโโ lowSrc (float) : series float Price series for pivot low detection (e.g., `low`).
โโโโ leftLen (int) : series int Number of bars to the left of a pivot (default 5).
โโโโ rightLen (int) : series int Number of bars to the right of a pivot (default 5).
โโโโ srcTol (float) : series float Percentage tolerance to consider two pivots as 'equal' (default 0.05%).
โโReturns: A tuple containing detailed market structure information.
pivType series PivType The type of the most recently formed pivot (e.g., `hh`, `ll`).
lastPivHi series float The price level of the last confirmed pivot high.
lastPivLo series float The price level of the last confirmed pivot low.
lastPiv series float The price level of the last confirmed pivot (either high or low).
pivHiBroken series bool `true` if the price has broken above the last pivot high.
pivLoBroken series bool `true` if the price has broken below the last pivot low.
trendState series TrendState The current trend state (`up`, `down`, or `neutral`).
LibVolmLibrary "LibVolm"
This library provides a collection of core functions for volume and
money flow analysis. It offers implementations of several classic
volume-based indicators, with a focus on flexibility
for applications like multi-timeframe and session-based analysis.
Key Features:
1. **Suite of Classic Volume Indicators:** Includes standard
implementations of several foundational indicators:
- **On Balance Volume (`obv`):** A momentum indicator that
accumulates volume based on price direction.
- **Accumulation/Distribution Line (`adLine`):** Measures cumulative
money flow using the close's position within the bar's range.
- **Chaikin Money Flow (`cmf`):** An oscillator version of the ADL
that measures money flow over a specified lookback period.
2. **Anchored/Resettable Indicators:** The library includes flexible,
resettable indicators ideal for cyclical analysis:
- **Anchored VWAP (`vwap`):** Calculates a Volume Weighted Average
Price that can be reset on any user-defined `reset` condition.
It returns both the VWAP and the number of bars (`prdBars`) in
the current period.
- **Resettable CVD (`cvd`):** Computes a Cumulative Volume Delta
that can be reset on a custom `reset` anchor. The function
also tracks and returns the highest (`hi`) and lowest (`lo`)
delta values reached within the current period.
(Note: The delta sign is determined by a specific logic:
it first checks close vs. open, then close vs. prior
close, and persists the last non-zero sign).
3. **Volume Sanitization:** All functions that use the built-in
`volume` variable automatically sanitize it via an internal
function. This process replaces `na` values with 0 and ensures
no negative volume values are used, providing stable calculations.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
obv(price)
โโCalculates the On Balance Volume (OBV) cumulative indicator.
โโParameters:
โโโโ price (float) : series float Source price series, typically the close.
โโReturns: series float Cumulative OBV value.
adLine()
โโComputes the Accumulation/Distribution Line (AD Line).
โโReturns: series float Cumulative AD Line value.
cmf(length)
โโComputes Chaikin Money Flow (CMF).
โโParameters:
โโโโ length (int) : series int Lookback length for the CMF calculation.
โโReturns: series float CMF value.
vwap(price, reset)
โโCalculates an anchored Volume Weighted Average Price (VWAP).
โโParameters:
โโโโ price (float) : series float Source price series (usually *close*).
โโโโ reset (bool) : series bool A signal that is *true* on the bar where the
accumulation should be reset.
โโReturns:
vwap series float The calculated Volume Weighted Average Price for the current period.
prdBars series int The number of bars that have passed since the last reset.
cvd(reset)
โโCalculates a resettable, cumulative Volume Delta (CVD).
It accumulates volume delta and tracks its high/low range. The
accumulation is reset to zero whenever the `reset` condition is true.
This is useful for session-based analysis, intra-bar calculations,
or any other custom-anchored accumulation.
โโParameters:
โโโโ reset (bool) : series bool A signal that is *true* on the bar where the
accumulation should be reset.
โโReturns:
cum series float The current cumulative volume delta.
hi series float The highest peak the cumulative delta has reached in the current period.
lo series float The lowest trough the cumulative delta has reached in the current period.
LibMvAvLibrary "LibMvAv"
This library provides a unified interface for calculating a
wide variety of moving averages. It is designed to simplify
indicator development by consolidating numerous MA calculations
into a single function and integrating the weighting
capabilities from the `LibWght` library.
Key Features:
1. **All-in-One MA Function:** The core of the library is the
`ma()` function. Users can select the desired calculation
method via the `MAType` enum, which helps create
cleaner and more maintainable code compared to using
many different `ta.*` or custom functions.
2. **Comprehensive Selection of MA Types:** It provides a
selection of 12 different moving averages, covering
common Pine Script built-ins and their weighted counterparts:
- **Standard MAs:** SMA, EMA, WMA, RMA (Wilder's), HMA (Hull), and
LSMA (Least Squares / Linear Regression).
- **Weighted MAs:** Weight-enhanced versions of the above
(WSMA, WEMA, WWMA, WRMA, WHMA, WLSMA).
3. **Integrated Weighting:** The library provides weighted versions
for each of its standard MA types (e.g., `wsma` alongside `sma`).
By acting as a dispatcher, the `ma()` function allows these
weighted calculations to be called using the optional
`weight` parameter, which are then processed by the `LibWght`
library.
4. **Simple API:** The library internally handles the logic of
choosing the correct function based on the selected `MAType`.
The user only needs to provide the source, length, and
optional weight, simplifying the development process.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
ma(maType, source, length, weight)
โโReturns the requested moving average.
โโParameters:
โโโโ maType (simple MAType) : simple MAType Desired type (see enum above).
โโโโ source (float) : series float Data series to smooth.
โโโโ length (simple int) : simple int Look-back / period length.
โโโโ weight (float) : series float Weight series (default = na)
โโReturns: series float Moving-average value.
LibWghtLibrary "LibWght"
This is a library of mathematical and statistical functions
designed for quantitative analysis in Pine Script. Its core
principle is the integration of a custom weighting series
(e.g., volume) into a wide array of standard technical
analysis calculations.
Key Capabilities:
1. **Universal Weighting:** All exported functions accept a `weight`
parameter. This allows standard calculations (like moving
averages, RSI, and standard deviation) to be influenced by an
external data series, such as volume or tick count.
2. **Weighted Averages and Indicators:** Includes a comprehensive
collection of weighted functions:
- **Moving Averages:** `wSma`, `wEma`, `wWma`, `wRma` (Wilder's),
`wHma` (Hull), and `wLSma` (Least Squares / Linear Regression).
- **Oscillators & Ranges:** `wRsi`, `wAtr` (Average True Range),
`wTr` (True Range), and `wR` (High-Low Range).
3. **Volatility Decomposition:** Provides functions to decompose
total variance into distinct components for market analysis.
- **Two-Way Decomposition (`wTotVar`):** Separates variance into
**between-bar** (directional) and **within-bar** (noise)
components.
- **Three-Way Decomposition (`wLRTotVar`):** Decomposes variance
relative to a linear regression into **Trend** (explained by
the LR slope), **Residual** (mean-reversion around the
LR line), and **Within-Bar** (noise) components.
- **Local Volatility (`wLRLocTotStdDev`):** Measures the total
"noise" (within-bar + residual) around the trend line.
4. **Weighted Statistics and Regression:** Provides a robust
function for Weighted Linear Regression (`wLinReg`) and a
full suite of related statistical measures:
- **Between-Bar Stats:** `wBtwVar`, `wBtwStdDev`, `wBtwStdErr`.
- **Residual Stats:** `wResVar`, `wResStdDev`, `wResStdErr`.
5. **Fallback Mechanism:** All functions are designed for reliability.
If the total weight over the lookback period is zero (e.g., in
a no-volume period), the algorithms automatically fall back to
their unweighted, uniform-weight equivalents (e.g., `wSma`
becomes a standard `ta.sma`), preventing errors and ensuring
continuous calculation.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
wSma(source, weight, length)
โโWeighted Simple Moving Average (linear kernel).
โโParameters:
โโโโ source (float) : series float Data to average.
โโโโ weight (float) : series float Weight series.
โโโโ length (int) : series int Look-back length โฅ 1.
โโReturns: series float Linear-kernel weighted mean; falls back to
the arithmetic mean if ฮฃweight = 0.
wEma(source, weight, length)
โโWeighted EMA (exponential kernel).
โโParameters:
โโโโ source (float) : series float Data to average.
โโโโ weight (float) : series float Weight series.
โโโโ length (simple int) : simple int Look-back length โฅ 1.
โโReturns: series float Exponential-kernel weighted mean; falls
back to classic EMA if ฮฃweight = 0.
wWma(source, weight, length)
โโWeighted WMA (linear kernel).
โโParameters:
โโโโ source (float) : series float Data to average.
โโโโ weight (float) : series float Weight series.
โโโโ length (int) : series int Look-back length โฅ 1.
โโReturns: series float Linear-kernel weighted mean; falls back to
classic WMA if ฮฃweight = 0.
wRma(source, weight, length)
โโWeighted RMA (Wilder kernel, ฮฑ = 1/len).
โโParameters:
โโโโ source (float) : series float Data to average.
โโโโ weight (float) : series float Weight series.
โโโโ length (simple int) : simple int Look-back length โฅ 1.
โโReturns: series float Wilder-kernel weighted mean; falls back to
classic RMA if ฮฃweight = 0.
wHma(source, weight, length)
โโWeighted HMA (linear kernel).
โโParameters:
โโโโ source (float) : series float Data to average.
โโโโ weight (float) : series float Weight series.
โโโโ length (int) : series int Look-back length โฅ 1.
โโReturns: series float Linear-kernel weighted mean; falls back to
classic HMA if ฮฃweight = 0.
wRsi(source, weight, length)
โโWeighted Relative Strength Index.
โโParameters:
โโโโ source (float) : series float Price series.
โโโโ weight (float) : series float Weight series.
โโโโ length (simple int) : simple int Look-back length โฅ 1.
โโReturns: series float Weighted RSI; uniform if ฮฃw = 0.
wAtr(tr, weight, length)
โโWeighted ATR (Average True Range).
Implemented as WRMA on *true range*.
โโParameters:
โโโโ tr (float) : series float True Range series.
โโโโ weight (float) : series float Weight series.
โโโโ length (simple int) : simple int Look-back length โฅ 1.
โโReturns: series float Weighted ATR; uniform weights if ฮฃw = 0.
wTr(tr, weight, length)
โโWeighted True Range over a window.
โโParameters:
โโโโ tr (float) : series float True Range series.
โโโโ weight (float) : series float Weight series.
โโโโ length (int) : series int Look-back length โฅ 1.
โโReturns: series float Weighted mean of TR; uniform if ฮฃw = 0.
wR(r, weight, length)
โโWeighted High-Low Range over a window.
โโParameters:
โโโโ r (float) : series float High-Low per bar.
โโโโ weight (float) : series float Weight series.
โโโโ length (int) : series int Look-back length โฅ 1.
โโReturns: series float Weighted mean of range; uniform if ฮฃw = 0.
wBtwVar(source, weight, length, biased)
โโWeighted Between Variance (biased/unbiased).
โโParameters:
โโโโ source (float) : series float Data series.
โโโโ weight (float) : series float Weight series.
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population (biased); false โ sample.
โโReturns:
variance series float The calculated between-bar variance (ฯยฒbtw), either biased or unbiased.
sumW series float The sum of weights over the lookback period (ฮฃw).
sumW2 series float The sum of squared weights over the lookback period (ฮฃwยฒ).
wBtwStdDev(source, weight, length, biased)
โโWeighted Between Standard Deviation.
โโParameters:
โโโโ source (float) : series float Data series.
โโโโ weight (float) : series float Weight series.
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population (biased); false โ sample.
โโReturns: series float ฯbtw uniform if ฮฃw = 0.
wBtwStdErr(source, weight, length, biased)
โโWeighted Between Standard Error.
โโParameters:
โโโโ source (float) : series float Data series.
โโโโ weight (float) : series float Weight series.
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population (biased); false โ sample.
โโReturns: series float โ(ฯยฒbtw / N_eff) uniform if ฮฃw = 0.
wTotVar(mu, sigma, weight, length, biased)
โโWeighted Total Variance (= between-group + within-group).
Useful when each bar represents an aggregate with its own
mean* and pre-estimated ฯ (e.g., second-level ranges inside a
1-minute bar). Assumes the *weight* series applies to both the
group means and their ฯ estimates.
โโParameters:
โโโโ mu (float) : series float Group means (e.g., HL2 of 1-second bars).
โโโโ sigma (float) : series float Pre-estimated ฯ of each group (same basis).
โโโโ weight (float) : series float Weight series (volume, ticks, โฆ).
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population (biased); false โ sample.
โโReturns:
varBtw series float The between-bar variance component (ฯยฒbtw).
varWtn series float The within-bar variance component (ฯยฒwtn).
sumW series float The sum of weights over the lookback period (ฮฃw).
sumW2 series float The sum of squared weights over the lookback period (ฮฃwยฒ).
wTotStdDev(mu, sigma, weight, length, biased)
โโWeighted Total Standard Deviation.
โโParameters:
โโโโ mu (float) : series float Group means (e.g., HL2 of 1-second bars).
โโโโ sigma (float) : series float Pre-estimated ฯ of each group (same basis).
โโโโ weight (float) : series float Weight series (volume, ticks, โฆ).
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population (biased); false โ sample.
โโReturns: series float ฯtot.
wTotStdErr(mu, sigma, weight, length, biased)
โโWeighted Total Standard Error.
SE = โ( total variance / N_eff ) with the same effective sample
size logic as `wster()`.
โโParameters:
โโโโ mu (float) : series float Group means (e.g., HL2 of 1-second bars).
โโโโ sigma (float) : series float Pre-estimated ฯ of each group (same basis).
โโโโ weight (float) : series float Weight series (volume, ticks, โฆ).
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population (biased); false โ sample.
โโReturns: series float โ(ฯยฒtot / N_eff).
wLinReg(source, weight, length)
โโWeighted Linear Regression.
โโParameters:
โโโโ source (float) : series float Data series.
โโโโ weight (float) : series float Weight series.
โโโโ length (int) : series int Look-back length โฅ 2.
โโReturns:
mid series float The estimated value of the regression line at the most recent bar.
slope series float The slope of the regression line.
intercept series float The intercept of the regression line.
wResVar(source, weight, midLine, slope, length, biased)
โโWeighted Residual Variance.
linear regression โ optionally biased (population) or
unbiased (sample).
โโParameters:
โโโโ source (float) : series float Data series.
โโโโ weight (float) : series float Weighting series (volume, etc.).
โโโโ midLine (float) : series float Regression value at the last bar.
โโโโ slope (float) : series float Slope per bar.
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population variance (ฯยฒ_P), denominator โ N_eff.
false โ sample variance (ฯยฒ_S), denominator โ N_eff - 2.
(Adjusts for 2 degrees of freedom lost to the regression).
โโReturns:
variance series float The calculated residual variance (ฯยฒres), either biased or unbiased.
sumW series float The sum of weights over the lookback period (ฮฃw).
sumW2 series float The sum of squared weights over the lookback period (ฮฃwยฒ).
wResStdDev(source, weight, midLine, slope, length, biased)
โโWeighted Residual Standard Deviation.
โโParameters:
โโโโ source (float) : series float Data series.
โโโโ weight (float) : series float Weight series.
โโโโ midLine (float) : series float Regression value at the last bar.
โโโโ slope (float) : series float Slope per bar.
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population (biased); false โ sample.
โโReturns: series float ฯres; uniform if ฮฃw = 0.
wResStdErr(source, weight, midLine, slope, length, biased)
โโWeighted Residual Standard Error.
โโParameters:
โโโโ source (float) : series float Data series.
โโโโ weight (float) : series float Weight series.
โโโโ midLine (float) : series float Regression value at the last bar.
โโโโ slope (float) : series float Slope per bar.
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population (biased); false โ sample.
โโReturns: series float โ(ฯยฒres / N_eff); uniform if ฮฃw = 0.
wLRTotVar(mu, sigma, weight, midLine, slope, length, biased)
โโWeighted Linear-Regression Total Variance **around the
windowโs weighted mean ฮผ**.
ฯยฒ_tot = E_w โถ *within-group variance*
+ Var_w โถ *residual variance*
+ Var_w โถ *trend variance*
where each bar i in the look-back window contributes
m_i = *mean* (e.g. 1-sec HL2)
ฯ_i = *sigma* (pre-estimated intrabar ฯ)
w_i = *weight* (volume, ticks, โฆ)
ลท_i = bโ + bโยทx (value of the weighted LR line)
r_i = m_i โ ลท_i (orthogonal residual)
โโParameters:
โโโโ mu (float) : series float Per-bar mean m_i.
โโโโ sigma (float) : series float Pre-estimated ฯ_i of each bar.
โโโโ weight (float) : series float Weight series w_i (โฅ 0).
โโโโ midLine (float) : series float Regression value at the latest bar (ลทโโโ).
โโโโ slope (float) : series float Slope bโ of the regression line.
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population; false โ sample.
โโReturns:
varRes series float The residual variance component (ฯยฒres).
varWtn series float The within-bar variance component (ฯยฒwtn).
varTrd series float The trend variance component (ฯยฒtrd), explained by the linear regression.
sumW series float The sum of weights over the lookback period (ฮฃw).
sumW2 series float The sum of squared weights over the lookback period (ฮฃwยฒ).
wLRTotStdDev(mu, sigma, weight, midLine, slope, length, biased)
โโWeighted Linear-Regression Total Standard Deviation.
โโParameters:
โโโโ mu (float) : series float Per-bar mean m_i.
โโโโ sigma (float) : series float Pre-estimated ฯ_i of each bar.
โโโโ weight (float) : series float Weight series w_i (โฅ 0).
โโโโ midLine (float) : series float Regression value at the latest bar (ลทโโโ).
โโโโ slope (float) : series float Slope bโ of the regression line.
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population; false โ sample.
โโReturns: series float โ(ฯยฒtot).
wLRTotStdErr(mu, sigma, weight, midLine, slope, length, biased)
โโWeighted Linear-Regression Total Standard Error.
SE = โ( ฯยฒ_tot / N_eff ) with N_eff = ฮฃwยฒ / ฮฃwยฒ (like in wster()).
โโParameters:
โโโโ mu (float) : series float Per-bar mean m_i.
โโโโ sigma (float) : series float Pre-estimated ฯ_i of each bar.
โโโโ weight (float) : series float Weight series w_i (โฅ 0).
โโโโ midLine (float) : series float Regression value at the latest bar (ลทโโโ).
โโโโ slope (float) : series float Slope bโ of the regression line.
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population; false โ sample.
โโReturns: series float โ((ฯยฒres, ฯยฒwtn, ฯยฒtrd) / N_eff).
wLRLocTotStdDev(mu, sigma, weight, midLine, slope, length, biased)
โโWeighted Linear-Regression Local Total Standard Deviation.
Measures the total "noise" (within-bar + residual) around the trend.
โโParameters:
โโโโ mu (float) : series float Per-bar mean m_i.
โโโโ sigma (float) : series float Pre-estimated ฯ_i of each bar.
โโโโ weight (float) : series float Weight series w_i (โฅ 0).
โโโโ midLine (float) : series float Regression value at the latest bar (ลทโโโ).
โโโโ slope (float) : series float Slope bโ of the regression line.
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population; false โ sample.
โโReturns: series float โ(ฯยฒwtn + ฯยฒres).
wLRLocTotStdErr(mu, sigma, weight, midLine, slope, length, biased)
โโWeighted Linear-Regression Local Total Standard Error.
โโParameters:
โโโโ mu (float) : series float Per-bar mean m_i.
โโโโ sigma (float) : series float Pre-estimated ฯ_i of each bar.
โโโโ weight (float) : series float Weight series w_i (โฅ 0).
โโโโ midLine (float) : series float Regression value at the latest bar (ลทโโโ).
โโโโ slope (float) : series float Slope bโ of the regression line.
โโโโ length (int) : series int Look-back length โฅ 2.
โโโโ biased (bool) : series bool true โ population; false โ sample.
โโReturns: series float โ((ฯยฒwtn + ฯยฒres) / N_eff).
wLSma(source, weight, length)
โโWeighted Least Square Moving Average.
โโParameters:
โโโโ source (float) : series float Data series.
โโโโ weight (float) : series float Weight series.
โโโโ length (int) : series int Look-back length โฅ 2.
โโReturns: series float Least square weighted mean. Falls back
to unweighted regression if ฮฃw = 0.
mysourcetypesncsLibrary "mysourcetypes"
Libreria personale per sorgenti estese (Close, Open, High, Low, Median, Typical, Weighted, Average, Average Median Body, Trend Biased, Trend Biased Extreme, Volume Body, Momentum Biased, Volatility Adjusted, Body Dominance, Shadow Biased, Gap Aware, Rejection Biased, Range Position, Adaptive Trend, Pressure Balanced, Impulse Wave)
rclose()
โโRegular Close
โโReturns: Close price
ropen()
โโRegular Open
โโReturns: Open price
rhigh()
โโRegular High
โโReturns: High price
rlow()
โโRegular Low
โโReturns: Low price
rmedian()
โโRegular Median (HL2)
โโReturns: (High + Low) / 2
rtypical()
โโRegular Typical (HLC3)
โโReturns: (High + Low + Close) / 3
rweighted()
โโRegular Weighted (HLCC4)
โโReturns: (High + Low + Close + Close) / 4
raverage()
โโRegular Average (OHLC4)
โโReturns: (Open + High + Low + Close) / 4
ravemedbody()
โโAverage Median Body
โโReturns: (Open + Close) / 2
rtrendb()
โโTrend Biased Regular
โโReturns: Trend-weighted price
rtrendbext()
โโTrend Biased Extreme
โโReturns: Extreme trend-weighted price
rvolbody()
โโVolume Weighted Body
โโReturns: Body midpoint weighted by volume intensity
rmomentum()
โโMomentum Biased
โโReturns: Price biased towards momentum direction
rvolatility()
โโVolatility Adjusted
โโReturns: Price adjusted by candle's volatility
rbodydominance()
โโBody Dominance
โโReturns: Emphasizes body over wicks
rshadowbias()
โโShadow Biased
โโReturns: Price biased by shadow length
rgapaware()
โโGap Aware
โโReturns: Considers gap between candles
rrejection()
โโRejection Biased
โโReturns: Emphasizes price rejection levels
rrangeposition()
โโRange Position
โโReturns: Where close sits within the candle range (0-100%)
radaptivetrend()
โโAdaptive Trend
โโReturns: Adapts based on recent trend strength
rpressure()
โโPressure Balanced
โโReturns: Balances buying/selling pressure within candle
rimpulse()
โโImpulse Wave
โโReturns: Detects impulsive moves vs corrections
BossExoticMAs
A next-generation moving average and smoothing library by TheStopLossBoss, featuring premium adaptive, exotic, and DSP-inspired filters โ optimized for Pine Scriptยฎ v6 and designed for Traders who demand precision and beauty.
> BossExoticMAs is a complete moving average and signal-processing toolkit built for Pine Script v6.
It combines the essential trend filters (SMA, EMA, WMA, etc.) with advanced, high-performance exotic types used by quants, algo designers, and adaptive systems.
Each function is precision-tuned for stability, speed, and visual clarity โ perfect for building custom baselines, volatility filters, dynamic ribbons, or hybrid signal engines.
Includes built-in color gradient theming powered by the exclusive BossGradient โ
//Key Features
โ
Full Moving Average Set
SMA, EMA, ZEMA, WMA, HMA, WWMA, SMMA
DEMA, TEMA, T3 (Tillson)
ALMA, KAMA, LSMA
VMA, VAMA, FRAMA
โ
Signal Filters
One-Euro Filter (Crispin/Casiez implementation)
ATR-bounded Range Filter
โ
Color Engine
lerpColor() safe blending using color.from_gradient
Thematic gradient palettes: STOPLOSS, VAPORWAVE, ROYAL FLAME, MATRIX FLOW
Exclusive: BOSS GRADIENT
โ
Helper Functions
Clamping, normalization, slope detection, tick delta
Slope-based dynamic color control via slopeThemeColor()
๐ง Usage Example
//@version=6
indicator("Boss Exotic MA Demo", overlay=true)
import TheStopLossBoss/BossExoticMAs/1 as boss
len = input.int(50, "Length")
atype = input.string("T3", "MA Type", options= )
t3factor = input.float(0.7, "T3 ฮฒ", step=0.05)
smoothColor = boss.slopeThemeColor(close, "BOSS GRADIENT", 0.001)ma = boss.maSelect(close, len, atype, t3factor, 0.85, 14)
plot(ma, "Boss Exotic MA", color=smoothColor, linewidth=2)
---
๐ Notes
Built exclusively for Pine Scriptยฎ v6
Library designed for import use โ all exports are prefixed cleanly (boss.functionName())
Some functions maintain internal state (var-based). Warnings are safe to ignore โ adaptive design choice.
Each MA output is non-repainting and mathematically stable.
---
๐ Author
TheStopLossBoss
Designer of precision trading systems and custom adaptive algorithms.
Follow for exclusive releases, educational material, and full-stack trend solutions.
movingaverage, trend, adaptive, filter, volatility, smoothing, quant, technicalanalysis, bossgradient, t3, alma, frama, vma
livremySMATestLibLibrary "livremySMATestLib"
TODO: add library description here
mySMA(x)
โโTODO: add function description here
โโParameters:
โโโโ x (int) : TODO: add parameter x description here
โโReturns: TODO: add what function returns
SequencerLibraryLibrary "SequencerLibrary"
SequencerLibrary v1 is a Pine Scriptโข library for identifying, tracking, and visualizing
sequential bullish and bearish patterns on price charts.
It provides a complete framework for building sequence-based trading systems, including:
โข Automatic detection and counting of setup and countdown phases.
โข Real-time tracking of completion states, perfected setups, and exhaustion signals.
โข Dynamic support and resistance thresholds derived from recent price structure.
โข Customizable visual highlighting for both setup and countdown sequences.
method doSequence(s, src, config, condition)
โโUpdates the sequence state based on the source value, and user configuration.
โโNamespace types: Sequence
โโParameters:
โโโโ s (Sequence) : The sequence object containing bullish and bearish setups.
โโโโ src (float) : The source value (e.g., close price) used for evaluating sequence conditions.
โโโโ config (SequenceInputs) : The user-defined settings for sequence analysis.
โโโโ condition (bool) : When true, executes the sequence logic.
โโReturns:
highlight(s, css, condition)
โโHighlights the bullish and bearish sequence setups and countdowns on the chart.
โโParameters:
โโโโ s (Sequence) : The sequence object containing bullish and bearish sequence states.
โโโโ css (SequenceCSS) : The styling configuration for customizing label appearances.
โโโโ condition (bool) : When true, the function creates and displays labels for setups and countdowns.
โโReturns:
SequenceState
โโA type representing the configuration and state of a sequence setup.
โโFields:
โโโโ setup (series int) : Current count of the setup phase (e.g., how many bars have met the setup criteria).
โโโโ countdown (series int) : Current count of the countdown phase (e.g., bars meeting countdown criteria).
โโโโ threshold (series float) : The price threshold level used as support/resistance for the sequence.
โโโโ priceWhenCompleted (series float) : The closing price when the setup or countdown phase is completed.
โโโโ indicatorWhenCompleted (series float) : The indicator value when the setup or countdown phase is completed.
โโโโ setupCompleted (series bool) : Indicates if the setup phase has been completed (i.e., reached the required count).
โโโโ countdownCompleted (series bool) : Indicates if the countdown phase has been completed (i.e., reached exhaustion).
โโโโ perfected (series bool) : Indicates if the setup meets the "perfected" condition (e.g., aligns with strict criteria).
โโโโ highlightSetup (series bool) : Determines whether the setup phase should be visually highlighted on the chart.
โโโโ highlightCountdown (series bool) : Determines whether the countdown phase should be visually highlighted on the chart.
Sequence
โโA type containing bullish and bearish sequence setups.
โโFields:
โโโโ bullish (SequenceState) : Configuration and state for bullish sequences.
โโโโ bearish (SequenceState) : Configuration and state for bearish sequences.
SequenceInputs
โโA type for user-configurable input settings for sequence-based analysis.
โโFields:
โโโโ showSetup (series bool) : Enables or disables the display of setup sequences.
โโโโ showCountdown (series bool) : Enables or disables the display of countdown sequences.
โโโโ setupFilter (series string) : A commaโseparated string containing setup sequence counts to be highlighted (e.g., "1,2,3,4,5,6,7,8,9").
โโโโ countdownFilter (series string) : A commaโseparated string containing countdown sequence counts to be highlighted (e.g., "1,2,3,4,5,6,7,8,9,10,11,12,13").
โโโโ lookbackSetup (series int) : Defines the lookback period for evaluating setup conditions (default: 4 bars).
โโโโ lookbackCountdown (series int) : Defines the lookback period for evaluating countdown conditions (default: 2 bars).
โโโโ lookbackSetupPerfected (series int) : Defines the lookback period to determine a perfected setup condition (default: 6 bars).
โโโโ maxSetup (series int) : The maximum count required to complete a setup phase (default: 9).
โโโโ maxCountdown (series int) : The maximum count required to complete a countdown phase (default: 13).
SequenceCSS
โโA type defining the visual styling options for sequence labels.
โโFields:
โโโโ bullish (series color) : Color used for bullish sequence labels.
โโโโ bearish (series color) : Color used for bearish sequence labels.
โโโโ imperfect (series color) : Color used for labels representing imperfect sequences.
AlertSenderLibrary_TradingFinderLibrary "AlertSenderLibrary_TradingFinder"
TODO: add library description here
AlertSender(Condition, Alert, AlertName, AlertType, DetectionType, SetupData, Frequncy, UTC, MoreInfo, Message, o, h, l, c, Entry, TP, SL, Distal, Proximal)
โโParameters:
โโโโ Condition (bool)
โโโโ Alert (string)
โโโโ AlertName (string)
โโโโ AlertType (string)
โโโโ DetectionType (string)
โโโโ SetupData (string)
โโโโ Frequncy (string)
โโโโ UTC (string)
โโโโ MoreInfo (string)
โโโโ Message (string)
โโโโ o (float)
โโโโ h (float)
โโโโ l (float)
โโโโ c (float)
โโโโ Entry (float)
โโโโ TP (float)
โโโโ SL (float)
โโโโ Distal (float)
โโโโ Proximal (float)
TAโ TA Library
๐ OVERVIEW
TA is a Pine Script technical analysis library. This library provides 25+ moving averages and smoothing filters , from classic SMA/EMA to Kalman Filters and adaptive algorithms, implemented based on academic research.
๐ฏ Core Features
Academic Based - Algorithms follow original papers and formulas
Performance Optimized - Pre-calculated constants for faster response
Unified Interface - Consistent function design
Research Based - Integrates technical analysis research
๐ฏ CONCEPTS
Library Design Philosophy
This technical analysis library focuses on providing:
Academic Foundation
Algorithms based on published research papers and academic standards
Implementations that follow original mathematical formulations
Clear documentation with research references
Developer Experience
Unified interface design for consistent usage patterns
Pre-calculated constants for optimal performance
Comprehensive function collection to reduce development time
Single import statement for immediate access to all functions
Each indicator encapsulated as a simple function call - one line of code simplifies complexity
Technical Excellence
25+ carefully implemented moving averages and filters
Support for advanced algorithms like Kalman Filter and MAMA/FAMA
Optimized code structure for maintainability and reliability
Regular updates incorporating latest research developments
๐ USING THIS LIBRARY
Import Library
//@version=6
import DCAUT/TA/1 as dta
indicator("Advanced Technical Analysis", overlay=true)
Basic Usage Example
// Classic moving average combination
ema20 = ta.ema(close, 20)
kama20 = dta.kama(close, 20)
plot(ema20, "EMA20", color.red, 2)
plot(kama20, "KAMA20", color.green, 2)
Advanced Trading System
// Adaptive moving average system
kama = dta.kama(close, 20, 2, 30)
= dta.mamaFama(close, 0.5, 0.05)
// Trend confirmation and entry signals
bullTrend = kama > kama and mamaValue > famaValue
bearTrend = kama < kama and mamaValue < famaValue
longSignal = ta.crossover(close, kama) and bullTrend
shortSignal = ta.crossunder(close, kama) and bearTrend
plot(kama, "KAMA", color.blue, 3)
plot(mamaValue, "MAMA", color.orange, 2)
plot(famaValue, "FAMA", color.purple, 2)
plotshape(longSignal, "Buy", shape.triangleup, location.belowbar, color.green)
plotshape(shortSignal, "Sell", shape.triangledown, location.abovebar, color.red)
๐ FUNCTIONS REFERENCE
ewma(source, alpha)
Calculates the Exponentially Weighted Moving Average with dynamic alpha parameter.
Parameters:
source (series float) : Series of values to process.
alpha (series float) : The smoothing parameter of the filter.
Returns: (float) The exponentially weighted moving average value.
dema(source, length)
Calculates the Double Exponential Moving Average (DEMA) of a given data series.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Double Exponential Moving Average value.
tema(source, length)
Calculates the Triple Exponential Moving Average (TEMA) of a given data series.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Triple Exponential Moving Average value.
zlema(source, length)
Calculates the Zero-Lag Exponential Moving Average (ZLEMA) of a given data series. This indicator attempts to eliminate the lag inherent in all moving averages.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Zero-Lag Exponential Moving Average value.
tma(source, length)
Calculates the Triangular Moving Average (TMA) of a given data series. TMA is a double-smoothed simple moving average that reduces noise.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Triangular Moving Average value.
frama(source, length)
Calculates the Fractal Adaptive Moving Average (FRAMA) of a given data series. FRAMA adapts its smoothing factor based on fractal geometry to reduce lag. Developed by John Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: (float) The calculated Fractal Adaptive Moving Average value.
kama(source, length, fastLength, slowLength)
Calculates Kaufman's Adaptive Moving Average (KAMA) of a given data series. KAMA adjusts its smoothing based on market efficiency ratio. Developed by Perry J. Kaufman.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the efficiency calculation.
fastLength (simple int) : Fast EMA length for smoothing calculation. Optional. Default is 2.
slowLength (simple int) : Slow EMA length for smoothing calculation. Optional. Default is 30.
Returns: (float) The calculated Kaufman's Adaptive Moving Average value.
t3(source, length, volumeFactor)
Calculates the Tilson Moving Average (T3) of a given data series. T3 is a triple-smoothed exponential moving average with improved lag characteristics. Developed by Tim Tillson.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
volumeFactor (simple float) : Volume factor affecting responsiveness. Optional. Default is 0.7.
Returns: (float) The calculated Tilson Moving Average value.
ultimateSmoother(source, length)
Calculates the Ultimate Smoother of a given data series. Uses advanced filtering techniques to reduce noise while maintaining responsiveness. Based on digital signal processing principles by John Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the smoothing calculation.
Returns: (float) The calculated Ultimate Smoother value.
kalmanFilter(source, processNoise, measurementNoise)
Calculates the Kalman Filter of a given data series. Optimal estimation algorithm that estimates true value from noisy observations. Based on the Kalman Filter algorithm developed by Rudolf Kalman (1960).
Parameters:
source (series float) : Series of values to process.
processNoise (simple float) : Process noise variance (Q). Controls adaptation speed. Optional. Default is 0.05.
measurementNoise (simple float) : Measurement noise variance (R). Controls smoothing. Optional. Default is 1.0.
Returns: (float) The calculated Kalman Filter value.
mcginleyDynamic(source, length)
Calculates the McGinley Dynamic of a given data series. McGinley Dynamic is an adaptive moving average that adjusts to market speed changes. Developed by John R. McGinley Jr.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the dynamic calculation.
Returns: (float) The calculated McGinley Dynamic value.
mama(source, fastLimit, slowLimit)
Calculates the Mesa Adaptive Moving Average (MAMA) of a given data series. MAMA uses Hilbert Transform Discriminator to adapt to market cycles dynamically. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
fastLimit (simple float) : Maximum alpha (responsiveness). Optional. Default is 0.5.
slowLimit (simple float) : Minimum alpha (smoothing). Optional. Default is 0.05.
Returns: (float) The calculated Mesa Adaptive Moving Average value.
fama(source, fastLimit, slowLimit)
Calculates the Following Adaptive Moving Average (FAMA) of a given data series. FAMA follows MAMA with reduced responsiveness for crossover signals. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
fastLimit (simple float) : Maximum alpha (responsiveness). Optional. Default is 0.5.
slowLimit (simple float) : Minimum alpha (smoothing). Optional. Default is 0.05.
Returns: (float) The calculated Following Adaptive Moving Average value.
mamaFama(source, fastLimit, slowLimit)
Calculates Mesa Adaptive Moving Average (MAMA) and Following Adaptive Moving Average (FAMA).
Parameters:
source (series float) : Series of values to process.
fastLimit (simple float) : Maximum alpha (responsiveness). Optional. Default is 0.5.
slowLimit (simple float) : Minimum alpha (smoothing). Optional. Default is 0.05.
Returns: ( ) Tuple containing values.
laguerreFilter(source, length, gamma, order)
Calculates the standard N-order Laguerre Filter of a given data series. Standard Laguerre Filter uses uniform weighting across all polynomial terms. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Length for UltimateSmoother preprocessing.
gamma (simple float) : Feedback coefficient (0-1). Lower values reduce lag. Optional. Default is 0.8.
order (simple int) : The order of the Laguerre filter (1-10). Higher order increases lag. Optional. Default is 8.
Returns: (float) The calculated standard Laguerre Filter value.
laguerreBinomialFilter(source, length, gamma)
Calculates the Laguerre Binomial Filter of a given data series. Uses 6-pole feedback with binomial weighting coefficients. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Length for UltimateSmoother preprocessing.
gamma (simple float) : Feedback coefficient (0-1). Lower values reduce lag. Optional. Default is 0.5.
Returns: (float) The calculated Laguerre Binomial Filter value.
superSmoother(source, length)
Calculates the Super Smoother of a given data series. SuperSmoother is a second-order Butterworth filter from aerospace technology. Developed by John F. Ehlers.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Period for the filter calculation.
Returns: (float) The calculated Super Smoother value.
rangeFilter(source, length, multiplier)
Calculates the Range Filter of a given data series. Range Filter reduces noise by filtering price movements within a dynamic range.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the average range calculation.
multiplier (simple float) : Multiplier for the smooth range. Higher values increase filtering. Optional. Default is 2.618.
Returns: ( ) Tuple containing filtered value, trend direction, upper band, and lower band.
qqe(source, rsiLength, rsiSmooth, qqeFactor)
Calculates the Quantitative Qualitative Estimation (QQE) of a given data series. QQE is an improved RSI that reduces noise and provides smoother signals. Developed by Igor Livshin.
Parameters:
source (series float) : Series of values to process.
rsiLength (simple int) : Number of bars for the RSI calculation. Optional. Default is 14.
rsiSmooth (simple int) : Number of bars for smoothing the RSI. Optional. Default is 5.
qqeFactor (simple float) : QQE factor for volatility band width. Optional. Default is 4.236.
Returns: ( ) Tuple containing smoothed RSI and QQE trend line.
sslChannel(source, length)
Calculates the Semaphore Signal Level (SSL) Channel of a given data series. SSL Channel provides clear trend signals using moving averages of high and low prices.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
Returns: ( ) Tuple containing SSL Up and SSL Down lines.
ma(source, length, maType)
Calculates a Moving Average based on the specified type. Universal interface supporting all moving average algorithms.
Parameters:
source (series float) : Series of values to process.
length (simple int) : Number of bars for the moving average calculation.
maType (simple MaType) : Type of moving average to calculate. Optional. Default is SMA.
Returns: (float) The calculated moving average value based on the specified type.
atr(length, maType)
Calculates the Average True Range (ATR) using the specified moving average type. Developed by J. Welles Wilder Jr.
Parameters:
length (simple int) : Number of bars for the ATR calculation.
maType (simple MaType) : Type of moving average to use for smoothing. Optional. Default is RMA.
Returns: (float) The calculated Average True Range value.
macd(source, fastLength, slowLength, signalLength, maType, signalMaType)
Calculates the Moving Average Convergence Divergence (MACD) with customizable MA types. Developed by Gerald Appel.
Parameters:
source (series float) : Series of values to process.
fastLength (simple int) : Period for the fast moving average.
slowLength (simple int) : Period for the slow moving average.
signalLength (simple int) : Period for the signal line moving average.
maType (simple MaType) : Type of moving average for main MACD calculation. Optional. Default is EMA.
signalMaType (simple MaType) : Type of moving average for signal line calculation. Optional. Default is EMA.
Returns: ( ) Tuple containing MACD line, signal line, and histogram values.
dmao(source, fastLength, slowLength, maType)
Calculates the Dual Moving Average Oscillator (DMAO) of a given data series. Uses the same algorithm as the Percentage Price Oscillator (PPO), but can be applied to any data series.
Parameters:
source (series float) : Series of values to process.
fastLength (simple int) : Period for the fast moving average.
slowLength (simple int) : Period for the slow moving average.
maType (simple MaType) : Type of moving average to use for both calculations. Optional. Default is EMA.
Returns: (float) The calculated Dual Moving Average Oscillator value as a percentage.
continuationIndex(source, length, gamma, order)
Calculates the Continuation Index of a given data series. The index represents the Inverse Fisher Transform of the normalized difference between an UltimateSmoother and an N-order Laguerre filter. Developed by John F. Ehlers, published in TASC 2025.09.
Parameters:
source (series float) : Series of values to process.
length (simple int) : The calculation length.
gamma (simple float) : Controls the phase response of the Laguerre filter. Optional. Default is 0.8.
order (simple int) : The order of the Laguerre filter (1-10). Optional. Default is 8.
Returns: (float) The calculated Continuation Index value.
๐ RELEASE NOTES
v1.0 (2025.09.24)
โ
25+ technical analysis functions
โ
Complete adaptive moving average series (KAMA, FRAMA, MAMA/FAMA)
โ
Advanced signal processing filters (Kalman, Laguerre, SuperSmoother, UltimateSmoother)
โ
Performance optimized with pre-calculated constants and efficient algorithms
โ
Unified function interface design following TradingView best practices
โ
Comprehensive moving average collection (DEMA, TEMA, ZLEMA, T3, etc.)
โ
Volatility and trend detection tools (QQE, SSL Channel, Range Filter)
โ
Continuation Index - Latest research from TASC 2025.09
โ
MACD and ATR calculations supporting multiple moving average types
โ
Dual Moving Average Oscillator (DMAO) for arbitrary data series analysis






















