Pine Script® Bibliothek
Techindicator
Adekoyotemon_VolumeProfileLibLibrary "VolumeProfileLib"
Auction-focused Volume Profile helper library.
This library does NOT build a full historical profile by itself.
It analyzes already-built aligned arrays:
volumes = volume at price row i
prices = price row center for row i
validate_profile(volumes, prices)
Validates volume/profile arrays.
Parameters:
volumes (array) : Volume row array.
prices (array) : Price row-center array.
Returns: true if arrays are non-empty, aligned, and contain no na values.
get_total_volume(volumes)
Sums all profile volume.
Parameters:
volumes (array) : Volume row array.
Returns: Total volume. Returns 0.0 if empty.
get_tick_size(prices)
Estimates row/tick spacing from adjacent price rows.
Parameters:
prices (array) : Price row-center array.
Returns: Absolute row spacing. Returns na if fewer than 2 rows.
get_profile_range(prices)
Returns profile low/high from price rows.
Parameters:
prices (array) : Price row-center array.
Returns:
get_poc_index(volumes)
Finds the POC index.
Parameters:
volumes (array) : Volume row array.
Returns: Index of highest-volume row. Returns -1 if invalid.
get_poc(volumes, prices)
Calculates Point of Control price.
Parameters:
volumes (array) : Volume row array.
prices (array) : Price row-center array.
Returns: POC price. Returns na if invalid.
get_value_area(volumes, prices, vaPercent)
Calculates Value Area High and Value Area Low.
Expands one row at a time from POC toward the side with greater adjacent volume.
Parameters:
volumes (array) : Volume row array.
prices (array) : Price row-center array.
vaPercent (float) : Value area percent, usually 70.
Returns: . Returns if invalid.
get_hvns(volumes, prices, window, thresholdPct)
Identifies High Volume Nodes using local maxima.
Parameters:
volumes (array) : Volume row array.
prices (array) : Price row-center array.
window (int) : Rows left/right to compare.
thresholdPct (float) : Minimum percent of max profile volume required.
Returns: Array of HVN prices.
get_lvns(volumes, prices, window, thresholdPct)
Identifies Low Volume Nodes using local minima.
Parameters:
volumes (array) : Volume row array.
prices (array) : Price row-center array.
window (int) : Rows left/right to compare.
thresholdPct (float) : Maximum percent of max profile volume allowed.
Returns: Array of LVN prices.
near_hvn(price, hvns, tickSize, thresholdTicks)
Checks whether price is near any HVN.
Parameters:
price (float) : Current/reference price.
hvns (array) : HVN price array.
tickSize (float) : Instrument tick/row size.
thresholdTicks (float) : Distance threshold in ticks.
Returns: true if price is near an HVN.
near_lvn(price, lvns, tickSize, thresholdTicks)
Checks whether price is near any LVN.
Parameters:
price (float) : Current/reference price.
lvns (array) : LVN price array.
tickSize (float) : Instrument tick/row size.
thresholdTicks (float) : Distance threshold in ticks.
Returns: true if price is near an LVN.
get_skew_score(volumes, prices)
Measures profile skew around the profile midpoint.
Positive = volume weighted toward upper half.
Negative = volume weighted toward lower half.
Parameters:
volumes (array)
prices (array)
Returns: Skew score from roughly -100 to +100.
get_profile_shape(volumes, prices)
Classifies profile shape using POC position, skew, HVN/LVN structure, and central concentration.
Parameters:
volumes (array)
prices (array)
Returns: "D", "P", "b", "B", "TREND_UP", "TREND_DOWN", "THIN", or "INVALID".
get_poc_migration(currentPOC, priorPOC, tickSize)
Compares current POC against prior POC.
Parameters:
currentPOC (float)
priorPOC (float)
tickSize (float)
Returns: 1 = up, -1 = down, 0 = flat/unknown.
get_value_migration(vah, val, priorVAH, priorVAL)
Compares current value area against prior value area.
Parameters:
vah (float)
val (float)
priorVAH (float)
priorVAL (float)
Returns: 1 = value migrating higher, -1 = lower, 0 = overlapping/flat.
price_vs_value(price, vah, val)
Locates price relative to value.
Parameters:
price (float)
vah (float)
val (float)
Returns: 1 = above VAH, -1 = below VAL, 0 = inside value.
is_accepting_above_vah(closePrice, vah, barsHeld, requiredBars)
Detects close acceptance above VAH.
barsHeld should be supplied by caller using its own consecutive-bar counter.
Parameters:
closePrice (float)
vah (float)
barsHeld (int)
requiredBars (int)
Returns: true if close remains above VAH and barsHeld requirement is met.
is_rejecting_above_vah(highPrice, closePrice, vah)
Detects rejection above VAH.
Parameters:
highPrice (float)
closePrice (float)
vah (float)
Returns: true if high pierced VAH but close returned below VAH.
is_accepting_below_val(closePrice, val, barsHeld, requiredBars)
Detects close acceptance below VAL.
barsHeld should be supplied by caller using its own consecutive-bar counter.
Parameters:
closePrice (float)
val (float)
barsHeld (int)
requiredBars (int)
Returns: true if close remains below VAL and barsHeld requirement is met.
is_rejecting_below_val(lowPrice, closePrice, val)
Detects rejection below VAL.
Parameters:
lowPrice (float)
closePrice (float)
val (float)
Returns: true if low pierced VAL but close returned above VAL.
detect_value_trap(highPrice, lowPrice, closePrice, vah, val)
Detects value-edge trap.
Parameters:
highPrice (float)
lowPrice (float)
closePrice (float)
vah (float)
val (float)
Returns: 1 = trapped shorts/reclaim below VAL, -1 = trapped longs/failure above VAH, 0 = none.
get_profile_bias_score(shape, pocMigration, valueMigration, priceLocation, acceptingAboveVAH, acceptingBelowVAL, rejectingAboveVAH, rejectingBelowVAL)
Converts profile shape, migration, and location into directional auction score.
Parameters:
shape (string)
pocMigration (int)
valueMigration (int)
priceLocation (int)
acceptingAboveVAH (bool)
acceptingBelowVAL (bool)
rejectingAboveVAH (bool)
rejectingBelowVAL (bool)
Returns: Bias score from -100 to +100.
analyze_profile(volumes, prices, price, highPrice, lowPrice, closePrice, priorPOC, priorVAH, priorVAL, barsAboveVAH, barsBelowVAL, requiredAcceptBars, nodeWindow, hvnThresholdPct, lvnThresholdPct, nodeThresholdTicks, vaPercent)
Full lightweight auction analysis.
Caller must pass prior POC/value values and acceptance bar counters.
Parameters:
volumes (array)
prices (array)
price (float)
highPrice (float)
lowPrice (float)
closePrice (float)
priorPOC (float)
priorVAH (float)
priorVAL (float)
barsAboveVAH (int)
barsBelowVAL (int)
requiredAcceptBars (int)
nodeWindow (int)
hvnThresholdPct (float)
lvnThresholdPct (float)
nodeThresholdTicks (float)
vaPercent (float)
Returns:
Pine Script® Bibliothek
Adekoyotemohn_Adv_VWAP_LibLibrary "AdvancedVWAPModels"
rolling(src, vol, length)
Parameters:
src (float)
vol (float)
length (int)
rollingWithBands(src, vol, length, mult)
Parameters:
src (float)
vol (float)
length (int)
mult (float)
anchored(src, vol, resetCondition)
Parameters:
src (float)
vol (float)
resetCondition (bool)
anchoredWithBands(src, vol, resetCondition, mult)
Parameters:
src (float)
vol (float)
resetCondition (bool)
mult (float)
periodAnchored(src, vol, anchorTf)
Parameters:
src (float)
vol (float)
anchorTf (string)
rvolWeighted(src, vol, length)
Parameters:
src (float)
vol (float)
length (int)
liquidityAnchored(src, vol, length, threshold)
Parameters:
src (float)
vol (float)
length (int)
threshold (float)
crossings(src, res)
Parameters:
src (float)
res (vwapResult)
rangeHits(highSrc, lowSrc, closeSrc, res)
Parameters:
highSrc (float)
lowSrc (float)
closeSrc (float)
res (vwapResult)
timeAnchored(src, vol, sessionStr)
Parameters:
src (float)
vol (float)
sessionStr (string)
volumeAnchored(src, vol, threshold)
Parameters:
src (float)
vol (float)
threshold (float)
zScore(src, vwap, stdev)
Parameters:
src (float)
vwap (float)
stdev (float)
evwap(src, vol, length)
Parameters:
src (float)
vol (float)
length (int)
multiRolling(src, vol, lengths)
Parameters:
src (float)
vol (float)
lengths (array)
vwapResult
Fields:
basis (series float)
upper (series float)
lower (series float)
vwapSignals
Fields:
crossUp (series bool)
crossDown (series bool)
upperHit (series bool)
lowerHit (series bool)
Pine Script® Bibliothek
RegimeLibLibrary "RegimeLib"
RegimeLib — Bayesian online change-point detection (BOCPD) with score-driven variance.
Implements Tsaknaki, Lillo, Mazzarisi 2023 (arXiv:2307.02375) score-driven extension
to Adams & MacKay 2007 BOCPD. Maintains run-length distribution P(r_t | data_{1:t})
and detects regime changes when MAP run length resets.
Layer L0 (imports NumLib/4 for math helpers only).
DESIGN DECISIONS:
1. Score-driven variance adaptation (GARCH-like) handles heteroskedasticity.
2. Broadcast pattern: single BOCPD instance shared across multiple setups via regime_id.
3. varip state arrays (run_length_probs, run_means, run_variances) persist across bars.
4. Compute cost: O(L) per bar where L = max_run_length (default 100).
f_default_regime_reading()
Create default RegimeReading
Returns: Empty RegimeReading
f_bocpd_regime_score_driven(x, hazard, max_run_length, omega, alpha, beta, rl_probs, run_means, run_vars, prev_map, regime_counter)
BOCPD with score-driven variance adaptation (Tsaknaki et al. 2023)
Parameters:
x (float) : Current observation (e.g. log return)
hazard (simple float) : Hazard rate H (probability of regime change per bar), default 1/250
max_run_length (simple int) : Maximum run length L to track (caps array size), default 100
omega (simple float) : Score-driven variance ω parameter, default 1e-4
alpha (simple float) : Score-driven variance α parameter (score weight), default 0.05
beta (simple float) : Score-driven variance β parameter (persistence), default 0.94
rl_probs (array) : varip array run-length probabilities (size L+1, caller-managed)
run_means (array) : varip array online means per run (size L+1, caller-managed)
run_vars (array) : varip array online variances per run (size L+1, caller-managed)
prev_map (int) : varip int previous MAP run length (caller-managed)
regime_counter (float) : varip float regime ID counter (caller-managed)
Returns: RegimeReading
f_bocpd_regime(x, hazard, max_run_length, rl_probs, run_means, run_vars, prev_map, regime_counter)
Vanilla BOCPD (fixed variance, no score-driven adaptation)
Parameters:
x (float) : Current observation
hazard (simple float) : Hazard rate H
max_run_length (simple int) : Maximum run length L
rl_probs (array) : varip array run-length probabilities (caller-managed)
run_means (array) : varip array online means per run (caller-managed)
run_vars (array) : varip array online variances per run (caller-managed)
prev_map (int) : varip int previous MAP run length (caller-managed)
regime_counter (float) : varip float regime ID counter (caller-managed)
Returns: RegimeReading
f_init_bocpd_state(max_run_length, initial_mean, initial_var)
Initialize BOCPD state arrays (call once on first bar)
Parameters:
max_run_length (simple int) : Maximum run length L
initial_mean (float) : Initial mean estimate
initial_var (float) : Initial variance estimate
Returns: Tuple of (rl_probs, run_means, run_vars)
RegimeReading
RegimeReading — output of BOCPD regime detector
Fields:
map_run_length (series int) : Current MAP run length (bars since last regime change)
change_point_detected (series bool) : True if regime change detected on this bar
regime_id (series float) : Incrementing counter per regime (resets on change-point)
predictive_likelihood (series float) : Diagnostic: P(x_t | data_in_run_r*)
current_variance (series float) : Score-driven variance estimate at MAP run length
Pine Script® Bibliothek
OscLibLibrary "OscLib"
OscLib — Oscillator primitives and normalization utilities.
Provides centered/clamped normalization for bounded and unbounded oscillators,
multi-oscillator dispatcher, and pivot-based divergence detection.
Architecture: L0 (no library dependencies, uses ta.* primitives only)
f_center_bounded(raw, midpoint)
Centered normalization for bounded oscillators (RSI, MFI, Stoch, WPR)
Parameters:
raw (float) : Raw oscillator value
midpoint (float) : Center point (typically 50.0 for RSI/MFI/Stoch)
Returns: Centered value in range
f_clamp_normalize(raw, threshold)
Clamped normalization for unbounded oscillators (CCI, MACD Hist, ATR)
Parameters:
raw (float) : Raw oscillator value
threshold (float) : Scaling threshold (e.g., 200 for CCI, 2*ATR for MACD)
Returns: Clamped value in range
f_compute_osc(kind, src, len)
Multi-oscillator dispatcher
Parameters:
kind (string) : Oscillator type: "RSI", "CCI", "MFI", "STOCH", "WPR"
src (float) : Source series (typically close or hlc3)
len (simple int) : Oscillator period/length
Returns: Raw oscillator value
f_divergence_pivot(osc, price, lb_left, lb_right)
Pivot-based divergence detection (matches REOS production pattern)
Parameters:
osc (float) : Oscillator series
price (float) : Price series (typically close)
lb_left (int) : Left lookback for pivot detection
lb_right (int) : Right lookback for pivot detection
Returns:
bearish_div: price makes higher high, oscillator doesn't
bullish_div: price makes lower low, oscillator doesn't
Pine Script® Bibliothek
fpa_unified_libLibrary "fpa_unified_lib"
lineStyle(styleText)
Parameters:
styleText (string)
labelSize(sizeText)
Parameters:
sizeText (string)
normalizeSession(sessionInput, hideWeekends)
Parameters:
sessionInput (string)
hideWeekends (bool)
isSessionActive(sessionInput, timezoneInput)
Parameters:
sessionInput (string)
timezoneInput (string)
tfInRange(lowTf, highTf)
Parameters:
lowTf (string)
highTf (string)
parseTradingDayOpenMinutes(sessionInput)
Parameters:
sessionInput (string)
safeColor(c, transp)
Parameters:
c (color)
transp (int)
updateRay(lineRef, shouldShow, startBarIndex, yPrice, lineColor, lineWidth, lineStyleText, rightOffsetBars, lookbackBars)
Parameters:
lineRef (line)
shouldShow (bool)
startBarIndex (int)
yPrice (float)
lineColor (color)
lineWidth (int)
lineStyleText (string)
rightOffsetBars (int)
lookbackBars (int)
updateLabel(labelRef, shouldShow, yPrice, textValue, labelColor, rightOffsetBars, sizeText)
Parameters:
labelRef (label)
shouldShow (bool)
yPrice (float)
textValue (string)
labelColor (color)
rightOffsetBars (int)
sizeText (string)
trimLines(arr, limit)
Parameters:
arr (array)
limit (int)
trimLabels(arr, limit)
Parameters:
arr (array)
limit (int)
parseFloatList(textArea)
Parameters:
textArea (string)
Pine Script® Bibliothek
cloudTheoryLibrary "cloudTheory"
// OBJECTTIVE: A Combination of EMA to Draw Cloud Pattern on Chart
//
// The "2-EMA Line System" is one of the most oldest and durable
// frameworks in technical analysis where we plot one "fast" (short)
// and one "slow" (long) exponential moving average line on the same
// chart and their relationships determine the state of the security.
drawCloud(fastLength, slowLength, src)
Parameters:
fastLength (simple int) : - Fast EMA Length, the shorter length which
typically determines the current rhythm of the security.
slowLength (simple int) : - Slow EMA Length, the longer length which
determines the underlying drift of the security.
src (float) : - Which value of the candle should be used to calculate
the moving average; defaults to candle close value.
Returns: - EMA
Values and the flags to determine the current sentiment.
Pine Script® Bibliothek
si_squeeze_live_summaryLibrary "si_squeeze_live_summary"
Lane-owned live summary entrypoint for the squeeze / expansion prototype. Staged for future host wiring without moving squeeze logic into the meta layer.
calc_squeeze_live_summary(regime_fast_length, regime_slow_length, regime_compression_length, regime_atr_length, regime_compression_threshold, structure_pivot_left, structure_pivot_right, structure_basis_length, structure_displacement_atr, fair_value_atr_length, fair_value_extreme_atr)
Public host-callable live squeeze summary surface. Returns the standardized 10-field primitive tuple.
Parameters:
regime_fast_length (simple int)
regime_slow_length (simple int)
regime_compression_length (int)
regime_atr_length (simple int)
regime_compression_threshold (float)
structure_pivot_left (int)
structure_pivot_right (int)
structure_basis_length (simple int)
structure_displacement_atr (float)
fair_value_atr_length (simple int)
fair_value_extreme_atr (float)
Pine Script® Bibliothek
EntropyLibLibrary "EntropyLib"
Entropy Library - Composite entropy calculation for oscillators with binary and ternary modes
f_clamp(x, lo, hi)
Clamp value to range
Parameters:
x (float) : Value to clamp
lo (float) : Lower bound
hi (float) : Upper bound
Returns: Clamped value
f_binary_entropy(x, length)
Calculate Shannon binary entropy from a series
Parameters:
x (float) : Input series (oscillator, price changes, etc.)
length (int) : Lookback period for entropy calculation
Returns: Binary entropy value where 0=deterministic, 1=maximum uncertainty
f_ternary_entropy(x, length, flatPct)
Calculate ternary entropy (up/down/flat states)
Parameters:
x (float) : Input series
length (int) : Lookback period for entropy calculation
flatPct (simple float) : Percentile threshold for flat zone (e.g., 55.0 means middle 55% is "flat")
Returns: Ternary entropy value
f_composite_entropy(osc, price, volume, length, osc_weight, price_weight, vol_weight, mode, flatPct)
Calculate composite entropy from oscillator, price, and volume components
Parameters:
osc (float) : Primary oscillator series
price (float) : Price series (typically close)
volume (float) : Volume series
length (int) : Lookback period for entropy calculation
osc_weight (float) : Weight for oscillator entropy component (e.g., 0.4)
price_weight (float) : Weight for price entropy component (e.g., 0.4)
vol_weight (float) : Weight for volume entropy component (e.g., 0.2)
mode (string) : Entropy mode: "binary" or "ternary"
flatPct (simple float) : Percentile for ternary flat zone (only used if mode="ternary", default 55.0)
Returns: Composite entropy
f_composite_entropy_simple(osc, length, mode, flatPct)
Simplified composite entropy using only oscillator
Parameters:
osc (float) : Oscillator series
length (int) : Lookback period
mode (string) : Entropy mode: "binary" or "ternary"
flatPct (simple float) : Percentile for ternary flat zone (default 55.0)
Returns: Composite entropy
f_composite_entropy_standard(osc, price, length, mode, flatPct)
Standard composite entropy with oscillator + price (50/50 split, no volume)
Parameters:
osc (float) : Oscillator series
price (float) : Price series
length (int) : Lookback period
mode (string) : Entropy mode: "binary" or "ternary"
flatPct (simple float) : Percentile for ternary flat zone (default 55.0)
Returns: Composite entropy
f_entropy_weighted_signal(signal, entropy)
Apply entropy weighting to a signal (REOS-style formula)
Parameters:
signal (float) : Input signal/oscillator
entropy (float) : Entropy value
Returns: Entropy-weighted signal: sign(signal) * |signal| * (1 - entropy)
f_detect_true_pivots(osc_series, price_series, pivot_left, pivot_right, entropy_len, max_entropy)
Detects true structural pivots by filtering out high-entropy noise
Parameters:
osc_series (float) : The oscillator series to evaluate
price_series (float) : The underlying price series
pivot_left (int) : Bars to the left of the pivot
pivot_right (int) : Bars to the right of the pivot
entropy_len (int) : Lookback window for entropy calculation (usually 8-14)
max_entropy (float) : The maximum allowed joint entropy for a valid pivot (e.g., 0.4)
Returns: - True pivot flags and pivot values
f_detect_spring(osc_series, price_series, chaos_len, osc_overbought, osc_oversold, min_chaos)
Detects extreme market compression (chaos) at oscillator extremes
Parameters:
osc_series (float) : The oscillator series to evaluate
price_series (float) : The underlying price series
chaos_len (int) : Ultra-short lookback window (e.g., 3, 4, or 5 bars)
osc_overbought (float) : The upper extreme threshold (e.g., 90)
osc_oversold (float) : The lower extreme threshold (e.g., 10)
min_chaos (float) : The minimum joint entropy required to signal compression (e.g., 0.8)
Returns: - Spring flag and chaos intensity
f_optimize_thresholds(osc_series, base_ob, base_os, entropy_len, expansion_factor)
Dynamically adjusts OB/OS levels based on background entropy
Parameters:
osc_series (float) : The oscillator series
base_ob (float) : The baseline overbought level (e.g., 80)
base_os (float) : The baseline oversold level (e.g., 20)
entropy_len (int) : Lookback for the background entropy evaluation (e.g., 30)
expansion_factor (float) : How much the bands can expand/contract (e.g., 10.0 points)
Returns: - Adaptive overbought and oversold thresholds
Pine Script® Bibliothek
rangeBreakoutLibrary "rangeBreakout"
markRange(trackTimePeriod, drawTimePeriod, highLineColor, lowLineColor, middleLineColor, maxLookbackDays)
Parameters:
trackTimePeriod (simple string) : - Time range for which the high and low values are tracked. This is the range; any breakout above/below this period can indicate a potential long/short entry condition.
drawTimePeriod (simple string) : - Time range for which the range is valid, this is typically from the end of the `trackTimePeriod` to the end of the day (or session) for security.
highLineColor (color)
lowLineColor (color)
middleLineColor (color)
maxLookbackDays (simple int) : - Number of historic days to retain the range value.
Returns: - Values to print the range values, and a boolean indicator that indicates if the current time is within the tracking time period.
The library can then be forward integrated into other indicators, strategies, and other libraries of TradingView, thus one function can be used globally.
Pine Script® Bibliothek
OriginLifecycleLibrary "OriginLifecycle"
Strict Highlander v7 origin lifecycle for engulfing indicators.
Exports enums, an OriginCandidate UDT, and four helper functions
used by engulfing_opportunities_v20.6+ to detect, track, promote,
invalidate, and consume origin levels discovered on lower
timeframes inside an engulfment zone.
Published-as-library rationale: the engulfing indicator is already at Pine v6's
top-level-declaration limit (CE10295). Moving these types and functions into a
library frees ~7 declarations in the main script without changing semantics.
Reference: highlander_v7.pine:212-293 for the state-transition rules this
implementation mirrors.
tickStateMachine(c, bO, bH, bL, bC, bTime)
Pure state-transition function. One closed LTF bar in,
updated candidate out. Mirrors highlander_v7.pine:212-293.
Parameters:
c (OriginCandidate) : The current candidate state.
bO (float) : Bar open.
bH (float) : Bar high.
bL (float) : Bar low.
bC (float) : Bar close.
bTime (int) : Bar start time in ms.
Returns: Updated OriginCandidate with `lastProcessedTime := bTime`.
Caller is responsible for:
- Only passing CLOSED LTF bars.
- Skipping bars whose time <= c.lastProcessedTime.
- On BROKEN_BSUT, looking for a retest in subsequent bars to delete.
scanForBreakCandidates(isBullish, zoneLow, zoneHigh, prevO, prevH, prevL, prevC, prevT, currO, currH, currL, currC, currT, ltfValid, ltfMin, tfLabel, outCandidates)
Find new BREAK pairs in the engulfment zone and push
them to `outCandidates` if not already tracked. De-dup
key is (price, createdTime, tfLabel).
Parameters:
isBullish (bool) : true -> look for SUPPORT (green-green) pairs;
false -> look for RESISTANCE (red-red) pairs.
zoneLow (float) : Lower bound of the engulfment zone (inclusive).
zoneHigh (float) : Upper bound of the engulfment zone (inclusive).
prevO (array)
prevH (array)
prevL (array)
prevC (array)
prevT (array)
currO (array)
currH (array)
currL (array)
currC (array)
currT (array)
ltfValid (bool) : Pre-computed validity flag for this LTF.
ltfMin (int) : LTF length in minutes (baked into each new candidate).
tfLabel (string) : Display string, e.g. "1H".
outCandidates (array) : The per-pattern candidate array to push into.
Returns: Nothing (mutates outCandidates).
processNewLTFBars(candidates, ltfMin, prevO, prevH, prevL, prevC, prevT, currO, currH, currL, currC, currT, ltfValid)
Drive the state machine across unprocessed LTF bars for every
candidate whose `ltfMinutes == ltfMin`. Removes candidates
that reach BROKEN_BSUT AND see a retest within the buffer.
Parameters:
candidates (array) : The per-pattern candidate array to update.
ltfMin (int) : The LTF length this buffer represents; candidates with a
different ltfMinutes are skipped.
prevO (array)
prevH (array)
prevL (array)
prevC (array)
prevT (array)
currO (array)
currH (array)
currL (array)
currC (array)
currT (array)
ltfValid (bool) : Validity flag.
Returns: Nothing (mutates candidates).
applyConsumedOnTouch(candidates, greedyEntries, greedyConsumedFlags, isBullish, curLow, curHigh)
Per-tick sweep. Marks CONFIRMED origins and
untouched greedy entries as consumed once price
wicks into them. Caller passes `curLow`/`curHigh`
because library functions cannot reference the
`low`/`high` chart globals directly.
Parameters:
candidates (array) : Per-pattern origin-candidate array.
greedyEntries (array) : Per-pattern greedy-entry price array.
greedyConsumedFlags (array) : Parallel bool array — resized lazily to match
greedyEntries size.
isBullish (bool) : Drives the touch check for greedy entries
(origins use their own per-candidate dir).
curLow (float) : Current bar low (pass `low` from caller).
curHigh (float) : Current bar high (pass `high` from caller).
Returns: Nothing (mutates both arrays).
OriginCandidate
A single tracked origin candidate.
Fields:
tfLabel (series string) : Display string ("1H", "5m" etc.).
ltfMinutes (series int) : Lower-timeframe length in minutes; used for the
price (series float) : The origin level price.
dir (series OriginDir) : UP (support) or DOWN (resistance).
state (series OriginState) : Current lifecycle state.
firstTouchTime (series int) : ms timestamp of first touch (0 if `touchSeen == false`).
touchSeen (series bool) : True once this candidate has been touched at least once.
createdTime (series int) : ms timestamp of the d1 bar that formed the BREAK pair.
lastProcessedTime (series int) : ms timestamp of the last LTF bar fed through the
consecutiveDirCount (series int) : Counter for 2-bar CONFIRMED confirmation, 0-2.
Pine Script® Bibliothek
KernelLens🟦 KernelLens is a professional kernel regression library for Pine Script v6, providing eight mathematically rigorous Nadaraya–Watson estimators, a three-mode filter layer, a unified string dispatcher, and a suite of trading utilities — all built from the ground up on correct non-parametric statistics. Unlike existing Pine smoothing libraries — which inherit a decade-old loop-bound bug that silently reduces every kernel window to a handful of bars, regardless of the bandwidth parameter — KernelLens is built with auditable math, NA-safe iteration, input validation at every entry point, and academic references cited inline next to the formulas they describe.
The library integrates eight independent kernel families — Rational Quadratic, Gaussian, Periodic, Locally Periodic, Epanechnikov, Tricube, Triangular, and Cosine — behind a consistent API, with every raw estimator wrapped in a filter layer (None / Smooth / Zero Lag), a unified dispatcher for dropdown-driven kernel selection, and five utility exports covering slope detection, trend state, crossover signaling, residual confidence bands, and Silverman's rule-of-thumb bandwidth recommendation. Every public function validates its inputs, raises descriptive runtime errors on misuse, and returns `na` only when there is genuinely no data — never as a silent fallback.
🟦 MATHEMATICAL FOUNDATION
**The Nadaraya–Watson Estimator**
Given a source series `y_t` and a symmetric kernel `K` with scale parameter `ℓ` (the "bandwidth"), the Nadaraya–Watson estimator of the regression function `m(x) = E ` evaluated at the current bar is:
```
Σᵢ K(dᵢ / ℓ) · y_{t−i}
ŷ(t) = ───────────────────────
Σᵢ K(dᵢ / ℓ)
```
where `dᵢ` is the bar-distance from the kernel center and the sum runs over a finite window determined by the effective support of `K`.
The estimator is a locally weighted average: bars close to the kernel center contribute heavily, distant bars contribute proportionally less, and bars outside the support contribute nothing. It is asymptotically unbiased up to `O(ℓ²)` for twice-differentiable `m`, with variance of order `(n·ℓ)⁻¹` — the classical bias–variance trade-off that defines all non-parametric smoothers.
**Why Kernel Regression Beats Rolling Means**
A simple moving average gives every bar in the window the same weight. Kernel regression gives each bar a weight that decays smoothly with distance, producing:
- **Smoother output** — no step artifacts when bars enter / leave the window
- **Better bias control** — the peak of the kernel sits exactly on the point being estimated
- **Kernel-specific behavior** — compact-support kernels eliminate tail contamination entirely; Rational Quadratic's `α` parameter exposes multi-scale mixing; Periodic kernels resonate with known cycle lengths
The math has been the academic standard for non-parametric regression since Nadaraya (1964) and Watson (1964). KernelLens brings it to Pine Script v6 in its correct, bug-free form.
🟦 THE EIGHT KERNELS
All eight kernels implement the Nadaraya–Watson weighting scheme. They differ in support (compact versus infinite), smoothness (how many times differentiable), and how weight decays with distance.
| # | Kernel | Formula | Support | Smoothness | Character |
|---|---|---|---|---|---|
| 1 | **Rational Quadratic** | `(1 + d² / (2·α·ℓ²))^(−α)` | ℝ | C∞ | Multi-scale mixer — `α` controls stretch versus wiggle |
| 2 | **Gaussian (RBF)** | `exp(−d² / (2·ℓ²))` | ℝ | C∞ | The canonical smoother — smoothest possible with L² optimality |
| 3 | **Periodic** | `exp(−2·sin²(π·d/p) / ℓ²)` | ℝ | C∞ | Resonates with repetition distance `p` — ideal for cycles |
| 4 | **Locally Periodic** | Periodic · Gaussian | ℝ | C∞ | Seasonal patterns that slowly drift with trend |
| 5 | **Epanechnikov** | `(3/4)(1 − u²) · 𝟙{|u|≤1}` | | C⁰ | Asymptotically MSE-optimal (Watson 1964) — no tail contamination |
| 6 | **Tricube** | `(70/81)(1 − \|u\|³)³ · 𝟙{|u|≤1}` | | C² | The LOWESS standard — near-Gaussian with compact support |
| 7 | **Triangular** | `(1 − \|u\|) · 𝟙{|u|≤1}` | | C⁰ | Simplest non-uniform kernel — fastest to compute |
| 8 | **Cosine** | `(π/4)·cos(π·u/2) · 𝟙{|u|≤1}` | | C¹ | Raised-cosine taper — smoother boundary than Epanechnikov |
where `u = d/ℓ` and `𝟙` is the indicator function.
**Infinite-Support vs Compact-Support — Why Both Matter**
| | Infinite Support (RQ, Gauss, Periodic, LocPeriodic) | Compact Support (Epa, Tricube, Triangular, Cosine) |
|---|---|---|
| **Tail weight** | Never exactly zero | Exactly zero beyond ±ℓ |
| **Loop depth** | `3·ℓ` (3-σ cutoff, ≈99.7% mass) | Exactly `ℓ` |
| **Bar contamination** | Distant bars still pull the estimate a tiny amount | Distant bars cannot affect the estimate at all |
| **Best for** | Smooth trends, Gaussian-process intuition | Robust regression, outlier resistance |
KernelLens picks the correct loop depth automatically based on kernel family: `_depthInfinite` for Gaussian-family kernels, `_depthCompact` for bounded kernels, `_depthPeriodic` for Periodic (which must span enough cycles to reach stable weights).
**Why Eight, Not Four**
Most Pine kernel libraries ship only the four kernels from MacKay's Gaussian process tutorial. KernelLens adds the four compact-support classical kernels because:
- **Epanechnikov** minimises asymptotic mean squared error among all non-negative kernels of bounded support (Watson 1964) — it is the MSE-optimal baseline against which all other kernels are measured
- **Tricube** is the kernel used by LOWESS (Cleveland 1979), the de-facto standard for robust locally weighted scatterplot smoothing
- **Triangular** is the cheapest non-uniform compact kernel — useful when loop-budget matters on intraday charts with huge dataset size
- **Cosine** is C¹-continuous at the support boundary, unlike Epanechnikov's C⁰ discontinuity, producing visibly smoother transitions at kernel edges
Adding them makes the library an academically complete toolkit, not just a Pine port of one tutorial.
🟦 FILTER LAYER — NONE / SMOOTH / ZERO LAG
Every kernel export accepts a `_filter` parameter with three valid values. The filter layer is implemented identically across all eight kernels, so switching kernel families does not change filter behavior.
**"No Filter" — Single-Pass Raw Estimate**
```
ŷ = K(y)
```
One Nadaraya–Watson pass over the source. Cheapest mode, most reactive, fully represents the underlying kernel. Use this when you want the kernel's raw behavior with no additional smoothing or lag correction.
**"Smooth" — Double-Pass Estimate**
```
ŷ = K(K(y))
```
The kernel is applied once to the source, then applied again to its own output using the same bandwidth and the same parameters. The result is a more strongly smoothed curve at the cost of one extra loop pass per bar.
This is mathematically equivalent to convolving the kernel with itself — the effective kernel is wider and flatter, pulling longer-range context into each estimate without requiring the user to double the bandwidth.
**"Zero Lag" — Ehlers De-Lagged Estimate**
```
ŷ = 2·K(y) − K(K(y))
```
The ZLEMA identity from Ehlers (*Rocket Science for Traders*, 2000): subtract the smoothing lag from the raw estimate, effectively shifting the output back in time to match the source more closely.
The intuition: `K(y)` lags `y` by some amount; `K(K(y))` lags `K(y)` by the same amount; so `K(y) − K(K(y))` is an estimate of the lag itself, and adding it back to `K(y)` cancels out. The result tracks the source more tightly than either pass alone, at the cost of slightly noisier turning points.
**Lazy Evaluation — No Wasted Cycles**
In `"No Filter"` mode, the second pass is skipped entirely — it never runs. The filter branch uses an `if` block (not a ternary), so Pine's short-circuit semantics prevent the unused computation. A single kernel call costs one pass; `"Smooth"` or `"Zero Lag"` costs two. You only pay for what you use.
🟦 KERNEL CENTER OFFSET — THE `_phase` PARAMETER
Every KernelLens kernel takes a `_phase` parameter that shifts the kernel center into the past by `_phase` bars. It is the library's non-repainting knob.
**_phase = 0 — Live Estimate**
The kernel is centered on the current bar. The most recent price has maximum weight, and the estimate is as fresh as possible. Suitable for live signal generation, but the most recent bar can re-evaluate as it develops within its interval — standard Pine real-time behavior.
**_phase > 0 — Non-Repainting Historical Estimate**
The kernel center is moved `_phase` bars into the past. The estimate becomes the smoothed value *at that historical bar*, not the current bar. Once the bar at `bar_index − _phase` is fully confirmed (`barstate.isconfirmed`), its estimate cannot change again.
This is the standard trick for publishing kernel indicators that do not repaint: you get a stable, historically accurate curve at the cost of shifting the entire output `_phase` bars to the right on the chart. A `_phase = 25` call gives a curve that lags live price by 25 bars but is guaranteed stable for every past bar.
**Why It Belongs in the Library, Not the Caller**
Pushing `_phase` into the kernel's own loop is not the same as evaluating the kernel at a shifted source (`K(src )`). Shifting the source just uses a stale input with a current-bar-centered kernel, which still produces a fresh estimate of a stale series. KernelLens's `_phase` genuinely moves the kernel center, producing a historical-bar estimate that computes over the correct surrounding window.
🟦 NON-REPAINTING BEHAVIOR
Repainting is the single most-asked question about any Pine indicator, and the single most common source of silent failure when a retail trader moves from backtest to live. A strategy that looks flawless on historical bars and then bleeds money the moment it is deployed is almost always suffering from some form of repainting. KernelLens is engineered from first principles to eliminate every class of repainting by construction — not by patching symptoms, but by removing the dependencies that cause repainting in the first place.
**The Two Forms of Repainting**
| Form | Symptom | Typical Cause |
|---|---|---|
| **Historical repainting** | A bar that was closed days or weeks ago silently changes its plotted value when the chart is refreshed or scrolled | `request.security()` with `lookahead = barmerge.lookahead_on`, un-gated higher-timeframe data, or incorrect array rotation that reads into future bars |
| **Real-time repainting** | The plotted value on the live (current developing) bar flickers tick-by-tick as new price ticks arrive, then freezes at a final value when the bar closes | The indicator reads `close ` (or any current-bar value) inside a weighted sum — the current-bar weight changes every tick |
KernelLens avoids the first kind **entirely and unconditionally**: the library contains no `request.security` calls, no higher-timeframe lookups, no `lookahead_on` usage, and no array rotation that could leak future bars into the window. Every historical bar plotted by any KernelLens kernel is computed exclusively from bars that existed at the time that bar was closed. The plotted history is immutable.
Real-time repainting is controlled explicitly by the `_phase` parameter — it is the user's choice whether to accept tick-by-tick flicker on the live bar in exchange for zero lag (`_phase = 0`) or to eliminate the flicker entirely at the cost of a small fixed lag (`_phase ≥ 1`).
**Why Kernel Regression Normally Repaints (And How KernelLens Stops It)**
A traditional Nadaraya–Watson call centered on the current bar evaluates:
```
ŷ(t) = Σᵢ K(dᵢ/ℓ) · y_{t−i} for i = 0 … depth
```
On the live bar, the term `y_{t−0} = close ` is the current real-time price — which changes on every tick. Every tick moves the weighted sum, every tick moves the estimate, and the trader watching the chart sees the kernel plot flicker as the bar develops. The historical bars (where `close ` for that past bar is now fixed) are stable, but the live plot is unstable.
KernelLens's `_phase` parameter shifts the loop so the kernel runs over `i = _phase … _phase + depth`. With `_phase = 2`:
```
ŷ(t) = Σᵢ K((i−2)/ℓ) · y_{t−i} for i = 2 … 2 + depth
```
The sum no longer touches `close ` or `close ` — every bar it reads is already confirmed and cannot change. The live-bar kernel output is therefore identical from the first tick of the bar to the last tick of the bar, and identical again when the bar finally closes. There is no flicker and nothing to repaint.
**The Lag / Stability Trade-Off**
| `_phase` | Lag on Live Bar | Live-Bar Flicker | Historical Repainting | Best For |
|---|---|---|---|---|
| **0** | 0 bars | Yes (real-time only; history is stable) | None | Scalping, academic research, calibration |
| **1** | 1 bar | None | None | Fast day-trading; minimum acceptable lag for a live trading desk |
| **2** | 2 bars | None | None | Default for most users — the sweet spot between freshness and stability |
| **3** | 3 bars | None | None | Swing trading — extra margin against false flickers from erratic ticks |
| **5+** | 5+ bars | None | None | Position trading, long-term chart analysis, published signal marks |
Even at `_phase = 0`, **historical repainting never occurs** — only the live bar flickers during its own development. Once a bar closes, its plotted value is final; scrolling away and back, refreshing the chart, or re-opening TradingView will never change that historical plot. The flicker is exclusively a live-bar tick-by-tick phenomenon.
**KernelLens as a Non-Repainting Primitive**
KernelLens exposes real-time flicker as an explicit, user-controlled trade-off rather than a hidden behavior. The caller picks any point on the spectrum from "fully live" (`_phase = 0`, maximum reactivity with tick-by-tick flicker) to "fully confirmed" (`_phase ≥ 1`, one or more bars of lag in exchange for a curve that never redraws) with a single integer parameter. Historical repainting — the dangerous form that silently rewrites past plots — is eliminated unconditionally regardless of `_phase`.
**How to Verify Non-Repainting Yourself**
Do not trust the word "non-repainting" from any library — always verify. KernelLens can be verified in about thirty seconds:
1. Load a chart with KernelLens on it using `_phase = 2` (or any value > 0).
2. Take a screenshot at any specific historical bar.
3. Scroll far to the left, refresh the chart, or reload the indicator.
4. Return to the same bar. The plotted value at that bar must be pixel-identical to the screenshot — because the computation on that bar used only the bars before it, which have not changed.
5. Repeat with `_phase = 0`. The historical bars must still be pixel-identical — only the live bar's plot can differ between observations, and only because the live bar's `close` is now a different number than it was when you took the screenshot.
For a stricter test, use TradingView's **Bar Replay** mode. Enable Bar Replay, step forward one bar at a time, and watch the kernel plot on each newly-closed bar. With `_phase ≥ 1`, the value plotted on each newly-closed bar will exactly match what the indicator shows after you exit replay mode and view the same bar normally. This is the gold-standard test — Bar Replay reproduces live-bar tick arrival in a controlled way.
**Common Misconceptions**
> *"Any Pine indicator that uses `close` repaints."*
False. Using `close` on a confirmed bar does not repaint — the confirmed bar's close is locked. What can repaint is using `close` on the live bar, and only within that live bar's interval. KernelLens with `_phase > 0` never reads the live-bar close at all.
> *"`lookahead = barmerge.lookahead_on` is always wrong."*
Context-dependent. `lookahead_on` is used correctly in some multi-timeframe indicators to request a higher-TF value that is already settled on the lower TF. KernelLens does not use `request.security` at all, so this question does not apply — but for libraries that do, `lookahead_on` is only problematic when it leaks values from bars that were not yet closed at the lower-TF time of evaluation.
> *"Non-repainting means zero lag."*
False. Zero lag and non-repainting are orthogonal properties. KernelLens `_phase = 0` is zero lag with real-time flicker; `_phase = 2` is two-bar lag with no flicker. You can have any combination of the two, and the right choice depends on the trading style.
> *"The `FILTER_ZEROLAG` mode makes the indicator non-repainting."*
False. `FILTER_ZEROLAG` is an Ehlers-style de-lagging filter applied to the kernel output; it reduces the perceived lag of the estimate, but it does not affect whether the live bar flickers. Non-repainting is controlled exclusively by `_phase`. Choose `_phase` for repainting behavior, and `_filter` for smoothness / lag shape — they are independent knobs.
**When to Accept Real-Time Flicker (`_phase = 0`)**
Despite everything above, there are legitimate reasons to deliberately use `_phase = 0`:
- **Academic research and backtesting** — you want the kernel mathematics in its classical form, centered on the point being estimated, with no phase adjustment
- **Scalping on very short timeframes** — a 2-bar lag on a 1-minute chart is a 2-minute delay, which can matter when you are exiting within a 4-minute window
- **Visual calibration** — when you are choosing a bandwidth by eye, the live-bar flicker actually helps: you see how sensitive the curve is to each incoming tick, which is diagnostic information
- **Indicators that read the kernel output only on `barstate.isconfirmed`** — if your signal logic is gated by `if barstate.isconfirmed`, then live-bar flicker is invisible to your signal (it sees only the frozen close-of-bar value), and you can safely use `_phase = 0` with no practical consequence
For every other case — and especially for any live alert or automated trading system — use `_phase ≥ 1`. Two bars of lag on a clean, stable curve is almost always worth more than zero lag on a curve that redraws itself several times per bar.
🟦 UNIFIED DISPATCHER — `estimate()`
For indicators where the user picks a kernel from a dropdown, writing eight separate ternary branches is tedious and error-prone. KernelLens ships with a unified dispatcher that routes to the correct kernel based on a string argument:
```pine
import a_jabbaroff/KernelLens/1 as kl
line = kl.estimate(
kernelType = kl.KERNEL_GAUSS,
src = close,
bandwidth = 32,
shapeAlpha = 1.0,
period = 1,
phase = 2,
filter = kl.FILTER_SMOOTH)
```
The dispatcher forwards to the matching typed export, so there is no performance penalty versus calling the kernel directly — it is a compile-time routing pass. Unknown kernel names raise a descriptive `runtime.error` naming every valid alternative, so typos fail loudly instead of silently returning `na`.
**Public Constants**
KernelLens exposes its string constants so callers never type the magic values by hand:
| Constant | Value |
|---|---|
| `FILTER_NONE` | `"No Filter"` |
| `FILTER_SMOOTH` | `"Smooth"` |
| `FILTER_ZEROLAG` | `"Zero Lag"` |
| `KERNEL_RQ` | `"Rational Quadratic"` |
| `KERNEL_GAUSS` | `"Gaussian"` |
| `KERNEL_PERIODIC` | `"Periodic"` |
| `KERNEL_LOCPER` | `"Locally Periodic"` |
| `KERNEL_EPA` | `"Epanechnikov"` |
| `KERNEL_TRICUBE` | `"Tricube"` |
| `KERNEL_TRIANG` | `"Triangular"` |
| `KERNEL_COSINE` | `"Cosine"` |
Using the constants in your caller code means the Pine compiler — not a runtime string compare — catches typos at edit time.
🟦 UTILITY LAYER — FIVE PROFESSIONAL HELPERS
KernelLens ships with five utility exports that complement the core estimators. They are the functions you almost always write immediately after getting a smoothed line, factored out so you don't rewrite them in every indicator.
**`slope(estimate, step)` — Discrete First Derivative**
Returns `(y_t − y_{t−step}) / step`, the normalized rate of change over `step` bars. Use it to detect whether a kernel output is trending up, flat, or down — the foundation for any trend-following signal built on top of KernelLens.
```pine
rising = kl.slope(line, 3) > 0.0
```
**`trendState(estimate, step)` — Ternary Trend Indicator**
Returns `+1` if the estimate is rising, `−1` if falling, `0` if exactly flat over the window. A single-call replacement for hand-rolled `line > line ? 1 : line < line ? -1 : 0` ladders.
**`crossSignal(fast, slow)` — Bi-directional Crossover**
Returns `+1` on the bar where `fast` crosses above `slow` (bullish), `−1` on a bearish cross, and `0` otherwise. Built on `ta.crossover` / `ta.crossunder`, so the signal is non-repainting once the bar is confirmed.
**`confidenceBand(src, estimate, window)` — Residual Standard Deviation**
Computes the rolling standard deviation of `(src − estimate)` over a user-defined window. Use the return value as the half-width of a confidence band around the estimate:
```pine
est = kl.gaussian(close, 32, 2, kl.FILTER_SMOOTH)
sigma = kl.confidenceBand(close, est, 50)
upper = est + 1.96 * sigma
lower = est - 1.96 * sigma
```
This is a computationally cheap proxy for the full kernel-weighted local variance — ideal when you need visual bands without paying for a second weighted pass.
**`silvermanBandwidth(src, window)` — Optimal ℓ Suggestion**
Returns the Silverman rule-of-thumb bandwidth:
```
h ≈ 1.06 · σ · n^(−1/5)
```
where `σ` is the rolling standard deviation of the source and `n` is the window size. This is the classical starting point for Gaussian-family bandwidths in academic texts (Silverman 1986). Because Pine requires `simple int` for kernel bandwidth, the returned value is intended for diagnostic display — plot it, read it off the chart, then hard-code the rounded integer into the kernel call.
🟦 INPUT VALIDATION — FAIL LOUDLY, FAIL EARLY
Every public function in KernelLens validates its inputs through a set of internal `_assert*` helpers. Invalid arguments never produce silent `na` fallbacks or buried zero-divisions — they raise `runtime.error` with a descriptive message identifying the function, the parameter, and the expected range.
| Helper | Checks | Raises On |
|---|---|---|
| `_assertFilter` | Filter string is `FILTER_NONE`, `FILTER_SMOOTH`, or `FILTER_ZEROLAG` | Typos like `"No FIlter"` (capital I) — a bug that exists in at least one published kernel indicator |
| `_assertBandwidth` | Bandwidth is a strictly positive integer | Negative or zero bandwidth, which would cause division by zero or infinite loops |
| `_assertPeriod` | Period is a strictly positive integer | Zero period, which would cause `sin(π·d/0)` in Periodic kernels |
| `_assertAlpha` | Rational Quadratic shape parameter is strictly positive | Zero or negative `α`, which would invert the RQ formula |
Error messages are prefixed `KernelLens:` (or `KernelLens.:`) so they are easy to spot in the TradingView runtime log. Every message names the parameter that failed, the value that was passed, and the set of valid alternatives — so a misconfigured chart tells you exactly what to fix.
🟦 LOOP DEPTH — THE BUG FIX THAT MOTIVATED KERNELLENS
The two most popular Pine kernel libraries on TradingView share the same fatal bug: both compute their loop depth as
```pine
_size = array.size(array.from(_src))
```
where `array.from(_src)` creates a **one-element array containing the current value of `_src`**, so `_size` is always `1`. The loop then runs `for i = 0 to 1 + startAtBar`, effectively using only `startAtBar + 2` bars — completely ignoring the user's bandwidth. Every published kernel indicator built on those libraries inherits this silent miscalculation.
KernelLens replaces the broken helper with three explicit depth selectors:
| Helper | Depth | Used By |
|---|---|---|
| `_depthInfinite(bw)` | `max(bw · 3, 4)` | Gaussian, Rational Quadratic, Locally Periodic |
| `_depthCompact(bw)` | `max(bw, 4)` | Epanechnikov, Tricube, Triangular, Cosine |
| `_depthPeriodic(bw, p)` | `max(bw · 3, p · 10, 4)` | Periodic |
For Gaussian-family kernels, the `3·ℓ` cutoff captures approximately 99.7% of the kernel mass (the three-sigma rule). For compact-support kernels, the depth equals the bandwidth exactly — the loop terminates at the kernel's natural zero point. For Periodic kernels, the depth is the larger of the scale-based and cycle-based minima, so the loop always spans enough periods to produce a stable weighted average.
The loop counter `i` runs over bar offsets starting at `_phase`, every bar lookup is NA-checked before being incorporated into the sum, and the final `num / den` division is guarded against zero denominators. On a fresh chart, the kernel gracefully returns `na` for bars where the window extends past available history, rather than producing poisoned sums from implicit NA arithmetic.
🟦 API REFERENCE
**Core Kernel Estimators — Eight Exports**
| Export | Signature |
|---|---|
| `rationalQuadratic` | `(src, bandwidth, shapeAlpha, phase, filter) → float` |
| `gaussian` | `(src, bandwidth, phase, filter) → float` |
| `periodic` | `(src, bandwidth, period, phase, filter) → float` |
| `locallyPeriodic` | `(src, bandwidth, period, phase, filter) → float` |
| `epanechnikov` | `(src, bandwidth, phase, filter) → float` |
| `tricube` | `(src, bandwidth, phase, filter) → float` |
| `triangular` | `(src, bandwidth, phase, filter) → float` |
| `cosineKernel` | `(src, bandwidth, phase, filter) → float` |
**Unified Dispatcher**
| Export | Signature |
|---|---|
| `estimate` | `(kernelType, src, bandwidth, shapeAlpha, period, phase, filter) → float` |
**Utility Layer — Five Exports**
| Export | Signature |
|---|---|
| `slope` | `(estimate, step) → float` |
| `trendState` | `(estimate, step) → int` |
| `crossSignal` | `(fast, slow) → int` |
| `confidenceBand` | `(src, estimate, window) → float` |
| `silvermanBandwidth` | `(src, window) → float` |
**Parameter Types**
| Name | Pine Type | Description |
|---|---|---|
| `src` | `series float` | Source series (close, hl2, ohlc4, or any other price-derived series) |
| `bandwidth` | `simple int` | Kernel scale `ℓ`, must be `> 0` |
| `shapeAlpha` | `simple float` | Rational Quadratic shape parameter, must be `> 0` |
| `period` | `simple int` | Periodic repetition distance, must be `> 0` |
| `phase` | `simple int` | Kernel center offset in bars, must be `≥ 0` |
| `filter` | `simple string` | One of `FILTER_NONE`, `FILTER_SMOOTH`, `FILTER_ZEROLAG` |
| `kernelType` | `simple string` | One of the eight `KERNEL_*` constants |
| `step` | `simple int` | Finite-difference step for `slope` / `trendState`, must be `≥ 1` |
| `window` | `simple int` | Rolling window for `confidenceBand` / `silvermanBandwidth`, must be `≥ 2` |
🟦 USAGE EXAMPLES
**Minimal — One Gaussian Curve**
```pine
//@version=6
indicator("KernelLens — Gaussian Demo", overlay = true)
import a_jabbaroff/KernelLens/1 as kl
line = kl.gaussian(close, 32, 2, kl.FILTER_SMOOTH)
plot(line, "Gaussian", color = color.orange, linewidth = 2)
```
**Fast / Slow Crossover System**
```pine
//@version=6
indicator("KernelLens — RQ Crossover", overlay = true)
import a_jabbaroff/KernelLens/1 as kl
fast = kl.rationalQuadratic(close, 8, 1.0, 2, kl.FILTER_NONE)
slow = kl.rationalQuadratic(close, 32, 1.0, 2, kl.FILTER_SMOOTH)
cross = kl.crossSignal(fast, slow)
plot(fast, "Fast", color = color.aqua, linewidth = 2)
plot(slow, "Slow", color = color.orange, linewidth = 2)
plotshape(cross == 1, "Bull", location = location.belowbar,
color = color.lime, style = shape.triangleup, size = size.tiny)
plotshape(cross == -1, "Bear", location = location.abovebar,
color = color.red, style = shape.triangledown, size = size.tiny)
```
**Confidence Band Envelope**
```pine
//@version=6
indicator("KernelLens — Confidence Band", overlay = true)
import a_jabbaroff/KernelLens/1 as kl
est = kl.tricube(close, 48, 2, kl.FILTER_SMOOTH)
sigma = kl.confidenceBand(close, est, 50)
k = 1.96
upper = est + k * sigma
lower = est - k * sigma
plot(est, "Estimate", color = color.orange, linewidth = 2)
p1 = plot(upper, "+1.96σ", color = color.new(color.aqua, 70))
p2 = plot(lower, "−1.96σ", color = color.new(color.aqua, 70))
fill(p1, p2, color = color.new(color.aqua, 92))
```
**Dropdown-Driven Kernel Selection**
```pine
//@version=6
indicator("KernelLens — Dropdown", overlay = true)
import a_jabbaroff/KernelLens/1 as kl
kernelType = input.string(kl.KERNEL_GAUSS, "Kernel",
options = )
bandwidth = input.int(32, "Bandwidth", minval = 2)
alphaRQ = input.float(1.0,"RQ Alpha", minval = 0.01, step = 0.25)
period = input.int(20, "Period", minval = 1)
phase = input.int(2, "Phase", minval = 0)
filter = input.string(kl.FILTER_SMOOTH, "Filter",
options = )
line = kl.estimate(kernelType, close, bandwidth, alphaRQ, period, phase, filter)
plot(line, "KernelLens", color = color.orange, linewidth = 2)
```
🟦 TIMEFRAME PRESETS — BANDWIDTH BY STYLE
Kernel bandwidth is the single most important parameter. It controls the trade-off between reactivity (small `ℓ`, tight fit, noisier) and stability (large `ℓ`, smooth curve, slower to react). The presets below are tested starting points — adjust by ±25 % to taste.
---
**SCALPER — 1m / 3m / 5m**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | 8 |
| Phase | 1 |
| Filter | `FILTER_NONE` |
| Best Kernel | Rational Quadratic or Gaussian |
| RQ shapeAlpha | 1.0 |
**Why:** Short bandwidth means the kernel reacts within a handful of bars. `FILTER_NONE` removes the double-pass lag, so the estimate tracks price as tightly as possible. Phase 1 keeps the estimate nearly live while still avoiding the current-bar tick noise.
---
**DAY TRADER — 15m / 30m / 1H**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | 16 |
| Phase | 2 |
| Filter | `FILTER_SMOOTH` |
| Best Kernel | Gaussian or Tricube |
| RQ shapeAlpha | 1.0 |
**Why:** Balanced reactivity — the 16-bar Gaussian is the default Silverman range for intraday price data, and `FILTER_SMOOTH` removes most of the bar-to-bar chop without significantly increasing lag. Tricube provides near-identical behaviour with strict compact support and is preferred on noisy assets where outlier bars should not influence the curve.
---
**SWING TRADER — 4H / 1D**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | 32 |
| Phase | 3 |
| Filter | `FILTER_SMOOTH` |
| Best Kernel | Rational Quadratic |
| RQ shapeAlpha | 2.0 |
**Why:** Swing trades need structural signals, not intraday noise. Rational Quadratic with `α = 2.0` mixes medium and long length scales, producing a curve that ignores transient spikes but catches genuine regime shifts. Phase 3 shifts the estimate three bars back so each swing decision is made against a fully confirmed kernel output.
---
**POSITION / LONG-TERM — 1D / 1W / 1M**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | 64 |
| Phase | 5 |
| Filter | `FILTER_SMOOTH` or `FILTER_ZEROLAG` |
| Best Kernel | Gaussian or Locally Periodic |
| Period (if LP) | 52 (weekly cycle) |
**Why:** Position traders care about the macro trajectory. A Gaussian with ℓ = 64 produces a curve that only turns on genuine multi-month inflections. Locally Periodic with `period = 52` is the ideal choice when a clear seasonal cycle is present — it uses both the long-range Gaussian envelope and the 52-bar periodicity to highlight cycle turns that align with trend.
---
**RESEARCH — Academic / Backtest**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | Compute via `silvermanBandwidth(src, 200)` |
| Phase | 0 |
| Filter | `FILTER_NONE` |
| Best Kernel | Epanechnikov |
**Why:** Epanechnikov is the MSE-optimal kernel; `FILTER_NONE` keeps the estimator in its classical single-pass form; `phase = 0` centers the kernel on the bar being evaluated. This is the configuration that matches the statistical literature exactly — use it when publishing research, running Monte-Carlo studies, or calibrating against reference implementations.
🟦 BANDWIDTH SELECTION
Bandwidth `ℓ` is the single most consequential choice in kernel regression. Too small and the estimate overfits local noise; too large and it flattens real structure. KernelLens exposes two helpers to support both manual and semi-automated bandwidth selection.
**Manual — Start with ℓ ≈ √n**
A practical starting point for financial time series: set `ℓ ≈ √window_of_interest`. If you care about 100-bar structure, try `ℓ = 10`. If you care about 400-bar structure, try `ℓ = 20`. Adjust by ±25 % based on how noisy the result looks.
**Silverman's Rule of Thumb**
The closed-form optimal bandwidth for Gaussian-family kernels under Gaussian source assumptions:
```
h ≈ 1.06 · σ · n^(−1/5)
```
Call `silvermanBandwidth(src, window)` to compute this value live. Because Pine requires `simple int` bandwidth at compile time, the returned value is for diagnostic use — plot it, read the stable value off the chart, then hard-code the rounded integer into your kernel calls.
**Leave-One-Out Cross-Validation (Manual)**
For academic rigor, compute the leave-one-out mean squared error for a range of bandwidths and pick the minimum. KernelLens does not automate this (it would require `series int` bandwidth, which Pine does not support inside kernel loops), but the formula is straightforward:
```
LOOCV(ℓ) = (1/n) · Σᵢ (yᵢ − ŷᵢ⁻ⁱ(ℓ))²
```
where `ŷᵢ⁻ⁱ` is the kernel estimate at bar `i` computed without including bar `i` in the sum. Evaluate offline, pick the minimum, hard-code the result.
🟦 FILTER SELECTION — WHEN TO USE EACH
| Filter | Best For | Avoid When |
|---|---|---|
| `FILTER_NONE` | Live signal generation, research / calibration, compact-support kernels on noisy data | Choppy markets where you need extra smoothing |
| `FILTER_SMOOTH` | Swing and position trades, confidence band midlines, most day-trading setups | Scalping — the double pass adds measurable lag |
| `FILTER_ZEROLAG` | Regime detection, crossover systems that need the curve to track price tightly | Low-volume assets — Zero Lag amplifies high-frequency noise |
The three filters use the same underlying kernel with the same bandwidth, so switching between them does not require re-tuning. Default to `FILTER_SMOOTH` when in doubt — it is the best-behaved option across the widest range of assets and timeframes.
🟦 COMPATIBILITY
KernelLens targets Pine Script v6 and runs on every TradingView chart — no exchange, asset class, or timeframe restriction.
- **Crypto** — Spot, futures, perpetual contracts
- **Forex** — All majors, minors, and exotics
- **Equities** — Stocks, ETFs, indices
- **Commodities** — Metals, energy, agriculture
- **Timeframes** — 1 minute through Monthly
The library is deterministic — given the same source and parameters, every bar of every symbol produces the same estimate. No calibration is needed across assets; the bandwidth parameter alone controls smoothness, and the kernel formulas are scale-free in the source dimension. Silverman's bandwidth helper automatically adapts to each asset's volatility.
🟦 TECHNICAL NOTES
- **Pine Script v6** — uses the modern type system, strict type checking, and the `switch` expression in the unified dispatcher
- **Non-repainting** — kernel outputs for any confirmed bar depend only on that bar's history; there is no look-ahead, no `request.security` with lookahead, and no dependency on the unconfirmed current bar unless `_phase = 0` is deliberately chosen
- **NA-safe iteration** — every bar lookup inside a kernel loop is guarded by `if not na(y)`, so chart history gaps and warm-up bars cannot poison the weighted sum
- **Division-by-zero protection** — every kernel's final division checks `den > 0.0` and returns `na` if the denominator collapses (which can only happen on truly empty windows)
- **Input validation** — every public function asserts its preconditions up front via `_assertFilter`, `_assertBandwidth`, `_assertPeriod`, `_assertAlpha`, and raises `runtime.error` with a descriptive message on misuse — no silent `na` fallbacks
- **Lazy filter evaluation** — the `"No Filter"` path never executes the second kernel pass; the `if`-branch check short-circuits, so single-pass mode is as cheap as a raw kernel call
- **Correct loop bounds** — `_depthInfinite`, `_depthCompact`, and `_depthPeriodic` compute the correct window size per kernel family, fixing the silent `_size = 1` bug that plagues every other published Pine kernel library
- **No persistent state** — the library is purely functional: no `var`, no arrays, no history buffers that grow over time; every export is a pure expression of `(inputs) → output`, so Pine's `max_*_count` limits cannot be exceeded and the library cannot leak memory
- **O(bandwidth) per bar per kernel call** — the loop depth is bounded by the constants in Section 0; there is no hidden quadratic behavior and the cost scales linearly with the user-chosen bandwidth
- **Unicode-safe comments** — the source uses academic notation (`σ`, `ℓ`, `α`, `ŷ`, `ℝ`) where it improves readability; all strings are plain ASCII for runtime compatibility
🟦 ACADEMIC REFERENCES
Every kernel and every formula in KernelLens is cited inline in the source. The combined bibliography:
- **Nadaraya, E. A. (1964).** On estimating regression. *Theory of Probability & Its Applications*, 9(1), 141–142.
- **Watson, G. S. (1964).** Smooth regression analysis. *Sankhyā: The Indian Journal of Statistics, Series A*, 26(4), 359–372.
- **Cleveland, W. S. (1979).** Robust locally weighted regression and smoothing scatterplots. *Journal of the American Statistical Association*, 74(368), 829–836. *(Tricube kernel, LOWESS.)*
- **Silverman, B. W. (1986).** *Density Estimation for Statistics and Data Analysis*. Chapman & Hall, London. *(Bandwidth rule of thumb.)*
- **Wand, M. P. & Jones, M. C. (1995).** *Kernel Smoothing*. Chapman & Hall. *(Unified treatment of all eight kernels.)*
- **MacKay, D. J. C. (1998).** Introduction to Gaussian Processes. *NIPS Tutorial*. *(Periodic and Rational Quadratic kernels.)*
- **Ehlers, J. F. (2000).** *Rocket Science for Traders*. John Wiley & Sons. *(Zero-lag smoothing trick.)*
- **Rasmussen, C. E. & Williams, C. K. I. (2006).** *Gaussian Processes for Machine Learning*. MIT Press. *(Locally Periodic and Rational Quadratic kernels.)*
🟦 VERSIONING & LICENSE
- **Version** — 1.0.0
- **Pine Script** — v6
- **License** — Mozilla Public License 2.0
- **Status** — Production-ready
KernelLens follows semantic versioning. Minor versions add new exports without breaking existing ones; patch versions fix bugs; major versions may change function signatures and will be announced in the changelog.
🟦 DISCLAIMER
KernelLens is a mathematical library for non-parametric regression on financial time series using the Nadaraya–Watson method. The library is provided solely for educational and research purposes and does not constitute financial, investment, or trading advice.
Kernel regression is a local smoothing technique. It estimates the mean of a source series in the neighborhood of the current bar based on historical data, but it does not predict future prices, does not generate trading signals on its own, and does not guarantee the profitability of any strategy built on top of its output.
Past performance of any model does not guarantee future results. Markets contain systemic risks that cannot be eliminated by any amount of mathematical rigor in the kernel itself. Responsibility for any trading decisions made using this library rests entirely with the user. Always apply sound capital management, conduct your own independent analysis, and never risk capital you are not prepared to lose.
The author assumes no liability for direct or indirect losses incurred through the use of KernelLens or any indicator built on top of it.
Pine Script® Bibliothek
IndiaVixLibrary "IndiaVix"
getPrevDayClose(_symbol, _tf)
Parameters:
_symbol (simple string)
_tf (simple string)
getSentientValues(_enable, _vix, _indexInput, _symbol, _sigma, _tredingDays)
Parameters:
_enable (bool)
_vix (float)
_indexInput (float)
_symbol (simple string)
_sigma (simple float)
_tredingDays (simple int)
getVix(_tf)
Parameters:
_tf (simple string)
method chgVsPrev(this)
Namespace types: Vix
Parameters:
this (Vix)
method chgVsPDC(this)
Namespace types: Vix
Parameters:
this (Vix)
method dailyMovePts(this, _c)
Namespace types: Vix
Parameters:
this (Vix)
_c (float)
method isRising(this)
Namespace types: Vix
Parameters:
this (Vix)
method regime(this)
Namespace types: Vix
Parameters:
this (Vix)
Vix
Fields:
now (series float)
prev (series float)
eod (series float)
Pine Script® Bibliothek
BasketLibLibrary "BasketLib"
f_calc_correlation_score(base_return, candidate_return, corr_len, smooth_len, is_self)
Parameters:
base_return (float) : Base asset 1-bar return
candidate_return (float) : Candidate asset 1-bar return
corr_len (int) : Correlation calculation length
smooth_len (simple int) : EMA smoothing length
is_self (bool) : Whether candidate is the base asset itself
Returns: Correlation score (0.7 * raw + 0.3 * ema), or na if invalid
f_rank_and_select(scores, n)
Parameters:
scores (array) : Array of correlation scores
n (int) : Number of assets to select (typically 4)
Returns: Array of selected indices
f_is_self_reference(candidate_symbol, base_ticker)
Parameters:
candidate_symbol (string) : Full symbol string (e.g., "BINANCE:BTCUSDT")
base_ticker (string) : Base asset ticker (e.g., "BTC")
Returns: True if candidate is the base asset
f_route_scan_idx(idx, prices)
Parameters:
idx (int) : Index (0-9)
prices (array) : Array of 10 scan candidate prices
Returns: Price at index, or na if invalid
f_get_preset_basket(preset_name)
Parameters:
preset_name (string) : Name of preset ("Basket B (Memes)", etc.)
Returns:
f_get_default_scan_symbols()
f_calc_basket_fit(score1, score2, score3, score4)
Parameters:
score1 (float) : Correlation score of asset 1
score2 (float) : Correlation score of asset 2
score3 (float) : Correlation score of asset 3
score4 (float) : Correlation score of asset 4
Returns: Basket fit percentage (0-100)
f_get_fit_label(fit_pct)
Parameters:
fit_pct (float) : Basket fit percentage (0-100)
Returns: Quality label ("Excellent", "Good", "Fair", "Poor")
f_get_fit_color(fit_pct)
Parameters:
fit_pct (float) : Basket fit percentage (0-100)
Returns: Color (lime, aqua, orange, red)
ScanCandidate
Fields:
symbol (series string)
price (series float)
return_1bar (series float)
correlation_raw (series float)
correlation_ema (series float)
score (series float)
is_self (series bool)
BasketSelection
Fields:
sym1 (series string)
sym2 (series string)
sym3 (series string)
sym4 (series string)
score1 (series float)
score2 (series float)
score3 (series float)
score4 (series float)
idx1 (series int)
idx2 (series int)
idx3 (series int)
idx4 (series int)
Pine Script® Bibliothek
FootprintCore
ExperimentaL WIP
The FootprintCore library is a Pine Script v6 toolset designed for deep analysis of order flow and footprint data. It provides structured data types and functions to extract, normalize, and interpret footprint features to identify market breakouts and execution regimes.
Core Data Types
FPBar: Captures raw footprint metrics including volume (total, buy, sell), Delta, POC/Value Area levels, and imbalance stack counts.
FPNorm: Stores normalized versions of key features, primarily using Z-Scores and Percentile Ranks to compare current activity against historical lookbacks.
FPDerived: Holds high-level interpretations such as "Stack Dominance," "Bullish Acceptance," and "Auction Failures".
FPSignal & FPExec: Define trade triggers and execution states (e.g., passive, caution, or avoid) based on current volatility and liquidity.
How to Use the Library
1. Feature Extraction
Use extractBar() to convert a footprint object into a structured FPBar type. You must provide price context (close, high, low) and an ATR value for normalization.
Pine Script
fp_data = footprint.get()
bar_features = FootprintCore.extractBar(fp_data, prevPoc, close, high, low, ta.atr(14))
2. Normalization
Pass the FPBar into normalizeBar() to calculate Z-Scores and Ranks for features like Value Area width and Delta efficiency.
Pine Script
norm_features = FootprintCore.normalizeBar(bar_features, 20, 100)
3. Generating Signals
The breakoutSignal() function identifies high-probability trade setups. It checks for:
Bullish/Bearish Acceptance: Price breaking out of the Value Area with positive/negative Delta.
+1
Stack Dominance: Presence of imbalance stacks (e.g., more than 3 buy stacks).
Efficiency: Delta efficiency and range compression requirements.
+1
4. Execution Governance
Before placing a trade, use executionState() to assess the "stress" of the current market.
ExecMode.avoid: Triggered when slippage proxies or fragility scores (based on Z-Scores) are too high.
+1
noTrade: A boolean flag that becomes true if footprint data is missing or the market structure is unstable.
5. Diagnostic Reason Codes
For debugging or logging, reasonCodeBreakout() returns a machine-readable string (e.g., "ACC|STACK|EFF|") indicating which specific conditions were met for a signal.
Pine Script® Bibliothek
FpFeaturesLibrary "FpFeatures"
buyStackCount(rows)
Parameters:
rows (array)
sellStackCount(rows)
Parameters:
rows (array)
maxRowDeltas(rows)
Parameters:
rows (array)
pocMid(fp)
Parameters:
fp (footprint)
pocShift(fp, prevPocMid)
Parameters:
fp (footprint)
prevPocMid (float)
vaWidthPct(fp, close_)
Parameters:
fp (footprint)
close_ (float)
deltaEfficiency(fp)
Parameters:
fp (footprint)
topTailUnfinished(fp, minSideVol)
Parameters:
fp (footprint)
minSideVol (float)
bottomTailUnfinished(fp, minSideVol)
Parameters:
fp (footprint)
minSideVol (float)
acceptanceAboveVAH(fp, close_, high_, low_, frac)
Parameters:
fp (footprint)
close_ (float)
high_ (float)
low_ (float)
frac (float)
acceptanceBelowVAL(fp, close_, high_, low_, frac)
Parameters:
fp (footprint)
close_ (float)
high_ (float)
low_ (float)
frac (float)
compute(fp, close_, high_, low_, prevPocMid, minTailSideVol, acceptanceFrac)
Parameters:
fp (footprint)
close_ (float)
high_ (float)
low_ (float)
prevPocMid (float)
minTailSideVol (float)
acceptanceFrac (float)
FeatureSet
Fields:
buyStackCount (series int)
sellStackCount (series int)
maxPosRowDelta (series float)
maxNegRowDelta (series float)
topTailUnfinished (series bool)
bottomTailUnfinished (series bool)
pocMid (series float)
pocShift (series float)
vaWidthPct (series float)
deltaEfficiency (series float)
acceptanceAboveVAH (series bool)
acceptanceBelowVAL (series bool)
Pine Script® Bibliothek
BH_LibLibrary "BH_Lib"
fullRange()
bodyRange()
midRange()
midBody()
blTarget()
brTarget()
ibs()
barDir()
abr(lookback)
Parameters:
lookback (int)
abrEma(lookback)
Parameters:
lookback (simple int)
abrIndex(lookback)
Parameters:
lookback (int)
tailPercent()
topTailPercent()
bottomTailPercent()
isOB()
isIB()
iOscale()
overlapRange()
overlapPct()
zScore(src, lookback)
Parameters:
src (float)
lookback (int)
zScoreFullRange(lookback)
Parameters:
lookback (int)
zScoreBodyRange(lookback)
Parameters:
lookback (int)
isInSession(sessionStr, tz)
Parameters:
sessionStr (string)
tz (string)
isSessionStart(sessionStr, tz)
Parameters:
sessionStr (string)
tz (string)
isFirstRTHbar()
skipFirst2Bars()
scalp50()
scalp75()
barLevel(fraction)
Parameters:
fraction (float)
Pine Script® Bibliothek
MLLibLibrary "MLLib"
Machine Learning Library - Adaptive learning algorithms for parameter optimization
f_kirschenbaum_sgd(feature_z, baseline_ma, baseline_dev, pivot_high, pivot_low, sensitivity_current, learning_rate, sensitivity_min, sensitivity_max, coupling_strength, coupling_gate, pivot_lookback, proximity_pct, survival_prob)
Pivot-based SGD for adaptive sensitivity tuning (Kirschenbaum method)
Parameters:
feature_z (float) : Z-score of the predictive feature (e.g., basket vector)
baseline_ma (float) : Baseline moving average (center line)
baseline_dev (float) : Standard deviation for band calculation
pivot_high (float) : Recent pivot high price (na if none)
pivot_low (float) : Recent pivot low price (na if none)
sensitivity_current (float) : Current sensitivity parameter value
learning_rate (float) : Learning rate for SGD updates
sensitivity_min (float) : Minimum allowed sensitivity value
sensitivity_max (float) : Maximum allowed sensitivity value
coupling_strength (float) : Coupling strength for gating updates (0-1)
coupling_gate (float) : Minimum coupling threshold for updates
pivot_lookback (int) : Lookback period to historical feature/price at pivot
proximity_pct (float) : Proximity threshold (0-1) for pivot to be "near band"
survival_prob (float) : Survival probability for band calculation (e.g., 0.68 for 1-sigma)
Returns: Updated sensitivity and number of updates performed
f_sgd_update(param_current, gradient, learning_rate, param_min, param_max, gate_strength, gate_threshold)
Generic SGD parameter update with optional gating
Parameters:
param_current (float) : Current parameter value
gradient (float) : Gradient (error * feature)
learning_rate (float) : Learning rate
param_min (float) : Minimum parameter value
param_max (float) : Maximum parameter value
gate_strength (float) : Gating strength (0-1, optional)
gate_threshold (float) : Minimum gate strength to allow full update
Returns: float Updated parameter value
SGDState
SGD learning state for tracking parameter updates
Fields:
param (series float) : Current parameter value
updates (series int) : Number of updates performed
last_error (series float) : Last prediction error
Pine Script® Bibliothek
MCLibLibrary "MCLib"
f_eval_validator_path(sim_buffer, run, setup_horizon, setup_entry_price, setup_direction, setup_tp1, setup_sl, fv_base, fv_drift_step, max_hold_bars)
Parameters:
sim_buffer (array)
run (int)
setup_horizon (int)
setup_entry_price (float)
setup_direction (string)
setup_tp1 (float)
setup_sl (float)
fv_base (float)
fv_drift_step (float)
max_hold_bars (int)
f_calc_validator_rr(entry_price, eval_direction, mae_price, mfe_price)
Parameters:
entry_price (float)
eval_direction (string)
mae_price (float)
mfe_price (float)
f_run_lite_antithetic_mc(sim_buffer_A, sim_buffer_B, lite_runs, setup_horizon, setup_entry_price, mc_pool_idx, mc_master_pool, mc_current_state, mc_pool_size, per_bar_vol, mc_squeeze_intensity, fv_cyclic_kalman, fv_drift, c0, is_stretched, is_coupled, shadow_price)
Parameters:
sim_buffer_A (array)
sim_buffer_B (array)
lite_runs (int)
setup_horizon (int)
setup_entry_price (float)
mc_pool_idx (array)
mc_master_pool (array)
mc_current_state (int)
mc_pool_size (int)
per_bar_vol (float)
mc_squeeze_intensity (float)
fv_cyclic_kalman (float)
fv_drift (float)
c0 (float)
is_stretched (bool)
is_coupled (bool)
shadow_price (float)
f_run_realtime_mc_chunk(mc_sim_buffer_A, mc_sim_buffer_B, mc_runs_done, mc_target_runs, mc_chunk_size, mc_horizon, mc_pool_idx, mc_master_pool, mc_current_state, mc_pool_size, per_bar_vol, mc_vol_scalar_base, mc_squeeze_intensity, mc_breakout_multiplier, fv_cyclic_kalman, fv_drift, c0, is_stretched, is_coupled, shadow_price)
Parameters:
mc_sim_buffer_A (array)
mc_sim_buffer_B (array)
mc_runs_done (int)
mc_target_runs (int)
mc_chunk_size (int)
mc_horizon (int)
mc_pool_idx (array)
mc_master_pool (array)
mc_current_state (int)
mc_pool_size (int)
per_bar_vol (float)
mc_vol_scalar_base (float)
mc_squeeze_intensity (float)
mc_breakout_multiplier (float)
fv_cyclic_kalman (float)
fv_drift (float)
c0 (float)
is_stretched (bool)
is_coupled (bool)
shadow_price (float)
f_update_progressive_percentiles(mc_sim_buffer_A, mc_sim_buffer_B, mc_horizon, mc_runs_done, mc_progressive_p10, mc_progressive_p50, mc_progressive_p90)
Parameters:
mc_sim_buffer_A (array)
mc_sim_buffer_B (array)
mc_horizon (int)
mc_runs_done (int)
mc_progressive_p10 (array)
mc_progressive_p50 (array)
mc_progressive_p90 (array)
Pine Script® Bibliothek
CB_CandleLibLibrary "CB_CandleLib"
bodySize()
candleRange()
bodyRatio()
upperWick()
lowerWick()
isBullish()
isBearish()
hasStrongBody(minRatio)
Parameters:
minRatio (float)
avgBody(length)
Parameters:
length (int)
bullishEngulfing()
hammer()
invertedHammer()
bullishPinBar()
morningStar()
bullishHarami()
threeWhiteSoldiers()
bearishEngulfing()
shootingStar()
bearishPinBar()
eveningStar()
bearishHarami()
threeBlackCrows()
doji(maxBodyRatio)
Parameters:
maxBodyRatio (float)
longLeggedDoji()
dragonflyDoji()
gravestoneDoji()
insideBar()
outsideBar()
bullishPatternScore()
bearishPatternScore()
bullishPatternName()
bearishPatternName()
Pine Script® Bibliothek
Objective Market Structure FrameworkThis library provides a systematic, rule-based approach to categorize market movements into four objective phases: Compression, Expansion, Distribution, and Consolidation.
Instead of subjective chart patterns, this tool uses volatility-relative thresholds (ATR) and momentum filters to identify significant trading ranges and structural breaks.
Main Use Cases:
Clear & Compact MTF Visualization: Map higher-timeframe (HTF) market structures directly onto your lower-timeframe (LTF) charts. Provides a clean, non-cluttered overview for an intuitive display of key levels without overcomplicating the chart.
Automated Setup Classification: Assign specific trading setups to distinct market regimes (Uptrends, Corrections, Sideways Ranges). Enables rapid, objective analysis every trading day, eliminating the need for manual re-evaluation or "hunting" for the current trend state.
Core Features:
Volatility-Adaptive: Range calculations scale automatically with the market's current ATR, making the analysis relevant across all asset classes.
MTF-Optimized Performance: Engineered for professional Multi-Timeframe workflows. Fetch 19 structural variables with a single request.security() call to minimize script load and prevent memory errors.
Momentum Validation: Distinguishes between high-conviction structural breaks and low-momentum "noise" using body-to-ATR ratios.
Reliability & Stability: Built-in Guard-Clauses protect against "Bar 0" and "NA" runtime errors, even when requesting lower timeframe data from a higher timeframe chart.
Key Parameters (Customizable Defaults):
Distribution Threshold (e.g. 1.2): Identifies price movement beyond the established range to confirm trend strength.
Compression (e.g. 1.5x ATR): Detects low-volatility buildup phases.
Expansion (e.g. 4.0x ATR): Flags explosive "Huge Range" impulses.
How to use (Educational Example included):
The source code contains a fully functional MTF Dashboard example (commented out at the bottom). It demonstrates how to map the library’s output variables into a visual trading interface, showing HTF trend alignment and real-time market phases.
Quick Start (Implementation):
import arnipoer/PriceActionStructure/1 as pa
// Single request for all 19 structural variables
=
request.security(syminfo.tickerid, "D",
pa.get_structure(true, 1.0, close, 14, 1.2, 1.5, 4.0))
// Example: Visualization
plot(strHigh, color=color.aqua, title="HTF Structure High")
bgcolor(hugeRange ? color.new(color.purple, 80) : na, title="Expansion Alert")
Disclaimer: No financial advice. Trading involves significant risk. This is an analytical tool for professional traders to build their own systematic strategies.
Pine Script® Bibliothek
GLLV_HelpersLibrary "GLLV_Helpers"
buildAlertMsg(pineLic, ticker, risk, sl, tp, strategyCode)
Parameters:
pineLic (string)
ticker (string)
risk (float)
sl (float)
tp (float)
strategyCode (string)
isRising(src, points, step)
Parameters:
src (float)
points (int)
step (int)
regimeOf(pip2, posLimit, negLimit)
Parameters:
pip2 (float)
posLimit (float)
negLimit (float)
calcMata(fast, mid, slow)
Parameters:
fast (float)
mid (float)
slow (float)
crossUpByColor(src, ema, pvsraColor, expectedColor)
Parameters:
src (float)
ema (float)
pvsraColor (color)
expectedColor (color)
crossDownByColor(src, ema, pvsraColor, expectedColor)
Parameters:
src (float)
ema (float)
pvsraColor (color)
expectedColor (color)
calcSlope(src, length, mult, method)
Parameters:
src (float)
length (simple int)
mult (float)
method (string)
createDebugTable()
updateDebugTable(tbl, row, label, value)
Parameters:
tbl (table)
row (int)
label (string)
value (string)
Pine Script® Bibliothek
HighClassCalculationsLibrary "HighClassCalculations"
Advanced Pine Script v6 calculation library for statistical, normalization, trend, and risk metrics.
safeDiv(numerator, denominator, fallback)
Safe division helper that prevents division-by-zero errors.
Parameters:
numerator (float) : Value on the top of the fraction.
denominator (float) : Value on the bottom of the fraction.
fallback (float) : Value returned when denominator is zero.
Returns: Result of the division or fallback.
clamp(value, minValue, maxValue)
Clamps a value into a fixed range.
Parameters:
value (float) : Source value.
minValue (float) : Minimum allowed value.
maxValue (float) : Maximum allowed value.
Returns: Clamped value.
rescale(value, oldMin, oldMax, newMin, newMax)
Rescales a value from one range into another range.
Parameters:
value (float) : Source value.
oldMin (float) : Source range minimum.
oldMax (float) : Source range maximum.
newMin (float) : Target range minimum.
newMax (float) : Target range maximum.
Returns: Rescaled value.
normalize(src, len)
Returns the min-max normalized position of a series within a rolling window.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Value between 0 and 1 when the range is valid.
rangePercent(src, len)
Returns the source position inside its rolling range as a percentage.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Value between 0 and 100 when the range is valid.
zScore(src, len)
Calculates the z-score of a series.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Standardized z-score.
robustZScore(src, len)
Calculates a robust z-score using median absolute deviation.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Robust z-score less sensitive to outliers.
percentileRank(src, len)
Calculates percentile rank for the latest value inside a rolling window.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Percentile rank from 0 to 100.
percentileValue(src, len, percentile)
Calculates the value at a requested percentile inside a rolling window.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
percentile (float) : Requested percentile from 0 to 100.
Returns: Percentile value.
simpleReturn(src)
Calculates simple arithmetic return versus the previous bar.
Parameters:
src (float) : Price or equity series.
Returns: One-bar simple return.
logReturn(src)
Calculates log return versus the previous bar.
Parameters:
src (float) : Price or equity series.
Returns: One-bar log return.
compoundedReturn(src, len)
Calculates cumulative return over a fixed lookback.
Parameters:
src (float) : Price or equity series.
len (int) : Lookback window.
Returns: Return from src to current src.
realizedVolatility(src, len, annualization)
Calculates realized volatility from log returns and annualizes it.
Parameters:
src (float) : Price or equity series.
len (int) : Rolling lookback window.
annualization (float) : Number of bars used for annualization.
Returns: Annualized volatility.
downsideDeviation(returnSeries, len, mar, annualization)
Calculates downside deviation from a return series.
Parameters:
returnSeries (float) : Series of returns, not raw price.
len (int) : Rolling lookback window.
mar (float) : Minimum acceptable return.
annualization (float) : Number of bars used for annualization.
Returns: Annualized downside deviation.
rollingSharpe(returnSeries, len, riskFreeRate, annualization)
Calculates a rolling Sharpe ratio from a return series.
Parameters:
returnSeries (float) : Series of returns, not raw price.
len (int) : Rolling lookback window.
riskFreeRate (float) : Per-bar risk free rate.
annualization (float) : Number of bars used for annualization.
Returns: Annualized Sharpe ratio.
rollingSortino(returnSeries, len, mar, annualization)
Calculates a rolling Sortino ratio from a return series.
Parameters:
returnSeries (float) : Series of returns, not raw price.
len (int) : Rolling lookback window.
mar (float) : Minimum acceptable return.
annualization (float) : Number of bars used for annualization.
Returns: Annualized Sortino ratio.
efficiencyRatio(src, len)
Calculates Kaufman's efficiency ratio.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Efficiency ratio from 0 to 1.
regressionSlope(src, len)
Calculates rolling linear regression slope.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Slope per bar.
regressionAngle(src, len)
Converts rolling regression slope into an angle.
Parameters:
src (float) : Source series.
len (int) : Rolling lookback window.
Returns: Slope angle in degrees.
beta(asset, benchmark, len)
Calculates rolling beta versus a benchmark series.
Parameters:
asset (float) : Asset series.
benchmark (float) : Benchmark series.
len (int) : Rolling lookback window.
Returns: Beta coefficient.
alpha(asset, benchmark, len, riskFreeRate)
Calculates Jensen-style alpha versus a benchmark series.
Parameters:
asset (float) : Asset return series.
benchmark (float) : Benchmark return series.
len (int) : Rolling lookback window.
riskFreeRate (float) : Per-bar risk free rate.
Returns: Alpha over the rolling window.
ulcerIndex(src, len)
Calculates the Ulcer Index for a series.
Parameters:
src (float) : Price or equity series.
len (int) : Rolling lookback window.
Returns: Ulcer Index value.
maxDrawdown(src, len)
Calculates the maximum drawdown over a rolling window.
Parameters:
src (float) : Price or equity series.
len (int) : Rolling lookback window.
Returns: Maximum drawdown as a negative decimal.
atrPercent(len, src)
Calculates ATR as a percentage of price.
Parameters:
len (simple int) : ATR lookback window.
src (float) : Reference price used for the percentage denominator.
Returns: ATR percent.
relativeVolume(len)
Calculates relative volume versus its rolling average.
Parameters:
len (simple int) : Rolling lookback window.
Returns: Volume divided by average volume.
getAllFunctions()
Returns a comma-separated list of all exported calculation helpers.
Returns: Function catalog for quick reference.
Pine Script® Bibliothek






















