PINE LIBRARY
Mis à jour

ValidationUtilities

412
ValidationUtilities 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 [Category] 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:
Pine Script®

💮 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 [Category] Message. Use add_error() for constraints that must halt execution and add_warning() for advisory messages.
Pine Script®

💮 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.

snapshot↑ Runtime error dialog showing a categorised validation error with count of additional issues

snapshot↑ 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.
Pine Script®

💮 safe_denominator()

Returns math.max(value, floor) to guard against division by zero. Default floor is 1e-9.
Pine Script®

🌸 --------- 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.
Pine Script®

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:
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.
Notes de version
v2

Major
  • Added render_banner() — a reusable rich, click-free status banner primitive. Draws a 1-column, 2-row table (bold title row plus a left-aligned body row) with a dark-mode-aware default background. This is the preferred surface for open-ended configuration errors and no-trades diagnostics, replacing the single-string runtime.error halt of trigger_errors() and the first-only "+N more" label of display_warnings().
  • Added issues_as_text() method — joins a framework's collected items into one body string ("✕ [cat] msg" for errors, "⚠ [cat] msg" for warnings), for use as a render_banner() body or a log line.

Minor
  • Added VERSION constant for programmatic version checking.
  • trigger_errors() and display_warnings() doc comments now point to render_banner() as the preferred surface. Both remain unchanged for back-compatibility and existing import …/1 pins.
  • Library chart demo now showcases render_banner() + issues_as_text() instead of the lone display_warnings() label.

Clause de non-responsabilité

Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.