TAUtilityLib

Technical Analysis Utility Library - Collection of functions for market analysis, smoothing, scaling, and structure detection
log_snapshot(label1, val1, label2, val2, label3, val3, label4, val4, label5, val5)
Creates formatted log snapshot with 5 labeled values
Parameters:
label1 (string)
val1 (float)
label2 (string)
val2 (float)
label3 (string)
val3 (float)
label4 (string)
val4 (float)
label5 (string)
val5 (float)
Returns: void (logs to console)
f_get_next_tf(tf, steps)
Gets next higher timeframe(s) from current
Parameters:
tf (string): Current timeframe string
steps (string): "1 TF Higher" for next TF, any other value for 2 TFs higher
Returns: Next timeframe string or na if at maximum
f_get_prev_tf(tf)
Gets previous lower timeframe from current
Parameters:
tf (string): Current timeframe string
Returns: Previous timeframe string or na if at minimum
supersmoother(_src, _length)
Ehler's SuperSmoother - low-lag smoothing filter
Parameters:
_src (float): Source series to smooth
_length (simple int): Smoothing period
Returns: Smoothed series
butter_smooth(src, len)
Butterworth filter for ultra-smooth price filtering
Parameters:
src (float): Source series
len (simple int): Filter period
Returns: Butterworth smoothed series
f_dynamic_ema(source, dynamic_length)
Dynamic EMA with variable length
Parameters:
source (float): Source series
dynamic_length (float): Dynamic period (can vary bar to bar)
Returns: Dynamically adjusted EMA
dema(source, length)
Double Exponential Moving Average (DEMA)
Parameters:
source (float): Source series
length (simple int): Period for DEMA calculation
Returns: DEMA value
f_scale_percentile(primary_line, secondary_line, x)
Scales secondary line to match primary line using percentile ranges
Parameters:
primary_line (float): Reference series for target scale
secondary_line (float): Series to be scaled
x (int): Lookback bars for percentile calculation
Returns: Scaled version of secondary_line
calculate_correlation_scaling(demamom_range, demamom_min, correlation_range, correlation_min)
Calculates scaling factors for correlation alignment
Parameters:
demamom_range (float): Range of primary series
demamom_min (float): Minimum of primary series
correlation_range (float): Range of secondary series
correlation_min (float): Minimum of secondary series
Returns: [scale_factor, offset] tuple for alignment
getBB(src, length, mult, chartlevel)
Calculates Bollinger Bands with chart level offset
Parameters:
src (float): Source series
length (simple int): MA period
mult (simple float): Standard deviation multiplier
chartlevel (simple float): Vertical offset for plotting
Returns: [upper, lower, basis] tuple
get_mrc(source, length, mult, mult2, gradsize)
Mean Reversion Channel with multiple bands and conditions
Parameters:
source (float): Price source
length (simple int): Channel period
mult (simple float): First band multiplier
mult2 (simple float): Second band multiplier
gradsize (simple float): Gradient size for zone detection
Returns: [meanline, meanrange, upband1, loband1, upband2, loband2, condition]
analyzeMarketStructure(highFractalBars, highFractalPrices, lowFractalBars, lowFractalPrices, trendDirection)
Analyzes market structure for ChoCH and BOS patterns
Parameters:
highFractalBars (array<int>): Array of high fractal bar indices
highFractalPrices (array<float>): Array of high fractal prices
lowFractalBars (array<int>): Array of low fractal bar indices
lowFractalPrices (array<float>): Array of low fractal prices
trendDirection (int): Current trend (1=up, -1=down, 0=neutral)
Returns: [choch, bos, newTrend] - change signals and new trend direction
Added:
f_safeArrayGet(arr, index)
Safe array access that prevents out-of-bounds errors
Parameters:
arr (array<float>): The array to access (float array)
index (int): The index to access (can be negative or exceed array size)
Returns: The value at the safe index, or 0.0 if array is empty
f_safeArrayGetInt(arr, index)
Safe array access for integer arrays
Parameters:
arr (array<int>): The array to access (int array)
index (int): The index to access
Returns: The value at the safe index, or 0 if array is empty
f_safeArrayGetBool(arr, index)
Safe array access for boolean arrays
Parameters:
arr (array<bool>): The array to access (bool array)
index (int): The index to access
Returns: The value at the safe index, or false if array is empty
f_safeArrayGetString(arr, index)
Safe array access for string arrays
Parameters:
arr (array<string>): The array to access (string array)
index (int): The index to access
Returns: The value at the safe index, or empty string if array is empty
Updated:
f_scale_percentile(primary_line, secondary_line, lookback, percentile)
Scales secondary line to match primary line using percentile ranges
Parameters:
primary_line (float): Reference series for target scale
secondary_line (float): Series to be scaled
lookback (int): Lookback bars for percentile calculation
percentile (simple float)
Returns: Scaled version of secondary_line
Removed:
calculate_correlation_scaling(demamom_range, demamom_min, correlation_range, correlation_min)
Calculates scaling factors for correlation alignment
Updated:
f_scale_percentile(primary_line, secondary_line, lookback, percentile, chart_level)
Scales secondary line to match primary line using percentile ranges
Parameters:
primary_line (float): Reference series for target scale
secondary_line (float): Series to be scaled
lookback (int): Lookback bars for percentile calculation
percentile (simple float)
chart_level (float)
Returns: Scaled version of secondary_line, with chart vertical offset
Added:
getfractalSweepRange(fractalBar, fractalPrice, isFractalHigh, prevFractalBar, prevFractalWasHigh)
Enhanced function to get the true sweep range for fractals
Parameters:
fractalBar (int): Bar index of the current fractal
fractalPrice (float): Price of the current fractal (high for bearish, low for bullish)
isFractalHigh (bool): True if current fractal is a HIGH fractal, false for LOW
prevFractalBar (int): Bar index of the previous fractal
prevFractalWasHigh (bool): True if previous fractal was a HIGH fractal
Returns: [rangeHigh, rangeLow] tuple representing sweep range boundaries
Added:
scale_for_subchart(primary_line, secondary_line, lookback, percentile, chart_level, offset_value, offset_is_percent)
Scales and offsets a series for subchart plotting using existing f_scale_percentile
Parameters:
primary_line (float): Reference series for scaling
secondary_line (float): Series to be scaled
lookback (int): Lookback period for percentile
percentile (simple float): Percentile value (e.g., 8 for 8th/92nd)
chart_level (float): Base chart level offset
offset_value (float): Additional offset from chart level
offset_is_percent (bool): If true, offset_value is % of primary range
Returns: Scaled and offset series ready for plotting
check_pivot_crossings(pivot_bars, pivot_prices, pivot_strengths, current_bar, current_price, is_high, max_age, max_touches)
Checks if price crosses through correlation/pivot lines and counts touches
Parameters:
pivot_bars (array<int>): Array of pivot bar indices
pivot_prices (array<float>): Array of pivot prices
pivot_strengths (array<float>): Array of pivot strengths/scores
current_bar (int): Current bar index being checked
current_price (float): Current price level
is_high (bool): True if checking high pivots, false for lows
max_age (int): Maximum age of pivots to check
max_touches (int): Maximum touches before pivot expires
Returns: [bullish_score, bearish_score, touch_count, touched_pivots_string, crossed_price]
create_tooltip(title, title_icon, section_titles, section_icons, param_names, param_values, param_icons, use_dividers)
Universal tooltip builder that formats structured data into tooltip text
Parameters:
title (string): Main tooltip title
title_icon (string): Unicode icon for the main title
section_titles (array<string>): Array of section titles
section_icons (array<string>): Array of section unicode icons
param_names (array<string>): Array of parameter names (use "|" to separate sections)
param_values (array<float>): Array of parameter values (parallel to param_names)
param_icons (array<string>): Array of parameter icons (parallel to param_names)
use_dividers (bool): Whether to add dividers between sections
Returns: Formatted tooltip string
create_tooltip_str(title, title_icon, section_titles, section_icons, param_names, param_values, param_icons, use_dividers)
Alternative version that accepts string values instead of floats
Parameters:
title (string): Main tooltip title
title_icon (string): Unicode icon for the main title
section_titles (array<string>): Array of section titles
section_icons (array<string>): Array of section unicode icons
param_names (array<string>): Array of parameter names (use "|" to separate sections)
param_values (array<string>): Array of parameter values as strings
param_icons (array<string>): Array of parameter icons
use_dividers (bool): Whether to add dividers between sections
Returns: Formatted tooltip string
Added:
getNormalizedCoefficient(sourceValue, lookbackPeriod, percentileMargin, smoothingLength, useZScore, zScoreClamp)
Parameters:
sourceValue (float)
lookbackPeriod (int)
percentileMargin (simple float)
smoothingLength (simple int)
useZScore (bool)
zScoreClamp (float)
getNormalizedCoefficientDynamic(sourceValue, lookbackSource, percentileMargin, smoothingLength)
Parameters:
sourceValue (float)
lookbackSource (float)
percentileMargin (simple float)
smoothingLength (simple int)
Updated:
getNormalizedCoefficient(sourceValue, lookbackPeriod, percentileMargin, smoothingLength, useZScore, zScoreClamp, oneRange)
Parameters:
sourceValue (float)
lookbackPeriod (int)
percentileMargin (simple float)
smoothingLength (simple int)
useZScore (bool)
zScoreClamp (float)
oneRange (bool)
Added:
touch(value, level, toleranceAbs, tolerancePerc, useSimpleTouch, useBodyCross, useWickTouch, checkCrossing, minDistFromPrev, useATR, atrPeriod, atrMultiplier, atrNormPeriod)
Parameters:
value (float): - Primary value to check (can be close, high, low, etc.)
level (float): - Level to check against (EMA, band, any threshold)
toleranceAbs (float): - Absolute tolerance value (optional, default = 0)
tolerancePerc (float): - Percentage tolerance (as decimal, optional, default = 0)
useSimpleTouch (bool): - Enable simple distance-based touch detection (default=true)
useBodyCross (bool): - Enable candle body crossing detection (default=true)
useWickTouch (bool): - Enable candle wick touch detection (default=true)
checkCrossing (bool): - Consider values crossing the level as touching (default=true)
minDistFromPrev (float): - Minimum distance from previous touch in bars (optional, default = 0)
useATR (bool): - Use ATR to scale tolerance (default=false)
atrPeriod (simple int): - ATR period if useATR is true (default=14)
atrMultiplier (float): - Multiplier for ATR-based tolerance (default=1.0)
atrNormPeriod (int): - Period for ATR normalization (default=20)
Returns: -1 for touch from above, 1 for touch from below, 0 for no touch
Updated:
touch(level, toleranceAbs, tolerancePerc, useATR, atrPeriod, atrMultiplier, atrNormPeriod, enableBodyDetection, enableWickDetection, enableHistoricalDetection)
Parameters:
level (float): - Level to check against (EMA, band, any threshold)
toleranceAbs (float): - Absolute tolerance value (optional, default = 0)
tolerancePerc (float): - Percentage tolerance (as decimal, optional, default = 0)
useATR (bool): - Use ATR to scale tolerance (default=false)
atrPeriod (simple int): - ATR period if useATR is true (default=14)
atrMultiplier (float): - Multiplier for ATR-based tolerance (default=1.0)
atrNormPeriod (int): - Period for ATR normalization (default=20)
enableBodyDetection (bool): - Enable all body-related detections (default=true)
enableWickDetection (bool): - Enable all wick-related detections (default=true)
enableHistoricalDetection (bool): - Enable detection using previous bar data (default=true)
Returns: 0 for body cross, -1 for touch from above, 1 for touch from below, na for no touch
Added:
calculateSlopeScore(dema_momentums, lookback_bars, percentile_period, percentile_margin, tanh_strength)
Calculate percentile-based slope score with optional tanh transformation
Parameters:
dema_momentums (float): Series of DEMA momentum values
lookback_bars (int): Number of bars to look back for slope calculation
percentile_period (int): Period for percentile calculation
percentile_margin (simple float): Margin for percentile boundaries (e.g., 5 for 5th and 95th percentiles)
tanh_strength (float): Strength of tanh transformation (0 for linear, >0 for curved response)
Returns: Score between -1 and 1 based on percentile position with optional tanh emphasis
Added:
cov(x, y, length)
Calculates covariance between two series
Parameters:
x (float): First data series
y (float): Second data series
length (simple int): Lookback period
Returns: Covariance value
Added:
f_dynamic_sma(src, dynamic_len)
Dynamic SMA (series period)
Parameters:
src (float): The input series
dynamic_len (float): Series-type window length for SMA (must be >=1)
Returns: SMA with dynamic window length
f_dynamic_stdev(src, dynamic_len)
Dynamic Standard Deviation (series period)
Parameters:
src (float): The input series
dynamic_len (float): Series-type window length for StdDev (must be >=2)
Returns: Stdev with dynamic window length
Added:
f_dynamic_rma(src, dynamic_len)
Dynamic RMA (Wilder) with series length
Parameters:
src (float): Input series
dynamic_len (float): Series-type period (>=1). If <1, coerced to 1.
Returns: RMA with variable length, stable and stateful
f_dynamic_sma_fast(src, dynamic_len)
Dynamic SMA (stateful, O(1) update) with series window
Note: exact rolling SMA with variable window requires O(N) sum; this version approximates SMA by adaptive EMA with alpha=2/(L+1) when L varies smoothly.
For exact SMA, keep your f_dynamic_sma above.
Parameters:
src (float): Input series
dynamic_len (float): Series-type window length (>=1)
Returns: Adaptive-EMA SMA approximation for speed-critical paths
Added:
cov_dynamic(x, y, dynamic_length)
Dynamic Covariance with series length support
Parameters:
x (float): First data series
y (float): Second data series
dynamic_length (int): Lookback period (can be series)
Returns: Covariance value with dynamic window
Added:
trimFractalArray(arr, maxSize)
Trims a FractalData array to maximum size by removing oldest elements
Parameters:
arr (array<FractalData>): Array of FractalData to trim
maxSize (int): Maximum allowed size
Returns: void (modifies array in place)
trimCorrelationArray(arr, maxSize)
Trims a CorrelationLine array to maximum size
Parameters:
arr (array<CorrelationLine>): Array of CorrelationLine to trim
maxSize (int): Maximum allowed size
Returns: void (modifies array in place)
newFractal(bar, price, momentum, marker)
Creates a new FractalData instance
Parameters:
bar (int): Bar index
price (float): Fractal price
momentum (float): DEMA momentum value
marker (string): Divergence marker type
Returns: New FractalData instance
newCorrelationLine(bar, price, lineType)
Creates a new CorrelationLine instance
Parameters:
bar (int): Bar index
price (float): Line price
lineType (string): Type of line
Returns: New CorrelationLine instance
getMaxDistance(arr)
Gets maximum value from an array of floats (for swept distances)
Parameters:
arr (array<float>): Array of float values
Returns: Maximum value or 0.0 if empty
getMarkerType(peak, peak1, peak2, ltfPeak, ltfPeak1, ltfPeak2, entry, colorChanged, colorChanged1, earlyReversal, earlyReversal1, colorChangedCurrent, markerPrefix)
Checks marker conditions for divergence detection (parameterized)
Parameters:
peak (bool): Main peak condition
peak1 (bool): Peak condition 1 bar ago
peak2 (bool): Peak condition 2 bars ago
ltfPeak (bool): LTF peak condition
ltfPeak1 (bool): LTF peak 1 bar ago
ltfPeak2 (bool): LTF peak 2 bars ago
entry (bool): Entry signal condition
colorChanged (bool): Color changed condition
colorChanged1 (bool): Color changed 1 bar ago
earlyReversal (bool): Early reversal condition
earlyReversal1 (bool): Early reversal 1 bar ago
colorChangedCurrent (bool): Color changed on current bar
markerPrefix (string): Prefix for marker type ("bearish" or "bullish")
Returns: Marker type string
createLiquiditySweepTooltip(title, icon, barIdx, fractalID, fractalPrice, labelText, sweptCount, sweptIDsList, maxDistance, hasDivergence, divergenceType, currMom)
Creates liquidity sweep tooltip data
Parameters:
title (string): Tooltip title
icon (string): Title icon
barIdx (int): Current bar index
fractalID (int): Fractal ID
fractalPrice (float): Fractal price
labelText (string): Label text (liquidity power)
sweptCount (int): Number of fractals swept
sweptIDsList (string): String of swept IDs
maxDistance (float): Maximum sweep distance
hasDivergence (bool): Whether divergence exists
divergenceType (string): Type of divergence
currMom (float): Current momentum
Returns: Formatted tooltip string
FractalData
Fractal data structure consolidating all fractal-related arrays
Fields:
bar (series int): Bar index where fractal occurred
price (series float): Price level of the fractal
liquidated (series bool): Whether this fractal's liquidity has been swept
sweptStrength (series float): Strength/distance of the liquidity sweep
momentum (series float): DEMA momentum value at the fractal
marker (series string): Divergence marker type ("none", "bearishPeak", "bullishPeak", etc.)
CorrelationLine
Correlation line data structure
Fields:
bar (series int): Bar index where line was created
price (series float): Price level of the line
lineType (series string): Type of correlation line ("osc_bull", "osc_bear", "extreme_bull", "extreme_bear")
touchCount (series int): Number of times price has touched this line
active (series bool): Whether the line is still active for touch detection
PrevFractalState
Previous fractal tracking for divergence detection
Fields:
price (series float): Price at the fractal
demamom (series float): DEMA momentum value at the fractal
bar (series int): Bar index of the fractal
Pine Bibliothek
Ganz im Sinne von TradingView hat dieser Autor seinen/ihren Pine Code als Open-Source-Bibliothek veröffentlicht. Auf diese Weise können nun auch andere Pine-Programmierer aus unserer Community den Code verwenden. Vielen Dank an den Autor! Sie können diese Bibliothek privat oder in anderen Open-Source-Veröffentlichungen verwenden. Die Nutzung dieses Codes in einer Veröffentlichung wird in unseren Hausregeln reguliert.
Haftungsausschluss
Pine Bibliothek
Ganz im Sinne von TradingView hat dieser Autor seinen/ihren Pine Code als Open-Source-Bibliothek veröffentlicht. Auf diese Weise können nun auch andere Pine-Programmierer aus unserer Community den Code verwenden. Vielen Dank an den Autor! Sie können diese Bibliothek privat oder in anderen Open-Source-Veröffentlichungen verwenden. Die Nutzung dieses Codes in einer Veröffentlichung wird in unseren Hausregeln reguliert.