utilsLibrary "utils"
Few essentials captured together by ajitgorde121
timer(timeStart, timeEnd)
finds difference between two timestamps
Parameters:
timeStart (int) : start timestamp
timeEnd (int)
Returns:
check_overflow(pivots, barArray, dir)
finds difference between two timestamps
Parameters:
pivots (array) : pivots array
barArray (array) : pivot bar array
dir (int) : direction for which overflow need to be checked
Returns: bool overflow
get_trend_series(pivots, length, highLow, trend)
finds series of pivots in particular trend
Parameters:
pivots (array) : pivots array
length (int) : length for which trend series need to be checked
highLow (int) : filter pivot high or low
trend (int) : Uptrend or Downtrend
Returns: int trendIndexes
get_trend_series(pivots, firstIndex, lastIndex)
finds series of pivots in particular trend
Parameters:
pivots (array) : pivots array
firstIndex (int) : First index of the series
lastIndex (int) : Last index of the series
Returns: int trendIndexes
getConsolidatedLabel(include, labels, separator)
Consolidates labels into single string by concatenating it with given separator
Parameters:
include (array) : array of conditions to include label or not
labels (array) : string array of labels
separator (simple string) : Separator for concatenating labels
Returns: string labelText
getColors(theme)
gets array of colors based on theme
Parameters:
theme (simple string) : dark or light theme
Returns: color themeColors Library

Input Library [1CG]Input Library (v1) – User Guide
Overview
The Input Library is a Pine Script® v6 utility library that standardizes and simplifies common user input patterns across indicators, strategies, and libraries.
It provides:
Predefined timezone enums mapped to IANA/Olson strings
24-hour and 60-minute enumerations
Standardized line styles, sizes, label styles, and box alignment options
Helper methods for converting enums into PulseWire constants
Utility functions for time formatting and span calculations
This library is designed to:
Reduce repetitive input boilerplate
Improve UI consistency across scripts
Prevent string-based input errors
Encourage clean, readable configuration logic
Library Declaration
To use the library in your script:
//@version=6
import OneCleverGuy/InputLibrary/1 as IL
Timezone Enums
Timezones
Provides a comprehensive list of IANA timezone identifiers using short, intuitive enum names.
Examples include:
utc → "UTC"
exch → Exchange timezone (syminfo.timezone)
ny → "America/New_York"
lon → "Europe/London"
tokyo → "Asia/Tokyo"
syd → "Australia/Sydney"
Method: timezoneToString()
Resolves the enum to a valid timezone string.
tzString = tzInput.timezoneToString()
Behavior:
If Timezones.exch is selected, returns syminfo.timezone
Otherwise returns the mapped IANA timezone string
Time Formatting Enums
hours
Represents 24-hour values from "00" through "23".
minutes
Represents minute values from "00" through "59".
Function: combineTime()
Combines hour and minute enums into a "HHMM" formatted string.
sessionTime = IL.combineTime(hourInput, minuteInput)
Example output:
"0930"
"1600"
Drawing Style Enums
The library standardizes visual input options and converts them into PulseWire constants.
LineStyle
solid
dotted
dashed
lArrow
rArrow
bArrow
Method: lineStyle()
lineStyleValue = styleInput.lineStyle()
LineSize
thin → 1px
normal → 2px
heavy → 3px
thick → 4px
wide → 5px
Method: lineSize()
width = sizeInput.lineSize()
TextSize
auto
tiny
small
normal
large
huge
Method: textSize()
textSizeValue = textSizeInput.textSize()
Box Alignment Enums
BoxHAlign
left
center
right
BoxVAlign
top
center
bottom
Methods:
hAlign = hAlignInput.boxHAlign()
vAlign = vAlignInput.boxVAlign()
Line Extension
LineExtend
none
right
left
both
Method: lineExtend()
extendValue = extendInput.lineExtend()
Label Styles
LabelStyle
center
down
left
right
up
lowLeft
lowRight
upperLeft
upperRight
Method: labelStyle()
labelStyleValue = labelInput.labelStyle()
String-Based Conversion Helpers
For compatibility with legacy scripts or string inputs:
lineStyleFromString()
lineSizeFromString()
These functions convert common string descriptions into valid PulseWire constants.
Timezone Offset Utility
Function: getTZOffset()
Calculates the difference between a specified timezone and UTC.
offset = IL.getTZOffset("America/New_York")
Returns:
Millisecond difference between UTC and the specified timezone
Accounts for daylight saving time
Time Span Utility
Function: timeSpan()
Converts common span names into milliseconds.
Supported values:
"Minute"
"Half Hour"
"Hour"
"4 Hours"
"8 Hours"
"12 Hours"
"Day"
"Week"
Example:
ms = IL.timeSpan("Hour")
Best Practices
Prefer enums over raw strings for safer configuration
Use conversion methods directly on enum inputs
Standardize visual settings across scripts using shared enums
Avoid hardcoding timezone strings where possible
Limitations
timeSpan() supports predefined span names only
getTZOffset() returns raw millisecond difference, not formatted hours
Library does not enforce input validation beyond enum constraints
Summary
The Input Library centralizes common input patterns into a reusable, structured framework. It improves script consistency, reduces UI friction, and ensures proper conversion between user selections and PulseWire internal constants.
Designed for Pine Script® v6. Library

Library

LECAPS_BONCAP_DUALES_LibraryLECAPS BONCAP DUALES Library - Argentine Fixed Income Data
===========================================================
Library containing instrument data for Argentine Treasury fixed-rate securities (LECAPs, BONCAPs, and DUALES) and Dólar Futures contracts.
📊 CONTENTS
-----------
• LECAP (9 instruments): Zero-coupon treasury notes with "S" prefix
• BONCAP (6 instruments): Fixed-rate treasury bonds with "T" prefix
• DUALES (2 instruments): Dual-rate TAMAR-linked bonds with "M" prefix
• Dólar Futures (11 contracts): ROFEX USD/ARS futures (Feb-Dec 2026)
📈 DATA PROVIDED
----------------
For each instrument:
• Ticker symbol (full and short versions)
• Maturity price (precio de vencimiento)
• Maturity date/timestamp
🔧 EXPORTED FUNCTIONS
---------------------
// Counts
getLecapCount() → int
getBoncapCount() → int
getDualesCount() → int
getDolarFuturesCount() → int
// LECAP data
getLecapTicker(index) → string // e.g., "BCBA:S27F6"
getLecapTickerShort(index) → string // e.g., "S27F6"
getLecapMaturityPrice(index) → float // e.g., 125.84
getLecapMaturityTimestamp(index) → int
// BONCAP data
getBoncapTicker(index) → string
getBoncapTickerShort(index) → string
getBoncapMaturityPrice(index) → float
getBoncapMaturityTimestamp(index) → int
// DUALES data
getDualesTicker(index) → string
getDualesTickerShort(index) → string
getDualesMaturityPrice(index) → float
getDualesMaturityTimestamp(index) → int
// Dólar Futures data
getDolarFuturesTicker(index) → string // e.g., "ROFEX:DLRG2026"
getDolarFuturesShort(index) → string // e.g., "DLR Feb26"
getDolarFuturesExpiry(index) → int
// Helpers
isExpired(maturityTs) → bool
getDaysToMaturity(maturityTs) → int
💡 USAGE EXAMPLE
----------------
import YourUsername/LECAPS_BONCAP_DUALES_Library/1 as lib
// Get LECAP count and iterate
for i = 0 to lib.getLecapCount() - 1
ticker = lib.getLecapTickerShort(i)
maturityPrice = lib.getLecapMaturityPrice(i)
maturityTs = lib.getLecapMaturityTimestamp(i)
if not lib.isExpired(maturityTs)
// Process active instrument
daysLeft = lib.getDaysToMaturity(maturityTs)
📅 INSTRUMENTS (as of 2026-02-11)
---------------------------------
LECAP:
S27F6 (27-Feb-26), S16M6 (16-Mar-26), S17A6 (17-Apr-26),
S30A6 (30-Apr-26), S29Y6 (29-May-26), S31L6 (31-Jul-26),
S31G6 (31-Aug-26), S30O6 (30-Oct-26), S30N6 (30-Nov-26)
BONCAP:
T13F6 (13-Feb-26), T30J6 (30-Jun-26), T15E7 (15-Jan-27),
T30A7 (30-Apr-27), T31Y7 (31-May-27), T30J7 (30-Jun-27)
DUALES:
M27F6 (27-Feb-26), M30A6 (30-Apr-26)
DÓLAR FUTURES:
DLRG2026 (Feb), DLRH2026 (Mar), DLRJ2026 (Apr), DLRK2026 (May),
DLRM2026 (Jun), DLRN2026 (Jul), DLRQ2026 (Aug), DLRU2026 (Sep),
DLRV2026 (Oct), DLRX2026 (Nov), DLRZ2026 (Dec)
⚠️ NOTES
--------
• Data is updated periodically as new instruments are issued
• Expired instruments are automatically filtered via isExpired()
• Maturity prices are set at public auction (licitación)
• Use with the companion indicator "Breakeven LECAPs BONCAPs DUALES"
🏷️ TAGS
-------
argentina, lecap, boncap, duales, treasury, fixed-income, bonds,
letras, bonos, dolar, futures, rofex, bcba, breakeven
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

Library

TrinityCore30Library "TrinityCore30"
TRINITY CORE LIBRARY v30.1 (Diamond Final / Safety Sync Fixed)
Architecture: Fixed 7 Calls / Raw Kernels / State Machine / Array Math
Constitution:
1. Max 7 security calls.
2. Bible Compliance: CD (Corr), DDG (Ratio), Dynamic Lengths.
3. Ironclad Math: Volatility %, NaN-Guarded.
4. Semantics: Safety Valve correctly syncs is_ready/risk_gate flags.
calc_weights(sym, cp, cs, s1, s2, s3, s4, s5, cfg)
Parameters:
sym (string)
cp (string)
cs (string)
s1 (string)
s2 (string)
s3 (string)
s4 (string)
s5 (string)
cfg (TrinityConfig)
calc_diagnostics(sym, cp, cs, s1, s2, s3, s4, s5, cfg)
Parameters:
sym (string)
cp (string)
cs (string)
s1 (string)
s2 (string)
s3 (string)
s4 (string)
s5 (string)
cfg (TrinityConfig)
calc_weights_flat(sym, cp, cs, s1, s2, s3, s4, s5, en, l20, w20, l63, w63, l126, w126, l252, w252, rf, fac, tvs, tvsf, gmm, kl, kd, ks, tk, bl, wcp, wcd, wvs, wdd, sp, sv, ft, rf2, ra, r_cp, r_dd, pen_v, rb)
Parameters:
sym (string)
cp (string)
cs (string)
s1 (string)
s2 (string)
s3 (string)
s4 (string)
s5 (string)
en (bool)
l20 (int)
w20 (float)
l63 (int)
w63 (float)
l126 (int)
w126 (float)
l252 (int)
w252 (float)
rf (float)
fac (float)
tvs (float)
tvsf (float)
gmm (float)
kl (int)
kd (float)
ks (float)
tk (int)
bl (float)
wcp (float)
wcd (float)
wvs (float)
wdd (float)
sp (float)
sv (float)
ft (float)
rf2 (float)
ra (float)
r_cp (float)
r_dd (float)
pen_v (float)
rb (int)
core_build()
TrinityWeights
Fields:
stock (series float)
safe1 (series float)
safe2 (series float)
safe3 (series float)
safe4 (series float)
safe5 (series float)
cash (series float)
TrinityDiagLite
Fields:
is_ready (series bool)
ready_code (series int)
core_build (series int)
risk_gate (series bool)
wroc_stock (series float)
valid_safe_count (series int)
passed_safe_count (series int)
sum_ok (series bool)
TrinityDiagFull
Fields:
raw_stock (series float)
mvol_stock (series float)
mdecel_stock (series float)
gov_stock (series float)
safe_budget (series float)
top1_id (series int)
top2_id (series int)
sum_weights (series float)
SafeDiag
Fields:
enabled (series bool)
valid (series bool)
sqs (series float)
final_w (series float)
drop_code (series int)
TrinityConfig
Fields:
enabled (series bool)
len_20 (series int)
w_20 (series float)
len_63 (series int)
w_63 (series float)
len_126 (series int)
w_126 (series float)
len_252 (series int)
w_252 (series float)
risk_floor (series float)
risk_factor (series float)
target_vol_stock (series float)
target_vol_safe (series float)
gov_min_mult (series float)
k_len (series int)
k_decay (series float)
k_scale (series float)
top_k (series int)
baseline (series float)
w_cp (series float)
w_cd (series float)
w_vs (series float)
w_ddg (series float)
shock_price (series float)
shock_vol (series float)
fall_thr (series float)
rate_fall (series float)
rate_accel (series float)
penalty_val (series float)
range_cp (series float)
range_dd (series float)
ready_bars (series int) Library

Library

Library

MovingAveragesLibrary "MovingAverages"
A collection of O(1) numerically stable moving averages that support anchors and fractional lengths up to 100k bars.
Pine Script has a robust set of moving averages suitable for a majority of cases, making these alternatives useful only if you need anchoring, fractional lengths, or more than 5k bars. Included are the classic SMA , EMA , RMA , WMA , VWMA , VWAP , HMA , SWMA , Linear Regression , and ATR . The common parameters are:
source (float) : Series of values to process.
length (simple float) : Number of bars. Optional.
anchor (bool) : The condition that triggers a calculation reset. Optional.
parity (simple bool) : Sets if built-in function should be used. Optional.
Other DSP filter adaptations include One Euro , Laguerre , Super Smoother , and Holt , as well as rate limiting functions such as Smooth Damp and Slew Rate Limiter .
ANCHORING
This is the libraries first and primary benefit. Akin to the built-in VWAP, anchoring is managed by passing a series bool into the function. For sessional anchoring, the included new_session() returns true on the first bar of intraday sessions, and stabilize_anchor() helps reduce near-anchor volatility. When no length is provided, the series continues indefinitely until a new anchor is set. Values during the warmup period are returned.
source = close
length = 9.5
anchor = ma.new_session() // Assumes library is imported as "ma"
swma = ma.swma(source, length, anchor).stabilize_anchor(source, length, anchor)
STREAMING UPDATES
Rather than naively using loops to recalculate the whole series on each bar, linear interpolation (aka. "lerping") is used to incrementally update and translate between values. The canonical formula being: a + (b - a) * t. This formula is effectively an EMA, but it's applicable to nearly all averaging equations. Coupling this technique with a circular buffer captures 3 of the 5 benefits this library offers: O(1) computation, fractional lengths, and 100k bars.
NUMERIC STABILITY
The last benefit is how the library minimizes floating point errors. When possible, Pine Script functions are used for mathematical parity. Otherwise Kahan summation error compensation is used when calculating an average. Not only does this keep custom implementations stable throughout the series, it also helps keep them within 1.0e-10 of the built-in functions. Automatically defaulting to the built-in functions can be disabled by setting parity to false . Library

blueprint_ephemeris_lib🔭 Library blueprint_ephemeris_lib
Consolidated planetary ephemeris library with improved accuracy. Supersedes previous individual planet libraries (lib_vsop_core, lib_vsop_mercury, lib_vsop_venus, etc.). One import gives you geocentric/heliocentric positions for all 10 solar system bodies.
█ ACCURACY — VALIDATED AGAINST JPL DE440
Every planetary body was validated against NASA's DE440 ephemeris (via Skyfield). Using only 1.6% of the full VSOP87D theory (511 of 31,577 terms), this library achieves sub-arcminute accuracy for all planets:
Sun 0.004° (14 arcseconds)
Mercury 0.005° (18")
Venus 0.006° (22")
Mars 0.010° (36")
Jupiter 0.007° (25")
Saturn 0.009° (32")
Uranus 0.013° (47")
Neptune 0.017° (61")
Moon 0.062° (3.7')
Pluto 0.059° (3.5')
All bodies under 0.1° RMS — more than sufficient for aspect calculations, ingress timing, and planetary line work. The Sun is accurate to 14 arcseconds using a truncated series that fits entirely inside Pine Script's token limits.
█ WHAT'S NEW (V2)
The original ephemeris required 11 chained library imports. A full validation audit uncovered critical coefficient errors and motivated this rewrite:
• L1 Precession Fix — All 8 VSOP87 planets had incorrect longitude rate coefficients (VSOP87B values instead of VSOP87D). Each was missing +0.24382 rad/millennium of general precession. This single correction reduced error from ~0.75° to < 0.1° across the board.
• 28% Smaller — 4,300 lines across 11 files → ~3,100 lines in 1 file.
• Single Import — No dependency chain. Faster execution.
• Moon Improvements — Functions accept raw `time` directly. Node functions renamed with explicit north/south designation.
█ THEORIES
VSOP87D (Bretagnon & Francou, 1988) — Mercury through Neptune
511 truncated terms out of 31,577 total (1.6%). Heliocentric spherical
coordinates in the ecliptic of date.
ELP2000-82 (Chapront-Touzé & Chapront, 1983) — Moon
91 terms (48 longitude + 43 latitude) from Meeus Chapter 47.
Meeus Series (Meeus, 1998) — Pluto
Analytical series from "Astronomical Algorithms" Ch. 37.
Valid ±1 century from J2000.
█ HOW TO USE
Import the library:
import BlueprintResearch/blueprint_ephemeris_lib/1 as eph
Basic — plot a planet's geocentric longitude and declination:
float jupiter_lon = eph.get_longitude(eph.Planet.Jupiter, time, true)
float jupiter_decl = eph.get_declination(eph.Planet.Jupiter, time)
plot(jupiter_lon, "Jupiter Geo Lon", color.yellow)
plot(jupiter_decl, "Jupiter Decl", color.red)
Retrograde detection:
bool mercury_retro = eph.is_retrograde(eph.Planet.Mercury, time)
bgcolor(mercury_retro ? color.new(color.red, 90) : na)
Moon nodes and declination:
float north_node = eph.get_mean_north_node_lon(time)
float south_node = eph.get_mean_south_node_lon(time)
float moon_decl = eph.get_declination(time)
plot(north_node, "North Node", color.green)
plot(south_node, "South Node", color.purple)
plot(moon_decl, "Moon Declination", color.orange)
Dynamic planet selection from input:
string planet_str = input.string("Sun", "Planet", options= )
eph.Planet p = eph.string_to_planet(planet_str)
float geo = eph.get_longitude(p, time, true)
float helio = eph.get_longitude(p, time, false)
float speed = eph.get_speed(p, time)
plot(geo, "Geocentric", color.yellow)
plot(helio, "Heliocentric", color.blue)
plot(speed * 100, "Speed x100", color.white)
All functions accept PulseWire's `time` variable directly.
█ FUNCTIONS
Unified API (all planets):
`get_longitude(Planet, time, preferGeo)` — geo or heliocentric longitude
`get_declination(Planet, time)` — equatorial declination
`get_speed(Planet, time)` — longitude speed (°/day)
`is_retrograde(Planet, time)` — true when retrograde
`string_to_planet(string)` — name to enum
Averages :
`get_avg6_geo_lon` / `get_avg6_helio_lon` — Mercury–Saturn
`get_avg8_geo_lon` / `get_avg8_helio_lon` — Mercury–Neptune
Moon (direct access):
`get_geo_ecl_lon(time)` · `get_geo_ecl_lat(time)` · `get_declination(time)`
`get_mean_north_node_lon(time)` · `get_mean_south_node_lon(time)`
`get_true_north_node_lon(time)` · `get_true_south_node_lon(time)`
`get_north_node_declination(time)` · `get_south_node_declination(time)`
█ LIMITATIONS
• Truncated series — sub-degree accuracy, not sub-arcsecond. More than sufficient for ingress timing and aspect work.
• Validated against DE440 across 250 years (1850–2100). Over this full span, the worst-case VSOP87 planet (Uranus) is 0.017° RMS / 0.043° max error. Ingress dates manually verified back to the late 1800s with consistent accuracy.
• Pluto uses Meeus series, limited to ±1 century from J2000.
• Moon has no speed function.
█ ACKNOWLEDGMENTS
Coefficient validation was made possible by Greg Miller's VSOP87 multi-language project, which provides the complete VSOP87D coefficient tables in accessible formats. His work converting the original Fortran data files into CSV/JSON for multiple languages was essential for identifying the L1 precession errors in the original libraries. Miller released this work into the public domain.
github.com/gmiller123456/vsop87-multilang
References :
• Meeus, Jean. Astronomical Algorithms (2nd Ed., 1998)
• Bretagnon & Francou. VSOP87 Solutions (Astronomy & Astrophysics, 1988)
• Chapront-Touzé & Chapront. ELP2000-82 (1983)
█ OPEN SOURCE
MIT License — part of the Blueprint Research open-source toolkit.
Source code on GitHub
get_geo_ecl_lon(time_)
Returns geocentric ecliptic longitude of the Moon.
Parameters:
time_ (float)
Returns: (float) Longitude in degrees, range [0, 360).
get_geo_ecl_lat(time_)
Returns geocentric ecliptic latitude of the Moon.
Parameters:
time_ (float)
Returns: (float) Latitude in degrees.
get_obliquity_j(time_)
Returns mean obliquity of the ecliptic.
Parameters:
time_ (float)
Returns: (float) Obliquity in degrees.
get_declination(time_)
Returns geocentric equatorial declination of the Moon.
Parameters:
time_ (float)
Returns: (float) Declination in degrees, range where positive is north.
get_declination(p, t)
Returns planetary geocentric equatorial declination.
Parameters:
p (series Planet) : (Planet) Planet to query.
t (float) : (float) Unix timestamp in milliseconds (use built-in 'time' variable).
Returns: (float) Geocentric declination in degrees, range where positive is north.
@note Declination is always geocentric (no heliocentric equivalent in library).
get_mean_north_node_lon(time_)
Returns mean longitude of the Moon's North Node (ascending node).
Parameters:
time_ (float)
Returns: (float) Longitude in degrees, range [0, 360).
@note Mean node is a simple averaged calculation, reducing computational error. Used for declination calculations.
get_mean_south_node_lon(time_)
Returns mean longitude of the Moon's South Node (descending node).
Parameters:
time_ (float)
Returns: (float) Longitude in degrees, range [0, 360). Equals North Node + 180°.
get_true_north_node_lon(time_)
Returns true longitude of the Moon's North Node with perturbation corrections.
Parameters:
time_ (float)
Returns: (float) Longitude in degrees, range [0, 360).
@note True node includes periodic perturbations but formula is low precision. Consider using mean node for consistency.
get_true_south_node_lon(time_)
Returns true longitude of the Moon's South Node with perturbation corrections.
Parameters:
time_ (float)
Returns: (float) Longitude in degrees, range [0, 360). Equals True North Node + 180°.
get_north_node_declination(time_)
Returns declination of the Moon's North Node.
Parameters:
time_ (float)
Returns: (float) Declination in degrees, range (bounded by obliquity).
@note Uses mean node for calculation (more consistent than true node).
get_south_node_declination(time_)
Returns declination of the Moon's South Node.
Parameters:
time_ (float)
Returns: (float) Declination in degrees. Inverse of North Node declination.
normalizeLongitude(lon)
Normalizes any longitude value to the range [0, 360) degrees.
Parameters:
lon (float) : (float) Longitude in degrees (can be any value, including negative or >360).
Returns: (float) Normalized longitude in range [0, 360).
string_to_planet(planetStr)
Converts a planet string identifier to Planet enum value.
Parameters:
planetStr (string) : (string) Planet name (case-insensitive). Supports formats: "Sun", "☉︎ Sun", "sun", "SUN"
Returns: (Planet) Corresponding Planet enum. Returns Planet.Sun if string not recognized.
@note Supported planet strings: Sun, Moon, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto
get_longitude(p, t, preferGeo)
Returns planetary longitude with automatic coordinate system selection.
Parameters:
p (series Planet) : (Planet) Planet to query.
t (float) : (float) Unix timestamp in milliseconds (use built-in 'time' variable).
preferGeo (bool) : (bool) If true, return geocentric; if false, return heliocentric.
Returns: (float) Longitude in degrees, normalized to range [0, 360).
@note Sun and Moon always return geocentric regardless of preference (heliocentric not applicable).
get_speed(p, t)
Returns planetary geocentric longitude speed (rate of change).
Parameters:
p (series Planet) : (Planet) Planet to query.
t (float) : (float) Unix timestamp in milliseconds (use built-in 'time' variable).
Returns: (float) Geocentric longitude speed in degrees per day. Negative values indicate retrograde motion. Returns na for Moon.
@note Speed is always geocentric (no heliocentric equivalent in library). Moon speed calculation not implemented.
get_avg6_geo_lon(t)
get_avg6_geo_lon
@description Returns the arithmetic average of the geocentric longitudes for the six outer planets: Mars, Jupiter, Saturn, Uranus, Neptune, and Pluto.
Parameters:
t (float) : (float) Time in Unix timestamp (milliseconds).
Returns: (float) Average geocentric longitude of the six outer planets in degrees, range [0, 360).
get_avg6_helio_lon(t)
get_avg6_helio_lon
@description Returns the arithmetic average of the heliocentric longitudes for the six outer planets: Mars, Jupiter, Saturn, Uranus, Neptune, and Pluto.
Parameters:
t (float) : (float) Time in Unix timestamp (milliseconds).
Returns: (float) Average heliocentric longitude of the six outer planets in degrees, range [0, 360).
get_avg8_geo_lon(t)
get_avg8_geo_lon
@description Returns the arithmetic average of the geocentric longitudes for all eight classical planets: Mercury, Venus, Mars, Jupiter, Saturn, Uranus, Neptune, and Pluto.
Parameters:
t (float) : (float) Time in Unix timestamp (milliseconds).
Returns: (float) Average geocentric longitude of all eight classical planets in degrees, range [0, 360).
get_avg8_helio_lon(t)
get_avg8_helio_lon
@description Returns the arithmetic average of the heliocentric longitudes for all eight classical planets: Mercury, Venus, Mars, Jupiter, Saturn, Uranus, Neptune, and Pluto.
Parameters:
t (float) : (float) Time in Unix timestamp (milliseconds).
Returns: (float) Average heliocentric longitude of all eight classical planets in degrees, range [0, 360).
is_retrograde(p, t)
Returns true if the planet is currently in retrograde motion (geocentric speed < 0) == 0 = stationary.
Parameters:
p (series Planet) : The planet to check.
t (float) : Time in Unix timestamp (milliseconds).
Returns: true if the planet is in retrograde, false otherwise. Library

Library

_MyLibraryV1Library "_MyLibraryV1"
maStackedBull(src, fastLen, midLen, slowLen)
Parameters:
src (float)
fastLen (int)
midLen (int)
slowLen (int)
maStackedBear(src, fastLen, midLen, slowLen)
Parameters:
src (float)
fastLen (int)
midLen (int)
slowLen (int)
bullCross(src1, src2)
Parameters:
src1 (float)
src2 (float)
bearCross(src1, src2)
Parameters:
src1 (float)
src2 (float)
bullRegime(src, len)
Parameters:
src (float)
len (int)
bearRegime(src, len)
Parameters:
src (float)
len (int)
rsiBull(len)
Parameters:
len (simple int)
rsiBear(len)
Parameters:
len (simple int)
atrExpansion(len)
Parameters:
len (simple int)
atrContraction(len)
Parameters:
len (simple int) Library

Library

Library

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

Library
