LogNormalLibrary "LogNormal"
A collection of functions used to model skewed distributions as log-normal.
Prices are commonly modeled using log-normal distributions (ie. Black-Scholes) because they exhibit multiplicative changes with long tails; skewed exponential growth and high variance. This approach is particularly useful for understanding price behavior and estimating risk, assuming continuously compounding returns are normally distributed.
Because log space analysis is not as direct as using math.log(price) , this library extends the Error Functions library to make working with log-normally distributed data as simple as possible.
- - -
QUICK START
Import library into your project
Initialize model with a mean and standard deviation
Pass model params between methods to compute various properties
var LogNorm model = LN.init(arr.avg(), arr.stdev()) // Assumes the library is imported as LN
var mode = model.mode()
Outputs from the model can be adjusted to better fit the data.
var Quantile data = arr.quantiles()
var more_accurate_mode = mode.fit(model, data) // Fits value from model to data
Inputs to the model can also be adjusted to better fit the data.
datum = 123.45
model_equivalent_datum = datum.fit(data, model) // Fits value from data to the model
area_from_zero_to_datum = model.cdf(model_equivalent_datum)
- - -
TYPES
There are two requisite UDTs: LogNorm and Quantile . They are used to pass parameters between functions and are set automatically (see Type Management ).
LogNorm
Object for log space parameters and linear space quantiles .
Fields:
mu (float) : Log space mu ( µ ).
sigma (float) : Log space sigma ( σ ).
variance (float) : Log space variance ( σ² ).
quantiles (Quantile) : Linear space quantiles.
Quantile
Object for linear quantiles, most similar to a seven-number summary .
Fields:
Q0 (float) : Smallest Value
LW (float) : Lower Whisker Endpoint
LC (float) : Lower Whisker Crosshatch
Q1 (float) : First Quartile
Q2 (float) : Second Quartile
Q3 (float) : Third Quartile
UC (float) : Upper Whisker Crosshatch
UW (float) : Upper Whisker Endpoint
Q4 (float) : Largest Value
IQR (float) : Interquartile Range
MH (float) : Midhinge
TM (float) : Trimean
MR (float) : Mid-Range
- - -
TYPE MANAGEMENT
These functions reliably initialize and update the UDTs. Because parameterization is interdependent, avoid setting the LogNorm and Quantile fields directly .
init(mean, stdev, variance)
Initializes a LogNorm object.
Parameters:
mean (float) : Linearly measured mean.
stdev (float) : Linearly measured standard deviation.
variance (float) : Linearly measured variance.
Returns: LogNorm Object
set(ln, mean, stdev, variance)
Transforms linear measurements into log space parameters for a LogNorm object.
Parameters:
ln (LogNorm) : Object containing log space parameters.
mean (float) : Linearly measured mean.
stdev (float) : Linearly measured standard deviation.
variance (float) : Linearly measured variance.
Returns: LogNorm Object
quantiles(arr)
Gets empirical quantiles from an array of floats.
Parameters:
arr (array) : Float array object.
Returns: Quantile Object
- - -
DESCRIPTIVE STATISTICS
Using only the initialized LogNorm parameters, these functions compute a model's central tendency and standardized moments.
mean(ln)
Computes the linear mean from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
median(ln)
Computes the linear median from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
mode(ln)
Computes the linear mode from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
variance(ln)
Computes the linear variance from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
skewness(ln)
Computes the linear skewness from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
kurtosis(ln, excess)
Computes the linear kurtosis from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
excess (bool) : Excess Kurtosis (true) or regular Kurtosis (false).
Returns: Between 0 and ∞
hyper_skewness(ln)
Computes the linear hyper skewness from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
Returns: Between 0 and ∞
hyper_kurtosis(ln, excess)
Computes the linear hyper kurtosis from log space parameters.
Parameters:
ln (LogNorm) : Object containing log space parameters.
excess (bool) : Excess Hyper Kurtosis (true) or regular Hyper Kurtosis (false).
Returns: Between 0 and ∞
- - -
DISTRIBUTION FUNCTIONS
These wrap Gaussian functions to make working with model space more direct. Because they are contained within a log-normal library, they describe estimations relative to a log-normal curve, even though they fundamentally measure a Gaussian curve.
pdf(ln, x, empirical_quantiles)
A Probability Density Function estimates the probability density . For clarity, density is not a probability .
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate for which a density will be estimated.
empirical_quantiles (Quantile) : Quantiles as observed in the data (optional).
Returns: Between 0 and ∞
cdf(ln, x, precise)
A Cumulative Distribution Function estimates the area under a Log-Normal curve between Zero and a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
ccdf(ln, x, precise)
A Complementary Cumulative Distribution Function estimates the area under a Log-Normal curve between a linear X coordinate and Infinity.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
cdfinv(ln, a, precise)
An Inverse Cumulative Distribution Function reverses the Log-Normal cdf() by estimating the linear X coordinate from an area.
Parameters:
ln (LogNorm) : Object of log space parameters.
a (float) : Normalized area .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
ccdfinv(ln, a, precise)
An Inverse Complementary Cumulative Distribution Function reverses the Log-Normal ccdf() by estimating the linear X coordinate from an area.
Parameters:
ln (LogNorm) : Object of log space parameters.
a (float) : Normalized area .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
cdfab(ln, x1, x2, precise)
A Cumulative Distribution Function from A to B estimates the area under a Log-Normal curve between two linear X coordinates (A and B).
Parameters:
ln (LogNorm) : Object of log space parameters.
x1 (float) : First linear X coordinate .
x2 (float) : Second linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
ott(ln, x, precise)
A One-Tailed Test transforms a linear X coordinate into an absolute Z Score before estimating the area under a Log-Normal curve between Z and Infinity.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 0.5
ttt(ln, x, precise)
A Two-Tailed Test transforms a linear X coordinate into symmetrical ± Z Scores before estimating the area under a Log-Normal curve from Zero to -Z, and +Z to Infinity.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
ottinv(ln, a, precise)
An Inverse One-Tailed Test reverses the Log-Normal ott() by estimating a linear X coordinate for the right tail from an area.
Parameters:
ln (LogNorm) : Object of log space parameters.
a (float) : Half a normalized area .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
tttinv(ln, a, precise)
An Inverse Two-Tailed Test reverses the Log-Normal ttt() by estimating two linear X coordinates from an area.
Parameters:
ln (LogNorm) : Object of log space parameters.
a (float) : Normalized area .
precise (bool) : Double precision (true) or single precision (false).
Returns: Linear space tuple :
- - -
UNCERTAINTY
Model-based measures of uncertainty, information, and risk.
sterr(sample_size, fisher_info)
The standard error of a sample statistic.
Parameters:
sample_size (float) : Number of observations.
fisher_info (float) : Fisher information.
Returns: Between 0 and ∞
surprisal(p, base)
Quantifies the information content of a single event.
Parameters:
p (float) : Probability of the event .
base (float) : Logarithmic base (optional).
Returns: Between 0 and ∞
entropy(ln, base)
Computes the differential entropy (average surprisal).
Parameters:
ln (LogNorm) : Object of log space parameters.
base (float) : Logarithmic base (optional).
Returns: Between 0 and ∞
perplexity(ln, base)
Computes the average number of distinguishable outcomes from the entropy.
Parameters:
ln (LogNorm)
base (float) : Logarithmic base used for Entropy (optional).
Returns: Between 0 and ∞
value_at_risk(ln, p, precise)
Estimates a risk threshold under normal market conditions for a given confidence level.
Parameters:
ln (LogNorm) : Object of log space parameters.
p (float) : Probability threshold, aka. the confidence level .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
value_at_risk_inv(ln, value_at_risk, precise)
Reverses the value_at_risk() by estimating the confidence level from the risk threshold.
Parameters:
ln (LogNorm) : Object of log space parameters.
value_at_risk (float) : Value at Risk.
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
conditional_value_at_risk(ln, p, precise)
Estimates the average loss beyond a confidence level, aka. expected shortfall.
Parameters:
ln (LogNorm) : Object of log space parameters.
p (float) : Probability threshold, aka. the confidence level .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
conditional_value_at_risk_inv(ln, conditional_value_at_risk, precise)
Reverses the conditional_value_at_risk() by estimating the confidence level of an average loss.
Parameters:
ln (LogNorm) : Object of log space parameters.
conditional_value_at_risk (float) : Conditional Value at Risk.
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and 1
partial_expectation(ln, x, precise)
Estimates the partial expectation of a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and µ
partial_expectation_inv(ln, partial_expectation, precise)
Reverses the partial_expectation() by estimating a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
partial_expectation (float) : Partial Expectation .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
conditional_expectation(ln, x, precise)
Estimates the conditional expectation of a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between X and ∞
conditional_expectation_inv(ln, conditional_expectation, precise)
Reverses the conditional_expectation by estimating a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
conditional_expectation (float) : Conditional Expectation .
precise (bool) : Double precision (true) or single precision (false).
Returns: Between 0 and ∞
fisher(ln, log)
Computes the Fisher Information Matrix for the distribution, not a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
log (bool) : Sets if the matrix should be in log (true) or linear (false) space.
Returns: FIM for the distribution
fisher(ln, x, log)
Computes the Fisher Information Matrix for a linear X coordinate, not the distribution itself.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
log (bool) : Sets if the matrix should be in log (true) or linear (false) space.
Returns: FIM for the linear X coordinate
confidence_interval(ln, x, sample_size, confidence, precise)
Estimates a confidence interval for a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate .
sample_size (float) : Number of observations.
confidence (float) : Confidence level .
precise (bool) : Double precision (true) or single precision (false).
Returns: CI for the linear X coordinate
- - -
CURVE FITTING
An overloaded function that helps transform values between spaces. The primary function uses quantiles, and the overloads wrap the primary function to make working with LogNorm more direct.
fit(x, a, b)
Transforms X coordinate between spaces A and B.
Parameters:
x (float) : Linear X coordinate from space A .
a (LogNorm | Quantile | array) : LogNorm, Quantile, or float array.
b (LogNorm | Quantile | array) : LogNorm, Quantile, or float array.
Returns: Adjusted X coordinate
- - -
EXPORTED HELPERS
Small utilities to simplify extensibility.
z_score(ln, x)
Converts a linear X coordinate into a Z Score.
Parameters:
ln (LogNorm) : Object of log space parameters.
x (float) : Linear X coordinate.
Returns: Between -∞ and +∞
x_coord(ln, z)
Converts a Z Score into a linear X coordinate.
Parameters:
ln (LogNorm) : Object of log space parameters.
z (float) : Standard normal Z Score.
Returns: Between 0 and ∞
iget(arr, index)
Gets an interpolated value of a pseudo -element (fictional element between real array elements). Useful for quantile mapping.
Parameters:
arr (array) : Float array object.
index (float) : Index of the pseudo element.
Returns: Interpolated value of the arrays pseudo element.
Индикаторы и стратегии
Min_Position_Size_ALLLibrary "Min_Position_Size_ALL"
getMinPositionSize(symbol_, type_, broker_)
Parameters:
symbol_ (string)
type_ (string)
broker_ (string)
ICOptimizerLibrary "ICOptimizer"
Library for IC-based parameter optimization
findOptimalParam(testParams, icValues, currentParam, smoothing)
Find optimal parameter from array of IC values
Parameters:
testParams (array) : Array of parameter values being tested
icValues (array) : Array of IC values for each parameter (same size as testParams)
currentParam (float) : Current parameter value (for smoothing)
smoothing (simple float) : Smoothing factor (0-1, e.g., 0.2 means 20% new, 80% old)
Returns: New parameter value, its IC, and array index
adaptiveParamWithStarvation(opt, testParams, icValues, smoothing, starvationThreshold, starvationJumpSize)
Adaptive parameter selection with starvation handling
Parameters:
opt (ICOptimizer) : ICOptimizer object
testParams (array) : Array of parameter values
icValues (array) : Array of IC values for each parameter
smoothing (simple float) : Normal smoothing factor
starvationThreshold (simple int) : Number of updates before triggering starvation mode
starvationJumpSize (simple float) : Jump size when in starvation (as fraction of range)
Returns: Updated parameter and IC
detectAndAdjustDomination(longCount, shortCount, currentLongLevel, currentShortLevel, dominationRatio, jumpSize, minLevel, maxLevel)
Detect signal imbalance and adjust parameters
Parameters:
longCount (int) : Number of long signals in period
shortCount (int) : Number of short signals in period
currentLongLevel (float) : Current long threshold
currentShortLevel (float) : Current short threshold
dominationRatio (simple int) : Ratio threshold (e.g., 4 = 4:1 imbalance)
jumpSize (simple float) : Size of adjustment
minLevel (simple float) : Minimum allowed level
maxLevel (simple float) : Maximum allowed level
Returns:
calcIC(signals, returns, lookback)
Parameters:
signals (float)
returns (float)
lookback (simple int)
classifyIC(currentIC, icWindow, goodPercentile, badPercentile)
Parameters:
currentIC (float)
icWindow (simple int)
goodPercentile (simple int)
badPercentile (simple int)
evaluateSignal(signal, forwardReturn)
Parameters:
signal (float)
forwardReturn (float)
updateOptimizerState(opt, signal, forwardReturn, currentIC, metaICPeriod)
Parameters:
opt (ICOptimizer)
signal (float)
forwardReturn (float)
currentIC (float)
metaICPeriod (simple int)
calcSuccessRate(successful, total)
Parameters:
successful (int)
total (int)
createICStatsTable(opt, paramName, normalSuccess, normalTotal)
Parameters:
opt (ICOptimizer)
paramName (string)
normalSuccess (int)
normalTotal (int)
initOptimizer(initialParam)
Parameters:
initialParam (float)
ICOptimizer
Fields:
currentParam (series float)
currentIC (series float)
metaIC (series float)
totalSignals (series int)
successfulSignals (series int)
goodICSignals (series int)
goodICSuccess (series int)
nonBadICSignals (series int)
nonBadICSuccess (series int)
goodICThreshold (series float)
badICThreshold (series float)
updateCounter (series int)
IC optimiser libLibrary "IC optimiser lib"
Library for IC-based parameter optimization
findOptimalParam(testParams, icValues, currentParam, smoothing)
Find optimal parameter from array of IC values
Parameters:
testParams (array) : Array of parameter values being tested
icValues (array) : Array of IC values for each parameter (same size as testParams)
currentParam (float) : Current parameter value (for smoothing)
smoothing (simple float) : Smoothing factor (0-1, e.g., 0.2 means 20% new, 80% old)
Returns: New parameter value, its IC, and array index
adaptiveParamWithStarvation(opt, testParams, icValues, smoothing, starvationThreshold, starvationJumpSize)
Adaptive parameter selection with starvation handling
Parameters:
opt (ICOptimizer) : ICOptimizer object
testParams (array) : Array of parameter values
icValues (array) : Array of IC values for each parameter
smoothing (simple float) : Normal smoothing factor
starvationThreshold (simple int) : Number of updates before triggering starvation mode
starvationJumpSize (simple float) : Jump size when in starvation (as fraction of range)
Returns: Updated parameter and IC
detectAndAdjustDomination(longCount, shortCount, currentLongLevel, currentShortLevel, dominationRatio, jumpSize, minLevel, maxLevel)
Detect signal imbalance and adjust parameters
Parameters:
longCount (int) : Number of long signals in period
shortCount (int) : Number of short signals in period
currentLongLevel (float) : Current long threshold
currentShortLevel (float) : Current short threshold
dominationRatio (simple int) : Ratio threshold (e.g., 4 = 4:1 imbalance)
jumpSize (simple float) : Size of adjustment
minLevel (simple float) : Minimum allowed level
maxLevel (simple float) : Maximum allowed level
Returns:
calcIC(signals, returns, lookback)
Parameters:
signals (float)
returns (float)
lookback (simple int)
classifyIC(currentIC, icWindow, goodPercentile, badPercentile)
Parameters:
currentIC (float)
icWindow (simple int)
goodPercentile (simple int)
badPercentile (simple int)
evaluateSignal(signal, forwardReturn)
Parameters:
signal (float)
forwardReturn (float)
updateOptimizerState(opt, signal, forwardReturn, currentIC, metaICPeriod)
Parameters:
opt (ICOptimizer)
signal (float)
forwardReturn (float)
currentIC (float)
metaICPeriod (simple int)
calcSuccessRate(successful, total)
Parameters:
successful (int)
total (int)
createICStatsTable(opt, paramName, normalSuccess, normalTotal)
Parameters:
opt (ICOptimizer)
paramName (string)
normalSuccess (int)
normalTotal (int)
initOptimizer(initialParam)
Parameters:
initialParam (float)
ICOptimizer
Fields:
currentParam (series float)
currentIC (series float)
metaIC (series float)
totalSignals (series int)
successfulSignals (series int)
goodICSignals (series int)
goodICSuccess (series int)
nonBadICSignals (series int)
nonBadICSuccess (series int)
goodICThreshold (series float)
badICThreshold (series float)
updateCounter (series int)
LIB_SDz_AucLibrary "LIB_SDz_Auc"
TODO: add library description here
getLineStyle(style)
Parameters:
style (string)
testLibLibrary "testLib"
TODO: add library description here
mySMA(x)
TODO: add function description here
Parameters:
x (int) : TODO: add parameter x description here
Returns: TODO: add what function returns
livremySMATestLibLibrary "livremySMATestLib"
TODO: add library description here
mySMA(x)
TODO: add function description here
Parameters:
x (int) : TODO: add parameter x description here
Returns: TODO: add what function returns
Material Color Palette Library█ OVERVIEW
Unlock a world of color in your Pine Script® projects with the Material Color Palette Library . This library provides a comprehensive and structured color system based on Google's Material Design palette, making it incredibly easy to create visually appealing and professional-looking indicators and strategies.
Forget about guessing hex codes. With this library, you have access to 19 distinct color families, each offering a wide range of shades. Every color can be fine-tuned with saturation, darkness, and opacity levels, giving you precise control over your script's appearance.
To make development even easier, the library includes a visual cheatsheet. Simply add the script to your chart to display a full table of all available colors and their corresponding parameters.
█ KEY FEATURES
Vast Spectrum: 19 distinct color families, from vibrant reds and blues to subtle greys and browns.
Fine-Tuned Control: Each color function accepts parameters for `saturationLevel` (1-13 or 1-9) and `darkLevel` (1-3) to select the perfect shade.
Opacity Parameter: Easily add transparency to any color for fills, backgrounds, or lines.
Quick Access Tones: A simple `tone()` function to grab base colors by name.
Visual Cheatsheet: An on-chart table displays the entire color palette, serving as a handy reference guide during development.
█ HOW TO USE
As a library, this script is meant to be imported into your own indicators or strategies.
1. Import the Library
Add the following line to the top of your script. Remember to replace `YourUsername` with your TradingView username.
import mastertop/ColorPalette/1 as colors
2. Call a Color Function
You can now use any of the exported functions to set colors for your plots, backgrounds, tables, and more.
The primary functions take three arguments: `functionName(saturationLevel, darkLevel, opacity)`
`saturationLevel`: An integer that controls the intensity of the color. Ranges from 1 (lightest) to 13 (most vibrant) for most colors, and 1-9 for `brown`, `grey`, and `blueGrey`.
`darkLevel`: An integer from 1 to 3 (1: light, 2: medium, 3: dark).
`opacity`: An integer from 0 (opaque) to 100 (invisible).
Example Usage:
Let's plot a moving average with a specific shade of teal.
// Import the library
import mastertop/ColorPalette/1 as colors
indicator("My Script with Custom Colors", overlay = true)
// Calculate a moving average
ma = ta.sma(close, 20)
// Plot the MA using a color from the library
// We'll use teal with saturation level 7, dark level 2, and 0% opacity
plot(ma, "MA", color = colors.teal(7, 2, 0), linewidth = 2)
3. Using the `tone()` Function
For quick access to a base color, you can use the `tone()` function.
// Set a red background with 85% transparency
bgcolor(colors.tone('red', 85))
█ VISUAL REFERENCE
To see all available colors at a glance, you can add this library script directly to your chart. It will display a comprehensive table showing every color variant. This makes it easy to pick the exact shade you need without guesswork.
This library is designed for fellow Pine Script® developers to streamline their workflow and enhance the visual quality of their scripts. Enjoy!
UTBotLibrary "UTBot"
is a powerful and flexible trading toolkit implemented in Pine Script. Based on the widely recognized UT Bot strategy originally developed by Yo_adriiiiaan with important enhancements by HPotter, this library provides users with customizable functions for dynamic trailing stop calculations using ATR (Average True Range), trend detection, and signal generation. It enables developers and traders to seamlessly integrate UT Bot logic into their own indicators and strategies without duplicating code.
Key features include:
Accurate ATR-based trailing stop and reversal detection
Multi-timeframe support for enhanced signal reliability
Clean and efficient API for easy integration and customization
Detailed documentation and examples for quick adoption
Open-source and community-friendly, encouraging collaboration and improvements
We sincerely thank Yo_adriiiiaan for the original UT Bot concept and HPotter for valuable improvements that have made this strategy even more robust. This library aims to honor their work by making the UT Bot methodology accessible to Pine Script developers worldwide.
This library is designed for Pine Script programmers looking to leverage the proven UT Bot methodology to build robust trading systems with minimal effort and maximum maintainability.
UTBot(h, l, c, multi, leng)
Parameters:
h (float) - high
l (float) - low
c (float)-close
multi (float)- multi for ATR
leng (int)-length for ATR
Returns:
xATRTS - ATR Based TrailingStop Value
pos - pos==1, long position, pos==-1, shot position
signal - 0 no signal, 1 buy, -1 sell
mt_elliott_coreLibrary "mt_elliott_core"
ewo(maFastLen, maSlowLen, smoothLen)
Parameters:
maFastLen (simple int)
maSlowLen (simple int)
smoothLen (simple int)
mt_phase_num(_len, _minGap)
Parameters:
_len (simple int)
_minGap (simple float)
mt_color_from_phase(_len, _minGap)
Parameters:
_len (simple int)
_minGap (simple float)
mt_phase_progress_pct(_len, _minGap)
Parameters:
_len (simple int)
_minGap (simple float)
anchor_p1_close(len, minGap)
Parameters:
len (simple int)
minGap (simple float)
anchor_p1_pivot(len, minGap)
Parameters:
len (simple int)
minGap (simple float)
row_group_from_ewo(ewoValue, atrValue, strongPct, neutralPct)
Parameters:
ewoValue (float)
atrValue (float)
strongPct (simple float)
neutralPct (simple float)
wave_event_pivot_aligned(ewoSeries, left, right, divTolPct, minBarsGap)
Parameters:
ewoSeries (float)
left (simple int)
right (simple int)
divTolPct (simple float)
minBarsGap (simple int)
DynLenLibLibrary "DynLenLib"
sum_dyn(src, len)
Parameters:
src (float)
len (int)
lag_dyn(src, len)
Parameters:
src (float)
len (int)
highest_dyn(src, len)
Parameters:
src (float)
len (int)
lowest_dyn(src, len)
Parameters:
src (float)
len (int)
var_dyn(src, len)
Parameters:
src (float)
len (int)
stdev_dyn(src, len)
Parameters:
src (float)
len (int)
hl2()
hlc3()
ohlc4()
sma_dyn(src, len)
Parameters:
src (float)
len (int)
ema_dyn(src, len)
Parameters:
src (float)
len (int)
rma_dyn(src, len)
Parameters:
src (float)
len (int)
smma_dyn(src, len)
Parameters:
src (float)
len (int)
wma_dyn(src, len)
Parameters:
src (float)
len (int)
vwma_dyn(price, vol, len)
Parameters:
price (float)
vol (float)
len (int)
hma_dyn(src, len)
Parameters:
src (float)
len (int)
dema_dyn(src, len)
Parameters:
src (float)
len (int)
tema_dyn(src, len)
Parameters:
src (float)
len (int)
kama_dyn(src, erLen, fastLen, slowLen)
Parameters:
src (float)
erLen (int)
fastLen (int)
slowLen (int)
mcginley_dyn(src, len)
Parameters:
src (float)
len (int)
median_price()
true_range()
atr_dyn(len)
Parameters:
len (int)
bbands_dyn(src, len, mult)
Parameters:
src (float)
len (int)
mult (float)
bb_percent_b(src, len, mult)
Parameters:
src (float)
len (int)
mult (float)
bb_bandwidth(src, len, mult)
Parameters:
src (float)
len (int)
mult (float)
keltner_dyn(src, lenEMA, lenATR, multATR)
Parameters:
src (float)
lenEMA (int)
lenATR (int)
multATR (float)
donchian_dyn(len)
Parameters:
len (int)
choppiness_index(len)
Parameters:
len (int)
vol_stop(lenATR, mult)
Parameters:
lenATR (int)
mult (float)
roc_dyn(src, len)
Parameters:
src (float)
len (int)
rsi_dyn(src, len)
Parameters:
src (float)
len (int)
stoch_dyn(kLen, dLen, smoothK)
Parameters:
kLen (int)
dLen (int)
smoothK (int)
stoch_rsi_dyn(rsiLen, stochLen, kSmooth, dLen)
Parameters:
rsiLen (int)
stochLen (int)
kSmooth (int)
dLen (int)
cci_dyn(src, len)
Parameters:
src (float)
len (int)
cmo_dyn(src, len)
Parameters:
src (float)
len (int)
trix_dyn(len)
Parameters:
len (int)
tsi_dyn(shortLen, longLen)
Parameters:
shortLen (int)
longLen (int)
ultimate_osc(len1, len2, len3)
Parameters:
len1 (int)
len2 (int)
len3 (int)
dpo_dyn(src, len)
Parameters:
src (float)
len (int)
willr_dyn(len)
Parameters:
len (int)
macd_dyn(src, fastLen, slowLen, sigLen)
Parameters:
src (float)
fastLen (int)
slowLen (int)
sigLen (int)
ppo_dyn(src, fastLen, slowLen, sigLen)
Parameters:
src (float)
fastLen (int)
slowLen (int)
sigLen (int)
aroon_dyn(len)
Parameters:
len (int)
dmi_adx_dyn(diLen, adxLen)
Parameters:
diLen (int)
adxLen (int)
vortex_dyn(len)
Parameters:
len (int)
coppock_dyn(rocLen1, rocLen2, wmaLen)
Parameters:
rocLen1 (int)
rocLen2 (int)
wmaLen (int)
rvi_dyn(len)
Parameters:
len (int)
price_osc_dyn(src, fastLen, slowLen)
Parameters:
src (float)
fastLen (int)
slowLen (int)
rci_dyn(src, len)
Parameters:
src (float)
len (int)
obv()
pvt()
cmf_dyn(len)
Parameters:
len (int)
adl()
chaikin_osc_dyn(fastLen, slowLen)
Parameters:
fastLen (int)
slowLen (int)
mfi_dyn(len)
Parameters:
len (int)
volume_osc_dyn(fastLen, slowLen)
Parameters:
fastLen (int)
slowLen (int)
up_down_volume()
cvd()
supertrend_dyn(atrLen, mult)
Parameters:
atrLen (int)
mult (float)
envelopes_dyn(src, len, pct)
Parameters:
src (float)
len (int)
pct (float)
linreg_line_slope(src, len)
Parameters:
src (float)
len (int)
lsma_dyn(src, len)
Parameters:
src (float)
len (int)
corrcoef_dyn(a, b, len)
Parameters:
a (float)
b (float)
len (int)
psar(step, maxStep)
Parameters:
step (float)
maxStep (float)
pivots_standard()
williams_alligator(src, jawLen, teethLen, lipsLen)
Parameters:
src (float)
jawLen (int)
teethLen (int)
lipsLen (int)
twap_dyn(src, len)
Parameters:
src (float)
len (int)
vwap_anchored(price, volume, reset)
Parameters:
price (float)
volume (float)
reset (bool)
performance_pct(len)
Parameters:
len (int)
AlgebraGeometryLabLibrary "AlgebraGeometryLab"
Algebra & 2D geometry utilities absent from Pine built-ins.
Rigorous, no-repaint, export-ready: vectors, robust roots, linear solvers, 2x2/3x3 det/inverse,
symmetric 2x2 eigensystem, orthogonal regression (TLS), affine transforms, intersections,
distances, projections, polygon metrics, point-in-polygon, convex hull (monotone chain),
Bezier/Catmull-Rom/Barycentric tools.
clamp(x, lo, hi)
clamp to
Parameters:
x (float)
lo (float)
hi (float)
near(a, b, atol, rtol)
approximately equal with relative+absolute tolerance
Parameters:
a (float)
b (float)
atol (float)
rtol (float)
sgn(x)
sign as {-1,0,1}
Parameters:
x (float)
hypot(x, y)
stable hypot (sqrt(x^2+y^2))
Parameters:
x (float)
y (float)
method length(v)
Namespace types: Vec2
Parameters:
v (Vec2)
method length2(v)
Namespace types: Vec2
Parameters:
v (Vec2)
method normalized(v)
Namespace types: Vec2
Parameters:
v (Vec2)
method add(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method sub(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method muls(v, s)
Namespace types: Vec2
Parameters:
v (Vec2)
s (float)
method dot(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method crossz(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method rotate(v, ang)
Namespace types: Vec2
Parameters:
v (Vec2)
ang (float)
method apply(v, T)
Namespace types: Vec2
Parameters:
v (Vec2)
T (Affine2)
affine_identity()
identity transform
affine_translate(tx, ty)
translation
Parameters:
tx (float)
ty (float)
affine_rotate(ang)
rotation about origin
Parameters:
ang (float)
affine_scale(sx, sy)
scaling about origin
Parameters:
sx (float)
sy (float)
affine_rotate_about(ang, px, py)
rotation about pivot (px,py)
Parameters:
ang (float)
px (float)
py (float)
affine_compose(T2, T1)
compose T2∘T1 (apply T1 then T2)
Parameters:
T2 (Affine2)
T1 (Affine2)
quadratic_roots(a, b, c)
Real roots of ax^2 + bx + c = 0 (numerically stable)
Parameters:
a (float)
b (float)
c (float)
Returns: with n∈{0,1,2}; r1<=r2 when n=2.
cubic_roots(a, b, c, d)
Real roots of ax^3+bx^2+cx+d=0 (Cardano; returns up to 3 real roots)
Parameters:
a (float)
b (float)
c (float)
d (float)
Returns: (valid r2/r3 only if n>=2/n>=3)
det2(a, b, c, d)
det2 of
Parameters:
a (float)
b (float)
c (float)
d (float)
inv2(a, b, c, d)
inverse of 2x2; returns
Parameters:
a (float)
b (float)
c (float)
d (float)
solve2(a, b, c, d, e, f)
solve 2x2 * = via Cramer
Parameters:
a (float)
b (float)
c (float)
d (float)
e (float)
f (float)
det3(a11, a12, a13, a21, a22, a23, a31, a32, a33)
det3 of 3x3
Parameters:
a11 (float)
a12 (float)
a13 (float)
a21 (float)
a22 (float)
a23 (float)
a31 (float)
a32 (float)
a33 (float)
inv3(a11, a12, a13, a21, a22, a23, a31, a32, a33)
inverse 3x3; returns
Parameters:
a11 (float)
a12 (float)
a13 (float)
a21 (float)
a22 (float)
a23 (float)
a31 (float)
a32 (float)
a33 (float)
eig2_symmetric(a, b, d)
symmetric 2x2 eigensystem: [ , ]
Parameters:
a (float)
b (float)
d (float)
Returns: with unit eigenvectors
tls_line(xs, ys)
Orthogonal (total least squares) regression line through point cloud
Input arrays must be same length N>=2. Returns line in normal form n•x + c = 0
Parameters:
xs (array)
ys (array)
Returns: where (nx,ny) unit normal; (cx,cy) centroid.
orient(a, b, c)
orientation (signed area*2): >0 CCW, <0 CW, 0 collinear
Parameters:
a (Vec2)
b (Vec2)
c (Vec2)
project_point_line(p, a, d)
project point p onto infinite line through a with direction d
Parameters:
p (Vec2)
a (Vec2)
d (Vec2)
Returns: where proj = a + t*d
closest_point_segment(p, a, b)
closest point on segment to p
Parameters:
p (Vec2)
a (Vec2)
b (Vec2)
Returns: where t∈ on segment
dist_point_line(p, a, d)
distance from point to line (infinite)
Parameters:
p (Vec2)
a (Vec2)
d (Vec2)
dist_point_segment(p, a, b)
distance from point to segment
Parameters:
p (Vec2)
a (Vec2)
b (Vec2)
intersect_lines(p1, d1, p2, d2)
line-line intersection: L1: p1+d1*t, L2: p2+d2*u
Parameters:
p1 (Vec2)
d1 (Vec2)
p2 (Vec2)
d2 (Vec2)
Returns:
intersect_segments(s1, s2)
segment-segment intersection (closed segments)
Parameters:
s1 (Segment2)
s2 (Segment2)
Returns: where kind: 0=no, 1=proper point, 2=overlap (ix/iy=na)
circumcircle(a, b, c)
circle through 3 non-collinear points
Parameters:
a (Vec2)
b (Vec2)
c (Vec2)
intersect_circle_line(C, p, d)
intersections of circle and line (param p + d t)
Parameters:
C (Circle2)
p (Vec2)
d (Vec2)
Returns: with n∈{0,1,2}
intersect_circles(A, B)
circle-circle intersection
Parameters:
A (Circle2)
B (Circle2)
Returns: with n∈{0,1,2}
polygon_area(xs, ys)
signed area (shoelace). Positive if CCW.
Parameters:
xs (array)
ys (array)
polygon_centroid(xs, ys)
polygon centroid (for non-self-intersecting). Fallback to vertex mean if area≈0.
Parameters:
xs (array)
ys (array)
point_in_polygon(px, py, xs, ys)
point-in-polygon test (ray casting). Returns true if inside; boundary counts as inside.
Parameters:
px (float)
py (float)
xs (array)
ys (array)
convex_hull(xs, ys)
convex hull (monotone chain). Returns array of hull vertex indices in CCW order.
Uses array.sort_indices(xs) (ascending by x). Ties on x are handled; result is deterministic.
Parameters:
xs (array)
ys (array)
lerp(a, b, t)
linear interpolate between a and b
Parameters:
a (float)
b (float)
t (float)
bezier2(p0, p1, p2, t)
quadratic Bezier B(t) for points p0,p1,p2
Parameters:
p0 (Vec2)
p1 (Vec2)
p2 (Vec2)
t (float)
bezier3(p0, p1, p2, p3, t)
cubic Bezier B(t) for p0,p1,p2,p3
Parameters:
p0 (Vec2)
p1 (Vec2)
p2 (Vec2)
p3 (Vec2)
t (float)
catmull_rom(p0, p1, p2, p3, t, alpha)
Catmull-Rom interpolation (centripetal form when alpha=0.5)
t∈ , returns point between p1 and p2
Parameters:
p0 (Vec2)
p1 (Vec2)
p2 (Vec2)
p3 (Vec2)
t (float)
alpha (float)
barycentric(A, B, C, P)
barycentric coordinates of P wrt triangle ABC
Parameters:
A (Vec2)
B (Vec2)
C (Vec2)
P (Vec2)
Returns:
point_in_triangle(A, B, C, P)
point-in-triangle using barycentric (boundary included)
Parameters:
A (Vec2)
B (Vec2)
C (Vec2)
P (Vec2)
Vec2
Fields:
x (series float)
y (series float)
Line2
Fields:
p (Vec2)
d (Vec2)
Segment2
Fields:
a (Vec2)
b (Vec2)
Circle2
Fields:
c (Vec2)
r (series float)
Affine2
Fields:
a (series float)
b (series float)
c (series float)
d (series float)
tx (series float)
ty (series float)
ema 狀態機Library "ema_flow_lib"
ema_flow_state(e10, e20, e100, entanglePct, farPct, e10_prev, e20_prev)
Parameters:
e10 (float)
e20 (float)
e100 (float)
entanglePct (float)
farPct (float)
e10_prev (float)
e20_prev (float)
state_name(s)
Parameters:
s (int)
phx_liq_tlLibrary "phx_liq_tl"
new_state()
update(st, len, cup, cdn, space, proximity_pct, shs)
Parameters:
st (LTState)
len (int)
cup (color)
cdn (color)
space (float)
proximity_pct (float)
shs (bool)
LTState
Fields:
upln (array)
dnln (array)
upBroken (series bool)
dnBroken (series bool)
phx_kroLibrary "phx_kro"
compute(src, bandwidth, bbwidth, sdLook, sdMult, obos_mult)
Parameters:
src (float)
bandwidth (int)
bbwidth (float)
sdLook (int)
sdMult (float)
obos_mult (float)
start_flags(src, bandwidth, bbwidth)
Parameters:
src (float)
bandwidth (int)
bbwidth (float)
KROFeed
Fields:
Wave (series float)
is_green (series bool)
is_red (series bool)
band_width (series float)
band_width_sma (series float)
band_width_std (series float)
is_hyper_wide (series bool)
wave_sma (series float)
wave_std (series float)
wave_ob_threshold (series float)
wave_os_threshold (series float)
is_overbought (series bool)
is_oversold (series bool)
is_oversold_confirmed (series bool)
is_overbought_confirmed (series bool)
enhanced_os_confirmed (series bool)
enhanced_ob_confirmed (series bool)
triple_green_transition (series bool)
triple_red_transition (series bool)
startwave_bull (series bool)
startwave_bear (series bool)
phx_fvgfvg generator 4h and current time frame
library to import fvg from 4h with midle line and proximity support and resistance
JK_Traders_Reality_LibLibrary "JK_Traders_Reality_Lib"
This library contains common elements used in Traders Reality scripts
calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, darkGreyCandleColor, lightGrayCandleColor)
calculate the pvsra candle color and return the color as well as an alert if a vector candle has apperared.
Situation "Climax"
Bars with volume >= 200% of the average volume of the 10 previous chart TFs, or bars
where the product of candle spread x candle volume is >= the highest for the 10 previous
chart time TFs.
Default Colors: Bull bars are green and bear bars are red.
Situation "Volume Rising Above Average"
Bars with volume >= 150% of the average volume of the 10 previous chart TFs.
Default Colors: Bull bars are blue and bear are violet.
Parameters:
pvsraVolume (float) : the instrument volume series (obtained from request.sequrity)
pvsraHigh (float) : the instrument high series (obtained from request.sequrity)
pvsraLow (float) : the instrument low series (obtained from request.sequrity)
pvsraClose (float) : the instrument close series (obtained from request.sequrity)
pvsraOpen (float) : the instrument open series (obtained from request.sequrity)
redVectorColor (simple color) : red vector candle color
greenVectorColor (simple color) : green vector candle color
violetVectorColor (simple color) : violet/pink vector candle color
blueVectorColor (simple color) : blue vector candle color
darkGreyCandleColor (simple color) : regular volume candle down candle color - not a vector
lightGrayCandleColor (simple color) : regular volume candle up candle color - not a vector
@return
adr(length, barsBack)
Parameters:
length (simple int) : how many elements of the series to calculate on
barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
@return adr the adr for the specified lenght
adrHigh(adr, fromDo)
Calculate the ADR high given an ADR
Parameters:
adr (float) : the adr
fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrHigh the position of the adr high in price
adrLow(adr, fromDo)
Parameters:
adr (float) : the adr
fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrLow the position of the adr low in price
splitSessionString(sessXTime)
given a session in the format 0000-0100:23456 split out the hours and minutes
Parameters:
sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
@return
calcSessionStartEnd(sessXTime, gmt)
calculate the start and end timestamps of the session
Parameters:
sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return
drawOpenRange(sessXTime, sessXcol, showOrX, gmt)
draw open range for a session
Parameters:
sessXTime (simple string) : session string in the format 0000-0100:23456
sessXcol (simple color) : the color to be used for the opening range box shading
showOrX (simple bool) : boolean flag to toggle displaying the opening range
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return void
drawSessionHiLo(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle)
Parameters:
sessXTime (simple string) : session string in the format 0000-0100:23456
showRectangleX (simple bool)
showLabelX (simple bool)
sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
sessXLabel (simple string) : the session label text
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
sessionLineStyle (simple string) : the line stile for the session high low lines
@return void
calcDst()
calculate market session dst on/off flags
@return indicating if DST is on or off for a particular region
timestampPreviousDayOfWeek(previousDayOfWeek, hourOfDay, gmtOffset, oneWeekMillis)
Timestamp any of the 6 previous days in the week (such as last Wednesday at 21 hours GMT)
Parameters:
previousDayOfWeek (simple string) : Monday or Satruday
hourOfDay (simple int) : the hour of the day when psy calc is to start
gmtOffset (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
oneWeekMillis (simple int) : the amount if time for a week in milliseconds
@return the timestamp of the psy level calculation start time
getdayOpen()
get the daily open - basically exchange midnight
@return the daily open value which is float price
newBar(res)
new_bar: check if we're on a new bar within the session in a given resolution
Parameters:
res (simple string) : the desired resolution
@return true/false is a new bar for the session has started
toPips(val)
to_pips Convert value to pips
Parameters:
val (float) : the value to convert to pips
@return the value in pips
rLabel(ry, rtext, rstyle, rcolor, valid, labelXOffset)
a function that draws a right aligned lable for a series during the current bar
Parameters:
ry (float) : series float the y coordinate of the lable
rtext (simple string) : the text of the label
rstyle (simple string) : the style for the lable
rcolor (simple color) : the color for the label
valid (simple bool) : a boolean flag that allows for turning on or off a lable
labelXOffset (int) : how much to offset the label from the current position
rLabelOffset(ry, rtext, rstyle, rcolor, valid, labelOffset)
a function that draws a right aligned lable for a series during the current bar
Parameters:
ry (float) : series float the y coordinate of the lable
rtext (string) : the text of the label
rstyle (simple string) : the style for the lable
rcolor (simple color) : the color for the label
valid (simple bool) : a boolean flag that allows for turning on or off a lable
labelOffset (int)
rLabelLastBar(ry, rtext, rstyle, rcolor, valid, labelXOffset)
a function that draws a right aligned lable for a series only on the last bar
Parameters:
ry (float) : series float the y coordinate of the lable
rtext (string) : the text of the label
rstyle (simple string) : the style for the lable
rcolor (simple color) : the color for the label
valid (simple bool) : a boolean flag that allows for turning on or off a lable
labelXOffset (int) : how much to offset the label from the current position
drawLine(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame)
a function that draws a line and a label for a series
Parameters:
xSeries (float) : series float the y coordinate of the line/label
res (simple string) : the desired resolution controlling when a new line will start
tag (simple string) : the text for the lable
xColor (simple color) : the color for the label
xStyle (simple string) : the style for the line
xWidth (simple int) : the width of the line
xExtend (simple string) : extend the line
isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
xLabelOffset (int)
validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
drawLineDO(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame)
a function that draws a line and a label for the daily open series
Parameters:
xSeries (float) : series float the y coordinate of the line/label
res (simple string) : the desired resolution controlling when a new line will start
tag (simple string) : the text for the lable
xColor (simple color) : the color for the label
xStyle (simple string) : the style for the line
xWidth (simple int) : the width of the line
xExtend (simple string) : extend the line
isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
xLabelOffset (int)
validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
drawPivot(pivotLevel, res, tag, pivotColor, pivotLabelColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid, validTimeFrame, levelStart, pivotLabelXOffset)
draw a pivot line - the line starts one day into the past
Parameters:
pivotLevel (float) : series of the pivot point
res (simple string) : the desired resolution
tag (simple string) : the text to appear
pivotColor (simple color) : the color of the line
pivotLabelColor (simple color) : the color of the label
pivotStyle (simple string) : the line style
pivotWidth (simple int) : the line width
pivotExtend (simple string) : extend the line
isLabelValid (simple bool) : boolean param allows to turn label on and off
validTimeFrame (simple bool) : only draw the line and label at a valid timeframe
levelStart (int) : basically when to start drawing the levels
pivotLabelXOffset (int) : how much to offset the label from its current postion
@return the pivot line series
getPvsraFlagByColor(pvsraColor, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, lightGrayCandleColor)
convert the pvsra color to an internal code
Parameters:
pvsraColor (color) : the calculated pvsra color
redVectorColor (simple color) : the user defined red vector color
greenVectorColor (simple color) : the user defined green vector color
violetVectorColor (simple color) : the user defined violet vector color
blueVectorColor (simple color) : the user defined blue vector color
lightGrayCandleColor (simple color) : the user defined regular up candle color
@return pvsra internal code
updateZones(pvsra, direction, boxArr, maxlevels, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneupdatetype, zonecolor, zonetype, borderwidth, coloroverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor)
a function that draws the unrecovered vector candle zones
Parameters:
pvsra (int) : internal code
direction (simple int) : above or below the current pa
boxArr (array) : the array containing the boxes that need to be updated
maxlevels (simple int) : the maximum number of boxes to draw
pvsraHigh (float) : the pvsra high value series
pvsraLow (float) : the pvsra low value series
pvsraOpen (float) : the pvsra open value series
pvsraClose (float) : the pvsra close value series
transperancy (simple int) : the transparencfy of the vecor candle zones
zoneupdatetype (simple string) : the zone update type
zonecolor (simple color) : the zone color if overriden
zonetype (simple string) : the zone type
borderwidth (simple int) : the width of the border
coloroverride (simple bool) : if the color overriden
redVectorColor (simple color) : the user defined red vector color
greenVectorColor (simple color) : the user defined green vector color
violetVectorColor (simple color) : the user defined violet vector color
blueVectorColor (simple color) : the user defined blue vector color
cleanarr(arr)
clean an array from na values
Parameters:
arr (array) : the array to clean
@return if the array was cleaned
calcPsyLevels(oneWeekMillis, showPsylevels, psyType, sydDST)
calculate the psy levels
4 hour res based on how mt4 does it
mt4 code
int Li_4 = iBarShift(NULL, PERIOD_H4, iTime(NULL, PERIOD_W1, Li_0)) - 2 - Offset;
ObjectCreate("PsychHi", OBJ_TREND, 0, Time , iHigh(NULL, PERIOD_H4, iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)), iTime(NULL, PERIOD_W1, 0), iHigh(NULL, PERIOD_H4,
iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)));
so basically because the session is 8 hours and we are looking at a 4 hour resolution we only need to take the highest high an lowest low of 2 bars
we use the gmt offset to adjust the 0000-0800 session to Sydney open which is at 2100 during dst and at 2200 otherwize. (dst - spring foward, fall back)
keep in mind sydney is in the souther hemisphere so dst is oposite of when london and new york go into dst
Parameters:
oneWeekMillis (simple int) : a constant value
showPsylevels (simple bool) : should psy levels be calculated
psyType (simple string) : the type of Psylevels - crypto or forex
sydDST (bool) : is Sydney in DST
@return
adrHiLo(length, barsBack, fromDO)
Parameters:
length (simple int) : how many elements of the series to calculate on
barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
fromDO (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adr, adrLow and adrHigh - the adr, the position of the adr High and adr Low with respect to price
drawSessionHiloLite(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle, sessXcol)
Parameters:
sessXTime (simple string) : session string in the format 0000-0100:23456
showRectangleX (simple bool)
showLabelX (simple bool)
sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
sessXLabel (simple string) : the session label text
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
sessionLineStyle (simple string) : the line stile for the session high low lines
sessXcol (simple color) : - the color for the box color that will color the session
@return void
msToHmsString(ms)
converts milliseconds into an hh:mm string. For example, 61000 ms to '0:01:01'
Parameters:
ms (int) : - the milliseconds to convert to hh:mm
@return string - the converted hh:mm string
countdownString(openToday, closeToday, showMarketsWeekends, oneDay)
that calculates how much time is left until the next session taking the session start and end times into account. Note this function does not work on intraday sessions.
Parameters:
openToday (int) : - timestamps of when the session opens in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
closeToday (int) : - timestamp of when the session closes in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
@return a countdown of when next the session opens or 'Open' if the session is open now
showMarketsWeekends (simple bool)
oneDay (simple int)
countdownStringSyd(sydOpenToday, sydCloseToday, showMarketsWeekends, oneDay)
that calculates how much time is left until the next session taking the session start and end times into account. special case of intraday sessions like sydney
Parameters:
sydOpenToday (int)
sydCloseToday (int)
showMarketsWeekends (simple bool)
oneDay (simple int)
Market Structure Report Library [TradingFinder]🔵 Introduction
Market Structure is one of the most fundamental concepts in Price Action and Smart Money theory. In simple terms, it represents how price moves between highs and lows and reveals which phase of the market cycle we are currently in uptrend, downtrend, or transition.
Each structure in the market is formed by a combination of Breaks of Structure (BoS) and Changes of Character (CHoCH) :
BoS occurs when the market breaks a previous high or low, confirming the continuation of the current trend.
CHoCH occurs when price breaks in the opposite direction for the first time, signaling a potential trend reversal.
Since price movement is inherently fractal, market structure can be analyzed on two distinct levels :
Major / External Structure: represents the dominant macro trend.
Minor / Internal Structure: represents corrective or smaller-scale movements within the larger trend.
🔵 Library Purpose
The “Market Structure Report Library” is designed to automatically detect the current market structure type in real time.
Without drawing or displaying any visuals, it analyzes raw price data and returns a series of logical and textual outputs (Return Values) that describe the current structural state of the market.
It provides the following information :
Trend Type :
External Trend (Major): Up Trend, Down Trend, No Trend
Internal Trend (Minor): Up Trend, Down Trend, No Trend
Structure Type :
BoS : Confirms trend continuation
CHoCH : Indicates a potential trend reversal
Consecutive BoS Counter : Measures trend strength on both Major and Minor levels.
Candle Type : Returns the current candle’s condition(Bullish, Bearish, Doji)
This library is specifically designed for use in Smart Money–based screeners, indicators, and algorithmic strategies.
It can analyze multiple symbols and timeframes simultaneously and return the exact structure type (BoS or CHoCH) and trend direction for each.
🔵 Function Outputs
The function MS() processes the price data and returns seven key outputs,
each representing a distinct structural state of the market. These values can be used in indicators, strategies, or multi-symbol screeners.
🟣 ExternalTrend
Type : string
Description : Represents the direction of the Major (External) market structure.
Possible values :
Up Trend
Down Trend
No Trend
This is determined based on the behavior of Major Pivots (swing highs/lows).
🟣 InternalTrend
Type : string
Description : Represents the direction of the Minor (Internal) market structure.
Possible values :
Up Trend
Down Trend
No Trend
🟣 M_State
Type : string
Description : Specifies the type of the latest Major Structure event.
Possible values :
BoS
CHoCH
🟣 m_State
Type : string
Description : Specifies the type of the latest Minor Structure event.
Possible values :
BoS
CHoCH
🟣 MBoS_Counter
Type : integer
Description : Counts the number of consecutive structural breaks (BoS) in the Major structure.
Useful for evaluating trend strength :
Increasing count: indicates trend continuation.
Reset to zero: typically occurs after a CHoCH.
🟣 mBoS_Counter
Type : integer
Description : Counts the number of consecutive structural breaks in the Minor structure.
Helps analyze the micro structure of the market on lower timeframes.
Higher value : strong internal trend.
Reset : indicates a minor pullback or reversal.
🟣 Candle_Type
Type : string
Description : Represents the type of the current candle.
Possible values :
Bullish
Bearish
Doji
import TFlab/Market_Structure_Report_Library_TradingFinder/1 as MSS
PP = input.int (5 , 'Market Structure Pivot Period' , group = 'Symbol 1' )
= MSS.MS(PP)
SequencerLibraryLibrary "SequencerLibrary"
SequencerLibrary v1 is a Pine Script™ library for identifying, tracking, and visualizing
sequential bullish and bearish patterns on price charts.
It provides a complete framework for building sequence-based trading systems, including:
• Automatic detection and counting of setup and countdown phases.
• Real-time tracking of completion states, perfected setups, and exhaustion signals.
• Dynamic support and resistance thresholds derived from recent price structure.
• Customizable visual highlighting for both setup and countdown sequences.
method doSequence(s, src, config, condition)
Updates the sequence state based on the source value, and user configuration.
Namespace types: Sequence
Parameters:
s (Sequence) : The sequence object containing bullish and bearish setups.
src (float) : The source value (e.g., close price) used for evaluating sequence conditions.
config (SequenceInputs) : The user-defined settings for sequence analysis.
condition (bool) : When true, executes the sequence logic.
Returns:
highlight(s, css, condition)
Highlights the bullish and bearish sequence setups and countdowns on the chart.
Parameters:
s (Sequence) : The sequence object containing bullish and bearish sequence states.
css (SequenceCSS) : The styling configuration for customizing label appearances.
condition (bool) : When true, the function creates and displays labels for setups and countdowns.
Returns:
SequenceState
A type representing the configuration and state of a sequence setup.
Fields:
setup (series int) : Current count of the setup phase (e.g., how many bars have met the setup criteria).
countdown (series int) : Current count of the countdown phase (e.g., bars meeting countdown criteria).
threshold (series float) : The price threshold level used as support/resistance for the sequence.
priceWhenCompleted (series float) : The closing price when the setup or countdown phase is completed.
indicatorWhenCompleted (series float) : The indicator value when the setup or countdown phase is completed.
setupCompleted (series bool) : Indicates if the setup phase has been completed (i.e., reached the required count).
countdownCompleted (series bool) : Indicates if the countdown phase has been completed (i.e., reached exhaustion).
perfected (series bool) : Indicates if the setup meets the "perfected" condition (e.g., aligns with strict criteria).
highlightSetup (series bool) : Determines whether the setup phase should be visually highlighted on the chart.
highlightCountdown (series bool) : Determines whether the countdown phase should be visually highlighted on the chart.
Sequence
A type containing bullish and bearish sequence setups.
Fields:
bullish (SequenceState) : Configuration and state for bullish sequences.
bearish (SequenceState) : Configuration and state for bearish sequences.
SequenceInputs
A type for user-configurable input settings for sequence-based analysis.
Fields:
showSetup (series bool) : Enables or disables the display of setup sequences.
showCountdown (series bool) : Enables or disables the display of countdown sequences.
setupFilter (series string) : A comma‐separated string containing setup sequence counts to be highlighted (e.g., "1,2,3,4,5,6,7,8,9").
countdownFilter (series string) : A comma‐separated string containing countdown sequence counts to be highlighted (e.g., "1,2,3,4,5,6,7,8,9,10,11,12,13").
lookbackSetup (series int) : Defines the lookback period for evaluating setup conditions (default: 4 bars).
lookbackCountdown (series int) : Defines the lookback period for evaluating countdown conditions (default: 2 bars).
lookbackSetupPerfected (series int) : Defines the lookback period to determine a perfected setup condition (default: 6 bars).
maxSetup (series int) : The maximum count required to complete a setup phase (default: 9).
maxCountdown (series int) : The maximum count required to complete a countdown phase (default: 13).
SequenceCSS
A type defining the visual styling options for sequence labels.
Fields:
bullish (series color) : Color used for bullish sequence labels.
bearish (series color) : Color used for bearish sequence labels.
imperfect (series color) : Color used for labels representing imperfect sequences.
GBB_lib_utilsLibrary "GBB_lib_utils"
gbb_moving_average_source(_source, _length, _ma_type)
gbb_moving_average_source
@description Calculates the moving average of a source series.
Parameters:
_source (float) : (series float)
_length (simple int) : (int)
_ma_type (string) : (string)
Returns: (series) Moving average series
gbb_tf_to_display(tf_minutes, tf_string)
gbb_tf_to_display
@description Converts minutes and TF string into a short standard label.
Parameters:
tf_minutes (float) : (float)
tf_string (string) : (string)
Returns: (string) Timeframe label (M1,H1,D1,...)
gbb_convert_bars(_bars)
gbb_convert_bars
@description Formats a number of bars into a duration (days, hours, minutes + bar count).
Parameters:
_bars (int) : (int)
Returns: (string)
gbb_goldorak_init(_tf5Levels_input)
gbb_goldorak_init
@description Builds a contextual message about the current timeframe and optional 5-level TF.
Parameters:
_tf5Levels_input (string) : (string) Alternative timeframe ("" = current timeframe).
Returns: (string, string, float)
CarolTradeLibLibrary "CarolTradeLib"
f_generateSignalID(strategyName)
Parameters:
strategyName (string)
f_buildJSON(orderType, action, symbol, price, strategyName, apiKey, additionalFields, indicatorJSON)
Parameters:
orderType (string)
action (string)
symbol (string)
price (float)
strategyName (string)
apiKey (string)
additionalFields (string)
indicatorJSON (string)
sendSignal(action, symbol, price, strategyName, apiKey, indicatorJSON)
Parameters:
action (string)
symbol (string)
price (float)
strategyName (string)
apiKey (string)
indicatorJSON (string)
marketOrder(action, symbol, price, strategyName, apiKey, stopLoss, takeProfit, rrRatio, size, indicatorJSON)
Parameters:
action (string)
symbol (string)
price (float)
strategyName (string)
apiKey (string)
stopLoss (float)
takeProfit (float)
rrRatio (float)
size (float)
indicatorJSON (string)
limitOrder(action, symbol, price, strategyName, apiKey, limitPrice, size, indicatorJSON)
Parameters:
action (string)
symbol (string)
price (float)
strategyName (string)
apiKey (string)
limitPrice (float)
size (float)
indicatorJSON (string)
stopLimitOrder(action, symbol, price, strategyName, apiKey, stopPrice, limitPrice, size, indicatorJSON)
Parameters:
action (string)
symbol (string)
price (float)
strategyName (string)
apiKey (string)
stopPrice (float)
limitPrice (float)
size (float)
indicatorJSON (string)






















