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

TR Utility Library v6 ForkTR Utility Helpers v6 Fork is an open-source Pine Script v6 compatibility fork based on the publicly available Traders_Reality_Lib originally published by TradersReality.
This publication is not the original Traders Reality library and is not presented as an official update from the original author. All original concept credit, authorship credit, and recognition for the underlying Traders Reality workflow belong to TradersReality and the original creator(s).
Original source reference:
Traders_Reality_Lib by TradersReality.
Purpose of this publication:
The purpose of this fork is to provide a Pine Script v6-compatible utility library structure for scripts that require reusable helper functions related to PVSRA-style candle classification, ADR/range calculations, session handling, labels, lines, pivots, vector candle zones, psychological levels, and market-session countdown utilities.
This is a developer utility library. It is not a standalone trading indicator, not a signal system, and not a strategy.
Main function groups:
1. PVSRA-style candle classification
The library includes helper functions for classifying candles using volume and candle-spread behavior. These functions can return candle colors, alert flags, average volume, volume-spread values, and related classification data.
2. ADR and range helpers
The library includes Average Daily Range helper functions and ADR-based high/low projection functions. These can support scripts that need daily range reference levels or range-based chart tools.
3. Session calculation utilities
The library includes functions for parsing session strings, calculating session start and end timestamps, and handling sessions that cross midnight.
4. Session drawing helpers
The library includes reusable drawing helpers for opening ranges, session highs/lows, midpoint lines, labels, and shaded session boxes.
5. Daily open and timeframe utilities
The library includes helper functions for detecting new bars on selected resolutions, retrieving the daily open, and converting price movement into pips.
6. Label, line, and pivot helpers
The library contains reusable functions for right-aligned labels, last-bar labels, dynamic horizontal lines, daily-open lines, and pivot-style chart levels.
7. Vector candle zone helpers
The library includes helper functions for creating, updating, trimming, and cleaning vector candle zone boxes.
8. Psychological level helpers
The library includes functions for calculating psychological high/low reference levels based on selected timing logic and market type.
9. Session countdown helpers
The library includes functions for formatting milliseconds into readable time strings and calculating countdown text for market-session timing.
How to use this library:
This library is intended for Pine developers who want to import reusable helper functions into their own open-source or private scripts.
Example use cases include:
* PVSRA-style candle tools
* ADR and daily range tools
* Session high/low indicators
* Opening range indicators
* Pivot and level drawing tools
* Vector candle zone tools
* Market-session countdown panels
This library does not generate buy or sell signals by itself. Any trading logic, alerts, entries, exits, or visual systems must be implemented in the script that imports this library.
Originality and reuse clarification:
This publication is primarily a compatibility fork and utility organization resource. It is not presented as a new original trading methodology.
The underlying Traders Reality concepts and original library work are credited to the original creator(s). This fork is published open-source so users can inspect the code and verify the changes.
Limitations:
This library is a developer utility and should not be interpreted as financial advice. It does not provide buy or sell recommendations, does not execute trades, and does not guarantee any trading result.
Users and developers are responsible for testing any script that imports this library and for verifying that all calculations, visual outputs, and trading decisions fit their own requirements.
Library

Library

ValidationUtilitiesValidationUtilities Library
🌸 Part of GoemonYae Trading System (GYTS) 🌸
🌸 --------- 1. INTRODUCTION --------- 🌸
💮 What Does This Library Contain?
ValidationUtilities is a centralised validation framework for Pine Script. It replaces scattered, ad-hoc input checks with a single, structured validation pass that catches every misconfiguration before a script begins operating.
The library spans the full validation workflow: framework lifecycle, configuration checks, position sizing guards, and signal completeness verification.
💮 Key Categories
The library contains:
Core Framework : the ValidationFramework UDT and its lifecycle methods (init, collect, report)
Standalone Utilities : bounded-buffer push and division-by-zero guard
Configuration Validation : range, ordering, exclusivity, lookback, source, and timeframe checks
Position Sizing & Risk : order size constraints, progressive risk alerts, allocation distribution, and Martingale safety
Signal & Timing : signal source completeness and cooldown gating
🌸 --------- 2. ADDED VALUE --------- 🌸
💮 Consistent, Readable Error Messages
Every error and warning follows the same Message format. Users see clear, categorised feedback instead of cryptic runtime error strings. A single validation pass surfaces all issues at once, so there is no need to fix one error only to hit the next on re-run.
💮 Single Import, Full Coverage
One import replaces dozens of inline validation blocks. Range checks, allocation constraints, timeframe guards, and position sizing validations are all available immediately.
💮 Errors and Warnings, Separated
Hard/soft boundary separation lets developers enforce critical constraints (errors halt execution via runtime.error() ) whilst still surfacing non-critical suggestions (warnings display as chart labels). The framework handles formatting, counting, and display.
💮 Proven in Production
ValidationUtilities underpins the validation layer of a strategy with an extensive configuration surface (12+ validated parameter groups). The methods have been refined against real misconfiguration scenarios including floating-point allocation sums, multiplier escalation, and unconnected data streams.
🌸 --------- 3. CORE FRAMEWORK --------- 🌸
💮 ValidationFramework (UDT)
The central data structure that collects validation results. It holds two string arrays, errors (critical, halt execution) and warnings (advisory, continue execution), alongside convenience flags has_errors and has_warnings .
Declare once with var , then call init() to reset state before each validation cycle:
var framework = vu.ValidationFramework.new()
framework.init()
💮 init()
Resets the framework: clears both arrays and resets flags to false . Call at the start of each validation cycle.
💮 add_error() and add_warning()
Building blocks for custom validation beyond the built-in methods. Both accept a category and message , formatting them as Message . Use add_error() for constraints that must halt execution and add_warning() for advisory messages.
framework.add_error("Position Sizing", "Order exceeds account equity.")
framework.add_warning("Risk", "Position represents 35% of equity — monitor carefully.")
💮 trigger_errors()
Fires runtime.error() with the first collected error and a count of any remaining. Always call after all validations have run so every misconfiguration is detected in a single pass.
💮 display_warnings()
Renders warnings as orange chart labels (below bar by default). Displays the first warning with a count of additional warnings, then clears state to prevent repetition. Accepts an optional yloc_arg for label placement.
↑ Runtime error dialog showing a categorised validation error with count of additional issues
↑ Warning labels displayed on the chart via display_warnings()
🌸 --------- 4. STANDALONE UTILITIES --------- 🌸
These functions are independent of the ValidationFramework and can be used anywhere.
💮 push_limited()
A FIFO bounded-buffer push: appends a value and evicts the oldest entry when the array exceeds a specified limit. Available for both float and int arrays.
vu.push_limited(price_buffer, close, 50) // Keeps the last 50 closes
💮 safe_denominator()
Returns math.max(value, floor) to guard against division by zero. Default floor is 1e-9 .
ratio = numerator / vu.safe_denominator(denominator)
🌸 --------- 5. CONFIGURATION VALIDATION --------- 🌸
These methods validate user-facing settings before a script begins operating. Each accepts the framework as self and a category string for error grouping. Refer to the source code for full parameter details.
💮 validate_range()
Checks that a value falls within hard bounds (error if violated) and optional soft bounds (warning if outside the optimal range). Supports a value_unit label for message clarity. Returns true if within hard bounds.
💮 validate_exclusive_selection()
Ensures exactly one boolean flag is active among a set of mutually exclusive options. Produces an error listing which options were found active, or that none were selected.
💮 validate_ascending_order()
Verifies that an array of values is in ascending order. Supports strict (default) or non-strict comparison. Skips na values.
💮 validate_minimum_lookback()
Checks that a lookback parameter meets a caller-derived minimum. Accepts an optional fix_hint for the error message. Returns true if met.
💮 validate_source_connected()
Detects when an input.source() has no external indicator connected (it silently defaults to close ). Uses a 2-bar close heuristic. Accepts an is_enabled flag to skip the check when the relevant feature is disabled. Returns true if the source appears connected.
💮 validate_higher_timeframe()
Validates that a user-selected timeframe is sufficiently higher than the chart timeframe. Returns the integer multiplier, useful for scaling lookback periods. Produces an error if below min_multiplier (default 1.0).
🌸 --------- 6. POSITION SIZING & RISK --------- 🌸
These methods guard against position sizing errors and excessive risk exposure. See the source code for parameter details and default thresholds.
💮 validate_order_size_constraints()
Checks a proposed order against account equity and position size limits. Errors if the order exceeds equity or a hard cap; warns if the position exceeds a configurable percentage of equity. Returns true if no errors were added.
💮 validate_multiplied_sizing_risk()
Progressive risk alerting for scripts that scale position sizes with multipliers (Martingale, Anti-Martingale, or any multiplicative sizing). Applies three escalating thresholds:
Warning (default 25%): elevated risk
Error (default 50%): high risk
Critical (default 75%): exceeds safe limits
Also warns when the multiplier itself exceeds a configurable threshold. Returns true if no errors were added.
💮 validate_martingale_settings()
Validates Martingale/Anti-Martingale parameter consistency: multiplier range, streak bounds, and maximum possible escalation. Warns when maximum escalation exceeds 100×.
💮 validate_allocations()
Validates percentage distributions (0–1 scale) for take-profit levels, portfolio weights, or any system that divides a whole into parts. Checks individual allocations and total against 1.0 with floating-point tolerance. Supports both mandatory full allocation and partial allocation.
🌸 --------- 7. SIGNAL & TIMING --------- 🌸
These methods verify signal completeness and enforce cooldown periods. See the source code for parameter details.
💮 validate_signal_configuration()
Completeness check for signal sources. Validates that an enabled signal has a connected primary data stream, a secondary stream (if required), at least one signal mapping, and activity in at least one market regime (when regime filtering is enabled).
💮 validate_timing_cooldown()
Gating check for entry timing. Verifies that enough bars have elapsed since the last relevant event and that a valid entry signal is present. Both conditions produce warnings rather than errors.
🌸 --------- 8. USAGE EXAMPLE --------- 🌸
A typical validation lifecycle: import, initialise, run validations, then trigger errors and display warnings.
import GoemonYae/ValidationUtilities/1 as vu
// Declare once, reset each bar
var framework = vu.ValidationFramework.new()
framework.init()
// Configuration validation
framework.validate_range("Config", "ATR Lookback", i_atr_lookback, 1, 500, 10, 50, "bars")
framework.validate_exclusive_selection("Distance", "TP Mode",
array.from(i_use_pct, i_use_atr, i_use_hl),
array.from("Percentage", "ATR", "High/Low"), "method")
// Allocation validation
framework.validate_allocations("TP Settings", "Take Profit",
array.from(i_tp1_alloc, i_tp2_alloc, i_tp3_alloc),
array.from("TP1", "TP2", "TP3"), true)
// Position sizing guard
framework.validate_order_size_constraints("Sizing",
order_size, close, strategy.equity, max_pos, 50.0)
// Report results
framework.trigger_errors() // Halts if any errors found
framework.display_warnings() // Shows warnings on chart
When all inputs are valid, trigger_errors() does nothing and execution continues; display_warnings() draws no labels. A correctly configured script simply runs with a clean chart.
🌸 --------- 9. PRACTICAL USAGE NOTES --------- 🌸
💮 Errors vs Warnings
Use add_error() for constraints that make the script unsafe or logically broken (missing data streams, impossible parameter combinations, equity-exceeding orders). Use add_warning() for suboptimal but non-dangerous configurations (values outside the recommended range, elevated risk percentages). Errors halt execution; warnings inform via chart labels.
💮 Single-Pass Collection
Always run all validations before calling trigger_errors() . The framework collects every error in a single pass so the user sees the total count of issues.
💮 Integration with Other GYTS Libraries
ValidationUtilities complements the GYTS library ecosystem:
FiltersToolkit : smoothing and signal processing
VolatilityToolkit : volatility estimation and regime detection
ColourUtilities : dynamic colour mapping
MathTransform : mathematical transformations and normalisation
Each library handles its own domain; ValidationUtilities handles the validation layer that sits above them.
💮 Limitations
A few constraints to keep in mind:
The validate_source_connected() heuristic (2-bar close comparison) can produce false positives if a source genuinely tracks price closely. It is a best-effort detection, not a guarantee.
Pine Script libraries cannot import other libraries. So ValidationUtilities is designed for indicators and strategies.
The framework validates configuration state, not runtime state. It catches misconfigurations at the input level; it does not monitor runtime behaviour.
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

TP_Ephem_LibLibrary "TP_Ephem_Lib"
Cowan-tailored heliocentric ephemeris (VSOP87D) for PulseWire.
@description Returns heliocentric ecliptic longitudes for Mercury through Neptune
@description (tropical or sidereal/Lahiri), synodic phases between any two planets,
@description and Cowan-canon helpers: 3-Step Astro cumulative advance (V4:L5079),
@description pentagram vertex dates (V4:L449), and cube-face boundary dates
@description (V1:L2106-2114, V1:L2962-2997). All math validated to <0.01 deg vs
@description Swiss Ephemeris (DE441) across 1899-2026. Frame: ecliptic of date.
jd_to_t_millennia(jd)
Parameters:
jd (float)
jd_from_timestamp(unix_ms)
Parameters:
unix_ms (int)
timestamp_from_jd(jd)
Parameters:
jd (float)
normalize_longitude(deg)
Parameters:
deg (float)
get_ayanamsa(jd)
Parameters:
jd (float)
get_helio_longitude(planet, jd, useSidereal)
Parameters:
planet (simple Planet)
jd (float)
useSidereal (simple bool)
get_sun_geo_longitude(jd, useSidereal)
Parameters:
jd (float)
useSidereal (simple bool)
get_synodic_phase(p1, p2, jd)
Parameters:
p1 (simple Planet)
p2 (simple Planet)
jd (float)
get_aspect_angle(p1, p2, jd)
Parameters:
p1 (simple Planet)
p2 (simple Planet)
jd (float)
average_speed_deg_per_day(planet)
Parameters:
planet (simple Planet)
speed_deg_per_day(planet, jd)
Parameters:
planet (simple Planet)
jd (float)
is_retrograde(planet, jd)
Parameters:
planet (simple Planet)
jd (float)
cumulative_advance_deg(planet, origin_jd, target_jd, useSidereal)
Parameters:
planet (simple Planet)
origin_jd (float)
target_jd (float)
useSidereal (simple bool)
cumulative_synodic_advance_deg(p1, p2, origin_jd, target_jd)
Parameters:
p1 (simple Planet)
p2 (simple Planet)
origin_jd (float)
target_jd (float)
find_advance_jd(planet, origin_jd, target_advance_deg, useSidereal)
Parameters:
planet (simple Planet)
origin_jd (float)
target_advance_deg (float)
useSidereal (simple bool)
find_synodic_advance_jd(p1, p2, origin_jd, target_synodic_advance_deg)
Parameters:
p1 (simple Planet)
p2 (simple Planet)
origin_jd (float)
target_synodic_advance_deg (float)
pentagram_vertex_jd(planet, origin_jd, n, useSidereal)
Parameters:
planet (simple Planet)
origin_jd (float)
n (simple int)
useSidereal (simple bool)
cube_face_boundary_jd(origin_jd, face_n)
Parameters:
origin_jd (float)
face_n (simple int) Library

MRScoringLibraryLibrary "MRScoringLibrary"
Mean-reversion graduated scoring: z-score any indicator into -3 to +3 integer scale.
mrScore(src, lookback, alreadyZ, invert)
Converts any continuous indicator value into a graduated
mean-reversion score from -3 (deep overbought) to +3 (deep oversold).
Parameters:
src (float) : Raw indicator value (or z-score if alreadyZ=true)
lookback (int) : Rolling lookback for z-score calc (ignored if alreadyZ=true)
alreadyZ (bool) : True if src is already a z-score — skips internal z-scoring
invert (bool) : True if HIGH indicator value = oversold (flips mapping)
Returns: Integer score: +3 to -3
zScore(src, lookback)
Returns the raw z-score without mapping to graduated scale.
Useful for plotting or custom threshold logic.
Parameters:
src (float) : Raw indicator value
lookback (int) : Rolling lookback period
Returns: Float z-score
mrScoreCustom(src, lookback, alreadyZ, invert, sd1, sd2, sd3)
Same as mrScore but with configurable SD band edges.
For indicators where standard 1/2/3 SD bands don't fit well
(e.g., an indicator only becomes useful at 1.5 SD).
Parameters:
src (float) : Raw indicator value (or z-score if alreadyZ=true)
lookback (int) : Rolling lookback for z-score calc
alreadyZ (bool) : True if src is already a z-score
invert (bool) : True if HIGH value = oversold
sd1 (float) : Inner band threshold (default would be 1.0)
sd2 (float) : Middle band threshold (default would be 2.0)
sd3 (float) : Outer band threshold (default would be 3.0)
Returns: Integer score: +3 to -3 Library

MRTestingLibraryLibrary "MRTestingLibrary"
Mean-reversion graduated scoring: z-score any indicator into -3 to +3 integer scale.
mrScore(src, lookback, alreadyZ, invert)
Converts any continuous indicator value into a graduated
mean-reversion score from -3 (deep overbought) to +3 (deep oversold).
Parameters:
src (float) : Raw indicator value (or z-score if alreadyZ=true)
lookback (int) : Rolling lookback for z-score calc (ignored if alreadyZ=true)
alreadyZ (bool) : True if src is already a z-score — skips internal z-scoring
invert (bool) : True if HIGH indicator value = oversold (flips mapping)
Returns: Integer score: +3 to -3
zScore(src, lookback)
Returns the raw z-score without mapping to graduated scale.
Useful for plotting or custom threshold logic.
Parameters:
src (float) : Raw indicator value
lookback (int) : Rolling lookback period
Returns: Float z-score
mrScoreCustom(src, lookback, alreadyZ, invert, sd1, sd2, sd3)
Same as mrScore but with configurable SD band edges.
For indicators where standard 1/2/3 SD bands don't fit well
(e.g., an indicator only becomes useful at 1.5 SD).
Parameters:
src (float) : Raw indicator value (or z-score if alreadyZ=true)
lookback (int) : Rolling lookback for z-score calc
alreadyZ (bool) : True if src is already a z-score
invert (bool) : True if HIGH value = oversold
sd1 (float) : Inner band threshold (default would be 1.0)
sd2 (float) : Middle band threshold (default would be 2.0)
sd3 (float) : Outer band threshold (default would be 3.0)
Returns: Integer score: +3 to -3 Library

Vantage_LO1_Sizing**Overview**
Position-sizing library for the LO1 breakout box day-trading strategy. Provides a unified recoup (opposite-add) sizing pipeline and dollar-risk/profit helpers. Extracting these functions into a library avoids Pine Script's function inlining, reducing compiled token count in the main strategy.
**Exported Type: RecoupSizingResult**
Holds the output of the 8-step sizing pipeline:
• Micro-level quantities (raw, DLL-capped, final)
• YM-level quantities (pre/post min-1-YM policy, proxy-capped)
• Risk gate values (projected loss, worst-case drawdown, pass/fail)
• Recoup scenario P&L (net outcome if T1 stops and recoup wins)
**Exported Functions**
`f_calcTradeRiskDollars(entry, stop, qty)` → float
Projected risk in dollars. Converts price distance to ticks via syminfo.mintick, then to dollars via syminfo.pointvalue.
`f_calcTradeProfitDollars(entry, tp, qty)` → float
Projected profit in dollars. Same tick-to-dollar conversion applied to the take-profit distance.
`f_computeRecoupSizing(...)` → RecoupSizingResult
8-step recoup sizing pipeline:
1. Raw micro qty from risk multiplier (CEILING)
2. Daily loss limit cap at micro level
3. Micro-to-YM conversion (FLOOR)
4. Minimum-1-YM policy
5. Proxy capacity cap
6. Micro-equivalent for risk gating
7. Worst-case projection (base stop + opposing flatten + recoup stop)
8. Risk gate pass/fail
Plus scenario P&L: net recoup outcome and T1-win profit.
**Usage**
import Vantage-Stack/Vantage_LO1_Sizing/1 as sz
float risk = sz.f_calcTradeRiskDollars(entry, stop, qty)
sz.RecoupSizingResult r = sz.f_computeRecoupSizing(baseQty, baseEntry, baseStop, recoupEntry, recoupStop,
recoupTP, multiplier, proxyMul, minOneYM, curLoss, maxLoss, maxProxy, t1TP, oppTP, oppFrac, oppRemoval)
======================
Library "Vantage_LO1_Sizing"
Position sizing library for LO1 breakout box strategy.
Extracts pure-computation functions to reduce compiled token count in the main script.
f_calcTradeRiskDollars(_entry, _stop, _qty)
Calculates projected risk in dollars for a position (qty × |entry−stop| in ticks × pointvalue).
Parameters:
_entry (float) : Entry price
_stop (float) : Stop-loss price
_qty (float) : Position quantity (contracts)
Returns: Risk in dollars
f_calcTradeProfitDollars(_entry, _tp, _qty)
Calculates projected profit in dollars for a position (qty × |tp−entry| in ticks × pointvalue).
Parameters:
_entry (float) : Entry price
_tp (float) : Take-profit price
_qty (float) : Position quantity (contracts)
Returns: Profit in dollars
f_computeRecoupSizing(baseQtyMicro, baseEntry, baseStop, recoupEntry, recoupStop, recoupTP, oppositeMultiplier, proxyQtyMul, minOneYMEnabled, currentLossDollars, maxDailyLossLimit, maxProxyCap, t1TPPrice, oppTPPrice, oppAddStopFrac, opposingRemovalEnabled)
Computes recoup (opposite-add) position sizing through an 8-step pipeline: raw micro qty, DLL cap, micro-to-YM conversion, min-1-YM policy, proxy cap, risk gating, worst-case projection, and recoup scenario P&L.
Parameters:
baseQtyMicro (int) : T1 micro-contract quantity
baseEntry (float) : T1 entry price
baseStop (float) : T1 stop-loss price
recoupEntry (float) : Recoup entry price
recoupStop (float) : Recoup stop-loss price
recoupTP (float) : Recoup take-profit price
oppositeMultiplier (float) : Target risk multiplier for recoup vs T1 (e.g., 4.0)
proxyQtyMul (float) : Micro-to-YM conversion factor (0 = no proxy)
minOneYMEnabled (bool) : Force minimum 1 YM contract when proxy is active
currentLossDollars (float) : Running session loss in dollars (0 for estimate mode)
maxDailyLossLimit (float) : Daily loss limit in dollars (-1 = disabled)
maxProxyCap (int) : Maximum proxy contracts cap (0 = unlimited)
t1TPPrice (float) : T1 take-profit price (for scenario P&L calculation)
oppTPPrice (float) : Opposing MYM TP price when T1 stops (for scenario profit calc)
oppAddStopFrac (float) : Fraction of base risk for opposite MYM emergency flatten
opposingRemovalEnabled (bool) : Whether opposing removal entry mode is active
Returns: RecoupSizingResult with quantities, risk values, and scenario P&L
RecoupSizingResult
Holds the complete output of the 8-step recoup sizing pipeline: micro/YM quantities, risk gate results, worst-case projections, and recoup-scenario P&L.
Fields:
microQtyRaw (series int)
microCapByDLL (series int)
microQtyCapped (series int)
ymQtyPre (series int)
ymQtyFinal (series int)
microEqForGate (series int)
projectedLossRecoup (series float)
dllRemaining (series float)
totalWorstCase (series float)
riskOK (series bool)
oppMYMLoss (series float)
didMinOneOverride (series bool)
dllForcedZero (series bool)
recoupScenarioNet (series float)
t1WinProfit (series float) Library

BASCOOL_LibBASCOOL Library v1
Range–Body Structure Analysis Toolkit for Intraday Trading
The BASCOOL Library provides high-quality, reusable Pine Script components for structural conviction analysis based purely on price action. It is designed for intraday traders who rely on volatility-adjusted range expansion and candle-body efficiency to identify strong, weak, or choppy market conditions.
Included Functions
rbm_from_ohlc() – Range–Body Measure (RBM)
A volatility-normalized structure indicator that evaluates:
Range Expansion:
Smooth EMA of (High–Low), normalized by ATR
→ captures strength of movement relative to volatility
Body Efficiency:
Body-to-Range ratio smoothed with EMA
→ measures how much of the candle’s range is “directional”
The RBM output is a smooth structural strength score typically between 0 and 1, where:
High RBM → strong structure, clean movement, trend-friendly conditions
Low RBM → compressed ranges, weak bodies, low-quality structure
Flat RBM → choppy environment, avoid directional trades Library

Input Library [1CG]Input Library (v1) – User Guide
Overview
The Input Library is a Pine Script® v6 utility library that standardizes and simplifies common user input patterns across indicators, strategies, and libraries.
It provides:
Predefined timezone enums mapped to IANA/Olson strings
24-hour and 60-minute enumerations
Standardized line styles, sizes, label styles, and box alignment options
Helper methods for converting enums into PulseWire constants
Utility functions for time formatting and span calculations
This library is designed to:
Reduce repetitive input boilerplate
Improve UI consistency across scripts
Prevent string-based input errors
Encourage clean, readable configuration logic
Library Declaration
To use the library in your script:
//@version=6
import OneCleverGuy/InputLibrary/1 as IL
Timezone Enums
Timezones
Provides a comprehensive list of IANA timezone identifiers using short, intuitive enum names.
Examples include:
utc → "UTC"
exch → Exchange timezone (syminfo.timezone)
ny → "America/New_York"
lon → "Europe/London"
tokyo → "Asia/Tokyo"
syd → "Australia/Sydney"
Method: timezoneToString()
Resolves the enum to a valid timezone string.
tzString = tzInput.timezoneToString()
Behavior:
If Timezones.exch is selected, returns syminfo.timezone
Otherwise returns the mapped IANA timezone string
Time Formatting Enums
hours
Represents 24-hour values from "00" through "23".
minutes
Represents minute values from "00" through "59".
Function: combineTime()
Combines hour and minute enums into a "HHMM" formatted string.
sessionTime = IL.combineTime(hourInput, minuteInput)
Example output:
"0930"
"1600"
Drawing Style Enums
The library standardizes visual input options and converts them into PulseWire constants.
LineStyle
solid
dotted
dashed
lArrow
rArrow
bArrow
Method: lineStyle()
lineStyleValue = styleInput.lineStyle()
LineSize
thin → 1px
normal → 2px
heavy → 3px
thick → 4px
wide → 5px
Method: lineSize()
width = sizeInput.lineSize()
TextSize
auto
tiny
small
normal
large
huge
Method: textSize()
textSizeValue = textSizeInput.textSize()
Box Alignment Enums
BoxHAlign
left
center
right
BoxVAlign
top
center
bottom
Methods:
hAlign = hAlignInput.boxHAlign()
vAlign = vAlignInput.boxVAlign()
Line Extension
LineExtend
none
right
left
both
Method: lineExtend()
extendValue = extendInput.lineExtend()
Label Styles
LabelStyle
center
down
left
right
up
lowLeft
lowRight
upperLeft
upperRight
Method: labelStyle()
labelStyleValue = labelInput.labelStyle()
String-Based Conversion Helpers
For compatibility with legacy scripts or string inputs:
lineStyleFromString()
lineSizeFromString()
These functions convert common string descriptions into valid PulseWire constants.
Timezone Offset Utility
Function: getTZOffset()
Calculates the difference between a specified timezone and UTC.
offset = IL.getTZOffset("America/New_York")
Returns:
Millisecond difference between UTC and the specified timezone
Accounts for daylight saving time
Time Span Utility
Function: timeSpan()
Converts common span names into milliseconds.
Supported values:
"Minute"
"Half Hour"
"Hour"
"4 Hours"
"8 Hours"
"12 Hours"
"Day"
"Week"
Example:
ms = IL.timeSpan("Hour")
Best Practices
Prefer enums over raw strings for safer configuration
Use conversion methods directly on enum inputs
Standardize visual settings across scripts using shared enums
Avoid hardcoding timezone strings where possible
Limitations
timeSpan() supports predefined span names only
getTZOffset() returns raw millisecond difference, not formatted hours
Library does not enforce input validation beyond enum constraints
Summary
The Input Library centralizes common input patterns into a reusable, structured framework. It improves script consistency, reduces UI friction, and ensures proper conversion between user selections and PulseWire internal constants.
Designed for Pine Script® v6. Library

Library

moving_averages# MovingAverages Library - PineScript v6
A comprehensive PineScript v6 library containing **50+ Moving Average calculations** for PulseWire.
---
## 📦 Installation
```pinescript
import TheTradingSpiderMan/moving_averages/1 as MA
```
---
## 📊 All Available Moving Averages (50+)
### Basic Moving Averages
| Function | Selector Key | Description |
| -------- | ------------ | ------------------------------------------ |
| `sma()` | `SMA` | Simple Moving Average - arithmetic mean |
| `ema()` | `EMA` | Exponential Moving Average |
| `wma()` | `WMA` | Weighted Moving Average |
| `vwma()` | `VWMA` | Volume Weighted Moving Average |
| `rma()` | `RMA` | Relative/Smoothed Moving Average |
| `smma()` | `SMMA` | Smoothed Moving Average (alias for RMA) |
| `swma()` | - | Symmetrically Weighted MA (4-period fixed) |
### Hull Family
| Function | Selector Key | Description |
| -------- | ------------ | ------------------------------- |
| `hma()` | `HMA` | Hull Moving Average |
| `ehma()` | `EHMA` | Exponential Hull Moving Average |
### Double/Triple Smoothed
| Function | Selector Key | Description |
| -------------- | ------------ | --------------------------------- |
| `dema()` | `DEMA` | Double Exponential Moving Average |
| `tema()` | `TEMA` | Triple Exponential Moving Average |
| `tma()` | `TMA` | Triangular Moving Average |
| `t3()` | `T3` | Tillson T3 Moving Average |
| `twma()` | `TWMA` | Triple Weighted Moving Average |
| `swwma()` | `SWWMA` | Smoothed Weighted Moving Average |
| `trixSmooth()` | `TRIXSMOOTH` | Triple EMA Smoothed |
### Zero/Low Lag
| Function | Selector Key | Description |
| --------- | ------------ | ----------------------------------- |
| `zlema()` | `ZLEMA` | Zero Lag Exponential MA |
| `lsma()` | `LSMA` | Least Squares Moving Average |
| `epma()` | `EPMA` | Endpoint Moving Average |
| `ilrs()` | `ILRS` | Integral of Linear Regression Slope |
### Adaptive Moving Averages
| Function | Selector Key | Description |
| ---------- | ------------ | ------------------------------- |
| `kama()` | `KAMA` | Kaufman Adaptive Moving Average |
| `frama()` | `FRAMA` | Fractal Adaptive Moving Average |
| `vidya()` | `VIDYA` | Variable Index Dynamic Average |
| `vma()` | `VMA` | Variable Moving Average |
| `vama()` | `VAMA` | Volume Adjusted Moving Average |
| `rvma()` | `RVMA` | Rolling VMA |
| `apexMA()` | `APEXMA` | Apex Moving Average |
### Ehlers Filters
| Function | Selector Key | Description |
| ----------------- | --------------- | --------------------------------- |
| `superSmoother()` | `SUPERSMOOTHER` | Ehlers Super Smoother |
| `butterworth2()` | `BUTTERWORTH2` | 2-Pole Butterworth Filter |
| `butterworth3()` | `BUTTERWORTH3` | 3-Pole Butterworth Filter |
| `instantTrend()` | `INSTANTTREND` | Ehlers Instantaneous Trendline |
| `edsma()` | `EDSMA` | Deviation Scaled Moving Average |
| `mama()` | `MAMA` | Mesa Adaptive Moving Average |
| `fama()` | `FAMAVAL` | Following Adaptive Moving Average |
### Laguerre Family
| Function | Selector Key | Description |
| -------------------- | ------------------ | ------------------------ |
| `laguerreFilter()` | `LAGUERRE` | Laguerre Filter |
| `adaptiveLaguerre()` | `ADAPTIVELAGUERRE` | Adaptive Laguerre Filter |
### Special Weighted
| Function | Selector Key | Description |
| ---------- | ------------ | -------------------------------- |
| `alma()` | `ALMA` | Arnaud Legoux Moving Average |
| `sinwma()` | `SINWMA` | Sine Weighted Moving Average |
| `gwma()` | `GWMA` | Gaussian Weighted Moving Average |
| `nma()` | `NMA` | Natural Moving Average |
### Jurik/McGinley/Coral
| Function | Selector Key | Description |
| ------------ | ------------ | --------------------- |
| `jma()` | `JMA` | Jurik Moving Average |
| `mcginley()` | `MCGINLEY` | McGinley Dynamic |
| `coral()` | `CORAL` | Coral Trend Indicator |
### Mean Types
| Function | Selector Key | Description |
| -------------- | ------------ | ------------------------- |
| `medianMA()` | `MEDIANMA` | Median Moving Average |
| `gma()` | `GMA` | Geometric Moving Average |
| `harmonicMA()` | `HARMONICMA` | Harmonic Moving Average |
| `trimmedMA()` | `TRIMMEDMA` | Trimmed Moving Average |
| `cma()` | `CMA` | Cumulative Moving Average |
### Volume-Based
| Function | Selector Key | Description |
| --------- | ------------ | -------------------------- |
| `evwma()` | `EVWMA` | Elastic Volume Weighted MA |
### Other Specialized
| Function | Selector Key | Description |
| ----------------- | --------------- | --------------------------- |
| `hwma()` | `HWMA` | Holt-Winters Moving Average |
| `gdema()` | `GDEMA` | Generalized DEMA |
| `rema()` | `REMA` | Regularized EMA |
| `modularFilter()` | `MODULARFILTER` | Modular Filter |
| `rmt()` | `RMT` | Recursive Moving Trendline |
| `qrma()` | `QRMA` | Quadratic Regression MA |
| `wilderSmooth()` | `WILDERSMOOTH` | Welles Wilder Smoothing |
| `leoMA()` | `LEOMA` | Leo Moving Average |
| `ahrensMA()` | `AHRENSMA` | Ahrens Moving Average |
| `runningMA()` | `RUNNINGMA` | Running Moving Average |
| `ppoMA()` | `PPOMA` | PPO-based Moving Average |
| `fisherMA()` | `FISHERMA` | Fisher Transform MA |
---
## 🎯 Helper Functions
| Function | Description |
| ---------------- | ------------------------------------------------------------- |
| `wcp()` | Weighted Close Price: (H+L+2\*C)/4 |
| `typicalPrice()` | Typical Price: (H+L+C)/3 |
| `medianPrice()` | Median Price: (H+L)/2 |
| `selector()` | **Master selector** - choose any MA by string name |
| `getAllTypes()` | Returns all supported MA type names as comma-separated string |
---
## 🔧 Usage Examples
### Basic Usage
```pinescript
//@version=6
indicator("MA Example")
import quantablex/moving_averages/1 as MA
// Simple calls
plot(MA.sma(close, 20), "SMA 20", color.blue)
plot(MA.ema(close, 20), "EMA 20", color.red)
plot(MA.hma(close, 20), "HMA 20", color.green)
```
### Using the Selector Function (50+ MA Types)
```pinescript
//@version=6
indicator("MA Selector")
import quantablex/moving_averages/1 as MA
// Full list of all supported types:
// SMA,EMA,WMA,VWMA,RMA,SMMA,HMA,EHMA,DEMA,TEMA,TMA,T3,TWMA,SWWMA,TRIXSMOOTH,
// ZLEMA,LSMA,EPMA,ILRS,KAMA,FRAMA,VIDYA,VMA,VAMA,RVMA,APEXMA,SUPERSMOOTHER,
// BUTTERWORTH2,BUTTERWORTH3,INSTANTTREND,EDSMA,LAGUERRE,ADAPTIVELAGUERRE,
// ALMA,SINWMA,GWMA,NMA,JMA,MCGINLEY,CORAL,MEDIANMA,GMA,HARMONICMA,TRIMMEDMA,
// EVWMA,HWMA,GDEMA,REMA,MODULARFILTER,RMT,QRMA,WILDERSMOOTH,LEOMA,AHRENSMA,
// RUNNINGMA,PPOMA,MAMA,FAMAVAL,FISHERMA,CMA
maType = input.string("EMA", "MA Type", options= )
length = input.int(20, "Length")
plot(MA.selector(close, length, maType), "Selected MA", color.orange)
```
### Advanced Moving Averages
```pinescript
//@version=6
indicator("Advanced MAs")
import quantablex/moving_averages/1 as MA
// ALMA with custom offset and sigma
plot(MA.alma(close, 20, 0.85, 6), "ALMA", color.purple)
// KAMA with custom fast/slow periods
plot(MA.kama(close, 10, 2, 30), "KAMA", color.teal)
// T3 with custom volume factor
plot(MA.t3(close, 20, 0.7), "T3", color.yellow)
// Laguerre Filter with custom gamma
plot(MA.laguerreFilter(close, 0.8), "Laguerre", color.lime)
```
---
## 📈 MA Selection Guide
| Use Case | Recommended MAs |
| ---------------------- | ------------------------------------------- |
| **Trend Following** | EMA, DEMA, TEMA, HMA, CORAL |
| **Low Lag Required** | ZLEMA, HMA, EHMA, JMA, LSMA |
| **Volatile Markets** | KAMA, VIDYA, FRAMA, VMA, ADAPTIVELAGUERRE |
| **Smooth Signals** | T3, LAGUERRE, SUPERSMOOTHER, BUTTERWORTH2/3 |
| **Support/Resistance** | SMA, WMA, TMA, MEDIANMA |
| **Scalping** | MCGINLEY, ZLEMA, HMA, INSTANTTREND |
| **Noise Reduction** | MAMA, EDSMA, GWMA, TRIMMEDMA |
| **Volume-Based** | VWMA, EVWMA, VAMA |
---
## ⚙️ Parameters Reference
### Common Parameters
- `src` - Source series (close, open, hl2, hlc3, etc.)
- `len` - Period length (integer)
### Special Parameters
- `alma()`: `offset` (0-1), `sigma` (curve shape)
- `kama()`: `fastLen`, `slowLen`
- `t3()`: `vFactor` (volume factor)
- `jma()`: `phase` (-100 to 100)
- `laguerreFilter()`: `gamma` (0-1 damping)
- `rema()`: `lambda` (regularization)
- `modularFilter()`: `beta` (sensitivity)
- `gdema()`: `mult` (multiplier, 2 = standard DEMA)
- `trimmedMA()`: `trimPct` (0-0.5, percentage to trim)
- `mama()/fama()`: `fastLimit`, `slowLimit`
- `adaptiveLaguerre()`: Uses `len` for adaptation period
---
## 📝 Notes
- All 50+ functions are exported for use in any PineScript v6 indicator/strategy
- The `selector()` function supports **all MA types** via string key
- Use `getAllTypes()` to get a comma-separated list of all supported MA names
- Some MAs (CMA, INSTANTTREND, LAGUERRE, MAMA) don't use `len` parameter
- Use `nz()` wrapper if handling potential NA values in your calculations
---
**Author:** thetradingspiderman
**Version:** 1.0
**PineScript Version:** 6
**Total MA Types:** 50+
Library

ArgentinaBondsLib - Argentina Sovereign Bonds Cashflow LibraryArgentinaBondsLib
A Pine Script v6 library providing cashflow data and financial calculation functions for Argentine sovereign bonds (Bonares and Globales).
## Supported Bonds
**Bonares** (Argentina legislation, USD MEP): AE38, AL29, AL30, AL35, AL41, AN29
**Globales** (Foreign legislation, USD Cable): GD29, GD30, GD35, GD38, GD41, GD46
## Exported Functions
### Cashflow Data
- `getCashflows_ ()` - Returns timestamps, cashflows, and count for each bond
### Bond Identification
- `getBondType(ticker)` - Returns BONAR() or GLOBAL()
- `getBaseTicker(ticker)` - Extracts base ticker without prefix/suffix
- `getCurrencyType(ticker)` - Returns 0=ARS, 1=MEP, 2=Cable
- `isSupported(baseTicker)` - Checks if bond is supported
### Financial Calculations
- `calcPV()` - Present Value calculation
- `calcIRR()` - Internal Rate of Return using Newton-Raphson method
- `calcPriceFromIRR()` - Calculate price from target IRR
### Currency Conversion
- `convertToNativeCurrency()` - Converts price to cashflow currency (MEP for Bonares, Cable for Globales)
### Utilities
- `getSettlementDate()` - Returns T+1 timestamp
- `BONAR()` / `GLOBAL()` - Bond type constants
## Methodology
- Day count convention: Actual/365
- Settlement: T+1
- IRR solver: Newton-Raphson iterative method
## Usage Example
```
import EcoValores/ArgentinaBondsLib/1 as Bonds
= Bonds.getCashflows_AL30()
settlementDate = Bonds.getSettlementDate()
irr = Bonds.calcIRR(ts, cf, count, settlementDate, close)
```
---
## Español
Librería Pine Script v6 con datos de flujos de fondos y funciones de cálculo financiero para bonos soberanos argentinos.
### Bonos Soportados
- **Bonares** (Legislación argentina, USD MEP): AE38, AL29, AL30, AL35, AL41, AN29
- **Globales** (Legislación extranjera, USD Cable): GD29, GD30, GD35, GD38, GD41, GD46
### Metodología
- Convención de días: Actual/365
- Liquidación: T+1
- Solver TIR: Método iterativo Newton-Raphson
---
**DISCLAIMER**: This library is for informational and educational purposes only. Eco Valores S.A. does NOT provide investment advice or recommendations. Consult a qualified financial advisor before making investment decisions.
**AVISO LEGAL**: Esta librería es solo para fines informativos y educativos. Eco Valores S.A. NO brinda asesoramiento ni recomendaciones de inversión. Consulte con un asesor financiero calificado antes de invertir.
Library

Library

Library

Library

Library

Library

PriceFormatLibrary for automatically converting price values to formatted strings
matching the same format that PulseWire uses to display open/high/low/close prices on the chart.
█ OVERVIEW
This library is intended for Pine Coders who are authors of scripts that display numbers onto a user's charts. Typically, 𝚜𝚝𝚛.𝚝𝚘𝚜𝚝𝚛𝚒𝚗𝚐() would be used to convert a number into a string which can be displayed in a label / box / table, but this only works well for values that are formatted as a simple decimal number. The purpose of this library is to provide an easy way to create a formatted string for values which use other types of formats besides the decimal format.
The main functions exported by this library are:
𝚏𝚘𝚛𝚖𝚊𝚝𝙿𝚛𝚒𝚌𝚎() - creates a formatted string from a price value
𝚖𝚎𝚊𝚜𝚞𝚛𝚎𝙿𝚛𝚒𝚌𝚎𝙲𝚑𝚊𝚗𝚐𝚎() - creates a formatted string from the distance between two prices
𝚝𝚘𝚜𝚝𝚛𝚒𝚗𝚐() - an alternative to the built-in 𝚜𝚝𝚛.𝚝𝚘𝚜𝚝𝚛𝚒𝚗𝚐(𝚟𝚊𝚕𝚞𝚎, 𝚏𝚘𝚛𝚖𝚊𝚝)
This library also exports some auxiliary functions which are used under the hood of the previously mentioned functions, but can also be useful to Pine Coders that need fine-tuned control for customized formatting of numeric values:
Functions that determine information about the current chart:
𝚒𝚜𝙵𝚛𝚊𝚌𝚝𝚒𝚘𝚗𝚊𝚕𝙵𝚘𝚛𝚖𝚊𝚝(), 𝚒𝚜𝚅𝚘𝚕𝚞𝚖𝚎𝙵𝚘𝚛𝚖𝚊𝚝(), 𝚒𝚜𝙿𝚎𝚛𝚌𝚎𝚗𝚝𝚊𝚐𝚎𝙵𝚘𝚛𝚖𝚊𝚝(), 𝚒𝚜𝙳𝚎𝚌𝚒𝚖𝚊𝚕𝙵𝚘𝚛𝚖𝚊𝚝(), 𝚒𝚜𝙿𝚒𝚙𝚜𝙵𝚘𝚛𝚖𝚊𝚝()
Functions that convert a 𝚏𝚕𝚘𝚊𝚝 value to a formatted string:
𝚊𝚜𝙳𝚎𝚌𝚒𝚖𝚊𝚕(), 𝚊𝚜𝙿𝚒𝚙𝚜(), 𝚊𝚜𝙵𝚛𝚊𝚌𝚝𝚒𝚘𝚗𝚊𝚕(), 𝚊𝚜𝚅𝚘𝚕𝚞𝚖𝚎()
█ EXAMPLES
• Simple Example
This example shows the simplest way to utilize this library.
//@version=6
indicator("Simple Example")
import n00btraders/PriceFormat/1
var table t = table.new(position.middle_right, 2, 1, bgcolor = color.new(color.blue, 90), force_overlay = true)
if barstate.isfirst
table.cell(t, 0, 0, "Current Price: ", text_color = color.black, text_size = 40)
table.cell(t, 1, 0, text_color = color.blue, text_size = 40)
if barstate.islast
string lastPrice = close.formatPrice() // Simple, easy way to format price
table.cell_set_text(t, 1, 0, lastPrice)
• Complex Example
This example calls all of the main functions and uses their optional arguments.
//@version=6
indicator("Complex Example")
import n00btraders/PriceFormat/1
// Enum values that can be used as optional arguments
precision = input.enum(PriceFormat.Precision.DEFAULT)
language = input.enum(PriceFormat.Language.ENGLISH)
// Main library functions used to create formatted strings
string formattedOpen = open.formatPrice(precision, language, allowPips = true)
string rawOpenPrice = PriceFormat.tostring(open, format.price)
string formattedClose = close.formatPrice(precision, language, allowPips = true)
string rawClosePrice = PriceFormat.tostring(close, format.price)
= PriceFormat.measurePriceChange(open, close, precision, language, allowPips = true)
// Labels to display formatted values on chart
string prices = str.format("Open: {0} ({1}) Close: {2} ({3})", formattedOpen, rawOpenPrice, formattedClose, rawClosePrice)
string change = str.format("Change (close - open): {0} / {1}", distance, ticks)
label.new(chart.point.now(high), prices, yloc = yloc.abovebar, textalign = text.align_left, force_overlay = true)
label.new(chart.point.now(low), change, yloc = yloc.belowbar, style = label.style_label_up, force_overlay = true)
█ NOTES
• Function Descriptions
The library source code uses Markdown for the exported functions. Hover over a function/method call in the Pine Editor to display formatted, detailed information about the function/method.
• Precision Settings
The Precision option in the chart settings can change the format of how prices are displayed on the chart. Since the user's selected choice cannot be known through any Pine built-in variable, this library provides a 𝙿𝚛𝚎𝚌𝚒𝚜𝚒𝚘𝚗 enum that can be used as an optional script input for the user to specify their selected choice.
• Language Settings
The Language option in the user menu can change the decimal/grouping separators in the prices that are displayed on the chart. Since the user's selected choice cannot be known through any Pine built-in variable, this library provides a 𝙻𝚊𝚗𝚐𝚞𝚊𝚐𝚎 enum that can be used as an optional script input for the user to specify their selected choice.
█ EXPORTED FUNCTIONS
method formatPrice(price, precision, language, allowPips)
Formats a price value to match how it would be displayed on the user's current chart.
Namespace types: series float, simple float, input float, const float
Parameters:
price (float) : The value to format.
precision (series Precision) : A Precision.* enum value.
language (series Language) : A Language.* enum value.
allowPips (simple bool) : Whether to allow decimal numbers to display as pips.
Returns: Automatically formatted price string.
measurePriceChange(startPrice, endPrice, precision, language, allowPips)
Measures a change in price in terms of both distance and ticks.
Parameters:
startPrice (float) : The starting price.
endPrice (float) : The ending price.
precision (series Precision) : A Precision.* enum value.
language (series Language) : A Language.* enum value.
allowPips (simple bool) : Whether to allow decimal numbers to display as pips.
Returns: A tuple of formatted strings: .
method tostring(value, format)
Alternative to the Pine `str.tostring(value, format)` built-in function.
Namespace types: series float, simple float, input float, const float
Parameters:
value (float) : (series float) The value to format.
format (string) : (series string) The format string.
Returns: String in the specified format.
isFractionalFormat()
Determines if the default behavior of the chart's price scale is to use a fractional format.
Returns: True if the chart can display prices in fractional format.
isVolumeFormat()
Determines if the default behavior of the chart's price scale is to display prices as volume.
Returns: True if the chart can display prices as volume.
isPercentageFormat()
Determines if the default behavior of the chart's price scale is to display percentages.
Returns: True if the chart can display prices as percentages.
isDecimalFormat()
Determines if the default behavior of the chart's price scale is to use a decimal format.
Returns: True if the chart can display prices in decimal format.
isPipsFormat()
Determines if the current symbol's prices can be displayed as pips.
Returns: True if the chart can display prices as pips.
method asDecimal(value, precision, minTick, decimalSeparator, groupingSeparator, eNotation)
Converts a number to a string in decimal format.
Namespace types: series float, simple float, input float, const float
Parameters:
value (float) : The value to format.
precision (int) : Number of decimal places.
minTick (float) : Minimum tick size.
decimalSeparator (string) : The decimal separator.
groupingSeparator (string) : The thousands separator, aka digit group separator.
eNotation (bool) : Whether the result should use E notation.
Returns: String in decimal format.
method asPips(value, priceScale, minMove, minMove2, decimalSeparator, groupingSeparator)
Converts a number to a string in decimal format with the last digit replaced by a superscript.
Namespace types: series float, simple float, input float, const float
Parameters:
value (float) : The value to format.
priceScale (int) : Price scale.
minMove (int) : Min move.
minMove2 (int) : Min move 2.
decimalSeparator (string) : The decimal separator.
groupingSeparator (string) : The thousands separator, aka digit group separator.
Returns: String in decimal format with an emphasis on the pip value.
method asFractional(value, priceScale, minMove, minMove2, fractionalSeparator1, fractionalSeparator2)
Converts a number to a string in fractional format.
Namespace types: series float, simple float, input float, const float
Parameters:
value (float) : The value to format.
priceScale (int) : Price scale.
minMove (int) : Min move.
minMove2 (int) : Min move 2.
fractionalSeparator1 (string) : The primary fractional separator.
fractionalSeparator2 (string) : The secondary fractional separator.
Returns: String in fractional format.
method asVolume(value, precision, minTick, decimalSeparator, groupingSeparator, spacing)
Converts a number to a string in volume format.
Namespace types: series float, simple float, input float, const float
Parameters:
value (float) : The value to format.
precision (int) : Maximum number of decimal places.
minTick (float) : Minimum tick size.
decimalSeparator (string) : The decimal separator.
groupingSeparator (string) : The thousands separator, aka digit group separator.
spacing (string) : The whitespace separator.
Returns: String in volume format. Library

AlgebraGeometryLabLibrary "AlgebraGeometryLab"
Algebra & 2D geometry utilities absent from Pine built-ins.
Rigorous, no-repaint, export-ready: vectors, robust roots, linear solvers, 2x2/3x3 det/inverse,
symmetric 2x2 eigensystem, orthogonal regression (TLS), affine transforms, intersections,
distances, projections, polygon metrics, point-in-polygon, convex hull (monotone chain),
Bezier/Catmull-Rom/Barycentric tools.
clamp(x, lo, hi)
clamp to
Parameters:
x (float)
lo (float)
hi (float)
near(a, b, atol, rtol)
approximately equal with relative+absolute tolerance
Parameters:
a (float)
b (float)
atol (float)
rtol (float)
sgn(x)
sign as {-1,0,1}
Parameters:
x (float)
hypot(x, y)
stable hypot (sqrt(x^2+y^2))
Parameters:
x (float)
y (float)
method length(v)
Namespace types: Vec2
Parameters:
v (Vec2)
method length2(v)
Namespace types: Vec2
Parameters:
v (Vec2)
method normalized(v)
Namespace types: Vec2
Parameters:
v (Vec2)
method add(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method sub(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method muls(v, s)
Namespace types: Vec2
Parameters:
v (Vec2)
s (float)
method dot(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method crossz(a, b)
Namespace types: Vec2
Parameters:
a (Vec2)
b (Vec2)
method rotate(v, ang)
Namespace types: Vec2
Parameters:
v (Vec2)
ang (float)
method apply(v, T)
Namespace types: Vec2
Parameters:
v (Vec2)
T (Affine2)
affine_identity()
identity transform
affine_translate(tx, ty)
translation
Parameters:
tx (float)
ty (float)
affine_rotate(ang)
rotation about origin
Parameters:
ang (float)
affine_scale(sx, sy)
scaling about origin
Parameters:
sx (float)
sy (float)
affine_rotate_about(ang, px, py)
rotation about pivot (px,py)
Parameters:
ang (float)
px (float)
py (float)
affine_compose(T2, T1)
compose T2∘T1 (apply T1 then T2)
Parameters:
T2 (Affine2)
T1 (Affine2)
quadratic_roots(a, b, c)
Real roots of ax^2 + bx + c = 0 (numerically stable)
Parameters:
a (float)
b (float)
c (float)
Returns: with n∈{0,1,2}; r1<=r2 when n=2.
cubic_roots(a, b, c, d)
Real roots of ax^3+bx^2+cx+d=0 (Cardano; returns up to 3 real roots)
Parameters:
a (float)
b (float)
c (float)
d (float)
Returns: (valid r2/r3 only if n>=2/n>=3)
det2(a, b, c, d)
det2 of
Parameters:
a (float)
b (float)
c (float)
d (float)
inv2(a, b, c, d)
inverse of 2x2; returns
Parameters:
a (float)
b (float)
c (float)
d (float)
solve2(a, b, c, d, e, f)
solve 2x2 * = via Cramer
Parameters:
a (float)
b (float)
c (float)
d (float)
e (float)
f (float)
det3(a11, a12, a13, a21, a22, a23, a31, a32, a33)
det3 of 3x3
Parameters:
a11 (float)
a12 (float)
a13 (float)
a21 (float)
a22 (float)
a23 (float)
a31 (float)
a32 (float)
a33 (float)
inv3(a11, a12, a13, a21, a22, a23, a31, a32, a33)
inverse 3x3; returns
Parameters:
a11 (float)
a12 (float)
a13 (float)
a21 (float)
a22 (float)
a23 (float)
a31 (float)
a32 (float)
a33 (float)
eig2_symmetric(a, b, d)
symmetric 2x2 eigensystem: [ , ]
Parameters:
a (float)
b (float)
d (float)
Returns: with unit eigenvectors
tls_line(xs, ys)
Orthogonal (total least squares) regression line through point cloud
Input arrays must be same length N>=2. Returns line in normal form n•x + c = 0
Parameters:
xs (array)
ys (array)
Returns: where (nx,ny) unit normal; (cx,cy) centroid.
orient(a, b, c)
orientation (signed area*2): >0 CCW, <0 CW, 0 collinear
Parameters:
a (Vec2)
b (Vec2)
c (Vec2)
project_point_line(p, a, d)
project point p onto infinite line through a with direction d
Parameters:
p (Vec2)
a (Vec2)
d (Vec2)
Returns: where proj = a + t*d
closest_point_segment(p, a, b)
closest point on segment to p
Parameters:
p (Vec2)
a (Vec2)
b (Vec2)
Returns: where t∈ on segment
dist_point_line(p, a, d)
distance from point to line (infinite)
Parameters:
p (Vec2)
a (Vec2)
d (Vec2)
dist_point_segment(p, a, b)
distance from point to segment
Parameters:
p (Vec2)
a (Vec2)
b (Vec2)
intersect_lines(p1, d1, p2, d2)
line-line intersection: L1: p1+d1*t, L2: p2+d2*u
Parameters:
p1 (Vec2)
d1 (Vec2)
p2 (Vec2)
d2 (Vec2)
Returns:
intersect_segments(s1, s2)
segment-segment intersection (closed segments)
Parameters:
s1 (Segment2)
s2 (Segment2)
Returns: where kind: 0=no, 1=proper point, 2=overlap (ix/iy=na)
circumcircle(a, b, c)
circle through 3 non-collinear points
Parameters:
a (Vec2)
b (Vec2)
c (Vec2)
intersect_circle_line(C, p, d)
intersections of circle and line (param p + d t)
Parameters:
C (Circle2)
p (Vec2)
d (Vec2)
Returns: with n∈{0,1,2}
intersect_circles(A, B)
circle-circle intersection
Parameters:
A (Circle2)
B (Circle2)
Returns: with n∈{0,1,2}
polygon_area(xs, ys)
signed area (shoelace). Positive if CCW.
Parameters:
xs (array)
ys (array)
polygon_centroid(xs, ys)
polygon centroid (for non-self-intersecting). Fallback to vertex mean if area≈0.
Parameters:
xs (array)
ys (array)
point_in_polygon(px, py, xs, ys)
point-in-polygon test (ray casting). Returns true if inside; boundary counts as inside.
Parameters:
px (float)
py (float)
xs (array)
ys (array)
convex_hull(xs, ys)
convex hull (monotone chain). Returns array of hull vertex indices in CCW order.
Uses array.sort_indices(xs) (ascending by x). Ties on x are handled; result is deterministic.
Parameters:
xs (array)
ys (array)
lerp(a, b, t)
linear interpolate between a and b
Parameters:
a (float)
b (float)
t (float)
bezier2(p0, p1, p2, t)
quadratic Bezier B(t) for points p0,p1,p2
Parameters:
p0 (Vec2)
p1 (Vec2)
p2 (Vec2)
t (float)
bezier3(p0, p1, p2, p3, t)
cubic Bezier B(t) for p0,p1,p2,p3
Parameters:
p0 (Vec2)
p1 (Vec2)
p2 (Vec2)
p3 (Vec2)
t (float)
catmull_rom(p0, p1, p2, p3, t, alpha)
Catmull-Rom interpolation (centripetal form when alpha=0.5)
t∈ , returns point between p1 and p2
Parameters:
p0 (Vec2)
p1 (Vec2)
p2 (Vec2)
p3 (Vec2)
t (float)
alpha (float)
barycentric(A, B, C, P)
barycentric coordinates of P wrt triangle ABC
Parameters:
A (Vec2)
B (Vec2)
C (Vec2)
P (Vec2)
Returns:
point_in_triangle(A, B, C, P)
point-in-triangle using barycentric (boundary included)
Parameters:
A (Vec2)
B (Vec2)
C (Vec2)
P (Vec2)
Vec2
Fields:
x (series float)
y (series float)
Line2
Fields:
p (Vec2)
d (Vec2)
Segment2
Fields:
a (Vec2)
b (Vec2)
Circle2
Fields:
c (Vec2)
r (series float)
Affine2
Fields:
a (series float)
b (series float)
c (series float)
d (series float)
tx (series float)
ty (series float) Library

Library

Library
