PatternHelpersLibrary "PatternHelpers"
method update(atr, h, l, c, period)
Namespace types: WilderAtr
Parameters:
atr (WilderAtr)
h (float)
l (float)
c (float)
period (int)
method push(buf, o, h, l, c, t, idx, max_len)
Namespace types: CandleBuffer
Parameters:
buf (CandleBuffer)
o (float)
h (float)
l (float)
c (float)
t (int)
idx (int)
max_len (int)
method gap_candles(buf, prev_end_idx, next_start_idx)
Namespace types: CandleBuffer
Parameters:
buf (CandleBuffer)
prev_end_idx (int)
next_start_idx (int)
quantile_rail(vals, upper)
Parameters:
vals (array)
upper (bool)
has_acceptable_coverage(values, upper_bounds, lower_bounds)
Parameters:
values (array)
upper_bounds (array)
lower_bounds (array)
has_acceptable_coverage_const(values, upper, lower)
Parameters:
values (array)
upper (float)
lower (float)
has_low_directional_drift(closes, upper, lower)
Parameters:
closes (array)
upper (float)
lower (float)
has_balanced_rotation(values, shape_width)
Parameters:
values (array)
shape_width (float)
has_no_dominant_run(values, shape_width)
Parameters:
values (array)
shape_width (float)
ols_regression(y, x, origin_x)
Parameters:
y (array)
x (array)
origin_x (int)
residual_rail(highs_or_lows, indices, intercept, slope, origin_idx, upper)
Parameters:
highs_or_lows (array)
indices (array)
intercept (float)
slope (float)
origin_idx (int)
upper (bool)
WilderAtr
Fields:
prev_close (series float)
atr_val (series float)
count (series int)
CandleBuffer
Fields:
opens (array)
highs (array)
lows (array)
closes (array)
times (array)
indices (array)
start_idx (series int) ライブラリ

ライブラリ

ライブラリ

ライブラリ

ライブラリ

ライブラリ

AssetCorrelationUtilsAssetCorrelationUtils
Auto-detection library for correlated asset pairings across futures, CFD, and crypto markets. Given any chart, returns the correct secondary and tertiary (and optionally quaternary) tickers for multi-asset divergence analysis, along with inversion flags and asset-category metadata.
Designed to eliminate the boilerplate of hardcoded ticker lists and manual "if EURUSD then GBPUSD" branching in every indicator that needs correlated data.
What it does
Consumer scripts call one function — resolveCurrentChart() — and receive a fully resolved AssetConfig object describing the current chart's correlated pair or triad. The library handles:
Symbol root extraction from full ticker IDs (with expiry suffixes, exchange prefixes, micro variants)
Asset category routing (futures / CFD / crypto branches)
Family-specific triad or dyad selection
Inversion detection (e.g. 6C inverse of USDCAD, DXY inverse of EUR/GBP)
Futures session and back-adjustment modifiers
Optional GXT mode for metals (currency-cross triads on Gold/Silver)
Optional Quad mode for metals (four-leg configurations)
Micro contracts always resolve to their higher-volume full-size correlated partners — MNQ correlates against ES/YM, not MES/MYM — matching the "trade the micros, read the majors" convention.
Supported asset classes
Futures
Indices: NQ, ES, YM, RTY + micros (MNQ, MES, MYM, M2K)
Metals: GC, SI, HG + micros (MGC, SIL, MHG)
Forex: 6E, 6B, 6A, 6N, 6C + micros (M6E, M6B, M6A, M6C)
Energy: CL, RB, HO + micros (MCL, MRB, MHO)
Treasury: ZB, ZF, ZN
Crypto: BTC, ETH + micros (MBT, MET)
CFD / Spot
Forex: EURUSD, GBPUSD, DXY, USDJPY, USDCHF, USDCAD
Metals: XAUUSD, XAGUSD, COPPER + cross-pairs (XAUEUR, XAUGBP, XAGEUR, XAGGBP)
Indices: NAS100, SP500, DJ30
EU Stocks: GER40, EU50 (dyad only)
Crypto (spot / perp)
Major: BTC, ETH, SOL, XRP
Alt: ZEC, DOGE, ADA, BNB, TAO
All routed via BINANCE perpetual (.P) pairs for consistent OHLC quality
Core functions
resolveCurrentChart(gxtMode = false, quadMode = false)
The one-liner entry point for most consumers. Wraps resolveAssets() with sensible defaults (uses syminfo.ticker, syminfo.tickerid, syminfo.type, syminfo.session, back-adjustment on).
resolveAssets(ticker, tickerId, assetType, session, useBackadjust, gxtMode, quadMode)
The full-control entry point. Same detection logic, but with explicit control over back-adjustment and session modification — useful for indicators with a strategy toggle (e.g. RTH vs ETH sessions).
Category detectors
detectIndicesFutures(ticker)
detectMetalsFutures(ticker) / detectMetalsFuturesGxt(ticker) / detectMetalsFuturesQuad(ticker)
detectForexFutures(ticker) / detectCADFutures(ticker)
detectEnergyFutures(ticker)
detectTreasuryFutures(ticker)
detectCryptoFutures(ticker)
detectForexCFD(ticker, tickerId)
detectCrypto(ticker, tickerId)
detectMetalsCFD(ticker, tickerId) / detectMetalsCFDGxt(ticker, tickerId) / detectMetalsCFDQuad(ticker, tickerId)
detectIndicesCFD(ticker, tickerId)
detectEUStocks(ticker, tickerId)
Each returns an AssetPairing — usable directly if you want to bypass the automatic category routing.
Resolution helpers
resolveTriad(chartTickerId, pairing) — returns primary + secondary + tertiary with inversion flags
resolveDyad(chartTickerId, pairing) — returns primary + secondary for two-asset configs
resolveQuad(chartTickerId, pairing) — returns four-asset config with inversion flags
Utility functions
applySessionModifierWithBackadjust(ticker, session) / applySessionModifierNoBackadjust(ticker, session) — apply ticker.modify with back-adjustment on or off
isTriadMode(pairing) — check whether a pairing has a valid tertiary
getAssetTicker(tickerId) — extract the clean ticker string from a full ticker ID
Fallback
getDefaultFallback(tickerId) — returns a pairing with the chart ticker as primary and empty secondaries. Used automatically when no category matches.
Return types
AssetConfig
detected (bool) — true if the chart asset was recognized
isTriadMode (bool) — true if 3 assets resolved, false for dyad
isQuadMode (bool) — true if 4 assets resolved
primary (string) — resolved primary ticker ID
secondary (string) — resolved secondary ticker ID
tertiary (string) — resolved tertiary ticker ID (empty for dyad)
quaternary (string) — resolved quaternary ticker ID (empty unless quad mode)
invertSecondary (bool)
invertTertiary (bool)
invertQuaternary (bool)
assetCategory (string) — category tag (e.g. "index_futures", "metal_cfd_gxt")
AssetPairing
Internal pairing structure used by detector functions. Consumers rarely construct this directly, but resolveTriad / resolveDyad / resolveQuad accept it if you're bypassing the auto-routing.
Quick start
import I_quacker_I/AssetCorrelationUtils/7 as AC
AC.AssetConfig config = AC.resolveCurrentChart()
string secondary = config.secondary
string tertiary = config.tertiary
bool inv2 = config.invertSecondary
bool inv3 = config.invertTertiary
bool detected = config.detected
For metals with currency-cross triads:
AC.AssetConfig config = AC.resolveCurrentChart(true)
// On Gold: secondary = "FOREXCOM:XAUEUR", tertiary = "FOREXCOM:XAUGBP"
// On Copper or non-metals: identical to resolveCurrentChart(false)
Full integration patterns (Off / Auto / Manual tri-state, explicit back-adjust control, and manual pairing) are documented inline in the library source.
Design notes
Robust ticker matching. All detectors use str.contains() on the root symbol, so any ticker format is recognized — bare (NQ), continuous (NQ1!), or dated with expiry (NQZ2025). Exchange prefixes are ignored during detection.
Consistent inversion semantics. DXY as the third leg of USD-base forex triads is marked inverted (rises when the pair falls). 6C as USDCAD's futures counterpart is fully inverted. Micros carry their parent's inversion flags unchanged.
Category tags. Every resolved AssetConfig carries an assetCategory string ("index_futures", "metal_cfd_gxt", "crypto", "fallback", etc.). Useful for consumer scripts that want to conditionally enable features per category (e.g. "only compute GXT confluence on metals").
Fallback safety. When no category matches, the library returns the chart ticker as primary with empty secondary / tertiary, detected = false, and assetCategory = "fallback". Consumer scripts should check detected before assuming correlated data is available.
Credits
Original library concept — @fstarcapital
Modifications and extensions — @I_quacker_I
Crypto remapped to BINANCE .P perpetuals
Micro contracts always correlate against higher-volume mini/full contracts
AUD/NZD forex futures family (6A, M6A, 6N)
GXT mode for metals (currency-cross triads)
Quad mode for four-leg metal configurations
Crypto tertiary swapped from TOTAL3 (market-cap index, no clean OHLC) to XRP (tradeable asset with proper sweep behavior)
License: Mozilla Public License 2.0 ライブラリ

ライブラリ

OhMyHtfLibraryLibrary "OhMyHtfLibrary"
HTF candle platform: timeframe alignment, profiles, and (future) packed OHLC / draw helpers. Import as `import daggerok/OhMyHtfLibrary/1 as omhl`. Sweep/OB domain → future `OhMyHtfSweepLibrary` (`omhsl`).
resolveHtfContext(chart_tf_seconds, default_htf, default_candle_count, align_ctf_max_seconds, align_htf, align_enabled, profile_ctf_exact_seconds, profile_htf, profile_enabled, profile_candle_counts)
Resolves HTF string, enable flag, and candle count from Timeframes Alignment + Profiles.
TFA: first alignment row where `chart_tf_seconds <= align_ctf_max_seconds ` wins.
Profiles: first enabled row where `chart_tf_seconds == profile_ctf_exact_seconds ` overrides TFA.
Parameters:
chart_tf_seconds (int) : Chart timeframe in seconds.
default_htf (string) : Fallback HTF when no alignment rule matches.
default_candle_count (int) : Default HTF candle count (HTF Candles input).
align_ctf_max_seconds (array) : Upper-bound CTF seconds per TFA row (length 14).
align_htf (array) : HTF string per TFA row.
align_enabled (array) : Enabled flag per TFA row.
profile_ctf_exact_seconds (array) : Exact chart TF seconds per profile row (length 12).
profile_htf (array) : HTF string per profile row.
profile_enabled (array) : Profile row enabled flags.
profile_candle_counts (array) : Candle count per profile row.
Returns: `HtfContext` with resolved settings.
HtfContext
Resolved HTF timeframe settings for the current chart.
Fields:
htf (series string) : Higher timeframe string for `request.security` and draw logic.
is_enabled (series bool) : Whether HTF features are active for this chart TF (TFA enable flag or profile override).
candle_count (series int) : Number of HTF candles to display (profile may override default).
profile_override (series bool) : True when a profile row matched (exact CTF). ライブラリ

ライブラリ

lib_fvgLibrary "lib_fvg"
Fair Value Gap engine — detection, testing/inversion lifecycle, HTF nesting filters, entry-candidate selection, stop-loss derivation, and FVG drawing — extracted 1:1 from rewrite_strategy.pine.
method equals(this, other)
Namespace types: FVG
Parameters:
this (FVG)
other (FVG)
method remove(this, item)
Namespace types: array
Parameters:
this (array)
item (FVG)
method check_nested_in(this, htf_fvg, check_nested, check_untested, check_nearby, nearby_threshold, check_newer_ltf)
Namespace types: FVG
Parameters:
this (FVG)
htf_fvg (FVG)
check_nested (bool)
check_untested (bool)
check_nearby (bool)
nearby_threshold (float)
check_newer_ltf (bool)
method distance_to_price_post_inverse(this, price)
Namespace types: FVG
Parameters:
this (FVG)
price (float)
method is_higher_tf_or_closer_to_price_than(this, other)
Namespace types: FVG
Parameters:
this (FVG)
other (FVG)
method get_stop_loss(this, entry_price, session_extreme, enable_sl_at_fvg_created_swing_point, trail_session_level_tight_threshold)
Namespace types: FVG
Parameters:
this (FVG)
entry_price (float)
session_extreme (float)
enable_sl_at_fvg_created_swing_point (bool)
trail_session_level_tight_threshold (float)
method delete_bar(this)
Namespace types: Bar
Parameters:
this (Bar)
method delete_fvg(this)
Namespace types: FVG
Parameters:
this (FVG)
log_entry_rejection(enable_log, fvg, reason, smt, note)
Parameters:
enable_log (bool)
fvg (FVG)
reason (series EntryFilterReason)
smt (SMT type from Danieltrade29292/lib_smt/1)
note (string)
method invalidate_fvg(this, fvg, reason, entry_block_reason, lifecycle)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
fvg (FVG)
reason (series FVGFilterReason)
entry_block_reason (series EntryFilterReason)
lifecycle (series FVGLifecycle)
method add_fvg(this, fvg, enable_single_fvg_per_tf)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
fvg (FVG)
enable_single_fvg_per_tf (bool)
method detect_fvg(this, tf, tf_id, t2, h2, l2, h1, l1, h0, l0, min_gap_size, fvg_deprecation_period, enable_single_fvg_per_tf)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
tf (string)
tf_id (int)
t2 (int)
h2 (float)
l2 (float)
h1 (float)
l1 (float)
h0 (float)
l0 (float)
min_gap_size (float)
fvg_deprecation_period (int)
enable_single_fvg_per_tf (bool)
method invalidate_all_of_direction(this, fvg_is_bullish, reason)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
fvg_is_bullish (bool)
reason (series FVGFilterReason)
method invalidate_fvgs_inversed_pre_smt(this, smt_buffer, enable_log)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
smt_buffer (SMTBuffer type from Danieltrade29292/lib_smt/1)
enable_log (bool)
method try_park_in(this, htf_pool, check_nested, check_untested, check_nearby, nearby_threshold, check_newer_ltf)
Namespace types: FVG
Parameters:
this (FVG)
htf_pool (array)
check_nested (bool)
check_untested (bool)
check_nearby (bool)
nearby_threshold (float)
check_newer_ltf (bool)
method update_htf_relations(this, enable_filter_by_full_nest_in_HTF_fvg, enable_filter_by_untested, enable_filter_by_edge_nearby_HTF_fvg, nearby_HTF_threshold, enable_filter_by_newer_LTF_fvg)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
enable_filter_by_full_nest_in_HTF_fvg (bool)
enable_filter_by_untested (bool)
enable_filter_by_edge_nearby_HTF_fvg (bool)
nearby_HTF_threshold (float)
enable_filter_by_newer_LTF_fvg (bool)
method update_fvgs(this, tf2, tf2_updated, fvg2_o, fvg2_h, fvg2_l, fvg2_c, tf3, tf3_updated, fvg3_o, fvg3_h, fvg3_l, fvg3_c, tf4, tf4_updated, fvg4_o, fvg4_h, fvg4_l, fvg4_c, min_inversion_distance, max_inversion_distance, tested_by_mode, max_tests_before_inverse)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
tf2 (string)
tf2_updated (bool)
fvg2_o (float)
fvg2_h (float)
fvg2_l (float)
fvg2_c (float)
tf3 (string)
tf3_updated (bool)
fvg3_o (float)
fvg3_h (float)
fvg3_l (float)
fvg3_c (float)
tf4 (string)
tf4_updated (bool)
fvg4_o (float)
fvg4_h (float)
fvg4_l (float)
fvg4_c (float)
min_inversion_distance (float)
max_inversion_distance (float)
tested_by_mode (series FVGTestedByMode)
max_tests_before_inverse (int)
method find_next_best_waiting_fvgs(this, smt_buffer)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
smt_buffer (SMTBuffer type from Danieltrade29292/lib_smt/1)
method find_entry_candidate_fvg(this, smt_buffer, enable_filter_by_inversion_bar_close_in_untested_HTF_fvg, enable_log)
Namespace types: FVGBuffer
Parameters:
this (FVGBuffer)
smt_buffer (SMTBuffer type from Danieltrade29292/lib_smt/1)
enable_filter_by_inversion_bar_close_in_untested_HTF_fvg (bool)
enable_log (bool)
method draw_bar(this, is_bullish, bgcolor, border_color, labelcolor, txt, show_box)
Namespace types: Bar
Parameters:
this (Bar)
is_bullish (bool)
bgcolor (color)
border_color (color)
labelcolor (color)
txt (string)
show_box (bool)
method draw_fvg(this, color_bull, color_bear, debug)
Namespace types: FVG
Parameters:
this (FVG)
color_bull (color)
color_bear (color)
debug (bool)
method draw_fvgs(this, color_bull, color_bear, debug)
Namespace types: array
Parameters:
this (array)
color_bull (color)
color_bear (color)
debug (bool)
method draw_entry_fvg(this, color_bull, color_bear, debug)
Namespace types: FVG
Parameters:
this (FVG)
color_bull (simple color)
color_bear (simple color)
debug (bool)
method delete_fvgs(this)
Namespace types: array
Parameters:
this (array)
Bar
Fields:
o (series float)
h (series float)
l (series float)
c (series float)
top (series float)
btm (series float)
t_open (series int)
i_open (series int)
t_close (series int)
i_close (series int)
bar_box (series box)
bar_label (series label)
FVG
Fields:
is_bullish_original (series bool)
is_bullish_post_inverse (series bool)
tf (series string)
tf_id (series int)
top_left (chart.point)
bottom_right (chart.point)
hh (series float)
ll (series float)
deprecate_at (series int)
sl_level (series float)
is_active (series bool)
test_count (series int)
first_test_idx (series int)
is_inversed (series bool)
has_touched (series bool)
fvg_box (series box)
tooltip_label (series label)
hidden (series bool)
draw_signal_inversed (series bool)
draw_signal_text (series bool)
draw_signal_highlight (series bool)
draw_signal_set_candidate (series bool)
draw_signal_reset_candidate (series bool)
fill_state (series FVGFillState)
lifecycle (series FVGLifecycle)
filter_reason (series FVGFilterReason)
entry_filter_reason (series EntryFilterReason)
tf_inversion_bar (Bar)
inversion_idx (series int)
FVGBuffer
Fields:
items (array)
inversed (array)
invalidated (array) ライブラリ

lib_smtLibrary "lib_smt"
SMT divergence + session detection/lifecycle, SMT buffers, premium/discount zones, and their on-chart drawing — extracted 1:1 from rewrite_strategy.pine.
method equals(this, other)
Namespace types: SMT
Parameters:
this (SMT)
other (SMT)
method delete_smt(this)
Namespace types: SMT
Parameters:
this (SMT)
method delete_smts(this)
Namespace types: array
Parameters:
this (array)
method replace(this, value)
Namespace types: array
Parameters:
this (array)
value (Session)
method replace(sess, idx, value, remove_buffer)
Namespace types: array
Parameters:
sess (array)
idx (int)
value (Session)
remove_buffer (array)
method reset(this)
Namespace types: SessionSignals
Parameters:
this (SessionSignals)
method reset(this)
Namespace types: SessionLevel
Parameters:
this (SessionLevel)
method reset(this)
Namespace types: Session
Parameters:
this (Session)
method invalidate_smt(this, smt, reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
smt (SMT)
reason (series SMTFilterReason)
method invalidate_session(this, sess, reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
sess (Session)
reason (series SMTFilterReason)
method set_intra(this, smt)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
smt (SMT)
method reset_intra(this, reason, sess, reset_bull, reset_bear)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
reason (series SMTFilterReason)
sess (Session)
reset_bull (bool)
reset_bear (bool)
method invalidate_all_daily_smts(this, reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
reason (series SMTFilterReason)
method invalidate_all_session_smts(this, is_bullish, reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
is_bullish (bool)
reason (series SMTFilterReason)
method invalidate_entry_daily_smt(this, entry_smt, reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
entry_smt (SMT)
reason (series SMTFilterReason)
method invalidate_by_detected_session_id(this, id, reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
id (int)
reason (series SMTFilterReason)
method invalidate_swept_sessions(this, session_signals, overflow_buffer)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
session_signals (SessionSignals)
overflow_buffer (array)
method add_smt(this, smt)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
smt (SMT)
method update_smt(this, other_high, other_low, smt_buffer, enable_invalidation_by_distance, invalidation_dist_chart_led, invalidation_dist_other_led)
Namespace types: SMT
Parameters:
this (SMT)
other_high (float)
other_low (float)
smt_buffer (SMTBuffer)
enable_invalidation_by_distance (bool)
invalidation_dist_chart_led (float)
invalidation_dist_other_led (float)
method update_smts(this, other_high, other_low, enable_invalidation_by_distance, invalidation_dist_chart_led, invalidation_dist_other_led)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
other_high (float)
other_low (float)
enable_invalidation_by_distance (bool)
invalidation_dist_chart_led (float)
invalidation_dist_other_led (float)
method update_session_level_sweeps(this, other_high, other_low)
Namespace types: Session
Parameters:
this (Session)
other_high (float)
other_low (float)
method detect_smt(this, smt_h1, smt_l1, smt_c1, smt_other_h1, smt_other_l1, is_smt_tf_new_bar, smt_buffer, active_session_id, smt_min_age, is_intra, is_blocked_intra_smt_bull, is_blocked_intra_smt_bear, timeout_intra, touch_tolerance, intra_min_swing_age)
─────────────────────────────────────────────────────────────────────────────
session.detect_smt — check if chart/other has swept H or L
§2.2.1 Level SMT Detection / §2.2.2 Daily SMT Detection / §2.2.3 Intra SMT Detection
is_intra=true → called on live active session (§2.2.3); uses running H/L, equal high/low counts
is_intra=false → called on archived session (§2.2.1/§2.2.2); levels are fixed at capture time
active_session_id: session currently open, stored as detected_session_id on new SMTs
so §2.3.2 London-detected invalidation can filter correctly on NY open
─────────────────────────────────────────────────────────────────────────────
Namespace types: Session
Parameters:
this (Session)
smt_h1 (float)
smt_l1 (float)
smt_c1 (float)
smt_other_h1 (float)
smt_other_l1 (float)
is_smt_tf_new_bar (bool)
smt_buffer (SMTBuffer)
active_session_id (int)
smt_min_age (int)
is_intra (bool)
is_blocked_intra_smt_bull (bool)
is_blocked_intra_smt_bear (bool)
timeout_intra (int)
touch_tolerance (float)
intra_min_swing_age (int)
method detect_smts(this, signals, smt_h1, smt_l1, smt_c1, smt_other_h1, smt_other_l1, is_smt_tf_new_bar, smt_buffer, active_session_id, smt_min_age, touch_tolerance)
Namespace types: array
Parameters:
this (array)
signals (SessionSignals)
smt_h1 (float)
smt_l1 (float)
smt_c1 (float)
smt_other_h1 (float)
smt_other_l1 (float)
is_smt_tf_new_bar (bool)
smt_buffer (SMTBuffer)
active_session_id (int)
smt_min_age (int)
touch_tolerance (float)
method has_active_daily_smt(this, seeks_bullish)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
seeks_bullish (bool)
method find_best_smt_by_prio(this, minimum_prio, seeks_bullish)
Namespace types: array
Parameters:
this (array)
minimum_prio (int)
seeks_bullish (bool)
method find_best_smt_by_direction(this, intra_smts_enabled, seeks_bullish)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
intra_smts_enabled (bool)
seeks_bullish (bool)
method update_best_smts(this, pd_zone, intra_smts_enabled, allow_bullish_intra_smt_post_cutoff_if_has_daily_smt_active, allow_bearish_intra_smt_post_cutoff_if_has_daily_smt_active)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
pd_zone (int)
intra_smts_enabled (bool)
allow_bullish_intra_smt_post_cutoff_if_has_daily_smt_active (bool)
allow_bearish_intra_smt_post_cutoff_if_has_daily_smt_active (bool)
method rotate(this, sess, max)
Namespace types: array
Parameters:
this (array)
sess (Session)
max (int)
method add_session(this, sess, overflow_buffer)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
sess (Session)
overflow_buffer (array)
method evict_consumed_days(this, overflow_buffer, max_history_days)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
overflow_buffer (array)
max_history_days (simple int)
method clear_invalidated_smts(this, keep_level, keep_intra, keep_reason)
Namespace types: SMTBuffer
Parameters:
this (SMTBuffer)
keep_level (bool)
keep_intra (bool)
keep_reason (bool)
method archive(this)
Namespace types: SessionLevel
Parameters:
this (SessionLevel)
method archive(this)
Namespace types: Session
Parameters:
this (Session)
method update_levels(this, is_smt_tf_new_bar, other_high, other_low, smt_t1, smt_h1, smt_l1, smt_other_h1, smt_other_l1)
Namespace types: Session
Parameters:
this (Session)
is_smt_tf_new_bar (bool)
other_high (float)
other_low (float)
smt_t1 (int)
smt_h1 (float)
smt_l1 (float)
smt_other_h1 (float)
smt_other_l1 (float)
method update_session(this, signals, smt_buffer, new_day, other_high, other_low, smt_t1, smt_h1, smt_l1, smt_c1, smt_other_h1, smt_other_l1, is_smt_tf_new_bar, smt_min_age, timeout_intra, in_any_no_intra_smt_zone, enable_block_intra_smts_pre_high_prio_sweep, previous_session, intra_min_swing_age)
Namespace types: Session
Parameters:
this (Session)
signals (SessionSignals)
smt_buffer (SMTBuffer)
new_day (bool)
other_high (float)
other_low (float)
smt_t1 (int)
smt_h1 (float)
smt_l1 (float)
smt_c1 (float)
smt_other_h1 (float)
smt_other_l1 (float)
is_smt_tf_new_bar (bool)
smt_min_age (int)
timeout_intra (int)
in_any_no_intra_smt_zone (bool)
enable_block_intra_smts_pre_high_prio_sweep (bool)
previous_session (Session)
intra_min_swing_age (int)
method draw_session(this, show_chart, show_panel)
Namespace types: Session
Parameters:
this (Session)
show_chart (bool)
show_panel (bool)
method draw_session_consumed(this)
Namespace types: Session
Parameters:
this (Session)
method delete(this)
Namespace types: Session
Parameters:
this (Session)
method delete(this)
Namespace types: array
Parameters:
this (array)
method register(this, enabled, session, _fill_color, _text, _text_color, _border_color, prio, id, is_daily, is_session, enable_intra_smts, is_no_intra_smt_zone, smt_timeout, strategy_config)
Namespace types: array
Parameters:
this (array)
enabled (bool)
session (string)
_fill_color (color)
_text (string)
_text_color (color)
_border_color (color)
prio (int)
id (int)
is_daily (bool)
is_session (bool)
enable_intra_smts (bool)
is_no_intra_smt_zone (bool)
smt_timeout (int)
strategy_config (StrategyConfig)
method short_id(this)
Namespace types: SMT
Parameters:
this (SMT)
method label_text(this, other_ticker, include_filter_reason, is_leader)
Namespace types: SMT
Parameters:
this (SMT)
other_ticker (string)
include_filter_reason (bool)
is_leader (bool)
method draw_smt(this, other_ticker, show_label_leader, show_label_follower, verbose)
Namespace types: SMT
Parameters:
this (SMT)
other_ticker (string)
show_label_leader (bool)
show_label_follower (bool)
verbose (bool)
method draw_smts(this, other_ticker, show_label_leader, show_label_follower, show_filter_reason)
Namespace types: array
Parameters:
this (array)
other_ticker (string)
show_label_leader (bool)
show_label_follower (bool)
show_filter_reason (bool)
get_pd_range(enable, bars_lookback, new_hour)
Parameters:
enable (simple bool)
bars_lookback (int)
new_hour (bool)
draw_pd(new_hour, pd_start, pd_high, pd_equilibrium, pd_low)
Parameters:
new_hour (bool)
pd_start (int)
pd_high (float)
pd_equilibrium (float)
pd_low (float)
SMT
Fields:
detected_session_id (series int)
leader (series int)
leader_level (chart.point)
sweep (chart.point)
follow_level (chart.point)
session_id (series int)
prio (series int)
is_bullish (series bool)
deprecate_at (series int)
detection_bar (series int)
detection_close (series float)
valid_from (series int)
invalidated (series bool)
filter_reason (series SMTFilterReason)
leader_line (series line)
leader_label (series label)
follow_line (series line)
follow_intermediate_line (series line)
follow_label (series label)
smt_color (series color)
draw_remove_highlight (series bool)
used_for_trade (series bool)
trade_end_time (series int)
SessionLevel
tracks session H/L
Fields:
chart (chart.point)
other (chart.point)
chart_smt_tf (chart.point)
other_smt_tf (chart.point)
is_consumed (series bool)
smt (SMT)
StrategyConfig
Fields:
big_win_threshold (series float)
cutoff_hour (series int)
cutoff_tz (series string)
cutoff_mode (series SessionCutoffMode)
max_losses (series int)
max_wins (series int)
Session
Fields:
id (series int)
prio (series int)
timeout (series int)
session (series string)
h (SessionLevel)
l (SessionLevel)
_fill_color (series color)
_text (series string)
_text_color (series color)
_border_color (series color)
is_daily (series bool)
is_session (series bool)
is_no_intra_smt_zone (series bool)
enable_intra_smts (series bool)
strategy_config (StrategyConfig)
start_time (series int)
end_time (series int)
cutoff_at (series int)
is_active (series bool)
is_consumed (series bool)
box_chart (series box)
box_other (series box)
mean_sum (series float)
mean_count (series float)
mean (series float)
is_any_low_swept (series bool)
is_any_high_swept (series bool)
draw_signal_consumed (series bool)
tooltip_chart (series label)
tooltip_other (series label)
SessionSignals
Fields:
signal_session_started (series int)
signal_session_ending (series int)
signal_session_ended (series int)
signal_no_intra_smt_zone_started (series int)
signal_no_intra_smt_zone_ending (series int)
signal_no_intra_smt_zone_ended (series int)
signal_intra_smt_h (series int)
signal_intra_smt_l (series int)
signal_session_consumed (series bool)
SMTBuffer
Fields:
session_smts (array)
daily_smts (array)
intra_smts (array)
invalidated (array)
delete_buffer (array)
monitored_sessions (array)
monitored_days (array)
consumed_days (array)
max_days (series int)
best_bull_smt (SMT)
best_bear_smt (SMT) ライブラリ

MarketReactionLibrary "MarketReaction"
Modular library for sessions, Initial Balance, PSY ranges, VWAPs, alerts, and macro sentiment helpers.
getSessionConfig(source)
Returns session config by source name.
Parameters:
source (simple string) : Session source: Tokyo, New York, London, Jerusalem, EU B, US B.
Returns: SessionConfig.
sessionModule(session, timeZone, sessionText, sessionColor, sessionDuration, showVisuals, showLabels, showLines, showMiddleLine, showBg, bgTransp)
Builds session high/low/middle lines, label, background fill and VWAP.
Parameters:
session (simple string) : Session string.
timeZone (simple string) : IANA timezone.
sessionText (simple string) : Label text.
sessionColor (color) : Session color.
sessionDuration (simple int) : Approximate session duration in ms.
showVisuals (bool) : Show this session visuals.
showLabels (bool) : Show labels.
showLines (bool) : Show high/low lines.
showMiddleLine (bool) : Show middle line.
showBg (bool) : Show background fill.
bgTransp (int) : Background transparency.
Returns: SessionResult.
initialBalanceModule(session, ibSession, timeZone, sessionLabel, showDLabels, showWLabels, showMLabels, showPrevD, showPrevW, showPrevM, dColor, wColor, mColor)
Calculates Daily, Weekly, Monthly Initial Balance and W/M IB VWAPs.
Parameters:
session (simple string) : Full session string.
ibSession (simple string) : IB sub-session string.
timeZone (simple string) : IANA timezone.
sessionLabel (simple string) : Session label.
showDLabels (bool) : Show D.IB labels.
showWLabels (bool) : Show W.IB labels.
showMLabels (bool) : Show M.IB labels.
showPrevD (bool) : Calculate previous daily IB.
showPrevW (bool) : Calculate previous weekly IB.
showPrevM (bool) : Calculate previous monthly IB.
dColor (color) : Daily IB label color.
wColor (color) : Weekly IB label color.
mColor (color) : Monthly IB label color.
Returns: IBResult.
psyRangeModule(session, timeZone, showLabels, showPrev, sessionColor)
Calculates PSY high/low, previous PSY levels, labels, and VWAP.
Parameters:
session (simple string) : Session string.
timeZone (simple string) : Timezone.
showLabels (bool) : Show PSY labels.
showPrev (bool) : Show previous PSY levels.
sessionColor (color) : PSY color.
Returns: PSYResult.
rangeSignal(highLevel, lowLevel, price)
Returns enter/exit signals for a range.
Parameters:
highLevel (float) : Range high.
lowLevel (float) : Range low.
price (float) : Price source.
Returns: RangeSignal.
tablePosition(pos)
Converts table position string to Pine position.
Parameters:
pos (simple string) : Position text.
Returns: Pine table position.
SessionConfig
Session configuration.
Fields:
session (series string) : Full session time.
ib (series string) : Initial Balance sub-session time.
tz (series string) : Session timezone.
label (series string) : Session label.
col (series color) : Session color.
duration (series int) : Approximate session duration in milliseconds.
SessionResult
Session result.
Fields:
high (series float) : Session high.
low (series float) : Session low.
mid (series float) : Session middle.
vwap (series float) : Session VWAP.
inSession (series bool) : True if bar is inside session.
firstBar (series bool) : True on first session bar.
highLine (series line) : Session high line.
lowLine (series line) : Session low line.
midLine (series line) : Session middle line.
IBResult
Initial Balance result.
Fields:
dHigh (series float) : Daily IB high.
dLow (series float) : Daily IB low.
pdHigh (series float) : Previous daily IB high.
pdLow (series float) : Previous daily IB low.
wHigh (series float) : Weekly IB high.
wLow (series float) : Weekly IB low.
pwHigh (series float) : Previous weekly IB high.
pwLow (series float) : Previous weekly IB low.
mHigh (series float) : Monthly IB high.
mLow (series float) : Monthly IB low.
pmHigh (series float) : Previous monthly IB high.
pmLow (series float) : Previous monthly IB low.
wVwap (series float) : Weekly IB VWAP.
mVwap (series float) : Monthly IB VWAP.
inSession (series bool) : True if bar is inside selected full session.
inIB (series bool) : True if bar is inside selected IB session.
ibFirstBar (series bool) : True on first IB bar.
sessionFirstBar (series bool) : True on first full-session bar.
PSYResult
PSY range result.
Fields:
high (series float) : Current PSY high.
low (series float) : Current PSY low.
pHigh (series float) : Previous PSY high.
pLow (series float) : Previous PSY low.
vwap (series float) : PSY VWAP.
inSession (series bool) : True if bar is inside PSY range.
firstBar (series bool) : True on first PSY bar.
RangeSignal
Range signal result.
Fields:
enter (series bool) : True when price enters range.
exit (series bool) : True when price exits range.
topDn (series bool) : Crossunder from above high.
topUp (series bool) : Crossover above high.
botUp (series bool) : Crossover from below low.
botDn (series bool) : Crossunder below low. ライブラリ

AxiomMovingAverageLibraryAxiom Moving Average Library
Overview
If your Pine script offers a moving average type selector, you have probably written the same dispatch logic more than once. An enum, a switch, and a quiet hope that the next script you copy it into stays consistent with the last one.
This library replaces that pattern. Import it, use the MaType enum for your dropdown, and call get_ma() to route the user's choice to the right computation. Eight standard moving average types — SMA, EMA, RMA, WMA, VWMA, HMA, and SWMA — all backed by Pine's built-in ta.* functions. Nothing custom under the hood.
Why it exists
This is a maintenance problem, and it compounds.
Every Axiom indicator and strategy that gives users a moving average choice needs the same underlying infrastructure: a type list, a dispatcher, and correct parameter handling for each type. When that logic lives inside every script individually, it drifts. One script picks up HMA support; another doesn't. A third gets the defaults wrong. None of this is visible until someone notices that the same configuration produces different behavior across two Axiom tools.
That kind of inconsistency doesn't announce itself — it just erodes confidence in the products over time.
This library makes the dispatch code shared. Every consuming script references the same enum, calls the same wrappers, and gets the same result for the same inputs. The repetitive parts stay consistent so you can focus on the work that's actually yours — choosing which averages to offer, deciding what lengths make sense, and building the logic around the result. The plumbing shouldn't be something you rewrite every time.
Quickstart
import AxiomCharts/AxiomMovingAverageLibrary/1 as maLib
maChoice = input.enum(maLib.MaType.EMA, title = "MA Type")
maLength = input.int(20, title = "MA Length", minval = 1)
maValue = maLib.get_ma(maChoice, close, maLength)
Import the library, give your users a dropdown, and route their selection through get_ma(). That covers the standard integration.
Recommended alias : maLib — short, and it distinguishes this from the Pro library if you end up using both.
API
The library exports three things: an enum, eight individual wrapper functions, and one dispatcher.
MaType enum
Eight values, each mapping to a standard moving average:
MaType.SMA - Simple Moving Average
MaType.EMA - Exponential Moving Average
MaType.RMA - Wilder / Relative Moving Average
MaType.WMA - Weighted Moving Average
MaType.VWMA - Volume-Weighted Moving Average
MaType.HMA - Hull Moving Average
MaType.SWMA - Symmetrically Weighted Moving Average
The enum works directly with input.enum(), so you can wire it into a settings dropdown without building your own type list.
Wrapper functions
Each type has a named function: ma_sma(src, length), ma_ema(src, length), ma_rma(src, length), ma_wma(src, length), ma_vwma(src, length), ma_hma(src, length), and ma_swma(src).
Two behaviors worth knowing before you use them:
SWMA takes no length. Pine's ta.swma applies a fixed symmetrical weighting over 4 bars. The wrapper accepts src only. If you route through get_ma with MaType.SWMA, the length argument is accepted for signature consistency but ignored. The window is always 4.
get_ma dispatcher
Accepts a MaType value and routes to the correct wrapper. If an unrecognized value reaches the switch, it falls back to SMA as a safety net.
Examples
Direct wrapper call
When you only need one moving average type and don't need a dropdown:
import AxiomCharts/AxiomMovingAverageLibrary/1 as maLib
smoothed = maLib.ma_ema(close, 20)
For a single MA type in a single script, a direct ta.ema(close, 20) is simpler and carries no dependency. The library earns its keep when you need the shared enum or when multiple scripts need to stay in sync.
User-selectable dropdown
The most common pattern — let users pick the MA type from a settings menu:
import AxiomCharts/AxiomMovingAverageLibrary/1 as maLib
maChoice = input.enum(maLib.MaType.EMA, title = "MA Type")
maLength = input.int(20, title = "MA Length", minval = 1)
maValue = maLib.get_ma(maChoice, close, maLength)
Watch for: VWMA on symbols without volume
ta.vwma requires volume data. On symbols that don't report volume — some forex feeds, certain indices — the result is na. The library does not guard against this. If your script includes VWMA as an option, handle the no-volume case in your own code.
FAQ
What's the difference between Lite and Pro?
Lite covers eight standard moving averages. Each one wraps a Pine built-in — no custom math involved. The Pro library adds thirteen additional types on top of those eight, including DEMA, TEMA, KAMA, JMA, FRAMA, T3MA, VAMA, ZLMA, ZLEMA, Laguerre, and McGinley variants. If your needs outgrow the standard eight, that's when Pro becomes relevant.
Why doesn't SWMA accept a length?
That's a Pine constraint. ta.swma applies a fixed symmetrical weighting across 4 bars. There is no length parameter to pass, so the wrapper doesn't accept one either. If you route through get_ma with MaType.SWMA, the length argument is there for API consistency but doesn't affect the output.
Can I use VWMA on any symbol?
Only on symbols that report volume data. On instruments without volume, VWMA returns na. The library won't catch that for you — if your script offers VWMA, check for volume data and handle the na case in your own code.
What Pine version do I need?
Pine v6. The library uses v6 enum syntax, so scripts on v5 or earlier cannot import it.
Limitations
Pine v6 required. Scripts on earlier versions cannot import this library.
Eight standard types only. Adaptive averages (KAMA, JMA, FRAMA), lag-compensated filters (T3MA, ZLMA, McGinley), and other specialized types are not included. The Pro library covers those.
SWMA uses a fixed 4-bar window. The length parameter passed through get_ma is ignored for SWMA.
VWMA needs volume data. On symbols without volume, it returns na. Your script should account for this.
The SMA fallback is a safety net, not a feature. If an unrecognized value reaches get_ma, it defaults to SMA. In practice, Pine's enum type system prevents this at compile time. Don't build routing logic around it.
Versioning and release notes
Pin your import to a specific version number you have actually verified in the environment where you are using the library:
import AxiomCharts/AxiomMovingAverageLibrary/
If you later need to move from Lite to Pro, expect changes: a different library title and an expanded MaType enum with additional values. It's not a drop-in swap — your code will need updating.
Support and training
Visit our website at axiomcharts.com for any documentation or questions.
Disclaimer
This library is published for educational and informational purposes. It provides standardized moving average computation utilities for Pine Script developers. It does not generate trading signals, recommend positions, or guarantee any financial outcome. All trading decisions and their consequences are yours. Use this library as one part of your own research and process. ライブラリ

ライブラリ

ライブラリ

ライブラリ

ライブラリ

ライブラリ

GB_JSON_LibLibrary "GB_JSON_Lib"
Alert payload string builders for GB-RMBP+ strategy.
N8N JSON entries/exits, Autoview key=value strings, PineConnector CSV.
n8n_entry_json(act, mode_lower, ticker, tf, price_now, lev, sug_lev, sl_price, liq_price, order_pct, tp1, tp1p, tp1a, tp2, tp2p, tp2a, tp3, tp3p, tp3a, tp4, tp4p, tp4a, tp5, tp5p, tp5a, tp6, tp6p, tp6a)
Build the N8N entry-side JSON payload, byte-identical to v1.0.77 output.
Parameters:
act (simple string) : "buy" or "sell"
mode_lower (simple string) : Execution mode in lowercase (stealth/hybrid/visible)
ticker (simple string) : syminfo.ticker
tf (simple string) : timeframe.period
price_now (float) : close
lev (float) : Final effective leverage used for the order
sug_lev (float) : Suggested leverage from risk-loss calculation
sl_price (float) : Stop-loss price (or 0 if none)
liq_price (float) : Calculated liquidation price
order_pct (float) : Order size as % of equity
tp1 (float)
tp1p (float)
tp1a (bool)
tp2 (float)
tp2p (float)
tp2a (bool)
tp3 (float)
tp3p (float)
tp3a (bool)
tp4 (float)
tp4p (float)
tp4a (bool)
tp5 (float)
tp5p (float)
tp5a (bool)
tp6 (float)
tp6p (float)
tp6a (bool)
Returns: JSON string
n8n_tp_exit_json(act, ticker, tp_idx, tp_pct, pos_size)
Build per-TP exit JSON payload.
Parameters:
act (simple string) : "closelong" or "closeshort"
ticker (simple string) : syminfo.ticker
tp_idx (int) : TP number 1..6
tp_pct (float) : Exit % for this TP
pos_size (float) : math.abs(strategy.position_size)
Returns: JSON string
n8n_close_json(act, ticker)
Build a full-position close JSON payload.
Parameters:
act (simple string) : "closelong" or "closeshort"
ticker (simple string) : syminfo.ticker
Returns: JSON string
n8n_order_pct(qty, price, lev, equity)
Compute order size as percentage of equity.
Parameters:
qty (float) : Final order quantity
price (float) : Current close
lev (float) : Effective leverage
equity (float) : strategy.equity
Returns: Rounded percentage to 4 decimals
av_entry_str(user, side, exchange, lev, symbol, ccy, testing)
Build Autoview entry command string.
Uses Pine placeholder '{{strategy.order.contracts}}' for the quantity.
Parameters:
user (simple string) : Acct identifier
side (simple string) : "long" or "short"
exchange (simple string) : Exchange name
lev (float) : Leverage value
symbol (simple string) : Symbol string
ccy (simple string) : "currency" or "contracts"
testing (simple string) : "" or " d=1"
Returns: Autoview-formatted command string
av_exit_str(user, side, exchange, symbol, ccy, testing, is_short)
Build Autoview exit command string. Short exits append "%" to qty per v1.0.77.
Parameters:
user (simple string) : Acct identifier
side (simple string) : "long" or "short"
exchange (simple string) : Exchange name
symbol (simple string) : Symbol string
ccy (simple string) : "currency" or "contracts"
testing (simple string) : "" or " d=1"
is_short (simple bool) : True if this is a short exit (appends "%")
Returns: Autoview-formatted command string
pc_alert_str(licence_id, symbol)
Build PineConnector CSV alert payload.
Uses Pine placeholders for action and contracts.
Parameters:
licence_id (int) : Numeric license ID
symbol (simple string) : Symbol with optional suffix (e.g. "EURUSD.a")
Returns: CSV-formatted command string ライブラリ

GB_Cond_LibLibrary "GB_Cond_Lib"
Condition operator evaluator + AND/OR combiner for GB-RMBP+ strategy.
Replaces 12-branch ternary chains and the 50-branch combiner used for external filter rules.
eval_cond_op(v1, op, v2)
Evaluate a binary condition between two series given an operator string.
Parameters:
v1 (float) : Left-hand series
op (simple string) : Operator: "CrossUp", "CrossDown", ">", ">=", "<", "<=", "==",
"> Previous", ">= Previous", "< Previous", "<= Previous", "== Previous"
v2 (float) : Right-hand series
Returns: Boolean result; false if op is unrecognized (including "🚫 None")
eval_cond_op_with_default(v1, op, v2, default_true)
Same as eval_cond_op, but if op is unrecognized returns `default_true`
(preserves the v1.0.77 quirk for LCond5/SCond5 which used `(make_custom ? true : true)` fallback).
Parameters:
v1 (float) : Left-hand series
op (simple string) : Operator string
v2 (float) : Right-hand series
default_true (bool) : Value returned when op is "🚫 None" or unknown
combine_AND(u1, u2, u3, u4, u5, c1, c2, c3, c4, c5, make_custom)
Combine 5 condition booleans with AND, gated by 5 "use" flags.
Matches v1.0.77 condition_function_AND exactly: if no flags are checked,
returns (make_custom ? false : true) — the strategy's "no filters = pass" default.
Parameters:
u1 (simple bool)
u2 (simple bool)
u3 (simple bool)
u4 (simple bool)
u5 (simple bool)
c1 (bool)
c2 (bool)
c3 (bool)
c4 (bool)
c5 (bool)
make_custom (simple bool) : The make_custom strategy flag
Returns: Combined boolean
combine_OR(u1, u2, u3, u4, u5, c1, c2, c3, c4, c5, make_custom)
Combine 5 condition booleans with OR, gated by 5 "use" flags.
Matches v1.0.77 condition_function_OR exactly.
Parameters:
u1 (simple bool)
u2 (simple bool)
u3 (simple bool)
u4 (simple bool)
u5 (simple bool)
c1 (bool)
c2 (bool)
c3 (bool)
c4 (bool)
c5 (bool)
make_custom (simple bool) ライブラリ

GB_MA_LibLibrary "GB_MA_Lib"
Moving Average bank + timeframe helper for GB-RMBP+ strategy.
22 MA implementations as standalone pure functions, plus htf_for_period.
Functions are lazy: only the one you call actually computes.
calc_sma(src, len)
Simple Moving Average
Parameters:
src (simple float) : Source series
len (simple int) : Length
Returns: SMA series
calc_ema(src, len)
Exponential Moving Average
Parameters:
src (simple float)
len (simple int)
calc_hma(src, len)
Hull Moving Average
Parameters:
src (simple float)
len (simple int)
calc_wma(src, len)
Weighted Moving Average
Parameters:
src (simple float)
len (simple int)
calc_vwma(src, len)
Volume Weighted Moving Average
Parameters:
src (simple float)
len (simple int)
calc_rma(src, len)
Wilder/Running Moving Average
Parameters:
src (simple float)
len (simple int)
calc_alma(src, len)
Arnaud Legoux Moving Average
Parameters:
src (simple float)
len (simple int)
calc_swma(src)
Symmetrically-Weighted Moving Average (length fixed by Pine)
Parameters:
src (simple float)
calc_dema(src, len)
Double Exponential Moving Average
Parameters:
src (simple float)
len (simple int)
calc_tema(src, len)
Triple Exponential Moving Average
Parameters:
src (simple float)
len (simple int)
calc_zema(src, len)
Zero-lag EMA variant (EMA1 + difference)
Parameters:
src (simple float)
len (simple int)
calc_zlema(src, len)
Zero-Lag EMA
Parameters:
src (simple float)
len (simple int)
calc_trama(src, len)
TRAMA (Trend-Regularity Adaptive MA, Lux Algo)
Parameters:
src (simple float)
len (simple int)
calc_pkama(src, len)
P-KAMA (Power-Kaufman Adaptive MA)
Parameters:
src (simple float)
len (simple int)
calc_t3(src, len)
T3 Moving Average
Parameters:
src (simple float)
len (simple int)
calc_tma(src, len)
Triangular Moving Average
Parameters:
src (simple float)
len (simple int)
calc_var(src, len)
VAR (Variable Index Dynamic MA-like)
Parameters:
src (simple float)
len (simple int)
calc_tsf(src, len)
Time Series Forecast
Parameters:
src (simple float)
len (simple int)
calc_zlsma(src, len)
Zero-Lag Least-Squares Moving Average
Parameters:
src (simple float)
len (simple int)
calc_mcginley(src, len)
McGinley Dynamic
Parameters:
src (simple float)
len (simple int)
calc_zldema(src, len)
Zero-Lag DEMA
Parameters:
src (simple float)
len (simple int)
calc_zltema(src, len)
Zero-Lag TEMA
Parameters:
src (simple float)
len (simple int)
htf_for_period(tf)
Maps chart timeframe to a higher timeframe string (used for HTF MA bias).
Parameters:
tf (simple string) : Current timeframe.period
Returns: HTF string for request.security ライブラリ

CyberCausalityLib# CyberCausalityLib v17
CyberCausalityLib provides information-theoretic and econometric causality detection for identifying directional influence between price series, filtering spurious correlations, and detecting lead-lag relationships across assets.
## What it does
Delivers 15+ causality functions in three categories: Transfer Entropy (information-theoretic directional causality), Granger Causality (econometric lagged correlation), and PCMCI filtering (partial correlation mediation for spurious causality detection). Answers questions like "Does Bitcoin volume predict Ethereum price?" and "Is Asset A→B correlation direct or mediated by Asset C?"
Outputs causality scores, directional indicators, and optimal lag values for multi-basket aggregation, lead-lag pair trading, and filtering false correlations driven by common factors.
## How it works
Transfer Entropy measures directional information flow: `TE(X→Y) = H(Y_t | Y_{t-1}) - H(Y_t | Y_{t-1}, X_{t-lag})` using Shannon entropy. Discretizes price data into 4-8 bins, calculates joint/conditional entropies. Higher TE = X predicts future Y beyond Y's own history.
Granger Causality aggregates lagged correlations: `Granger = Σ(w_i × corr(Y_t, X_{t-i}))` with weights `w_i = |corr_i| / Σ|corr_j|`. Supports Pearson/Spearman/Kendall. Returns magnitude + directional coefficient.
PCMCI filtering detects spurious causality via partial correlation: `ρ(X,Y|Z)`. If partial << raw correlation, Z mediates X→Y (indirect causality). Reduces score proportionally.
## Why this is original
First TradingView library with information-theoretic causality. Pine has no native entropy, Granger tests, or partial correlation. Existing libraries offer only basic correlation without directionality or lag optimization.
Unique features:
- Transfer Entropy with Shannon entropy discretization
- Granger Causality with auto-lag search (1-10)
- PCMCI filtering (up to 4 mediators)
- Ensemble aggregation (5 baskets)
- Möbius transformation state tracking
No other Pine library combines information theory, econometrics, and graph-based causality with NA guards and graceful degradation.
## How to use it
```pine
//@version=6
indicator("CyberCausalityLib Demo", overlay=false)
import cybermediaboy/CyberCausalityLib/17 as C
import cybermediaboy/NumLib/4 as N
// Transfer Entropy: Does volume predict price?
var price_buf = array.new()
var vol_buf = array.new()
if bar_index >= 99
array.clear(price_buf)
array.clear(vol_buf)
for i = 0 to 99
array.push(price_buf, close )
array.push(vol_buf, volume )
= C.f_calculate_te_score_v2(
price_buf, vol_buf, 100, 5, 2
)
// te_score > 0.15 → volume predicts price
plot(te_score, "TE Score", color.blue)
// Granger Causality: Lead-lag detection
var x_buf = array.new()
var y_buf = array.new()
// ...populate buffers...
= C.f_calculate_granger_score(
y_buf, x_buf, 100, 5, "Pearson"
)
// granger > 0.3 → X Granger-causes Y
// PCMCI Filtering: Remove spurious correlation
= C.f_calculate_granger_score(y_buf, x_buf, 100, 5, "Pearson")
filtered = C.f_pcmci_filter_score(
raw, y_buf, x_buf, mediator_buf,
array.new(), array.new(), array.new(), 100
)
// filtered << raw → indirect causality
```
## Key functions
- `f_calculate_te_score_v2()` - Transfer Entropy (recommended)
- `f_calculate_granger_score()` - Granger Causality with lag search
- `f_pcmci_filter_score()` - Spurious correlation filtering
- `f_compute_te_ensemble()` - Multi-basket aggregation
- `f_shannon_entropy()` - Shannon entropy calculation
- `MobiusState` UDT - Non-linear state tracking
## Dependencies
Requires NumLib v4 for correlation functions (Pearson/Spearman/Kendall).
```pine
import cybermediaboy/CyberCausalityLib/17 as C
import cybermediaboy/NumLib/4 as N
```
## Version history
- **v17** (2026-04-17): Added HAR-RV forecast, Durbin-Watson autocorrelation test, PCA explained variance, improved entropy discretization (v2 algorithm)
- **v16** (2026-03-xx): Added PCMCI filtering, Möbius state tracking UDT
- **v15** (2026-02-xx): Added Granger causality, multi-lag search, correlation at lag
- **v14** (2026-01-xx): Initial release with Transfer Entropy, ensemble aggregation
## License
Mozilla Public License 2.0
## Author
© cybermediaboy
## Support
For questions, bug reports, or feature requests, comment on the library publication page or reference the source code documentation.
ライブラリ
