Library

Objective Market Structure FrameworkThis library provides a systematic, rule-based approach to categorize market movements into four objective phases: Compression, Expansion, Distribution, and Consolidation.
Instead of subjective chart patterns, this tool uses volatility-relative thresholds (ATR) and momentum filters to identify significant trading ranges and structural breaks.
Main Use Cases:
Clear & Compact MTF Visualization: Map higher-timeframe (HTF) market structures directly onto your lower-timeframe (LTF) charts. Provides a clean, non-cluttered overview for an intuitive display of key levels without overcomplicating the chart.
Automated Setup Classification: Assign specific trading setups to distinct market regimes (Uptrends, Corrections, Sideways Ranges). Enables rapid, objective analysis every trading day, eliminating the need for manual re-evaluation or "hunting" for the current trend state.
Core Features:
Volatility-Adaptive: Range calculations scale automatically with the market's current ATR, making the analysis relevant across all asset classes.
MTF-Optimized Performance: Engineered for professional Multi-Timeframe workflows. Fetch 19 structural variables with a single request.security() call to minimize script load and prevent memory errors.
Momentum Validation: Distinguishes between high-conviction structural breaks and low-momentum "noise" using body-to-ATR ratios.
Reliability & Stability: Built-in Guard-Clauses protect against "Bar 0" and "NA" runtime errors, even when requesting lower timeframe data from a higher timeframe chart.
Key Parameters (Customizable Defaults):
Distribution Threshold (e.g. 1.2): Identifies price movement beyond the established range to confirm trend strength.
Compression (e.g. 1.5x ATR): Detects low-volatility buildup phases.
Expansion (e.g. 4.0x ATR): Flags explosive "Huge Range" impulses.
How to use (Educational Example included):
The source code contains a fully functional MTF Dashboard example (commented out at the bottom). It demonstrates how to map the library’s output variables into a visual trading interface, showing HTF trend alignment and real-time market phases.
Quick Start (Implementation):
import arnipoer/PriceActionStructure/1 as pa
// Single request for all 19 structural variables
=
request.security(syminfo.tickerid, "D",
pa.get_structure(true, 1.0, close, 14, 1.2, 1.5, 4.0))
// Example: Visualization
plot(strHigh, color=color.aqua, title="HTF Structure High")
bgcolor(hugeRange ? color.new(color.purple, 80) : na, title="Expansion Alert")
Disclaimer: No financial advice. Trading involves significant risk. This is an analytical tool for professional traders to build their own systematic strategies. Library

GLLV_HelpersLibrary "GLLV_Helpers"
buildAlertMsg(pineLic, ticker, risk, sl, tp, strategyCode)
Parameters:
pineLic (string)
ticker (string)
risk (float)
sl (float)
tp (float)
strategyCode (string)
isRising(src, points, step)
Parameters:
src (float)
points (int)
step (int)
regimeOf(pip2, posLimit, negLimit)
Parameters:
pip2 (float)
posLimit (float)
negLimit (float)
calcMata(fast, mid, slow)
Parameters:
fast (float)
mid (float)
slow (float)
crossUpByColor(src, ema, pvsraColor, expectedColor)
Parameters:
src (float)
ema (float)
pvsraColor (color)
expectedColor (color)
crossDownByColor(src, ema, pvsraColor, expectedColor)
Parameters:
src (float)
ema (float)
pvsraColor (color)
expectedColor (color)
calcSlope(src, length, mult, method)
Parameters:
src (float)
length (simple int)
mult (float)
method (string)
createDebugTable()
updateDebugTable(tbl, row, label, value)
Parameters:
tbl (table)
row (int)
label (string)
value (string) Library

HighClassCalculationsLibrary "HighClassCalculations"
Advanced Pine Script v6 calculation library for statistical, normalization, trend, and risk metrics.
safeDiv(numerator, denominator, fallback)
Safe division helper that prevents division-by-zero errors.
Parameters:
numerator (float) : Value on the top of the fraction.
denominator (float) : Value on the bottom of the fraction.
fallback (float) : Value returned when denominator is zero.
Returns: Result of the division or fallback.
clamp(value, minValue, maxValue)
Clamps a value into a fixed range.
Parameters:
value (float) : Source value.
minValue (float) : Minimum allowed value.
maxValue (float) : Maximum allowed value.
Returns: Clamped value.
rescale(value, oldMin, oldMax, newMin, newMax)
Rescales a value from one range into another range.
Parameters:
value (float) : Source value.
oldMin (float) : Source range minimum.
oldMax (float) : Source range maximum.
newMin (float) : Target range minimum.
newMax (float) : Target range maximum.
Returns: Rescaled value.
normalize(src, len)
Returns the min-max normalized position of a series within a rolling window.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Value between 0 and 1 when the range is valid.
rangePercent(src, len)
Returns the source position inside its rolling range as a percentage.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Value between 0 and 100 when the range is valid.
zScore(src, len)
Calculates the z-score of a series.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Standardized z-score.
robustZScore(src, len)
Calculates a robust z-score using median absolute deviation.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Robust z-score less sensitive to outliers.
percentileRank(src, len)
Calculates percentile rank for the latest value inside a rolling window.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Percentile rank from 0 to 100.
percentileValue(src, len, percentile)
Calculates the value at a requested percentile inside a rolling window.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
percentile (float) : Requested percentile from 0 to 100.
Returns: Percentile value.
simpleReturn(src)
Calculates simple arithmetic return versus the previous bar.
Parameters:
src (float) : Price or equity series.
Returns: One-bar simple return.
logReturn(src)
Calculates log return versus the previous bar.
Parameters:
src (float) : Price or equity series.
Returns: One-bar log return.
compoundedReturn(src, len)
Calculates cumulative return over a fixed lookback.
Parameters:
src (float) : Price or equity series.
len (int) : Lookback window.
Returns: Return from src to current src.
realizedVolatility(src, len, annualization)
Calculates realized volatility from log returns and annualizes it.
Parameters:
src (float) : Price or equity series.
len (int) : Rolling lookback window.
annualization (float) : Number of bars used for annualization.
Returns: Annualized volatility.
downsideDeviation(returnSeries, len, mar, annualization)
Calculates downside deviation from a return series.
Parameters:
returnSeries (float) : Series of returns, not raw price.
len (int) : Rolling lookback window.
mar (float) : Minimum acceptable return.
annualization (float) : Number of bars used for annualization.
Returns: Annualized downside deviation.
rollingSharpe(returnSeries, len, riskFreeRate, annualization)
Calculates a rolling Sharpe ratio from a return series.
Parameters:
returnSeries (float) : Series of returns, not raw price.
len (int) : Rolling lookback window.
riskFreeRate (float) : Per-bar risk free rate.
annualization (float) : Number of bars used for annualization.
Returns: Annualized Sharpe ratio.
rollingSortino(returnSeries, len, mar, annualization)
Calculates a rolling Sortino ratio from a return series.
Parameters:
returnSeries (float) : Series of returns, not raw price.
len (int) : Rolling lookback window.
mar (float) : Minimum acceptable return.
annualization (float) : Number of bars used for annualization.
Returns: Annualized Sortino ratio.
efficiencyRatio(src, len)
Calculates Kaufman's efficiency ratio.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Efficiency ratio from 0 to 1.
regressionSlope(src, len)
Calculates rolling linear regression slope.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Slope per bar.
regressionAngle(src, len)
Converts rolling regression slope into an angle.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Slope angle in degrees.
beta(asset, benchmark, len)
Calculates rolling beta versus a benchmark series.
Parameters:
asset (float) : Asset series.
benchmark (float) : Benchmark series.
len (int) : Rolling lookback window.
Returns: Beta coefficient.
alpha(asset, benchmark, len, riskFreeRate)
Calculates Jensen-style alpha versus a benchmark series.
Parameters:
asset (float) : Asset return series.
benchmark (float) : Benchmark return series.
len (int) : Rolling lookback window.
riskFreeRate (float) : Per-bar risk free rate.
Returns: Alpha over the rolling window.
ulcerIndex(src, len)
Calculates the Ulcer Index for a series.
Parameters:
src (float) : Price or equity series.
len (int) : Rolling lookback window.
Returns: Ulcer Index value.
maxDrawdown(src, len)
Calculates the maximum drawdown over a rolling window.
Parameters:
src (float) : Price or equity series.
len (int) : Rolling lookback window.
Returns: Maximum drawdown as a negative decimal.
atrPercent(len, src)
Calculates ATR as a percentage of price.
Parameters:
len (simple int) : ATR lookback window.
src (float) : Reference price used for the percentage denominator.
Returns: ATR percent.
relativeVolume(len)
Calculates relative volume versus its rolling average.
Parameters:
len (simple int) : Rolling lookback window.
Returns: Volume divided by average volume.
getAllFunctions()
Returns a comma-separated list of all exported calculation helpers.
Returns: Function catalog for quick reference. Library

Library

Library

Library

MomentumResetsMomentumResets is a compact Pine Script library for detecting momentum reset events using finite-state logic.
You get three different reset models that all return one shared exported signal enum, so integration in your own scripts stays simple and consistent.
Advantages of using this library include:
• Unified signal type : All models return the same `Signal` enum (`bullish`, `bearish`, `none`).
• State-driven logic : Explicit states are more robust than brittle one-bar pattern checks.
• Input validation : Built-in runtime checks catch invalid thresholds and shoulder settings early.
• Flexible strictness : Optional `skipValidation` when you need tolerant behaviour for dynamic or partial inputs.
• Model choice : Stoch, Static Level, and Pivot variants cover different momentum structures.
🟩 RESET MODELS
Stoch Reset
Tracks Stoch around upper/lower thresholds and emits resets when momentum rotates with confirmation conditions.
Use this when you want directional reset events, not just overbought/oversold touches.
Static Level Reset
Uses a two-phase path per side around static thresholds with an optional tolerance buffer.
Use this for "break -> return -> re-break" style momentum structures around fixed levels.
Pivot Reset
Uses shoulder distances and trailed extremes to detect retrace/bounce resets after directional expansion.
Use this for swing-style turns where relative move size matters more than absolute levels.
The models are easier to grasp by seeing them than they are to explain. They all have example visualisations included.
🟩 VALIDATION & ERROR HANDLING
The library includes defensive checks with `runtime.error()` messaging for critical misconfiguration.
Examples of guarded inputs:
• Thresholds cannot be `na`.
• Lower threshold must be below upper threshold.
• Stoch thresholds must stay within 0-100.
• Tolerance must be 0 or greater.
• Shoulder distances must be greater than 0.
• Optional pivot bounds are checked for logical consistency when both are used.
Each error message is prefixed with the library + function name to make debugging easier.
🟩 HOW TO USE
Pine Script libraries contain reusable code for importing into indicators. You do not need to copy any code out of here. Just import the library and call the function you want.
For version 1, import it like this:
import SimpleCryptoLife/MomentumResets/1
Then call one reset function per model/series path each bar, and route the returned `Signal` enum into your entries, exits, filters, or alerts.
For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script User Manual.
🟩 BRING ON THE FUNCTIONS
getStochResetSignal(_stochK, _stochD, _lowerThreshold, _upperThreshold, _skipValidation)
Returns a Stoch momentum reset signal using internal FSM states (neutral, tracking, suppressed).
Parameters:
_stochK (float)
Current Stoch %K value used in state transitions.
_stochD (float)
Current Stoch %D value used for confirmation logic.
_lowerThreshold (float, default 20.0)
Lower Stoch threshold used for setup and reset detection.
_upperThreshold (float, default 80.0)
Upper Stoch threshold used for setup and reset detection.
_skipValidation (bool, default false)
If true, skips guard checks and allows tolerant execution with dynamic/partial inputs.
Returns: Signal (`Signal.bullish`, `Signal.bearish`, or `Signal.none` for this bar).
getStaticLevelResetSignal(_value, _lowerThreshold, _upperThreshold, _tolerance, _skipValidation)
Returns a reset signal when value completes the threshold/tolerance path on either side.
Parameters:
_value (float)
Current series value to evaluate.
_lowerThreshold (float)
Lower static level used by the bullish reset path.
_upperThreshold (float)
Upper static level used by the bearish reset path.
_tolerance (float, default 0.0)
Optional buffer zone around levels before a reset can complete.
_skipValidation (bool, default false)
If true, skips guard checks and allows tolerant execution with dynamic/partial inputs.
Returns: Signal (`Signal.bullish`, `Signal.bearish`, or `Signal.none` for this bar).
getPivotResetSignal(_value, _leftShoulder, _rightShoulder, _bearMinHeight, _bullMaxDepth, _skipValidation)
Returns a reset signal using shoulder-based priming and trailing extremes for pivot-style turns.
Parameters:
_value (float)
Current series value to evaluate.
_leftShoulder (float)
Relative move from anchor required to prime a directional setup.
_rightShoulder (float)
Relative retrace/bounce from the trailed extreme required to trigger a reset.
_bearMinHeight (float, optional)
Optional absolute minimum high required before bearish resets are allowed.
_bullMaxDepth (float, optional)
Optional absolute maximum low required before bullish resets are allowed.
_skipValidation (bool, default false)
If true, skips guard checks and allows tolerant execution with dynamic/partial inputs.
Returns: Signal (`Signal.bullish`, `Signal.bearish`, or `Signal.none` for this bar).
Library

BASCOOL_LibBASCOOL Library v1
Range–Body Structure Analysis Toolkit for Intraday Trading
The BASCOOL Library provides high-quality, reusable Pine Script components for structural conviction analysis based purely on price action. It is designed for intraday traders who rely on volatility-adjusted range expansion and candle-body efficiency to identify strong, weak, or choppy market conditions.
Included Functions
rbm_from_ohlc() – Range–Body Measure (RBM)
A volatility-normalized structure indicator that evaluates:
Range Expansion:
Smooth EMA of (High–Low), normalized by ATR
→ captures strength of movement relative to volatility
Body Efficiency:
Body-to-Range ratio smoothed with EMA
→ measures how much of the candle’s range is “directional”
The RBM output is a smooth structural strength score typically between 0 and 1, where:
High RBM → strong structure, clean movement, trend-friendly conditions
Low RBM → compressed ranges, weak bodies, low-quality structure
Flat RBM → choppy environment, avoid directional trades Library

Letras_Lecaps_Library---
**Letras_Lecaps_Library — Argentine Fixed-Rate Instruments & Dollar Futures Data**
Pine Script library that provides centralized reference data for Argentine Lecaps, Boncaps, and Matba-Rofex Dollar Futures contracts. Designed to be imported by indicators and strategies that need ticker symbols, maturity dates, and redemption prices without hardcoding them.
**What's inside**
The library exports simple accessor functions for three instrument classes:
- **Lecaps** (9 series): BCBA tickers, maturity price per VN100 (Monto_al_Vto), and payment date for each active short-term zero-coupon treasury bill.
- **Boncaps** (6 series): Same structure as Lecaps, covering longer-term capitalization bonds.
- **Dollar Futures** (12 contracts): MATBAROFEX tickers and expiry dates for USD/ARS futures.
Count functions (`lecapCount()`, `boncapCount()`, `futuresCount()`) return the number of active instruments in each category, so consuming scripts can adapt dynamically.
**Data sources**
- Lecaps & Boncaps: IAMC (Instituto Argentino de Mercado de Capitales) periodic report.
- Dollar Futures: A3 Mercados (Matba-Rofex), expiry dates verified against PulseWire contract pages.
**How to use**
```pine
import EcoValores/Letras_Lecaps_Library/1 as lib
// Get the ticker and maturity data for the first Lecap
ticker = lib.lecapTicker1() // "BCBA:S27F6"
matPx = lib.lecapMaturityPrice1() // 125.84
matDt = lib.lecapMaturityDate1() // timestamp for 27/02/2026
```
**Update cycle**
This library reflects a point-in-time snapshot. It should be updated and republished after each public auction or when new IAMC data becomes available. Expired instruments are removed and new ones added, with count functions adjusted accordingly. The last data source date is noted in the script header.
**Related**
This library is the data backend for the **Breakeven Lecaps_Boncaps** indicator, which uses it to calculate and plot breakeven USD exchange rates across the term structure.
---
**Descripción en Español**
Librería Pine Script que centraliza los datos de referencia de Lecaps, Boncaps y contratos de Dólar Futuro de Matba-Rofex. Diseñada para ser importada por indicadores y estrategias que necesitan tickers, fechas de vencimiento y precios de rescate sin codificarlos directamente.
Exporta funciones de acceso para tres clases de instrumentos: Lecaps (9 series, tickers BCBA, precio al vencimiento por VN100 y fecha de pago), Boncaps (6 series, misma estructura), y Dólar Futuro (12 contratos, tickers MATBAROFEX y fecha de expiración). Las funciones de conteo permiten que los scripts consumidores se adapten dinámicamente.
Fuentes de datos: Lecaps y Boncaps del informe periódico del IAMC; Dólar Futuro de A3 Mercados (Matba-Rofex). La librería refleja una foto puntual y debe republicarse tras cada licitación o cuando haya nuevos datos disponibles.
Esta librería es el backend de datos del indicador **Breakeven Lecaps_Boncaps**, que la utiliza para calcular y graficar el tipo de cambio breakeven en dólares a lo largo de la curva.
---
**Disclaimer / Aviso legal**
This library is for informational and educational purposes only. It does not constitute investment advice. Data may be incomplete, delayed, or inaccurate. Verify all tickers and values independently before use. Past performance is not indicative of future results. Consult a licensed financial advisor before making investment decisions.
Esta librería es solo para fines informativos y educativos. No constituye asesoramiento de inversión. Los datos pueden ser incompletos, estar demorados o ser inexactos. Verifique todos los tickers y valores de forma independiente antes de utilizarla. El rendimiento pasado no es indicativo de resultados futuros. Consulte a un asesor financiero matriculado antes de invertir. Library

Library

Library

Library

ohlcLibrary "ohlc"
Library having OHLC and Indicator type and method implementations.
getOhlcArray(o, h, l, c, highBeforeLow, highAfterLow, lowBeforeHigh, lowAfterHigh, barindex, bartime, indicators)
get array of OHLC values when called on every bar
Parameters:
o (float) : Open price
h (float) : High Price
l (float) : Low Price
c (float) : Close Price
highBeforeLow (float) : to be calculated based on lower timeframe. high price attained within the candle before reaching the lowest point.
highAfterLow (float) : to be calculated based on lower timeframe. high price attained within the candle after reaching the lowest point.
lowBeforeHigh (float) : to be calculated based on lower timeframe. low price attained within the candle before reaching the highest point.
lowAfterHigh (float) : to be calculated based on lower timeframe. low price attained within the candle after reaching the highest point.
barindex (int) : bar_index of OHLC data
bartime (int) : time of OHLC cata
indicators (array) : array containing indicator
Returns: Array of OHLC objects
push(this, item, maxItems)
Push items to OHLC array with maxItems limit
Parameters:
this (array)
item (OHLC) : OHLC Item to be pushed to the array
maxItems (int) : max Items the array can hold at a time
Returns: current object
push(this, item, maxItems)
Push items to Indicator array with maxItems limit
Parameters:
this (array)
item (Indicator) : Indicator Item to be pushed to the array
maxItems (int) : max Items the array can hold at a time
Returns: current object
unshift(this, item, maxItems)
Unshift items to OHLC array with maxItems limit
Parameters:
this (array)
item (OHLC) : OHLC Item to be unshifted to the array
maxItems (int) : max Items the array can hold at a time
Returns: current object
unshift(this, item, maxItems)
Unshift items to Indicator array with maxItems limit
Parameters:
this (array)
item (Indicator) : Indicator Item to be unshifted to the array
maxItems (int) : max Items the array can hold at a time
Returns: current object
method getPoints(indicators)
get array of points based on array of indicator values
Namespace types: array
Parameters:
indicators (array) : Array containing indicator objects
Returns: array of indicator points
method plot(indicator, xloc, line_color, line_style, line_width)
plots an array of Indicator using polyline
Namespace types: array
Parameters:
indicator (array) : Array containing indicator objects
xloc (string) : can have values xloc.bar_index or xloc.bar_time. Used for drawing the line based on either bars or time.
line_color (color) : color in which the plots need to be printed on chart.
line_style (string) : line style line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_right, line.style_arrow_left, line.style_arrow_both
line_width (int) : width of the plot line
Returns: array of plot polyline
Indicator
Object containing Indicator name and value
Fields:
name (series string) : Indicator Name
value (chart.point) : Indicator Value as a chart point
OHLC
Object containing OHLC and indicator values
Fields:
o (series float) : Open price
h (series float) : High Price
l (series float) : Low Price
c (series float) : Close Price
highBeforeLow (series float) : to be calculated based on lower timeframe. high price attained within the candle before reaching the lowest point.
highAfterLow (series float) : to be calculated based on lower timeframe. high price attained within the candle after reaching the lowest point.
lowBeforeHigh (series float) : to be calculated based on lower timeframe. low price attained within the candle before reaching the highest point.
lowAfterHigh (series float) : to be calculated based on lower timeframe. low price attained within the candle after reaching the highest point.
barindex (series int) : bar_index of OHLC data
bartime (series int) : time of OHLC cata
indicators (array) : array containing indicator Library

Kerbal_BreadthLibrary "kerbal_breadth"
Kerbal Indicators Shared Library - Breadth Analysis
This library provides functions for analyzing market breadth indicators including
Advance/Decline lines, Bullish Percent Index, and breadth divergence detection.
getAdvDecLine()
Get NYSE Advance/Decline line
Returns: NYSE A/D line value
getAdvDecRatio()
Get NYSE Advance/Decline ratio
Returns: NYSE Advance/Decline ratio
advDecSlope(length)
Calculate A/D line slope (rate of change)
Parameters:
length (int) : Period for slope calculation
Returns: A/D line slope (positive = breadth improving, negative = deteriorating)
advDecDivergence(priceHigh, priceHighBar, lookback)
Detect A/D line divergence with price
Parameters:
priceHigh (float) : Recent price high
priceHighBar (int) : Bar index of price high
lookback (int) : Bars to look back for divergence
Returns: Tuple - true if divergence detected
getBullishPercentNYSE()
Get Bullish Percent Index for NYSE
Returns: NYSE BPI value (0-100 scale)
getBullishPercentSPX()
Get Bullish Percent Index for S&P 500
Returns: SPX BPI value (0-100 scale)
getBullishPercentNDX()
Get Bullish Percent Index for Nasdaq
Returns: NDX BPI value (0-100 scale)
bpiRegime(bpi, oversoldThresh, overboughtThresh)
Classify BPI regime
Parameters:
bpi (float) : BPI value (0-100)
oversoldThresh (float) : Oversold threshold (contrarian bullish)
overboughtThresh (float) : Overbought threshold (contrarian bearish)
Returns: Regime: "OVERSOLD", "BULLISH", "NEUTRAL", "BEARISH", "OVERBOUGHT"
pctAbove200MA_SPX()
Get percentage of S&P 500 stocks above their 200-day MA
Returns: Percentage (0-100)
pctAbove50MA_SPX()
Get percentage of S&P 500 stocks above their 50-day MA
Returns: Percentage (0-100)
breadthHealth(pct200, pct50)
Analyze breadth health based on MA participation
Parameters:
pct200 (float) : Percentage above 200-day MA
pct50 (float) : Percentage above 50-day MA
Returns: Health assessment: "STRONG", "HEALTHY", "WEAK", "POOR"
breadthThrust(period, threshold)
Detect breadth thrust (rapid improvement in breadth)
Parameters:
period (int) : Measurement period
threshold (float) : Minimum improvement threshold
Returns: True if breadth thrust detected
breadthScore(advDecSlope, bpi, pct200)
Calculate composite breadth score
Parameters:
advDecSlope (float) : A/D line slope
bpi (float) : Bullish Percent Index value
pct200 (float) : Percentage above 200-day MA
Returns: Breadth score 0-100 (higher = better breadth)
currentBreadthScore()
Get current composite breadth with all data retrieval
Returns: Composite breadth score 0-100
breadthBearishDivergence(priceHigh, prevPriceHigh, currentBreadth, prevBreadth)
Detect bearish breadth divergence
Parameters:
priceHigh (float) : Current price high
prevPriceHigh (float) : Previous price high
currentBreadth (float) : Current breadth score
prevBreadth (float) : Previous breadth score
Returns: True if bearish divergence (price up, breadth down)
breadthBullishDivergence(priceLow, prevPriceLow, currentBreadth, prevBreadth)
Detect bullish breadth divergence
Parameters:
priceLow (float) : Current price low
prevPriceLow (float) : Previous price low
currentBreadth (float) : Current breadth score
prevBreadth (float) : Previous breadth score
Returns: True if bullish divergence (price down, breadth up)
breadthConfirmsBullish(breadthScore, minScore)
Check if breadth confirms bullish price action
Parameters:
breadthScore (float) : Current breadth score (0-100)
minScore (float) : Minimum acceptable breadth score
Returns: True if breadth is confirming
breadthConfirmsBearish(breadthScore, maxScore)
Check if breadth confirms bearish price action
Parameters:
breadthScore (float) : Current breadth score (0-100)
maxScore (float) : Maximum acceptable breadth score
Returns: True if breadth is confirming
breadthWarning(breadthScore, priceAction)
Detect breadth warning signals
Parameters:
breadthScore (float) : Current breadth score
priceAction (int) : Recent price direction (1 = up, -1 = down, 0 = neutral)
Returns: Tuple
marketHealthFromBreadth(breadthScore, hasThrust, divergenceType)
Comprehensive market health from breadth indicators
Parameters:
breadthScore (float) : Composite breadth score
hasThrust (bool) : Whether breadth thrust detected
divergenceType (int) : Divergence type: 1 = bearish, -1 = bullish, 0 = none
Returns: Health string: "EXCELLENT", "GOOD", "FAIR", "POOR", "WARNING"
marketHealth(sentimentScore, breadthScore)
Combined sentiment and breadth confirmation
Parameters:
sentimentScore (float) : Sentiment score from kerbal_sentiment library (0-100)
breadthScore (float) : Breadth score (0-100)
Returns: Tuple Library

Kerbal_SentimentLibrary "kerbal_sentiment"
Kerbal Indicators Shared Library - Sentiment Analysis
This library provides functions for accessing and analyzing market sentiment indicators
including VIX and Put/Call ratios for contrarian signal generation.
getVIX()
Get VIX (CBOE Volatility Index) close value
Returns: VIX close price
vixPercentile(length)
Calculate VIX percentile rank over lookback period
Parameters:
length (int) : Lookback period for percentile calculation
Returns: VIX percentile (0-100)
vixRegime(vix, lowThresh, highThresh, extremeThresh)
Classify VIX regime based on thresholds
Parameters:
vix (float) : VIX value to classify (use na for current)
lowThresh (float) : Low VIX threshold (complacent market)
highThresh (float) : High VIX threshold (fearful market)
extremeThresh (float) : Extreme fear threshold
Returns: Regime: "COMPLACENT", "NORMAL", "FEARFUL", or "EXTREME_FEAR"
vixZScore(length)
Calculate VIX z-score for relative positioning
Parameters:
length (int) : Lookback period for mean and standard deviation
Returns: VIX z-score
getPutCallRatio()
Get equity put/call ratio
Returns: Put/Call ratio (typically from CBOE data feed)
putCallSmoothed(length)
Get smoothed put/call ratio using SMA
Parameters:
length (int) : Smoothing period
Returns: Smoothed put/call ratio
putCallZScore(length)
Calculate put/call z-score for extremes detection
Parameters:
length (int) : Lookback period for mean and standard deviation
Returns: Put/Call z-score (positive = elevated put buying)
putCallRegime(pc, lowThresh, highThresh)
Classify put/call ratio regime
Parameters:
pc (float) : Put/call ratio (use na for current)
lowThresh (float) : Low P/C threshold (complacent/bullish)
highThresh (float) : High P/C threshold (fearful/bearish sentiment)
Returns: Regime: "COMPLACENT", "NORMAL", "DEFENSIVE", "FEARFUL"
sentimentScore(vixPercentile, putCallZScore)
Calculate composite sentiment score
Parameters:
vixPercentile (float) : VIX percentile rank (0-100)
putCallZScore (float) : Put/Call ratio z-score
Returns: Sentiment score 0-100 (0 = extreme fear/bullish contrarian, 100 = extreme complacency/bearish contrarian)
contrarianSignal(sentimentScore, bullishThreshold, bearishThreshold)
Check if sentiment is at contrarian extreme
Parameters:
sentimentScore (float) : Composite sentiment score (0-100)
bullishThreshold (float) : Threshold for contrarian bullish signal (extreme fear)
bearishThreshold (float) : Threshold for contrarian bearish signal (extreme complacency)
Returns: Tuple
sentimentTrend(sentimentScore, prevSentimentScore, threshold)
Get sentiment direction and strength
Parameters:
sentimentScore (float) : Current sentiment score
prevSentimentScore (float) : Previous sentiment score
threshold (float)
Returns: Tuple where direction is "INCREASING_FEAR", "DECREASING_FEAR", "STABLE"
vixSpike(spikeThreshold)
Detect VIX spike (sudden fear increase)
Parameters:
spikeThreshold (float) : Z-score threshold for spike detection
Returns: True if VIX is spiking
putCallSpike(spikeThreshold)
Detect put/call spike (sudden defensive positioning)
Parameters:
spikeThreshold (float) : Z-score threshold for spike detection
Returns: True if P/C ratio is spiking
marketStress()
Composite market stress indicator
Returns: Stress level 0-100 (higher = more stress)
contrarianBuyOpportunity(minStress)
Identify contrarian buy opportunity
Parameters:
minStress (float) : Minimum stress level required
Returns: True if contrarian buy opportunity detected
contrarianSellOpportunity(maxStress)
Identify contrarian sell opportunity
Parameters:
maxStress (float) : Maximum stress level (complacency)
Returns: True if contrarian sell opportunity detected Library

Kerbal_HelpersLibrary "kerbal_helpers"
Kerbal Indicators Shared Library - Drawing object helpers
This library provides utilities for managing labels, boxes, and areas within Pine Script limits (500 each).
Includes deduplication, cleanup, filtering, and zone management functions.
ageFilter(barIndex, creationBar, maxAge)
Check if an object is too old based on bar index
Parameters:
barIndex (int) : Current bar index
creationBar (int) : Bar index when object was created
maxAge (int) : Maximum age in bars
Returns: True if object should be filtered out (too old)
distanceFilter(price, referencePrice, atrMultiplier, atr)
Check if price is within acceptable distance from reference
Parameters:
price (float) : The price to check
referencePrice (float) : The reference price
atrMultiplier (float) : ATR multiplier for distance
atr (float) : The ATR value
Returns: True if within acceptable distance
weightFilter(weight, minWeight)
Check if weight meets minimum threshold
Parameters:
weight (float) : The weight value
minWeight (float) : Minimum acceptable weight
Returns: True if weight is acceptable
perfectionFilter(isPerfected, requirePerfection)
Check perfection requirement (for Price Exhaustion clusters)
Parameters:
isPerfected (bool) : Whether the signal is perfected
requirePerfection (bool) : Whether perfection is required
Returns: True if passes perfection filter
boxOverlaps(box1Top, box1Bot, box2Top, box2Bot)
Check if two boxes overlap in price space
Parameters:
box1Top (float) : Top price of first box
box1Bot (float) : Bottom price of first box
box2Top (float) : Top price of second box
box2Bot (float) : Bottom price of second box
Returns: True if boxes overlap
boxMerge(box1Top, box1Bot, box2Top, box2Bot)
Calculate the merged boundaries of two overlapping boxes
Parameters:
box1Top (float) : Top price of first box
box1Bot (float) : Bottom price of first box
box2Top (float) : Top price of second box
box2Bot (float) : Bottom price of second box
Returns: Tuple
priceInZone(price, boxTop, boxBot)
Check if a price is within a box/zone
Parameters:
price (float) : The price to check
boxTop (float) : Top of the box
boxBot (float) : Bottom of the box
Returns: True if price is within box boundaries
zoneCenter(boxTop, boxBot)
Calculate the center price of a zone
Parameters:
boxTop (float) : Top of the zone
boxBot (float) : Bottom of the zone
Returns: Center price
zoneWidth(boxTop, boxBot)
Calculate zone width/thickness
Parameters:
boxTop (float) : Top of the zone
boxBot (float) : Bottom of the zone
Returns: Zone width
labelsNearby(x1, y1, x2, y2, barTolerance, priceTolerance)
Check if two labels would be too close (for deduplication)
Parameters:
x1 (int) : Bar index of first label
y1 (float) : Price of first label
x2 (int) : Bar index of second label
y2 (float) : Price of second label
barTolerance (int) : Maximum bar distance for considering labels duplicate
priceTolerance (float) : Maximum price distance for considering labels duplicate
Returns: True if labels are close enough to be considered duplicates
labelDistance(x1, y1, x2, y2, atr)
Calculate distance score between two label positions (lower is closer)
Parameters:
x1 (int) : Bar index of first label
y1 (float) : Price of first label
x2 (int) : Bar index of second label
y2 (float) : Price of second label
atr (float) : ATR value for price normalization
Returns: Distance score (0+ range, lower means closer)
clusterType(hasSession, hasPivot, hasVolume, weight, goldThreshold, limeThreshold)
Classify cluster composition based on anchor types present
Parameters:
hasSession (bool) : Whether cluster contains session anchors (daily/weekly)
hasPivot (bool) : Whether cluster contains pivot anchors
hasVolume (bool) : Whether cluster contains volume anchors
weight (float) : Total cluster weight
goldThreshold (float) : Weight threshold for "gold" classification
limeThreshold (float) : Weight threshold for "lime" classification
Returns: Cluster type: "GOLD", "LIME", "MIXED", "SESSION", "PIVOT", "VOLUME"
clusterColor(clusterType)
Get color for cluster based on type
Parameters:
clusterType (string) : The cluster type string
Returns: Appropriate color for the cluster type
zoneSignificant(weight, width, minWeight, maxWidth)
Check if a zone is significant enough to display
Parameters:
weight (float) : Zone weight
width (float) : Zone width in price
minWeight (float) : Minimum weight threshold
maxWidth (float) : Maximum width threshold (ATR-based)
Returns: True if zone should be displayed
mergeZones(prices, widths, tolerance)
Merge multiple nearby zones into a single wider zone
Parameters:
prices (array) : Array of zone center prices
widths (array) : Array of zone widths
tolerance (float) : Merging tolerance (typically ATR-based)
Returns: Tuple of arrays
findSupportResistance(prices, currentPrice)
Calculate support and resistance levels from an array of prices
Parameters:
prices (array) : Array of price levels
currentPrice (float) : Current market price
Returns: Tuple of
zoneStrength(weight, age, touches, width, maxAge, maxTouches, optimalWidth)
Calculate zone strength score based on multiple factors
Parameters:
weight (float) : Zone weight (volume participation)
age (int) : Bars since zone creation
touches (int) : Number of price touches/tests
width (float) : Zone width
maxAge (int) : Maximum age for full score
maxTouches (int) : Maximum touches for full score
optimalWidth (float) : Optimal zone width (narrower is better)
Returns: Strength score 0-100 Library

Kerbal_LibLibrary "kerbal_lib"
Kerbal Indicators Shared Library - Core utilities for PulseWire indicators
This library provides reusable functions for ATR calculations, multi-timeframe analysis,
confluence detection, clustering, regime classification, and more.
atrTolerance(length, multiplier)
Calculate ATR-based tolerance value
Parameters:
length (simple int) : The ATR calculation length
multiplier (float) : The ATR multiplier for tolerance
Returns: The tolerance value (ATR * multiplier)
pricesWithinATR(price1, price2, atrMultiplier, atrLength)
Check if two prices are within ATR tolerance
Parameters:
price1 (float) : First price level
price2 (float) : Second price level
atrMultiplier (float) : ATR multiplier for tolerance
atrLength (simple int) : ATR calculation length
Returns: True if prices are within tolerance
atrPercentile(atrLength, lookback, percentile)
Get ATR percentile for compression detection
Parameters:
atrLength (simple int) : The ATR calculation length
lookback (int) : Lookback period for percentile
percentile (simple float) : The percentile to calculate (0-100)
Returns: ATR percentile value
isHigherTimeframe(htfPeriod)
Check if a given timeframe is higher than current chart timeframe
Parameters:
htfPeriod (string) : Higher timeframe period string
Returns: True if HTF is genuinely higher than chart TF
confluenceCount(signal1, signal2, signal3, signal4, signal5)
Count how many boolean signals are true
Parameters:
signal1 (bool) : First signal
signal2 (bool) : Second signal
signal3 (bool) : Third signal
signal4 (bool) : Fourth signal
signal5 (bool) : Fifth signal
Returns: Count of true signals
confluenceScore(signal1, signal2, signal3, signal4, signal5, weight1, weight2, weight3, weight4, weight5)
Calculate weighted confluence score from multiple signals
Parameters:
signal1 (bool) : First signal
signal2 (bool) : Second signal
signal3 (bool) : Third signal
signal4 (bool) : Fourth signal
signal5 (bool) : Fifth signal
weight1 (float) : Weight for first signal
weight2 (float) : Weight for second signal
weight3 (float) : Weight for third signal
weight4 (float) : Weight for fourth signal
weight5 (float) : Weight for fifth signal
Returns: Weighted score (0-100)
clusterPrices(prices, weights, tolerance)
Cluster prices within tolerance using weighted averaging
Parameters:
prices (array) : Array of price levels to cluster
weights (array) : Array of weights for each price
tolerance (float) : Distance tolerance for grouping (typically ATR-based)
Returns: Tuple of arrays
clusterSort(centers, weights, maxClusters)
Sort clusters by weight and return top N
Parameters:
centers (array) : Array of cluster center prices
weights (array) : Array of cluster weights
maxClusters (int) : Maximum number of clusters to return
Returns: Tuple of arrays (descending by weight)
regimeClassify(hurst, thresholdHi, thresholdLo)
Classify market regime based on Hurst exponent
Parameters:
hurst (float) : The Hurst exponent value (0-1)
thresholdHi (float) : Upper threshold for trending regime
thresholdLo (float) : Lower threshold for mean-reverting regime
Returns: Regime string: "TREND", "REVERT", or "MIXED"
volatilityRegime(atrLength, lookback, percentile)
Classify volatility regime based on ATR percentile
Parameters:
atrLength (simple int) : ATR calculation length
lookback (int) : Lookback period for percentile
percentile (simple float) : Compression threshold percentile
Returns: Volatility regime: "COMPRESSED", "NORMAL", or "EXPANDED"
normalizedSlope(current, previous, atrLength)
Calculate normalized slope using ATR
Parameters:
current (float) : Current value
previous (float) : Previous value
atrLength (simple int) : ATR length for normalization
Returns: Normalized slope value
slopeColor(slope, threshold, upColor, downColor, flatColor)
Get color based on slope direction
Parameters:
slope (float) : The slope value to evaluate
threshold (float) : Threshold for flat detection
upColor (color) : Color for rising slope
downColor (color) : Color for falling slope
flatColor (color) : Color for flat slope
Returns: Color based on slope direction
slopeDirection(current, previous, threshold)
Determine slope direction as string
Parameters:
current (float) : Current value
previous (float) : Previous value
threshold (float) : Threshold for flat detection
Returns: Direction string: "RISING", "FALLING", or "FLAT"
dojiMid(openPrice, closePrice)
Calculate doji midpoint (fair value for doji candles)
Parameters:
openPrice (float) : Open price
closePrice (float) : Close price
Returns: Midpoint between open and close
vwap(sumPriceVolume, sumVolume)
Calculate VWAP from cumulative values
Parameters:
sumPriceVolume (float) : Cumulative sum of price * volume
sumVolume (float) : Cumulative sum of volume
Returns: VWAP value
isNewSession(tf)
Check if a new session has started for given timeframe
Parameters:
tf (string) : Timeframe string (e.g., "1D", "1W")
Returns: True if new session started
isIntraday()
Check if current timeframe is intraday
Returns: True if intraday timeframe
relativeVolume(length)
Calculate relative volume using median baseline
Parameters:
length (int) : Lookback length for median calculation
Returns: Relative volume (current volume / median volume)
volumeCategory(relVol, lowThreshold, highThreshold, extremeThreshold)
Categorize volume level
Parameters:
relVol (float) : Relative volume value
lowThreshold (float) : Threshold for low volume
highThreshold (float) : Threshold for high volume
extremeThreshold (float) : Threshold for extreme volume
Returns: Volume category: "EXTREME", "HIGH", "NORMAL", or "LOW"
volumeTrend(shortLength, longLength)
Calculate volume trend (fast median vs slow median)
Parameters:
shortLength (int) : Short median length
longLength (int) : Long median length
Returns: Volume trend ratio
volumeMultiplier(relVol, lowThreshold, highThreshold, extremeThreshold)
Get volume multiplier for calculations based on relative volume
Parameters:
relVol (float) : Relative volume value
lowThreshold (float) : Threshold for low volume multiplier
highThreshold (float) : Threshold for high volume multiplier
extremeThreshold (float) : Threshold for extreme volume multiplier
Returns: Multiplier value (0.5 for low, 1.0 for normal, 1.5 for high, 2.0 for extreme) Library

Kerbal_CloudsLibrary "kerbal_clouds"
Kerbal Indicators Shared Library - EMA/SMA Cloud Helpers
This library provides convenient functions for creating and managing moving average clouds (high/close/low based).
emaCloud(period)
Calculate EMA cloud values (high, close, low)
Parameters:
period (simple int) : The EMA period
Returns: Tuple of
cloudWidth(emaHigh, emaLow)
Calculate EMA cloud width
Parameters:
emaHigh (float) : EMA of high
emaLow (float) : EMA of low
Returns: Cloud width (emaHigh - emaLow)
cloudPosition(emaHigh, emaClose, emaLow)
Calculate price position within cloud (0-1 scale)
Parameters:
emaHigh (float) : EMA of high
emaClose (float) : EMA of close
emaLow (float) : EMA of low
Returns: Position from 0 (at low) to 1 (at high)
distanceToCloud(price, emaHigh, emaLow)
Calculate distance from price to cloud
Parameters:
price (float) : Current price to check
emaHigh (float) : EMA of high
emaLow (float) : EMA of low
Returns: Distance (positive if above cloud, negative if below, 0 if inside)
priceCloudRelation(price, emaHigh, emaLow)
Check if price is above, below, or within cloud
Parameters:
price (float) : Current price
emaHigh (float) : EMA of high
emaLow (float) : EMA of low
Returns: Position string: "ABOVE", "BELOW", or "INSIDE"
smaCloud(period)
Calculate SMA cloud values (high, close, low)
Parameters:
period (int) : The SMA period
Returns: Tuple of
cloudStacking(shortHigh, shortLow, mediumHigh, mediumLow, longHigh, longLow)
Check if clouds are properly stacked (bullish or bearish)
Parameters:
shortHigh (float) : Short period EMA high
shortLow (float) : Short period EMA low
mediumHigh (float) : Medium period EMA high
mediumLow (float) : Medium period EMA low
longHigh (float) : Long period EMA high
longLow (float) : Long period EMA low
Returns: Stacking string: "BULLISH" (short > medium > long), "BEARISH" (short < medium < long), "MIXED"
cloudAlignment(shortClose, mediumClose, longClose)
Calculate cloud alignment score (0-100)
Parameters:
shortClose (float) : Short period EMA close
mediumClose (float) : Medium period EMA close
longClose (float) : Long period EMA close
Returns: Alignment score (100 = perfect bullish, 0 = perfect bearish, 50 = mixed)
cloudTrendStrength(shortClose, mediumClose, longClose, atr)
Calculate trend strength based on cloud separation
Parameters:
shortClose (float) : Short period EMA close
mediumClose (float) : Medium period EMA close
longClose (float) : Long period EMA close
atr (float) : Current ATR for normalization
Returns: Trend strength (-1 to 1, negative for bearish, positive for bullish)
cloudSqueeze(shortWidth, mediumWidth, longWidth, atr, threshold)
Detect cloud squeeze (compression)
Parameters:
shortWidth (float) : Short cloud width
mediumWidth (float) : Medium cloud width
longWidth (float) : Long cloud width
atr (float) : Current ATR
threshold (float) : Squeeze threshold (width/ATR ratio)
Returns: True if all clouds are squeezed below threshold
bullishCloudCross(price, cloudHigh)
Detect bullish cloud crossover
Parameters:
price (float) : Current price
cloudHigh (float) : Cloud high boundary
Returns: True if price crossed above cloud
bearishCloudCross(price, cloudLow)
Detect bearish cloud crossover
Parameters:
price (float) : Current price
cloudLow (float) : Cloud low boundary
Returns: True if price crossed below cloud
tripleCloud(shortPeriod, mediumPeriod, longPeriod)
Calculate triple cloud system (short, medium, long periods)
Parameters:
shortPeriod (simple int) : Short EMA period
mediumPeriod (simple int) : Medium EMA period
longPeriod (simple int) : Long EMA period
Returns: Tuple of 9 values:
cloudTrendColor(emaClose, emaPrevClose, bullishColor, bearishColor)
Get cloud color based on position and trend
Parameters:
emaClose (float) : EMA close value
emaPrevClose (float) : Previous EMA close value
bullishColor (color) : Color for bullish/rising cloud
bearishColor (color) : Color for bearish/falling cloud
Returns: Appropriate cloud color Library

ma_libraryTitle: Library: Advanced Moving Average Collection
Description:
This library provides a comprehensive set of Moving Average algorithms, ranging from standard filters (SMA, EMA) to adaptive trendlines (KAMA, FRAMA) and experimental smoothers (ALMA, JMA).
It has been fully optimized for Pine Script v6, ensuring efficient execution and strict robustness against na (missing) values. Unlike standard implementations that propagate na values, these functions dynamically recalculate weights to maintain continuity in disjointed datasets.
🧩 Library Features
Robustness: Non-recursive filters ignore na values within the lookback window. Recursive filters maintain state to prevent calculation breaks.
Optimization: Logic updated to v6 standards, utilizing efficient loops and var persistence.
Standardization: All functions utilize a consistent f_ prefix and standardized parameters for easy integration.
Scope: Contains over 35 different smoothing algorithms.
📊 Input Requirements
Source (src): The data series to smooth (usually close, hl2, etc.).
Length (length): The lookback period (must be a simple int).
Specifics: Some adaptive MAs (like f_evwma) require volume data, while others (like f_alma) require offset/sigma settings.
🛠️ Integration Example
You can import the library and call functions directly, or use the built-in f_selector to create dynamic inputs for your users.
code
Pine
download
content_copy
expand_less
//@version=6
indicator("MA Library Demo", overlay=true)
// Import the library
import YourUsername/ma_/1 as ma
// --- Example 1: Direct Function Call ---
// calculating Jurik Moving Average (JMA)
float jma_val = ma.f_jma(close, 14)
plot(jma_val, "JMA", color=color.yellow, linewidth=2)
// --- Example 2: User Selector ---
// Allowing the user to choose the MA type via settings
string selected_type = input.string("ALMA", "MA Type", options= )
int length = input.int(20, "Length")
// Using the generic selector function
float dynamic_ma = ma.f_selector(close, length, selected_type)
plot(dynamic_ma, "Dynamic MA", color=color.aqua)
📋 Included Algorithms
The following methods are available (prefixed with f_):
Standard: SMA, EMA, WMA, VWMA, RMA
Adaptive: KAMA (Kaufman), FRAMA (Fractal), VIDYA (Chande/VARMA), VAMA (Vol. Adjusted)
Low Lag: ZLEMA (Zero Lag), HMA (Hull), JMA (Jurik), DEMA, TEMA
Statistical/Math: LSMA (Least Squares), GMMA (Geometric Mean), FLSMA (Fisher Least Squares)
Advanced/Exotic:
ALMA (Arnaud Legoux)
EIT (Ehlers Instantaneous Trend)
ESD (Ehlers Simple Decycler)
AHMA (Ahrens)
BMF (Blackman Filter)
CMA (Corrective)
DSWF (Damped Sine Wave)
EVWMA (Elastic Vol. Weighted)
HCF (Hybrid Convolution)
LMA (Leo)
MD (McGinley Dynamic)
MF (Modular Filter)
MM (Moving Median)
QMA (Quick)
RPMA (Repulsion)
RSRMA (Right Sided Ricker)
SMMA (Smoothed)
SSMA (Shapeshifting)
SWMA (Sine Weighted)
TMA (Triangular)
TSF (True Strength Force)
VBMA (Variable Band) Library

Library

HawkDoveScoreLibLibrary "HawkDoveScoreLib"
hds_score(sym2y, sym10y, symBE10, symBS, symFCI, tfMacro, lenTrend, lenNorm, smoothScore, useRatePath, useCurve, useRealYield, useBalanceSh, useStressFCI, wRatePath, wCurve, wRealYield, wBS, wStress)
Parameters:
sym2y (string)
sym10y (string)
symBE10 (string)
symBS (string)
symFCI (string)
tfMacro (string)
lenTrend (int)
lenNorm (int)
smoothScore (simple int)
useRatePath (bool)
useCurve (bool)
useRealYield (bool)
useBalanceSh (bool)
useStressFCI (bool)
wRatePath (float)
wCurve (float)
wRealYield (float)
wBS (float)
wStress (float)
hds_regime(score, thrDove, thrHawk)
Parameters:
score (float)
thrDove (int)
thrHawk (int)
hds_regime_label(score, thrDove, thrHawk)
Parameters:
score (float)
thrDove (int)
thrHawk (int) Library

moving_averages# MovingAverages Library - PineScript v6
A comprehensive PineScript v6 library containing **50+ Moving Average calculations** for PulseWire.
---
## 📦 Installation
```pinescript
import TheTradingSpiderMan/moving_averages/1 as MA
```
---
## 📊 All Available Moving Averages (50+)
### Basic Moving Averages
| Function | Selector Key | Description |
| -------- | ------------ | ------------------------------------------ |
| `sma()` | `SMA` | Simple Moving Average - arithmetic mean |
| `ema()` | `EMA` | Exponential Moving Average |
| `wma()` | `WMA` | Weighted Moving Average |
| `vwma()` | `VWMA` | Volume Weighted Moving Average |
| `rma()` | `RMA` | Relative/Smoothed Moving Average |
| `smma()` | `SMMA` | Smoothed Moving Average (alias for RMA) |
| `swma()` | - | Symmetrically Weighted MA (4-period fixed) |
### Hull Family
| Function | Selector Key | Description |
| -------- | ------------ | ------------------------------- |
| `hma()` | `HMA` | Hull Moving Average |
| `ehma()` | `EHMA` | Exponential Hull Moving Average |
### Double/Triple Smoothed
| Function | Selector Key | Description |
| -------------- | ------------ | --------------------------------- |
| `dema()` | `DEMA` | Double Exponential Moving Average |
| `tema()` | `TEMA` | Triple Exponential Moving Average |
| `tma()` | `TMA` | Triangular Moving Average |
| `t3()` | `T3` | Tillson T3 Moving Average |
| `twma()` | `TWMA` | Triple Weighted Moving Average |
| `swwma()` | `SWWMA` | Smoothed Weighted Moving Average |
| `trixSmooth()` | `TRIXSMOOTH` | Triple EMA Smoothed |
### Zero/Low Lag
| Function | Selector Key | Description |
| --------- | ------------ | ----------------------------------- |
| `zlema()` | `ZLEMA` | Zero Lag Exponential MA |
| `lsma()` | `LSMA` | Least Squares Moving Average |
| `epma()` | `EPMA` | Endpoint Moving Average |
| `ilrs()` | `ILRS` | Integral of Linear Regression Slope |
### Adaptive Moving Averages
| Function | Selector Key | Description |
| ---------- | ------------ | ------------------------------- |
| `kama()` | `KAMA` | Kaufman Adaptive Moving Average |
| `frama()` | `FRAMA` | Fractal Adaptive Moving Average |
| `vidya()` | `VIDYA` | Variable Index Dynamic Average |
| `vma()` | `VMA` | Variable Moving Average |
| `vama()` | `VAMA` | Volume Adjusted Moving Average |
| `rvma()` | `RVMA` | Rolling VMA |
| `apexMA()` | `APEXMA` | Apex Moving Average |
### Ehlers Filters
| Function | Selector Key | Description |
| ----------------- | --------------- | --------------------------------- |
| `superSmoother()` | `SUPERSMOOTHER` | Ehlers Super Smoother |
| `butterworth2()` | `BUTTERWORTH2` | 2-Pole Butterworth Filter |
| `butterworth3()` | `BUTTERWORTH3` | 3-Pole Butterworth Filter |
| `instantTrend()` | `INSTANTTREND` | Ehlers Instantaneous Trendline |
| `edsma()` | `EDSMA` | Deviation Scaled Moving Average |
| `mama()` | `MAMA` | Mesa Adaptive Moving Average |
| `fama()` | `FAMAVAL` | Following Adaptive Moving Average |
### Laguerre Family
| Function | Selector Key | Description |
| -------------------- | ------------------ | ------------------------ |
| `laguerreFilter()` | `LAGUERRE` | Laguerre Filter |
| `adaptiveLaguerre()` | `ADAPTIVELAGUERRE` | Adaptive Laguerre Filter |
### Special Weighted
| Function | Selector Key | Description |
| ---------- | ------------ | -------------------------------- |
| `alma()` | `ALMA` | Arnaud Legoux Moving Average |
| `sinwma()` | `SINWMA` | Sine Weighted Moving Average |
| `gwma()` | `GWMA` | Gaussian Weighted Moving Average |
| `nma()` | `NMA` | Natural Moving Average |
### Jurik/McGinley/Coral
| Function | Selector Key | Description |
| ------------ | ------------ | --------------------- |
| `jma()` | `JMA` | Jurik Moving Average |
| `mcginley()` | `MCGINLEY` | McGinley Dynamic |
| `coral()` | `CORAL` | Coral Trend Indicator |
### Mean Types
| Function | Selector Key | Description |
| -------------- | ------------ | ------------------------- |
| `medianMA()` | `MEDIANMA` | Median Moving Average |
| `gma()` | `GMA` | Geometric Moving Average |
| `harmonicMA()` | `HARMONICMA` | Harmonic Moving Average |
| `trimmedMA()` | `TRIMMEDMA` | Trimmed Moving Average |
| `cma()` | `CMA` | Cumulative Moving Average |
### Volume-Based
| Function | Selector Key | Description |
| --------- | ------------ | -------------------------- |
| `evwma()` | `EVWMA` | Elastic Volume Weighted MA |
### Other Specialized
| Function | Selector Key | Description |
| ----------------- | --------------- | --------------------------- |
| `hwma()` | `HWMA` | Holt-Winters Moving Average |
| `gdema()` | `GDEMA` | Generalized DEMA |
| `rema()` | `REMA` | Regularized EMA |
| `modularFilter()` | `MODULARFILTER` | Modular Filter |
| `rmt()` | `RMT` | Recursive Moving Trendline |
| `qrma()` | `QRMA` | Quadratic Regression MA |
| `wilderSmooth()` | `WILDERSMOOTH` | Welles Wilder Smoothing |
| `leoMA()` | `LEOMA` | Leo Moving Average |
| `ahrensMA()` | `AHRENSMA` | Ahrens Moving Average |
| `runningMA()` | `RUNNINGMA` | Running Moving Average |
| `ppoMA()` | `PPOMA` | PPO-based Moving Average |
| `fisherMA()` | `FISHERMA` | Fisher Transform MA |
---
## 🎯 Helper Functions
| Function | Description |
| ---------------- | ------------------------------------------------------------- |
| `wcp()` | Weighted Close Price: (H+L+2\*C)/4 |
| `typicalPrice()` | Typical Price: (H+L+C)/3 |
| `medianPrice()` | Median Price: (H+L)/2 |
| `selector()` | **Master selector** - choose any MA by string name |
| `getAllTypes()` | Returns all supported MA type names as comma-separated string |
---
## 🔧 Usage Examples
### Basic Usage
```pinescript
//@version=6
indicator("MA Example")
import quantablex/moving_averages/1 as MA
// Simple calls
plot(MA.sma(close, 20), "SMA 20", color.blue)
plot(MA.ema(close, 20), "EMA 20", color.red)
plot(MA.hma(close, 20), "HMA 20", color.green)
```
### Using the Selector Function (50+ MA Types)
```pinescript
//@version=6
indicator("MA Selector")
import quantablex/moving_averages/1 as MA
// Full list of all supported types:
// SMA,EMA,WMA,VWMA,RMA,SMMA,HMA,EHMA,DEMA,TEMA,TMA,T3,TWMA,SWWMA,TRIXSMOOTH,
// ZLEMA,LSMA,EPMA,ILRS,KAMA,FRAMA,VIDYA,VMA,VAMA,RVMA,APEXMA,SUPERSMOOTHER,
// BUTTERWORTH2,BUTTERWORTH3,INSTANTTREND,EDSMA,LAGUERRE,ADAPTIVELAGUERRE,
// ALMA,SINWMA,GWMA,NMA,JMA,MCGINLEY,CORAL,MEDIANMA,GMA,HARMONICMA,TRIMMEDMA,
// EVWMA,HWMA,GDEMA,REMA,MODULARFILTER,RMT,QRMA,WILDERSMOOTH,LEOMA,AHRENSMA,
// RUNNINGMA,PPOMA,MAMA,FAMAVAL,FISHERMA,CMA
maType = input.string("EMA", "MA Type", options= )
length = input.int(20, "Length")
plot(MA.selector(close, length, maType), "Selected MA", color.orange)
```
### Advanced Moving Averages
```pinescript
//@version=6
indicator("Advanced MAs")
import quantablex/moving_averages/1 as MA
// ALMA with custom offset and sigma
plot(MA.alma(close, 20, 0.85, 6), "ALMA", color.purple)
// KAMA with custom fast/slow periods
plot(MA.kama(close, 10, 2, 30), "KAMA", color.teal)
// T3 with custom volume factor
plot(MA.t3(close, 20, 0.7), "T3", color.yellow)
// Laguerre Filter with custom gamma
plot(MA.laguerreFilter(close, 0.8), "Laguerre", color.lime)
```
---
## 📈 MA Selection Guide
| Use Case | Recommended MAs |
| ---------------------- | ------------------------------------------- |
| **Trend Following** | EMA, DEMA, TEMA, HMA, CORAL |
| **Low Lag Required** | ZLEMA, HMA, EHMA, JMA, LSMA |
| **Volatile Markets** | KAMA, VIDYA, FRAMA, VMA, ADAPTIVELAGUERRE |
| **Smooth Signals** | T3, LAGUERRE, SUPERSMOOTHER, BUTTERWORTH2/3 |
| **Support/Resistance** | SMA, WMA, TMA, MEDIANMA |
| **Scalping** | MCGINLEY, ZLEMA, HMA, INSTANTTREND |
| **Noise Reduction** | MAMA, EDSMA, GWMA, TRIMMEDMA |
| **Volume-Based** | VWMA, EVWMA, VAMA |
---
## ⚙️ Parameters Reference
### Common Parameters
- `src` - Source series (close, open, hl2, hlc3, etc.)
- `len` - Period length (integer)
### Special Parameters
- `alma()`: `offset` (0-1), `sigma` (curve shape)
- `kama()`: `fastLen`, `slowLen`
- `t3()`: `vFactor` (volume factor)
- `jma()`: `phase` (-100 to 100)
- `laguerreFilter()`: `gamma` (0-1 damping)
- `rema()`: `lambda` (regularization)
- `modularFilter()`: `beta` (sensitivity)
- `gdema()`: `mult` (multiplier, 2 = standard DEMA)
- `trimmedMA()`: `trimPct` (0-0.5, percentage to trim)
- `mama()/fama()`: `fastLimit`, `slowLimit`
- `adaptiveLaguerre()`: Uses `len` for adaptation period
---
## 📝 Notes
- All 50+ functions are exported for use in any PineScript v6 indicator/strategy
- The `selector()` function supports **all MA types** via string key
- Use `getAllTypes()` to get a comma-separated list of all supported MA names
- Some MAs (CMA, INSTANTTREND, LAGUERRE, MAMA) don't use `len` parameter
- Use `nz()` wrapper if handling potential NA values in your calculations
---
**Author:** thetradingspiderman
**Version:** 1.0
**PineScript Version:** 6
**Total MA Types:** 50+
Library
