KernelFunctionLibrary "KernelFunction"
This library provides non-repainting kernel functions for Nadaraya-Watson estimator implementations. This allows for easy substition/comparison of different kernel functions for one another in indicators. Furthermore, kernels can easily be combined with other kernels to create newer, more customized kernels.
rationalQuadratic(_src)
Parameters:
_src (float)
Indicators and strategies
Metrics_IndicatorLibrary "Metrics_Indicator"
v1
table_display(option, position, metrics, assessment)
Parameters:
option (string)
position (string)
metrics (array)
assessment (string)
MyLibraryLibrary "MyLibrary"
TODO: add library description here
fun(x)
TODO: add function description here
Parameters:
x (float) : TODO: add parameter x description here
Returns: TODO: add what function returns
ShortPatternsLibLibrary "ShortPatternsLib"
checkShortPatterns(bar_number)
Parameters:
bar_number (int)
KTUtilsLibrary "KTUtils"
Utility functions for technical analysis indicators, trend detection, and volatility confirmation.
MGz(close, length)
MGz
@description Moving average smoother used for signal processing
Parameters:
close (float) : float Price input (typically close)
length (int) : int Length of smoothing period
Returns: float Smoothed value
atrConf(length)
atrConf
@description Calculates Average True Range (ATR) for volatility confirmation
Parameters:
length (simple int) : int Length for ATR calculation
Returns: float ATR value
f(input)
f
@description Simple Moving Average with fixed length
Parameters:
input (float) : float Input value
Returns: float Smoothed average
bcwSMA(s, l, m)
bcwSMA
@description Custom smoothing function with weight multiplier
Parameters:
s (float) : float Signal value
l (int) : int Length of smoothing
m (int) : int Weighting multiplier
Returns: float Smoothed output
MGxx(close, length)
MGxx
@description Custom Weighted Moving Average (WMA) variant
Parameters:
close (float) : float Price input
length (int) : int Period length
Returns: float MGxx smoothed output
_PerChange(lengthTime)
_PerChange
@description Measures percentage price change over a period and range deviation
Parameters:
lengthTime (int) : int Period for change measurement
Returns: tuple Measured change, high deviation, low deviation
dirmov(len)
dirmov
@description Calculates directional movement components
Parameters:
len (simple int) : int Lookback period
Returns: tuple Plus and Minus DI values
adx(dilen, adxlen)
adx
@description Calculates Average Directional Index (ADX)
Parameters:
dilen (simple int) : int Length for DI calculation
adxlen (simple int) : int Length for ADX smoothing
Returns: float ADX value
trChopAnalysis()
trChopAnalysis
@description Identifies chop and trend phases based on True Range Bollinger Bands
Returns: tuple TR SMA, chop state, trending state
wtiAnalysis(haclose, close, filterValue)
wtiAnalysis
@description Wave Trend Indicator (WTI) with signal crossover logic
Parameters:
haclose (float) : float Heikin-Ashi close
close (float) : float Standard close
filterValue (simple int) : int Smoothing length
Returns: tuple WTI lines and direction states
basicTrend(hahigh, halow, close, open, filterValue)
basicTrend
@description Determines trend direction based on HA high/low and close
Parameters:
hahigh (float) : float Heikin-Ashi high
halow (float) : float Heikin-Ashi low
close (float) : float Standard close
open (float) : float Standard open
filterValue (simple int) : int Smoothing period
Returns: tuple Uptrend, downtrend flags
metrics(close, filterValue)
metrics
@description Common market metrics
Parameters:
close (float) : float Price input
filterValue (int) : int RSI smoothing length
Returns: tuple VWMA, SMA10, RSI, smoothed RSI
piff(close, trend_change)
piff
@description Price-Informed Forward Forecasting (PIFF) model for trend strength
Parameters:
close (float) : float Price input
trend_change (float) : float Change in trend
Returns: tuple Percent change, flags for trend direction
getMACD()
getMACD
@description Returns MACD, signal line, and histogram
Returns: tuple MACD line, Signal line, Histogram
getStoch()
getStoch
@description Returns K and D lines of Stochastic Oscillator
Returns: tuple K and D lines
getKDJ()
getKDJ
@description KDJ momentum oscillator
Returns: tuple K, D, J, Average
getBBRatio()
getBBRatio
@description Bollinger Band Ratio (BBR) and signal flags
Returns: tuple Basis, Upper, Lower, BBR, BBR Up, BBR Down
getSupertrend()
getSupertrend
@description Supertrend values and direction flags
Returns: tuple Supertrend, Direction, Up, Down
HelperLibLibrary "HelperLib"
This library offers various functions and types based on the algorithmic
concepts as authored by ICT (x.com).
kv(key, value)
Returns a string of the key/value set, suitable for debug logging
Parameters:
key (string)
value (string)
Returns: A string formatted as "{key}: {value}"
kv(key, value)
Parameters:
key (string)
value (int)
kv(key, value)
Parameters:
key (string)
value (float)
kv(key, value)
Parameters:
key (string)
value (bool)
style_getLineStyleFromType(opt)
Returns the corresponding line style constant for the given LineStyleType
Parameters:
opt (series LineStyleType) : The selected line style type
Returns: The Pine Script line style constant
style_getTextSizeFromType(opt)
Returns the corresponding text size constant for the given TextSizeType
Parameters:
opt (series TextSizeType) : The selected text size type
Returns: The Pine Script text size constant
style_getTextHAlignFromType(t)
Returns the corresponding horizontal text align constant for the given HAlignType
Parameters:
t (series HAlignType) : The selected text align type
Returns: The Pine Script text align constant
style_getTextVAlignFromType(t)
Returns the corresponding vertical text align constant for the given VAlignType
Parameters:
t (series VAlignType) : The selected text align type
Returns: The Pine Script text align constant
format_sentimentType(sentiment, pd)
Used to produce a string with the sentiment and PD array type (e.g., "+FVG")
Parameters:
sentiment (series SentimentType) : The sentiment value (e.g., SentimentType.BULLISH)
pd (series PDArrayType) : The price data array (e.g., PDArrayType.FVG)
Returns: A formatted string with the sentiment and PD array (e.g., "+FVG")
format_timeToString(timestamp)
Formats a UNIX timestamp into a date and time string based on predefined formats
Parameters:
timestamp (int) : The UNIX timestamp to format
Returns: A formatted string as "MM-dd (E) - HH:mm"
method init(this)
Initializes the session and validates the configuration. This MUST be called immediately after creating a new instance.
Namespace types: Session
Parameters:
this (Session) : The Session object reference
Returns: The Session object (chainable) or throws a runtime error if invalid
method isActive(this, _time)
Determines if the session is active based on the current bar time
Namespace types: Session
Parameters:
this (Session) : The Session object reference
_time (int)
Returns: `true` if the session is currently active; `false` otherwise
method draw(this)
Draws the line and optional label
Namespace types: LineLabel
Parameters:
this (LineLabel) : The LineLabel object reference
Returns: The LineLabel object (chainable)
method extend(this, x)
Extends the line and label right to the specified bar index
Namespace types: LineLabel
Parameters:
this (LineLabel) : The LineLabel object reference
x (int) : The bar index to extend to
Returns: The LineLabel object (chainable)
method destroy(this)
Removes the line and label from the chart
Namespace types: LineLabel
Parameters:
this (LineLabel) : The LineLabel object reference
method group(this, label)
Creates a group label for nested debug() invocations
Namespace types: Debugger
Parameters:
this (Debugger)
label (string)
method groupEnd(this, label)
Ends the specified debug group
Namespace types: Debugger
Parameters:
this (Debugger)
label (string)
method log(this, s, arg1, arg2, arg3, arg4, arg5)
Logs the param values if debug mode is enabled
Namespace types: Debugger
Parameters:
this (Debugger)
s (string) : Title of the log message
arg1 (string)
arg2 (string)
arg3 (string)
arg4 (string)
arg5 (string)
method logIf(this, expr, s, arg1, arg2, arg3, arg4, arg5)
Same behavior as debug() except will only log if the passed expression is true
Namespace types: Debugger
Parameters:
this (Debugger)
expr (bool) : Boolean expression to determine if debug logs should be logged
s (string) : Title of the log message
arg1 (string)
arg2 (string)
arg3 (string)
arg4 (string)
arg5 (string)
isFVG(includeVI, barIdx)
Checks if the previous bars form a Fair Value Gap (FVG)
Parameters:
includeVI (bool) : If true, includes Volume Imbalance in the FVG calculation
barIdx (int) : The index of the bar to check from (default is 0 for the current bar)
Returns: A Gap object if a FVG is detected; otherwise, `na`
isVolumeImbalance(barIdx)
Checks if the previous bars form a Volume Imbalance (VI)
Parameters:
barIdx (int) : The index of the bar to check from (default is 0 for the current bar)
Returns: A Gap object if a VI is detected; otherwise, `na`
isLiquidityVoid(barIdx)
Checks if the previous bars form a Liquidity Void (LV)
Parameters:
barIdx (int) : The index of the bar to check from (default is 0 for the current bar)
Returns: A Gap object if an LV is detected; otherwise, `na`
isSwingPoint(barIdx)
Checks if the previous bars form a swing point
Parameters:
barIdx (int) : The index of the bar to check from (default is 0 for the current bar)
Returns: A SwingPoint object if a swing point is detected; otherwise, `na`
Session
Defines a trading session with a name and time range. When creating a new instance of this type, you MUST call init() immediately.
Fields:
name (series string) : A display-friendly name (e.g., "NY AM")
session (series string) : A string defining the session time range (e.g., "1300-1400")
enabled (series bool) : Optional flag for custom logic; defaults to false
start (series int) : UNIX time representing the session start (set via isActive())
end (series int) : UNIX time representing the session end (set via isActive())
_t (series int)
_start_HH (series float)
_start_mm (series float)
_end_HH (series float)
_end_mm (series float)
Gap
Represents a price inefficiency (gap) with details on sentiment and price levels
Fields:
type (series SentimentType) : The sentiment of the gap (e.g., SentimentType.BULLISH)
name (series string) : A display-friendly name (e.g., "+FVG")
startTime (series int) : UNIX time value for the gap's start
endTime (series int) : UNIX time value for the gap's end
startIndex (series int) : Bar index where the gap starts
endIndex (series int) : Bar index where the gap ends
gapLow (series float) : The lowest price level of the gap
gapHigh (series float) : The highest price level of the gap
ce (series float) : The consequent encroachment level of the gap
SwingPoint
Represents a swing point with details on type and price level
Fields:
type (series SwingPointType) : The type of swing point (e.g., SwingPointType.HIGH)
time (series int) : UNIX time value for the swing point
barIdx (series int) : Bar index where the swing point occurs
price (series float) : The price level of the swing point which is either the high or low of the middle bar
LineLabel
Combines a line and box type to produce a line with a label that is properly aligned
Fields:
x (series int) : The X-axis starting point as a bar index
y (series float) : The Y-axis starting point as the price level
color (series color) : Both the line and text color
width (series int) : Thickness of the line
label (series string) : Text to display
showLabel (series bool) : Boolean to conditionally show/hide the label (default is false)
lineStyle (series LineStyleType) : The style of the line
textSize (series TextSizeType)
_b (series box)
_l (series line)
Debugger
A debug logging utility with group support
Fields:
enabled (series bool)
_debugGroupStack (array)
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)
DisplayUtilitiesLibrary "DisplayUtilities"
Display utilities for color management and visual presentation
get_direction_color(direction, up_excessive, up_normal, neutral, down_normal, down_excessive)
Get candle color based on direction and color scheme
Parameters:
direction (int) : Direction value (-2, -1, 0, 1, 2)
up_excessive (color) : Color for +2 direction
up_normal (color) : Color for +1 direction
neutral (color) : Color for 0 direction
down_normal (color) : Color for -1 direction
down_excessive (color) : Color for -2 direction
Returns: Appropriate color for the direction
get_candle_paint_directions(paint_opt, body_dir, bar_dir, breakout_dir, combined_dir)
Get candle directions for different painting algorithms
Parameters:
paint_opt (string) : Painting option algorithm
body_dir (int) : Body direction
bar_dir (int) : Bar direction
breakout_dir (int) : Breakout direction
combined_dir (int) : Combined direction
Returns:
get_bias_paint_directions(paint_bias, unified_dir)
Get paint directions based on bias filter
Parameters:
paint_bias (string) : Paint bias option ("All", "Bull Bias", "Bear Bias")
unified_dir (int) : Unified direction
Returns: Directions for two plotcandle series
get_transparency_levels(sf_filtered, fade_option, fade_opacity)
Calculate transparency levels for strength factor filtering
Parameters:
sf_filtered (bool) : Is strength factor filtered
fade_option (string) : Fade option ("Disabled", "Fade Candle", "Do Not Fade Wick", "Do Not Fade Wick and Border")
fade_opacity (int) : Fade opacity percentage
Returns:
get_strength_factor_filter(filter_option, individual_filters)
Generate strength factor filter conditions
Parameters:
filter_option (string) : Filter option string
individual_filters (map) : Map of individual filter conditions
Returns: Boolean filter result
get_signal_bar_condition(signal_option, individual_filters)
Generate signal bar conditions (inverted filters)
Parameters:
signal_option (string) : Signal bar option string
individual_filters (map) : Map of individual filter conditions
Returns: Boolean signal bar result
get_zscore_signal_condition(z_signal_option, z_filters)
Get Z-score signal bar conditions
Parameters:
z_signal_option (string) : Z-score signal option
z_filters (map) : Map of Z-score filters
Returns: Boolean Z-score signal condition
get_standard_colors()
Create a standard color scheme for directions
Returns: Standard color set
apply_zscore_modification(original_dir, z_filtered)
Modify directions for Z-score excess display
Parameters:
original_dir (int) : Original direction
z_filtered (bool) : Is Z-score filtered (shows excess)
Returns: Modified direction (doubled if excess detected)
get_default_fade_colors()
Get default fade colors for strength factor overlay
Returns: Default colors for TV overlay
should_paint_candles(paint_algo)
Check if paint algorithm should show candles
Parameters:
paint_algo (string) : Paint algorithm option
Returns: True if algorithm should display candles
get_signal_bar_char(signal_type, is_bullish)
Get signal bar character based on signal type
Parameters:
signal_type (string) : Signal type ("strength_factor" or "zscore")
is_bullish (bool) : Direction is bullish
Returns: Character and location for plotchar
get_signal_bar_color(signal_type, is_bullish)
Get signal bar colors
Parameters:
signal_type (string) : Signal type ("strength_factor" or "zscore")
is_bullish (bool) : Direction is bullish
Returns: Signal bar color
ZScoreAnalysisLibrary "ZScoreAnalysis"
Z-score analysis for detecting statistical deviations and excess market behavior
calculate_zscore(source, lookback, threshold, switch_enabled)
Calculate Z-score and related metrics with history tracking
Parameters:
source (float) : Data source for Z-score calculation
lookback (int) : Lookback period for mean and standard deviation
threshold (float) : Z-score threshold for significance
switch_enabled (string) : Enable/disable switch ("Enabled"/"Disabled")
Returns: Z-score, historical significant values, and running average
get_zscore_threshold(opt, input_thr, avg)
Get threshold based on threshold option
Parameters:
opt (string) : Threshold option ("User Input Threshold", "Average as Threshold", or other)
input_thr (float) : User input threshold
avg (float) : Average threshold
Returns: Calculated threshold value
is_zscore_filtered(switch_enabled, zscore, threshold)
Check if a metric passes the Z-score filter
Parameters:
switch_enabled (string) : Enable/disable switch
zscore (float) : Current Z-score value
threshold (float) : Z-score threshold
Returns: True if filtered (exceeds threshold)
get_consecutive_distances(body_dir, breakout_dir, is_inside_bar)
Calculate consecutive distances for Z-score analysis
Parameters:
body_dir (int) : Body direction
breakout_dir (int) : Breakout direction
is_inside_bar (bool) : Inside bar flag
Returns:
get_trend_to_mean_distance()
Calculate distance from trend to mean for momentum analysis
Returns: Distance between trend and mean
get_all_zscores(lookback, threshold, bar_dist_switch, body_dist_switch, chl_dist_switch, cc_dist_switch, m_dist_switch, body_dir, breakout_dir, is_inside_bar)
Get all Z-score calculations for the indicator
Parameters:
lookback (int) : Z-score lookback period
threshold (float) : Z-score threshold
bar_dist_switch (string) : Enable bar distance Z-score
body_dist_switch (string) : Enable body distance Z-score
chl_dist_switch (string) : Enable consecutive highs/lows Z-score
cc_dist_switch (string) : Enable consecutive closes Z-score
m_dist_switch (string) : Enable momentum distance Z-score
body_dir (int) : Body direction
breakout_dir (int) : Breakout direction
is_inside_bar (bool) : Inside bar flag
Returns: Array of Z-score results and filters
get_combined_zscore_filters(z_filters)
Get combined Z-score filters
Parameters:
z_filters (map) : Map of individual Z-score filters
Returns: Various combinations of Z-score filters
get_basic_distances()
Calculate basic distances used in Z-score analysis
Returns: Bar range and body range
get_individual_zscore_filter(z_filters, filter_name)
Get individual Z-score filter by name
Parameters:
z_filters (map) : Map of Z-score filters
filter_name (string) : Name of the filter ("bar_dist", "body_dist", etc.)
Returns: Boolean filter result
has_any_zscore_signal(z_filters)
Check if any Z-score filter is active
Parameters:
z_filters (map) : Map of individual Z-score filters
Returns: True if any Z-score exceeds threshold
StrengthFactorsLibrary "StrengthFactors"
Strength factor calculations for various market analysis metrics
get_threshold(opt, input_val, avg_val, lineancy)
Calculate threshold based on options
Parameters:
opt (string) : Threshold option ("Disabled", "User Input Threshold", "Average as Threshold")
input_val (float) : User input threshold value
avg_val (float) : Average value for threshold
lineancy (float) : Lineancy adjustment percentage
Returns: Calculated threshold
get_percentage_of_threshold(value, threshold)
Calculate percentage of threshold
Parameters:
value (float) : Current value
threshold (float) : Threshold value
Returns: Percentage of threshold
get_distance_sf(lookback, thr_opt, thr_inp, lineancy)
Calculate Distance Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_uniformity_sf(lookback, thr_opt, thr_inp, stddev_mult, lineancy)
Calculate Uniformity Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
stddev_mult (float) : Standard deviation multiplier
lineancy (float) : Lineancy adjustment
Returns:
get_overlap_sf(lookback, thr_opt, thr_inp, lineancy)
Calculate Overlap Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_body_sf(lookback, thr_opt, thr_inp, lineancy)
Calculate Body Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_close_sf(lookback, thr_opt, thr_inp, lineancy)
Calculate Close Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_breakout_sf(lookback, thr_opt, thr_inp, lineancy, bro_dir, is_inside_bar)
Calculate Breakout Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
bro_dir (int) : Breakout direction
is_inside_bar (bool) : Is inside bar flag
Returns:
get_always_in_sf(thr_opt, thr_inp, lineancy)
Calculate Always-In Strength Factor
Parameters:
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_directional_sf(overlap_prc, distance_prc, body_prc, close_prc, breakout_prc, lookback, thr_opt, thr_inp, lineancy)
Calculate Directional Strength Factor (composite)
Parameters:
overlap_prc (float) : Overlap SF as percentage of threshold
distance_prc (float) : Distance SF as percentage of threshold
body_prc (float) : Body SF as percentage of threshold
close_prc (float) : Close SF as percentage of threshold
breakout_prc (float) : Breakout SF as percentage of threshold
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_combined_direction_sf(body_prc, close_prc, breakout_prc, lookback, thr_opt, thr_inp, lineancy)
Calculate Combined Direction Strength Factor
Parameters:
body_prc (float) : Body SF as percentage of threshold
close_prc (float) : Close SF as percentage of threshold
breakout_prc (float) : Breakout SF as percentage of threshold
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_all_strength_factors(lookback, lineancy, dist_thr_opt, dist_thr_inp, body_thr_opt, body_thr_inp, close_thr_opt, close_thr_inp, breakout_thr_opt, breakout_thr_inp, bro_dir, is_inside_bar)
Get all strength factors at once (convenience function)
Parameters:
lookback (int) : Lookback period for averages
lineancy (float) : Lineancy adjustment percentage
dist_thr_opt (string) : Distance threshold option
dist_thr_inp (float) : Distance threshold input
body_thr_opt (string) : Body threshold option
body_thr_inp (float) : Body threshold input
close_thr_opt (string) : Close threshold option
close_thr_inp (float) : Close threshold input
breakout_thr_opt (string) : Breakout threshold option
breakout_thr_inp (float) : Breakout threshold input
bro_dir (int) : Breakout direction
is_inside_bar (bool) : Is inside bar flag
Returns: Map containing all strength factor results
DirectionCalculationsLibrary "DirectionCalculations"
Direction calculation algorithms for body, bar, and breakout directions
get_body_direction()
Calculate body direction based on open vs close
Returns: Body direction: 1 (bullish), -1 (bearish), 0 (doji)
get_bar_direction()
Calculate bar direction based on close position relative to hl2
Returns: Bar direction: 1 (upper half), -1 (lower half), 0 (middle)
get_breakout_direction()
Calculate breakout direction with outside/inside bar logic
Returns:
get_combined_direction(bod_dir, bar_dir, bro_dir, bro_ob_dir)
Calculate combined direction from body and bar directions
Parameters:
bod_dir (int) : Body direction
bar_dir (int) : Bar direction
bro_dir (int) : Breakout direction
bro_ob_dir (int) : Outside bar direction
Returns: Combined direction
is_consecutive_direction(current_dir, previous_dir)
Check if directions are consecutive (no reversal)
Parameters:
current_dir (int) : Current direction
previous_dir (int) : Previous direction
Returns: True if consecutive (no reversal from +1 to -1 or -1 to +1)
get_all_directions()
Get all direction calculations at once
Returns:
get_breakout_distances()
Get distance calculations for breakout analysis
Returns: High-to-high and low-to-low distances
get_bar_patterns()
Check for specific bar patterns
Returns:
WeightedVolumeUtilsLibrary "WeightedVolumeUtils"
fun(x)
Returns the input value (placeholder function).
Parameters:
x (float) : A float value.
Returns: The same float value passed as input.
weightedBSEVolume()
Calculates the weighted volume for BSE index based on top constituent stocks.
Returns: Weighted volume value based on fixed weights for BSE SENSEX stocks.
getAdjustedVolume()
Returns the adjusted volume for SENSEX or regular volume otherwise.
Returns: Weighted BSE volume if current symbol is SENSEX, else raw volume.
PatternsLibLibrary "PatternsLib"
getPatterns()
Pattern
Fields:
id (series string)
bars (array)
highMask (series int)
lowMask (series int)
USHolidayCalendarLibrary "USHolidayCalendar"
isLeapYear(year)
Parameters:
year (int)
getDayOfWeek(y, m, d)
Parameters:
y (int)
m (int)
d (int)
getDateTimestamp(y, m, d)
Parameters:
y (int)
m (int)
d (int)
getThirdMonday(year, month)
Parameters:
year (int)
month (int)
getLastMonday(year, month)
Parameters:
year (int)
month (int)
getThanksgivingDay(year)
Parameters:
year (int)
getEasterDate(year)
Parameters:
year (int)
getGoodFridayDate(year)
Parameters:
year (int)
createHolidayTimestamps()
MathSpecialFunctionsConvolve1DLibrary "MathSpecialFunctionsConvolve1D"
Convolution is one of the most important mathematical operations used in signal processing. This simple mathematical operation pops up in many scientific and industrial applications, from its use in a billion-layer large CNN to simple image denoising.
___
Reference:
www.algorithm-archive.org
numpy.org
lloydrochester.com
www.geeksforgeeks.org
f(signal, filter)
Convolve
Parameters:
signal (array) : List with signal data.
filter (array) : List with weights to apply to the signal data.
Returns: Discrete, linear convolution of `signal` and `filter`.
BTC_News_2025Library "BTC_News_2025"
This library contains the tooltips used in the script "Bitcoin History Events (BTC Story)"
V1 News from January to May
tt_020125()
tt_070125()
tt_200125()
tt_270125()
tt_300125()
tt_030225()
tt_260225()
tt_240225()
tt_020325()
tt_030325()
tt_090325()
tt_110325()
tt_190325()
tt_280325()
tt_310325()
tt_020425()
tt_060425()
tt_090425()
tt_150425()
tt_190425()
tt_220425()
tt_050525()
tt_080525()
tt_130525()
tt_200525()
tt_220525()
ErrorFunctionsLibrary "ErrorFunctions"
A collection of functions used to approximate the area beneath a Gaussian curve.
Because an ERF (Error Function) is an integral, there is no closed-form solution to calculating the area beneath the curve. Meaning all ERFs are approximations; precisely wrong, but mostly accurate. How close you need to get to the actual area depends entirely on your use case, with more precision being less efficient.
The internal precision of floats in Pine Script is 1e-16 (16 decimals, aka. double precision). This library adapts well known algorithms designed to efficiently reach double precision. Single precision alternates are also included. All of them were made free to use, modify, and distribute by their original authors.
HASTINGS
Adaptation of a single precision ERF by Cecil Hastings Jr, published through Princeton University in 1955. It was later documented by Abramowitz and Stegun as equation 7.1.26 in their 1972 Handbook of Mathematical Functions. Fast, efficient, and ideal when precision beyond a few decimals is unnecessary.
GILES
Adaptation of a single precision Inverse ERF by Michael Giles, published through the University of Oxford in 2012. It reverses the ERF, estimating an X coordinate from an area. It too is fast, efficient, and ideal when precision beyond a few decimals is unnecessary.
LIBC
Adaptation of the double precision ERF & ERFC in the standard C library (aka. libc). It is also the same ERF & ERFC that SciPy uses. While not quite as efficient as the Hastings approximation, it's still very fast and fully maximizes Pines precision.
BOOST
Adaptation of the double precision Inverse ERF & Inverse ERFC in the Boost Math C++ library. SciPy uses these as well. These reverse the ERF & ERFC, estimating an X coordinate from an area. It too isn't quite as efficient as the Giles approximation, but still fast and fully maximizes Pines precision.
While these algorithms are not exported directly, they are available through their exported counterparts.
- - -
ERROR FUNCTIONS
erf(x, precise)
An Error Function estimates the theoretical error of a measurement.
Parameters:
x (float) : (float) Upper limit of the integration.
precise (bool) : Double precision (true) or single precision (false).
Returns: (float) Between -1 and 1.
erfc(x, precise)
A Complementary Error Function estimates the difference between a theoretical error and infinity.
Parameters:
x (float) : (float) Lower limit of the integration.
precise (bool) : Double precision (true) or single precision (false).
Returns: (float) Between 0 and 2.
erfinv(x, precise)
An Inverse Error Function reverses the erf() by estimating the original measurement from the theoretical error.
Parameters:
x (float) : (float) Theoretical error.
precise (bool) : Double precision (true) or single precision (false).
Returns: (float) Between 0 and ± infinity.
erfcinv(x, precise)
An Inverse Complementary Error Function reverses the erfc() by estimating the original measurement from the difference between the theoretical error and infinity.
Parameters:
x (float) : (float) Difference between the theoretical error and infinity.
precise (bool) : Double precision (true) or single precision (false).
Returns: (float) Between 0 and ± infinity.
- - -
DISTRIBUTION FUNCTIONS
pdf(x, m, s)
A Probability Density Function estimates the probability density . For clarity, density is not a probability .
Parameters:
x (float) : (float) X coordinate for which a density will be estimated.
m (float) : (float) Mean
s (float) : (float) Sigma
Returns: (float) Between 0 and ∞.
cdf(z, precise)
A Cumulative Distribution Function estimates the area under a Gaussian curve between negative infinity and the Z Score.
Parameters:
z (float) : (float) Z Score.
precise (bool) : Double precision (true) or single precision (false).
Returns: (float) Between 0 and 1.
cdfinv(a, precise)
An Inverse Cumulative Distribution Function reverses the cdf() by estimating the Z Score from an area.
Parameters:
a (float) : (float) Area between 0 and 1.
precise (bool) : Double precision (true) or single precision (false).
Returns: (float) Between -∞ and +∞
cdfab(z1, z2, precise)
A Cumulative Distribution Function from A to B estimates the area under a Gaussian curve between two Z Scores (A and B).
Parameters:
z1 (float) : (float) First Z Score.
z2 (float) : (float) Second Z Score.
precise (bool) : Double precision (true) or single precision (false).
Returns: (float) Between 0 and 1.
ttt(z, precise)
A Two-Tailed Test estimates the area under a Gaussian curve between symmetrical ± Z scores and ± infinity.
Parameters:
z (float) : (float) One of the symmetrical Z Scores.
precise (bool) : Double precision (true) or single precision (false).
Returns: (float) Between 0 and 1.
tttinv(a, precise)
An Inverse Two-Tailed Test reverses the ttt() by estimating the absolute Z Score from an area.
Parameters:
a (float) : (float) Area between 0 and 1.
precise (bool) : Double precision (true) or single precision (false).
Returns: (float) Between 0 and ∞.
ott(z, precise)
A One-Tailed Test estimates the area under a Gaussian curve between an absolute Z Score and infinity.
Parameters:
z (float) : (float) Z Score.
precise (bool) : Double precision (true) or single precision (false).
Returns: (float) Between 0 and 1.
ottinv(a, precise)
An Inverse One-Tailed Test Reverses the ott() by estimating the Z Score from a an area.
Parameters:
a (float) : (float) Area between 0 and 1.
precise (bool) : Double precision (true) or single precision (false).
Returns: (float) Between 0 and ∞.
OHLCVRangeXThe OHLCVRange library provides modular range-building utilities for Pine Script v6 based on custom conditions like time, price, volatility, volume, and pattern detection. Each function updates a persistent range (OHLCVRange) passed in from the calling script, based on live streaming candles.
This library is designed to support dynamic windowing over incoming OHLCV bars, with all persistent state handled externally (in the indicator or strategy). The library merely acts as a filter and updater, appending or clearing candles according to custom logic.
📦
export type OHLCVRange
OHLCV.OHLCV candles // Sliding window of candles
The OHLCVRange is a simple container holding an array of OHLCV.OHLCV structures.
This structure should be declared in the indicator using var to ensure persistence across candles.
🧩 Range Updater Functions
Each function follows this pattern:
export updateXxxRange(OHLCVRange r, OHLCV.OHLCV current, ...)
r is the range to update.
current is the latest OHLCV candle (typically from your indicator).
Additional parameters control the behavior of the range filter.
🔁 Function List
1. Fixed Lookback Range
export updateFixedRange(OHLCVRange r, OHLCV.OHLCV current, int barsBack)
Keeps only the last barsBack candles.
Sliding window based purely on number of bars.
2. Session Time Range
export updateSessionRange(OHLCVRange r, OHLCV.OHLCV current, int minuteStart, int minuteEnd)
Keeps candles within the [minuteStart, minuteEnd) intraday session.
Clears the range once out of session bounds.
3. Price Zone Range
export updatePriceZoneRange(OHLCVRange r, OHLCV.OHLCV current, float minP, float maxP)
Retains candles within the vertical price zone .
Clears when a candle exits the zone.
4. Consolidation Range
export updateConsolidationRange(OHLCVRange r, OHLCV.OHLCV current, float thresh)
Stores candles as long as the candle range (high - low) is less than or equal to thresh.
Clears on volatility breakout.
5. Volume Spike Range
export updateVolumeSpikeRange(OHLCVRange r, OHLCV.OHLCV current, float avgVol, float mult, int surround)
Triggers a new range when a volume spike ≥ avgVol * mult occurs.
Adds candles around the spike (total surround * 2 + 1).
Can be used to zoom in around anomalies.
6. Engulfing Pattern Range
export updateEngulfingRange(OHLCVRange r, OHLCV.OHLCV current, int windowAround)
Detects bullish or bearish engulfing candles.
Stores 2 * windowAround + 1 candles centered around the pattern.
Clears if no valid engulfing pattern is found.
7. HTF-Aligned Range
export updateHTFAlignedRange(OHLCVRange r, OHLCV.OHLCV current, OHLCV.OHLCV prevHtf)
Used when aligning lower timeframe candles to higher timeframe bars.
Clears and restarts the range on HTF bar transition (compare prevHtf.bar_index with current).
Requires external management of HTF candle state.
💡 Usage Notes
All OHLCVRange instances should be declared as var in the indicator to preserve state:
var OHLCVRange sessionRange = OHLCVRange.new()
sessionRange := OHLCVRange.updateSessionRange(sessionRange, current, 540, 900)
All OHLCV data should come from the OHLCVData library (v15 or later):
import userId/OHLCVData/15 as OHLCV
OHLCV.OHLCV current = OHLCV.getCurrentChartOHLCV()
This library does not use var internally to enforce clean separation of logic and persistence.
📅 Planned Enhancements
Fib zone ranges: capture candles within custom Fibonacci levels.
Custom event ranges: combine multiple filters (e.g., pattern + volume spike).
Trend-based ranges: windowing based on moving average or trend breaks.
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.
StrategyUtilsLibrary "StrategyUtils"
getHeikinAshi(open, high, low, close)
getHeikinAshi
Parameters:
open (float) : float: Raw open price
high (float) : float: Raw high price
low (float) : float: Raw low price
close (float) : float: Raw close price
Returns: tuple of haOpen, haClose, haHigh, haLow
getFibExtensions(high, low)
getFibExtensions
Parameters:
high (float) : float: Highest point before trade
low (float) : float: Lowest point before trade
Returns: tuple of extension levels
inBacktestWindow(time, start, end)
inBacktestWindow
Parameters:
time (int) : int: Current bar time
start (int) : int: Start timestamp
end (int) : int: End timestamp
Returns: bool: true if within Fbrange
getCurrentState(buy, sell)
getCurrentState
Parameters:
buy (bool) : bool: Buy signal condition
sell (bool) : bool: Sell signal condition
Returns: string: "Buy", "Sell", or "None"
formatPrice(price)
formatPrice
Parameters:
price (float) : float: Input price value
Returns: string: Formatted price string
getColorByProfit(netprofit, initial, green, red)
getColorByProfit
Parameters:
netprofit (float) : float: Strategy net profit
initial (float) : float: Initial capital
green (color) : color: Positive color
red (color) : color: Negative color
Returns: color: Display color based on PnL
MyLibraryLibrary "MyLibrary"
isPriceAbove(threshold)
Parameters:
threshold (float) :
isBullishCandle()