Wskaźniki i strategie
OverfittingMetricsLibrary "OverfittingMetrics"
calculateMetrics(tradeResults, tradeTypes, minTrades, startCapital)
Parameters:
tradeResults (array)
tradeTypes (array)
minTrades (int)
startCapital (float)
randomizeParameter(baseValue, variationPercent, seed)
Parameters:
baseValue (float)
variationPercent (float)
seed (int)
classifyMarket(priceSeries, lookbackLength)
Parameters:
priceSeries (float)
lookbackLength (simple int)
checkOverfittingWarnings(winRate, profitFactor, totalTrades)
Parameters:
winRate (float)
profitFactor (float)
totalTrades (int)
calculateConsistency(tradeResults)
Parameters:
tradeResults (array)
isOverfitDetected(winRate, profitFactor, totalTrades, minTrades)
Parameters:
winRate (float)
profitFactor (float)
totalTrades (int)
minTrades (int)
getOverfitScore(winRate, profitFactor, totalTrades)
Parameters:
winRate (float)
profitFactor (float)
totalTrades (int)
TrinityCoreLibrary "TrinityCore"
TRINITY STRATEGY CORE v1.10 (Golden Master)
calc_target_weights(_stk_c, _vol_tgt)
Parameters:
_stk_c (float)
_vol_tgt (simple float)
TrinityWeights
Fields:
stock (series float)
s1 (series float)
s2 (series float)
s3 (series float)
cash (series float)
PineStats█ OVERVIEW
PineStats is a comprehensive statistical analysis library for Pine Script v6, providing 104 functions across 6 modules. Built for quantitative traders, researchers, and indicator developers who need professional-grade statistics without reinventing the wheel.
For building mean-reversion strategies, analyzing return distributions, measuring correlations, or testing for market regimes.
█ MODULES
CORE STATISTICS (20 functions)
• Central tendency: mean, median, WMA, EMA
• Dispersion: variance, stdev, MAD, range
• Standardization: z-score, robust z-score, normalize, percentile
• Distribution shape: skewness, kurtosis
PROBABILITY DISTRIBUTIONS (17 functions)
• Normal: PDF, CDF, inverse CDF (quantile function)
• Power-law: Hill estimator, MLE alpha, survival function
• Exponential: PDF, CDF, rate estimation
• Normality testing: Jarque-Bera test
ENTROPY (9 functions)
• Shannon entropy (information theory)
• Tsallis entropy (non-extensive, fat-tail sensitive)
• Permutation entropy (ordinal patterns)
• Approximate entropy (regularity measure)
• Entropy-based regime detection
PROBABILITY (21 functions)
• Win rates and expected value
• First passage time estimation
• TP/SL probability analysis
• Conditional probability and Bayes updates
• Streak and drawdown probabilities
REGRESSION (19 functions)
• Linear regression: slope, intercept, forecast
• Goodness of fit: R², adjusted R², standard error
• Statistical tests: t-statistic, p-value, significance
• Trend analysis: strength, angle, acceleration
• Quadratic regression
CORRELATION (18 functions)
• Pearson, Spearman, Kendall correlation
• Covariance, beta, alpha (Jensen's)
• Rolling correlation analysis
• Autocorrelation and cross-correlation
• Information ratio, tracking error
█ QUICK START
import HenriqueCentieiro/PineStats/1 as stats
// Z-score for mean reversion
z = stats.zscore(close, 20)
// Test if returns are normally distributed
returns = (close - close ) / close
isGaussian = stats.is_normal(returns, 100, 0.05)
// Regression channel
= stats.linreg_channel(close, 50, 2.0)
// Correlation with benchmark
spyReturns = request.security("SPY", timeframe.period, close/close - 1)
beta = stats.beta(returns, spyReturns, 60)
█ USE CASES
✓ Mean Reversion — z-scores, percentiles, Bollinger-style analysis
✓ Regime Detection — entropy measures, correlation regimes
✓ Risk Analysis — drawdown probability, VaR via quantiles
✓ Strategy Evaluation — expected value, win rates, R:R analysis
✓ Distribution Analysis — normality tests, fat-tail detection
✓ Multi-Asset — beta, alpha, correlation, relative strength
█ NOTES
• All functions return `na` on invalid inputs
• Designed for Pine Script v6
• Fully documented in the library header
• Part of the Pine ecosystem: PineStats, PineQuant, PineCriticality, PineWavelet
█ REFERENCES
• Abramowitz & Stegun — Normal CDF approximation
• Acklam's algorithm — Inverse normal CDF
• Hill estimator — Power-law tail estimation
• Tsallis statistics — Non-extensive entropy
Full documentation in the library header.
mean(src, length)
Calculates the arithmetic mean (simple moving average) over a lookback period
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Arithmetic mean of the last `length` values, or `na` if inputs invalid
wma_custom(src, length)
Calculates weighted moving average with linearly decreasing weights
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Weighted moving average, or `na` if inputs invalid
ema_custom(src, length)
Calculates exponential moving average
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Exponential moving average, or `na` if inputs invalid
median(src, length)
Calculates the median value over a lookback period
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Median value, or `na` if inputs invalid
variance(src, length)
Calculates population variance over a lookback period
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Population variance, or `na` if inputs invalid
stdev(src, length)
Calculates population standard deviation over a lookback period
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Population standard deviation, or `na` if inputs invalid
mad(src, length)
Calculates Median Absolute Deviation (MAD) - robust dispersion measure
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: MAD value, or `na` if inputs invalid
data_range(src, length)
Calculates the range (highest - lowest) over a lookback period
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Range value, or `na` if inputs invalid
zscore(src, length)
Calculates z-score (number of standard deviations from mean)
Parameters:
src (float) : Source series
length (simple int) : Lookback period for mean and stdev calculation (must be >= 2)
Returns: Z-score, or `na` if inputs invalid or stdev is zero
zscore_robust(src, length)
Calculates robust z-score using median and MAD (resistant to outliers)
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 2)
Returns: Robust z-score, or `na` if inputs invalid or MAD is zero
normalize(src, length)
Normalizes value to range using min-max scaling
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Normalized value in , or `na` if inputs invalid or range is zero
percentile(src, length)
Calculates percentile rank of current value within lookback window
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Percentile rank (0 to 100), or `na` if inputs invalid
winsorize(src, length, lower_pct, upper_pct)
Winsorizes values by clamping to percentile bounds (reduces outlier impact)
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
lower_pct (simple float) : Lower percentile bound (0-100, e.g., 5 for 5th percentile)
upper_pct (simple float) : Upper percentile bound (0-100, e.g., 95 for 95th percentile)
Returns: Winsorized value clamped to bounds
skewness(src, length)
Calculates sample skewness (measure of distribution asymmetry)
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 3)
Returns: Skewness value (negative = left tail, positive = right tail), or `na` if invalid
kurtosis(src, length)
Calculates excess kurtosis (measure of distribution tail heaviness)
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 4)
Returns: Excess kurtosis (>0 = heavy tails, <0 = light tails), or `na` if invalid
count_valid(src, length)
Counts non-na values in lookback window (useful for data quality checks)
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Count of valid (non-na) values
sum(src, length)
Calculates sum over lookback period
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 1)
Returns: Sum of values, or `na` if inputs invalid
cumsum(src)
Calculates cumulative sum (running total from first bar)
Parameters:
src (float) : Source series
Returns: Cumulative sum
change(src, length)
Returns the change (difference) from n bars ago
Parameters:
src (float) : Source series
length (simple int) : Number of bars to look back (must be >= 1)
Returns: Current value minus value from `length` bars ago
roc(src, length)
Calculates Rate of Change (percentage change from n bars ago)
Parameters:
src (float) : Source series
length (simple int) : Number of bars to look back (must be >= 1)
Returns: Percentage change as decimal (0.05 = 5%), or `na` if invalid
normal_pdf_standard(x)
Calculates the standard normal probability density function (PDF)
Parameters:
x (float) : The value to evaluate
Returns: PDF value at x for standard normal N(0,1)
normal_pdf(x, mu, sigma)
Calculates the normal probability density function (PDF)
Parameters:
x (float) : The value to evaluate
mu (float) : Mean of the distribution (default: 0)
sigma (float) : Standard deviation (default: 1, must be > 0)
Returns: PDF value at x for normal N(mu, sigma²)
normal_cdf_standard(x)
Calculates the standard normal cumulative distribution function (CDF)
Parameters:
x (float) : The value to evaluate
Returns: Probability P(X <= x) for standard normal N(0,1)
@description Uses Abramowitz & Stegun approximation (formula 7.1.26), accurate to ~1.5e-7
normal_cdf(x, mu, sigma)
Calculates the normal cumulative distribution function (CDF)
Parameters:
x (float) : The value to evaluate
mu (float) : Mean of the distribution (default: 0)
sigma (float) : Standard deviation (default: 1, must be > 0)
Returns: Probability P(X <= x) for normal N(mu, sigma²)
normal_inv_standard(p)
Calculates the inverse standard normal CDF (quantile function)
Parameters:
p (float) : Probability value (must be in (0, 1))
Returns: x such that P(X <= x) = p for standard normal N(0,1)
@description Uses Acklam's algorithm, accurate to ~1.15e-9
normal_inv(p, mu, sigma)
Calculates the inverse normal CDF (quantile function)
Parameters:
p (float) : Probability value (must be in (0, 1))
mu (float) : Mean of the distribution
sigma (float) : Standard deviation (must be > 0)
Returns: x such that P(X <= x) = p for normal N(mu, sigma²)
power_law_alpha(src, length, tail_pct)
Estimates power-law exponent (alpha) using Hill estimator
Parameters:
src (float) : Source series (typically absolute returns or drawdowns)
length (simple int) : Lookback period (must be >= 10 for reliable estimates)
tail_pct (simple float) : Percentage of data to use for tail estimation (default: 0.1 = top 10%)
Returns: Estimated alpha (tail index), typically 2-4 for financial data
@description Alpha < 2 indicates infinite variance (very heavy tails)
@description Alpha < 3 indicates infinite kurtosis
@description Alpha > 4 suggests near-Gaussian behavior
power_law_alpha_mle(src, length, x_min)
Estimates power-law alpha using maximum likelihood (Clauset method)
Parameters:
src (float) : Source series (positive values expected)
length (simple int) : Lookback period (must be >= 20)
x_min (float) : Minimum threshold for power-law behavior
Returns: Estimated alpha using MLE
power_law_pdf(x, alpha, x_min)
Calculates power-law probability density (Pareto Type I)
Parameters:
x (float) : Value to evaluate (must be >= x_min)
alpha (float) : Power-law exponent (must be > 1)
x_min (float) : Minimum value / scale parameter (must be > 0)
Returns: PDF value
power_law_survival(x, alpha, x_min)
Calculates power-law survival function P(X > x)
Parameters:
x (float) : Value to evaluate (must be >= x_min)
alpha (float) : Power-law exponent (must be > 1)
x_min (float) : Minimum value / scale parameter (must be > 0)
Returns: Probability of exceeding x
power_law_ks(src, length, alpha, x_min)
Tests if data follows power-law using simplified Kolmogorov-Smirnov
Parameters:
src (float) : Source series
length (simple int) : Lookback period
alpha (float) : Estimated alpha from power_law_alpha()
x_min (float) : Threshold value
Returns: KS statistic (lower = better fit, typically < 0.1 for good fit)
is_power_law(src, length, tail_pct, ks_threshold)
Simple test if distribution appears to follow power-law
Parameters:
src (float) : Source series
length (simple int) : Lookback period
tail_pct (simple float) : Tail percentage for alpha estimation
ks_threshold (simple float) : Maximum KS statistic for acceptance (default: 0.1)
Returns: true if KS test suggests power-law fit
exp_pdf(x, lambda)
Calculates exponential probability density function
Parameters:
x (float) : Value to evaluate (must be >= 0)
lambda (float) : Rate parameter (must be > 0)
Returns: PDF value
exp_cdf(x, lambda)
Calculates exponential cumulative distribution function
Parameters:
x (float) : Value to evaluate (must be >= 0)
lambda (float) : Rate parameter (must be > 0)
Returns: Probability P(X <= x)
exp_lambda(src, length)
Estimates exponential rate parameter (lambda) using MLE
Parameters:
src (float) : Source series (positive values)
length (simple int) : Lookback period
Returns: Estimated lambda (1/mean)
jarque_bera(src, length)
Calculates Jarque-Bera test statistic for normality
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 10)
Returns: JB statistic (higher = more deviation from normality)
@description Under normality, JB ~ chi-squared(2). JB > 6 suggests non-normality at 5% level
is_normal(src, length, significance)
Tests if distribution is approximately normal
Parameters:
src (float) : Source series
length (simple int) : Lookback period
significance (simple float) : Significance level (default: 0.05)
Returns: true if Jarque-Bera test does not reject normality
shannon_entropy(src, length, n_bins)
Calculates Shannon entropy from a probability distribution
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 10)
n_bins (simple int) : Number of histogram bins for discretization (default: 10)
Returns: Shannon entropy in bits (log base 2)
@description Higher entropy = more randomness/uncertainty, lower = more predictability
shannon_entropy_norm(src, length, n_bins)
Calculates normalized Shannon entropy
Parameters:
src (float) : Source series
length (simple int) : Lookback period
n_bins (simple int) : Number of histogram bins
Returns: Normalized entropy where 0 = perfectly predictable, 1 = maximum randomness
tsallis_entropy(src, length, q, n_bins)
Calculates Tsallis entropy with q-parameter
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 10)
q (float) : Entropic index (q=1 recovers Shannon entropy)
n_bins (simple int) : Number of histogram bins
Returns: Tsallis entropy value
@description q < 1: emphasizes rare events (fat tails)
@description q = 1: equivalent to Shannon entropy
@description q > 1: emphasizes common events
optimal_q(src, length)
Estimates optimal q parameter from kurtosis
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Estimated q value that best captures the distribution's tail behavior
@description Uses relationship: q ≈ (5 + kurtosis) / (3 + kurtosis) for kurtosis > 0
tsallis_q_gaussian(x, q, beta)
Calculates Tsallis q-Gaussian probability density
Parameters:
x (float) : Value to evaluate
q (float) : Tsallis q parameter (must be < 3)
beta (float) : Width parameter (inverse temperature, must be > 0)
Returns: q-Gaussian PDF value
@description q=1 recovers standard Gaussian
permutation_entropy(src, length, order)
Calculates permutation entropy (ordinal pattern complexity)
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 20)
order (simple int) : Embedding dimension / pattern length (2-5, default: 3)
Returns: Normalized permutation entropy
@description Measures complexity of temporal ordering patterns
@description 0 = perfectly predictable sequence, 1 = random
approx_entropy(src, length, m, r)
Calculates Approximate Entropy (ApEn) - regularity measure
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 50)
m (simple int) : Embedding dimension (default: 2)
r (simple float) : Tolerance as fraction of stdev (default: 0.2)
Returns: Approximate entropy value (higher = more irregular/complex)
@description Lower ApEn indicates more self-similarity and predictability
entropy_regime(src, length, q, n_bins)
Detects market regime based on entropy level
Parameters:
src (float) : Source series (typically returns)
length (simple int) : Lookback period
q (float) : Tsallis q parameter (use optimal_q() or default 1.5)
n_bins (simple int) : Number of histogram bins
Returns: Regime indicator: -1 = trending (low entropy), 0 = transition, 1 = ranging (high entropy)
entropy_risk(src, length)
Calculates entropy-based risk indicator
Parameters:
src (float) : Source series (typically returns)
length (simple int) : Lookback period
Returns: Risk score where 1 = maximum divergence from Gaussian 1
hit_rate(src, length)
Calculates hit rate (probability of positive outcome) over lookback
Parameters:
src (float) : Source series (positive values count as hits)
length (simple int) : Lookback period
Returns: Hit rate as decimal
hit_rate_cond(condition, length)
Calculates hit rate for custom condition over lookback
Parameters:
condition (bool) : Boolean series (true = hit)
length (simple int) : Lookback period
Returns: Hit rate as decimal
expected_value(src, length)
Calculates expected value of a series
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Expected value (mean)
expected_value_trade(win_prob, take_profit, stop_loss)
Calculates expected value for a trade with TP and SL levels
Parameters:
win_prob (float) : Probability of hitting TP (0-1)
take_profit (float) : Take profit in price units or %
stop_loss (float) : Stop loss in price units or % (positive value)
Returns: Expected value per trade
@description EV = (win_prob * TP) - ((1 - win_prob) * SL)
breakeven_winrate(take_profit, stop_loss)
Calculates breakeven win rate for given TP/SL ratio
Parameters:
take_profit (float) : Take profit distance
stop_loss (float) : Stop loss distance
Returns: Required win rate for breakeven (EV = 0)
reward_risk_ratio(take_profit, stop_loss)
Calculates the reward-to-risk ratio
Parameters:
take_profit (float) : Take profit distance
stop_loss (float) : Stop loss distance
Returns: R:R ratio
fpt_probability(src, length, target, max_bars)
Estimates probability of price reaching target within N bars
Parameters:
src (float) : Source series (typically returns)
length (simple int) : Lookback for volatility estimation
target (float) : Target move (in same units as src, e.g., % return)
max_bars (simple int) : Maximum bars to consider
Returns: Probability of reaching target within max_bars
@description Based on random walk with drift approximation
fpt_mean(src, length, target)
Estimates mean first passage time to target level
Parameters:
src (float) : Source series (typically returns)
length (simple int) : Lookback for volatility estimation
target (float) : Target move
Returns: Expected number of bars to reach target (can be infinite)
fpt_historical(src, length, target)
Counts historical bars to reach target from each point
Parameters:
src (float) : Source series (typically price or returns)
length (simple int) : Lookback period
target (float) : Target move from each starting point
Returns: Array of first passage times (na if target not reached within lookback)
tp_probability(src, length, tp_distance, sl_distance)
Estimates probability of hitting TP before SL
Parameters:
src (float) : Source series (typically returns)
length (simple int) : Lookback for estimation
tp_distance (float) : Take profit distance (positive)
sl_distance (float) : Stop loss distance (positive)
Returns: Probability of TP being hit first
trade_probability(src, length, tp_pct, sl_pct)
Calculates complete trade probability and EV analysis
Parameters:
src (float) : Source series (typically returns)
length (simple int) : Lookback period
tp_pct (float) : Take profit percentage
sl_pct (float) : Stop loss percentage
Returns: Tuple:
cond_prob(condition_a, condition_b, length)
Calculates conditional probability P(B|A) from historical data
Parameters:
condition_a (bool) : Condition A (the given condition)
condition_b (bool) : Condition B (the outcome)
length (simple int) : Lookback period
Returns: P(B|A) = P(A and B) / P(A)
bayes_update(prior, likelihood, false_positive)
Updates probability using Bayes' theorem
Parameters:
prior (float) : Prior probability P(H)
likelihood (float) : P(E|H) - probability of evidence given hypothesis
false_positive (float) : P(E|~H) - probability of evidence given hypothesis is false
Returns: Posterior probability P(H|E)
streak_prob(win_rate, streak_length)
Calculates probability of N consecutive wins given win rate
Parameters:
win_rate (float) : Single-trade win probability
streak_length (simple int) : Number of consecutive wins
Returns: Probability of streak
losing_streak_prob(win_rate, streak_length)
Calculates probability of experiencing N consecutive losses
Parameters:
win_rate (float) : Single-trade win probability
streak_length (simple int) : Number of consecutive losses
Returns: Probability of losing streak
drawdown_prob(src, length, dd_threshold)
Estimates probability of drawdown exceeding threshold
Parameters:
src (float) : Source series (returns)
length (simple int) : Lookback period
dd_threshold (float) : Drawdown threshold (as positive decimal, e.g., 0.10 = 10%)
Returns: Historical probability of exceeding drawdown threshold
prob_to_odds(prob)
Calculates odds from probability
Parameters:
prob (float) : Probability (0-1)
Returns: Odds (prob / (1 - prob))
odds_to_prob(odds)
Calculates probability from odds
Parameters:
odds (float) : Odds ratio
Returns: Probability (0-1)
implied_prob(decimal_odds)
Calculates implied probability from decimal odds (betting)
Parameters:
decimal_odds (float) : Decimal odds (e.g., 2.5 means $2.50 return per $1 bet)
Returns: Implied probability
logit(prob)
Calculates log-odds (logit) from probability
Parameters:
prob (float) : Probability (must be in (0, 1))
Returns: Log-odds
inv_logit(log_odds)
Calculates probability from log-odds (inverse logit / sigmoid)
Parameters:
log_odds (float) : Log-odds value
Returns: Probability (0-1)
linreg_slope(src, length)
Calculates linear regression slope
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 2)
Returns: Slope coefficient (change per bar)
linreg_intercept(src, length)
Calculates linear regression intercept
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 2)
Returns: Intercept (predicted value at oldest bar in window)
linreg_value(src, length)
Calculates predicted value at current bar using linear regression
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Predicted value at current bar (end of regression line)
linreg_forecast(src, length, offset)
Forecasts value N bars ahead using linear regression
Parameters:
src (float) : Source series
length (simple int) : Lookback period for regression
offset (simple int) : Bars ahead to forecast (positive = future)
Returns: Forecasted value
linreg_channel(src, length, mult)
Calculates linear regression channel with bands
Parameters:
src (float) : Source series
length (simple int) : Lookback period
mult (simple float) : Standard deviation multiplier for bands
Returns: Tuple:
r_squared(src, length)
Calculates R-squared (coefficient of determination)
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: R² value where 1 = perfect linear fit
adj_r_squared(src, length)
Calculates adjusted R-squared (accounts for sample size)
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Adjusted R² value
std_error(src, length)
Calculates standard error of estimate (residual standard deviation)
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Standard error
residual(src, length)
Calculates residual at current bar
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Residual (actual - predicted)
residuals(src, length)
Returns array of all residuals in lookback window
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Array of residuals
t_statistic(src, length)
Calculates t-statistic for slope coefficient
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: T-statistic (slope / standard error of slope)
slope_pvalue(src, length)
Approximates p-value for slope t-test (two-tailed)
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Approximate p-value
is_significant(src, length, alpha)
Tests if regression slope is statistically significant
Parameters:
src (float) : Source series
length (simple int) : Lookback period
alpha (simple float) : Significance level (default: 0.05)
Returns: true if slope is significant at alpha level
trend_strength(src, length)
Calculates normalized trend strength based on R² and slope
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Trend strength where sign indicates direction
trend_angle(src, length)
Calculates trend angle in degrees
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Angle in degrees (positive = uptrend, negative = downtrend)
linreg_acceleration(src, length)
Calculates trend acceleration (second derivative)
Parameters:
src (float) : Source series
length (simple int) : Lookback period for each regression
Returns: Acceleration (change in slope)
linreg_deviation(src, length)
Calculates deviation from regression line in standard error units
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Deviation in standard error units (like z-score)
quadreg_coefficients(src, length)
Fits quadratic regression and returns coefficients
Parameters:
src (float) : Source series
length (simple int) : Lookback period (must be >= 4)
Returns: Tuple: for y = a*x² + b*x + c
quadreg_value(src, length)
Calculates quadratic regression value at current bar
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: Predicted value from quadratic fit
correlation(x, y, length)
Calculates Pearson correlation coefficient between two series
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period (must be >= 3)
Returns: Correlation coefficient
covariance(x, y, length)
Calculates sample covariance between two series
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period (must be >= 2)
Returns: Covariance value
beta(asset, benchmark, length)
Calculates beta coefficient (slope of regression of y on x)
Parameters:
asset (float) : Asset returns series
benchmark (float) : Benchmark returns series
length (simple int) : Lookback period
Returns: Beta coefficient
@description Beta = Cov(asset, benchmark) / Var(benchmark)
alpha(asset, benchmark, length, risk_free)
Calculates alpha (Jensen's alpha / intercept)
Parameters:
asset (float) : Asset returns series
benchmark (float) : Benchmark returns series
length (simple int) : Lookback period
risk_free (float) : Risk-free rate (default: 0)
Returns: Alpha value (excess return not explained by beta)
spearman(x, y, length)
Calculates Spearman rank correlation coefficient
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period (must be >= 3)
Returns: Spearman correlation
@description More robust to outliers than Pearson correlation
kendall_tau(x, y, length)
Calculates Kendall's tau rank correlation (simplified)
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period (must be >= 3)
Returns: Kendall's tau
correlation_change(x, y, length, change_period)
Calculates change in correlation over time
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period for correlation
change_period (simple int) : Period over which to measure change
Returns: Change in correlation
correlation_regime(x, y, length, ma_length)
Detects correlation regime based on level and stability
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period for correlation
ma_length (simple int) : Moving average length for smoothing
Returns: Regime: -1 = negative, 0 = uncorrelated, 1 = positive
correlation_stability(x, y, length, stability_length)
Calculates correlation stability (inverse of volatility)
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback for correlation
stability_length (simple int) : Lookback for stability calculation
Returns: Stability score where 1 = perfectly stable
relative_strength(asset, benchmark, length)
Calculates relative strength of asset vs benchmark
Parameters:
asset (float) : Asset price series
benchmark (float) : Benchmark price series
length (simple int) : Smoothing period
Returns: Relative strength ratio (normalized)
tracking_error(asset, benchmark, length)
Calculates tracking error (standard deviation of excess returns)
Parameters:
asset (float) : Asset returns
benchmark (float) : Benchmark returns
length (simple int) : Lookback period
Returns: Tracking error (annualize by multiplying by sqrt(252) for daily data)
information_ratio(asset, benchmark, length)
Calculates information ratio (risk-adjusted excess return)
Parameters:
asset (float) : Asset returns
benchmark (float) : Benchmark returns
length (simple int) : Lookback period
Returns: Information ratio
capture_ratio(asset, benchmark, length, up_capture)
Calculates up/down capture ratio
Parameters:
asset (float) : Asset returns
benchmark (float) : Benchmark returns
length (simple int) : Lookback period
up_capture (simple bool) : If true, calculate up capture; if false, down capture
Returns: Capture ratio
autocorrelation(src, length, lag)
Calculates autocorrelation at specified lag
Parameters:
src (float) : Source series
length (simple int) : Lookback period
lag (simple int) : Lag for autocorrelation (default: 1)
Returns: Autocorrelation at specified lag
partial_autocorr(src, length)
Calculates partial autocorrelation at lag 1
Parameters:
src (float) : Source series
length (simple int) : Lookback period
Returns: PACF at lag 1 (equals ACF at lag 1)
autocorr_test(src, length, max_lag)
Tests for significant autocorrelation (Ljung-Box inspired)
Parameters:
src (float) : Source series
length (simple int) : Lookback period
max_lag (simple int) : Maximum lag to test
Returns: Sum of squared autocorrelations (higher = more autocorrelation)
cross_correlation(x, y, length, lag)
Calculates cross-correlation at specified lag
Parameters:
x (float) : First series
y (float) : Second series (lagged)
length (simple int) : Lookback period
lag (simple int) : Lag to apply to y (positive = y leads x)
Returns: Cross-correlation at specified lag
cross_correlation_peak(x, y, length, max_lag)
Finds lag with maximum cross-correlation
Parameters:
x (float) : First series
y (float) : Second series
length (simple int) : Lookback period
max_lag (simple int) : Maximum lag to search (both directions)
Returns: Tuple:
colors_library# ColorsLibrary - PineScript v6
A comprehensive PineScript v6 library containing **10 color themes** and utility functions for TradingView.
---
## 📦 Installation
```pinescript
import TheTradingSpiderMan/colors_library/1 as CLR
```
---
## 🎨 All Available Color Themes (10)
### Default Theme (Green/Red - Classic Trading)
| Function | Description |
| ------------------ | --------------- |
| `defaultBull()` | Green (#26A69A) |
| `defaultBear()` | Red (#EF5350) |
| `defaultNeutral()` | Grey (#787B86) |
### Monochrome Theme (White/Grey/Black)
| Function | Description |
| --------------- | -------------------- |
| `monoBull()` | White (#FFFFFF) |
| `monoBear()` | Black (#000000) |
| `monoNeutral()` | Grey (#808080) |
| `monoLight()` | Light Grey (#C0C0C0) |
| `monoDark()` | Dark Grey (#404040) |
### Vaporwave Theme (Purple/Pink, Blue/Cyan)
| Function | Description |
| ---------------- | ----------------------- |
| `vaporBull()` | Cyan (#00FFFF) |
| `vaporBear()` | Magenta (#FF00FF) |
| `vaporNeutral()` | Grey (#787B86) |
| `vaporPurple()` | Purple (#9B59B6) |
| `vaporPink()` | Hot Pink (#FF6EC7) |
| `vaporBlue()` | Electric Blue (#0080FF) |
### Neon Theme (Bright Fluorescent Colors)
| Function | Description |
| --------------- | --------------------- |
| `neonBull()` | Neon Green (#39FF14) |
| `neonBear()` | Neon Red (#FF073A) |
| `neonNeutral()` | Grey (#787B86) |
| `neonYellow()` | Neon Yellow (#FFFF00) |
| `neonOrange()` | Neon Orange (#FF6600) |
| `neonBlue()` | Neon Blue (#00BFFF) |
### Ocean Theme (Blues and Teals)
| Function | Description |
| ---------------- | ------------------- |
| `oceanBull()` | Teal (#20B2AA) |
| `oceanBear()` | Deep Blue (#1E3A5F) |
| `oceanNeutral()` | Grey (#787B86) |
| `oceanAqua()` | Aqua (#00CED1) |
| `oceanNavy()` | Navy (#000080) |
| `oceanSeafoam()` | Seafoam (#3EB489) |
### Sunset Theme (Oranges, Yellows, Reds)
| Function | Description |
| ----------------- | ----------------------- |
| `sunsetBull()` | Golden Yellow (#FFD700) |
| `sunsetBear()` | Crimson (#DC143C) |
| `sunsetNeutral()` | Grey (#787B86) |
| `sunsetOrange()` | Orange (#FF8C00) |
| `sunsetCoral()` | Coral (#FF7F50) |
| `sunsetPurple()` | Twilight (#8B008B) |
### Forest Theme (Greens and Browns)
| Function | Description |
| ----------------- | ---------------------- |
| `forestBull()` | Forest Green (#228B22) |
| `forestBear()` | Brown (#8B4513) |
| `forestNeutral()` | Grey (#787B86) |
| `forestLime()` | Lime Green (#32CD32) |
| `forestOlive()` | Olive (#6B8E23) |
| `forestEarth()` | Earth Brown (#704214) |
### Candy Theme (Pastel/Soft Colors)
| Function | Description |
| ----------------- | -------------------- |
| `candyBull()` | Mint Green (#98FB98) |
| `candyBear()` | Soft Pink (#FFB6C1) |
| `candyNeutral()` | Grey (#787B86) |
| `candyLavender()` | Lavender (#E6E6FA) |
| `candyPeach()` | Peach (#FFDAB9) |
| `candySky()` | Sky Blue (#87CEEB) |
### Fire Theme (Reds, Oranges, Yellows)
| Function | Description |
| --------------- | ---------------------- |
| `fireBull()` | Flame Orange (#FF5722) |
| `fireBear()` | Dark Red (#B71C1C) |
| `fireNeutral()` | Grey (#787B86) |
| `fireYellow()` | Flame Yellow (#FFC107) |
| `fireEmber()` | Ember (#FF6F00) |
| `fireAsh()` | Ash Grey (#424242) |
### Ice Theme (Cool Blues and Whites)
| Function | Description |
| -------------- | ---------------------- |
| `iceBull()` | Ice Blue (#B3E5FC) |
| `iceBear()` | Frost Blue (#0277BD) |
| `iceNeutral()` | Grey (#787B86) |
| `iceWhite()` | Snow White (#F5F5F5) |
| `iceCrystal()` | Crystal Blue (#81D4FA) |
| `iceFrost()` | Frost (#4FC3F7) |
---
## 🔧 Selector & Utility Functions
| Function | Description |
| -------------------- | --------------------------------------------------- |
| `bullColor()` | Get bullish color by theme name |
| `bearColor()` | Get bearish color by theme name |
| `trendColor()` | Returns bull/bear color based on boolean condition |
| `gradientColor()` | Creates gradient between bull/bear (0-100 value) |
| `rsiGradient()` | RSI-style coloring (oversold=bull, overbought=bear) |
| `candleColor()` | Returns color based on candle direction |
| `volumeColor()` | Returns color based on close vs previous close |
| `withTransparency()` | Applies transparency to any color |
| `getAllThemes()` | Returns comma-separated list of all theme names |
| `getThemeOptions()` | Returns array of theme names for input options |
---
## 🔧 Usage Examples
### Basic Usage
```pinescript
//@version=6
indicator("Color Example")
import quantablex/colors_library/1 as CLR
// Direct color usage
plot(close, "Close", CLR.defaultBull())
plot(open, "Open", CLR.defaultBear())
// With transparency
plot(high, "High", CLR.vaporPurple(50))
```
### Using Theme Selector
```pinescript
//@version=6
indicator("Theme Selector")
import quantablex/colors_library/1 as CLR
theme = input.string("DEFAULT", "Color Theme",
options= )
bullCol = CLR.bullColor(theme)
bearCol = CLR.bearColor(theme)
plot(close, "Close", close >= open ? bullCol : bearCol)
```
### Trend Coloring
```pinescript
//@version=6
indicator("Trend Colors")
import quantablex/colors_library/1 as CLR
theme = input.string("VAPOR", "Theme")
ma = ta.ema(close, 20)
// Auto trend color based on condition
trendCol = CLR.trendColor(close > ma, theme)
plot(ma, "EMA", trendCol, 2)
```
### Gradient & RSI Coloring
```pinescript
//@version=6
indicator("Gradient Example")
import quantablex/colors_library/1 as CLR
rsi = ta.rsi(close, 14)
// Gradient based on RSI value
gradCol = CLR.gradientColor(rsi, "NEON")
plot(rsi, "RSI", gradCol)
// Or use built-in RSI gradient
rsiCol = CLR.rsiGradient(rsi, "DEFAULT")
bgcolor(rsiCol, transp=90)
```
### Candle & Volume Coloring
```pinescript
//@version=6
indicator("Candle Colors", overlay=true)
import quantablex/colors_library/1 as CLR
theme = input.string("FIRE", "Theme")
// Auto candle coloring
barcolor(CLR.candleColor(theme))
// Volume bars colored by direction
plotshape(volume, style=shape.circle, color=CLR.volumeColor(theme, 30))
```
---
## 🎨 Theme Selection Guide
| Use Case | Recommended Themes |
| --------------------- | --------------------- |
| **Classic Trading** | DEFAULT, MONO |
| **Dark Mode Charts** | NEON, VAPOR, ICE |
| **Light Mode Charts** | CANDY, SUNSET, FOREST |
| **High Visibility** | NEON, FIRE |
| **Low Eye Strain** | OCEAN, CANDY, ICE |
| **Professional Look** | MONO, DEFAULT, OCEAN |
| **Aesthetic/Stylish** | VAPOR, SUNSET, CANDY |
---
## ⚙️ Parameters Reference
### Common Parameters
- `transparency` - Transparency level (0-100, where 0=opaque, 100=invisible)
### Selector Parameters
- `theme` - Theme name string: `DEFAULT`, `MONO`, `VAPOR`, `NEON`, `OCEAN`, `SUNSET`, `FOREST`, `CANDY`, `FIRE`, `ICE`
---
## 📝 Notes
- All functions accept optional `transparency` parameter (default 0)
- Theme selector functions default to `DEFAULT` theme if invalid name provided
- Use `getAllThemes()` to get comma-separated list of all theme names
- Use `getThemeOptions()` to get array for `input.string` options
- All 50+ color functions are exported for direct use
---
**Author:** thetradingspiderman
**Version:** 1.0
**PineScript Version:** 6
**Total Themes:** 10
**Total Color Functions:** 50+
moving_averages# MovingAverages Library - PineScript v6
A comprehensive PineScript v6 library containing **50+ Moving Average calculations** for TradingView.
---
## 📦 Installation
```pinescript
import TheTradingSpiderMan/moving_averages/1 as MA
```
---
## 📊 All Available Moving Averages (50+)
### Basic Moving Averages
| Function | Selector Key | Description |
| -------- | ------------ | ------------------------------------------ |
| `sma()` | `SMA` | Simple Moving Average - arithmetic mean |
| `ema()` | `EMA` | Exponential Moving Average |
| `wma()` | `WMA` | Weighted Moving Average |
| `vwma()` | `VWMA` | Volume Weighted Moving Average |
| `rma()` | `RMA` | Relative/Smoothed Moving Average |
| `smma()` | `SMMA` | Smoothed Moving Average (alias for RMA) |
| `swma()` | - | Symmetrically Weighted MA (4-period fixed) |
### Hull Family
| Function | Selector Key | Description |
| -------- | ------------ | ------------------------------- |
| `hma()` | `HMA` | Hull Moving Average |
| `ehma()` | `EHMA` | Exponential Hull Moving Average |
### Double/Triple Smoothed
| Function | Selector Key | Description |
| -------------- | ------------ | --------------------------------- |
| `dema()` | `DEMA` | Double Exponential Moving Average |
| `tema()` | `TEMA` | Triple Exponential Moving Average |
| `tma()` | `TMA` | Triangular Moving Average |
| `t3()` | `T3` | Tillson T3 Moving Average |
| `twma()` | `TWMA` | Triple Weighted Moving Average |
| `swwma()` | `SWWMA` | Smoothed Weighted Moving Average |
| `trixSmooth()` | `TRIXSMOOTH` | Triple EMA Smoothed |
### Zero/Low Lag
| Function | Selector Key | Description |
| --------- | ------------ | ----------------------------------- |
| `zlema()` | `ZLEMA` | Zero Lag Exponential MA |
| `lsma()` | `LSMA` | Least Squares Moving Average |
| `epma()` | `EPMA` | Endpoint Moving Average |
| `ilrs()` | `ILRS` | Integral of Linear Regression Slope |
### Adaptive Moving Averages
| Function | Selector Key | Description |
| ---------- | ------------ | ------------------------------- |
| `kama()` | `KAMA` | Kaufman Adaptive Moving Average |
| `frama()` | `FRAMA` | Fractal Adaptive Moving Average |
| `vidya()` | `VIDYA` | Variable Index Dynamic Average |
| `vma()` | `VMA` | Variable Moving Average |
| `vama()` | `VAMA` | Volume Adjusted Moving Average |
| `rvma()` | `RVMA` | Rolling VMA |
| `apexMA()` | `APEXMA` | Apex Moving Average |
### Ehlers Filters
| Function | Selector Key | Description |
| ----------------- | --------------- | --------------------------------- |
| `superSmoother()` | `SUPERSMOOTHER` | Ehlers Super Smoother |
| `butterworth2()` | `BUTTERWORTH2` | 2-Pole Butterworth Filter |
| `butterworth3()` | `BUTTERWORTH3` | 3-Pole Butterworth Filter |
| `instantTrend()` | `INSTANTTREND` | Ehlers Instantaneous Trendline |
| `edsma()` | `EDSMA` | Deviation Scaled Moving Average |
| `mama()` | `MAMA` | Mesa Adaptive Moving Average |
| `fama()` | `FAMAVAL` | Following Adaptive Moving Average |
### Laguerre Family
| Function | Selector Key | Description |
| -------------------- | ------------------ | ------------------------ |
| `laguerreFilter()` | `LAGUERRE` | Laguerre Filter |
| `adaptiveLaguerre()` | `ADAPTIVELAGUERRE` | Adaptive Laguerre Filter |
### Special Weighted
| Function | Selector Key | Description |
| ---------- | ------------ | -------------------------------- |
| `alma()` | `ALMA` | Arnaud Legoux Moving Average |
| `sinwma()` | `SINWMA` | Sine Weighted Moving Average |
| `gwma()` | `GWMA` | Gaussian Weighted Moving Average |
| `nma()` | `NMA` | Natural Moving Average |
### Jurik/McGinley/Coral
| Function | Selector Key | Description |
| ------------ | ------------ | --------------------- |
| `jma()` | `JMA` | Jurik Moving Average |
| `mcginley()` | `MCGINLEY` | McGinley Dynamic |
| `coral()` | `CORAL` | Coral Trend Indicator |
### Mean Types
| Function | Selector Key | Description |
| -------------- | ------------ | ------------------------- |
| `medianMA()` | `MEDIANMA` | Median Moving Average |
| `gma()` | `GMA` | Geometric Moving Average |
| `harmonicMA()` | `HARMONICMA` | Harmonic Moving Average |
| `trimmedMA()` | `TRIMMEDMA` | Trimmed Moving Average |
| `cma()` | `CMA` | Cumulative Moving Average |
### Volume-Based
| Function | Selector Key | Description |
| --------- | ------------ | -------------------------- |
| `evwma()` | `EVWMA` | Elastic Volume Weighted MA |
### Other Specialized
| Function | Selector Key | Description |
| ----------------- | --------------- | --------------------------- |
| `hwma()` | `HWMA` | Holt-Winters Moving Average |
| `gdema()` | `GDEMA` | Generalized DEMA |
| `rema()` | `REMA` | Regularized EMA |
| `modularFilter()` | `MODULARFILTER` | Modular Filter |
| `rmt()` | `RMT` | Recursive Moving Trendline |
| `qrma()` | `QRMA` | Quadratic Regression MA |
| `wilderSmooth()` | `WILDERSMOOTH` | Welles Wilder Smoothing |
| `leoMA()` | `LEOMA` | Leo Moving Average |
| `ahrensMA()` | `AHRENSMA` | Ahrens Moving Average |
| `runningMA()` | `RUNNINGMA` | Running Moving Average |
| `ppoMA()` | `PPOMA` | PPO-based Moving Average |
| `fisherMA()` | `FISHERMA` | Fisher Transform MA |
---
## 🎯 Helper Functions
| Function | Description |
| ---------------- | ------------------------------------------------------------- |
| `wcp()` | Weighted Close Price: (H+L+2\*C)/4 |
| `typicalPrice()` | Typical Price: (H+L+C)/3 |
| `medianPrice()` | Median Price: (H+L)/2 |
| `selector()` | **Master selector** - choose any MA by string name |
| `getAllTypes()` | Returns all supported MA type names as comma-separated string |
---
## 🔧 Usage Examples
### Basic Usage
```pinescript
//@version=6
indicator("MA Example")
import quantablex/moving_averages/1 as MA
// Simple calls
plot(MA.sma(close, 20), "SMA 20", color.blue)
plot(MA.ema(close, 20), "EMA 20", color.red)
plot(MA.hma(close, 20), "HMA 20", color.green)
```
### Using the Selector Function (50+ MA Types)
```pinescript
//@version=6
indicator("MA Selector")
import quantablex/moving_averages/1 as MA
// Full list of all supported types:
// SMA,EMA,WMA,VWMA,RMA,SMMA,HMA,EHMA,DEMA,TEMA,TMA,T3,TWMA,SWWMA,TRIXSMOOTH,
// ZLEMA,LSMA,EPMA,ILRS,KAMA,FRAMA,VIDYA,VMA,VAMA,RVMA,APEXMA,SUPERSMOOTHER,
// BUTTERWORTH2,BUTTERWORTH3,INSTANTTREND,EDSMA,LAGUERRE,ADAPTIVELAGUERRE,
// ALMA,SINWMA,GWMA,NMA,JMA,MCGINLEY,CORAL,MEDIANMA,GMA,HARMONICMA,TRIMMEDMA,
// EVWMA,HWMA,GDEMA,REMA,MODULARFILTER,RMT,QRMA,WILDERSMOOTH,LEOMA,AHRENSMA,
// RUNNINGMA,PPOMA,MAMA,FAMAVAL,FISHERMA,CMA
maType = input.string("EMA", "MA Type", options= )
length = input.int(20, "Length")
plot(MA.selector(close, length, maType), "Selected MA", color.orange)
```
### Advanced Moving Averages
```pinescript
//@version=6
indicator("Advanced MAs")
import quantablex/moving_averages/1 as MA
// ALMA with custom offset and sigma
plot(MA.alma(close, 20, 0.85, 6), "ALMA", color.purple)
// KAMA with custom fast/slow periods
plot(MA.kama(close, 10, 2, 30), "KAMA", color.teal)
// T3 with custom volume factor
plot(MA.t3(close, 20, 0.7), "T3", color.yellow)
// Laguerre Filter with custom gamma
plot(MA.laguerreFilter(close, 0.8), "Laguerre", color.lime)
```
---
## 📈 MA Selection Guide
| Use Case | Recommended MAs |
| ---------------------- | ------------------------------------------- |
| **Trend Following** | EMA, DEMA, TEMA, HMA, CORAL |
| **Low Lag Required** | ZLEMA, HMA, EHMA, JMA, LSMA |
| **Volatile Markets** | KAMA, VIDYA, FRAMA, VMA, ADAPTIVELAGUERRE |
| **Smooth Signals** | T3, LAGUERRE, SUPERSMOOTHER, BUTTERWORTH2/3 |
| **Support/Resistance** | SMA, WMA, TMA, MEDIANMA |
| **Scalping** | MCGINLEY, ZLEMA, HMA, INSTANTTREND |
| **Noise Reduction** | MAMA, EDSMA, GWMA, TRIMMEDMA |
| **Volume-Based** | VWMA, EVWMA, VAMA |
---
## ⚙️ Parameters Reference
### Common Parameters
- `src` - Source series (close, open, hl2, hlc3, etc.)
- `len` - Period length (integer)
### Special Parameters
- `alma()`: `offset` (0-1), `sigma` (curve shape)
- `kama()`: `fastLen`, `slowLen`
- `t3()`: `vFactor` (volume factor)
- `jma()`: `phase` (-100 to 100)
- `laguerreFilter()`: `gamma` (0-1 damping)
- `rema()`: `lambda` (regularization)
- `modularFilter()`: `beta` (sensitivity)
- `gdema()`: `mult` (multiplier, 2 = standard DEMA)
- `trimmedMA()`: `trimPct` (0-0.5, percentage to trim)
- `mama()/fama()`: `fastLimit`, `slowLimit`
- `adaptiveLaguerre()`: Uses `len` for adaptation period
---
## 📝 Notes
- All 50+ functions are exported for use in any PineScript v6 indicator/strategy
- The `selector()` function supports **all MA types** via string key
- Use `getAllTypes()` to get a comma-separated list of all supported MA names
- Some MAs (CMA, INSTANTTREND, LAGUERRE, MAMA) don't use `len` parameter
- Use `nz()` wrapper if handling potential NA values in your calculations
---
**Author:** thetradingspiderman
**Version:** 1.0
**PineScript Version:** 6
**Total MA Types:** 50+
Master_UtilsLibrary "Master_Utils"
get_theme(theme_name)
Parameters:
theme_name (string)
label_buy(y, txt, col, txt_col, size_str, tooltip)
Parameters:
y (float)
txt (string)
col (color)
txt_col (color)
size_str (string)
tooltip (string)
label_sell(y, txt, col, txt_col, size_str, tooltip)
Parameters:
y (float)
txt (string)
col (color)
txt_col (color)
size_str (string)
tooltip (string)
Palette
Fields:
bull (series color)
bear (series color)
neutral (series color)
text_ (series color)
glow (series color)
Table_UtilsLibrary "Table_Utils"
Enhanced Table Utilities for Professional Dashboards V2.0
get_position(posStr)
Convert string to position constant
Parameters:
posStr (string) : User-selected position string
Returns: Pine Script position constant
get_size(sizeStr)
Convert string to size constant
Parameters:
sizeStr (string) : User-selected size string
Returns: Pine Script size constant
get_theme_color(scheme, colorType)
Get color from predefined palette
Parameters:
scheme (string) : Palette name: "Cyberpunk", "Professional", "Pastel", "Dark"
colorType (string) : Color role: "bull", "bear", "neutral", "bg", "border"
Returns: Color value
create_dashboard(posStr, cols, rows, scheme)
Create standard dashboard table with preset styling
Parameters:
posStr (string) : Position string
cols (int) : Number of columns
rows (int) : Number of rows
scheme (string) : Color scheme name
Returns: Configured table object
add_header_cell(tbl, col, row, text_, scheme)
Add header cell with preset styling
Parameters:
tbl (table) : Table object
col (int) : Column index
row (int) : Row index
text_ (string)
scheme (string) : Color scheme
add_data_cell(tbl, col, row, text_, value, scheme)
Add data cell with conditional coloring
Parameters:
tbl (table) : Table object
col (int) : Column index
row (int) : Row index
text_ (string)
value (float) : Numeric value for color coding
scheme (string) : Color scheme
format_number(value, decimals)
Format number with appropriate suffix (K, M, B)
Parameters:
value (float) : Number to format
decimals (int) : Number of decimal places
Returns: Formatted string
format_percentage(value)
Format percentage with sign
Parameters:
value (float) : Percentage value (as decimal, e.g., 0.05 = 5%)
Returns: Formatted string with % symbol
LibProfLibrary "LibProf"
Core Profiling Library.
This library provides a generic, object-oriented framework for
creating, managing, and analyzing 1D distributions (profiles) on
a customizable coordinate grid.
Unlike traditional Volume Profile libraries, `LibProf` is designed
as a **neutral Engine**. It abstracts away specific concepts
like "Price" or "Volume" in favor of mathematical primitives
("Level" and "Mass"). This allows developers to profile *any*
data series, such as Time-at-Price, Velocity, Delta, or Ticks.
Key Features:
1. **Object-Oriented Design (UDT):** Built around the `Prof`
object, encapsulating grid geometry, two generic data accumulators
(Array A & B), and cached statistical metrics. Supports full
lifecycle management: creation, cloning, clearing, and merging.
2. **Data-Agnostic Abstraction:**
- **Level (X-Axis):** Represents the coordinate system (e.g.,
Price, Time, Oscillator Value).
- **Mass (Y-Axis):** Represents the accumulated quantity
(e.g., Volume, Duration, Count).
- **Resolution (Grain):** The grid represents continuous data
discretized by a customizable resolution step size.
3. **Dual-Mode Geometry (Linear & Logarithmic):**
The engine supports seamless switching between two geometric modes:
- **Linear:** Arithmetic scaling (equal distance).
- **Logarithmic:** Geometric scaling (equal percentage), essential
for consistent density analysis across large ranges (Crypto).
Includes strict domain validation (enforcing positive bounds for log-space)
and physics-based constraints to prevent aliasing.
4. **High-Fidelity Resampling:**
Includes a sophisticated **Trapezoidal Integration Model** to
handle grid resizing and profile merging. When data is moved
between grids of different resolutions or geometries, the
library calculates the exact integral of the mass density
to ensure strict mass conservation.
5. **Dynamic Grid Management:**
- **Adapting:** Automatically expands the coordinate boundaries
to include new data points (`adapt`).
- **Resizing:** Allows changing the resolution (bins) or
boundaries on the fly, triggering the interpolation engine to
re-sample existing data accurately.
6. **Statistical Analysis (Lazy Evaluation):**
Comprehensive metrics calculated on-demand.
In Logarithmic mode, metrics adapt to use **Geometric Mean** and
**Geometric Interpolation** for maximum precision.
- **Location:** Peak (Mode), Weighted Mean (Center of Gravity), Median.
- **Dispersion:** Standard Deviation (Population), Coverage.
- **Shape:** Skewness and Excess Kurtosis.
7. **Structural Analysis:**
Includes a monotonic segmentation algorithm (configured by gapSize)
to decompose the distribution into its fundamental unimodal
segments, aiding in the detection of multi-modal distributions.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
create(bins, upper, lower, resolution, dynamic, isLog, coverage, gapSize)
Construct a new `Prof` object with fixed bin count & bounds.
Parameters:
bins (int) : series int number of level bins ≥ 1
upper (float) : series float upper level bound (absolute)
lower (float) : series float lower level bound (absolute)
resolution (float) : series float Smallest allowed bin size (resolution).
dynamic (bool) : series bool Flag for dynamic adaption of profile bounds
isLog (bool) : series bool Flag to enable Logarithmic bin scaling.
coverage (int) : series int Percentage of total mass to include in the Coverage Area (1..100)
gapSize (int) : series int Noise filter for segmentation. Number of allowed bins against trend.
Returns: Prof freshly initialised profile
method clone(self)
Create a deep copy of the profile.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object to copy
Returns: Prof A new, independent copy of the profile
method merge(self, massA, massB, upper, lower)
Merges mass data from a source profile into the current profile.
If resizing is needed, it performs a high-fidelity re-binning of existing
mass using a linear interpolation model inferred from neighboring bins,
preventing aliasing artifacts and ensuring accurate mass preservation.
Namespace types: Prof
Parameters:
self (Prof) : Prof The target profile object to merge into.
massA (array) : array float The source profile's mass A bin array.
massB (array) : array float The source profile's mass B bin array.
upper (float) : series float The upper level bound of the source profile.
lower (float) : series float The lower level bound of the source profile.
Returns: Prof `self` (chaining), now containing the merged data.
method clear(self)
Reset all bin tallies while keeping configuration intact.
Namespace types: Prof
Parameters:
self (Prof) : Prof profile object
Returns: Prof cleared profile (chaining)
method addMass(self, idx, mass, useMassA)
Adds mass to a bin.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
idx (int) : series int Bin index
mass (float) : series float Mass to add (must be > 0)
useMassA (bool) : series bool If true, adds to Array A, otherwise Array B
method adapt(self, upper, lower)
Automatically adapts the profile's boundaries to include a given level interval.
If the level bound exceeds the current profile bounds, it triggers
the _resizeGrid method to resize the profile and re-bin existing mass.
Namespace types: Prof
Parameters:
self (Prof) : Prof The profile object.
upper (float) : series float The upper level to fit.
lower (float) : series float The lower level to fit.
Returns: Prof `self` (chaining).
method setBins(self, bins)
Sets the number of bins for the profile.
Behavior depends on the `isDynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-binning to a new resolution.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
bins (int) : series int The new number of bins
Returns: Prof `self` (chaining)
method setBounds(self, upper, lower)
Sets the level bounds for the profile.
Behavior depends on the `dynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-binning existing mass
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
upper (float) : series float The new upper level bound
lower (float) : series float The new lower level bound
Returns: Prof `self` (chaining)
method setResolution(self, resolution)
Sets the minimum resolution size (granularity limit) for the profile.
If the current bin count exceeds the limit imposed by the new
resolution, the profile is automatically resized (downsampled) to fit.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
resolution (float) : series float The new smallest allowed bin size.
Returns: Prof `self` (chaining)
method setLog(self, isLog)
Toggles the geometry of the profile between Linear and Logarithmic.
Behavior depends on the `dynamic` flag.
- If `dynamic = true`: Mass is re-distributed (merged) into the new geometric grid.
- If `dynamic = false`: Only works on empty profiles.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
isLog (bool) : series bool True for Logarithmic, False for Linear.
Returns: Prof `self` (chaining)
method setCoverage(self, coverage)
Set the percentage of mass for the Coverage Area. If the value
changes, the profile is finalized again.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
coverage (int) : series int The new Mass Coverage Percentage (0..100)
Returns: Prof `self` (chaining)
method setGapSize(self, gapSize)
Sets the gapSize (noise filter) for segmentation.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
gapSize (int) : series int Number of bins allowed to violate monotonicity
Returns: Prof `self` (chaining)
method getBins(self)
Returns the current number of bins in the profile.
Namespace types: Prof
Parameters:
self (Prof) : Prof The profile object.
Returns: series int The number of bins.
method getBounds(self)
Returns the current level bounds of the profile.
Namespace types: Prof
Parameters:
self (Prof) : Prof The profile object.
Returns:
upper series float The upper level bound of the profile.
lower series float The lower level bound of the profile.
method getBinWidth(self)
Get Width of a bin.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
Returns: series float The width of a bin
method getBinIdx(self, level)
Get Index of a bin.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
level (float) : series float absolute coordinate to locate
Returns: series int bin index 0…bins‑1 (clamped)
method getBinBnds(self, idx)
Get Bounds of a bin.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
idx (int) : series int Bin index
Returns:
up series float The upper level bound of the bin.
lo series float The lower level bound of the bin.
method getBinMid(self, idx)
Get Mid level of a bin.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
idx (int) : series int Bin index
Returns: series float Mid level
method getMassA(self)
Returns a copy of the internal raw data array A (Mass A).
Namespace types: Prof
Parameters:
self (Prof) : Prof The profile object.
Returns: array The internal array for mass A.
method getMassB(self)
Returns a copy of the internal raw data array B (Mass B).
Namespace types: Prof
Parameters:
self (Prof) : Prof The profile object.
Returns: array The internal array for mass B.
method getBinMassA(self, idx)
Get Mass A of a bin.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
idx (int) : series int Bin index
Returns: series float mass A
method getBinMassB(self, idx)
Get Mass B of a bin.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
idx (int) : series int Bin index
Returns: series float mass B
method getPeak(self)
Get Peak information.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
Returns:
peakIndex series int The index of the Peak bin.
peakLevel. series float The mid-level of the Peak bin.
method getCoverage(self)
Get Coverage information.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object
Returns:
covUpIndex series int The index of the upper bound bin of the Coverage Area.
covUpLevel series float The upper level bound of the Coverage Area.
covLoIndex series int The index of the lower bound bin of the Coverage Area.
covLoLevel series float The lower level bound of the Coverage Area.
method getMedian(self)
Get the profile's median level and its bin index. Calculates the value on-demand if stale.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object.
Returns:
medianIndex series int The index of the bin containing the Median.
medianLevel series float The Median level of the profile.
method getMean(self)
Get the profile's mean and its bin index. Calculates the value on-demand if stale.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object.
Returns:
meanIndex series int The index of the bin containing the mean.
meanLevel series float The mean of the profile.
method getStdDev(self)
Get the profile's standard deviation. Calculates the value on-demand if stale.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object.
Returns: series float The Standard deviation of the profile.
method getSkewness(self)
Get the profile's skewness. Calculates the value on-demand if stale.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object.
Returns: series float The Skewness of the profile.
method getKurtosis(self)
Get the profile's excess kurtosis. Calculates the value on-demand if stale.
Namespace types: Prof
Parameters:
self (Prof) : Prof Profile object.
Returns: series float The Kurtosis of the profile.
method getSegments(self)
Get the profile's fundamental unimodal segments. Calculates on-demand if stale.
Uses a pivot-based recursive algorithm configured by gapSize.
Namespace types: Prof
Parameters:
self (Prof) : Prof The profile object.
Returns: matrix A 2-column matrix where each row is an pair.
Prof
Prof Generic Profile object containing the grid and two data arrays.
Fields:
_bins (series int) : int Number of discrete containers (bins).
_upper (series float) : float Upper boundary of the domain.
_lower (series float) : float Lower boundary of the domain.
_resolution (series float) : float Smallest atomic grid unit (Resolution).
_isLog (series bool) : bool If true, the grid uses logarithmic scaling.
_logFactor (series float) : float Cached multiplier for log iteration (k = (up/lo)^(1/n)).
_logStep (series float) : float Cached natural logarithm of the factor (ln(k)) for optimized index calculation.
_dynamic (series bool) : bool Flag for dynamic resizing/resampling.
_coverage (series int) : int Target Mass Coverage Percentage (Input for Coverage).
_gapSize (series int) : int Tolerance against trend violations (Noise filter).
_maxBins (series int) : int Hard capacity limit for bins.
_massA (array) : array Generic Mass Array A.
_massB (array) : array Generic Mass Array B.
_peak (series int) : int Index of max mass (Mode).
_covUp (series int) : int Index of Coverage Upper Bound.
_covLo (series int) : int Index of Coverage Lower Bound.
_median (series float) : float Median level of distribution.
_mean (series float) : float Weighted Average Level (Center of Gravity).
_stdDev (series float) : float Population Standard Deviation.
_skewness (series float) : float Asymmetry measure.
_kurtosis (series float) : float Tail heaviness measure.
_segments (matrix) : matrix Identified unimodal segments.
SimpleTableA library for when you just want to get a table up with the least hassle.
The function `f_drawTableFromColumns()`, is intended to be the simplest possible way to draw a table with the least code in the calling script. Just pass in between one and ten arrays that contain the strings you want to show. Each string array represents one column. That's it. You get a table back.
If you want to style the table you can optionally pass colours, size, and whether the table has a header row that should be displayed differently.
An example usage section demonstrates creating a three-column table.
The function automatically sizes the table based on the number of non-na arrays and the maximum column length.
Optional styling parameters cover table position, text size, text alignment, text colour, cell background, header background, header text, and border width. If you don't supply any of these arguments, the table uses some sensible default values.
The table is created and updated on the last bar only, with caching to avoid unnecessary redraws.
Column shrink detection clears the table only when required, preventing stale cell content.
This is not a full-fledged table management library; there are already lots of those published. It is (I believe and hope) the easiest library to use. For example, you don't need to supply a matrix, or a user-defined type full of settings. The library wraps the input arrays into a map, and uses a user-defined type, but internally, so you don't need to worry about it. Just supply one or more arrays with some text.
f_drawTableFromColumnArrays(_a_col1, _a_col2, _a_col3, _a_col4, _a_col5, _a_col6, _a_col7, _a_col8, _a_col9, _a_col10, _position, _textSize, _textAlign, _textColor, _cellBgColor, _headerBgColor, _headerTextColor, _hasHeaderRow, _borderWidth)
Renders a table using up to ten string arrays. The table size is derived from the number of non-na arrays and the maximum length across the supplied arrays.
Parameters:
_a_col1 (array) : (array) Column 1 values. Supply na to omit.
_a_col2 (array) : (array) Column 2 values. Supply na to omit.
_a_col3 (array) : (array) Column 3 values. Supply na to omit.
_a_col4 (array) : (array) Column 4 values. Supply na to omit.
_a_col5 (array) : (array) Column 5 values. Supply na to omit.
_a_col6 (array) : (array) Column 6 values. Supply na to omit.
_a_col7 (array) : (array) Column 7 values. Supply na to omit.
_a_col8 (array) : (array) Column 8 values. Supply na to omit.
_a_col9 (array) : (array) Column 9 values. Supply na to omit.
_a_col10 (array) : (array) Column 10 values. Supply na to omit.
_position (string) : (TablePosition) Table position on the chart. Default is top right.
_textSize (string) : (TableTextSize) Text size for all cells. Default is normal.
_textAlign (string) : (TableTextAlign) Horizontal alignment for all cells. Default is left.
_textColor (color) : (color) Text colour for all cells. Default is chart foreground color.
_cellBgColor (color) : (color) Background colour for all cells. Uses a default if na. Default is gray 90%.
_headerBgColor (color) : (color) Background colour for the header row. Uses a default if na. Default is gray 75%.
_headerTextColor (color) : (color) Text colour for the header row. Uses a default if na.
_hasHeaderRow (bool) : (bool) If true, row 0 is treated as a header. Default is true.
_borderWidth (int) : (int) Table border width. Must be non-negative. Default is 1.
Returns: The table object, so the caller can store the table ID if required.
LO1_News2023H2Library "LO1_News2023H2" - Contains the news events for 2023 H2
f_loadNewsRows()
f_loadExcSevByTypeId()
f_loadExcTagByTypeId()
f_loadExcDelayAfterNewsMins()
LO1_News2023H1Library "LO1_News2023H1" - Contains the news events for 2023
f_loadNewsRows()
f_loadExcSevByTypeId()
f_loadExcTagByTypeId()
f_loadExcDelayAfterNewsMins()
AssetCorrelationUtils
- Open source Library Used for Indicators that utilize correlation between assets for divergence calculations. It has no drawing elements.
ASSET CORRELATION UTILS
PineScript library for automatic detection of correlated asset pairs and triads for multi-asset analysis.
WHAT IT DOES
This library automatically identifies correlated assets based on the current chart symbol. It returns properly configured asset pairings for use in SMT divergence detection, inter-market analysis, and multi-asset comparison tools.
HOW IT WORKS
The library matches your chart symbol against known correlation groups:
Index Futures: NQ/ES/YM/RTY triads (including micros)
Metals: Gold/Silver/Copper triads (futures and CFD)
Forex: EUR/GBP/DXY and USD/JPY/CHF triads
Energy: Crude/Gasoline/Heating Oil triads
Treasury: ZB/ZF/ZN bond triads
Crypto: BTC/ETH/TOTAL3 and major altcoin pairings
Inversion flags are automatically computed for assets that move inversely (e.g., DXY vs EUR pairs).
HOW TO USE
import fstarcapital/AssetCorrelationUtils/1 as acu
// Simple: auto-detect from current chart
config = acu.resolveCurrentChart()
// Access resolved assets
primary = config.primary
secondary = config.secondary
tertiary = config.tertiary
EXPORTED FUNCTIONS
resolveCurrentChart(): One-call auto-detection using chart syminfo
resolveAssets(): Full detection with custom parameters
resolveTriad() / resolveDyad(): Manual resolution with inversion logic
detect*() functions: Category-specific detectors for custom workflows
TYPES
AssetPairing: Core structure for primary/secondary/tertiary tickers with inversion flags
AssetConfig: Full resolution result with detection status and asset category
DISCLAIMER
This library is a utility for building multi-asset indicators. Asset correlations are not guaranteed and may change over time. Always validate pairings for your specific trading context.
Full Default Function @type and @field descriptions below.
Library "AssetCorrelationUtils"
detectIndicesFutures(ticker)
Detects Index Futures (NQ/ES/YM/RTY + micro variants)
Parameters:
ticker (string) : The ticker string to check (typically syminfo.ticker)
Returns: AssetPairing with secondary and tertiary assets configured
detectMetalsFutures(ticker)
Detects Metal Futures (GC/SI/HG + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectForexFutures(ticker)
Detects Forex Futures (6E/6B + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectEnergyFutures(ticker)
Detects Energy Futures (CL/RB/HO + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectTreasuryFutures(ticker)
Detects Treasury Futures (ZB/ZF/ZN)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectCryptoFutures(ticker)
Detects CME Crypto Futures (BTC/ETH + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectCADFutures(ticker)
Detects CAD Forex Futures (6C + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectForexCFD(ticker, tickerId)
Detects Forex CFD pairs (EUR/GBP/DXY, USD/JPY/CHF triads)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID (syminfo.tickerid) for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectCrypto(ticker, tickerId)
Detects major Crypto assets (BTC, ETH, SOL, XRP, alts)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectMetalsCFD(ticker, tickerId)
Detects Metals CFD (XAU/XAG/Copper)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectIndicesCFD(ticker, tickerId)
Detects Indices CFD (NAS100/SP500/DJ30)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectEUStocks(ticker, tickerId)
Detects EU Stock Indices (GER40/EU50) - Dyad only
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary asset configured (tertiary empty for dyad)
getDefaultFallback(tickerId)
Returns default fallback assets (chart ticker only, no correlation)
Parameters:
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with chart ticker as primary, empty secondary/tertiary (no correlation)
applySessionModifierWithBackadjust(tickerStr, sessionType)
Applies futures session modifier to ticker WITH back adjustment
Parameters:
tickerStr (string) : The ticker to modify
sessionType (string) : The session type (syminfo.session)
Returns: Modified ticker string with session and backadjustment.on applied
applySessionModifierNoBackadjust(tickerStr, sessionType)
Applies futures session modifier to ticker WITHOUT back adjustment
Parameters:
tickerStr (string) : The ticker to modify
sessionType (string) : The session type (syminfo.session)
Returns: Modified ticker string with session and backadjustment.off applied
isTriadMode(pairing)
Checks if a pairing represents a valid triad (3 assets)
Parameters:
pairing (AssetPairing) : The AssetPairing to check
Returns: True if tertiary is non-empty (triad mode), false for dyad
getAssetTicker(tickerId)
Extracts clean ticker string from full ticker ID
Parameters:
tickerId (string) : The full ticker ID (e.g., "BITGET:BTCUSDT.P")
Returns: Clean ticker string (e.g., "BTCUSDT.P")
resolveTriad(chartTickerId, pairing)
Resolves triad asset assignments with proper inversion flags
Parameters:
chartTickerId (string) : The current chart's ticker ID (syminfo.tickerid)
pairing (AssetPairing) : The detected AssetPairing
Returns: Tuple
resolveDyad(chartTickerId, pairing)
Resolves dyad asset assignment with proper inversion flag
Parameters:
chartTickerId (string) : The current chart's ticker ID
pairing (AssetPairing) : The detected AssetPairing (dyad: tertiary is empty)
Returns: Tuple
resolveAssets(ticker, tickerId, assetType, sessionType, useBackadjust)
Main auto-detection entry point. Detects asset category and returns fully resolved config.
Parameters:
ticker (string) : The ticker string to check (typically syminfo.ticker)
tickerId (string) : The full ticker ID (typically syminfo.tickerid)
assetType (string) : The asset type (typically syminfo.type)
sessionType (string) : The session type for futures (typically syminfo.session)
useBackadjust (bool) : Whether to apply back adjustment for futures session alignment
Returns: AssetConfig with fully resolved assets, inversion flags, and detection status
resolveCurrentChart()
Simplified auto-detection using current chart's syminfo values
Returns: AssetConfig with fully resolved assets, inversion flags, and detection status
AssetPairing
Core asset pairing structure for triad/dyad configurations
Fields:
primary (series string) : The primary (chart) asset ticker ID
secondary (series string) : The secondary correlated asset ticker ID
tertiary (series string) : The tertiary correlated asset ticker ID (empty for dyad)
invertSecondary (series bool) : Whether secondary asset should be inverted for divergence calc
invertTertiary (series bool) : Whether tertiary asset should be inverted for divergence calc
AssetConfig
Full asset resolution result with mode detection and computed values
Fields:
detected (series bool) : Whether auto-detection succeeded
isTriadMode (series bool) : True if triad (3 assets), false if dyad (2 assets)
primary (series string) : The resolved primary asset ticker ID
secondary (series string) : The resolved secondary asset ticker ID
tertiary (series string) : The resolved tertiary asset ticker ID (empty for dyad)
invertSecondary (series bool) : Computed inversion flag for secondary asset
invertTertiary (series bool) : Computed inversion flag for tertiary asset
assetCategory (series string) : String describing the detected asset category
LiveTracker by N&MLiveTracker is a real-time trade execution and accounting engine built on top of statistically validated backtest states.
It mirrors live trading conditions with precise fee modeling, partial take-profits, trailing stops, and liquidation logic.
Each trade is tracked with both mark-to-market PnL and “net if closed now” metrics for full transparency.
Designed as a modular Pine Script® library, it enables reliable, state-driven live execution without repainting.
historicalEngine by N&M🇬🇧 English Introduction
historicalEngine is a Pine Script library designed for advanced state-based backtesting.
It does not test a single strategy, but evaluates full market configurations (trend, structure, momentum, multi-TF context).
Each trade is linked to a unique state hash, revealing which conditions truly perform over time.
The engine computes professional metrics: PnL, win rate, expectancy, Sharpe, drawdown, reliability.
It includes dynamic TP/SL, liquidation logic, early exits, realistic fees and slippage.
Built to be modular, extensible, and efficient, it plugs into any indicator.
Goal: turn historical data into a statistical trading edge.
V1 – a solid foundation for adaptive and data-driven trading systems.
tradeEngineLibrary "tradeEngine"
calculateLiquidationPrice(entryPrice, isLong, leverage, buffer)
Parameters:
entryPrice (float)
isLong (bool)
leverage (int)
buffer (float)
calculateTPLevels(entryPrice, atr, isLong, risk)
Parameters:
entryPrice (float)
atr (float)
isLong (bool)
risk (RiskConfig)
calculateSL(entryLow, entryHigh, isLong, risk)
Parameters:
entryLow (float)
entryHigh (float)
isLong (bool)
risk (RiskConfig)
simulateTrade(highs, lows, closes, entryIdx, entryPrice, entryLow, entryHigh, entryATR, isLong, risk, maxBars)
Parameters:
highs (array)
lows (array)
closes (array)
entryIdx (int)
entryPrice (float)
entryLow (float)
entryHigh (float)
entryATR (float)
isLong (bool)
risk (RiskConfig)
maxBars (int)
createRiskConfig(leverage, liqBuffer, useTP1, tp1ATR, useTP2, tp2ATR, useSL, slBuffer, maker, taker, slip)
Parameters:
leverage (int)
liqBuffer (float)
useTP1 (bool)
tp1ATR (float)
useTP2 (bool)
tp2ATR (float)
useSL (bool)
slBuffer (float)
maker (float)
taker (float)
slip (float)
TradeResult
Fields:
exitType (series string)
exitBarIdx (series int)
exitPrice (series float)
finalPnL (series float)
maxPnL (series float)
tp1Hit (series bool)
tp2Hit (series bool)
slHit (series bool)
liquidated (series bool)
barsInTrade (series int)
tp1Level (series float)
tp2Level (series float)
slLevel (series float)
liqLevel (series float)
RiskConfig
Fields:
leverage (series int)
liquidationBuffer (series float)
useTP1 (series bool)
tp1ATR (series float)
useTP2 (series bool)
tp2ATR (series float)
useFixedSL (series bool)
slBuffer (series float)
makerFee (series float)
takerFee (series float)
slippage (series float)
matrixCoreLibrary "matrixCore"
analyzeCandleStructure(o, h, l, c, atr, smallBodyThreshold, longWickRatio)
Parameters:
o (float)
h (float)
l (float)
c (float)
atr (float)
smallBodyThreshold (float)
longWickRatio (float)
isRedRejectionCandle(o, l, c, redRejectionWickMin)
Parameters:
o (float)
l (float)
c (float)
redRejectionWickMin (float)
isEqual(a, b, tol)
Parameters:
a (float)
b (float)
tol (float)
detectPattern(kf, km, ks, tol)
Parameters:
kf (float)
km (float)
ks (float)
tol (float)
calculateStateHash(kp, ep, pp, comp, cType, slope, tfH, tfL, redRej)
Parameters:
kp (int)
ep (int)
pp (int)
comp (int)
cType (int)
slope (int)
tfH (bool)
tfL (bool)
redRej (bool)
createStateConfig(kp, ep, pp, comp, cType, slope, tfH, tfL, redRej, hash)
Parameters:
kp (int)
ep (int)
pp (int)
comp (int)
cType (int)
slope (int)
tfH (bool)
tfL (bool)
redRej (bool)
hash (int)
createBarSnapshot(barIdx, o, h, l, c, atr, ema, stateHash, kp, ep, pp, comp, cType, slope, tfH, tfL, redRej)
Parameters:
barIdx (int)
o (float)
h (float)
l (float)
c (float)
atr (float)
ema (float)
stateHash (int)
kp (int)
ep (int)
pp (int)
comp (int)
cType (int)
slope (int)
tfH (bool)
tfL (bool)
redRej (bool)
stateToString(cfg)
Parameters:
cfg (StateConfig)
getTablePosition(pos)
Parameters:
pos (string)
getGradientColor(value, minVal, maxVal)
Parameters:
value (float)
minVal (float)
maxVal (float)
StateConfig
Fields:
kijunPattern (series int)
emaPattern (series int)
pricePos (series int)
compression (series int)
candleType (series int)
emaSlope (series int)
tfHigherBullish (series bool)
tfLowerBullish (series bool)
redRejection (series bool)
hash (series int)
BarSnapshot
Fields:
barIndex (series int)
openPrice (series float)
highPrice (series float)
lowPrice (series float)
closePrice (series float)
atr (series float)
emaFast (series float)
stateHash (series int)
kijunPattern (series int)
emaPattern (series int)
pricePos (series int)
compression (series int)
candleType (series int)
emaSlope (series int)
tfHigherBullish (series bool)
tfLowerBullish (series bool)
redRejection (series bool)
labConfigCoreLibrary "labConfigCore"
Configuration centrale pour tous les indicateurs LAB (Kijun + EMA + S/R)
Centralise les valeurs par défaut pour éviter les désynchronisations entre indicateurs
getTFFast()
Retourne le timeframe Fast par défaut
Returns: String - Timeframe Fast ("15" par défaut)
getTFMid()
Retourne le timeframe Mid par défaut
Returns: String - Timeframe Mid ("60" par défaut)
getTFSlow()
Retourne le timeframe Slow par défaut
Returns: String - Timeframe Slow ("240" par défaut)
getTFATR()
Retourne le timeframe ATR par défaut
Returns: String - Timeframe ATR ("60" par défaut)
getKijunLength()
Retourne la longueur Kijun par défaut
Returns: Int - Longueur Kijun (26 par défaut)
getShowKijun()
Retourne l'état d'affichage Kijun par défaut
Returns: Bool - Afficher Kijun (true par défaut)
getEMALength()
Retourne la longueur EMA par défaut
Returns: Int - Longueur EMA (50 par défaut)
getChannelWidth()
Retourne la largeur des canaux EMA par défaut
Returns: Float - Largeur canal en % (2.0 par défaut)
getChannelAlpha()
Retourne la transparence des canaux par défaut
Returns: Int - Alpha channel (93 par défaut)
getShowChannelFast()
Retourne l'état d'affichage canal Fast par défaut
Returns: Bool - Afficher canal Fast (false par défaut)
getShowChannelMid()
Retourne l'état d'affichage canal Mid par défaut
Returns: Bool - Afficher canal Mid (true par défaut)
getShowChannelSlow()
Retourne l'état d'affichage canal Slow par défaut
Returns: Bool - Afficher canal Slow (true par défaut)
getChannelColorFast()
Retourne la couleur canal Fast par défaut
Returns: Color - Couleur Fast (#00BCD4 par défaut)
getChannelColorMid()
Retourne la couleur canal Mid par défaut
Returns: Color - Couleur Mid (#4CAF50 par défaut)
getChannelColorSlow()
Retourne la couleur canal Slow par défaut
Returns: Color - Couleur Slow (#FF9800 par défaut)
getSRDisplayMode()
Retourne le mode d'affichage S/R par défaut
Returns: String - Mode ('S/R Zones' par défaut)
getSRTimeframe()
Retourne le timeframe S/R par défaut
Returns: String - Timeframe S/R ('Chart' par défaut)
getSRVolMA()
Retourne la longueur Volume MA par défaut
Returns: Int - Longueur Vol MA (6 par défaut)
getSRNumZones()
Retourne le nombre de zones back par défaut
Returns: Int - Zones back (10 par défaut)
getSRExtendLines()
Retourne l'état extend lines par défaut
Returns: Bool - Extend to next zone (true par défaut)
getSRExtendActive()
Retourne l'état extend active par défaut
Returns: Bool - Extend active right (true par défaut)
getSRExtendRight()
Retourne l'état extend right par défaut
Returns: Bool - Extend right (false par défaut)
getSRShowLabels()
Retourne l'état affichage labels par défaut
Returns: Bool - Show labels (true par défaut)
getSRLabelLocation()
Retourne la position labels par défaut
Returns: String - Position ('Right' par défaut)
getSRLabelOffset()
Retourne l'offset labels par défaut
Returns: Int - Offset (15 par défaut)
getSRShowHL()
Retourne l'état affichage H/L par défaut
Returns: Bool - Show H/L lines (true par défaut)
getSRShowOC()
Retourne l'état affichage O/C par défaut
Returns: Bool - Show O/C lines (true par défaut)
getSRLineStyleHL()
Retourne le style ligne H/L par défaut
Returns: String - Style ('Solid' par défaut)
getSRLineWidthHL()
Retourne l'épaisseur ligne H/L par défaut
Returns: Int - Width (1 par défaut)
getSRLineStyleOC()
Retourne le style ligne O/C par défaut
Returns: String - Style ('Solid' par défaut)
getSRLineWidthOC()
Retourne l'épaisseur ligne O/C par défaut
Returns: Int - Width (1 par défaut)
getSRResLinesColor()
Retourne la couleur lignes résistance par défaut
Returns: Color - Couleur (rouge 20% transparent)
getSRResZoneColor()
Retourne la couleur zone résistance par défaut
Returns: Color - Couleur (rouge 90% transparent)
getSRSupLinesColor()
Retourne la couleur lignes support par défaut
Returns: Color - Couleur (lime 20% transparent)
getSRSupZoneColor()
Retourne la couleur zone support par défaut
Returns: Color - Couleur (lime 90% transparent)
getNormMode()
Retourne le mode de normalisation par défaut
Returns: String - Mode ('ATR' par défaut)
getATRLength()
Retourne la longueur ATR par défaut
Returns: Int - Longueur ATR (14 par défaut)
getTolEqual()
Retourne la tolérance égalité par défaut
Returns: Float - Tolérance (0.10 par défaut)
getThresholdTight()
Retourne le seuil compression par défaut
Returns: Float - Seuil tight (0.25 par défaut)
getThresholdWide()
Retourne le seuil extension par défaut
Returns: Float - Seuil wide (1.50 par défaut)
getShowDashboard()
Retourne l'état d'affichage dashboard par défaut
Returns: Bool - Show table (true par défaut)
getDashboardPosition()
Retourne la position dashboard par défaut
Returns: String - Position ('Top Right' par défaut)
getDashboardSize()
Retourne la taille dashboard par défaut
Returns: String - Size ('Small' par défaut)
getProbBarsForward()
Retourne le nombre de barres forward par défaut
Returns: Int - Bars forward (20 par défaut)
getProbWinThreshold()
Retourne le seuil win par défaut
Returns: Float - Win threshold % (1.5 par défaut)
getProbLossThreshold()
Retourne le seuil loss par défaut
Returns: Float - Loss threshold % (1.0 par défaut)
getProbHistorySize()
Retourne la taille historique par défaut
Returns: Int - History size (500 par défaut)
getStrategyTPSLMode()
Retourne le mode TP/SL par défaut
Returns: String - Mode ('% Fixed' ou 'ATR Multiple')
getStrategyTPPercent()
Retourne le take profit % par défaut
Returns: Float - TP % (2.0 par défaut)
getStrategySLPercent()
Retourne le stop loss % par défaut
Returns: Float - SL % (1.0 par défaut)
getStrategyTPATRMultiple()
Retourne le multiple ATR pour TP par défaut
Returns: Float - TP ATR multiple (2.0 par défaut)
getStrategySLATRMultiple()
Retourne le multiple ATR pour SL par défaut
Returns: Float - SL ATR multiple (1.5 par défaut)
getStrategyUseTrailing()
Retourne l'état trailing stop par défaut
Returns: Bool - Use trailing stop (false par défaut)
getStrategyTrailingActivation()
Retourne l'activation trailing % par défaut
Returns: Float - Trailing activation % (1.0 par défaut)
getStrategyTrailingOffset()
Retourne le trailing offset % par défaut
Returns: Float - Trailing offset % (0.5 par défaut)
getStrategyPositionSize()
Retourne la taille position par défaut
Returns: Float - Position size % equity (100 par défaut)
getStrategyInitialCapital()
Retourne le capital initial par défaut
Returns: Float - Initial capital (10000 par défaut)
getStrategyCommission()
Retourne la commission par défaut
Returns: Float - Commission % (0.1 par défaut)
getStrategySlippage()
Retourne le slippage par défaut
Returns: Int - Slippage ticks (2 par défaut)
getAllKijunDefaults()
Retourne TOUS les paramètres Kijun sous forme de tuple
Returns: - TF Fast, Mid, Slow, Length, Show
getAllEMADefaults()
Retourne TOUS les paramètres EMA sous forme de tuple
Returns: - Length, Width, Alpha, Show Fast, Mid, Slow
getAllNormDefaults()
Retourne TOUS les paramètres Normalisation sous forme de tuple
Returns: - Mode, TF ATR, Length, Tol, Tight, Wide
getAllDashboardDefaults()
Retourne TOUS les paramètres Dashboard sous forme de tuple
Returns: - Show, Position, Size
volSRCoreLibrary volSRCore
Library to compute volume-based support and resistance zones using fractal logic.
tfStringToFormat(tfInput)
Converts a timeframe string into Pine Script format.
Parameters:
tfInput (string): Timeframe string ("Chart", "1m", "5m", "1h", "D", etc.)
Returns:
string — Pine Script–formatted timeframe
resInMinutes()
Converts the current chart timeframe into minutes.
Returns:
float — number of minutes of the current timeframe
fractalUp(tfHigh, tfVol, tfVolMA)
Detects a bullish fractal (potential resistance).
Parameters:
tfHigh (float): High series of the timeframe
tfVol (float): Volume series of the timeframe
tfVolMA (float): Volume moving average series
Returns:
bool — true if a bullish fractal is detected
fractalDown(tfLow, tfVol, tfVolMA)
Detects a bearish fractal (potential support).
Parameters:
tfLow (float): Low series of the timeframe
tfVol (float): Volume series of the timeframe
tfVolMA (float): Volume moving average series
Returns:
bool — true if a bearish fractal is detected
calcFractalUpLevel(tfHigh, tfVol, tfVolMA)
Computes the resistance level from a bullish fractal.
Parameters:
tfHigh (float): High series
tfVol (float): Volume series
tfVolMA (float): Volume MA series
Returns:
float — resistance level
calcFractalDownLevel(tfLow, tfVol, tfVolMA)
Computes the support level from a bearish fractal.
Parameters:
tfLow (float): Low series
tfVol (float): Volume series
tfVolMA (float): Volume MA series
Returns:
float — support level
calcResistanceZone(tfHigh, tfOpen, tfClose, tfVol, tfVolMA)
Computes the resistance zone (between High and Open/Close).
Parameters:
tfHigh (float): High series
tfOpen (float): Open series
tfClose (float): Close series
tfVol (float): Volume series
tfVolMA (float): Volume MA series
Returns:
float — lower boundary of the resistance zone
calcSupportZone(tfLow, tfOpen, tfClose, tfVol, tfVolMA)
Computes the support zone (between Low and Open/Close).
Parameters:
tfLow (float): Low series
tfOpen (float): Open series
tfClose (float): Close series
tfVol (float): Volume series
tfVolMA (float): Volume MA series
Returns:
float — upper boundary of the support zone
tfNewBar(tfRes)
Detects a new bar on a given timeframe.
Parameters:
tfRes (simple string): Timeframe string
Returns:
bool — true if a new bar is detected
tfBarIndexBack(tfRes, barsBack)
Computes the bar_index N bars back on a target timeframe.
Parameters:
tfRes (simple string): Timeframe string
barsBack (simple int): Number of bars back (1, 3, 5, etc.)
Returns:
int — bar_index at that point in time
tfBarsRange(tfRes, startBar, endBar)
Computes the number of chart bars between two bars of a target timeframe.
Parameters:
tfRes (simple string): Timeframe string
startBar (simple int): Start bar (e.g., 1)
endBar (simple int): End bar (e.g., 5)
Returns:
int — number of chart bars in that range
calcPivotHighBarIndex(startBarsBack, rangeSize, maxBarsBack)
Finds the exact bar_index of the highest high within a given range.
Parameters:
startBarsBack (simple int): Start of the scan (bars back)
rangeSize (simple int): Size of the scan range
maxBarsBack (simple int): max_bars_back limit (e.g., 4999)
Returns:
int — bar_index of the highest high, or maxBarsBack if out of bounds
calcPivotLowBarIndex(startBarsBack, rangeSize, maxBarsBack)
Finds the exact bar_index of the lowest low within a given range.
Parameters:
startBarsBack (simple int): Start of the scan (bars back)
rangeSize (simple int): Size of the scan range
maxBarsBack (simple int): max_bars_back limit (e.g., 4999)
Returns:
int — bar_index of the lowest low, or maxBarsBack if out of bounds
detectPriceInteraction(resLevel, resZone, supLevel, supZone)
Detects price interactions with support/resistance zones.
Parameters:
resLevel (float): Resistance level
resZone (float): Resistance zone
supLevel (float): Support level
supZone (float): Support zone
Returns:
EntersResZone
TestsResAsSupport
EntersSupZone
TestsSupAsResistance
BreaksResistance
BreaksSupport
calcSRLevelsFromData(tfOpen, tfHigh, tfLow, tfClose, tfVol, volMaLength)
Computes all support/resistance levels from already-fetched MTF data.
Parameters:
tfOpen (float): TF open
tfHigh (float): TF high
tfLow (float): TF low
tfClose (float): TF close
tfVol (float): TF volume
volMaLength (simple int): Volume MA length
Returns:
ResistanceLevel
ResistanceZone
SupportLevel
SupportZone
IsFractalUp
IsFractalDown
detectNewSR(resLevel, supLevel)
Detects a new fractal event (new support or resistance found).
Parameters:
resLevel (float): Current resistance level
supLevel (float): Current support level
Returns:
NewResistance
NewSupport
emaStackCoreLibrary "emaStackCore"
emaCalc(source, length)
Calculate EMA
Parameters:
source (float) : Price source (close, hl2, etc.)
length (simple int) : EMA period
Returns: EMA value
emaSlope(emaValue, lookback)
Calculate EMA slope (% change over lookback period)
Parameters:
emaValue (float) : Current EMA value
lookback (int) : Number of bars to look back
Returns: Slope in percentage
emaDist(ema1, ema2, mode, atrVal, price)
Calculate distance between 2 EMAs (normalized)
Parameters:
ema1 (float) : First EMA value
ema2 (float) : Second EMA value
mode (string) : Normalization mode ("ATR" or "%")
atrVal (float) : ATR value for ATR mode
price (float) : Reference price for % mode
Returns: Normalized distance
slopeClass(slope, thresholdFlat)
Classify EMA slope
Parameters:
slope (float) : EMA slope in %
thresholdFlat (float) : Threshold to consider slope as flat
Returns: +1 (rising), 0 (flat), -1 (falling)
slopeScore5(slope10, slope20, slope50, slope100, slope200, threshold)
Calculate combined slope score for 5 EMAs
Parameters:
slope10 (float) : EMA10 slope
slope20 (float) : EMA20 slope
slope50 (float) : EMA50 slope
slope100 (float) : EMA100 slope
slope200 (float) : EMA200 slope
threshold (float) : Flat threshold
Returns: Sum of slope classes (-5 to +5)
emaStack5Score(e10, e20, e50, e100, e200, tolEq)
Calculate EMA stack score (5 EMAs)
Parameters:
e10 (float) : EMA 10 value
e20 (float) : EMA 20 value
e50 (float) : EMA 50 value
e100 (float) : EMA 100 value
e200 (float) : EMA 200 value
tolEq (float) : Tolerance for equality (%)
Returns: Stack score (-4 to +4)
emaStack5ScoreWithSlope(e10, e20, e50, e100, e200, slope10, slope20, slope50, slope100, slope200, tolEq, slopeThreshold)
Enhanced EMA stack with slope
Parameters:
e10 (float)
e20 (float)
e50 (float)
e100 (float)
e200 (float)
slope10 (float)
slope20 (float)
slope50 (float)
slope100 (float)
slope200 (float)
tolEq (float)
slopeThreshold (float)
Returns:
emaRegimeChange(currentScore, previousScore, threshold)
Detect regime change in EMA stack
Parameters:
currentScore (int) : Current stack score
previousScore (int) : Previous stack score
threshold (int) : Minimum change to consider significant
Returns:
emaCompressed(e10, e20, e50, e100, e200, threshold)
Detect EMA compression (squeeze)
Parameters:
e10 (float) : EMA 10 value
e20 (float) : EMA 20 value
e50 (float) : EMA 50 value
e100 (float) : EMA 100 value
e200 (float) : EMA 200 value
threshold (float) : Max spread % to consider compressed
Returns:
emaConfluence9(price, e10_tf1, e20_tf1, e50_tf1, e10_tf2, e20_tf2, e50_tf2, e10_tf3, e20_tf3, e50_tf3, threshold)
Calculate confluence score (how many EMAs are near price)
Parameters:
price (float) : Current price
e10_tf1 (float) : EMA10 on timeframe 1
e20_tf1 (float) : EMA20 on timeframe 1
e50_tf1 (float) : EMA50 on timeframe 1
e10_tf2 (float) : EMA10 on timeframe 2
e20_tf2 (float) : EMA20 on timeframe 2
e50_tf2 (float) : EMA50 on timeframe 2
e10_tf3 (float) : EMA10 on timeframe 3
e20_tf3 (float) : EMA20 on timeframe 3
e50_tf3 (float) : EMA50 on timeframe 3
threshold (float) : Max distance % to consider "near"
Returns: Confluence count (0-9)
emaConfluence3(price, e10, e20, e50, threshold)
Simplified confluence for 3 EMAs on single TF
Parameters:
price (float)
e10 (float)
e20 (float)
e50 (float)
threshold (float)
Returns: Confluence count (0-3)
emaLeadLag(score15m, score1H, score4H, lookback)
Determine which timeframe is leading the move
Parameters:
score15m (int) : Stack score on 15m
score1H (int) : Stack score on 1H
score4H (int) : Stack score on 4H
lookback (int) : Bars to look back for change detection
Returns: Leader timeframe ("15m", "1H", "4H", "ALIGNED", "MIXED")
emaPriceDivergence(price, emaValue, lookback)
Detect divergence between price and EMA direction
Parameters:
price (float) : Current price
emaValue (float) : EMA value (typically EMA20)
lookback (int) : Bars to compare
Returns:
emaOrderStrength(e10, e20, e50, e100, e200)
Calculate EMA order strength (weighted by distance)
Parameters:
e10 (float) : EMA 10
e20 (float) : EMA 20
e50 (float) : EMA 50
e100 (float) : EMA 100
e200 (float) : EMA 200
Returns: Strength score (higher = stronger trend)
emaPriceZone(price, e10, e20, e50, e100, e200)
Determine which EMA zone price is in
Parameters:
price (float) : Current price
e10 (float) : EMA 10
e20 (float) : EMA 20
e50 (float) : EMA 50
e100 (float) : EMA 100
e200 (float) : EMA 200
Returns: Zone code (5=above all, 0=below all, -1=mixed)
kijunStackCoreLibrary "kijunStackCore"
kijun(highSeries, lowSeries, length)
Parameters:
highSeries (float)
lowSeries (float)
length (int)
distNormAtr(a, b, atrValue)
Parameters:
a (float)
b (float)
atrValue (float)
distNormPct(a, b, price)
Parameters:
a (float)
b (float)
price (float)
stack3Code(kFast, kMid, kSlow, distFastMid, distMidSlow, tolEq)
Parameters:
kFast (float)
kMid (float)
kSlow (float)
distFastMid (float)
distMidSlow (float)
tolEq (float)
stack3Compressed(distFastMid, distMidSlow, tight)
Parameters:
distFastMid (float)
distMidSlow (float)
tight (float)
stack3Stretched(distFastMid, distMidSlow, wide)
Parameters:
distFastMid (float)
distMidSlow (float)
wide (float)
QTCoreLibrary "QTCore"
qt_config_default()
qt_state_new()
qt_daily_update(st, cfg, t, tClose)
Parameters:
st (CycleState)
cfg (QTConfig)
t (int)
tClose (int)
qt_m90_update(st, cfg, t, tClose)
Parameters:
st (CycleState)
cfg (QTConfig)
t (int)
tClose (int)
qt_micro_update(st, cfg, t, tClose)
Parameters:
st (CycleState)
cfg (QTConfig)
t (int)
tClose (int)
qt_nano_update(st, cfg, t, tClose)
Parameters:
st (CycleState)
cfg (QTConfig)
t (int)
tClose (int)
QTConfig
Fields:
tz (series string)
dayStartHour (series int)
dayStartMin (series int)
keepCycles (series int)
tfDaily (series string)
tfM90 (series string)
tfMicro (series string)
tfNano (series string)
QuarterOHLC
Fields:
startTs (series int)
o (series float)
h (series float)
l (series float)
c (series float)
has (series bool)
CycleResult
Fields:
startTs (series int)
endTs (series int)
startRealized (series bool)
endRealized (series bool)
q1Ts (series int)
q2Ts (series int)
q3Ts (series int)
q4Ts (series int)
q2Realized (series bool)
q3Realized (series bool)
q4Realized (series bool)
curQuarterIndex (series int)
inWindow (series bool)
q1 (QuarterOHLC)
q2 (QuarterOHLC)
q3 (QuarterOHLC)
q4 (QuarterOHLC)
FixedCycleState
Fields:
starts (array)
lastStartTs (series int)
CycleState
Fields:
daily (FixedCycleState)
m90 (FixedCycleState)
micro (FixedCycleState)
nano (FixedCycleState)
TradingHelperLibLibrary "TradingHelperLib"
Trading Helper Library - Limit order, pip calculation and utility functions for trading bots
f_pipValue()
Calculates pip value based on symbol info
Returns: Pip value
f_pipsToPrice(pips)
Converts pip count to price difference
Parameters:
pips (float) : Number of pips
Returns: Price difference
calcExpireBarCount(minutesToExpire)
Converts minutes to bar count based on timeframe
Parameters:
minutesToExpire (float) : Duration in minutes
Returns: Bar count
calcLimitPrice(isLong, signalPrice, deviation, deviationType)
Calculates limit order price with deviation
Parameters:
isLong (bool) : True for long, false for short
signalPrice (float) : Signal price
deviation (float) : Deviation amount
deviationType (string) : Deviation type ("USDT" or "%")
Returns: Limit price
checkLimitFill(isLong, limitPrice)
Checks if limit order is filled
Parameters:
isLong (bool) : True for long, false for short
limitPrice (float) : Limit price to check
Returns: True if filled
f_multiplier(lvl, mode)
Calculates DCA multiplier based on level and mode
Parameters:
lvl (int) : DCA level
mode (string) : Multiplier mode ("Sabit", "Fibonacci", "Martingale", etc.)
Returns: Multiplier value
f_pctToPrice(pct, basePrice)
Converts percentage value to price difference
Parameters:
pct (float) : Percentage value (e.g. 2.0 = 2%)
basePrice (float) : Reference price
Returns: Price difference
f_priceChange_toPct(priceChange, basePrice)
Converts price change to percentage
Parameters:
priceChange (float) : Price difference
basePrice (float) : Reference price
Returns: Percentage value
calcMargin(notional, leverage)
Calculates margin from notional value
Parameters:
notional (float) : Trade size (e.g. $1000)
leverage (int) : Leverage value (e.g. 100)
Returns: Margin value
calcNotional(margin, leverage)
Calculates notional from margin
Parameters:
margin (float) : Collateral value
leverage (int) : Leverage value
Returns: Notional value
calcLiqPriceLongSimple(avgPrice, leverage)
Calculates simple liquidation price for Long position
Parameters:
avgPrice (float) : Average entry price
leverage (int) : Leverage value
Returns: Estimated liquidation price
calcLiqPriceShortSimple(avgPrice, leverage)
Calculates simple liquidation price for Short position
Parameters:
avgPrice (float) : Average entry price
leverage (int) : Leverage value
Returns: Estimated liquidation price
calcPnlLong(entryPrice, currentPrice, notional)
Calculates Long position PNL
Parameters:
entryPrice (float) : Entry price
currentPrice (float) : Current price
notional (float) : Position size
Returns: PNL value
calcPnlShort(entryPrice, currentPrice, notional)
Calculates Short position PNL
Parameters:
entryPrice (float) : Entry price
currentPrice (float) : Current price
notional (float) : Position size
Returns: PNL value
calcFee(notional, feeRate)
Calculates trading fee
Parameters:
notional (float) : Trade size
feeRate (float) : Fee rate in percentage (e.g. 0.1 = 0.1%)
Returns: Fee value






















