lib_b2_INDILibrary "lib_b2_INDI"
f_getChunk0()
f_getChunkNames()
f_getExpectedLength()
f_getKeyword()
f_dummyRegister()
f_loadChunk(name)
Parameters:
name (string)
Indicatori e strategie
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)
LO1_News_MasterLibrary "LO1_News_Master"
News filtering library for LO1 breakout box strategy.
Manages news event loading, policy evaluation, blocking/delay decisions,
and future trading window scanning.
DateKey(_s)
Parameters:
_s (string)
LoadEvents(this)
Parameters:
this (NewsState)
IsAllDayBlocked(this)
Parameters:
this (NewsState)
IsDelayed(this, currentTimeMs)
Parameters:
this (NewsState)
currentTimeMs (int)
GetReleaseMs(this)
Parameters:
this (NewsState)
GetReasonsToday(this)
Parameters:
this (NewsState)
GetPrimaryBlockReason(this)
Parameters:
this (NewsState)
GetPrimaryDelayReason(this)
Parameters:
this (NewsState)
GetMaxSeverity(this)
Parameters:
this (NewsState)
GetNextBlockDate(this)
Parameters:
this (NewsState)
GetNextBlockReasons(this)
Parameters:
this (NewsState)
GetNextBlockSev(this)
Parameters:
this (NewsState)
GetNextAllowedDate(this)
Parameters:
this (NewsState)
GetNextTradingDate(this)
Parameters:
this (NewsState)
GetNextTradingStartMs(this)
Parameters:
this (NewsState)
GetNextTradingReasons(this)
Parameters:
this (NewsState)
IsBlocked(this, currentTimeMs)
Parameters:
this (NewsState)
currentTimeMs (int)
WillTradeToday(this)
Parameters:
this (NewsState)
GetDelayText(this, currentTimeMs)
Parameters:
this (NewsState)
currentTimeMs (int)
GetActionUntilText(this, currentTimeMs)
Parameters:
this (NewsState)
currentTimeMs (int)
GetDelayHHMM(this, currentTimeMs)
Parameters:
this (NewsState)
currentTimeMs (int)
GetBlockedFlag(this)
Parameters:
this (NewsState)
GetDelayHour(this, currentTimeMs)
Parameters:
this (NewsState)
currentTimeMs (int)
GetDelayMinute(this, currentTimeMs)
Parameters:
this (NewsState)
currentTimeMs (int)
GetDelayEndTimestamp(this, _sessionRangeEnd, currentTimeMs)
Parameters:
this (NewsState)
_sessionRangeEnd (int)
currentTimeMs (int)
GetNextTradingWindowText(this, _defaultStartMs, _tzInput)
Parameters:
this (NewsState)
_defaultStartMs (int)
_tzInput (string)
GetEventName(_tid)
Parameters:
_tid (int)
CheckDateBlocked(this, _dateStr)
Parameters:
this (NewsState)
_dateStr (string)
CheckDateDelay(this, _dateStr)
Parameters:
this (NewsState)
_dateStr (string)
EvaluateForDate(this, _dateStr)
Parameters:
this (NewsState)
_dateStr (string)
ScanFuture(this, _sessionDateStr, _rangeEndTime, _tzInput)
Parameters:
this (NewsState)
_sessionDateStr (string)
_rangeEndTime (int)
_tzInput (string)
ScanNextEvent(this, _sessionDateStr)
Parameters:
this (NewsState)
_sessionDateStr (string)
FindNextTradingWindow(this, _todayDateStr, _rangeEndTime, _defaultStartMs, _tzInput)
Parameters:
this (NewsState)
_todayDateStr (string)
_rangeEndTime (int)
_defaultStartMs (int)
_tzInput (string)
CheckCmeEarlyClose(this, _dateStr, _rangeEndTs, _tzInput)
Parameters:
this (NewsState)
_dateStr (string)
_rangeEndTs (int)
_tzInput (string)
NewsConfig
Fields:
useSev3TimeWindow (series bool)
useSev3Filter (series bool)
useSev2Filter (series bool)
useSev1Filter (series bool)
sev3PostDelayMin (series int)
applyLibExceptionMappings (series bool)
newsTzConst (series string)
policyByTypeId (array)
typeSevByTypeId (array)
defaultPolicyHigh (series PolicyType)
defaultPolicyMedium (series PolicyType)
defaultPolicyLow (series PolicyType)
NewsCache
Fields:
dateStr (array)
timeMS (array)
severity (array)
excTag (array)
typeId (array)
libDelayMins (array)
dayStr (array)
dayStart (array)
dayEnd (array)
NewsState
Fields:
config (NewsConfig)
cache (NewsCache)
allDayBlocked (series bool)
timedBlocked (series bool)
releaseMs (series int)
reasonsToday (series string)
primaryBlockReason (series string)
primaryDelayReason (series string)
maxSevToday (series int)
evaluatedDate (series string)
initialized (series bool)
nextBlockDate (series string)
nextBlockReasons (series string)
nextBlockSev (series int)
nextAllowedDate (series string)
nextNewsDate (series string)
nextNewsReasons (series string)
nextNewsIsBlock (series bool)
nextNewsReleaseMs (series int)
nextTradingDate (series string)
nextTradingStartMs (series int)
nextTradingReasons (series string)
lastEventMs (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+
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.






















