Library

Library

KLP_Telemetry_LibLibrary "KLP_Telemetry_Lib"
build_payload(sym, tf, dir, fam, sub, bt, loc, ichi_st, ichi_wr, vwap_c, lvn_p, ilvn, hvn_p, sb, wick_p, body_p, close_l, dist_kl, dist_vw, entry, stop, tp1, tp2, rticks, qtag, ts_ms, acct, zdz, zsz, qlvl, shlb, spmx, a5tk, sess_src, active_sess, family_name, manual_sess, auto_switched, stop_meth, atr15tk, atr2tk, atr25tk, sw_stop_tk, vol_reg, tp_cnt, be_rule, raw_conf, kl_match_count, kl_match_names_json, vwap_aligned, poc_magnet, poc_dist_r_x100, ichi_at_break, hvn_break_thru, cont_path, zone_exempt_used)
Parameters:
sym (string)
tf (string)
dir (int)
fam (string)
sub (string)
bt (int)
loc (string)
ichi_st (string)
ichi_wr (float)
vwap_c (bool)
lvn_p (bool)
ilvn (bool)
hvn_p (bool)
sb (bool)
wick_p (float)
body_p (float)
close_l (float)
dist_kl (float)
dist_vw (float)
entry (float)
stop (float)
tp1 (float)
tp2 (float)
rticks (int)
qtag (string)
ts_ms (int)
acct (string)
zdz (bool)
zsz (bool)
qlvl (int)
shlb (int)
spmx (int)
a5tk (int)
sess_src (string)
active_sess (string)
family_name (string)
manual_sess (string)
auto_switched (int)
stop_meth (string)
atr15tk (int)
atr2tk (int)
atr25tk (int)
sw_stop_tk (int)
vol_reg (int)
tp_cnt (int)
be_rule (string)
raw_conf (int)
kl_match_count (int)
kl_match_names_json (string)
vwap_aligned (bool)
poc_magnet (bool)
poc_dist_r_x100 (int)
ichi_at_break (bool)
hvn_break_thru (bool)
cont_path (string)
zone_exempt_used (bool) Library

EKGapEngineLibrary "EKGapEngine"
Gap engine library: NWOG (New Week Opening Gaps), NDOG (New Day Opening Gaps),
9:30 NY Opening Range Gap, and PXH/L (Previous X High/Low) levels.
Extracted from qt-pro-enigma.pine to avoid PulseWire compiler timeouts.
GAP_VOID_BULL()
Gap type constant: Void Bullish
Returns: 1
GAP_VOID_BEAR()
Gap type constant: Void Bearish
Returns: 2
GAP_OVERLAP_BULL()
Gap type constant: Overlap Bullish
Returns: 3
GAP_OVERLAP_BEAR()
Gap type constant: Overlap Bearish
Returns: 4
getLineStyle(styleStr)
Convert a style string to a line style constant
Parameters:
styleStr (string) : Style string ("Solid", "Dashed", "Dotted")
Returns: line.style_solid, line.style_dashed, or line.style_dotted
getLabelSize(labelSize)
Convert a label size string to a size constant
Parameters:
labelSize (string) : Label size string ("Tiny", "Small", "Normal", "Large")
Returns: size.tiny, size.small, size.normal, or size.large
calcTradingDaysAgo(creationTimestamp)
Calculate approximate trading days since a timestamp
Parameters:
creationTimestamp (int) : The creation timestamp to measure from
Returns: Approximate number of trading days elapsed
getNwogSubtypeName(gapType)
Get the human-readable name for an NWOG gap subtype
Parameters:
gapType (int) : Gap type constant (1-4)
Returns: String name of the gap subtype
buildNwogLabelText(gapType, daysAgo, labelStyle)
Build label text for an NWOG
Parameters:
gapType (int) : Gap type constant (1-4)
daysAgo (int) : Number of trading days ago the gap was created
labelStyle (string) : Label style ("Simple" or "Descriptive")
Returns: Formatted label text string
buildNdogLabelText(isBullish, daysAgo, labelStyle)
Build label text for an NDOG
Parameters:
isBullish (bool) : Whether the gap is bullish
daysAgo (int) : Number of trading days ago the gap was created
labelStyle (string) : Label style ("Simple" or "Descriptive")
Returns: Formatted label text string
getGapColors(nwogColor, boxFillTransp, boxBorderTransp, midLineColor, quadLineColor)
Compute fill, border, mid, and quad colors for an NWOG
Parameters:
nwogColor (color) : Base NWOG color
boxFillTransp (int) : Box fill transparency (0-100)
boxBorderTransp (int) : Box border transparency (0-100)
midLineColor (color) : Midline color
quadLineColor (color) : Quadrant line color
Returns: Tuple of
getNdogColors(ndogColor, boxFillTransp, boxBorderTransp, midLineColor, quadLineColor)
Compute fill, border, mid, and quad colors for an NDOG
Parameters:
ndogColor (color) : Base NDOG color
boxFillTransp (int) : Box fill transparency (0-100)
boxBorderTransp (int) : Box border transparency (0-100)
midLineColor (color) : Midline color
quadLineColor (color) : Quadrant line color
Returns: Tuple of
classifyGap(friClose, friOpen, monOpen)
Classify a weekend gap as Void Bull/Bear or Overlap Bull/Bear
Parameters:
friClose (float) : Friday close price
friOpen (float) : Friday open price
monOpen (float) : Monday open price
Returns: Gap type constant (0 if no gap)
passesAtrFilter(gapSize, atr, multiplier)
Check if a gap passes the ATR size filter
Parameters:
gapSize (float) : Absolute size of the gap
atr (float) : Current ATR value
multiplier (float) : ATR multiplier threshold
Returns: true if the gap passes the filter
isWithinPriceDistance(topPrice, bottomPrice, currentPrice, atr, onlyShowNearPrice, maxDistanceAtr)
Check if a gap is within the max price distance
Parameters:
topPrice (float) : Top of gap zone
bottomPrice (float) : Bottom of gap zone
currentPrice (float) : Current price (close)
atr (float) : Current ATR value
onlyShowNearPrice (bool) : Whether the near-price filter is enabled
maxDistanceAtr (float) : Maximum distance in ATR multiples
Returns: true if within distance (or filter is disabled)
shouldDisplayGapType(gapType, showVoidGaps, showOverlapGaps)
Check if a gap type should be displayed based on settings
Parameters:
gapType (int) : Gap type constant (1-4)
showVoidGaps (bool) : Whether void gaps are enabled
showOverlapGaps (bool) : Whether overlap gaps are enabled
Returns: true if this gap type should be shown
createNwog(nwogArray, cfg, friClose, friOpen, monOpen, atrVal, fridayBarIdx)
Create a new NWOG and add it to the array, removing oldest if over max count
Parameters:
nwogArray (array) : Array of NWOGBox objects
cfg (GapConfig) : GapConfig with all settings
friClose (float) : Friday close price
friOpen (float) : Friday open price
monOpen (float) : Monday open price
atrVal (float) : Current ATR value for size filtering
fridayBarIdx (int) : Bar index of Friday (for left edge of box)
createNdog(ndogArray, cfg, prevClose, todayOpn, atrVal, prevDayBarIdx)
Create a new NDOG and add it to the array, removing oldest if over max count
Parameters:
ndogArray (array) : Array of NDOGBox objects
cfg (GapConfig) : GapConfig with all settings
prevClose (float) : Previous day close price
todayOpn (float) : Today open price
atrVal (float) : Current ATR value for size filtering
prevDayBarIdx (int) : Bar index of previous day (for left edge of box)
updateNwogExtensions(nwogArray, cfg, dailyAtr, shouldRunCleanup)
Update all NWOG box/line/label extensions and handle cleanup
Parameters:
nwogArray (array) : Array of NWOGBox objects
cfg (GapConfig) : GapConfig with all settings
dailyAtr (float) : Current daily ATR value for distance filtering
shouldRunCleanup (bool) : Whether cleanup should run this bar (based on interval)
updateNdogExtensions(ndogArray, cfg, dailyAtr, shouldRunCleanup)
Update all NDOG box/line/label extensions and handle cleanup
Parameters:
ndogArray (array) : Array of NDOGBox objects
cfg (GapConfig) : GapConfig with all settings
dailyAtr (float) : Current daily ATR value for distance filtering
shouldRunCleanup (bool) : Whether cleanup should run this bar (based on interval)
markWeekEndForNwogs(nwogArray, isWeekCloseRisingEdge)
Mark week end for all active NWOGs when week close rising edge detected
Parameters:
nwogArray (array) : Array of NWOGBox objects
isWeekCloseRisingEdge (bool) : Whether the week close rising edge was detected this bar
markDayEndForNdogs(ndogArray, isNewTradingDay)
Mark day end for all active NDOGs when new trading day detected
Parameters:
ndogArray (array) : Array of NDOGBox objects
isNewTradingDay (bool) : Whether a new trading day started this bar
f_get_size(s)
Convert a size string to a size constant
Parameters:
s (string) : Size string ("Auto", "Tiny", "Small", "Normal", "Large")
Returns: Corresponding size constant
f_get_pxhl_style(str)
Convert a style string to a line style constant (PXH/L version)
Parameters:
str (string) : Style string ("Solid", "Dotted", "Dashed")
Returns: Corresponding line style constant
f_is_within_distance(target_price, filter_enabled, daily_atr, filter_preset)
Check if a target price is within distance filter range
Parameters:
target_price (float) : The price to check
filter_enabled (bool) : Whether the distance filter is enabled
daily_atr (float) : Current daily ATR value
filter_preset (string) : Filter preset string ("Really Close", "Balanced", "Slightly Far")
Returns: true if within distance (or filter disabled)
f_find_exact_in_window(target_price, p_start, p_end, is_high)
Find the exact bar time where a high/low occurred within a period window
Parameters:
target_price (float) : The price to find
p_start (int) : Period start time
p_end (int) : Period end time
is_high (bool) : Whether looking for a high (true) or low (false)
Returns: Timestamp of the exact bar where the price was found
f_add_level_smart(arr, h, l, t_start, t_end, count)
Smart-add high/low levels to an array, maintaining count limit
Parameters:
arr (array) : Array of Level objects
h (float) : High price to add
l (float) : Low price to add
t_start (int) : Period start time
t_end (int) : Period end time
count (int) : Maximum number of level pairs
f_check_mitigation(arr)
Check mitigation of levels in an array (price broke through)
Parameters:
arr (array) : Array of Level objects to check
f_draw_single_level(draw_lines, draw_labels, t_start, t_end, price, txt, col, sty, show_lbl, size_val, font_val, filter_enabled, daily_atr, filter_preset)
Draw a single PXH/L level line and optional label
Parameters:
draw_lines (array) : Array to store created line objects
draw_labels (array) : Array to store created label objects
t_start (int) : Start time for the line
t_end (int) : End time for the line
price (float) : Price level
txt (string) : Label text
col (color) : Line/label color
sty (string) : Line style constant
show_lbl (bool) : Whether to show the label
size_val (string) : Label size constant
font_val (string) : Font family constant
filter_enabled (bool) : Whether distance filter is enabled
daily_atr (float) : Current daily ATR
filter_preset (string) : Distance filter preset string
f_clear_drawings(draw_lines, draw_labels)
Clear all PXH/L drawing objects (lines and labels)
Parameters:
draw_lines (array) : Array of line objects to delete
draw_labels (array) : Array of label objects to delete
f_draw_levels(arr, show, mode, show_lbl, col, sty_global, txt_base, txt_size_val, font_val, draw_lines, draw_labels, filter_enabled, daily_atr, filter_preset)
Draw all levels from a PXH/L level array with EQ/Quadrant support
Parameters:
arr (array) : Array of Level objects
show (bool) : Whether to show this timeframe's levels
mode (string) : Midline mode ("None", "EQ", "Quadrants")
show_lbl (bool) : Whether to show labels
col (color) : Level color
sty_global (string) : Global style string ("Solid", "Dotted", "Dashed")
txt_base (string) : Base text for labels (e.g. "pD", "pW", "pM")
txt_size_val (string) : Label size string
font_val (string) : Font family constant
draw_lines (array) : Array to store created line objects
draw_labels (array) : Array to store created label objects
filter_enabled (bool) : Whether distance filter is enabled
daily_atr (float) : Current daily ATR
filter_preset (string) : Distance filter preset string
process_930_gap(cfg930, m1_time, m1_open, m1_close, g930_prevClosePrice, g930_boxArray, g930_lineArray, isStock, isValidTimeframe930)
Process 9:30 NY opening range gap from 1-minute lower timeframe data.
Handles the entire gap creation logic: detects the 16:14 (or 15:59 for stocks) close,
then at 9:30 creates box/midline/quadrant drawings.
Parameters:
cfg930 (Gap930Config) : Gap930Config with all 9:30 gap settings
m1_time (array) : Array of 1-minute bar timestamps from request.security_lower_tf
m1_open (array) : Array of 1-minute bar open prices from request.security_lower_tf
m1_close (array) : Array of 1-minute bar close prices from request.security_lower_tf
g930_prevClosePrice (float) : Previous close price state (pass in, returns updated value)
g930_boxArray (array) : Array to store created box objects
g930_lineArray (array) : Array to store created line objects
isStock (bool) : Whether the symbol is a stock/fund/dr
isValidTimeframe930 (bool) : Whether the current timeframe is valid for 9:30 gaps (intraday <= 15min)
Returns: Updated g930_prevClosePrice value
NWOGBox
New Week Opening Gap box with all price levels and drawing references
Fields:
gapType (series int) : Gap classification (1=Void Bull, 2=Void Bear, 3=Overlap Bull, 4=Overlap Bear)
fridayClose (series float) : Friday close price
fridayOpen (series float) : Friday open price
mondayOpen (series float) : Monday open price
topPrice (series float) : Top of gap zone
bottomPrice (series float) : Bottom of gap zone
midPrice (series float) : Midpoint of gap zone
upperQuad (series float) : Upper quadrant (75%) of gap zone
lowerQuad (series float) : Lower quadrant (25%) of gap zone
gapSize (series float) : Absolute size of gap
startBar (series int) : Bar index where gap starts
creationTime (series int) : Timestamp of gap creation
weekEndBar (series int) : Bar index where the week ended
weekEnded (series bool) : Whether the week has ended for this NWOG
nwogBox (series box) : Box drawing object
midLine (series line) : Midline drawing object
q3Line (series line) : Upper quadrant line drawing object
q1Line (series line) : Lower quadrant line drawing object
infoLabel (series label) : Label drawing object
isActive (series bool) : Whether this NWOG is still active
NDOGBox
New Day Opening Gap box with all price levels and drawing references
Fields:
isBullish (series bool) : Whether the gap opened bullish (today open > prev close)
prevClose (series float) : Previous day close price
todayOpen (series float) : Today open price
topPrice (series float) : Top of gap zone
bottomPrice (series float) : Bottom of gap zone
midPrice (series float) : Midpoint of gap zone
upperQuad (series float) : Upper quadrant (75%) of gap zone
lowerQuad (series float) : Lower quadrant (25%) of gap zone
gapSize (series float) : Absolute size of gap
startBar (series int) : Bar index where gap starts
creationTime (series int) : Timestamp of gap creation
dayEndBar (series int) : Bar index where the day ended
dayEnded (series bool) : Whether the day has ended for this NDOG
ndogBox (series box) : Box drawing object
midLine (series line) : Midline drawing object
q3Line (series line) : Upper quadrant line drawing object
q1Line (series line) : Lower quadrant line drawing object
infoLabel (series label) : Label drawing object
isActive (series bool) : Whether this NDOG is still active
Level
PXH/L level with price, time range, and mitigation state
Fields:
price (series float) : The price level
start_time (series int) : Timestamp where the level starts
is_high (series bool) : Whether this is a high (true) or low (false)
broken (series bool) : Whether the level has been mitigated
stop_time (series int) : Timestamp where the level was mitigated
GapConfig
Configuration for NWOG/NDOG gap display and filtering
Fields:
showNwogs (series bool) : Enable NWOGs
showVoidGaps (series bool) : Show void gap types
showOverlapGaps (series bool) : Show overlap gap types
showNwogLabels (series bool) : Show NWOG labels
extensionMode (series string) : NWOG extension mode ("Extend Live" or "Extend to Week Close")
maxNwogCount (series int) : Maximum number of NWOGs to display
showNdogs (series bool) : Enable NDOGs
showNdogLabels (series bool) : Show NDOG labels
ndogExtensionMode (series string) : NDOG extension mode ("Extend Live" or "Extend to Day Close")
maxNdogCount (series int) : Maximum number of NDOGs to display
force1800 (series bool) : Force 18:00 open for NDOG calculation
customOpenSession (series string) : Session string for custom open time
nwogColor (series color) : Base color for NWOGs
ndogColor (series color) : Base color for NDOGs
boxFillTransp (series int) : Box fill transparency
boxBorderTransp (series int) : Box border transparency
boxBorderWidth (series int) : Box border width
showMidline (series bool) : Show midline on gaps
showQuadrants (series bool) : Show quadrant lines on gaps
midLineColor (series color) : Midline color
quadLineColor (series color) : Quadrant line color
midLineStyle (series string) : Midline style string ("Solid", "Dotted", "Dashed")
quadLineStyle (series string) : Quadrant line style string ("Solid", "Dotted", "Dashed")
labelSize (series string) : Label size string ("Tiny", "Small", "Normal", "Large")
nwogTextColor (series color) : NWOG label text color
labelStyle (series string) : Label style ("Simple" or "Descriptive")
hideHistoryLabels (series bool) : Hide labels on historical gaps
atrMultiplier (series float) : Pre-computed ATR multiplier for NWOG size filter
ndogAtrMultiplier (series float) : Pre-computed ATR multiplier for NDOG size filter
maxDistanceAtr (series float) : Pre-computed max distance in ATR multiples
onlyShowNearPrice (series bool) : Only show gaps near current price
cleanupIntervalMs (series int) : Cleanup interval in milliseconds (0 = immediate)
barOffset (series int) : Bar offset for right edge of drawings
PXHLConfig
Configuration for PXH/L (Previous X High/Low) display
Fields:
global_sty (series string) : Global line style ("Solid", "Dotted", "Dashed")
lbl_size_str (series string) : Label size string ("Auto", "Tiny", "Small", "Normal", "Large")
use_mono (series bool) : Use monospace font for labels
filter_enabled (series bool) : Enable distance filter
filter_preset (series string) : Distance filter preset ("Really Close", "Balanced", "Slightly Far")
filter_atr_len (series int) : ATR length for distance filter
show_d (series bool) : Show daily levels
show_w (series bool) : Show weekly levels
show_m (series bool) : Show monthly levels
col_d (series color) : Daily level color
col_w (series color) : Weekly level color
col_m (series color) : Monthly level color
cnt_d (series int) : Daily level count
cnt_w (series int) : Weekly level count
cnt_m (series int) : Monthly level count
mode_d (series string) : Daily midline mode ("None", "EQ", "Quadrants")
mode_w (series string) : Weekly midline mode ("None", "EQ", "Quadrants")
mode_m (series string) : Monthly midline mode ("None", "EQ", "Quadrants")
show_lbl_d (series bool) : Show daily labels
show_lbl_w (series bool) : Show weekly labels
show_lbl_m (series bool) : Show monthly labels
Gap930Config
Configuration for 9:30 NY Opening Range Gap
Fields:
g930_historyCount (series int) : Number of historical 9:30 gaps to show
g930_projEndH (series int) : End hour for gap projection (NY time)
g930_projEndM (series int) : End minute for gap projection (NY time)
g930_showBox (series bool) : Show gap box
g930_boxColor (series color) : Gap box color
g930_showMid (series bool) : Show midline
g930_midColor (series color) : Midline color
g930_midStyleStr (series string) : Midline style string ("Solid", "Dashed", "Dotted")
g930_showQuad (series bool) : Show quadrant lines
g930_quadColor (series color) : Quadrant line color
g930_quadStyleStr (series string) : Quadrant line style string ("Solid", "Dashed", "Dotted") Library

EKTrueOpensLibrary "EKTrueOpens"
True Opens library: calculation, drawing, history management, and price tracking table
for opening prices at multiple timeframes (yearly, quarterly, monthly, weekly, daily, session, 90-minute).
Extracted from qt-ultimate-enigma.pine lines 1951-2597.
to_tf_to_min(tf)
Converts a timeframe string to minutes
Parameters:
tf (string) : Timeframe string (e.g. "1", "60", "D", "W")
Returns: Float value in minutes
to_is_visible(min_s, max_s)
Checks if current chart timeframe is within the given min/max range
Parameters:
min_s (string) : Minimum timeframe string
max_s (string) : Maximum timeframe string
Returns: True if current timeframe is within range
to_get_style_const(s)
Converts a style name string to a line style constant
Parameters:
s (string) : Style name: "Solid", "Dashed", or "Dotted"
Returns: line.style_* constant
to_get_active_style(cfg)
Returns the line style for active (current) True Open lines
Parameters:
cfg (TOConfig) : TOConfig with style_mode and custom_style settings
Returns: line.style_* constant
to_get_sess_end(start_time)
Calculates the hard session end time for a given start time
Parameters:
start_time (int) : Bar time of the session start
Returns: Timestamp of the session end (6-hour boundaries in NY time)
to_enforce_limit(arr, allow_hist, hist_count)
Enforces the history limit on a TO_Level array, deleting excess old lines/labels
Parameters:
arr (array) : The array of TO_Level objects
allow_hist (bool) : Whether history is enabled for this timeframe
hist_count (int) : Maximum number of historical levels to keep
to_force_close_period(arr, allow_hist, cfg)
Force-closes the current active period in an array (used at timeframe boundaries)
Parameters:
arr (array) : The array of TO_Level objects
allow_hist (bool) : Whether history is enabled for this timeframe
cfg (TOConfig) : TOConfig with style settings
to_manage_history(arr, p, start_time, txt, col, allow_hist, use_hard_end, custom_end, cfg)
Closes the previous active level and creates a new one for the new period
Parameters:
arr (array) : The array of TO_Level objects
p (float) : The opening price for the new period
start_time (int) : Bar time of the new period start
txt (string) : Label text for the new level
col (color) : Color for the new level
allow_hist (bool) : Whether history is enabled for this timeframe
use_hard_end (bool) : Whether to calculate a hard session end time
custom_end (int) : Custom end time (0 = none, overrides hard end calc)
cfg (TOConfig) : TOConfig with style, font, and text size settings
to_maintain_lines(arr, is_vis, is_time_label_mode, allow_hist, cfg)
Updates line extensions, visibility, colors, and label text for all levels in an array
Parameters:
arr (array) : The array of TO_Level objects
is_vis (bool) : Whether this timeframe is visible at current chart resolution
is_time_label_mode (bool) : Whether labels should show time instead of name (for sessions/90m)
allow_hist (bool) : Whether history is enabled for this timeframe
cfg (TOConfig) : TOConfig with offset, session label mode, and font settings
to_calc_yr_func()
Calculates the True Yearly Open (April open per ICT/Daye methodology)
Returns: Tuple
to_calc_qt_func()
Calculates the True Quarterly Open (4th Sunday of quarter-start month)
Returns: Tuple
to_calc_mn_func(t_hour)
Calculates the True Monthly Open (2nd week Sunday at trigger hour)
Parameters:
t_hour (int) : The trigger hour in NY time (typically 18)
Returns: Tuple
to_calc_wk_func(t_hour)
Calculates the True Weekly Open (Monday at trigger hour)
Parameters:
t_hour (int) : The trigger hour in NY time (typically 18)
Returns: Tuple
to_calc_dy_func()
Calculates the True Daily Open (midnight NY time)
Returns: Tuple
to_calc_session_func(t_h, t_m)
Calculates a True Session Open at the given hour:minute in NY time
Parameters:
t_h (int) : Session start hour (NY time)
t_m (int) : Session start minute (NY time)
Returns: Tuple
to_calc_90m_func()
Calculates the True 90-Minute Open (:23/:53 cycle boundaries)
Returns: Tuple
to_is_current_period(trigger_time, type)
Checks if a trigger time falls within the current period of the given type
Parameters:
trigger_time (int) : The bar time when the True Open was triggered
type (string) : Period type: "D", "W", "M", "Q", "Y", "SESS", or "90M"
Returns: True if the trigger time is within the current period
to_get_status(lvl_price, trig_t, period_type, c_tbl_none, c_tbl_above, c_tbl_below)
Gets the status text and color for a single True Open level vs current close
Parameters:
lvl_price (float) : The True Open price
trig_t (int) : The trigger time for the True Open
period_type (string) : Period type string for is_current_period check
c_tbl_none (color) : Color for "Not Open" state
c_tbl_above (color) : Color for "Above" state
c_tbl_below (color) : Color for "Below" state
Returns: Tuple
to_get_array_status(arr, label_name, c_tbl_none, c_tbl_above, c_tbl_below)
Gets the status for an array-based True Open (sessions, 90m) including label text
Parameters:
arr (array) : The array of TO_Level objects
label_name (string) : Display name for the table row (e.g. "Session", "90-Min")
c_tbl_none (color) : Color for "Not Open" state
c_tbl_above (color) : Color for "Above" state
c_tbl_below (color) : Color for "Below" state
Returns: Tuple
to_render_table(tbl_cfg, to_tbl, to_arr_sess, to_arr_90m, to_yr_p, to_yr_t, to_qt_p, to_qt_t, to_mn_p, to_mn_t, to_wk_p, to_wk_t, to_dy_p, to_dy_t)
Renders the True Opens price tracking table with all timeframe rows
Parameters:
tbl_cfg (TOTableConfig) : TOTableConfig with all table display settings
to_tbl (table) : The pre-created table object
to_arr_sess (array) : Session TO_Level array
to_arr_90m (array) : 90-minute TO_Level array
to_yr_p (float) : Yearly True Open price (from request.security)
to_yr_t (int) : Yearly trigger time
to_qt_p (float) : Quarterly True Open price
to_qt_t (int) : Quarterly trigger time
to_mn_p (float) : Monthly True Open price
to_mn_t (int) : Monthly trigger time
to_wk_p (float) : Weekly True Open price
to_wk_t (int) : Weekly trigger time
to_dy_p (float) : Daily True Open price
to_dy_t (int) : Daily trigger time
TO_Level
Core level structure for a single True Open line/label pair
Fields:
l (series line) : The line object drawn on chart
lbl (series label) : The label object drawn on chart
price (series float) : The opening price value
active (series bool) : Whether this level is the current (still-extending) period
name (series string) : Display name for the label (e.g. "TYO", "AO", "90m")
c (series color) : The color assigned to this level
start_t (series int) : Bar time when this level started
end_t (series int) : Hard end time (0 = no hard end, extends until next period)
TOConfig
Configuration for True Opens general settings (replaces input.*() calls)
Fields:
to_style_mode (series string) : "Auto" or "Custom" line style mode
to_custom_style (series string) : "Solid", "Dashed", or "Dotted" when mode is Custom
to_hist_count_global (series int) : How many past lines to keep for selected timeframes
to_offset_val (series int) : Label offset in bars
to_textSize (series string) : Text size for chart labels
to_font_fam (series string) : Font family string (font.family_monospace or font.family_default)
to_sess_lbl_mode (series string) : "Name" or "Time" for session label display
TOTableConfig
Configuration for the True Opens price tracking table (replaces input.*() calls)
Fields:
to_show_table (series bool) : Whether to show the table at all
to_table_pos (series string) : Table position string (e.g. position.bottom_right)
to_table_txt_size (series string) : Table text size
to_tbl_show_90m (series bool) : Show 90-Min row
to_tbl_show_sess (series bool) : Show Session row
to_tbl_show_dy (series bool) : Show Daily row
to_tbl_show_wk (series bool) : Show Weekly row
to_tbl_show_mn (series bool) : Show Monthly row
to_tbl_show_qt (series bool) : Show Quarterly row
to_tbl_show_yr (series bool) : Show Yearly row
to_c_tbl_above (series color) : Color when price is above True Open
to_c_tbl_below (series color) : Color when price is below True Open
to_c_tbl_none (series color) : Color when period is not open
to_font_fam (series string) : Font family string for table cells Library

EKSSMTLibrary "EKSSMT"
SSMT (Smart Money Tool) detection engine library. Handles normal and hidden SMT detection,
QCISD level creation/management, PSP (Price Sync Pattern) calculation, multi-condition alert logic,
status bar color computation, and all session/quarter math.
Extracted from qt-ultimate-enigma.pine to avoid PulseWire compiler timeout.
init_qcisd_state()
Creates and returns an initialized QCISDState with empty arrays.
Returns: QCISDState with all arrays initialized
add_to_line_array(arr, value, limit)
Adds a line to a managed array, deleting the oldest if over the limit.
Parameters:
arr (array) : The line array to manage
value (line) : The new line to add
limit (int) : Maximum array size
add_to_label_array(arr, value, limit)
Adds a label to a managed array, deleting the oldest if over the limit.
Parameters:
arr (array) : The label array to manage
value (label) : The new label to add
limit (int) : Maximum array size
compute_sessions(t, tz, dayStartHour)
Computes all session and quarter values for the current bar.
Calculates micro, 90m, daily, weekly, monthly, quarterly, and yearly session indices,
plus change flags for each.
Parameters:
t (int) : The current bar time
tz (string) : Timezone string (e.g. "UTC-4")
dayStartHour (int) : Hour of day start in the given timezone (e.g. 18)
Returns: SessionState with all computed session/quarter values
f_main_process(_tf_ok, _val_ses, op, cls, hi, lo, ti)
Tracks H/L/close extremes per session period. Core price tracking for SSMT detection.
Parameters:
_tf_ok (bool) : Whether the current timeframe is within the valid range
_val_ses (int) : The current session index value
op (float) : Open price (chart or correlated asset)
cls (float) : Close price
hi (float) : High price
lo (float) : Low price
ti (int) : Time value
Returns: Tuple of 18 values:
f_ssmt(cfg, qcisd_state, ah2, ah1, ah0, al2, al1, al0, bh2, bh1, bh0, bl2, bl1, bl0, _hmaxt, _lmint, _hmaxt1, _lmint1, _tfok, _val_ses, showon, _smt_clr, _smt_txt_clr, _tf_ok_V, lbl, name, pair, _inv, _time_limit, ssmt_pair, ssmt_pair2)
Normal SMT detection with line/label drawing and QCISD level creation.
Parameters:
cfg (SSMTConfig) : SSMTConfig settings
qcisd_state (QCISDState) : QCISDState arrays for QCISD level management
ah2 (float) : Chart asset high 2 periods ago
ah1 (float) : Chart asset high 1 period ago
ah0 (float) : Chart asset current high
al2 (float) : Chart asset low 2 periods ago
al1 (float) : Chart asset low 1 period ago
al0 (float) : Chart asset current low
bh2 (float) : Correlated asset high 2 periods ago
bh1 (float) : Correlated asset high 1 period ago
bh0 (float) : Correlated asset current high
bl2 (float) : Correlated asset low 2 periods ago
bl1 (float) : Correlated asset low 1 period ago
bl0 (float) : Correlated asset current low
_hmaxt (int) : Time of current high maximum
_lmint (int) : Time of current low minimum
_hmaxt1 (int) : Time of previous high maximum
_lmint1 (int) : Time of previous low minimum
_tfok (bool) : Whether timeframe is valid for this SSMT level
_val_ses (int) : Current session index
showon (bool) : Whether to show this SSMT level on chart
_smt_clr (color) : Color for SSMT lines
_smt_txt_clr (color) : Color for SSMT label text
_tf_ok_V (bool) : Whether timeframe is valid for visibility
lbl (string) : Label text string
name (string) : SSMT timeframe name ("90m", "Daily", "Weekly", etc.)
pair (int) : Pair number (2=secondary, 3=tertiary)
_inv (bool) : Whether this pair is inverse correlated
_time_limit (int) : Time limit for active status checking (dayStart or 0)
ssmt_pair (string) : Name string of secondary pair
ssmt_pair2 (string) : Name string of tertiary pair
Returns: Tuple:
f_hidden_ssmt(cfg, _clsmax, _clsmax1, _clsmin, _clsmin1, _clsmaxt, _clsmaxt1, _clsmint, _clsmint1, _cclsmax, _cclsmax1, _cclsmin, _cclsmin1, _tfok, showon, _smt_clr, _smt_txt_clr, _val_ses, _tf_ok_V, lbl, name, pair, _inv, _time_limit, ssmt_pair, ssmt_pair2)
Hidden SMT detection with line/label drawing.
Parameters:
cfg (SSMTConfig) : SSMTConfig settings
_clsmax (float) : Current close max
_clsmax1 (float) : Previous close max
_clsmin (float) : Current close min
_clsmin1 (float) : Previous close min
_clsmaxt (int) : Time of current close max
_clsmaxt1 (int) : Time of previous close max
_clsmint (int) : Time of current close min
_clsmint1 (int) : Time of previous close min
_cclsmax (float) : Correlated asset current close max
_cclsmax1 (float) : Correlated asset previous close max
_cclsmin (float) : Correlated asset current close min
_cclsmin1 (float) : Correlated asset previous close min
_tfok (bool) : Whether timeframe is valid
showon (bool) : Whether to show on chart
_smt_clr (color) : Color for hidden SSMT lines
_smt_txt_clr (color) : Color for hidden SSMT label text
_val_ses (int) : Current session index
_tf_ok_V (bool) : Whether timeframe is within visibility range
lbl (string) : Label text string
name (string) : SSMT timeframe name
pair (int) : Pair number (2=secondary, 3=tertiary)
_inv (bool) : Whether pair is inverse correlated
_time_limit (int) : Time limit for active status checking
ssmt_pair (string) : Name string of secondary pair
ssmt_pair2 (string) : Name string of tertiary pair
Returns: Tuple:
run_ssmt(cfg, qcisd_state, _tf_ok, _tf_ok_V, _val_ses, name, _show_smt, _smt_clr, _hsmt_clr, _smt_txt_clr, _show_hsmt, X_SSMT, shortname, _time_limit, xo0, xc0, xh0, xl0, xt0, yo0, yc0, yh0, yl0, yt0, ssmt_pair, ssmt_pair2, arr_inv, triad_ok, showsmt2)
Orchestrator that calls f_main_process + f_ssmt + f_hidden_ssmt for each timeframe.
This replaces f_allrun from the monolithic indicator.
Parameters:
cfg (SSMTConfig) : SSMTConfig settings
qcisd_state (QCISDState) : QCISDState arrays
_tf_ok (bool) : Whether timeframe is within valid range
_tf_ok_V (bool) : Whether timeframe is within visibility range
_val_ses (int) : Current session index value
name (string) : SSMT timeframe name ("90m", "Daily", "Weekly", etc.)
_show_smt (bool) : Whether to show normal SSMT
_smt_clr (color) : Color for normal SSMT lines
_hsmt_clr (color) : Color for hidden SSMT lines
_smt_txt_clr (color) : Color for SSMT label text
_show_hsmt (bool) : Whether to show hidden SSMT
X_SSMT (array) : The bool array (size 14) for this timeframe's SSMT state
shortname (string) : Short name for labels (e.g. "90m", "D", "W")
_time_limit (int) : Time limit for active status (dayStart or 0)
xo0 (float) : Secondary asset open
xc0 (float) : Secondary asset close
xh0 (float) : Secondary asset high
xl0 (float) : Secondary asset low
xt0 (int) : Secondary asset time
yo0 (float) : Tertiary asset open
yc0 (float) : Tertiary asset close
yh0 (float) : Tertiary asset high
yl0 (float) : Tertiary asset low
yt0 (int) : Tertiary asset time
ssmt_pair (string) : Name of secondary pair
ssmt_pair2 (string) : Name of tertiary pair
arr_inv (array) : Array of inversion flags
triad_ok (bool) : Whether triad mode is active
showsmt2 (bool) : Whether to show SMT pair 2
run_alert(cfg, a_con1, a_con3, number, M_SSMT, W_SSMT, D_SSMT, Q_SSMT, Y_SSMT, N_SSMT, m_SSMT, newMo, newW, newD, newN, newm, newQ, newY)
Multi-condition alert logic for SSMT signals.
Parameters:
cfg (SSMTConfig) : SSMTConfig settings
a_con1 (string) : First alert condition string (e.g. "W Bull SSMT")
a_con3 (string) : Second alert condition string
number (string) : Alert number string ("1", "2", "3", "4")
M_SSMT (array) : Monthly SSMT state array (size 14)
W_SSMT (array) : Weekly SSMT state array
D_SSMT (array) : Daily SSMT state array
Q_SSMT (array) : Quarterly SSMT state array
Y_SSMT (array) : Yearly SSMT state array
N_SSMT (array) : 90m SSMT state array
m_SSMT (array) : Micro SSMT state array
newMo (bool) : Whether monthly session just changed
newW (bool) : Whether weekly session just changed
newD (bool) : Whether daily session just changed
newN (bool) : Whether 90m session just changed
newm (bool) : Whether micro session just changed
newQ (bool) : Whether quarterly session just changed
newY (bool) : Whether yearly session just changed
calc_psp_adaptive(_show, xc0, xo0, xt0, yc0, yo0, yt0, arr_inv, triad_ok, dyad_ok, showsmt1, showsmt2)
PSP (Price Sync Pattern) adaptive bar-by-bar divergence calculation.
Parameters:
_show (bool) : Whether PSP is enabled and visible
xc0 (float) : Secondary asset close
xo0 (float) : Secondary asset open
xt0 (int) : Secondary asset time
yc0 (float) : Tertiary asset close
yo0 (float) : Tertiary asset open
yt0 (int) : Tertiary asset time
arr_inv (array) : Inversion flags array
triad_ok (bool) : Whether triad mode is active
dyad_ok (bool) : Whether dyad mode is active
showsmt1 (bool) : Whether SMT pair 1 is shown
showsmt2 (bool) : Whether SMT pair 2 is shown
Returns: Tuple:
get_sb_color_norm(_arr, _c_bull, _c_bear, _c_sand, _c_neut)
Computes the status bar color for a given SSMT timeframe array.
Parameters:
_arr (array) : The SSMT bool array (size 14) for this timeframe
_c_bull (color) : Bullish color
_c_bear (color) : Bearish color
_c_sand (color) : Sandwich/conflict color
_c_neut (color) : Neutral color
Returns: The computed color for the status bar cell
process_qcisd(qcisd_state, cfg)
QCISD global processor and mitigation loop. Handles confirmation, invalidation,
retest detection, and cleanup of QCISD levels.
Parameters:
qcisd_state (QCISDState) : QCISDState arrays to process
cfg (SSMTConfig) : SSMTConfig settings
SSMTConfig
Configuration settings for SSMT detection, drawing, alerts, and QCISD engine.
Fields:
hidelines (series bool) : Whether to hide SSMT divergence lines on chart
hidelabels (series bool) : Whether to hide SSMT divergence labels on chart
normstyle (series string) : Line style for normal SSMT lines (line.style_solid, etc.)
hiddstyle (series string) : Line style for hidden SSMT lines
i_font (series string) : Text size for SSMT labels ("tiny", "small", "normal", "large", "huge")
alerttype (series string) : Type of SSMT to show/alert ("All", "Normal", "Hidden")
ssmt_history_limit (series int) : Maximum number of SSMT lines/labels to keep
show_qcisd (series bool) : Whether QCISD engine is enabled
bias_input (series string) : Market bias for QCISD ("Bullish", "Bearish", "Neutral")
qcisd_bull_clr (series color) : Color for bullish QCISD levels
qcisd_bear_clr (series color) : Color for bearish QCISD levels
qcisd_pend_clr (series color) : Color for pending (threatened) QCISD levels
qcisd_text_clr (series color) : Color for QCISD label text
qcisd_width (series int) : Line width for QCISD levels
qcisd_lbl_size (series string) : Text size for QCISD labels (size.tiny, size.small, size.normal)
qcisd_mono (series bool) : Whether to use monospace font for QCISD labels
qcisd_max_limit (series int) : Maximum number of QCISD lines to draw
qcisd_trigger (series string) : HP-QCISD alert trigger mode ("All", "Confirmation", "Invalidation", "Retest", "Off")
qcisd_norm_trigger (series string) : Normal QCISD alert trigger mode
QCISDState
Holds the global QCISD state arrays. Passed by reference so library functions can modify in place.
Fields:
g_q_lines (array) : Array of QCISD line drawings
g_q_lbls (array) : Array of QCISD label drawings
g_q_dirs (array) : Array of directions (1=bullish, -1=bearish)
g_q_hp (array) : Array of high-probability flags
g_q_conf (array) : Array of confirmation flags
g_q_names (array) : Array of SSMT source names (e.g. "90m", "Daily")
g_q_pairs (array) : Array of pair names
SessionState
Holds all computed session and quarter values for the current bar.
Fields:
val_sesm (series int) : Micro session index (0-63)
val_ses (series int) : 90m session index (0-15)
val_sesD (series int) : Daily session index (0-3)
val_sesW (series int) : Weekly session index (0-6)
val_sesMo (series int) : Monthly session index (0-4)
val_sesQ (series int) : Quarterly session index (0-3)
val_sesY (series int) : Yearly session index (0-3)
newMo (series bool) : Whether monthly session just changed
newW (series bool) : Whether weekly session just changed
newD (series bool) : Whether daily session just changed
newN (series bool) : Whether 90m session just changed
newm (series bool) : Whether micro session just changed
newQ (series bool) : Whether quarterly session just changed
newY (series bool) : Whether yearly session just changed
dayStart (series int) : Timestamp of the current day start Library

EKAssetCorrelationLibrary "EKAssetCorrelation"
Full asset correlation library for SMT divergence detection. Drop-in replacement for fstarcapital/AssetCorrelationUtils/11.
detectIndicesFutures(ticker)
Detects Index Futures (NQ/ES/YM/RTY + micro variants)
Parameters:
ticker (string) : The ticker string to check (typically syminfo.ticker)
Returns: AssetPairing with secondary and tertiary assets configured
detectMetalsFutures(ticker)
Detects Metal Futures (GC/SI/HG + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectMetalsFuturesQuad(ticker)
Detects Metal Futures in Quad Mode (Gold->SI/XAUEUR/XAUGBP, Silver->GC/XAGEUR/XAGGBP)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with futures secondary + GXT cross-pairs as tertiary/quaternary (empty for copper)
detectMetalsFuturesGxt(ticker)
Detects Metal Futures in GXT Mode (Gold->XAUEUR/XAUGBP, Silver->XAGEUR/XAGGBP)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with GXT secondary and tertiary assets (empty for copper)
detectForexFutures(ticker)
Detects Forex Futures (6E/6B + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectEnergyFutures(ticker)
Detects Energy Futures (CL/RB/HO + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectTreasuryFutures(ticker)
Detects Treasury Futures (ZB/ZF/ZN)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectCryptoFutures(ticker)
Detects CME Crypto Futures (BTC/ETH + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectCADFutures(ticker)
Detects CAD Forex Futures (6C + micro variants)
Parameters:
ticker (string) : The ticker string to check
Returns: AssetPairing with secondary and tertiary assets configured
detectForexCFD(ticker, tickerId)
Detects Forex CFD pairs (EUR/GBP/DXY, USD/JPY/CHF triads)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID (syminfo.tickerid) for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectCrypto(ticker, tickerId)
Detects major Crypto assets (BTC, ETH, SOL, XRP, alts)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectMetalsCFD(ticker, tickerId)
Detects Metals CFD (XAU/XAG/Copper + EUR/GBP cross-pairs)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectMetalsCFDGxt(ticker, tickerId)
Detects Metals CFD in GXT Mode (XAUUSD->XAUEUR/XAUGBP, XAGUSD->XAGEUR/XAGGBP)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with GXT secondary and tertiary assets (empty for copper)
detectMetalsCFDQuad(ticker, tickerId)
Detects Metals CFD in Quad Mode (XAUUSD->XAGUSD/XAUEUR/XAUGBP, etc.)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with quad assets (empty for copper)
detectIndicesCFD(ticker, tickerId)
Detects Indices CFD (NAS100/SP500/DJ30)
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary and tertiary assets configured
detectEUStocks(ticker, tickerId)
Detects EU Stock Indices (GER40/EU50) - Dyad only
Parameters:
ticker (string) : The ticker string to check
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with secondary asset configured (tertiary empty for dyad)
getDefaultFallback(tickerId)
Returns default fallback assets (chart ticker only, no correlation)
Parameters:
tickerId (string) : The full ticker ID for primary asset
Returns: AssetPairing with chart ticker as primary, empty secondary/tertiary (no correlation)
applySessionModifierWithBackadjust(tickerStr, sessionType)
Applies futures session modifier to ticker WITH back adjustment
Parameters:
tickerStr (string) : The ticker to modify
sessionType (string) : The session type (syminfo.session)
Returns: Modified ticker string with session and backadjustment.on applied
applySessionModifierNoBackadjust(tickerStr, sessionType)
Applies futures session modifier to ticker WITHOUT back adjustment
Parameters:
tickerStr (string) : The ticker to modify
sessionType (string) : The session type (syminfo.session)
Returns: Modified ticker string with session and backadjustment.off applied
isTriadMode(pairing)
Checks if a pairing represents a valid triad (3 assets)
Parameters:
pairing (AssetPairing) : The AssetPairing to check
Returns: True if tertiary is non-empty (triad mode), false for dyad
getAssetTicker(tickerId)
Extracts clean ticker string from full ticker ID
Parameters:
tickerId (string) : The full ticker ID (e.g., "BITGET:BTCUSDT.P")
Returns: Clean ticker string (e.g., "BTCUSDT.P")
resolveTriad(chartTickerId, pairing)
Resolves triad asset assignments with proper inversion flags
Parameters:
chartTickerId (string) : The current chart's ticker ID (syminfo.tickerid)
pairing (AssetPairing) : The detected AssetPairing
Returns: Tuple
resolveDyad(chartTickerId, pairing)
Resolves dyad asset assignment with proper inversion flag
Parameters:
chartTickerId (string) : The current chart's ticker ID
pairing (AssetPairing) : The detected AssetPairing (dyad: tertiary is empty)
Returns: Tuple
resolveQuad(chartTickerId, pairing)
Resolves quad asset assignments with proper inversion flags (4 assets)
Parameters:
chartTickerId (string) : The current chart's ticker ID (syminfo.tickerid)
pairing (AssetPairing) : The detected AssetPairing with quaternary populated
Returns: Tuple
resolveAssets(ticker, tickerId, assetType, sessionType, useBackadjust, gxtMode, quadMode)
Main auto-detection entry point. Detects asset category and returns fully resolved config.
Parameters:
ticker (string) : The ticker string to check (typically syminfo.ticker)
tickerId (string) : The full ticker ID (typically syminfo.tickerid)
assetType (string) : The asset type (typically syminfo.type)
sessionType (string) : The session type for futures (typically syminfo.session)
useBackadjust (bool) : Whether to apply back adjustment for futures session alignment
gxtMode (bool) : When true, metals use currency-cross triads instead of standard metal correlations
quadMode (bool) : When true, metals use futures secondary + GXT cross-pairs as tertiary/quaternary. Takes priority over gxtMode for metals.
Returns: AssetConfig with fully resolved assets, inversion flags, and detection status
resolveCurrentChart(gxtMode, quadMode)
Simplified auto-detection using current chart's syminfo values
Parameters:
gxtMode (bool) : When true, metals use currency-cross triads instead of standard metal correlations
quadMode (bool) : When true, metals use futures secondary + GXT cross-pairs as tertiary/quaternary
Returns: AssetConfig with fully resolved assets, inversion flags, and detection status
AssetPairing
Core asset pairing structure for triad/dyad configurations
Fields:
primary (series string) : The primary (chart) asset ticker ID
secondary (series string) : The secondary correlated asset ticker ID
tertiary (series string) : The tertiary correlated asset ticker ID (empty for dyad)
quaternary (series string) : The quaternary correlated asset ticker ID (empty unless quad mode)
invertSecondary (series bool) : Whether secondary asset should be inverted for divergence calc
invertTertiary (series bool) : Whether tertiary asset should be inverted for divergence calc
invertQuaternary (series bool) : Whether quaternary asset should be inverted for divergence calc
AssetConfig
Full asset resolution result with mode detection and computed values
Fields:
detected (series bool) : Whether auto-detection succeeded
isTriadMode (series bool) : True if triad (3 assets), false if dyad (2 assets)
isQuadMode (series bool) : True if quad (4 assets)
primary (series string) : The resolved primary asset ticker ID
secondary (series string) : The resolved secondary asset ticker ID
tertiary (series string) : The resolved tertiary asset ticker ID (empty for dyad)
quaternary (series string) : The resolved quaternary asset ticker ID (empty unless quad mode)
invertSecondary (series bool) : Computed inversion flag for secondary asset
invertTertiary (series bool) : Computed inversion flag for tertiary asset
invertQuaternary (series bool) : Computed inversion flag for quaternary asset
assetCategory (series string) : String describing the detected asset category Library

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 Library

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) Library

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 Library

CyberVisLib# CyberVisLib v5
CyberVisLib provides rendering and visualization utilities for multi-oscillator indicators: color blending, sub-pane management, diagnostic tables, and tooltip formatting. Pure visualization layer—no market logic.
## What it does
Delivers four capabilities: color utilities (RGB blending, diverging/sequential gradients, confidence-to-transparency), sub-pane management (vertical space allocation for multiple oscillators), diagnostic tables (key-value pairs, dynamic coloring), and tooltip formatting. Stack RSI, MACD, Stochastic in non-overlapping vertical bands.
Outputs color values, MiniSubPane structs (band coordinates), table objects, formatted strings. All stateless, rendering-focused.
## How it works
Color blending: `RGB_out = (1-t)×RGB_a + t×RGB_b`. Diverging gradients split at zero (negative→red-yellow, positive→yellow-green). Transparency: `90 - 60×confidence`.
Sub-pane management:
1. Register oscillators (MiniOscMeta)
2. Finalize layout (STACK_TOP/BOTTOM/EQUAL_SPLIT policies)
3. Map values: `pane.band_y(unit_val)` converts to vertical coordinate
Diagnostic tables: key-value pairs, multi-column grids, conditional formatting.
## Why this is original
Only PulseWire library with complete rendering toolkit. Existing libraries mix rendering with market logic.
Unique features:
- Sub-pane vertical allocation (automatic band calculation)
- Lightweight UDT variants (co-import with OscLib)
- Diverging gradients with zero-centering
- Confidence-to-transparency mapping
- Regime color enum (consistent color mapping)
Separation of concerns: VisLib (rendering), NumLib (math), SignalLib (signals).
## How to use it
```pine
//@version=6
indicator("CyberVisLib Demo", overlay=false)
import cybermediaboy/CyberVisLib/5 as VL
// Diverging gradient
rsi = ta.rsi(close, 14)
z_rsi = (rsi - 50.0) / 25.0
color rsi_color = VL.f_diverging_rgyg(z_rsi)
plot(rsi, "RSI", color=rsi_color)
// Sub-pane management
var spm = VL.f_subpane_manager_new(VL.SubPanePolicy.EQUAL_SPLIT, 5.0)
if barstate.isfirst
spm.register(VL.f_meta_unipolar0100("rsi", "RSI", color.blue))
spm.register(VL.f_meta_bipolar("macd", "MACD", color.orange))
spm.finalize()
var pane_rsi = array.get(spm.panes, 0)
rsi_y = pane_rsi.band_y(pane_rsi.meta.to_unit(rsi))
plot(rsi_y, "RSI Pane", color.blue)
// Confidence transparency
conf = math.abs(rsi - 50.0) / 50.0
bgcolor(color.new(color.green, VL.f_transp(conf)))
```
## Key functions
- `f_blend()` - RGB color blending
- `f_diverging_rgyg()` - Diverging gradient (zero-centered)
- `f_transp()` - Confidence-to-transparency mapping
- `f_subpane_manager_new()` - Sub-pane allocation
- `f_regime_color()` - Regime color enum
- `f_kv_tooltip()` - Tooltip formatting
## Limitations
- Sub-pane allocation static after finalize
- RGB-only blending (no HSL/HSV)
- No automatic label/line cleanup
- Tables require manual cell updates
- Assumes `overlay=false` (separate pane indicators only)
Library

CyberMarketLib# CyberMarketLib v2
CyberMarketLib provides market structure analysis combining swing point detection, Break of Structure (BoS) / Change of Character (CHoCH) identification, session classification, and volatility regime tracking.
## What it does
Delivers four core capabilities: swing point tracking (configurable left/right bar lookback), market structure events (BoS/CHoCH for trend continuation vs reversal), session classification (Asia/London/NY via UTC bucketing), and volatility regimes (LOW/NORMAL/HIGH/EXTREME via ATR percentiles). Build context-aware indicators that adapt to market conditions.
Outputs FractalData structs, StructureEvent/Session/VolRegime enums. All pivots use confirmed swing points (requires right_len bars validation), preventing repainting.
## How it works
Swing detection: `high < high > high `. Stores pivots in SwingHistory circular buffers with automatic capacity management.
BoS/CHoCH follows Smart Money Concepts:
- BOS_UP/DOWN: Price breaks recent swing (trend continuation)
- CHOCH_UP/DOWN: Pivot break after opposite swing (reversal)
Sessions via UTC hours: ASIA (00-08), LONDON (08-13), NY_OVERLAP (13-17), NY_AFTERNOON (17-21), OFF_HOURS (21-24).
Volatility regimes via ATR percentiles (100-bar window): LOW (<25th), NORMAL (25-75th), HIGH (75-90th), EXTREME (>90th).
## Why this is original
Only PulseWire library combining BoS/CHoCH, sessions, and volatility regimes. Existing SMC indicators lack reusable libraries.
Unique features:
- Confirmed pivots only (no repainting)
- CHoCH sequence analysis (pivot pattern detection)
- UTC-based sessions (exchange-agnostic, DST-safe)
- Percentile volatility (asset-adaptive)
- Circular buffer (O(1) operations, memory-efficient)
Designed for composability: sessions → conditional logic, regimes → stop multipliers, BoS/CHoCH → entry/exit signals.
## How to use it
```pine
//@version=6
indicator("CyberMarketLib Demo", overlay=true)
import cybermediaboy/CyberMarketLib/2 as ML
// Swing points + BoS/CHoCH detection
var swing_hist = ML.f_swing_history_new(max_n=20)
var fractal = ML.f_detect_pivot(left_len=5, right_len=5)
if not na(fractal)
swing_hist.push(fractal)
var event = ML.f_detect_structure_event(swing_hist, close)
// event: BOS_UP, BOS_DOWN, CHOCH_UP, CHOCH_DOWN, NONE
// Session + volatility regime
session = ML.f_current_session() // ASIA, LONDON, NY_OVERLAP, etc.
vol_regime = ML.f_volatility_regime(14, 100) // LOW, NORMAL, HIGH, EXTREME
// Adaptive stops
atr = ta.atr(14)
stop_mult = vol_regime == ML.VolRegime.EXTREME ? 3.0 : 1.5
plot(close - atr * stop_mult, "Stop", color.red)
```
## Key functions
- `f_detect_pivot()` - Confirmed swing points (no repainting)
- `f_detect_structure_event()` - BoS/CHoCH detection
- `f_current_session()` - UTC-based session classification
- `f_volatility_regime()` - ATR percentile regimes
- `f_htf_for()` - Higher timeframe string generation
- SwingHistory UDT - Circular buffer for pivot storage
## Limitations
- Swing detection: `right_len` bars confirmation delay (lag vs repainting indicators)
- BoS/CHoCH: Assumes trending markets (false signals in choppy ranges)
- Sessions: UTC-only (no exchange-native or DST-aware sessions)
- Volatility: ATR-based only (may lag on sudden spikes)
- SwingHistory: Fixed capacity at initialization
- CHoCH: Requires manual state tracking to avoid duplicate signals
Library

CyberSignalLib# CyberSignalLib v2
CyberSignalLib provides advanced signal processing tools for Pine Script traders, combining Kalman filtering, entropy-based changepoint detection, and market microstructure analysis in a single dependency.
## What it does
SignalLib delivers three core capabilities: N-dimensional Kalman filters for multi-feature state estimation (price, velocity, z-scores), entropy-based changepoint detectors for regime shifts (NIS, CUSUM, BOCPD), and microstructure metrics for order flow analysis (delta, aggression, volume imbalance). Traders use these tools to build adaptive indicators that respond to market regime changes—for example, a Kalman filter tracking price and volatility simultaneously, with automatic parameter adjustment when a changepoint detector signals a structural break.
The library outputs filtered state estimates (smoothed price, velocity, Mahalanobis distance), changepoint probabilities (0-1 scores indicating regime shift likelihood), and microstructure features (signed delta, aggression ratio, volume-weighted imbalance). All functions support real-time bar-by-bar updates with minimal memory overhead via circular buffers and packed covariance matrices.
## How it works
The Kalman filter implementation uses an N-dimensional state vector with upper-triangular packed covariance storage, reducing memory from O(N²) to O(N(N+1)/2). The filter supports diagonal process noise (Q) and scalar measurement noise (R), both adaptive via innovation tracking. The update step follows the standard predict-correct cycle: predict state using transition matrix F, compute innovation (measurement - prediction), update state and covariance via Kalman gain. Normalized Innovation Squared (NIS) is computed as `innovation² / (H·P·H' + R)` to detect outliers and trigger adaptive R adjustments.
Changepoint detection uses three methods:
1. **NIS-based**: Flags regime change when NIS exceeds a threshold (e.g., 9.0 for 99% confidence under chi-squared distribution)
2. **CUSUM**: Cumulative sum of log-likelihood ratios, resets when crossing upper/lower bounds
3. **BOCPD (Bayesian Online Changepoint Detection)**: Maintains run-length distribution, computes changepoint probability via hazard function
Entropy calculations support four modes: binary (up/down), ternary (up/flat/down), combo (binary + ternary), and composite (weighted average). Shannon entropy is computed as `-Σ p_i log₂(p_i)` where p_i are empirical frequencies over a rolling window. High entropy (near maximum) indicates unpredictable price action; low entropy signals trending or mean-reverting regimes.
Microstructure metrics derive from tick-level order flow:
- **Delta**: Signed volume (buy volume - sell volume)
- **Aggression**: Ratio of aggressive orders (market orders) to total volume
- **Imbalance**: `(buy_vol - sell_vol) / (buy_vol + sell_vol)`, range
These metrics are computed via request.security calls to lower timeframes (1-minute typical) and aggregated to the chart timeframe.
## Why this is original
CyberSignalLib is the only PulseWire library combining Kalman filtering, changepoint detection, and microstructure analysis in a unified interface. Existing Kalman filter libraries are limited to 1D or 2D state spaces and lack adaptive noise parameters. No public library offers BOCPD or CUSUM changepoint detection. Microstructure metrics typically require manual request.security calls with hardcoded timeframes—SignalLib abstracts this into reusable functions with configurable lookback windows.
Unique features:
- **Tri-packed covariance**: Memory-efficient N-dimensional Kalman filter (supports up to 16 features on PulseWire's memory limits)
- **Adaptive Q/R**: Automatic process/measurement noise tuning based on innovation statistics, eliminating manual parameter tweaking
- **Trajectory store**: Circular buffer for Kalman state history, enabling lookback analysis (e.g., "was price above Kalman estimate 5 bars ago?")
- **Mahalanobis distance**: 3D analytic formula with shrinkage regularization for outlier detection in multi-feature space
- **Unified changepoint API**: Single enum-based interface for NIS/CUSUM/BOCPD, simplifying regime-switching indicator logic
No other Pine library provides this combination of statistical rigor (Kalman optimality, Bayesian changepoint inference) and practical usability (adaptive parameters, memory-efficient storage, microstructure integration).
## How to use it
```pine
//@version=6
indicator("CyberSignalLib Demo", overlay=true)
import cybermediaboy/CyberSignalLib/2 as SL
import cybermediaboy/NumLib/5 as N
// Example 1: 2D Kalman filter (price + velocity)
var kal = SL.f_kalman_init(nfeat=2, P0=1.0, Q0=0.01, R0=0.1, innov_window=20)
if not na(close)
kal.update_scalar(0, close, 1.0) // Measure price (feature 0)
kal.predict(SL.f_transition_identity(2))
kal.adapt_Q(Q_min=0.001, Q_max=0.1, gain=1.5)
kal.adapt_R(high_thresh=9.0, low_thresh=1.0, R_step=0.1)
float price_est = array.get(kal.x, 0)
float velocity_est = array.get(kal.x, 1)
plot(price_est, "Kalman Price", color.blue, linewidth=2)
plot(close + velocity_est * 10, "Velocity Offset", color.orange)
// Example 2: NIS-based changepoint detection
bool changepoint = kal.lastnis > 9.0 // 99% confidence threshold
bgcolor(changepoint ? color.new(color.red, 80) : na, title="Regime Change")
// Example 3: Entropy calculation (ternary mode)
var ent_buf = array.new(50, 0)
int direction = close > close ? 1 : (close < close ? -1 : 0)
array.push(ent_buf, direction)
if array.size(ent_buf) > 50
array.shift(ent_buf)
float entropy = SL.f_entropy_ternary(ent_buf)
plot(entropy, "Ternary Entropy", color.green)
// Example 4: Mahalanobis distance (3D outlier detection)
var z_vec = array.from(close, volume, ta.rsi(close, 14))
var mu_vec = array.from(ta.sma(close, 50), ta.sma(volume, 50), 50.0)
var cov_tri = array.from(1.0, 0.0, 0.0, 1.0, 0.0, 1.0) // Identity covariance
float maha = SL.f_mahalanobis_3d(z_vec, mu_vec, cov_tri, shrinkage=0.1)
plot(maha, "Mahalanobis Distance", color.purple)
```
## Inputs, outputs, expected behavior
**Kalman filter** (`f_kalman_init`, `update_scalar`, `predict`):
- **Inputs**: `nfeat` (int, 1-16 typical), `P0/Q0/R0` (float, initial noise estimates), `measurement` (float), `H` (float, observation matrix row)
- **Outputs**: Updated state vector `x` (array), NIS value `lastnis` (float, unbounded), ready flag `ready` (bool)
- **Edge cases**: Returns unmodified state if measurement is NA, requires ≥20 bars for adaptive Q/R to stabilize
**Changepoint detection** (`f_changepoint_nis`, `f_changepoint_cusum`, `f_changepoint_bocpd`):
- **Inputs**: `nis` (float, typically from Kalman filter), `threshold` (float, 9.0 for 99% confidence), `hazard` (float, 0.01-0.1 for BOCPD)
- **Outputs**: Changepoint probability (float, ) or binary flag (bool)
- **Edge cases**: CUSUM resets on boundary crossing, BOCPD requires ≥10 bars for stable run-length distribution
**Entropy functions** (`f_entropy_binary`, `f_entropy_ternary`, `f_entropy_combo`):
- **Inputs**: `data` (array, direction codes: -1/0/1), `window` (int, 20-100 typical)
- **Outputs**: Shannon entropy (float, ), max entropy = 1.0 for binary, 1.585 for ternary
- **Edge cases**: Returns 0.0 if all elements identical, handles empty arrays gracefully
**Microstructure metrics** (`f_get_micro_state`, `f_get_scientific_delta`, `f_get_aggregated_volume`):
- **Inputs**: `timeframe` (string, "1" for 1-minute), `lookback` (int, bars to aggregate)
- **Outputs**: Delta (float, signed volume), aggression (float, ), imbalance (float, )
- **Edge cases**: Returns NA if lower timeframe data unavailable, requires Premium/Pro account for intraday request.security
**Trajectory store** (`f_trajectory_new`, `push`, `read`):
- **Inputs**: `snap_dim` (int, state vector length), `capacity` (int, max snapshots), `offset` (int, 0=latest)
- **Outputs**: Snapshot array (array, length `snap_dim`)
- **Edge cases**: Returns NA-filled array if offset exceeds filled count, circular overwrite after capacity reached
## Limitations
1. **Kalman filter assumes linear dynamics**: The transition matrix F is diagonal (no cross-feature coupling). For non-linear systems (e.g., price-volatility feedback loops), the filter may diverge. Extended Kalman Filter (EKF) or Unscented Kalman Filter (UKF) variants are not implemented.
2. **Changepoint detection requires tuning**: NIS threshold (default 9.0) assumes Gaussian measurement noise. In heavy-tailed distributions (crypto, low-liquidity assets), false positives increase. CUSUM and BOCPD require manual hazard/boundary tuning per asset and timeframe.
3. **Microstructure functions require lower timeframe data**: `f_get_micro_state` and related functions call request.security with `timeframe="1"` (1-minute). This fails on daily/weekly charts or for symbols without intraday data. Users must handle NA returns or pre-filter symbols.
4. **Memory overhead for high-dimensional Kalman**: An N=16 feature Kalman filter requires 136 floats for packed covariance (16×17/2) plus state vector. On PulseWire's 50,000 float limit per script, this restricts other arrays. Reduce `nfeat` or use sparse feature selection.
5. **Entropy calculations assume discrete states**: Binary/ternary entropy requires pre-discretized input (direction codes -1/0/1). Continuous price data must be manually binned. The library does not auto-discretize or suggest bin counts.
6. **No multi-step prediction**: The Kalman filter supports one-step-ahead prediction only. For multi-bar forecasts (e.g., "predict price 5 bars ahead"), users must manually iterate the predict step, which compounds uncertainty without re-measurement.
7. **Adaptive Q/R convergence time**: Adaptive noise parameters require 20-50 bars to stabilize after initialization or regime change. During this period, filter estimates may be suboptimal. Consider using fixed Q/R for the first 50 bars, then enabling adaptation.
Library

CyberLearningLib# CyberLearningLib v4
CyberLearningLib provides online learning primitives for Pine Script traders building adaptive machine learning indicators, including circular training buffers, feature scaling, stochastic gradient descent (SGD), and distance metrics for k-nearest neighbors (kNN) algorithms.
## What it does
LearningLib delivers four core components: circular training buffers for memory-efficient sample storage (O(1) push/read), feature scalers with exponentially weighted moving average (EWMA) normalization, SGD optimizers with gradient clipping and multiple loss functions (squared, hinge, logistic, Huber), and distance metrics for kNN classification (Euclidean, Manhattan, Cosine, Mahalanobis, Chebyshev). Traders use these tools to build indicators that learn from historical price patterns—for example, a kNN classifier predicting next-bar direction based on the 10 most similar historical setups, with features auto-scaled via EWMA to handle non-stationary markets.
The library outputs trained model weights (SGD state vector), scaled feature vectors (normalized to or z-scores), distance matrices for kNN queries, and sample metadata (timestamp, sample type, trade direction). All data structures use circular buffers to maintain constant memory usage regardless of training duration, critical for long-running indicators on PulseWire's 50,000 float limit.
## How it works
The training buffer uses a circular array with write-head indexing: when capacity is reached, new samples overwrite the oldest. Each sample stores a feature vector (array), label (float, regression target or {-1,+1} for classification), weight (float, for importance sampling), timestamp (bar_index), sample type (enum: LIVE/SIMULATED/SHADOW/BACKFILL), trade direction (LONG/SHORT/FLAT), and two free metadata integers for custom categorization. The `read(offset)` method retrieves samples in reverse chronological order (0 = most recent), while `read_chrono(pos)` accesses samples in insertion order (0 = oldest).
Feature scaling supports three methods:
1. **EWMA normalization**: Maintains running mean/variance via `μ_t = (1-α)μ_{t-1} + αx_t`, scales features to z-scores
2. **Min-max scaling**: Tracks rolling min/max over window, normalizes to
3. **Percentile-based**: Uses IQR (interquartile range) for outlier-resistant scaling
SGD updates follow the standard formula `w_t = w_{t-1} - η∇L(w)` where η is learning rate and ∇L is loss gradient. Supported loss functions:
- **Squared**: `0.5(y - ŷ)²`, gradient = `-(y - ŷ)`
- **Hinge**: `max(0, 1 - y·ŷ)` for y ∈ {-1,+1}, gradient = `-y` if margin violated
- **Logistic**: `log(1 + exp(-y·ŷ))`, gradient = `-y / (1 + exp(y·ŷ))`
- **Huber**: Squared loss for small errors (|err| ≤ δ), linear for large errors (robust to outliers)
Gradient clipping prevents exploding gradients: `g_clipped = g / max(1, ||g|| / threshold)`. The library also provides gated SGD updates that skip parameter changes when innovation (measurement error) is below a threshold, reducing overfitting to noise.
Distance metrics compute similarity between feature vectors for kNN:
- **Euclidean**: `√Σ(x_i - y_i)²`
- **Manhattan**: `Σ|x_i - y_i|`
- **Cosine**: `1 - (x·y) / (||x|| ||y||)` (angle-based, scale-invariant)
- **Mahalanobis**: `√((x-y)'Σ⁻¹(x-y))` where Σ is covariance (accounts for feature correlations)
- **Chebyshev**: `max_i |x_i - y_i|` (L∞ norm)
## Why this is original
CyberLearningLib is the only PulseWire library providing a complete online learning toolkit with memory-efficient circular buffers and production-ready SGD implementations. Existing ML libraries either use linear arrays (memory grows unbounded), lack feature scaling (assume stationary data), or implement only Euclidean distance (ignoring feature correlations).
Unique features:
- **Circular training buffers**: O(1) push/read with constant memory, critical for indicators running 24/7 on crypto markets. No other Pine library offers circular indexing with chronological/reverse-chronological access.
- **Sample type tracking**: LIVE/SIMULATED/SHADOW/BACKFILL enum enables mixed training sets (e.g., "train on LIVE samples only, use SIMULATED for validation"). Essential for walk-forward optimization and out-of-sample testing.
- **Gated SGD updates**: Skip weight updates when innovation < threshold, preventing overfitting during low-volatility regimes. Based on Kalman filter innovation gating, not found in standard ML libraries.
- **Huber loss with configurable δ**: Robust regression loss that transitions from squared (δ-sensitive) to linear (outlier-resistant). Most Pine implementations use fixed δ=1.0; this library exposes δ as parameter.
- **Mahalanobis distance with shrinkage**: Accounts for feature correlations via inverse covariance, with Ledoit-Wolf shrinkage to prevent singular matrix errors. No other Pine library implements this (most use Euclidean only).
The library is designed for composition: training buffers feed into feature scalers, scaled features feed into SGD or kNN, distances feed into weighted voting. This modular design enables complex workflows (e.g., "scale features via EWMA, train linear SVM via hinge loss, classify new samples via kNN with Mahalanobis distance") without code duplication.
## How to use it
```pine
//@version=6
indicator("CyberLearningLib Demo", overlay=false)
import cybermediaboy/CyberLearningLib/4 as LL
import cybermediaboy/NumLib/5 as N
// Example 1: Circular training buffer
var tb = LL.f_buffer_new(capacity=100, nfeat=3)
if not na(close)
var features = array.from(ta.rsi(close, 14), ta.atr(14), volume)
float label = close < close ? 1.0 : -1.0 // Next-bar direction
var sample = LL.f_sample_new(features, label, LL.SampleType.LIVE,
LL.TradeDirection.LONG, meta_a=0, meta_b=0)
tb.push(sample)
// Read most recent sample
var recent = tb.read(0)
if not na(recent)
plot(recent.label, "Last Label", color.blue)
// Example 2: Feature scaling (EWMA)
var scaler = LL.f_scaler_new(nfeat=3, alpha=0.1)
if not na(close)
var raw_features = array.from(close, volume, ta.rsi(close, 14))
var scaled = scaler.scale(raw_features)
plot(array.get(scaled, 0), "Scaled Close", color.orange)
// Example 3: SGD training (hinge loss for binary classification)
var sgd = LL.f_sgd_new(nfeat=3, learning_rate=0.01, loss=LL.LossKind.HINGE)
if tb.filled >= 10
var train_sample = tb.read(0)
if not na(train_sample)
sgd.update(train_sample.features, train_sample.label, clip_threshold=5.0)
float prediction = sgd.predict(train_sample.features)
plot(prediction, "SGD Prediction", color.green)
// Example 4: kNN distance calculation
if tb.filled >= 2
var s1 = tb.read(0)
var s2 = tb.read(1)
if not na(s1) and not na(s2)
float dist_euclidean = LL.f_distance(s1.features, s2.features, LL.DistanceKind.EUCLIDEAN)
float dist_cosine = LL.f_distance(s1.features, s2.features, LL.DistanceKind.COSINE)
plot(dist_euclidean, "Euclidean Dist", color.red)
plot(dist_cosine, "Cosine Dist", color.purple)
```
## Inputs, outputs, expected behavior
**Training buffer** (`f_buffer_new`, `push`, `read`, `read_chrono`):
- **Inputs**: `capacity` (int, 50-1000 typical), `nfeat` (int, feature dimension), `offset/pos` (int, sample index)
- **Outputs**: TBSample (struct with features, label, metadata) or na if index out of bounds
- **Edge cases**: Returns na for invalid offsets, overwrites oldest sample at capacity, `filled` count saturates at capacity
**Feature scaler** (`f_scaler_new`, `scale`, `update`):
- **Inputs**: `nfeat` (int), `alpha` (float, EWMA decay 0.01-0.3 typical), `features` (array)
- **Outputs**: Scaled feature vector (array, z-scores or normalized)
- **Edge cases**: Returns unscaled features on first call (no history), handles NA elements via nz()
**SGD optimizer** (`f_sgd_new`, `update`, `predict`):
- **Inputs**: `nfeat` (int), `learning_rate` (float, 0.001-0.1 typical), `loss` (enum), `features/label` (float), `clip_threshold` (float, 1.0-10.0)
- **Outputs**: Prediction (float, unbounded for regression, {-1,+1} for classification after sign()), updated weights (internal state)
- **Edge cases**: Gradient clipping prevents exploding weights, returns 0.0 prediction before first update
**Distance metrics** (`f_distance`, `f_distance_mahalanobis`):
- **Inputs**: `x/y` (array, same length), `kind` (enum), `cov_inv` (array, tri-packed inverse covariance for Mahalanobis)
- **Outputs**: Distance (float, ≥0 for Euclidean/Manhattan/Chebyshev, for Cosine, unbounded for Mahalanobis)
- **Edge cases**: Returns NA if array lengths mismatch, Mahalanobis requires non-singular covariance (use shrinkage if needed)
**Sample filtering** (`by_type`, `by_direction`):
- **Inputs**: `tb` (TrainingBuffer), `st` (SampleType enum), `dir` (TradeDirection enum)
- **Outputs**: Filtered array (subset of buffer matching criteria)
- **Edge cases**: Returns empty array if no matches, preserves chronological order
## Limitations
1. **Fixed feature dimension**: Training buffers and scalers require `nfeat` declared at initialization. Changing feature count mid-stream requires creating a new buffer/scaler. Dynamic feature sets (e.g., "use 3 features on stocks, 5 on crypto") are not supported.
2. **No automatic hyperparameter tuning**: Learning rate, loss function, gradient clip threshold, and EWMA alpha must be manually specified. The library does not provide grid search, cross-validation, or adaptive learning rate schedules (e.g., Adam, RMSprop). Users must tune via backtesting.
3. **SGD assumes i.i.d. samples**: Stochastic gradient descent converges optimally when samples are independent and identically distributed. Financial time series violate this (autocorrelation, regime changes). For non-stationary data, consider using gated updates or periodically resetting weights.
4. **Mahalanobis distance requires covariance matrix**: Computing inverse covariance for N features requires O(N³) operations and N(N+1)/2 storage. For high-dimensional features (N > 10), this becomes computationally expensive. Use Euclidean or Cosine distance for N > 10, or apply PCA to reduce dimensionality first.
5. **No mini-batch SGD**: The library implements single-sample (online) SGD only. Mini-batch updates (averaging gradients over K samples) are not supported. For noisy gradients, increase EWMA alpha in feature scaling or use Huber loss instead of squared loss.
6. **Circular buffer overwrites without warning**: When capacity is reached, `push()` silently overwrites the oldest sample. If you need to preserve all historical data, implement external archiving (e.g., export to CSV via log.info) before buffer fills.
7. **Distance metrics do not handle missing features**: If a feature vector contains NA, distance functions return NA. The library does not impute missing values (mean, median, forward-fill). Users must handle NA via nz() or filtering before calling distance functions.
Library

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 PulseWire 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.
Library

CyberNumLib# CyberNumLib v5
CyberNumLib provides stateless numerical primitives for Pine Script traders who need advanced statistical calculations, robust normalization methods, and mathematical functions not available in PulseWire's native library.
## What it does
NumLib delivers 56 pure functions covering five categories: mathematical polyfills (hyperbolic functions, normal distribution CDF/inverse, error function), advanced smoothing filters (Ehlers Super Smoother, Butterworth, Savitzky-Golay), robust statistics (median-MAD, IQR-based scaling, Winsorized bounds), normalization methods (z-scores, percentile ranks, min-max scaling), and correlation analysis (Pearson, Spearman, Kendall, Hurst exponent). Traders use these functions to build custom indicators requiring statistical rigor beyond Pine's built-in ta.* namespace—for example, calculating confidence intervals from normal quantiles, applying outlier-resistant smoothing to noisy price data, or measuring non-linear correlation between assets.
The library outputs standardized numerical values ready for downstream indicator logic: z-scores for mean-reversion signals, normalized coefficients for ML feature engineering, correlation matrices for multi-asset analysis, and smoothed series for trend detection. All functions are stateless (no internal state variables), making them composable and predictable across different timeframes and symbols.
## How it works
NumLib implements well-documented statistical algorithms with explicit citations. The normal CDF uses the Abramowitz & Stegun 26.2.17 polynomial approximation (max error ~7e-8), while the inverse normal CDF employs the Beasley-Springer-Moro rational approximation for converting probabilities to z-scores with ~1e-10 precision—critical for quantile-based risk calculations. Hyperbolic tangent (tanh) is computed via the numerically stable identity `(e^(2x) - 1) / (e^(2x) + 1)` with argument clamping to ±20 to prevent math.exp overflow.
Smoothing filters follow Ehlers' DSP methodology: the Super Smoother is a 2-pole IIR Butterworth-equivalent with coefficients derived from `exp(-1.414π/len)`, providing lag reduction vs simple moving averages while suppressing high-frequency noise. The Savitzky-Golay filter uses fixed polynomial coefficients (order 2, length 13) for edge-preserving smoothing without phase shift.
Robust statistics leverage percentile-based methods resistant to outliers. The median-MAD estimator computes scale as `(Q75 - Q25) / 0.7413`, where 0.7413 is the IQR-to-standard-deviation conversion factor for normal distributions. Correlation functions implement textbook formulas: Pearson via covariance normalization, Spearman via rank transformation, Kendall via concordant-discordant pair counting. The Hurst exponent uses rescaled range (R/S) analysis to detect mean-reversion (H < 0.5) vs trending (H > 0.5) regimes.
## Why this is original
NumLib fills critical gaps in Pine Script's native math library. PulseWire provides no hyperbolic functions (tanh, sinh, cosh), no normal distribution quantile functions, no Savitzky-Golay smoothing, and no robust statistics beyond basic percentiles. Existing public libraries either bundle these functions with unrelated indicator logic (mixing calculation with rendering) or implement simplified versions without numerical stability guards.
This library is the only PulseWire publication offering:
- **Numerically stable implementations**: tanh with overflow clamping, normal CDF with Abramowitz-Stegun precision, inverse CDF with Beasley-Springer-Moro accuracy
- **Robust statistics suite**: median-MAD, IQR normalization, Winsorization—essential for outlier-resistant indicators in volatile markets
- **Ehlers DSP filters**: Super Smoother and Butterworth implementations with exact coefficient formulas from Ehlers' published work
- **Comprehensive correlation toolkit**: Pearson, Spearman, Kendall, plus Hurst exponent for regime detection—all in one dependency-free library
No other Pine library combines these four categories with explicit algorithm citations and edge-case handling (NA guards, zero-division checks, warmup period validation).
## How to use it
```pine
//@version=6
indicator("CyberNumLib Demo", overlay=false)
import cybermediaboy/CyberNumLib/5 as N
// Example 1: Z-score with robust median-MAD scaling
= N.f_basis_median_mad(close, 50)
plot(z_robust, "Robust Z-Score", color.blue)
// Example 2: Smooth price with Ehlers Super Smoother
smooth_close = N.f_supersmoother(close, 20)
plot(smooth_close, "Super Smooth", color.orange)
// Example 3: Calculate correlation between two assets
// (Assumes you have arrays x_data and y_data populated)
var x_arr = array.new(50)
var y_arr = array.new(50)
array.push(x_arr, close)
array.push(y_arr, volume)
if array.size(x_arr) > 50
array.shift(x_arr)
array.shift(y_arr)
corr_pearson = N.f_pearson(x_arr, y_arr, 50)
plot(corr_pearson, "Pearson Correlation", color.green)
// Example 4: Convert confidence level to z-score
conf_95 = 0.95
z_95 = N.f_norm_inv((1.0 + conf_95) / 2.0) // Returns ~1.96
plot(z_95, "95% Confidence Z", color.red)
```
## Inputs, outputs, expected behavior
**Smoothing functions** (`f_supersmoother`, `f_buttersmooth`, `f_savgol_2_13`):
- **Inputs**: `src` (float, typically close/high/low), `len` (int, window size 5-100 typical)
- **Outputs**: Smoothed float value, range matches input series
- **Edge cases**: Returns input value on first bar (no warmup), handles NA via nz()
**Statistical functions** (`f_zscore`, `f_basis_median_mad`, `f_percentile_bands`):
- **Inputs**: `src` (float series), `len` (int, minimum 10 for stability)
- **Outputs**: Z-scores (unbounded float), percentiles (price units), scale factors (positive float)
- **Edge cases**: Returns 0.0 for z-score if stdev = 0, returns NA for insufficient data (bar_index < len)
**Correlation functions** (`f_pearson`, `f_spearman`, `f_kendall`, `f_hurst_rs`):
- **Inputs**: `array` (length ≥ 10), `len` (int, sample size)
- **Outputs**: Correlation coefficient for Pearson/Spearman/Kendall, Hurst
- **Edge cases**: Returns 0.0 if array size < len, handles NA elements via filtering
**Math polyfills** (`f_tanh`, `f_norm_cdf`, `f_norm_inv`, `f_erf`):
- **Inputs**: Float values (unbounded for tanh/erf, for norm_inv, any for norm_cdf)
- **Outputs**: Bounded floats (tanh: , sigmoid: , norm_cdf: , norm_inv: unbounded)
- **Edge cases**: Clamps extreme inputs to prevent overflow (tanh at ±20, norm_inv at )
**Normalization functions** (`f_normalize`, `f_iqr_normalize`, `f_tanh_norm`):
- **Inputs**: `value` (float), `minval/maxval` (float bounds) or `len` (int window)
- **Outputs**: Normalized float in for f_normalize, for tanh-based methods
- **Edge cases**: Returns 0.0 if range is zero, handles NA inputs gracefully
## Limitations
1. **No dynamic array sizing**: Correlation functions require pre-allocated arrays of fixed size. If your data stream length varies, you must manage array resizing externally (e.g., via array.push + array.shift pattern). The library does not auto-resize or buffer data.
2. **Warmup period required**: Statistical functions (z-score, percentile bands, correlation) return unreliable values during the first `len` bars. Indicators using NumLib should display a warmup warning (e.g., "Insufficient data: need 50 bars") or gate signals until `bar_index >= len`.
3. **Precision limits on extreme inputs**: Math polyfills use polynomial approximations with documented error bounds (e.g., normal CDF ~7e-8, erf ~1.5e-7). For applications requiring higher precision (e.g., options pricing), these approximations may be insufficient. Extreme inputs (|x| > 20 for tanh, p < 1e-10 for norm_inv) are clamped to prevent overflow, which can distort tail probabilities.
4. **Correlation functions assume stationarity**: Pearson, Spearman, and Kendall correlations are computed over rolling windows without detrending. In strongly trending markets, these measures may overstate correlation due to common trend components. For non-stationary data, consider differencing the series first or using Hurst exponent to detect regime changes.
5. **No built-in significance testing**: The library returns raw correlation coefficients without p-values or confidence intervals. Traders must implement their own significance tests (e.g., t-test for Pearson correlation) or use rule-of-thumb thresholds (|r| > 0.7 for strong correlation).
6. **Single-threaded execution**: All functions execute sequentially on each bar. For indicators calling multiple NumLib functions per bar (e.g., computing 10 correlations), execution time may exceed PulseWire's script timeout on lower timeframes with large datasets. Optimize by caching results or reducing calculation frequency.
Library

CyberAssetLib# CyberAssetLib v2
CyberAssetLib provides a typed asset registry for Pine Script traders managing multi-asset indicators, offering centralized metadata for asset classes, trading hours, parent blockchains, and venue selection across spot, perpetual, and futures markets.
## What it does
CyberAssetLib delivers a single source of truth for asset metadata, replacing scattered hardcoded lookups with a structured registry. Traders use this library to build cross-asset indicators that adapt behavior based on asset type—for example, applying different volatility filters to 24/7 crypto vs 9:30-16:00 US equities, or aggregating volume across multiple venues (Binance spot + Coinbase + CME futures) with liquidity-tier weighting. The library supports symbol aliasing (e.g., "BINANCE:BTCUSDT" → "BTC"), parent chain lookups (e.g., "MATIC" → "ETH" for Polygon), and venue filtering by kind (spot/perp/fut) and liquidity tier (T1/T2/T3).
The library outputs AssetRecord structs containing asset class (CRYPTO_MAIN, ALTS, SHARES, COMMODITY, INDEX, FX), trading hours regime (24x7, 23x5, EU, US), parent chain symbol, and arrays of Venue objects with exchange, ticker, kind, and tier. Traders query the registry via canonical symbol ("BTC") or full ticker alias ("BINANCE:BTCUSDT"), receiving structured metadata for downstream logic (e.g., "if asset.hours == H_24X7, disable session filters").
## How it works
The registry uses two hash maps: `bysymbol` (canonical symbol → AssetRecord) and `byalias` (full ticker → canonical symbol). Initialization populates these maps with hardcoded entries for major assets (BTC, ETH, SOL, SPX, GOLD, etc.). The `byalias` map enables O(1) ticker normalization: "BINANCE:BTCUSDT" → "BTC", eliminating 66-iteration if-else chains from prior implementations.
Each AssetRecord stores:
- **symbol**: Canonical key (e.g., "BTC")
- **cls**: AssetClass enum (CRYPTO_MAIN, ALTS, SHARES, COMMODITY, INDEX, FX)
- **subtype**: Fine-grained label (e.g., "bitcoin", "sp500-fut", "natgas-cfd")
- **chain**: Parent L1 blockchain symbol (e.g., "ETH" for MATIC, "SOL" for BONK)
- **isl1**: Boolean flag (true if asset IS its own chain, e.g., BTC, ETH, SOL)
- **hours**: TradingHours enum (H_24X7 for crypto, H_US for NYSE, H_EU for DAX)
- **venues**: Array of Venue objects (spot, perp, fut combined)
- **aliases**: Array of full ticker strings for byalias map population
Venue objects contain:
- **ticker**: Full PulseWire ticker (e.g., "BINANCE:BTCUSDT")
- **kind**: VenueKind enum (SPOT, PERP, FUT)
- **exchange**: Exchange name (e.g., "BINANCE", "CME")
- **tier**: LiquidityTier enum (T1 for Binance/Coinbase/CME, T2 for OKX/Bybit, T3 for others)
The `f_build_venue` function auto-detects venue kind from ticker patterns: ".P" or "PERP" → PERP, "1!" or "FUT" → FUT, else SPOT. Exchange is extracted via string split on ":".
Volume aggregation uses AggregationPolicy to filter venues: `include_spot/perp/fut` (booleans), `max_tier` (1=T1 only, 3=all), `max_venues` (cap on returned venues). The VolumeAggregator struct stores selected venues with normalized weights (e.g., T1 venues get 2x weight vs T2).
## Why this is original
CyberAssetLib is the only PulseWire library providing a typed, enum-based asset registry with multi-venue support. Existing solutions use hardcoded if-else chains (unmaintainable for 100+ assets), string-based classification (error-prone, no type safety), or single-venue assumptions (ignore liquidity fragmentation across exchanges).
Unique features:
- **Enum-typed fields**: AssetClass, TradingHours, VenueKind, LiquidityTier are frozen enums (backward-compatible with kNN integer casts), preventing typos and enabling exhaustive switch statements
- **Parent chain tracking**: `chain` field links L2 tokens to L1 blockchains (e.g., MATIC → ETH), enabling cross-chain correlation analysis
- **Multi-venue aggregation**: Single asset can have 10+ venues (Binance spot, Coinbase, Kraken, CME futures, Bybit perp), with policy-based filtering and liquidity-tier weighting
- **Alias normalization**: O(1) ticker → canonical symbol lookup (e.g., "BINANCE:BTCUSDT" → "BTC"), eliminating regex parsing or 66-iteration if-else chains
- **Trading hours metadata**: Enables session-aware indicators (e.g., "disable mean-reversion signals during US market close for equities, but keep active for 24/7 crypto")
The library is designed for extensibility: adding a new asset requires one AssetRecord entry, not scattered updates across multiple functions. Enum ordering is frozen (P11 convention) to ensure backward compatibility with indicators that serialize enum values to integers for kNN training data.
## How to use it
```pine
//@version=6
indicator("CyberAssetLib Demo", overlay=false)
import cybermediaboy/CyberAssetLib/2 as AL
// Example 1: Initialize registry and lookup asset by symbol
var reg = AL.f_registry_new()
AL.f_registry_init(reg) // Populate with default assets
var btc = reg.bysymbol.get("BTC")
if not na(btc)
label.new(bar_index, high, "BTC Class: " + str.tostring(btc.cls),
color=color.blue, textcolor=color.white)
// Example 2: Normalize ticker to canonical symbol
string current_ticker = syminfo.tickerid
string canonical = reg.byalias.get(current_ticker)
if not na(canonical)
label.new(bar_index, low, "Canonical: " + canonical,
color=color.orange, textcolor=color.white)
// Example 3: Filter venues by kind (get all perpetual venues for BTC)
if not na(btc)
var perp_venues = btc.venues_of(AL.VenueKind.PERP)
if array.size(perp_venues) > 0
var first_perp = array.get(perp_venues, 0)
label.new(bar_index, close, "First Perp: " + first_perp.ticker,
color=color.green, textcolor=color.white)
// Example 4: Build volume aggregator with policy
if not na(btc)
var policy = AL.AggregationPolicy.new(
include_spot=true, include_perp=true, include_fut=false,
max_tier=2, max_venues=5)
var agg = AL.f_build_aggregator(btc, policy)
if array.size(agg.selected) > 0
string venues_str = ""
for i = 0 to math.min(array.size(agg.selected) - 1, 2)
var v = array.get(agg.selected, i)
venues_str += v.ticker + " "
label.new(bar_index, high * 1.01, "Top Venues: " + venues_str,
color=color.purple, textcolor=color.white)
// Example 5: Check trading hours and adapt indicator behavior
if not na(btc)
bool is_24x7 = btc.hours == AL.TradingHours.H_24X7
bgcolor(is_24x7 ? color.new(color.green, 90) : color.new(color.red, 90),
title="24x7 Market")
```
## Inputs, outputs, expected behavior
**Registry initialization** (`f_registry_new`, `f_registry_init`):
- **Inputs**: None (uses hardcoded asset definitions)
- **Outputs**: AssetRegistry with populated `bysymbol` and `byalias` maps
- **Edge cases**: `f_registry_init` must be called once before lookups, idempotent (safe to call multiple times)
**Asset lookup** (`bysymbol.get`, `byalias.get`):
- **Inputs**: `symbol` (string, canonical like "BTC") or `ticker` (string, full like "BINANCE:BTCUSDT")
- **Outputs**: AssetRecord or na if not found
- **Edge cases**: Returns na for unknown symbols (no silent fallback to "ETH" like prior versions), case-sensitive keys
**Venue filtering** (`venues_of`, `venues_t1`, `venues_spot`):
- **Inputs**: `rec` (AssetRecord), `kind` (VenueKind enum)
- **Outputs**: array (filtered subset)
- **Edge cases**: Returns empty array if no venues match, preserves insertion order
**Venue builder** (`f_build_venue`):
- **Inputs**: `ticker` (string, e.g., "BINANCE:BTCUSDT.P"), `tier` (LiquidityTier enum)
- **Outputs**: Venue with auto-detected kind and exchange
- **Edge cases**: Defaults to SPOT if no perp/fut pattern detected, exchange is empty string if ticker lacks ":"
**Aggregation policy** (`f_build_aggregator`, `AggregationPolicy`):
- **Inputs**: `rec` (AssetRecord), `policy` (include_spot/perp/fut bools, max_tier int, max_venues int)
- **Outputs**: VolumeAggregator with selected venues and normalized weights
- **Edge cases**: Returns empty selected array if no venues match policy, weights sum to 1.0 (or 0.0 if no venues)
**Parent chain lookup** (`rec.chain`, `rec.isl1`):
- **Inputs**: AssetRecord
- **Outputs**: `chain` (string, parent L1 symbol), `isl1` (bool, true if asset IS its own chain)
- **Edge cases**: For L1 assets (BTC, ETH, SOL), `chain == symbol` and `isl1 == true`
## Limitations
1. **Hardcoded asset list**: The library ships with ~50 pre-defined assets (major crypto, indices, commodities). Adding new assets requires library source modification and republishing. No runtime registration API exists (Pine Script limitations on dynamic map population).
2. **No real-time venue discovery**: Venue lists are static (defined at library publication). If Binance launches a new BTC perpetual contract, the library won't auto-detect it. Users must manually update the library or use custom venue builders.
3. **Liquidity tier assignments are subjective**: T1/T2/T3 classifications are based on typical volume rankings (Binance/Coinbase/CME = T1, OKX/Bybit = T2, others = T3). Actual liquidity varies by asset and time. The library does not query real-time volume data to adjust tiers.
4. **No support for exotic derivatives**: The library covers spot, perpetual, and dated futures. Options, structured products, and leveraged tokens are not classified. VenueKind.FUT assumes CME-style dated contracts, not perpetual futures with funding rates.
5. **Trading hours are regime-level, not session-precise**: `TradingHours.H_US` means "US market hours" but doesn't encode exact open/close times (9:30-16:00 ET). Indicators needing precise session boundaries must implement additional logic (e.g., via `time()` and timezone offsets).
6. **Alias map requires exact ticker match**: `byalias.get("BINANCE:BTCUSDT")` works, but `byalias.get("binance:btcusdt")` (lowercase) returns na. The library does not auto-normalize case. Use `str.upper(syminfo.tickerid)` before lookup.
7. **No FIGI or ISIN support**: The library uses PulseWire ticker strings as identifiers. Financial Instrument Global Identifiers (FIGI) or International Securities Identification Numbers (ISIN) are not supported. Cross-platform symbol mapping (e.g., Bloomberg → PulseWire) requires external tools.
8. **Parent chain field is single-valued**: Assets with multi-chain deployments (e.g., USDC on Ethereum, Solana, Polygon) store only one parent chain. The library does not model multi-chain tokens or cross-chain bridges.
Library

Library

pbkr_commonLibrary "pbkr_common"
f_clamp(v, lo, hi)
Parameters:
v (float)
lo (float)
hi (float)
f_roc(src, len)
Parameters:
src (float)
len (int)
f_dcr(h, l, c)
Parameters:
h (float)
l (float)
c (float)
f_tick(p)
Parameters:
p (float)
f_round_up(p)
Parameters:
p (float)
f_round_down(p)
Parameters:
p (float)
f_nzmax(a, b)
Parameters:
a (float)
b (float)
f_best_support(entry, a, b, c, d, e)
Parameters:
entry (float)
a (float)
b (float)
c (float)
d (float)
e (float)
f_ma_pack()
f_launch_conv(sma10, ema21, sma50, sma200, ref_price)
Parameters:
sma10 (float)
ema21 (float)
sma50 (float)
sma200 (float)
ref_price (float)
f_vol_pack()
f_vol_dryup(vol10, vol50, mult)
Parameters:
vol10 (float)
vol50 (float)
mult (float)
f_hv1(vol, vol50, mult)
Parameters:
vol (float)
vol50 (float)
mult (float)
f_pocket_pivot_vol(lookback)
Parameters:
lookback (simple int)
f_adr20()
f_tight_range(short_n, long_n, ratio)
Parameters:
short_n (int)
long_n (int)
ratio (float)
f_high_low_pack()
f_phase_code(lookback)
Parameters:
lookback (int)
f_phase_txt(phase)
Parameters:
phase (int)
f_px(v)
Parameters:
v (float)
f_pct(v)
Parameters:
v (float)
MAPack
Fields:
sma10 (series float)
ema21 (series float)
sma50 (series float)
sma150 (series float)
sma200 (series float)
VolPack
Fields:
vol50 (series float)
vol10 (series float)
vol5 (series float)
rvol (series float)
run_rate (series float)
HighLowPack
Fields:
hh52 (series float)
ll52 (series float)
off_52h_pct (series float)
off_52l_pct (series float) Library

CandlePressure_UtilitiesCandlePressure_Utilities is a lightweight Pine library for converting raw OHLC candle structure into a normalized candle-pressure score, buy/sell percentage estimates, oscillator output, and compact display helpers.
The library is designed for scripts that want a reusable candle-pressure layer without rebuilding the same CLV/body/wick math every time.
It centralizes the pieces that commonly repeat across pressure-based scripts:
• close-location value / CLV calculation
• candle body dominance
• upper-vs-lower wick imbalance
• deadzone-filtered wick pressure
• normalized pressure output from -1 to +1
• buy/sell percentage conversion
• pressure oscillator conversion from -100 to +100
• alternate body/wick buy-sell allocation
• compact volume and relative-volume formatting
• table/label size and table-position helpers
• small percent and black/white text helpers
On the example chart, the pressure candles, pressure oscillator, buy/sell split, CLV/body/wick breakdown, alternate body/wick comparison, and compact table values are all materially driven by this library.
This library is intentionally focused on pure candle structure. It does not confirm trend, detect pivots, calculate RSI/DMI/ATR context, decide trade direction, or choose final signal logic for the calling script. Those layers remain script-level decisions.
➖Quick Start➖
Import the library near the top of your script in global scope, alongside any other imports, before calling its helpers.
Typical placement:
//@version=6
indicator(...) or strategy(...)
import MYNAMEISBRANDON/CandlePressure_Utilities/1 as cp
Replace /1 with the latest published version if a newer version is available.
The main helper for most scripts is candlePressureMetrics(), which returns:
• pressure
• buyPct
• sellPct
Example:
= cp.candlePressureMetrics(
open,
high,
low,
close,
volume)
string splitText = cp.fmtBuySellSplit(
buyPct,
sellPct,
volume)
float pressureOsc = cp.pressureOsc(
pressure)
The library uses standard OHLCV argument order:
open, high, low, close, volume
➖What The Library Measures➖
The default candle-pressure model uses:
• Wick Deadzone = 0.02
• CLV Weight = 0.55
• Body Weight = 0.30
• Wick Weight = 0.15
CLV measures where the close finished inside the candle range. Body contribution measures open-to-close directional dominance. Wick contribution measures lower-wick vs upper-wick imbalance.
The final pressure score is a weighted blend of those components, normalized from -1 to +1.
That pressure score can then be converted into buy/sell percentage estimates, a -100 to +100 pressure oscillator, candle-overlay colors, table values, labels, or dashboard outputs.
➖Function Reference➖
These helpers are grouped by purpose.
Most scripts will only need:
• candlePressureMetrics()
• fmtBuySellSplit()
• pressureOsc()
More advanced scripts can use the full component helpers for tables, tooltips, debug output, or custom pressure models.
➖Model + Math Helpers➖
modelDefaults()
Returns the default candle-pressure model values used by this library.
Returns:
Wick deadzone, CLV weight, body weight, wick weight
clamp(v, lo, hi)
Restricts a value between a lower and upper bound.
Parameters:
v (float): Input value
lo (float): Lower bound
hi (float): Upper bound
Returns:
Clamped value
safeDiv(numerator, denominator, fallback)
Safely divides two values and returns the fallback when division is not valid.
Parameters:
numerator (float): Numerator value
denominator (float): Denominator value
fallback (float): Value returned when division is unsafe
Returns:
numerator / denominator, or fallback when unsafe
➖Display + UI Helpers➖
fmtCompact(val, sigFigs, naText)
Formats large values into compact display text such as 1.5k, 2.4m, or 1.2b.
Parameters:
val (float): Value to format
sigFigs (simple int): Significant figures to keep
naText (simple string): Text returned when val is na
Returns:
Compact formatted string
fmtBuySellSplit(buyPct, sellPct, volumeValue)
Formats buy/sell percentages into rounded split text such as 62/38.
Parameters:
buyPct (float): Buy percentage
sellPct (float): Sell percentage
volumeValue (float): Volume value used to handle missing or no-volume bars
Returns:
Formatted buy/sell split text
contrastText(bg)
Chooses black or white text based on background brightness.
Parameters:
bg (color): Background color
Returns:
Readable contrast text color
stripLeadingZero(txt)
Removes the leading zero from decimal text.
Parameters:
txt (string): Input text
Returns:
Adjusted text, such as 0.25 -> .25 or -0.25 -> -.25
fmtRelVol(val, naText)
Formats relative volume with two decimals and strips the leading zero.
Parameters:
val (float): Relative volume value
naText (string): Text returned when val is na
Returns:
Formatted relative-volume text
pctChange(currentValue, baseValue)
Returns the percent change from a base value.
Parameters:
currentValue (float): Current or projected value
baseValue (float): Comparison baseline
Returns:
Percent change
fmtPctWhole(val, naText)
Formats a percent value as rounded whole-percent text.
Parameters:
val (float): Percent value
naText (string): Text returned when val is na
Returns:
Rounded percent string
pctInt(pct)
Rounds and clamps a percentage into 0–100 integer form.
Parameters:
pct (float): Percent value
Returns:
Integer percent from 0 to 100
pctIntVol(pct, volumeValue)
Rounds and clamps a percentage into 0–100 integer form, returning 0 on no-volume bars.
Parameters:
pct (float): Percent value
volumeValue (float): Volume value
Returns:
Integer percent from 0 to 100
tableTextSize(sizeText)
Converts user-facing table-size text into Pine table text-size enums.
Parameters:
sizeText (string): Size text. Expected values: "Tiny", "Small", "Normal", or "Large"
Returns:
Pine table text-size enum
labelSize(sizeText)
Converts user-facing label-size text into Pine label-size enums.
Parameters:
sizeText (string): Size text. Expected values: "Tiny", "Small", "Normal", "Large", or "Huge"
Returns:
Pine label-size enum
tablePos(posText)
Converts user-facing table-position text into Pine table position enums.
Parameters:
posText (string): Table position text
Returns:
Pine table position enum
bw(useBlack)
Returns black text when the condition is true, otherwise white.
Parameters:
useBlack (bool): Whether black text should be used
Returns:
Black or white text color
➖Candle Pressure Helpers➖
candlePressurePartsFull(openValue, highValue, lowValue, closeValue, wickDeadzone, weightClv, weightBody, weightWick)
Converts OHLC candle structure into the full normalized pressure component set.
Parameters:
openValue (float): Candle open
highValue (float): Candle high
lowValue (float): Candle low
closeValue (float): Candle close
wickDeadzone (float): Wick imbalance threshold below which wick contribution is forced to 0
weightClv (float): Weight assigned to the CLV component
weightBody (float): Weight assigned to the body component
weightWick (float): Weight assigned to the wick component
Returns:
CLV, body % of range, signed body term, raw wick imbalance, deadzoned wick imbalance, final pressure
Note:
wickDeadzone, weightClv, weightBody, and weightWick are optional. If omitted, the library uses its default model:
Wick Deadzone 0.02 / CLV 0.55 / Body 0.30 / Wick 0.15
candlePressureParts(openValue, highValue, lowValue, closeValue, wickDeadzone, weightClv, weightBody, weightWick)
Converts OHLC candle structure into the compact pressure component set.
Parameters:
openValue (float): Candle open
highValue (float): Candle high
lowValue (float): Candle low
closeValue (float): Candle close
wickDeadzone (float): Wick imbalance threshold below which wick contribution is forced to 0
weightClv (float): Weight assigned to the CLV component
weightBody (float): Weight assigned to the body component
weightWick (float): Weight assigned to the wick component
Returns:
CLV, body % of range, raw wick imbalance, deadzoned wick imbalance, final pressure
Note:
wickDeadzone, weightClv, weightBody, and weightWick are optional. If omitted, the library uses its default model:
Wick Deadzone 0.02 / CLV 0.55 / Body 0.30 / Wick 0.15
pressureToBuySell(pressure, volumeValue)
Converts normalized pressure into buy/sell percentages.
Parameters:
pressure (float): Candle pressure in the -1..+1 range
volumeValue (float): Volume value used to handle missing or no-volume bars
Returns:
Buy %, Sell %
pressureOsc(pressure)
Converts normalized pressure into a -100..+100 oscillator value.
Parameters:
pressure (float): Candle pressure in the -1..+1 range
Returns:
Pressure oscillator value
candlePressureMetrics(openValue, highValue, lowValue, closeValue, volumeValue, wickDeadzone, weightClv, weightBody, weightWick)
One-call convenience wrapper for scripts that need final pressure, buy %, and sell %.
Parameters:
openValue (float): Candle open
highValue (float): Candle high
lowValue (float): Candle low
closeValue (float): Candle close
volumeValue (float): Volume value used to handle missing or no-volume bars
wickDeadzone (float): Wick imbalance threshold below which wick contribution is forced to 0
weightClv (float): Weight assigned to the CLV component
weightBody (float): Weight assigned to the body component
weightWick (float): Weight assigned to the wick component
Returns:
Pressure, Buy %, Sell %
Note:
wickDeadzone, weightClv, weightBody, and weightWick are optional. If omitted, the library uses its default model:
Wick Deadzone 0.02 / CLV 0.55 / Body 0.30 / Wick 0.15
bodyWickRateBuyPct(openValue, highValue, lowValue, closeValue)
Returns an alternate buy percentage using body/wick structure only.
Parameters:
openValue (float): Candle open
highValue (float): Candle high
lowValue (float): Candle low
closeValue (float): Candle close
Returns:
Buy percentage
bodyWickRateBuySell(openValue, highValue, lowValue, closeValue, volumeValue)
Returns alternate body/wick buy and sell percentages.
Parameters:
openValue (float): Candle open
highValue (float): Candle high
lowValue (float): Candle low
closeValue (float): Candle close
volumeValue (float): Volume value used to handle missing or no-volume bars
Returns:
Buy %, Sell %
➖Important Notes➖
Candle Pressure is not order flow.
The buy/sell split produced by this library is an estimate derived from candle structure. It is not true bid/ask volume, footprint data, or exchange-level order flow.
The pressure model is intentionally pure OHLC structure:
• CLV measures where the close finished inside the candle range.
• Body contribution measures open-to-close directional dominance.
• Wick contribution measures lower-wick vs upper-wick imbalance.
• Final pressure is a weighted blend of those components.
Momentum filters such as RSI, DMI, ATR, trend state, relative volume, or multi-timeframe context should be added by the calling script when needed.
This library provides the reusable candle-pressure foundation only.
➖Release Notes➖
v1
Initial release of CandlePressure_Utilities.
This release provides a focused candle-pressure utility layer for Pine scripts that need reusable OHLC pressure calculations, buy/sell percentage estimates, pressure oscillator output, compact display formatting, and small table/label helper functions.
Included in this release:
• default candle-pressure model values
• safe math helpers
• compact number formatting
• buy/sell split formatting
• relative-volume formatting
• table/label size and table-position helpers
• percent and bias display helpers
• full candle-pressure component output
• compact candle-pressure component output
• pressure-to-buy/sell conversion
• pressure oscillator conversion
• alternate body/wick buy-sell allocation
The library is designed to stay focused on reusable candle-pressure mechanics. It does not decide trend, trade direction, signal confirmation, pivot structure, RSI/DMI filters, ATR filters, or final color logic. Calling scripts remain responsible for their own signal model and visual interpretation.
Library

Library

GBB_lib_webhookLibrary "GBB_lib_webhook"
buildPayload(action, comment)
buildPayload
@description Builds a JSON string containing standard OHLCV market data
and a custom action label, ready to be passed to alert().
Special characters in `action` and `comment` are automatically
escaped so the resulting JSON is always valid.
Parameters:
action (string) : (string) Signal label sent in the payload. Typical values:
"BUY", "SELL", "CLOSE". Any string is accepted.
comment (string) : (string) Optional free-text field (signal name, setup
description, etc.). Defaults to an empty string.
Returns: (string) A JSON object string with the fields: action, ticker,
exchange, interval, price, open, high, low, volume, time, comment.
buildPayloadFull(action, comment, qty, sl, tp, strategy)
buildPayloadFull
@description Builds an extended JSON string that includes all standard
OHLCV fields plus position-sizing and strategy metadata.
Numeric fields (qty, sl, tp) are serialised as JSON numbers
when provided, or as JSON null when omitted (na).
String fields are escaped to ensure valid JSON output.
Parameters:
action (string) : (string) Signal label. Typical values: "BUY", "SELL", "CLOSE".
comment (string) : (string) Optional free-text description. Defaults to "".
qty (float) : (float) Position size or quantity. Pass na to omit (serialised as null).
sl (float) : (float) Stop-loss price level. Pass na to omit (serialised as null).
tp (float) : (float) Take-profit price level. Pass na to omit (serialised as null).
strategy (string) : (string) Strategy identifier (e.g. "EMA_Cross"). Defaults to "".
Returns: (string) A JSON object string with the fields: action, ticker,
exchange, interval, price, open, high, low, volume, time, comment,
qty, sl, tp, strategy.
sendSignal(condition, action, comment)
sendSignal
@description Fires a PulseWire alert containing a basic JSON payload
whenever `condition` is true. Alert frequency is set to
once_per_bar_close.
Parameters:
condition (bool) : (bool) Trigger condition.
action (string) : (string) Signal label.
comment (string) : (string) Optional description. Defaults to "".
Returns: void
sendSignalFull(condition, action, comment, qty, sl, tp, strategy)
sendSignalFull
@description Fires a PulseWire alert containing an extended JSON payload
whenever `condition` is true. Alert frequency is set to
once_per_bar_close.
Parameters:
condition (bool) : (bool) Trigger condition.
action (string) : (string) Signal label.
comment (string) : (string) Optional description. Defaults to "".
qty (float) : (float) Position size. Pass na to omit. Defaults to na.
sl (float) : (float) Stop-loss price. Pass na to omit. Defaults to na.
tp (float) : (float) Take-profit price. Pass na to omit. Defaults to na.
strategy (string) : (string) Strategy name. Defaults to "".
Returns: void Library

PickMyTradeLibLibrary "PickMyTradeLib"
PickMyTradeLib — Market Microstructure & Quantitative Finance Library for Pine Script.
Provides analytically rigorous, academically grounded functions covering five domains:
(1) Synthetic bid-ask spread estimation (Roll 1984, Corwin-Schultz 2012),
(2) Market illiquidity & price impact (Amihud 2002, Kyle 1985),
(3) OHLC-efficient volatility estimators (Garman-Klass 1980, Parkinson 1980, Rogers-Satchell 1991),
(4) Fractal & complexity measures (Higuchi 1988, Hurst R/S, Katz 1988),
(5) Realized distributional moments (skewness, excess kurtosis, realized variance).
All functions are pure Pine — no request.security calls, no external dependencies.
Compatible with any instrument and timeframe. Import with:
import PickMyTrade/PickMyTradeLib/1 as pmtq
rollSpread(src, len, zLen)
Roll's (1984) synthetic bid-ask spread estimator.
Exploits the negative serial covariance of price changes that
arises from the bid-ask bounce. Requires no order-book data.
Formula: spread = 2 * sqrt(max(0, -Cov(Δp_t, Δp_{t-1})))
Reference: Roll, R. (1984). "A Simple Implicit Measure of the
Effective Bid-Ask Spread in an Efficient Market." JoF 39(4).
Parameters:
src (float) : Price series (typically close)
len (simple int) : Lookback window for covariance estimation (minimum 10)
zLen (simple int) : Window for z-score normalisation (default = len * 3)
Returns: SpreadResult with value, zscore, and anomaly flag
corwinSchultz(h, l, zLen)
Corwin & Schultz (2012) high-low spread estimator.
Derives the effective spread from the ratio of two-day to
one-day high-low ranges. More robust than Roll on noisy series.
Reference: Corwin, S. & Schultz, P. (2012). "A Simple Way to
Estimate Bid-Ask Spreads from Daily High and Low Prices."
JoF 67(2), 719-760.
Parameters:
h (float) : High series
l (float) : Low series
zLen (simple int) : Window for z-score normalisation
Returns: SpreadResult
amihud(src, vol, len, zLen)
Amihud (2002) illiquidity ratio.
Measures how much price moves per unit of trading volume —
higher values mean illiquid markets where small trades move price.
Formula: ILLIQ_t = |r_t| / Volume_t, smoothed over len bars.
Reference: Amihud, Y. (2002). "Illiquidity and stock returns."
Journal of Financial Markets 5(1), 31-56.
Parameters:
src (float) : Price series for return calculation
vol (float) : Volume series
len (simple int) : Rolling average window
zLen (simple int) : Z-score window
Returns: SpreadResult (value = illiquidity ratio, z-scored)
kyleLambda(src, vol, len)
Kyle's Lambda — price impact coefficient (Kyle 1985).
Estimates how aggressively price responds to signed order flow.
Approximates signed volume as: buy volume when close >= open,
sell volume otherwise. Lambda = OLS slope of Δprice on signed vol.
Reference: Kyle, A.S. (1985). "Continuous Auctions and Insider
Trading." Econometrica 53(6), 1315-1335.
Parameters:
src (float) : Price series
vol (float) : Volume series
len (simple int) : Regression window (minimum 15)
Returns: SpreadResult (value = lambda slope)
garmanKlass(o, h, l, c, len)
Garman-Klass (1980) volatility estimator.
Uses OHLC data to estimate variance more efficiently than
close-to-close (theoretical efficiency ratio ≈ 7.4×).
Formula: σ² = 0.5*(ln H/L)² − (2ln2−1)*(ln C/O)²
Reference: Garman, M. & Klass, M. (1980). "On the Estimation
of Security Price Volatilities from Historical Data."
Journal of Business 53(1), 67-78.
Parameters:
o (float) : Open series
h (float) : High series
l (float) : Low series
c (float) : Close series
len (simple int) : Averaging window
Returns: VolResult with daily, annual, and rank fields
parkinson(h, l, len)
Parkinson (1980) volatility estimator.
Uses only High and Low — ignores close. More efficient than
close-to-close (theoretical efficiency ≈ 5.2×) but assumes
no overnight gaps or drift. Good intraday baseline.
Reference: Parkinson, M. (1980). "The Extreme Value Method
for Estimating the Variance of the Rate of Return."
Journal of Business 53(1), 61-65.
Parameters:
h (float) : High series
l (float) : Low series
len (simple int) : Averaging window
Returns: VolResult
rogersSatchell(o, h, l, c, len)
Rogers-Satchell (1991) volatility estimator.
Accounts for non-zero drift — unbiased even when price trends.
The only classical OHLC estimator that handles drift correctly.
Formula: σ² = ln(H/C)*ln(H/O) + ln(L/C)*ln(L/O)
Reference: Rogers, L. & Satchell, S. (1991). "Estimating
Variance From High, Low and Closing Prices."
Annals of Applied Probability 1(4), 504-512.
Parameters:
o (float) : Open series
h (float) : High series
l (float) : Low series
c (float) : Close series
len (simple int) : Averaging window
Returns: VolResult
higuchifd(src, len, kMax)
Higuchi (1988) Fractal Dimension.
Estimates the fractal complexity of a time series directly from
the data. D = 1 → perfectly smooth trend. D = 2 → pure noise.
D < 1.4: trending. 1.4-1.6: random walk. D > 1.6: mean-reverting.
This implementation uses the average of k=2..kMax curve lengths
and OLS regression of log(L_k) on log(k) to get the slope (= -FD).
Reference: Higuchi, T. (1988). "Approach to an irregular time
series on the basis of the fractal theory." Physica D 31(2).
Parameters:
src (float) : Input price series
len (simple int) : Number of bars to sample (minimum 20, recommended 30-50)
kMax (simple int) : Maximum lag (2-8; higher = more stable but slower)
Returns: FractalResult with fd, regime string, and normalised
hurstRS(src, len)
Hurst Exponent via Rescaled Range (R/S) analysis.
H > 0.55 → persistent trend-following (long memory).
H ≈ 0.50 → random walk (no memory).
H < 0.45 → mean-reverting (anti-persistent).
Note: FD and Hurst are complementary: FD = 2 - H (theoretically).
Parameters:
src (float) : Input price series
len (simple int) : Lookback length (minimum 30, recommended 60-100)
Returns: float Hurst exponent in
moments(src, len)
Rolling distributional moments of a return series.
Computes mean, standard deviation, skewness, and excess kurtosis
over a rolling window using Welford's online algorithm for
numerical stability.
Parameters:
src (float) : Input series (typically log returns: math.log(close/close ))
len (simple int) : Rolling window length
Returns: MomentResult with mean, stdev, skew, kurt
normalise(src, len)
Normalise any float series to over a rolling window.
Parameters:
src (float) : Input series
len (simple int) : Lookback for min/max
Returns: float in
ewZscore(src, len)
Exponentially weighted z-score — reacts faster than simple z-score.
Parameters:
src (float) : Input series
len (simple int) : EMA length for mean and variance estimation
Returns: float z-score
zscoreColor(z)
Colour helper — maps a z-score to a green-grey-red gradient.
z < -2: bright green (anomaly low) z > 2: bright red (anomaly high)
Parameters:
z (float) : Z-score value
Returns: color
SpreadResult
Holds a complete spread estimate result with its z-score
Fields:
value (series float) : Raw spread estimate (in price units or as ratio)
zscore (series float) : Rolling z-score of the estimate vs lookback window
isAnomaly (series bool) : True when zscore > threshold (default 2.0)
VolResult
Holds a volatility estimate with annualisation
Fields:
daily (series float) : Daily volatility estimate (fraction of price)
annual (series float) : Annualised estimate (daily * sqrt(252))
rank (series float) : 0-100 percentile rank vs lookback window
FractalResult
Fractal / complexity measurement result
Fields:
fd (series float) : Fractal Dimension value (1.0 = smooth trend, 2.0 = noise)
regime (series string) : "Trending" when fd < 1.4, "Random" 1.4–1.6, "Choppy" > 1.6
normalised (series float) : fd linearly mapped to 0.0 (trend) – 1.0 (noise)
MomentResult
Rolling moment statistics
Fields:
mean (series float) : Rolling mean
stdev (series float) : Rolling standard deviation
skew (series float) : Rolling skewness (negative = left tail)
kurt (series float) : Rolling excess kurtosis (positive = fat tails / leptokurtic) Library
