NodialTreesLows2: ML Random Forest / Pivot Lows (Part 2 of 2)Title: `Library: ML Random Forest / Pivot Lows (Part 2 of 2)`
Description:
This library contains the second half (Trees 6-11) of the Random Forest Classifier designed to validate Pivot Lows (Long setups).
It is a direct extension of NodialTreesL1 and cannot be used alone. Due to Pine Script's compilation limits on complexity and file size, the 12-tree ensemble model has been split into two separate libraries.
### 🧩 Library Contents
This module exports the following methods representing the specific decision paths of the trained AI model:
- `tree_6(array f)`
- `tree_7(array f)`
- `tree_8(array f)`
- `tree_9(array f)`
- `tree_10(array f)`
- `tree_11(array f)`
### ⚠️ Implementation Guide
To use this library, you must combine it with Part 1.
Please refer to the NodialTreesLows1 library description for:
1. The full Integration Code Example (how to average the votes).
2. The exact Input Feature List (the 27 required metrics).
3. Detailed explanation of the Machine Learning logic.
How to finish the integration:
Import this library alongside Part 1 and add the results of `tree_6` through `tree_11` to your voting sum, as shown in the Part 1 documentation.
المؤشرات والاستراتيجيات
lib_b2_INDILibrary "lib_b2_INDI"
f_getChunk0()
f_getChunkNames()
f_getExpectedLength()
f_getKeyword()
f_dummyRegister()
f_loadChunk(name)
Parameters:
name (string)
NodialTreesLows1: ML Random Forest / Pivot Lows (Part 1 of 2)Title: `Library: ML Random Forest / Pivot Lows (Part 1 of 2)`
Description:
This library contains the first half (Trees 0-5) of a Random Forest Classifier designed to validate Pivot Lows (Long setups).
Due to Pine Script size constraints, the model is split into two libraries. You must use this library in conjunction with NodialTreesL2 to run the full ensemble.
### 🧩 System Architecture
- Model: Random Forest (12 Trees total).
- This Library: Contains `tree_0` to `tree_5`.
- Logic: Each tree analyzes a feature array and outputs a probability score.
- Target: Validating Swing Lows / Support Bounces.
### 📊 Input Requirements
The methods expect an `array` of size 27 containing market features (Price Action, Momentum, Volatility, Volume, Structure). The exact order of features is critical for the model's accuracy.
### 🛠️ Integration Example
Since this is a modular library, you need to import both parts and average their results to get the final prediction.
### 📋 Feature Mapping (Array Indexing)
To get accurate predictions, the input array must contain exactly 27 floats in this specific order:
0. Timeframe (in seconds)
1. RSI (Raw Value)
2. MACD Histogram
3. Relative Volume
4. EMA Distance (%)
5. EMA Slope
6. ATR Ratio
7. ADX
8. Buying/Selling Pressure
9. Wick Ratio
10-16. Divergences & Pattern Flags (Boolean 0.0/1.0)
17-22. Proprietary Momentum Metrics ("Onion" Structure)
23-26. Derived Volatility/Volume Features
*Note: For the advanced proprietary metrics (Indices 17-26), users must implement their own calculations or use compatible indicators.*
//@version=6
indicator("My ML Long Strategy", overlay=true)
// Import BOTH libraries
import YourUsername/NodialTreesL1/1 as rf_part1
import YourUsername/NodialTreesL2/1 as rf_part2
// ... (Calculate your 27 features and fill the array) ...
// var features = array.from(timeframe, rsi, macd, ...)
// Calculate Ensemble Probability (Average of 12 Trees)
float vote_sum = 0.0
// Trees from Part 1
vote_sum += rf_part1.tree_0(features)
vote_sum += rf_part1.tree_1(features)
vote_sum += rf_part1.tree_2(features)
vote_sum += rf_part1.tree_3(features)
vote_sum += rf_part1.tree_4(features)
vote_sum += rf_part1.tree_5(features)
// Trees from Part 2 (Trees 6-11)
vote_sum += rf_part2.tree_6(features)
vote_sum += rf_part2.tree_7(features)
vote_sum += rf_part2.tree_8(features)
vote_sum += rf_part2.tree_9(features)
vote_sum += rf_part2.tree_10(features)
vote_sum += rf_part2.tree_11(features)
// Final Probability (0.0 to 1.0)
float final_prob = vote_sum / 12.0
if final_prob > 0.60
label.new(bar_index, low, "Valid Low", color=color.green)
NodialTreesHighs2: ML Random Forest / Pivot Highs (Part 2 of 2)Title: `Library: ML Random Forest / Pivot Highs (Part 2 of 2)`
Description:
This library contains the second half (Trees 6-11) of the Random Forest Classifier designed to validate Pivot Highs (Short setups).
It is a direct extension of NodialTreesH1 and cannot be used alone. Due to Pine Script's compilation limits on complexity and file size, the 12-tree ensemble model has been split into two separate libraries.
### 🧩 Library Contents
This module exports the following methods representing the specific decision paths of the trained AI model:
- `tree_6(array f)`
- `tree_7(array f)`
- `tree_8(array f)`
- `tree_9(array f)`
- `tree_10(array f)`
- `tree_11(array f)`
### ⚠️ Implementation Guide
To use this library, you must combine it with Part 1.
Please refer to the NodialTreesH1 library description for:
1. The full Integration Code Example (how to average the votes).
2. The exact Input Feature List (the 27 required metrics).
3. Detailed explanation of the Machine Learning logic.
How to finish the integration:
Import this library alongside Part 1 and add the results of `tree_6` through `tree_11` to your voting sum, as shown in the Part 1 documentation.
NodialTreesHighs1: ML Random Forest / Pivot Highs (Part 1 of 2)Title: `Library: ML Random Forest / Pivot Highs (Part 1 of 2)`
Description:
This library contains the first half (Trees 0-5) of a Random Forest Classifier designed to validate Pivot Highs (Short setups).
Due to Pine Script size constraints, the model is split into two libraries. You must use this library in conjunction with NodialTreesH2 to run the full ensemble.
### 🧩 System Architecture
- Model: Random Forest (12 Trees total).
- This Library: Contains `tree_0` to `tree_5`.
- Logic: Each tree analyzes a feature array and outputs a probability score.
- Target: Validating Swing Highs / Resistance Rejections.
### 📊 Input Requirements
The methods expect an `array` of size 27 containing market features (Price Action, Momentum, Volatility, Volume, Structure). The exact order of features is critical for the model's accuracy.
### 🛠️ Integration Example
Since this is a modular library, you need to import both parts and average their results to get the final prediction.
### 📋 Feature Mapping (Array Indexing)
To get accurate predictions, the input array must contain exactly 27 floats in this specific order:
0. Timeframe (in seconds)
1. RSI (Raw Value)
2. MACD Histogram
3. Relative Volume
4. EMA Distance (%)
5. EMA Slope
6. ATR Ratio
7. ADX
8. Buying/Selling Pressure
9. Wick Ratio
10-16. Divergences & Pattern Flags (Boolean 0.0/1.0)
17-22. Proprietary Momentum Metrics ("Onion" Structure)
23-26. Derived Volatility/Volume Features
*Note: For the advanced proprietary metrics (Indices 17-26), users must implement their own calculations or use compatible indicators.*
//@version=6
indicator("My ML Short Strategy", overlay=true)
// Import BOTH libraries
import YourUsername/NodialTreesH1/1 as rf_part1
import YourUsername/NodialTreesH2/1 as rf_part2
// ... (Calculate your 27 features and fill the array) ...
// var features = array.from(timeframe, rsi, macd, ...)
// Calculate Ensemble Probability (Average of 12 Trees)
float vote_sum = 0.0
// Trees from Part 1
vote_sum += rf_part1.tree_0(features)
vote_sum += rf_part1.tree_1(features)
vote_sum += rf_part1.tree_2(features)
vote_sum += rf_part1.tree_3(features)
vote_sum += rf_part1.tree_4(features)
vote_sum += rf_part1.tree_5(features)
// Trees from Part 2 (Trees 6-11)
vote_sum += rf_part2.tree_6(features)
vote_sum += rf_part2.tree_7(features)
vote_sum += rf_part2.tree_8(features)
vote_sum += rf_part2.tree_9(features)
vote_sum += rf_part2.tree_10(features)
vote_sum += rf_part2.tree_11(features)
// Final Probability (0.0 to 1.0)
float final_prob = vote_sum / 12.0
if final_prob > 0.60
label.new(bar_index, high, "Valid Short", color=color.red)
NormalizedVolume_HHHLNormalized volume + HH/HL/LH/LL structure logic for confirming moves and spotting traps. Library only—intended for use with indicators. Does not plot or draw anything by itself.
lib_w2c_INDILibrary "lib_w2c_INDI"
f_getChunk18()
f_getChunk19()
f_getChunk20()
f_getChunkNames()
f_getExpectedLength()
f_getKeyword()
f_dummyRegister()
f_loadChunk(name)
Parameters:
name (string)
lib_w2b_INDILibrary "lib_w2b_INDI"
f_getChunk9()
f_getChunk10()
f_getChunk11()
f_getChunk12()
f_getChunk13()
f_getChunk14()
f_getChunk15()
f_getChunk16()
f_getChunk17()
f_getChunkNames()
f_getExpectedLength()
f_getKeyword()
f_dummyRegister()
f_loadChunk(name)
Parameters:
name (string)
lib_w2a_INDILibrary "lib_w2a_INDI"
f_getChunk0()
f_getChunk1()
f_getChunk2()
f_getChunk3()
f_getChunk4()
f_getChunk5()
f_getChunk6()
f_getChunk7()
f_getChunk8()
f_getChunkNames()
f_getExpectedLength()
f_getKeyword()
f_dummyRegister()
f_loadChunk(name)
Parameters:
name (string)
lib_w1c_INDILibrary "lib_w1c_INDI"
f_getChunk18()
f_getChunkNames()
f_getExpectedLength()
f_getKeyword()
f_dummyRegister()
f_loadChunk(name)
Parameters:
name (string)
lib_w1b_INDILibrary "lib_w1b_INDI"
f_getChunk9()
f_getChunk10()
f_getChunk11()
f_getChunk12()
f_getChunk13()
f_getChunk14()
f_getChunk15()
f_getChunk16()
f_getChunk17()
f_getChunkNames()
f_getExpectedLength()
f_getKeyword()
f_dummyRegister()
f_loadChunk(name)
Parameters:
name (string)
lib_w1a_INDILibrary "lib_w1a_INDI"
f_getChunk0()
f_getChunk1()
f_getChunk2()
f_getChunk3()
f_getChunk4()
f_getChunk5()
f_getChunk6()
f_getChunk7()
f_getChunk8()
f_getChunkNames()
f_getExpectedLength()
f_getKeyword()
f_dummyRegister()
f_loadChunk(name)
Parameters:
name (string)
lib_b1_INDILibrary "lib_b1_INDI"
f_getChunk0()
f_getChunkNames()
f_getExpectedLength()
f_getKeyword()
f_dummyRegister()
f_loadChunk(name)
Parameters:
name (string)
TPOSmartMoneyLibLibrary "TPOSmartMoneyLib"
Library for TPO (Time Price Opportunity) and Smart Money concepts including session management, PDH/PDL detection, sweeping logic, and volume profile utilities
f_price_to_tick(p)
Convert price to tick
Parameters:
p (float) : Price value
Returns: Tick value
f_tick_to_row(t, row_ticks_in)
Convert tick to row
Parameters:
t (int) : Tick value
row_ticks_in (int) : Number of ticks per row
Returns: Row index
f_row_to_price(row, row_ticks_in)
Convert row to price (midpoint)
Parameters:
row (int) : Row index
row_ticks_in (int) : Number of ticks per row
Returns: Price at row midpoint
f_calc_row_ticks(natr_ref, row_gran_mult)
Calculate dynamic row size based on normalized ATR
Parameters:
natr_ref (float) : Daily normalized ATR reference value
row_gran_mult (float) : Row granularity multiplier
Returns: Number of ticks per row
f_more_transp_pct(c, pct)
Increase color transparency by percentage
Parameters:
c (color) : Input color
pct (float) : Percentage to increase transparency (0.0 to 1.0)
Returns: Color with increased transparency
f_dom_color(dom, buy_col, sell_col, gamma, transp_weak, transp_strong)
Calculate dominance color based on buy/sell ratio
Parameters:
dom (float) : Dominance ratio (-1 to 1, negative = sell, positive = buy)
buy_col (color) : Buy dominant color
sell_col (color) : Sell dominant color
gamma (float) : Gamma correction for color intensity
transp_weak (int) : Transparency for weak dominance
transp_strong (int) : Transparency for strong dominance
Returns: Blended color
f_sess_part(sess_str, get_start)
Parse session string to get start or end time
Parameters:
sess_str (string) : Session string in format "HHMM-HHMM"
get_start (bool) : True to get start time, false to get end time
Returns: Time string in HHMM format
f_hhmm_to_h(hhmm)
Convert HHMM string to hours
Parameters:
hhmm (string) : Time string in HHMM format
Returns: Hours (0-23)
f_hhmm_to_m(hhmm)
Convert HHMM string to minutes
Parameters:
hhmm (string) : Time string in HHMM format
Returns: Minutes (0-59)
f_prev_day_window_bounds(today_day_rth, win_start, win_end, session_tz)
Calculate previous day window bounds
Parameters:
today_day_rth (int) : Today's RTH start timestamp
win_start (string) : Window start time in HHMM format
win_end (string) : Window end time in HHMM format
session_tz (string) : Session timezone
Returns: Tuple of
f_default_session_colors()
Get default session colors
Returns: Array of 4 colors
f_session_names()
Get session names
Returns: Array of 4 session names
f_process_hl(arr, rng, keep_bars, lock_to_live)
Process high/low lines with sweeping detection
Parameters:
arr (array) : Array of HLLine objects
rng (float) : Price range for visibility filtering
keep_bars (int) : Maximum bars to keep lines
lock_to_live (bool) : Whether to lock line end to current bar
Returns: 0 (for chaining)
f_process_naked_lines(arr, calc_bars, bars_per_day, keep_to_day_end)
Process naked lines (POC/VAH/VAL) with sweeping detection
Parameters:
arr (array) : Array of NakedLine objects
calc_bars (int) : Maximum calculation bars
bars_per_day (int) : Bars per day for scope calculation
keep_to_day_end (bool) : Whether to extend to day end
Returns: 0 (for chaining)
f_update_pdhl_lines(pd_hl, pdh, pdl, new_day, pd_rng, bars_per_day, pdh_color, pdl_color)
Detect and create PDH/PDL lines
Parameters:
pd_hl (array) : Array to store HLLine objects
pdh (float) : Previous day high
pdl (float) : Previous day low
new_day (bool) : Whether it's a new day
pd_rng (float) : Price range for visibility
bars_per_day (int) : Bars per day
pdh_color (color) : PDH line color
pdl_color (color) : PDL line color
Returns: 0 (for chaining)
f_poc_from_vals(keys, vals)
Calculate POC from sorted keys and values
Parameters:
keys (array) : Sorted array of row keys
vals (array) : Array of volume values
Returns: POC row key
f_value_area(keys, vals, poc_key, va_pct)
Calculate Value Area from volume distribution
Parameters:
keys (array) : Sorted array of row keys
vals (array) : Array of volume values
poc_key (int) : POC row key
va_pct (float) : Value Area percentage (typically 0.70)
Returns: Tuple of
f_find_key_sorted(keys, target)
Find key in sorted array using binary search
Parameters:
keys (array) : Sorted array of keys
target (int) : Target key to find
Returns: Index of key, or -1 if not found
f_zscore_safe(x, len)
Safe z-score calculation using built-in functions
Parameters:
x (float) : Input series
len (int) : Lookback length
Returns: Z-score
HLLine
Represents a high/low line with sweeping detection
Fields:
ln (series line) : Line object
lb (series label) : Label object
lvl (series float) : Price level
startBar (series int) : Bar index where line starts
swept (series bool) : Whether the level has been swept
isHigh (series bool) : True if this is a high, false if low
col (series color) : Line color
NakedLine
Represents a naked POC/VAH/VAL line
Fields:
ln (series line) : Line object
lb (series label) : Label object
lvl (series float) : Price level
startBar (series int) : Bar index where line starts
swept (series bool) : Whether the level has been swept
sweptBar (series int) : Bar index where swept occurred
endBar (series int) : Bar index where line should end
TrinityCore1Library "TrinityCore1"
default_config()
calc_weights(sym, cp, cs, s1, s2, s3, s4, s5, cfg)
Parameters:
sym (string)
cp (string)
cs (string)
s1 (string)
s2 (string)
s3 (string)
s4 (string)
s5 (string)
cfg (TrinityConfig)
calc_diagnostics(sym, cp, cs, s1, s2, s3, s4, s5, cfg)
Parameters:
sym (string)
cp (string)
cs (string)
s1 (string)
s2 (string)
s3 (string)
s4 (string)
s5 (string)
cfg (TrinityConfig)
TrinityWeights
Fields:
stock (series float)
s1 (series float)
s2 (series float)
s3 (series float)
s4 (series float)
s5 (series float)
cash (series float)
SafeDiag
Fields:
id (series string)
vol (series float)
corr (series float)
dd (series float)
score (series float)
final_w (series float)
TrinityDiagLite
Fields:
ready_code (series int)
drop_code (series int)
is_ready (series bool)
risk_gate (series bool)
p_value (series float)
d_bar_index (series int)
TrinityDiagFull
Fields:
base (TrinityDiagLite)
raw_vol (series float)
adj_vol (series float)
target_w (series float)
penalty_mult (series float)
sd1 (SafeDiag)
sd2 (SafeDiag)
sd3 (SafeDiag)
sd4 (SafeDiag)
sd5 (SafeDiag)
TrinityConfig
Fields:
enabled (series bool)
len_20 (series int)
w_20 (series float)
len_63 (series int)
w_63 (series float)
len_126 (series int)
w_126 (series float)
len_252 (series int)
w_252 (series float)
risk_floor (series float)
risk_factor (series float)
target_vol_stock (series float)
target_vol_safe (series float)
gov_max_lev (series float)
gov_min_mult (series float)
top_k (series int)
sqs_base (series float)
sqs_w_corr (series float)
sqs_w_vol (series float)
sqs_w_dd (series float)
sqs_range_corr (series float)
sqs_range_dd (series float)
fall_thr (series float)
rate_fall (series float)
rate_accel (series float)
penalty_val (series float)
ready_bars (series int)
RSMPatternLibLibrary "RSMPatternLib"
RSM Pattern Library - All chart patterns from PATTERNS.md
Implements: Candlestick patterns, Support/Resistance, Gaps, Triangles, Volume Divergence, and more
ALL PATTERNS ARE OWN IMPLEMENTATION - No external dependencies
EDGE CASES HANDLED:
- Zero/tiny candle bodies
- Missing volume data
- Low bar count scenarios
- Integer division issues
- Price normalization for different instruments
bullishEngulfing(minBodyRatio, minPrevBodyRatio)
Detects Bullish Engulfing pattern
Parameters:
minBodyRatio (float) : Minimum body size as ratio of total range (default 0.3)
minPrevBodyRatio (float) : Minimum previous candle body ratio to filter dojis (default 0.1)
Returns: bool True when bullish engulfing detected
EDGE CASES: Handles doji previous candle, zero range, tiny bodies
bearishEngulfing(minBodyRatio, minPrevBodyRatio)
Detects Bearish Engulfing pattern
Parameters:
minBodyRatio (float) : Minimum body size as ratio of total range (default 0.3)
minPrevBodyRatio (float) : Minimum previous candle body ratio to filter dojis (default 0.1)
Returns: bool True when bearish engulfing detected
EDGE CASES: Handles doji previous candle, zero range, tiny bodies
doji(maxBodyRatio, minRangeAtr)
Detects Doji candle (indecision)
Parameters:
maxBodyRatio (float) : Maximum body size as ratio of total range (default 0.1)
minRangeAtr (float) : Minimum range as multiple of ATR to filter flat candles (default 0.3)
Returns: bool True when doji detected
EDGE CASES: Filters out no-movement bars, handles zero range
shootingStar(wickMultiplier, maxLowerWickRatio, minBodyAtrRatio)
Detects Shooting Star (bearish reversal)
Parameters:
wickMultiplier (float) : Upper wick must be at least this times the body (default 2.0)
maxLowerWickRatio (float) : Lower wick max as ratio of body (default 0.5)
minBodyAtrRatio (float) : Minimum body size as ratio of ATR (default 0.1)
Returns: bool True when shooting star detected
EDGE CASES: Handles zero body (uses range-based check), tiny bodies
hammer(wickMultiplier, maxUpperWickRatio, minBodyAtrRatio)
Detects Hammer (bullish reversal)
Parameters:
wickMultiplier (float) : Lower wick must be at least this times the body (default 2.0)
maxUpperWickRatio (float) : Upper wick max as ratio of body (default 0.5)
minBodyAtrRatio (float) : Minimum body size as ratio of ATR (default 0.1)
Returns: bool True when hammer detected
EDGE CASES: Handles zero body (uses range-based check), tiny bodies
invertedHammer(wickMultiplier, maxLowerWickRatio)
Detects Inverted Hammer (bullish reversal after downtrend)
Parameters:
wickMultiplier (float) : Upper wick must be at least this times the body (default 2.0)
maxLowerWickRatio (float) : Lower wick max as ratio of body (default 0.5)
Returns: bool True when inverted hammer detected
EDGE CASES: Same as shootingStar but requires bullish close
hangingMan(wickMultiplier, maxUpperWickRatio)
Detects Hanging Man (bearish reversal after uptrend)
Parameters:
wickMultiplier (float) : Lower wick must be at least this times the body (default 2.0)
maxUpperWickRatio (float) : Upper wick max as ratio of body (default 0.5)
Returns: bool True when hanging man detected
NOTE: Identical to hammer - context (uptrend) determines meaning
morningStar(requireGap, minAvgBars)
Detects Morning Star (3-candle bullish reversal)
Parameters:
requireGap (bool) : Whether to require gap between candles (default false for crypto/forex)
minAvgBars (int) : Minimum bars for average body calculation (default 14)
Returns: bool True when morning star pattern detected
EDGE CASES: Gap is optional, handles low bar count, uses shifted average
eveningStar(requireGap, minAvgBars)
Detects Evening Star (3-candle bearish reversal)
Parameters:
requireGap (bool) : Whether to require gap between candles (default false for crypto/forex)
minAvgBars (int) : Minimum bars for average body calculation (default 14)
Returns: bool True when evening star pattern detected
EDGE CASES: Gap is optional, handles low bar count
gapUp()
Detects Gap Up
Returns: bool True when current bar opens above previous bar's high
gapDown()
Detects Gap Down
Returns: bool True when current bar opens below previous bar's low
gapSize()
Returns gap size in price
Returns: float Gap size (positive for gap up, negative for gap down, 0 for no gap)
gapPercent()
Returns gap size as percentage
Returns: float Gap size as percentage of previous close
gapType(volAvgLen, breakawayMinPct, highVolMult)
Classifies gap type based on volume
Parameters:
volAvgLen (int) : Length for volume average (default 20)
breakawayMinPct (float) : Minimum gap % for breakaway (default 1.0)
highVolMult (float) : Volume multiplier for high volume (default 1.5)
Returns: string Gap type: "Breakaway", "Common", "Continuation", or "None"
EDGE CASES: Handles missing volume data, low bar count
swingHigh(leftBars, rightBars)
Detects swing high using pivot
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
Returns: float Swing high price or na
swingLow(leftBars, rightBars)
Detects swing low using pivot
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
Returns: float Swing low price or na
higherHigh(leftBars, rightBars, lookback)
Checks if current swing high is higher than previous swing high
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : How many bars back to search for previous pivot (default 50)
Returns: bool True when higher high pattern detected
EDGE CASES: Searches backwards for pivots instead of using var (library-safe)
higherLow(leftBars, rightBars, lookback)
Checks if current swing low is higher than previous swing low
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : How many bars back to search for previous pivot (default 50)
Returns: bool True when higher low pattern detected
lowerHigh(leftBars, rightBars, lookback)
Checks if current swing high is lower than previous swing high
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : How many bars back to search for previous pivot (default 50)
Returns: bool True when lower high pattern detected
lowerLow(leftBars, rightBars, lookback)
Checks if current swing low is lower than previous swing low
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : How many bars back to search for previous pivot (default 50)
Returns: bool True when lower low pattern detected
bullishTrend(leftBars, rightBars, lookback)
Detects Bullish Trend (HH + HL within lookback)
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : Lookback period (default 50)
Returns: bool True when making higher highs AND higher lows
bearishTrend(leftBars, rightBars, lookback)
Detects Bearish Trend (LH + LL within lookback)
Parameters:
leftBars (int) : Bars to left for pivot (default 5)
rightBars (int) : Bars to right for pivot (default 5)
lookback (int) : Lookback period (default 50)
Returns: bool True when making lower highs AND lower lows
nearestResistance(lookback, leftBars, rightBars)
Finds nearest resistance level above current price
Parameters:
lookback (int) : Number of bars to look back (default 50)
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
Returns: float Nearest resistance level or na
EDGE CASES: Pre-computes pivots, handles bounds properly
nearestSupport(lookback, leftBars, rightBars)
Finds nearest support level below current price
Parameters:
lookback (int) : Number of bars to look back (default 50)
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
Returns: float Nearest support level or na
resistanceBreakout(lookback, leftBars, rightBars)
Detects resistance breakout
Parameters:
lookback (int) : Number of bars to look back (default 50)
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
Returns: bool True when price breaks above resistance
EDGE CASES: Uses previous bar's resistance to avoid lookahead
supportBreakdown(lookback, leftBars, rightBars)
Detects support breakdown
Parameters:
lookback (int) : Number of bars to look back (default 50)
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
Returns: bool True when price breaks below support
bullishVolumeDivergence(leftBars, rightBars, lookback)
Detects Bullish Volume Divergence (price makes lower low, volume decreases)
Parameters:
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
lookback (int) : Bars to search for previous pivot (default 50)
Returns: bool True when bullish volume divergence detected
EDGE CASES: Library-safe (no var), searches for previous pivot
bearishVolumeDivergence(leftBars, rightBars, lookback)
Detects Bearish Volume Divergence (price makes higher high, volume decreases)
Parameters:
leftBars (int) : Pivot left bars (default 5)
rightBars (int) : Pivot right bars (default 5)
lookback (int) : Bars to search for previous pivot (default 50)
Returns: bool True when bearish volume divergence detected
rangeContracting(lookback)
Detects if price is in a contracting range (triangle formation)
Parameters:
lookback (int) : Bars to analyze (default 20)
Returns: bool True when range is contracting
EDGE CASES: Uses safe integer division, checks minimum lookback
ascendingTriangle(lookback, flatTolerance)
Detects Ascending Triangle (flat top, rising bottom)
Parameters:
lookback (int) : Bars to analyze (default 20)
flatTolerance (float) : Max normalized slope for "flat" line (default 0.002)
Returns: bool True when ascending triangle detected
EDGE CASES: Safe division, normalized slope, minimum lookback
descendingTriangle(lookback, flatTolerance)
Detects Descending Triangle (falling top, flat bottom)
Parameters:
lookback (int) : Bars to analyze (default 20)
flatTolerance (float) : Max normalized slope for "flat" line (default 0.002)
Returns: bool True when descending triangle detected
symmetricalTriangle(lookback, minSlope)
Detects Symmetrical Triangle (converging trend lines)
Parameters:
lookback (int) : Bars to analyze (default 20)
minSlope (float) : Minimum normalized slope magnitude (default 0.0005)
Returns: bool True when symmetrical triangle detected
doubleBottom(tolerance, minSpanBars, lookback)
Detects Double Bottom (W pattern) - OWN IMPLEMENTATION
Two swing lows at similar price levels with a swing high between them
Parameters:
tolerance (float) : Max price difference between lows as % (default 3)
minSpanBars (int) : Minimum bars between the two lows (default 5)
lookback (int) : Max bars to search for pattern (default 100)
Returns: bool True when double bottom detected
doubleTop(tolerance, minSpanBars, lookback)
Detects Double Top (M pattern) - OWN IMPLEMENTATION
Two swing highs at similar price levels with a swing low between them
Parameters:
tolerance (float) : Max price difference between highs as % (default 3)
minSpanBars (int) : Minimum bars between the two highs (default 5)
lookback (int) : Max bars to search for pattern (default 100)
Returns: bool True when double top detected
tripleBottom(tolerance, minSpanBars, lookback)
Detects Triple Bottom - OWN IMPLEMENTATION
Three swing lows at similar price levels
Parameters:
tolerance (float) : Max price difference between lows as % (default 3)
minSpanBars (int) : Minimum total bars for pattern (default 10)
lookback (int) : Max bars to search for pattern (default 150)
Returns: bool True when triple bottom detected
tripleTop(tolerance, minSpanBars, lookback)
Detects Triple Top - OWN IMPLEMENTATION
Three swing highs at similar price levels
Parameters:
tolerance (float) : Max price difference between highs as % (default 3)
minSpanBars (int) : Minimum total bars for pattern (default 10)
lookback (int) : Max bars to search for pattern (default 150)
Returns: bool True when triple top detected
bearHeadShoulders()
Detects Bearish Head and Shoulders (OWN IMPLEMENTATION)
Head is higher than both shoulders, shoulders roughly equal, with valid neckline
STRICT VERSION - requires proper structure, neckline, and minimum span
Returns: bool True when bearish H&S detected
bullHeadShoulders()
Detects Bullish (Inverse) Head and Shoulders (OWN IMPLEMENTATION)
Head is lower than both shoulders, shoulders roughly equal, with valid neckline
STRICT VERSION - requires proper structure, neckline, and minimum span
Returns: bool True when bullish H&S detected
bearAscHeadShoulders()
Detects Bearish Ascending Head and Shoulders (variant)
Returns: bool True when pattern detected
bullAscHeadShoulders()
Detects Bullish Ascending Head and Shoulders (variant)
Returns: bool True when pattern detected
bearDescHeadShoulders()
Detects Bearish Descending Head and Shoulders (variant)
Returns: bool True when pattern detected
bullDescHeadShoulders()
Detects Bullish Descending Head and Shoulders (variant)
Returns: bool True when pattern detected
isSwingLow()
Re-export: Detects swing low
Returns: bool True when swing low detected
isSwingHigh()
Re-export: Detects swing high
Returns: bool True when swing high detected
swingHighPrice(idx)
Re-export: Gets swing high price at index
Parameters:
idx (int) : Index (0 = most recent)
Returns: float Swing high price
swingLowPrice(idx)
Re-export: Gets swing low price at index
Parameters:
idx (int) : Index (0 = most recent)
Returns: float Swing low price
swingHighBarIndex(idx)
Re-export: Gets swing high bar index
Parameters:
idx (int) : Index (0 = most recent)
Returns: int Bar index of swing high
swingLowBarIndex(idx)
Re-export: Gets swing low bar index
Parameters:
idx (int) : Index (0 = most recent)
Returns: int Bar index of swing low
cupBottom(smoothLen, minDepthAtr, maxDepthAtr)
Detects Cup and Handle pattern formation
Uses price acceleration and depth analysis
Parameters:
smoothLen (int) : Smoothing length for price (default 10)
minDepthAtr (float) : Minimum cup depth as ATR multiple (default 1.0)
maxDepthAtr (float) : Maximum cup depth as ATR multiple (default 5.0)
Returns: bool True when potential cup bottom detected
EDGE CASES: Added depth filter, ATR validation
cupHandle(lookback, maxHandleRetraceRatio)
Detects potential handle formation after cup
Parameters:
lookback (int) : Bars to look back for cup (default 30)
maxHandleRetraceRatio (float) : Maximum handle retracement of cup depth (default 0.5)
Returns: bool True when handle pattern detected
bullishPatternCount()
Returns count of bullish patterns detected
Returns: int Number of bullish patterns currently active
bearishPatternCount()
Returns count of bearish patterns detected
Returns: int Number of bearish patterns currently active
detectedPatterns()
Returns string description of detected patterns
Returns: string Comma-separated list of detected patterns
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+






















