TAIndicatorsThis library offers a comprehensive suite of enhanced  technical indicator  functions, building upon TradingView's built-in indicators. The primary advantage of this library is its expanded flexibility, allowing you to select from a wider range of  moving average types  for  calculations  and  smoothing  across various indicators.
The core difference between these functions and TradingView's standard ones is the ability to specify different moving average types beyond the default. While a standard  ta.rsi()  is fixed, the  rsi()  in this library, for example, can be smoothed by an 'SMMA (RMA)', 'WMA', 'VWMA', or others, giving you greater control over your analysis.
█  FEATURES 
This library provides enhanced versions of the following popular indicators:
 
 Moving Average (ma):  A versatile MA function that includes optional secondary smoothing and Bollinger Bands.
 RSI (rsi):  Calculate RSI with an optional smoothed signal line using various MA types, plus built-in divergence detection.
 MACD (macd):  A MACD function where you can define the MA type for both the main calculation and the signal line.
 ATR (atr):  An ATR function that allows for different smoothing types.
 VWAP (vwap):  A comprehensive anchored VWAP with multiple configurable bands.
 ADX (adx):  A standard ADX calculation.
 Cumulative Volume Delta (cvd):  Provides CVD data based on a lower timeframe.
 Bollinger Bands (bb):  Create Bollinger Bands with a customizable MA type for the basis line.
 Keltner Channels (kc):  Keltner Channels with selectable MA types and band styles.
 On-Balance Volume (obv):  An OBV indicator with an optional smoothed signal line using various MA types.
 ... and more to come!  This library will be actively maintained, with new useful indicator functions added over time.
 
█  HOW TO USE 
To use this library in your scripts, import it using its publishing link. You can then call the functions directly.
For example, to calculate a  Weighted Moving Average (WMA)  and then smooth it with a  Simple Moving Average (SMA) :
 import ActiveQuants/TAIndicators/1 as tai
// Calculate a 20-period WMA of the close
// Then, smooth the result with a 10-period SMA
  = tai.ma("WMA", close, 20, "SMA", 10)
plot(myWma, color = color.blue)
plot(smoothedWma, color = color.orange) 
█  Why Choose This Library? 
If you're looking for more control and customization than what's offered by the standard built-in functions, this library is for you. By allowing for a variety of smoothing methods across multiple indicators, it enables a more nuanced and personalized approach to technical analysis. Fine-tune your indicators to better fit your trading style and strategies.
Statistics
StatMetricsLibrary   "StatMetrics" 
A utility library for common statistical indicators and ratios used in technical analysis.
Includes Z-Score, correlation, PLF, SRI, Sharpe, Sortino, Omega ratios, and normalization tools.
 zscore(src, len) 
  Calculates the Z-score of a series
  Parameters:
     src (float) : The input price or series (e.g., close)
     len (simple int) : The lookback period for mean and standard deviation
  Returns: Z-score: number of standard deviations the input is from the mean
 corr(x, y, len) 
  Computes Pearson correlation coefficient between two series
  Parameters:
     x (float) : First series
     y (float) : Second series
     len (simple int) : Lookback period
  Returns: Correlation coefficient between -1 and 1
 plf(src, longLen, shortLen, smoothLen) 
  Calculates the Price Lag Factor (PLF) as the difference between long and short Z-scores, normalized and smoothed
  Parameters:
     src (float) : Source series (e.g., close)
     longLen (simple int) : Long Z-score period
     shortLen (simple int) : Short Z-score period
     smoothLen (simple int) : Hull MA smoothing length
  Returns: Smoothed and normalized PLF oscillator
 sri(signal, len) 
  Computes the Statistical Reliability Index (SRI) based on trend persistence
  Parameters:
     signal (float) : A price or signal series (e.g., smoothed PLF)
     len (simple int) : Lookback period for smoothing and deviation
  Returns: Normalized trend reliability score
 sharpe(src, len) 
  Calculates the Sharpe Ratio over a period
  Parameters:
     src (float) : Price series (e.g., close)
     len (simple int) : Lookback period
  Returns: Sharpe ratio value
 sortino(src, len) 
  Calculates the Sortino Ratio over a period, using only downside volatility
  Parameters:
     src (float) : Price series
     len (simple int) : Lookback period
  Returns: Sortino ratio value
 omega(src, len) 
  Calculates the Omega Ratio as the ratio of upside to downside return area
  Parameters:
     src (float) : Price series
     len (simple int) : Lookback period
  Returns: Omega ratio value
 beta(asset, benchmark, len) 
  Calculates beta coefficient of asset vs benchmark using rolling covariance
  Parameters:
     asset (float) : Series of the asset (e.g., close)
     benchmark (float) : Series of the benchmark (e.g., SPX close)
     len (simple int) : Lookback window
  Returns: Beta value (slope of linear regression)
 alpha(asset, benchmark, len) 
  Calculates rolling alpha of an asset relative to a benchmark
  Parameters:
     asset (float) : Series of the asset (e.g., close)
     benchmark (float) : Series of the benchmark (e.g., SPX close)
     len (simple int) : Lookback window
  Returns: Alpha value (excess return not explained by Beta exposure)
 skew(x, len) 
  Computes skewness of a return series
  Parameters:
     x (float) : Input series (e.g., returns)
     len (simple int) : Lookback period
  Returns: Skewness value
 kurtosis(x, len) 
  Computes kurtosis of a return series
  Parameters:
     x (float) : Input series (e.g., returns)
     len (simple int) : Lookback period
  Returns: Kurtosis value
 cv(x, len) 
  Calculates Coefficient of Variation
  Parameters:
     x (float) : Input series (e.g., returns or prices)
     len (simple int) : Lookback period
  Returns: CV value
 autocorr(x, len) 
  Calculates autocorrelation with 1-lag
  Parameters:
     x (float) : Series to test
     len (simple int) : Lookback window
  Returns: Autocorrelation at lag 1
 stderr(x, len) 
  Calculates rolling standard error of a series
  Parameters:
     x (float) : Input series
     len (simple int) : Lookback window
  Returns: Standard error (std dev / sqrt(n))
 info_ratio(asset, benchmark, len) 
  Calculates the Information Ratio
  Parameters:
     asset (float) : Asset price series
     benchmark (float) : Benchmark price series
     len (simple int) : Lookback period
  Returns: Information ratio (alpha / tracking error)
 tracking_error(asset, benchmark, len) 
  Measures deviation from benchmark (Tracking Error)
  Parameters:
     asset (float) : Asset return series
     benchmark (float) : Benchmark return series
     len (simple int) : Lookback window
  Returns: Tracking error value
 max_drawdown(x, len) 
  Computes maximum drawdown over a rolling window
  Parameters:
     x (float) : Price series
     len (simple int) : Lookback window
  Returns: Rolling max drawdown percentage (as a negative value)
 zscore_signal(z, ob, os) 
  Converts Z-score into a 3-level signal
  Parameters:
     z (float) : Z-score series
     ob (float) : Overbought threshold
     os (float) : Oversold threshold
  Returns: -1, 0, or 1 depending on signal state
 r_squared(x, y, len) 
  Calculates rolling R-squared (coefficient of determination)
  Parameters:
     x (float) : Asset returns
     y (float) : Benchmark returns
     len (simple int) : Lookback window
  Returns: R-squared value (0 to 1)
 entropy(x, len) 
  Approximates Shannon entropy using log returns
  Parameters:
     x (float) : Price series
     len (simple int) : Lookback period
  Returns: Approximate entropy
 zreversal(z) 
  Detects Z-score reversals to the mean
  Parameters:
     z (float) : Z-score series
  Returns: +1 on upward reversal, -1 on downward
 momentum_rank(x, len) 
  Calculates relative momentum strength
  Parameters:
     x (float) : Price series
     len (simple int) : Lookback window
  Returns: Proportion of lookback where current price is higher
 normalize(x, len) 
  Normalizes a series to a 0–1 range over a period
  Parameters:
     x (float) : The input series
     len (simple int) : Lookback period
  Returns: Normalized value between 0 and 1
 composite_score(score1, score2, score3) 
  Combines multiple normalized scores into a composite score
  Parameters:
     score1 (float) 
     score2 (float) 
     score3 (float) 
  Returns: Average composite score
MonthlyPnLTableLibrary   "MonthlyPnLTable" 
 monthlyPnL(currentClose, initialOpenPrice, monthsToDisplay) 
  Parameters:
     currentClose (float) 
     initialOpenPrice (float) 
     monthsToDisplay (int) 
 displayPnLTable(pnls, pnlMonths, pnlYears, textSizeOption, labelColor) 
  Parameters:
     pnls (array) 
     pnlMonths (array) 
     pnlYears (array) 
     textSizeOption (string) 
     labelColor (color)
Crypto_in_details_MAlibCrypto_in_details_MaLib — Advanced Moving Average Library for Pine Script
Overview:
Crypto_in_details_MaLib is a comprehensive, performance-optimized Moving Average (MA) library designed specifically for Pine Script v6 users seeking advanced technical analysis tools. Developed by Crypto_in_details, this library consolidates the most popular and sophisticated MA calculation methods — including classical, weighted, exponential, and Hull variants — into one seamless package.
Key Features:
Implements a wide range of Moving Averages: SMA, EMA, WMA, RMA, VWMA, HMA, TEMA, EHMA, THMA.
Designed for precision and flexibility — suitable for diverse trading strategies and indicator development.
Fully typed functions compatible with Pine Script v6 standards.
Simplifies your scripting workflow by providing ready-to-use MA functions via clean and easy-to-import methods.
Well-documented and maintained by an experienced Pine Script developer.
Why Use Crypto_in_details_MaLib?
Gain access to advanced MA calculations that enhance trend analysis, smoothing, and signal accuracy.
Save time on coding complex moving averages from scratch.
Easily extend or combine with your own strategies or indicators for improved performance.
Rely on a tested and community-driven solution backed by a prolific Pine Script author.
Ideal for:
Traders and developers building custom indicators or strategies requiring versatile MA techniques.
Anyone looking to improve their Pine Script efficiency and code maintainability.
Pine Script enthusiasts wanting a professional-grade MA toolkit.
VolumeFlowOscillatorLibVolume Flow Oscillator Library 
 Overview 
The Volume Flow Oscillator library provides a comprehensive framework for analyzing directional volume flow in financial markets. It creates a multi-band oscillator system that transforms price and volume data into a spectrum of sensitivity bands, revealing the underlying buying and selling pressure.
 Technical Approach 
The library combines price direction with trading volume to generate an oscillator that fluctuates around a zero line, with positive values indicating buying pressure and negative values showing selling pressure. Using sophisticated ALMA (Arnaud Legoux Moving Average) smoothing techniques with asymmetric sensitivity, the library creates seven distinct bands that help identify various intensity levels of volume flow.
 Key Features 
 
  Multi-band oscillator system with seven sensitivity levels
  Directional volume flow analysis combining price movement and volume
  Zero-line oscillation showing the balance between buying and selling pressure
  Asymmetric ALMA smoothing for different sensitivity on positive/negative bands
  Customizable lookback periods and multipliers for fine-tuning
  Color-coded visualization for intuitive chart reading
 
 Applications 
This library offers developers a versatile foundation for creating volume-based indicators that go beyond simple volume measurement to reveal the directional force behind market movements. Ideal for confirming price trends, detecting divergences, identifying volume climaxes, and assessing overall market strength.
TradeTrackerLibrary   "TradeTracker" 
Simple Library for tracking trades
 method track(this) 
  tracks trade when called on every bar
  Namespace types: Trade
  Parameters:
     this (Trade) : Trade object
  Returns: current Trade object
 Trade 
  Has the constituents to track trades generated by any method.
  Fields:
     id (series int) 
     direction (series int) : Trade direction. Positive values for long and negative values for short trades
     initialEntry (series float) : Initial entry price. This value will not change even if the entry is changed in the lifecycle of the trade
     entry (series float) : Updated entry price. Allows variations to initial calculated entry. Useful in cases of trailing entry.
     initialStop (series float) : Initial stop. Similar to initial entry, this is the first calculated stop for the lifecycle of trade.
     stop (series float) : Trailing Stop. If there is no trailing, the value will be same as that of initial trade
     targets (array) : array of target values.
     startBar (series int) : bar index of starting bar. Set by default when object is created. No need to alter this after that.
     endBar (series int) : bar index of last bar in trade. Set by tracker on each execution
     startTime (series int) : time of the start bar. Set by default when object is created. No need to alter this after that.
     endTime (series int) : time of the ending bar. Updated by tracking method.
     status (series int) : Integer parameter to track the status of the trade
     retest (series bool) : Boolean parameter to notify if there was retest of the entry price
tafirstlibGeneral Purpose: Starts by stating it's a collection of utility functions for technical analysis.
Core Functionality Areas: Mentions key categories like:
Extrema detection (isMin, isMax, etc.)
Condition checking over time (isMachedInRange, isContinuous, etc.)
Rate of change analysis (isSlowDown)
Moving average calculation (getMA)
Advanced Features: Highlights the more complex functions:
Visualization helpers (getColorNew)
Moving Regression (mr) for smoothing/trend
Cycle analysis (bpDom)
Overall Goal: Concludes by stating the library's aim – simplifying development and enabling complex analysis.
Library   "tafirstlib" 
TODO: add library description here
 isSlowDown(data) 
  isSlowDown
  Parameters:
     data (float) : array of numbers
  Returns: boolean
 isMin(data, maeLength) 
  isMin
  Parameters:
     data (float) : array of numbers
     maeLength (int) : number
  Returns: boolean
 isMax(data, maeLength) 
  isMax
  Parameters:
     data (float) : array of numbers
     maeLength (int) : number
  Returns: boolean
 isMinStopped(data, maeLength) 
  isMinStopped
  Parameters:
     data (float) : array of numbers
     maeLength (int) : number
  Returns: boolean
 isMaxStopped(data, maeLength) 
  isMaxStopped
  Parameters:
     data (float) : array of numbers
     maeLength (int) : number
  Returns: boolean
 isLongMinStopped(data, maeLength, distance) 
  isLongMinStopped
  Parameters:
     data (float) : array of numbers
     maeLength (int) : number
     distance (int) : number
  Returns: boolean
 isLongMaxStopped(data, maeLength, distance) 
  isLongMaxStopped
  Parameters:
     data (float) : array of numbers
     maeLength (int) : number
     distance (int) : number
  Returns: boolean
 isMachedInRangeSkipCurrent(data, findRange, findValue) 
  isMachedInRangeSkipCurrent
  Parameters:
     data (bool) : array of numbers
     findRange (int) : number
     findValue (bool) : number
  Returns: boolean
 isMachedInRange(data, findRange, findValue) 
  isMachedInRange
  Parameters:
     data (bool) : array of numbers
     findRange (int) : number
     findValue (bool) : number
  Returns: boolean
 isMachedColorInRange(data, findRange, findValue) 
  isMachedColorInRange  isMachedColorInRange(series color data, int findRange, color findValue)
  Parameters:
     data (color) : series of color
     findRange (int) : int
     findValue (color) : color
  Returns: boolean
 countMachedInRange(data, findRange, findValue) 
  countMachedInRange
  Parameters:
     data (bool) : array of numbers
     findRange (int) : number
     findValue (bool) : number
  Returns: number
 getColor(data) 
  getColor
  Parameters:
     data (float) : array of numbers
  Returns: color
 getColorNew(data) 
  getColorNew
  Parameters:
     data (float) : array of numbers
  Returns: color
 isColorBetter(color_data) 
  isColorBetter
  Parameters:
     color_data (color) : array of colors
  Returns: boolean
 isColorWorst(color_data) 
  isColorWorst
  Parameters:
     color_data (color) : array of colors
  Returns: boolean
 isColorBetter2(color_data) 
  isColorBetter2
  Parameters:
     color_data (color) : array of colors
  Returns: boolean
 isColorWorst2(color_data) 
  isColorWorst2
  Parameters:
     color_data (color) : array of colors
  Returns: boolean
 isDecreased2Bar(data) 
  isDecreased2Bar
  Parameters:
     data (float) : array of numbers
  Returns: boolean
 isContinuousAdvance(targetSeries, range2Find, howManyException) 
  isContinuousAdvance
  Parameters:
     targetSeries (bool) : array of booleans
     range2Find (int) : number
     howManyException (int) : number
  Returns: boolean
 isContinuous(targetSeries, range2Find, truefalse) 
  isContinuous
  Parameters:
     targetSeries (bool) : array of booleans
     range2Find (int) : number
     truefalse (bool) : boolean
  Returns: boolean
 isContinuousNotNow(targetSeries, range2Find, truefalse) 
  isContinuousNotNow
  Parameters:
     targetSeries (bool) : array of booleans
     range2Find (int) : number
     truefalse (bool) : boolean
  Returns: boolean
 isContinuousTwoFactors(targetSeries, range2Find, truefalse) 
  isContinuousTwoFactors
  Parameters:
     targetSeries (bool) : array of booleans
     range2Find (int) : number
     truefalse (bool) : boolean
  Returns: boolean
 findEventInRange(startDataBarIndex, neededDataBarIndex, currentBarIndex) 
  findEventInRange
  Parameters:
     startDataBarIndex (int) : number
     neededDataBarIndex (int) : number
     currentBarIndex (int) : number
  Returns: boolean
 findMin(firstdata, secondata, thirddata, forthdata) 
  findMin
  Parameters:
     firstdata (float) : number
     secondata (float) : number
     thirddata (float) : number
     forthdata (float) : number
  Returns: number
 findMax(firstdata, secondata, thirddata, forthdata) 
  findMax
  Parameters:
     firstdata (float) : number
     secondata (float) : number
     thirddata (float) : number
     forthdata (float) : number
  Returns: number
 getMA(src, length, mav) 
  getMA
  Parameters:
     src (float) : number
     length (simple int) : number
     mav (string) : string
  Returns: number
 mr(mrb_src, mrb_window, mrb_degree) 
  Parameters:
     mrb_src (float) 
     mrb_window (int) 
     mrb_degree (int) 
 bpDom(maeLength, bpw, mult) 
  Parameters:
     maeLength (int) 
     bpw (float) 
     mult (float)
FunctionSurvivalEstimationLibrary   "FunctionSurvivalEstimation" 
The Survival Estimation function, also known as Kaplan-Meier estimation or product-limit method, is a statistical technique used to estimate the survival probability of an individual over time. It's commonly used in medical research and epidemiology to analyze the survival rates of patients with different treatments, diseases, or risk factors.
 What does it do? 
The Survival Estimation function takes into account censored observations (i.e., individuals who are still alive at a certain point) and calculates the probability that an individual will survive beyond a specific time period. It's particularly useful when dealing with right-censoring, where some subjects are lost to follow-up or have not experienced the event of interest by the end of the study.
 Interpretation 
The Survival Estimation function provides a plot of the estimated survival probability over time, which can be used to:
1. Compare survival rates between different groups (e.g., treatment arms)
2. Identify patterns in the data that may indicate differences in mortality or disease progression
3. Make predictions about future outcomes based on historical data
4. In a trading context it may be used to ascertain the survival ratios of trading under specific conditions.
 Reference: 
www.global-developments.org
"Beyond GDP" ~ www.aeaweb.org
en.wikipedia.org
www.kdnuggets.com
 survival_probability(alive_at_age, initial_alive) 
  Kaplan-Meier Survival Estimator.
  Parameters:
     alive_at_age (int) : The number of subjects still alive at a age.
     initial_alive (int) : The Total number of initial subjects.
  Returns: The probability that a subject lives longer than a certain age.
 utility(c, l) 
  Captures the utility value from consumption and leisure.
  Parameters:
     c (float) : Consumption.
     l (float) : Leisure.
  Returns: Utility value from consumption and leisure.
 welfare_utility(age, b, u, s) 
  Calculate the welfare utility value based age, basic needs and social interaction.
  Parameters:
     age (int) : Age of the subject.
     b (float) : Value representing basic needs (food, shelter..).
     u (float) : Value representing overall well-being and happiness.
     s (float) : Value representing social interaction and connection with others.
  Returns: Welfare utility value.
 expected_lifetime_welfare(beta, consumption, leisure, alive_data, expectation) 
  Calculates the expected lifetime welfare of an individual based on their consumption, leisure, and survival probability over time.
  Parameters:
     beta (float) : Discount factor.
     consumption (array) : List of consumption values at each step of the subjects life.
     leisure (array) : List of leisure values at each step of the subjects life.
     alive_data (array) : List of subjects alive at each age, the first element is the total or initial number of subjects.
     expectation (float) : Optional, `defaut=1.0`. Expectation or weight given to this calculation.
  Returns: Expected lifetime welfare value.
NR_VersatilitiesLibrary   "NR_Versatilities" 
Versatilities (aka, Versatile Utilities) includes:
- Seventeen Price Variants returned as a tuple,
- Eight Smoothing functions rolled into one,
- Pick any Past Value from any series with offset,
- Or just the previous value from any series.
 pastVal(src, len) 
  Fetches past value from src that came len distance ago
  Parameters:
     src (float) : source series
     len (int) : lookback distance - (optional) default is 1
  Returns: latest src if len <= 0, else src 
 previous(src) 
  Fetches past value from src that came len distance ago
  Parameters:
     src (float) : source series
  Returns: previous value in the series if found, else current value
 price_variants() 
  Computes Several different averages using current and previous OHLC values
  Returns: Seventeen Uncommon Average Price Combinations
 dynamic_MA(matyp, masrc, malen, lsmaoff, almasgm, almaoff, almaflr) 
  Dynamically computes Eight different MAs on-demand individually, or an average of all taken together
  Parameters:
     matyp (string) : pick one of these MAs - ALMA, EMA, HMA, LSMA, RMA, SMA, SWMA, WMA, ALL  
     masrc (float) : source series to compute MA
     malen (simple int) : lookback distance for MA
     lsmaoff (simple int) : optional LSMA offset - default is 0
     almasgm (simple float) : optional ALMA sigma - default is 5
     almaoff (simple float) : optional ALMA offset - default is 0.5
     almaflr (simple bool) : optional ALMA floor flag - default is false
  Returns: MA series for chosen type or, an average of all of them, if chosen so
HarmonicMapLibLibrary   "HarmonicMapLib" 
Harmonic Pattern Library implementation utilising maps
 method tostring(this) 
  convert Range value to string
  Namespace types: Range
  Parameters:
     this (Range) : Range value
  Returns: converted string representation
 method tostring(this) 
  convert array of Range value to string
  Namespace types: array
  Parameters:
     this (array) : array object
  Returns: converted string representation
 method tostring(this) 
  convert map of string to Range value to string
  Namespace types: map
  Parameters:
     this (map) : map object
  Returns: converted string representation
 method tostring(this) 
  convert RatioMap to string
  Namespace types: RatioMap
  Parameters:
     this (RatioMap) : RatioMap object
  Returns: converted string representation
 method tostring(this) 
  convert array of RatioMap to string
  Namespace types: array
  Parameters:
     this (array) : array object
  Returns: converted string representation
 method tostring(this) 
  convert map of string to RatioMap to string
  Namespace types: map
  Parameters:
     this (map) : map object
  Returns: converted string representation
 method tostring(this) 
  convert map of string to bool to string
  Namespace types: map
  Parameters:
     this (map) : map object
  Returns: converted string representation
 method tostring(this) 
  convert PrzRange to string
  Namespace types: PrzRange
  Parameters:
     this (PrzRange) : PrzRange object
  Returns: converted string representation
 method tostring(this) 
  convert array of PrzRange to string
  Namespace types: array
  Parameters:
     this (array) : array object
  Returns: converted string representation
 getHarmonicMap() 
  Creates the RatioMap for harmonic patterns
  Returns: map haronic ratio rules for all patterns
 method evaluate(patternsMap, pattern, ratioRange, properties, ratioValue) 
  evaluates harmonic ratio range
  Namespace types: map
  Parameters:
     patternsMap (map) : parameter containing valid pattern names
     pattern (string) : Pattern type to be evaluated
     ratioRange (Range) : ratio range to be checked
     properties (ScanProperties) : Scan Properties
     ratioValue (float) 
  Returns: void
 method evaluate(przRange, pattern, ratioRange, priceRange, properties) 
  Evaluate PRZ ranges
  Namespace types: map
  Parameters:
     przRange (map) 
     pattern (string) : Pattern name
     ratioRange (Range) : Range of ratio for the pattern
     priceRange (Range) : Price range based on ratio
     properties (ScanProperties) : ScanProperties object
  Returns: void
 method scanRatio(currentPatterns, rules, properties, ratioName, ratioValue) 
  Scan for particular named ratio of harmonic pattern to filter valid patterns
  Namespace types: map
  Parameters:
     currentPatterns (map) : Current valid patterns map
     rules (map) : map Harmonic ratio rules
     properties (ScanProperties) : ScanProperties object
     ratioName (string) : Specific ratio name
     ratioValue (float) : ratio value to be checked
  Returns: updated currentPatterns object
 method scanPatterns(patterns, x, a, b, c, d, properties) 
  Scan for patterns based on X, A, B, C, D values
  Namespace types: map
  Parameters:
     patterns (map) : List of allowed patterns
     x (float) : X coordinate
     a (float) : A coordinate
     b (float) : B coordinate
     c (float) : C coordinate
     d (float) : D coordinate
     properties (ScanProperties) : ScanProperties object. If na, default values are initialised
  Returns: updated valid patterns map
 method scanProjections(patterns, x, a, b, c, properties) 
  Scan for projections based on X, A, B, C values
  Namespace types: map
  Parameters:
     patterns (map) : List of allowed patterns
     x (float) : X coordinate
     a (float) : A coordinate
     b (float) : B coordinate
     c (float) : C coordinate
     properties (ScanProperties) : ScanProperties object. If na, default values are initialised
  Returns: updated valid projections map
 method merge(this, other) 
  merge two ranges into one
  Namespace types: Range
  Parameters:
     this (Range) : first range
     other (Range) : second range
  Returns: combined range
 method union(this, other) 
  union of two ranges into one
  Namespace types: Range
  Parameters:
     this (Range) : first range
     other (Range) : second range
  Returns: union range
 method overlaps(this, other) 
  checks if two ranges intersect
  Namespace types: Range
  Parameters:
     this (Range) : first range
     other (Range) : second range
  Returns: true if intersects, false otherwise
 method consolidate(this) 
  Consolidate ranges into PRZ
  Namespace types: map
  Parameters:
     this (map) : map of Ranges
  Returns: consolidated PRZ
 method consolidateMany(this) 
  Consolidate ranges into multiple PRZ ranges
  Namespace types: map
  Parameters:
     this (map) : map of Ranges
  Returns: consolidated array of PRZ ranges
 method getRange(currentPatterns, x, a, b, c, properties) 
  Get D range based on X, A, B, C coordinates for the current patterns
  Namespace types: map
  Parameters:
     currentPatterns (map) : List of valid patterns
     x (float) : X coordinate
     a (float) : A coordinate
     b (float) : B coordinate
     c (float) : C coordinate
     properties (ScanProperties) : ScanProperties object. If na, default values are initialised
  Returns: map of D ranges
 method getPrzRange(currentPatterns, x, a, b, c, properties) 
  Get PRZ range based on X, A, B, C coordinates for the current patterns
  Namespace types: map
  Parameters:
     currentPatterns (map) : List of valid patterns
     x (float) : X coordinate
     a (float) : A coordinate
     b (float) : B coordinate
     c (float) : C coordinate
     properties (ScanProperties) : ScanProperties object. If na, default values are initialised
  Returns: PRZRange for the pattern
 method getProjectionRanges(currentPatterns, x, a, b, c, properties) 
  Get projection range based on X, A, B, C coordinates for the current patterns
  Namespace types: map
  Parameters:
     currentPatterns (map) : List of valid patterns
     x (float) : X coordinate
     a (float) : A coordinate
     b (float) : B coordinate
     c (float) : C coordinate
     properties (ScanProperties) : ScanProperties object. If na, default values are initialised
  Returns: array of projection ranges
 Range 
  Collection of range values
  Fields:
     values (array) : array of float values
 RatioMap 
  ratio map for pattern
  Fields:
     ratioMap (map) : map of string to Range (array of float)
 ScanProperties 
  Pattern Scanning properties
  Fields:
     strictMode (series bool) : strict scanning mode will check for overflows
     logScale (series bool) : scan ratios in log scale
     errorMin (series float) : min error threshold
     errorMax (series float) 
     mintick (series float) : minimum tick value of price
 PrzRange 
  Potential reversal zone range
  Fields:
     patterns (array) : array of pattern names for the given XABCD combination
     prz (Range) : PRZ range
TrendLibrary   "Trend" 
 calculateSlopeTrend(source, length, thresholdMultiplier) 
  Parameters:
     source (float) 
     length (int) 
     thresholdMultiplier (float) 
 Purpose: 
The primary goal of this function is to determine the short-term trend direction of a given data series (like closing prices). It does this by calculating the slope of the data over a specified period and then comparing that slope against a dynamic threshold based on the data's recent volatility. It classifies the trend into one of three states: Upward, Downward, or Flat.
 Parameters: 
 
 `source` (Type: `series float`): This is the input data series you want to analyze. It expects a series of floating-point numbers, typically price data like `close`, `open`, `hl2` (high+low)/2, etc.
 `length` (Type: `int`): This integer defines the lookback period. The function will analyze the `source` data over the last `length` bars to calculate the slope and standard deviation.
 `thresholdMultiplier` (Type: `float`, Default: `0.1`): This is a sensitivity factor. It's multiplied by the standard deviation to determine how steep the slope needs to be before it's considered a true upward or downward trend. A smaller value makes it more sensitive (detects trends earlier, potentially more false signals), while a larger value makes it less sensitive (requires a stronger move to confirm a trend).
 
 Calculation Steps: 
 
 Linear Regression:  It first calculates the value of a linear regression line fitted to the `source` data over the specified `length` (`ta.linreg(source, length, 0)`). Linear regression finds the "best fit" straight line through the data points.
 Slope Calculation:  It then determines the slope of this linear regression line. Since `ta.linreg` gives the *value* of the line on the current bar, the slope is calculated as the difference between the current bar's linear regression value (`linRegValue`) and the previous bar's value (`linRegValue `). A positive difference means an upward slope, negative means downward.
 Volatility Measurement:  It calculates the standard deviation (`ta.stdev(source, length)`) of the `source` data over the same `length`. Standard deviation is a measure of how spread out the data is, essentially quantifying its recent volatility.
 Adaptive Threshold:  An adaptive threshold (`threshold`) is calculated by multiplying the standard deviation (`stdDev`) by the `thresholdMultiplier`. This is crucial because it means the definition of a "flat" trend adapts to the market's volatility. In volatile times, the threshold will be wider, requiring a larger slope to signal a trend. In quiet times, the threshold will be narrower.
 Trend Determination:  Finally, it compares the calculated `slope` to the adaptive `threshold`:
 
 
 If the `slope` is greater than the positive `threshold`, the trend is considered **Upward**, and the function returns `1`.
 If the `slope` is less than the negative `threshold` (`-threshold`), the trend is considered **Downward**, and the function returns `-1`.
 If the `slope` falls between `-threshold` and `+threshold` (inclusive of 0), the trend is considered **Flat**, and the function returns `0`.
 
 Return Value: 
The function returns an integer representing the determined trend direction:
 
 `1`: Upward trend
 `-1`: Downward trend
 `0`: Flat trend
 
In essence, this library function provides a way to gauge trend direction using linear regression, but with a smart filter (the adaptive threshold) to avoid classifying minor noise or low-volatility periods as significant trends.
rate_of_changeLibrary   "rate_of_change" 
// @description: Applies ROC algorithm to any pair of values.
// This library function is used to scale change of value (price, volume) to a percentage value, just as the ROC indicator would do. It is good practice to scale arbitrary ranges to set boundaries when you try to train statistical model.
 rateOfChange(value, base, hardlimit) 
  This function is a helper to scale a value change to its percentage value.
  Parameters:
     value (float) 
     base (float) 
     hardlimit (int) 
  Returns: per: A float comprised between 0 and 100
MonthlyReturnTableLibrary   "MonthlyReturnTable" 
TODO: The table displays monthly returns, profits, MDD, and number of trades.
 get_table(mode, tablePosition, precision, textSize, marginTop, marginBottom, marginLeft, marginRight, colorHead, colorBull, colorBear, colorZero) 
  : get_table
  Parameters:
     mode (string) 
     tablePosition (string) 
     precision (int) 
     textSize (int) 
     marginTop (int) 
     marginBottom (int) 
     marginLeft (int) 
     marginRight (int) 
     colorHead (color) 
     colorBull (color) 
     colorBear (color) 
     colorZero (color) 
  Returns: : null, plot perfTable
DynamicMALibrary   "DynamicMA" 
 Dynamic Moving Averages Library 
 Introduction 
The Dynamic Moving Averages Library is a specialized collection of custom built functions designed to calculate moving averages dynamically, beginning from the first available bar. Unlike standard moving averages, which rely on fixed length lookbacks, this library ensures that indicators remain fully functional from the very first data point, making it an essential tool for analysing assets with short time series or limited historical data.
This approach allows traders and developers to build robust indicators that do not require a preset amount of historical data before generating meaningful outputs. It is particularly advantageous for:
 
 Newly listed assets with minimal price history.
 High-timeframe trading, where large lookback periods can lead to delayed or missing data.
 
By eliminating the constraints of fixed lookback periods, this library enables the seamless construction of trend indicators, smoothing functions, and hybrid models that adapt instantly to market conditions.
 Comprehensive Set of Custom Moving Averages 
The library includes a wide range of custom dynamic moving averages, each designed for specific analytical use cases:
 
 SMA (Simple Moving Average) – The fundamental moving average, dynamically computed.
 EMA (Exponential Moving Average) – Adaptive smoothing for better trend tracking.
 DEMA (Double Exponential Moving Average) – Faster trend detection with reduced lag.
 TEMA (Triple Exponential Moving Average) – Even more responsive than DEMA.
 WMA (Weighted Moving Average) – Emphasizes recent price action while reducing noise.
 VWMA (Volume Weighted Moving Average) – Accounts for volume to give more weight to high-volume periods.
 HMA (Hull Moving Average) – A superior smoothing method with low lag.
 SMMA (Smoothed Moving Average) – A hybrid approach between SMA and EMA.
 LSMA (Least Squares Moving Average) – Uses linear regression for trend detection.
 RMA (Relative Moving Average) – Used in RSI-based calculations for smooth momentum readings.
 ALMA (Arnaud Legoux Moving Average) – A Gaussian-weighted MA for superior signal clarity.
 Hyperbolic MA (HyperMA) – A mathematically optimized averaging method with dynamic weighting.
 
Each function dynamically adjusts its calculation length to match the available bar count, ensuring instant functionality on all assets.
 Fully Optimized for Pine Script v6 
This library is built on Pine Script v6, ensuring compatibility with modern TradingView indicators and scripts. It includes exportable functions for seamless integration into custom indicators, making it easy to develop trend-following models, volatility filters, and adaptive risk-management systems.
 Why Use Dynamic Moving Averages? 
Traditional moving averages suffer from a common limitation: they require a fixed historical window to generate meaningful values. This poses several problems:
 
 New Assets Have No Historical Data  - If an asset has only been trading for a short period, traditional moving averages may not be able to generate valid signals.
 High Timeframes Require Massive Lookbacks  - On 1W or 1M charts, a 200-period SMA would require 200 weeks or months of data, making it unusable on newer assets.
 Delayed Signal Initialization  - Standard indicators often take dozens of bars to stabilize, reducing effectiveness when trading new trends.
 
The Dynamic Moving Averages Library eliminates these issues by ensuring that every function:
 
 Starts calculation from bar one, using available data instead of waiting for a lookback period.
 Adapts dynamically across timeframes, making it equally effective on low or high timeframes.
 Allows smoother, more responsive trend tracking, particularly useful for volatile or low-liquidity assets.
 
This flexibility makes it indispensable for custom script developers, quantitative analysts, and discretionary traders looking to build more adaptive and resilient indicators.
 Final Summary 
The Dynamic Moving Averages Library is a versatile and powerful set of functions designed to overcome the limitations of fixed-lookback indicators. By dynamically adjusting the calculation length from the first bar, this library ensures that moving averages remain fully functional across all timeframes and asset types, making it an essential tool for traders and developers alike.
With built-in adaptability, low-lag smoothing, and support for multiple moving average types, this library unlocks new possibilities for quantitative trading and strategy development - especially for assets with short price histories or those traded on higher timeframes.
 For traders looking to enhance signal reliability, minimize lag, and build adaptable trading systems, the Dynamic Moving Averages Library provides an efficient and flexible solution. 
 
 
 
 
 SMA(sourceData, maxLength) 
  Dynamic SMA
  Parameters:
     sourceData (float) 
     maxLength (int) 
 EMA(src, length) 
  Dynamic EMA
  Parameters:
     src (float) 
     length (int) 
 DEMA(src, length) 
  Dynamic DEMA
  Parameters:
     src (float) 
     length (int) 
 TEMA(src, length) 
  Dynamic TEMA
  Parameters:
     src (float) 
     length (int) 
 WMA(src, length) 
  Dynamic WMA
  Parameters:
     src (float) 
     length (int) 
 HMA(src, length) 
  Dynamic HMA
  Parameters:
     src (float) 
     length (int) 
 VWMA(src, volsrc, length) 
  Dynamic VWMA
  Parameters:
     src (float) 
     volsrc (float) 
     length (int) 
 SMMA(src, length) 
  Dynamic SMMA
  Parameters:
     src (float) 
     length (int) 
 LSMA(src, length, offset) 
  Dynamic LSMA
  Parameters:
     src (float) 
     length (int) 
     offset (int) 
 RMA(src, length) 
  Dynamic RMA
  Parameters:
     src (float) 
     length (int) 
 ALMA(src, length, offset_sigma, sigma) 
  Dynamic ALMA
  Parameters:
     src (float) 
     length (int) 
     offset_sigma (float) 
     sigma (float) 
 HyperMA(src, length) 
  Dynamic HyperbolicMA
  Parameters:
     src (float) 
     length (int) 
ValueAtTime█ OVERVIEW 
This library is a Pine Script® programming tool for accessing historical values in a time series using  UNIX timestamps . Its data structure and functions index values by time, allowing scripts to retrieve past values based on absolute timestamps or relative time offsets instead of relying on bar index offsets. 
 █ CONCEPTS 
 UNIX timestamps 
In Pine Script®, a  UNIX timestamp  is an integer representing the number of milliseconds elapsed since January 1, 1970, at 00:00:00 UTC (the  UNIX Epoch ). The timestamp is a unique,  absolute  representation of a specific point in time. Unlike a calendar date and time, a UNIX timestamp's meaning does not change relative to any  time zone . 
This library's functions process series values and corresponding UNIX timestamps in  pairs , offering a simplified way to identify values that occur at or near distinct points in time instead of on specific bars. 
 Storing and retrieving time-value pairs 
This library's `Data`  type  defines the structure for collecting time and value information in pairs.  Objects  of the `Data` type contain the following two fields:
 • `times` – An array of "int" UNIX timestamps for each recorded value.
 • `values` – An array of "float" values for each saved timestamp.
Each index in both  arrays  refers to a specific time-value pair. For instance, the `times` and `values` elements at index 0 represent the  first  saved timestamp and corresponding value. The library functions that maintain `Data` objects  queue  up to one time-value pair per bar into the object's arrays, where the saved timestamp represents the bar's  opening time . 
Because the `times` array contains a distinct UNIX timestamp for each item in the `values` array, it serves as a custom mapping for retrieving saved values. All the library functions that return information from a `Data` object use this simple two-step process to identify a value based on time:
 1. Perform a  binary search  on the `times` array to find the earliest saved timestamp closest to the specified time or offset and get the element's index.
 2. Access the element from the `values` array at the retrieved index, returning the stored value corresponding to the found timestamp. 
 Value search methods 
There are several techniques programmers can use to identify historical values from corresponding timestamps. This library's functions include three different search methods to locate and retrieve values based on absolute times or relative time offsets:
 Timestamp search  
Find the value with the earliest saved timestamp closest to a specified timestamp. 
 Millisecond offset search  
Find the value with the earliest saved timestamp closest to a specified number of milliseconds behind the current bar's opening time. This search method provides a time-based alternative to retrieving historical values at specific bar offsets. 
 Period offset search  
Locate the value with the earliest saved timestamp closest to a defined period offset behind the current bar's opening time. The function calculates the span of the offset based on a  period string . The "string" must contain one of the following unit tokens: 
 • "D" for days
 • "W" for weeks
 • "M" for months
 • "Y" for years
 • "YTD" for year-to-date, meaning the time elapsed since the beginning of the bar's opening year in the exchange time zone. 
The period string can include a multiplier prefix for all supported units except "YTD" (e.g., "2W" for two weeks). 
Note that the precise span covered by the "M", "Y", and "YTD" units varies across time. The "1M" period can cover 28, 29, 30, or 31 days, depending on the bar's opening month and year in the exchange time zone. The "1Y" period covers 365 or 366 days, depending on leap years. The "YTD" period's span changes with each new bar, because it always measures the time from the start of the current bar's opening year.  
 █ CALCULATIONS AND USE 
This library's functions offer a flexible, structured approach to retrieving historical values at or near specific timestamps, millisecond offsets, or period offsets for different analytical needs.
See below for explanations of the exported functions and how to use them. 
 Retrieving single values 
The library includes three functions that retrieve a single stored value using timestamp, millisecond offset, or period offset search methods:
 • `valueAtTime()` – Locates the saved value with the earliest timestamp closest to a specified timestamp. 
 • `valueAtTimeOffset()` – Finds the saved value with the earliest timestamp closest to the specified number of milliseconds behind the current bar's opening time. 
 • `valueAtPeriodOffset()` – Finds the saved value with the earliest timestamp closest to the period-based offset behind the current bar's opening time. 
Each function has  two overloads  for advanced and simple use cases. The first overload searches for a value in a user-specified `Data` object created by the `collectData()` function (see below). It returns a  tuple  containing the found value and the corresponding timestamp. 
The second overload maintains a `Data` object  internally  to store and retrieve values for a specified `source` series. This overload returns a tuple containing the historical `source` value, the corresponding timestamp, and the current bar's `source` value, making it helpful for comparing past and present values from requested contexts. 
 Retrieving multiple values 
The library includes the following functions to retrieve values from multiple historical points in time, facilitating calculations and comparisons with values retrieved across several intervals:
 • `getDataAtTimes()` – Locates a past `source` value for each item in a `timestamps` array. Each retrieved value's timestamp represents the earliest time closest to one of the specified timestamps. 
 • `getDataAtTimeOffsets()` – Finds a past `source` value for each item in a `timeOffsets` array. Each retrieved value's timestamp represents the earliest time closest to one of the specified millisecond offsets behind the current bar's opening time. 
 • `getDataAtPeriodOffsets()` – Finds a past value for each item in a `periods` array. Each retrieved value's timestamp represents the earliest time closest to one of the specified period offsets behind the current bar's opening time. 
Each function returns a tuple with arrays containing the found `source` values and their corresponding timestamps. In addition, the tuple includes the current `source` value and the symbol's description, which also makes these functions helpful for multi-interval comparisons using data from requested contexts. 
 Processing period inputs 
When writing scripts that retrieve historical values based on several user-specified period offsets, the most concise approach is to create a single text input that allows users to list each period, then process the "string" list into an array for use in the `getDataAtPeriodOffsets()` function. 
This library includes a `getArrayFromString()` function to provide a simple way to process strings containing comma-separated lists of periods. The function splits the specified `str` by its commas and returns an array containing every  non-empty  item in the list with surrounding whitespaces removed. View the example code to see how we use this function to process the value of a  text area input . 
 Calculating period offset times 
Because the exact amount of time covered by a specified period offset can vary, it is often helpful to verify the resulting times when using the `valueAtPeriodOffset()` or `getDataAtPeriodOffsets()` functions to ensure the calculations work as intended for your use case. 
The library's `periodToTimestamp()` function calculates an offset timestamp from a given period and reference time. With this function, programmers can verify the time offsets in a period-based data search and use the calculated offset times in additional operations. 
For periods with "D" or "W" units, the function calculates the time offset based on the absolute number of milliseconds the period covers (e.g., `86400000` for "1D"). For periods with "M", "Y", or "YTD" units, the function calculates an offset time based on the reference time's  calendar date  in the exchange time zone. 
 Collecting data 
All the `getDataAt*()` functions, and the second overloads of the `valueAt*()` functions, collect and maintain data internally, meaning scripts do not require a separate `Data` object when using them. However, the first overloads of the `valueAt*()` functions  do not  collect data, because they retrieve values from a  user-specified  `Data` object. 
For cases where a script requires a separate `Data` object for use with these overloads or other custom routines, this library exports the `collectData()` function. This function queues each bar's `source` value and opening timestamp into a `Data` object and returns the object's ID. 
This function is particularly useful when searching for values from a specific series more than once. For instance, instead of using multiple calls to the second overloads of `valueAt*()` functions with the same `source` argument, programmers can call `collectData()` to store each bar's `source` and opening timestamp, then use the returned `Data` object's ID in calls to the  first  `valueAt*()` overloads to reduce memory usage. 
The `collectData()` function and all the functions that collect data internally include two optional parameters for limiting the saved time-value pairs to a sliding window: `timeOffsetLimit` and `timeframeLimit`. When either has a non-na argument, the function restricts the collected data to the maximum number of recent bars covered by the specified millisecond- and timeframe-based intervals. 
 NOTE : All calls to the functions that collect data for a `source` series can execute up to  once  per bar or realtime tick, because each stored value requires a unique corresponding timestamp. Therefore, scripts  cannot  call these functions iteratively within a  loop . If a call to these functions executes more than once inside a loop's scope, it causes a runtime error. 
 █ EXAMPLE CODE 
The example code at the end of the script demonstrates one possible use case for this library's functions. The code retrieves historical price data at user-specified period offsets, calculates price returns for each period from the retrieved data, and then populates a  table  with the results. 
The example code's process is as follows:
  1. Input a list of periods  – The user specifies a comma-separated list of period strings in the script's "Period list" input (e.g., "1W, 1M, 3M, 1Y, YTD"). Each item in the input list represents a period offset from the latest bar's opening time. 
  2. Process the period list  – The example calls `getArrayFromString()` on the first bar to split the input list by its commas and construct an array of period strings. 
  3. Request historical data  – The code uses a call to `getDataAtPeriodOffsets()` as the `expression` argument in a  request.security()  call to retrieve the closing prices of "1D" bars for each period included in the processed `periods` array. 
  4. Display information in a table  – On the latest bar, the code uses the retrieved data to calculate price returns over each specified period, then populates a two-row table with the results. The cells for each return percentage are color-coded based on the magnitude and direction of the price change. The cells also include tooltips showing the compared daily bar's opening date in the exchange time zone. 
 █ NOTES 
 • This library's architecture relies on a  user-defined type (UDT)  for its data storage format. UDTs are blueprints from which scripts create  objects , i.e., composite structures with fields containing independent values or references of any supported type. 
 • The library functions search through a `Data` object's `times` array using the  array.binary_search_leftmost()  function, which is more efficient than looping through collected data to identify matching timestamps. Note that this built-in works only for arrays with elements sorted in  ascending order . 
 • Each function that collects data from a `source` series updates the values and times stored in a local `Data` object's arrays. If a single call to these functions were to execute in a  loop , it would store multiple values with an  identical  timestamp, which can cause erroneous search behavior. To prevent looped calls to these functions, the library uses the `checkCall()` helper function in their scopes. This function maintains a counter that increases by one each time it executes on a confirmed bar. If the count  exceeds  the total number of bars, indicating the call executes more than once in a loop, it raises a  runtime error . 
 • Typically, when requesting  higher-timeframe  data with  request.security()  while using  barmerge.lookahead_on  as the `lookahead` argument, the `expression` argument should be  offset  with the  history-referencing operator  to prevent  lookahead bias  on historical bars. However, the call in this script's example code enables lookahead without offsetting the `expression` because the script displays results only on the last historical bar and all realtime bars, where there is  no future data  to leak into the past. This call ensures the displayed results use the latest data available from the context on realtime bars.
 Look first. Then leap. 
 █ EXPORTED TYPES 
 Data 
  A structure for storing successive timestamps and corresponding values from a dataset.
  Fields:
     times (array) : An "int" array containing a UNIX timestamp for each value in the `values` array.
     values (array) : A "float" array containing values corresponding to the timestamps in the `times` array.
 █ EXPORTED FUNCTIONS 
 getArrayFromString(str) 
  Splits a "string" into an array of substrings using the comma (`,`) as the delimiter. The function trims surrounding whitespace characters from each substring, and it excludes empty substrings from the result.
  Parameters:
     str (series string) : The "string" to split into an array based on its commas.
  Returns: (array) An array of trimmed substrings from the specified `str`.
 periodToTimestamp(period, referenceTime) 
  Calculates a UNIX timestamp representing the point offset behind a reference time by the amount of time within the specified `period`.
  Parameters:
     period (series string) : The period string, which determines the time offset of the returned timestamp. The specified argument must contain a unit and an optional multiplier (e.g., "1Y", "3M", "2W", "YTD"). Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the `referenceTime` value's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
     referenceTime (series int) : The millisecond UNIX timestamp from which to calculate the offset time.
  Returns: (int) A millisecond UNIX timestamp representing the offset time point behind the `referenceTime`.
 collectData(source, timeOffsetLimit, timeframeLimit) 
  Collects `source` and `time` data successively across bars. The function stores the information within a `Data` object for use in other exported functions/methods, such as `valueAtTimeOffset()` and `valueAtPeriodOffset()`. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     source (series float) : The source series to collect. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: (Data) A `Data` object containing collected `source` values and corresponding timestamps over the allowed time range.
 method valueAtTime(data, timestamp) 
  (Overload 1 of 2) Retrieves value and time data from a `Data` object's fields at the index of the earliest timestamp closest to the specified `timestamp`. Callable as a method or a function.
  Parameters:
     data (series Data) : The `Data` object containing the collected time and value data.
     timestamp (series int) : The millisecond UNIX timestamp to search. The function returns data for the earliest saved timestamp that is closest to the value.
  Returns: ( ) A tuple containing the following data from the `Data` object:
- The stored value corresponding to the identified timestamp ("float").
- The earliest saved timestamp that is closest to the specified `timestamp` ("int").
 valueAtTime(source, timestamp, timeOffsetLimit, timeframeLimit) 
  (Overload 2 of 2) Retrieves `source` and time information for the earliest bar whose opening timestamp is closest to the specified `timestamp`. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     timestamp (series int) : The millisecond UNIX timestamp to search. The function returns data for the earliest bar whose timestamp is closest to the value.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : (simple string) Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: ( ) A tuple containing the following data:
- The `source` value corresponding to the identified timestamp ("float").
- The earliest bar's timestamp that is closest to the specified `timestamp` ("int").
- The current bar's `source` value ("float").
 method valueAtTimeOffset(data, timeOffset) 
  (Overload 1 of 2) Retrieves value and time data from a `Data` object's fields at the index of the earliest saved timestamp closest to `timeOffset` milliseconds behind the current bar's opening time. Callable as a method or a function.
  Parameters:
     data (series Data) : The `Data` object containing the collected time and value data.
     timeOffset (series int) : The millisecond offset behind the bar's opening time. The function returns data for the earliest saved timestamp that is closest to the calculated offset time.
  Returns: ( ) A tuple containing the following data from the `Data` object:
- The stored value corresponding to the identified timestamp ("float").
- The earliest saved timestamp that is closest to `timeOffset` milliseconds before the current bar's opening time ("int").
 valueAtTimeOffset(source, timeOffset, timeOffsetLimit, timeframeLimit) 
  (Overload 2 of 2) Retrieves `source` and time information for the earliest bar whose opening timestamp is closest to `timeOffset` milliseconds behind the current bar's opening time. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     timeOffset (series int) : The millisecond offset behind the bar's opening time. The function returns data for the earliest bar's timestamp that is closest to the calculated offset time.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: ( ) A tuple containing the following data:
- The `source` value corresponding to the identified timestamp ("float").
- The earliest bar's timestamp that is closest to `timeOffset` milliseconds before the current bar's opening time ("int").
- The current bar's `source` value ("float").
 method valueAtPeriodOffset(data, period) 
  (Overload 1 of 2) Retrieves value and time data from a `Data` object's fields at the index of the earliest timestamp closest to a calculated offset behind the current bar's opening time. The calculated offset represents the amount of time covered by the specified `period`. Callable as a method or a function.
  Parameters:
     data (series Data) : The `Data` object containing the collected time and value data.
     period (series string) : The period string, which determines the calculated time offset. The specified argument must contain a unit and an optional multiplier (e.g., "1Y", "3M", "2W", "YTD"). Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the current bar's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
  Returns: ( ) A tuple containing the following data from the `Data` object:
- The stored value corresponding to the identified timestamp ("float").
- The earliest saved timestamp that is closest to the calculated offset behind the bar's opening time ("int").
 valueAtPeriodOffset(source, period, timeOffsetLimit, timeframeLimit) 
  (Overload 2 of 2) Retrieves `source` and time information for the earliest bar whose opening timestamp is closest to a calculated offset behind the current bar's opening time. The calculated offset represents the amount of time covered by the specified `period`. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     period (series string) : The period string, which determines the calculated time offset. The specified argument must contain a unit and an optional multiplier (e.g., "1Y", "3M", "2W", "YTD"). Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the current bar's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: ( ) A tuple containing the following data:
- The `source` value corresponding to the identified timestamp ("float").
- The earliest bar's timestamp that is closest to the calculated offset behind the current bar's opening time ("int").
- The current bar's `source` value ("float").
 getDataAtTimes(timestamps, source, timeOffsetLimit, timeframeLimit) 
  Retrieves `source` and time information for each bar whose opening timestamp is the earliest one closest to one of the UNIX timestamps specified in the `timestamps` array. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     timestamps (array) : An array of "int" values representing UNIX timestamps. The function retrieves `source` and time data for each element in this array.
     source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: ( ) A tuple of the following data:
- An array containing a `source` value for each identified timestamp (array).
- An array containing an identified timestamp for each item in the `timestamps` array (array).
- The current bar's `source` value ("float").
- The symbol's description from `syminfo.description` ("string").
 getDataAtTimeOffsets(timeOffsets, source, timeOffsetLimit, timeframeLimit) 
  Retrieves `source` and time information for each bar whose opening timestamp is the earliest one closest to one of the time offsets specified in the `timeOffsets` array. Each offset in the array represents the absolute number of milliseconds behind the current bar's opening time. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     timeOffsets (array) : An array of "int" values representing the millisecond time offsets used in the search. The function retrieves `source` and time data for each element in this array. For example, the array ` ` specifies that the function returns data for the timestamps closest to one day and one week behind the current bar's opening time.
     source (float) : (series float) The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: ( ) A tuple of the following data:
- An array containing a `source` value for each identified timestamp (array).
- An array containing an identified timestamp for each offset specified in the `timeOffsets` array (array).
- The current bar's `source` value ("float").
- The symbol's description from `syminfo.description` ("string").
 getDataAtPeriodOffsets(periods, source, timeOffsetLimit, timeframeLimit) 
  Retrieves `source` and time information for each bar whose opening timestamp is the earliest one closest to a calculated offset behind the current bar's opening time. Each calculated offset represents the amount of time covered by a period specified in the `periods` array. Any call to this function cannot execute more than once per bar or realtime tick.
  Parameters:
     periods (array) : An array of period strings, which determines the time offsets used in the search. The function retrieves `source` and time data for each element in this array. For example, the array ` ` specifies that the function returns data for the timestamps closest to one day, week, and month behind the current bar's opening time. Each "string" in the array must contain a unit and an optional multiplier. Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the current bar's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
     source (float) : (series float) The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
     timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
     timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
  Returns: ( ) A tuple of the following data:
- An array containing a `source` value for each identified timestamp (array).
- An array containing an identified timestamp for each period specified in the `periods` array (array).
- The current bar's `source` value ("float").
- The symbol's description from `syminfo.description` ("string").
VolumeProfileLibrary   "VolumeProfile" 
Analyzes volume and price and calculates a volume profile, in particular the Point Of Control and Value Area values.
 new(rowSizeInTicks, valueAreaCoverage, startTime) 
  Constructor method that creates a new Volume Profile
  Parameters:
     rowSizeInTicks (float) : Internal row size (aka resolution) of the volume profile. Useful for most futures contracts would be '1 / syminfo.mintick'. Default '4'.
     valueAreaCoverage (int) : Percentage of total volume that is considered the Value Area. Default '70'
     startTime (int) : Start time (unix timestamp in milliseconds) of the Volume Profile. Default 'time'.
  Returns: VolumeProfile object
 method calculatePOC(vp) 
  Calculates current Point Of Control of the VP
  Namespace types: VolumeProfile
  Parameters:
     vp (VolumeProfile) 
  Returns: void
 method calculateVA(vp) 
  Calculates current Value Area High and Low of the VP
  Namespace types: VolumeProfile
  Parameters:
     vp (VolumeProfile) 
  Returns: void
 method update(vp, h, l, v, t) 
  Processes new chart data and sorts volume into rows. Then calls calculatePOC() and calculateVA() to update the VP. Parameters are usually the output of request.security_lower_tf.
  Namespace types: VolumeProfile
  Parameters:
     vp (VolumeProfile) 
     h (array) : Array of highs
     l (array) : Array of lows
     v (array) : Array of volumes
     t (array) : Array of candle times
  Returns: void
 method setSessionHigh(vp, h) 
  Sets the high of the session the VP is tracking
  Namespace types: VolumeProfile
  Parameters:
     vp (VolumeProfile) 
     h (float) 
  Returns: void
 method setSessionLow(vp, l) 
  Sets the low of the session the VP is tracking
  Namespace types: VolumeProfile
  Parameters:
     vp (VolumeProfile) 
     l (float) 
  Returns: void
 method getPOC(vp) 
  Gets the current Point Of Control
  Namespace types: VolumeProfile
  Parameters:
     vp (VolumeProfile) 
  Returns: Point Of Control (float)
 method getVAH(vp) 
  Gets the current Value Area High
  Namespace types: VolumeProfile
  Parameters:
     vp (VolumeProfile) 
  Returns: Value Area High (float)
 method getVAL(vp) 
  Gets the current Value Area Low
  Namespace types: VolumeProfile
  Parameters:
     vp (VolumeProfile) 
  Returns: Value Area Low (float)
 VolumeProfile 
  Fields:
     rowSizeInTicks (series float) 
     valueAreaCoverage (series int) 
     startTime (series int) 
     valueAreaHigh (series float) 
     pointOfControl (series float) 
     valueAreaLow (series float) 
     sessionHigh (series float) 
     sessionLow (series float) 
     volumeByRow (map) 
     totalVolume (series float) 
     pocRow (series float) 
     pocVol (series float)
KalmanfilterLibrary   "Kalmanfilter" 
A sophisticated Kalman Filter implementation for financial time series analysis
@author Rocky-Studio
@version 1.0
 initialize(initial_value, process_noise, measurement_noise) 
  Initializes Kalman Filter parameters
  Parameters:
     initial_value (float) : (float) The initial state estimate
     process_noise (float) : (float) The process noise coefficient (Q)
     measurement_noise (float) : (float) The measurement noise coefficient (R)
  Returns:   A tuple containing  
 update(prev_state, prev_covariance, measurement, process_noise, measurement_noise) 
  Update Kalman Filter state
  Parameters:
     prev_state (float) 
     prev_covariance (float) 
     measurement (float) 
     process_noise (float) 
     measurement_noise (float) 
 calculate_measurement_noise(price_series, length) 
  Adaptive measurement noise calculation
  Parameters:
     price_series (array) 
     length (int) 
 calculate_measurement_noise_simple(price_series) 
  Parameters:
     price_series (array) 
 update_trading(prev_state, prev_velocity, prev_covariance, measurement, volatility_window) 
  Enhanced trading update with velocity
  Parameters:
     prev_state (float) 
     prev_velocity (float) 
     prev_covariance (float) 
     measurement (float) 
     volatility_window (int) 
 model4_update(prev_mean, prev_speed, prev_covariance, price, process_noise, measurement_noise) 
  Kalman Filter Model 4 implementation (Benhamou 2018)
  Parameters:
     prev_mean (float) 
     prev_speed (float) 
     prev_covariance (array) 
     price (float) 
     process_noise (array) 
     measurement_noise (float) 
 model4_initialize(initial_price) 
  Initialize Model 4 parameters
  Parameters:
     initial_price (float) 
 model4_default_process_noise() 
  Create default process noise matrix for Model 4
 model4_calculate_measurement_noise(price_series, length) 
  Adaptive measurement noise calculation for Model 4
  Parameters:
     price_series (array) 
     length (int)
Request█   OVERVIEW 
This library is a tool for Pine Script™ programmers that consolidates access to a wide range of lesser-known data feeds available on TradingView, including metrics from the FRED database, FINRA short sale volume, open interest, and COT data. The functions in this library simplify requests for these data feeds, making them easier to retrieve and use in custom scripts. 
█   CONCEPTS 
 Federal Reserve Economic Data (FRED) 
 FRED  (Federal Reserve Economic Data) is a comprehensive online database curated by the Federal Reserve Bank of St. Louis. It provides free access to extensive economic and financial data from U.S. and international sources. FRED includes numerous economic indicators such as GDP, inflation, employment, and interest rates. Additionally, it provides financial market data, regional statistics, and international metrics such as exchange rates and trade balances. 
Sourced from reputable organizations, including U.S. government agencies, international institutions, and other public and private entities, FRED enables users to analyze over 825,000 time series, download their data in various formats, and integrate their information into analytical tools and programming workflows. 
On TradingView, FRED data is available from ticker identifiers with the "FRED:" prefix. Users can search for FRED symbols in the "Symbol Search" window, and Pine scripts can retrieve data for these symbols via `request.*()` function calls.
 FINRA Short Sale Volume 
FINRA (the Financial Industry Regulatory Authority) is a non-governmental organization that supervises and regulates U.S. broker-dealers and securities professionals. Its primary aim is to protect investors and ensure integrity and transparency in financial markets. 
FINRA's  Short Sale Volume data  provides detailed information about daily short-selling activity across U.S. equity markets. This data tracks the volume of short sales reported to FINRA's trade reporting facilities (TRFs), including shares sold on FINRA-regulated Alternative Trading Systems (ATSs) and over-the-counter (OTC) markets, offering transparent access to short-selling information not typically available from exchanges. This data helps market participants, researchers, and regulators monitor trends in short-selling and gain insights into bearish sentiment, hedging strategies, and potential market manipulation. Investors often use this data alongside other metrics to assess stock performance, liquidity, and overall trading activity. 
It is important to note that FINRA's Short Sale Volume data does not consolidate short sale information from public exchanges and excludes trading activity that is not publicly disseminated.
TradingView provides ticker identifiers for requesting Short Sale Volume data with the format "FINRA:_SHORT_VOLUME", where "" is a supported U.S. equities symbol (e.g., "AAPL"). 
 Open Interest (OI) 
 Open interest  is a cornerstone indicator of market activity and sentiment in derivatives markets such as options or futures. In contrast to volume, which measures the number of contracts opened or closed within a period, OI measures the number of  outstanding contracts  that are not yet settled. This distinction makes OI a more robust indicator of how money flows through derivatives, offering meaningful insights into liquidity, market interest, and trends. Many traders and investors analyze OI alongside volume and price action to gain an enhanced perspective on market dynamics and reinforce trading decisions. 
TradingView offers many ticker identifiers for requesting OI data with the format "_OI", where "" represents a derivative instrument's  ticker ID  (e.g., "COMEX:GC1!").
 Commitment of Traders (COT) 
 Commitment of Traders  data provides an informative weekly breakdown of the aggregate positions held by various market participants, including commercial hedgers, non-commercial speculators, and small traders, in the U.S. derivative markets. Tallied and managed by the  Commodity Futures Trading Commission (CFTC) , these reports provide traders and analysts with detailed insight into an asset's open interest and help them assess the actions of various market players. COT data is valuable for gaining a deeper understanding of market dynamics, sentiment, trends, and liquidity, which helps traders develop informed trading strategies.
TradingView has numerous ticker identifiers that provide access to time series containing data for various COT metrics. To learn about COT ticker IDs and how they work, see our  LibraryCOT  publication. 
█   USING THE LIBRARY 
 Common function characteristics 
 • This library's functions construct ticker IDs with valid formats based on their specified parameters, then use them as the `symbol` argument in  request.security()  to retrieve data from the specified context. 
 • Most of these functions automatically select the timeframe of a data request because the data feeds are not available for all timeframes. 
 • All the functions have  two  overloads. The first overload of each function uses values with the  "simple"  qualifier to define the requested context, meaning the context does not change after the first script execution. The second accepts  "series"  values, meaning it can request data from different contexts across executions. 
 • The `gaps` parameter in most of these functions specifies whether the returned data is `na` when a new value is unavailable for request. By default, its value is `false`, meaning the call returns the last retrieved data when no new data is available. 
 • The `repaint` parameter in applicable functions determines whether the request can fetch the latest unconfirmed values from a higher timeframe on realtime bars, which might repaint after the script restarts. If `false`, the function only returns confirmed higher-timeframe values to avoid repainting. The default value is `true`.
 `fred()` 
The `fred()` function retrieves the most recent value of a specified series from the Federal Reserve Economic Data (FRED) database. With this function, programmers can easily fetch macroeconomic indicators, such as GDP and unemployment rates, and use them directly in their scripts. 
 How it works 
The function's `fredCode` parameter accepts a "string" representing the unique identifier of a specific FRED series. Examples include "GDP" for the "Gross Domestic Product" series and "UNRATE" for the "Unemployment Rate" series. Over 825,000 codes are available. To access codes for available series, search the  FRED website .  
The function adds the "FRED:" prefix to the specified `fredCode` to construct a valid FRED ticker ID (e.g., "FRED:GDP"), which it uses in  request.security()  to retrieve the series data.
 Example Usage 
This line of code requests the latest value from the Gross Domestic Product series and assigns the returned value to a `gdpValue` variable:
 float gdpValue = fred("GDP") 
 `finraShortSaleVolume()` 
The `finraShortSaleVolume()` function retrieves  EOD  data from a FINRA  Short Sale Volume  series. Programmers can call this function to retrieve short-selling information for equities listed on supported exchanges, namely NASDAQ, NYSE, and NYSE ARCA. 
 How it works 
The `symbol` parameter determines which symbol's short sale volume information is retrieved by the function. If the value is  na , the function requests short sale volume data for the chart's symbol. The argument can be the name of the symbol from a supported exchange (e.g., "AAPL") or a ticker ID with an exchange prefix ("NASDAQ:AAPL"). If the `symbol` contains an exchange prefix, it must be one of the following: "NASDAQ", "NYSE", "AMEX", or "BATS". 
The function constructs a ticker ID in the format "FINRA:ticker_SHORT_VOLUME", where "ticker" is the symbol name  without  the exchange prefix (e.g., "AAPL"). It then uses the ticker ID in  request.security()  to retrieve the available data. 
 Example Usage 
This line of code retrieves short sale volume for the chart's symbol and assigns the result to a `shortVolume` variable:
 float shortVolume = finraShortSaleVolume(syminfo.tickerid) 
This example requests short sale volume for the "NASDAQ:AAPL" symbol, irrespective of the current chart:
 float shortVolume = finraShortSaleVolume("NASDAQ:AAPL") 
 `openInterestFutures()` and `openInterestCrypto()` 
The `openInterestFutures()` function retrieves  EOD  open interest (OI) data for futures contracts. The `openInterestCrypto()` function provides more granular OI data for cryptocurrency contracts. 
 How they work 
The `openInterestFutures()` function retrieves EOD closing OI information. Its design is focused primarily on retrieving OI data for futures, as only EOD OI data is available for these instruments. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe. 
The `openInterestCrypto()` function retrieves opening, high, low, and closing OI data for a cryptocurrency contract on a specified timeframe. Unlike `openInterest()`, this function can also retrieve granular data from intraday timeframes. 
Both functions contain a `symbol` parameter that determines the symbol for which the calls request OI data. The functions construct a valid OI ticker ID from the chosen symbol by appending "_OI" to the end (e.g., "CME:ES1!_OI"). 
The `openInterestFutures()` function requests and returns a two-element tuple containing the futures instrument's EOD closing OI and a "bool" condition indicating whether OI is rising.
The `openInterestCrypto()` function requests and returns a five-element tuple containing the cryptocurrency contract's opening, high, low, and closing OI, and a "bool" condition indicating whether OI is rising. 
 Example usage 
This code line calls `openInterest()` to retrieve EOD OI and the OI rising condition for a futures symbol on the chart, assigning the values to two variables in a tuple:
  = openInterestFutures(syminfo.tickerid) 
This line retrieves the EOD OI data for "CME:ES1!", irrespective of the current chart's symbol:
  = openInterestFutures("CME:ES1!") 
This example uses `openInterestCrypto()` to retrieve OHLC OI data and the OI rising condition for a cryptocurrency contract on the chart, sampled at the chart's timeframe. It assigns the returned values to five variables in a tuple:
  = openInterestCrypto(syminfo.tickerid, timeframe.period) 
This call retrieves OI OHLC and rising information for "BINANCE:BTCUSDT.P" on the "1D" timeframe:
  = openInterestCrypto("BINANCE:BTCUSDT.P", "1D") 
 `commitmentOfTraders()` 
The `commitmentOfTraders()` function retrieves data from the Commitment of Traders (COT) reports published by the Commodity Futures Trading Commission (CFTC). This function significantly simplifies the COT request process, making it easier for programmers to access and utilize the available data. 
 How It Works 
This function's parameters determine different parts of a valid ticker ID for retrieving COT data, offering a streamlined alternative to constructing complex COT ticker IDs manually. The `metricName`, `metricDirection`, and `includeOptions` parameters are required. They specify the name of the reported metric, the direction, and whether it includes information from options contracts. 
The function also includes several optional parameters. The `CFTCCode` parameter allows programmers to request data for a specific report code. If unspecified, the function requests data based on the chart symbol's root prefix, base currency, or quoted currency, depending on the `mode` argument. The call can specify the report type ("Legacy", "Disaggregated", or "Financial") and metric type ("All", "Old", or "Other") with the `typeCOT` and `metricType` parameters. 
Explore the  CFTC website  to find valid report codes for specific assets. To find detailed information about the metrics included in the reports and their meanings, see the  CFTC's Explanatory Notes . 
View the function's documentation below for detailed explanations of its parameters. For in-depth information about COT ticker IDs and more advanced functionality, refer to our previously published  COT library . 
 Available metrics 
Different COT report types provide  different metrics . The tables below list all available metrics for each type and their applicable directions:
 +------------------------------+------------------------+
|  Legacy (COT) Metric Names   |       Directions       |
+------------------------------+------------------------+
| Open Interest                | No direction           |
| Noncommercial Positions      | Long, Short, Spreading |
| Commercial Positions         | Long, Short            |
| Total Reportable Positions   | Long, Short            |
| Nonreportable Positions      | Long, Short            |
| Traders Total                | No direction           |
| Traders Noncommercial        | Long, Short, Spreading |
| Traders Commercial           | Long, Short            |
| Traders Total Reportable     | Long, Short            |
| Concentration Gross LT 4 TDR | Long, Short            |
| Concentration Gross LT 8 TDR | Long, Short            |
| Concentration Net LT 4 TDR   | Long, Short            |
| Concentration Net LT 8 TDR   | Long, Short            |
+------------------------------+------------------------+
+-----------------------------------+------------------------+
| Disaggregated (COT2) Metric Names |       Directions       |
+-----------------------------------+------------------------+
| Open Interest                     | No Direction           |
| Producer Merchant Positions       | Long, Short            |
| Swap Positions                    | Long, Short, Spreading |
| Managed Money Positions           | Long, Short, Spreading |
| Other Reportable Positions        | Long, Short, Spreading |
| Total Reportable Positions        | Long, Short            |
| Nonreportable Positions           | Long, Short            |
| Traders Total                     | No Direction           |
| Traders Producer Merchant         | Long, Short            |
| Traders Swap                      | Long, Short, Spreading |
| Traders Managed Money             | Long, Short, Spreading |
| Traders Other Reportable          | Long, Short, Spreading |
| Traders Total Reportable          | Long, Short            |
| Concentration Gross LE 4 TDR      | Long, Short            |
| Concentration Gross LE 8 TDR      | Long, Short            |
| Concentration Net LE 4 TDR        | Long, Short            |
| Concentration Net LE 8 TDR        | Long, Short            |
+-----------------------------------+------------------------+
+-------------------------------+------------------------+
| Financial (COT3) Metric Names |       Directions       |
+-------------------------------+------------------------+
| Open Interest                 | No Direction           |
| Dealer Positions              | Long, Short, Spreading |
| Asset Manager Positions       | Long, Short, Spreading |
| Leveraged Funds Positions     | Long, Short, Spreading |
| Other Reportable Positions    | Long, Short, Spreading |
| Total Reportable Positions    | Long, Short            |
| Nonreportable Positions       | Long, Short            |
| Traders Total                 | No Direction           |
| Traders Dealer                | Long, Short, Spreading |
| Traders Asset Manager         | Long, Short, Spreading |
| Traders Leveraged Funds       | Long, Short, Spreading |
| Traders Other Reportable      | Long, Short, Spreading |
| Traders Total Reportable      | Long, Short            |
| Concentration Gross LE 4 TDR  | Long, Short            |
| Concentration Gross LE 8 TDR  | Long, Short            |
| Concentration Net LE 4 TDR    | Long, Short            |
| Concentration Net LE 8 TDR    | Long, Short            |
+-------------------------------+------------------------+ 
 Example usage 
This code line retrieves "Noncommercial Positions (Long)" data, without options information, from the "Legacy" report for the chart symbol's root, base currency, or quote currency:
 float nonCommercialLong = commitmentOfTraders("Noncommercial Positions", "Long", false) 
This example retrieves "Managed Money Positions (Short)" data, with options included, from the "Disaggregated" report:
 float disaggregatedData = commitmentOfTraders("Managed Money Positions", "Short", true, "", "Disaggregated") 
█   NOTES 
 • This library uses  dynamic requests , allowing dynamic ("series") arguments for the parameters defining the context (ticker ID, timeframe, etc.) of a `request.*()` function call. With this feature, a single `request.*()` call instance can flexibly retrieve data from different feeds across historical executions. Additionally, scripts can use such calls in the  local scopes  of loops, conditional structures, and even exported library functions, as demonstrated in this script. All scripts coded in Pine Script™ v6 have dynamic requests enabled by default. To learn more about the behaviors and limitations of this feature, see the  Dynamic requests  section of the Pine Script™ User Manual.
 • The library's example code offers a simple demonstration of the exported functions. The script retrieves available data using the function specified by the "Series type" input. The code requests a FRED series or COT (Legacy), FINRA Short Sale Volume, or Open Interest series for the chart's symbol with specific parameters, then plots the retrieved data as a step-line with diamond markers. 
 Look first. Then leap.  
█   EXPORTED FUNCTIONS 
This library exports the following functions:
 fred(fredCode, gaps) 
  Requests a value from a specified Federal Reserve Economic Data (FRED) series. FRED is a comprehensive source that hosts numerous U.S. economic datasets. To explore available FRED datasets and codes, search for specific categories or keywords at fred.stlouisfed.org Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
     fredCode (series string) : The unique identifier of the FRED series. The function uses the value to create a valid ticker ID for retrieving FRED data in the format `"FRED:fredCode"`. For example, `"GDP"` refers to the "Gross Domestic Product" series ("FRED:GDP"), and `"GFDEBTN"` refers to the "Federal Debt: Total Public Debt" series ("FRED:GFDEBTN").
     gaps (simple bool) : Optional. If `true`, the function returns a non-na value only when a new value is available from the requested context. If `false`, the function returns the latest retrieved value when new data is unavailable. The default is `false`.
  Returns: (float) The value from the requested FRED series.
 finraShortSaleVolume(symbol, gaps, repaint) 
  Requests FINRA daily short sale volume data for a specified symbol from one of the following exchanges: NASDAQ, NYSE, NYSE ARCA. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe. Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
     symbol (series string) : The symbol for which to request short sale volume data. If the specified value contains an exchange prefix, it must be one of the following: "NASDAQ", "NYSE", "AMEX", "BATS".
     gaps (simple bool) : Optional. If `true`, the function returns a non-na value only when a new value is available from the requested context. If `false`, the function returns the latest retrieved value when new data is unavailable. The default is `false`.
     repaint (simple bool) : Optional. If `true` and the chart's timeframe is intraday, the value requested on realtime bars may change its time offset after the script restarts its executions. If `false`, the function returns the last confirmed period's values to avoid repainting. The default is `true`.
  Returns: (float) The short sale volume for the specified symbol or the chart's symbol.
 openInterestFutures(symbol, gaps, repaint) 
  Requests EOD open interest (OI) and OI rising information for a valid futures symbol. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe. Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
     symbol (series string) : The symbol for which to request open interest data.
     gaps (simple bool) : Optional. If `true`, the function returns non-na values only when new values are available from the requested context. If `false`, the function returns the latest retrieved values when new data is unavailable. The default is `false`.
     repaint (simple bool) : Optional. If `true` and the chart's timeframe is intraday, the value requested on realtime bars may change its time offset after the script restarts its executions. If `false`, the function returns the last confirmed period's values to avoid repainting. The default is `true`.
  Returns: ( ) A tuple containing the following values:
    - The closing OI value for the symbol.
    - `true` if the closing OI is above the previous period's value, `false` otherwise.
 openInterestCrypto(symbol, timeframe, gaps, repaint) 
  Requests opening, high, low, and closing open interest (OI) data and OI rising information for a valid cryptocurrency contract on a specified timeframe. Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
     symbol (series string) : The symbol for which to request open interest data.
     timeframe (series string) : The timeframe of the data request. If the timeframe is lower than the chart's timeframe, it causes a runtime error.
     gaps (simple bool) : Optional. If `true`, the function returns non-na values only when new values are available from the requested context. If `false`, the function returns the latest retrieved values when new data is unavailable. The default is `false`.
     repaint (simple bool) : Optional. If `true` and the `timeframe` represents a higher timeframe, the function returns unconfirmed values from the timeframe on realtime bars, which repaint when the script restarts its executions. If `false`, it returns only confirmed higher-timeframe values to avoid repainting. The default is `true`.
  Returns: ( ) A tuple containing the following values:
    - The opening, high, low, and closing OI values for the symbol, respectively.
    - `true` if the closing OI is above the previous period's value, `false` otherwise.
 commitmentOfTraders(metricName, metricDirection, includeOptions, CFTCCode, typeCOT, mode, metricType) 
  Requests Commitment of Traders (COT) data with specified parameters. This function provides a simplified way to access CFTC COT data available on TradingView. Calls to this function count toward a script's `request.*()` call limit. For more advanced tools and detailed information about COT data, see TradingView's  LibraryCOT  library.
  Parameters:
     metricName (series string) : One of the valid metric names listed in the library's documentation and source code.
     metricDirection (series string) : Metric direction. Possible values are: "Long", "Short", "Spreading", and "No direction". Consult the library's documentation or code to see which direction values apply to the specified metric.
     includeOptions (series bool) : If `true`, the COT symbol includes options information. Otherwise, it does not.
     CFTCCode (series string) : Optional. The CFTC code for the asset. For example, wheat futures (root "ZW") have the code "001602". If one is not specified, the function will attempt to get a valid code for the chart symbol's root, base currency, or main currency.
     typeCOT (series string) : Optional. The type of report to request. Possible values are: "Legacy", "Disaggregated", "Financial". The default is "Legacy".
     mode (series string) : Optional. Specifies the information the function extracts from a symbol. Possible modes are:
  - "Root": The function extracts the futures symbol's root prefix information (e.g., "ES" for "ESH2020").
  - "Base currency": The function extracts the first currency from a currency pair (e.g., "EUR" for "EURUSD").
  - "Currency": The function extracts the currency of the symbol's quoted values (e.g., "JPY" for "TSE:9984" or "USDJPY").
  - "Auto": The function tries the first three modes (Root -> Base currency -> Currency) until it finds a match.
  The default is "Auto". If the specified mode is not available for the symbol, it causes a runtime error.
     metricType (series string) : Optional. The metric type. Possible values are: "All", "Old", "Other". The default is "All".
  Returns: (float) The specified Commitment of Traders data series. If no data is available, it causes a runtime error.
lib_divergenceLibrary   "lib_divergence" 
offers a commonly usable function to detect divergences. This will take the default RSI or other symbols / indicators / oscillators as source data.
 divergence(osc, pivot_left_bars, pivot_right_bars, div_min_range, div_max_range, ref_low, ref_high, min_divergence_offset_fraction, min_divergence_offset_dev_len, min_divergence_offset_atr_mul) 
  Detects Divergences between Price and Oscillator action. For bullish divergences, look at trend lines between lows. For bearish divergences, look at trend lines between highs. (strong) oscillator trending, price opposing it | (medium) oscillator trending, price trend flat | (weak) price opposite trending, oscillator trend flat | (hidden) price trending, oscillator opposing it. Pivot detection is only properly done in oscillator data, reference price data is only compared at the oscillator pivot (speed optimization)
  Parameters:
     osc (float) : (series float) oscillator data (can be anything, even another instrument price)
     pivot_left_bars (simple int) : (simple int) optional number of bars left of a confirmed pivot point, confirming it is the highest/lowest in the range before and up to the pivot (default: 5)
     pivot_right_bars (simple int) : (simple int) optional number of bars right of a confirmed pivot point, confirming it is the highest/lowest in the range from and after the pivot (default: 5)
     div_min_range (simple int) : (simple int) optional minimum distance to the pivot point creating a divergence (default: 5)
     div_max_range (simple int) : (simple int) optional maximum amount of bars in a divergence (default: 50)
     ref_low (float) : (series float) optional reference range to compare the oscillator pivot points to. (default: low)
     ref_high (float) : (series float) optional reference range to compare the oscillator pivot points to. (default: high)
     min_divergence_offset_fraction (simple float) : (simple float) optional scaling factor for the offset zone (xDeviation) around the last oscillator H/L detecting following equal H/Ls (default: 0.01)
     min_divergence_offset_dev_len (simple int) : (simple int) optional lookback distance for the deviation detection for the offset zone around the last oscillator H/L detecting following equal H/Ls. Used as well for the ATR that does the equal H/L detection for the reference price. (default: 14)
     min_divergence_offset_atr_mul (simple float) : (simple float) optional scaling factor for the offset zone (xATR) around the last price H/L detecting following equal H/Ls (default: 1)
@return A tuple of deviation flags. 
QTALibrary   "QTA" 
This is simple library for basic Quantitative Technical Analysis for retail investors. One example of it being used can be seen here ().
 calculateKellyRatio(returns) 
  Parameters:
     returns (array) : An array of floats representing the returns from bets.
  Returns: The calculated Kelly Ratio, which indicates the optimal bet size based on winning and losing probabilities.
 calculateAdjustedKellyFraction(kellyRatio, riskTolerance, fedStance) 
  Parameters:
     kellyRatio (float) : The calculated Kelly Ratio.
     riskTolerance (float) : A float representing the risk tolerance level.
     fedStance (string) : A string indicating the Federal Reserve's stance ("dovish", "hawkish", or neutral).
  Returns: The adjusted Kelly Fraction, constrained within the bounds of  .
 calculateStdDev(returns) 
  Parameters:
     returns (array) : An array of floats representing the returns.
  Returns: The standard deviation of the returns, or 0 if insufficient data.
 calculateMaxDrawdown(returns) 
  Parameters:
     returns (array) : An array of floats representing the returns.
  Returns: The maximum drawdown as a percentage.
 calculateEV(avgWinReturn, winProb, avgLossReturn) 
  Parameters:
     avgWinReturn (float) : The average return from winning bets.
     winProb (float) : The probability of winning a bet.
     avgLossReturn (float) : The average return from losing bets.
  Returns: The calculated Expected Value of the bet.
 calculateTailRatio(returns) 
  Parameters:
     returns (array) : An array of floats representing the returns.
  Returns: The Tail Ratio, or na if the 5th percentile is zero to avoid division by zero.
 calculateSharpeRatio(avgReturn, riskFreeRate, stdDev) 
  Parameters:
     avgReturn (float) : The average return of the investment.
     riskFreeRate (float) : The risk-free rate of return.
     stdDev (float) : The standard deviation of the investment's returns.
  Returns: The calculated Sharpe Ratio, or na if standard deviation is zero.
 calculateDownsideDeviation(returns) 
  Parameters:
     returns (array) : An array of floats representing the returns.
  Returns: The standard deviation of the downside returns, or 0 if no downside returns exist.
 calculateSortinoRatio(avgReturn, downsideDeviation) 
  Parameters:
     avgReturn (float) : The average return of the investment.
     downsideDeviation (float) : The standard deviation of the downside returns.
  Returns: The calculated Sortino Ratio, or na if downside deviation is zero.
 calculateVaR(returns, confidenceLevel) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     confidenceLevel (float) : A float representing the confidence level (e.g., 0.95 for 95% confidence).
  Returns: The Value at Risk at the specified confidence level.
 calculateCVaR(returns, varValue) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     varValue (float) : The Value at Risk threshold.
  Returns: The average Conditional Value at Risk, or na if no returns are below the threshold.
 calculateExpectedPriceRange(currentPrice, ev, stdDev, confidenceLevel) 
  Parameters:
     currentPrice (float) : The current price of the asset.
     ev (float) : The expected value (in percentage terms).
     stdDev (float) : The standard deviation (in percentage terms).
     confidenceLevel (float) : The confidence level for the price range (e.g., 1.96 for 95% confidence).
  Returns: A tuple containing the minimum and maximum expected prices.
 calculateRollingStdDev(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling standard deviation of returns.
 calculateRollingVariance(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling variance of returns.
 calculateRollingMean(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling mean of returns.
 calculateRollingCoefficientOfVariation(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling coefficient of variation of returns.
 calculateRollingSumOfPercentReturns(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling sum of percent returns.
 calculateRollingCumulativeProduct(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling cumulative product of returns.
 calculateRollingCorrelation(priceReturns, volumeReturns, window) 
  Parameters:
     priceReturns (array) : An array of floats representing the price returns.
     volumeReturns (array) : An array of floats representing the volume returns.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling correlation.
 calculateRollingPercentile(returns, window, percentile) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
     percentile (int) : An integer representing the desired percentile (0-100).
  Returns: An array of floats representing the rolling percentile of returns.
 calculateRollingMaxMinPercentReturns(returns, window) 
  Parameters:
     returns (array) : An array of floats representing the returns.
     window (int) : An integer representing the rolling window size.
  Returns: A tuple containing two arrays: rolling max and rolling min percent returns.
 calculateRollingPriceToVolumeRatio(price, volData, window) 
  Parameters:
     price (array) : An array of floats representing the price data.
     volData (array) : An array of floats representing the volume data.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the rolling price-to-volume ratio.
 determineMarketRegime(priceChanges) 
  Parameters:
     priceChanges (array) : An array of floats representing the price changes.
  Returns: A string indicating the market regime ("Bull", "Bear", or "Neutral").
 determineVolatilityRegime(price, window) 
  Parameters:
     price (array) : An array of floats representing the price data.
     window (int) : An integer representing the rolling window size.
  Returns: An array of floats representing the calculated volatility.
 classifyVolatilityRegime(volatility) 
  Parameters:
     volatility (array) : An array of floats representing the calculated volatility.
  Returns: A string indicating the volatility regime ("Low" or "High").
 method percentPositive(thisArray) 
  Returns the percentage of positive non-na values in this array.
This method calculates the percentage of positive values in the provided array, ignoring NA values.
  Namespace types: array
  Parameters:
     thisArray (array) 
 _candleRange() 
 _PreviousCandleRange(barsback) 
  Parameters:
     barsback (int) : An integer representing how far back you want to get a range
 redCandle() 
 greenCandle() 
 _WhiteBody() 
 _BlackBody() 
 HighOpenDiff() 
 OpenLowDiff() 
 _isCloseAbovePreviousOpen(length) 
  Parameters:
     length (int) 
 _isCloseBelowPrevious() 
 _isOpenGreaterThanPrevious() 
 _isOpenLessThanPrevious() 
 BodyHigh() 
 BodyLow() 
 _candleBody() 
 _BodyAvg(length) 
  _BodyAvg function.
  Parameters:
     length (simple int) : Required (recommended is 6).
 _SmallBody(length) 
  Parameters:
     length (simple int) : Length of the slow EMA
  Returns: a series of bools, after checking if the candle body was less than body average.
 _LongBody(length) 
  Parameters:
     length (simple int) 
 bearWick() 
  bearWick() function.
  Returns: a SERIES of FLOATS, checks if it's a blackBody(open > close), if it is, than check the difference between the high and open, else checks the difference between high and close.
 bullWick() 
 barlength() 
 sumbarlength() 
 sumbull() 
 sumbear() 
 bull_vol() 
 bear_vol() 
 volumeFightMA() 
 volumeFightDelta() 
 weightedAVG_BullVolume() 
 weightedAVG_BearVolume() 
 VolumeFightDiff() 
 VolumeFightFlatFilter() 
 avg_bull_vol(userMA) 
  avg_bull_vol(int) function.
  Parameters:
     userMA (int) 
 avg_bear_vol(userMA) 
  avg_bear_vol(int) function.
  Parameters:
     userMA (int) 
 diff_vol(userMA) 
  diff_vol(int) function.
  Parameters:
     userMA (int) 
 vol_flat(userMA) 
  vol_flat(int) function.
  Parameters:
     userMA (int) 
 _isEngulfingBullish() 
 _isEngulfingBearish() 
 dojiup() 
 dojidown() 
 EveningStar() 
 MorningStar() 
 ShootingStar() 
 Hammer() 
 InvertedHammer() 
 BearishHarami() 
 BullishHarami() 
 BullishBelt() 
 BullishKicker() 
 BearishKicker() 
 HangingMan() 
 DarkCloudCover()
CandleCandle: A Comprehensive Pine Script™ Library for Candlestick Analysis 
 Overview 
The Candle library, developed in Pine Script™, provides traders and developers with a robust toolkit for analyzing candlestick data. By offering easy access to fundamental candlestick components like open, high, low, and close prices, along with advanced derived metrics such as body-to-wick ratios, percentage calculations, and volatility analysis, this library enables detailed insights into market behavior.
This library is ideal for creating custom indicators, trading strategies, and backtesting frameworks, making it a powerful resource for any Pine Script™ developer.
 Key Features 
 1. Core Candlestick Data 
 •    Open : Access the opening price of the current candle.
 •    High : Retrieve the highest price.
 •    Low : Retrieve the lowest price.
 •    Close : Access the closing price.
 2. Candle Metrics 
 •    Full Size : Calculates the total range of the candle (high - low).
 •    Body Size : Computes the size of the candle’s body (open - close).
 •    Wick Size : Provides the combined size of the upper and lower wicks.
 3. Wick and Body Ratios 
 •    Upper Wick Size  and  Lower Wick Size .
 •    Body-to-Wick Ratio  and  Wick-to-Body Ratio .
 4. Percentage Calculations 
 •    Upper Wick Percentage : The proportion of the upper wick size relative to the full candle size.
 •    Lower Wick Percentage : The proportion of the lower wick size relative to the full candle size.
 •    Body Percentage  and  Wick Percentage  relative to the candle’s range.
 5. Candle Direction Analysis 
 •   Determines if a candle is "Bullish" or "Bearish" based on its closing and opening prices.
 6. Price Metrics 
 •    Average Price : The mean of the open, high, low, and close prices.
 •    Midpoint Price : The midpoint between the high and low prices.
 7. Volatility Measurement 
 •   Calculates the standard deviation of the OHLC prices, providing a volatility metric for the current candle.
 Code Architecture 
 Example Functionality 
The library employs a modular structure, exporting various functions that can be used independently or in combination. For instance:
 
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © DevArjun
//@version=6
indicator("Candle Data", overlay = true)
import DevArjun/Candle/1 as Candle
// Body Size %
bodySize = Candle.BodySize()
// Determining the candle direction
candleDirection = Candle.CandleDirection()
// Calculating the volatility of the current candle
volatility = Candle.Volatility()
// Plotting the metrics (for demonstration)
plot(bodySize, title="Body Size", color=color.blue)
label.new(bar_index, high, candleDirection, style=label.style_circle)
 
 Scalability 
The modularity of the Candle library allows seamless integration into more extensive trading systems. Functions can be mixed and matched to suit specific analytical or strategic needs.
 Use Cases 
 Trading Strategies 
Developers can use the library to create strategies based on candle properties such as:
 •   Identifying long-bodied candles (momentum signals).
 •   Detecting wicks as potential reversal zones.
 •   Filtering trades based on candle ratios.
 Visualization 
Plotting components like body size, wick size, and directional labels helps visualize market behavior and identify patterns.
 Backtesting 
By incorporating volatility and ratio metrics, traders can design and test strategies on historical data, ensuring robust performance before live trading.
 Education 
This library is a great tool for teaching candlestick analysis and how each component contributes to market behavior.
 Portfolio Highlights 
 Project Objective 
To create a Pine Script™ library that simplifies candlestick analysis by providing comprehensive metrics and insights, empowering traders and developers with advanced tools for market analysis.
 Development Challenges and Solutions 
 •    Challenge : Achieving high precision in calculating ratios and percentages.
 •    Solution : Implemented robust mathematical operations and safeguarded against division-by-zero errors.
 •    Challenge : Ensuring modularity and scalability.
 •    Solution : Designed functions as independent modules, allowing flexible integration.
 Impact 
 •    Efficiency : The library reduces the time required to calculate complex candlestick metrics.
 •    Versatility : Supports various trading styles, from scalping to swing trading.
 •    Clarity : Clean code and detailed documentation ensure usability for developers of all levels.
 Conclusion 
The Candle library exemplifies the power of Pine Script™ in simplifying and enhancing candlestick analysis. By including this project in your portfolio, you showcase your expertise in:
 •   Financial data analysis.
 •   Pine Script™ development.
 •   Creating tools that solve real-world trading challenges.
This project demonstrates both technical proficiency and a keen understanding of market analysis, making it an excellent addition to your professional portfolio.
Library   "Candle" 
A comprehensive library to access and analyze the basic components of a candlestick, including open, high, low, close prices, and various derived metrics such as full size, body size, wick sizes, ratios, percentages, and additional analysis metrics.
 Open() 
  Open
@description Returns the opening price of the current candle.
  Returns: float - The opening price of the current candle.
 High() 
  High
@description Returns the highest price of the current candle.
  Returns: float - The highest price of the current candle.
 Low() 
  Low
@description Returns the lowest price of the current candle.
  Returns: float - The lowest price of the current candle.
 Close() 
  Close
@description Returns the closing price of the current candle.
  Returns: float - The closing price of the current candle.
 FullSize() 
  FullSize
@description Returns the full size (range) of the current candle (high - low).
  Returns: float - The full size of the current candle.
 BodySize() 
  BodySize
@description Returns the body size of the current candle (open - close).
  Returns: float - The body size of the current candle.
 WickSize() 
  WickSize
@description Returns the size of the wicks of the current candle (full size - body size).
  Returns: float - The size of the wicks of the current candle.
 UpperWickSize() 
  UpperWickSize
@description Returns the size of the upper wick of the current candle.
  Returns: float - The size of the upper wick of the current candle.
 LowerWickSize() 
  LowerWickSize
@description Returns the size of the lower wick of the current candle.
  Returns: float - The size of the lower wick of the current candle.
 BodyToWickRatio() 
  BodyToWickRatio
@description Returns the ratio of the body size to the wick size of the current candle.
  Returns: float - The body to wick ratio of the current candle.
 UpperWickPercentage() 
  UpperWickPercentage
@description Returns the percentage of the upper wick size relative to the full size of the current candle.
  Returns: float - The percentage of the upper wick size relative to the full size of the current candle.
 LowerWickPercentage() 
  LowerWickPercentage
@description Returns the percentage of the lower wick size relative to the full size of the current candle.
  Returns: float - The percentage of the lower wick size relative to the full size of the current candle.
 WickToBodyRatio() 
  WickToBodyRatio
@description Returns the ratio of the wick size to the body size of the current candle.
  Returns: float - The wick to body ratio of the current candle.
 BodyPercentage() 
  BodyPercentage
@description Returns the percentage of the body size relative to the full size of the current candle.
  Returns: float - The percentage of the body size relative to the full size of the current candle.
 WickPercentage() 
  WickPercentage
@description Returns the percentage of the wick size relative to the full size of the current candle.
  Returns: float - The percentage of the wick size relative to the full size of the current candle.
 CandleDirection() 
  CandleDirection
@description Returns the direction of the current candle.
  Returns: string - "Bullish" if the candle is bullish, "Bearish" if the candle is bearish.
 AveragePrice() 
  AveragePrice
@description Returns the average price of the current candle (mean of open, high, low, and close).
  Returns: float - The average price of the current candle.
 MidpointPrice() 
  MidpointPrice
@description Returns the midpoint price of the current candle (mean of high and low).
  Returns: float - The midpoint price of the current candle.
 Volatility() 
  Volatility
@description Returns the standard deviation of the OHLC prices of the current candle.
  Returns: float - The volatility of the current candle.
DynamicPeriodPublicDynamic Period Calculation Library 
This library provides tools for adaptive period determination, useful for creating indicators or strategies that automatically adjust to market conditions.
 Overview 
The  Dynamic Period Library  calculates adaptive periods based on pivot points, enabling the creation of responsive indicators and strategies that adjust to market volatility.
 Key Features 
 
  Dynamic Periods: Computes periods using distances between pivot highs and lows.
  Customizable Parameters: Users can adjust detection settings and period constraints.
  Robust Handling: Includes fallback mechanisms for cases with insufficient pivot data.
 
 Use Cases 
 
  Adaptive Indicators: Build tools that respond to market volatility by adjusting their periods dynamically.
  Dynamic Strategies: Enhance trading strategies by integrating pivot-based period adjustments.
 
 Function: `dynamic_period` 
 Description 
Calculates a dynamic period based on the average distances between pivot highs and lows.
 Parameters 
 
  `left` (default: 5): Number of left-hand bars for pivot detection.
  `right` (default: 5): Number of right-hand bars for pivot detection.
  `numPivots` (default: 5): Minimum pivots required for calculation.
  `minPeriod` (default: 2): Minimum allowed period.
  `maxPeriod` (default: 50): Maximum allowed period.
  `defaultPeriod` (default: 14): Fallback period if no pivots are found.
 
 Returns 
A dynamic period calculated based on pivot distances, constrained by `minPeriod` and `maxPeriod`.
 Example 
 //@version=6
import CrimsonVault/DynamicPeriodPublic/1
left = input.int(5, "Left bars", minval = 1)
right = input.int(5, "Right bars", minval = 1)
numPivots = input.int(5, "Number of Pivots", minval = 2)
period = DynamicPeriodPublic.dynamic_period(left, right, numPivots)
plot(period, title = "Dynamic Period", color = color.blue) 
 Implementation Notes 
 
 Pivot Detection: Requires sufficient historical data to identify pivots accurately.
 Edge Cases: Ensures a default period is applied when pivots are insufficient.
 Constraints: Limits period values to a user-defined range for stability.
lib_kernelLibrary   "lib_kernel" 
Library   "lib_kernel" 
This is a tool / library for developers, that contains several common and adapted kernel functions as well as a kernel regression function and enum to easily select and embed a list into the settings dialog.
How to Choose and Modify Kernels in Practice
 
 Compact Support Kernels (e.g., Epanechnikov, Triangular): Use for localized smoothing and emphasizing nearby data. 
  Oscillatory Kernels (e.g., Wave, Cosine): Ideal for detecting periodic patterns or mean-reverting behavior. 
  Smooth Tapering Kernels (e.g., Gaussian, Logistic): Use for smoothing long-term trends or identifying global price behavior. 
 
 kernel_Epanechnikov(u) 
  Parameters:
     u (float) 
 kernel_Epanechnikov_alt(u, sensitivity) 
  Parameters:
     u (float) 
     sensitivity (float) 
 kernel_Triangular(u) 
  Parameters:
     u (float) 
 kernel_Triangular_alt(u, sensitivity) 
  Parameters:
     u (float) 
     sensitivity (float) 
 kernel_Rectangular(u) 
  Parameters:
     u (float) 
 kernel_Uniform(u) 
  Parameters:
     u (float) 
 kernel_Uniform_alt(u, sensitivity) 
  Parameters:
     u (float) 
     sensitivity (float) 
 kernel_Logistic(u) 
  Parameters:
     u (float) 
 kernel_Logistic_alt(u) 
  Parameters:
     u (float) 
 kernel_Logistic_alt2(u, sigmoid_steepness) 
  Parameters:
     u (float) 
     sigmoid_steepness (float) 
 kernel_Gaussian(u) 
  Parameters:
     u (float) 
 kernel_Gaussian_alt(u, sensitivity) 
  Parameters:
     u (float) 
     sensitivity (float) 
 kernel_Silverman(u) 
  Parameters:
     u (float) 
 kernel_Quartic(u) 
  Parameters:
     u (float) 
 kernel_Quartic_alt(u, sensitivity) 
  Parameters:
     u (float) 
     sensitivity (float) 
 kernel_Biweight(u) 
  Parameters:
     u (float) 
 kernel_Triweight(u) 
  Parameters:
     u (float) 
 kernel_Sinc(u) 
  Parameters:
     u (float) 
 kernel_Wave(u) 
  Parameters:
     u (float) 
 kernel_Wave_alt(u) 
  Parameters:
     u (float) 
 kernel_Cosine(u) 
  Parameters:
     u (float) 
 kernel_Cosine_alt(u, sensitivity) 
  Parameters:
     u (float) 
     sensitivity (float) 
 kernel(u, select, alt_modificator) 
  wrapper for all standard kernel functions, see enum Kernel comments and function descriptions for usage szenarios and parameters
  Parameters:
     u (float) 
     select (series Kernel) 
     alt_modificator (float) 
 kernel_regression(src, bandwidth, kernel, exponential_distance, alt_modificator) 
  wrapper for kernel regression with all standard kernel functions, see enum Kernel comments for usage szenarios. performance optimized version using fixed bandwidth and target
  Parameters:
     src (float) : input data series
     bandwidth (simple int) : sample window of nearest neighbours for the kernel to process
     kernel (simple Kernel) : type of Kernel to use for processing, see Kernel enum or respective functions for more details
     exponential_distance (simple bool) : if true this puts more emphasis on local / more recent values
     alt_modificator (float) : see kernel functions for parameter descriptions. Mostly used to pronounce emphasis on local values or introduce a decay/dampening to the kernel output






















