PINE LIBRARY

LibProf

142
Library "LibProf"
Core Profiling Library.
This library provides a generic, object-oriented framework for
creating, managing, and analyzing 1D distributions (profiles) on
a customizable coordinate grid.

Unlike traditional Volume Profile libraries, `LibProf` is designed
as a **neutral Engine**. It abstracts away specific concepts
like "Price" or "Volume" in favor of mathematical primitives
("Level" and "Mass"). This allows developers to profile *any*
data series, such as Time-at-Price, Velocity, Delta, or Ticks.

Key Features:

1. **Object-Oriented Design (UDT):** Built around the `Prof`
object, encapsulating grid geometry, two generic data accumulators
(Array A & B), and cached statistical metrics. Supports full
lifecycle management: creation, cloning, clearing, and merging.

2. **Data-Agnostic Abstraction:**
- **Level (X-Axis):** Represents the coordinate system (e.g.,
Price, Time, Oscillator Value).
- **Mass (Y-Axis):** Represents the accumulated quantity
(e.g., Volume, Duration, Count).
- **Resolution (Grain):** The grid represents continuous data
discretized by a customizable resolution step size.

3. **Dual-Mode Geometry (Linear & Logarithmic):**
The engine supports seamless switching between two geometric modes:
- **Linear:** Arithmetic scaling (equal distance).
- **Logarithmic:** Geometric scaling (equal percentage), essential
for consistent density analysis across large ranges (Crypto).
Includes strict domain validation (enforcing positive bounds for log-space)
and physics-based constraints to prevent aliasing.

4. **High-Fidelity Resampling:**
Includes a sophisticated **Trapezoidal Integration Model** to
handle grid resizing and profile merging. When data is moved
between grids of different resolutions or geometries, the
library calculates the exact integral of the mass density
to ensure strict mass conservation.

5. **Dynamic Grid Management:**
- **Adapting:** Automatically expands the coordinate boundaries
to include new data points (`adapt`).
- **Resizing:** Allows changing the resolution (bins) or
boundaries on the fly, triggering the interpolation engine to
re-sample existing data accurately.

6. **Statistical Analysis (Lazy Evaluation):**
Comprehensive metrics calculated on-demand.
In Logarithmic mode, metrics adapt to use **Geometric Mean** and
**Geometric Interpolation** for maximum precision.
- **Location:** Peak (Mode), Weighted Mean (Center of Gravity), Median.
- **Dispersion:** Standard Deviation (Population), Coverage.
- **Shape:** Skewness and Excess Kurtosis.

7. **Structural Analysis:**
Includes a monotonic segmentation algorithm (configured by gapSize)
to decompose the distribution into its fundamental unimodal
segments, aiding in the detection of multi-modal distributions.

---

**DISCLAIMER**

This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.

The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.

As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.

create(bins, upper, lower, resolution, dynamic, isLog, coverage, gapSize)
  Construct a new `Prof` object with fixed bin count & bounds.
  Parameters:
    bins (int): series int number of level bins ≥ 1
    upper (float): series float upper level bound (absolute)
    lower (float): series float lower level bound (absolute)
    resolution (float): series float Smallest allowed bin size (resolution).
    dynamic (bool): series bool Flag for dynamic adaption of profile bounds
    isLog (bool): series bool Flag to enable Logarithmic bin scaling.
    coverage (int): series int Percentage of total mass to include in the Coverage Area (1..100)
    gapSize (int): series int Noise filter for segmentation. Number of allowed bins against trend.
  Returns: Prof freshly initialised profile

method clone(self)
  Create a deep copy of the profile.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object to copy
  Returns: Prof A new, independent copy of the profile

method merge(self, massA, massB, upper, lower)
  Merges mass data from a source profile into the current profile.
If resizing is needed, it performs a high-fidelity re-binning of existing
mass using a linear interpolation model inferred from neighboring bins,
preventing aliasing artifacts and ensuring accurate mass preservation.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof The target profile object to merge into.
    massA (array<float>): array float The source profile's mass A bin array.
    massB (array<float>): array float The source profile's mass B bin array.
    upper (float): series float The upper level bound of the source profile.
    lower (float): series float The lower level bound of the source profile.
  Returns: Prof `self` (chaining), now containing the merged data.

method clear(self)
  Reset all bin tallies while keeping configuration intact.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof profile object
  Returns: Prof cleared profile (chaining)

method addMass(self, idx, mass, useMassA)
  Adds mass to a bin.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
    idx (int): series int Bin index
    mass (float): series float Mass to add (must be > 0)
    useMassA (bool): series bool If true, adds to Array A, otherwise Array B

method adapt(self, upper, lower)
  Automatically adapts the profile's boundaries to include a given level interval.
If the level bound exceeds the current profile bounds, it triggers
the _resizeGrid method to resize the profile and re-bin existing mass.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof The profile object.
    upper (float): series float The upper level to fit.
    lower (float): series float The lower level to fit.
  Returns: Prof `self` (chaining).

method setBins(self, bins)
  Sets the number of bins for the profile.
Behavior depends on the `isDynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-binning to a new resolution.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
    bins (int): series int The new number of bins
  Returns: Prof `self` (chaining)

method setBounds(self, upper, lower)
  Sets the level bounds for the profile.
Behavior depends on the `dynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-binning existing mass
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
    upper (float): series float The new upper level bound
    lower (float): series float The new lower level bound
  Returns: Prof `self` (chaining)

method setResolution(self, resolution)
  Sets the minimum resolution size (granularity limit) for the profile.
If the current bin count exceeds the limit imposed by the new
resolution, the profile is automatically resized (downsampled) to fit.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
    resolution (float): series float The new smallest allowed bin size.
  Returns: Prof `self` (chaining)

method setLog(self, isLog)
  Toggles the geometry of the profile between Linear and Logarithmic.
Behavior depends on the `dynamic` flag.
- If `dynamic = true`: Mass is re-distributed (merged) into the new geometric grid.
- If `dynamic = false`: Only works on empty profiles.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
    isLog (bool): series bool True for Logarithmic, False for Linear.
  Returns: Prof `self` (chaining)

method setCoverage(self, coverage)
  Set the percentage of mass for the Coverage Area. If the value
changes, the profile is finalized again.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
    coverage (int): series int The new Mass Coverage Percentage (0..100)
  Returns: Prof `self` (chaining)

method setGapSize(self, gapSize)
  Sets the gapSize (noise filter) for segmentation.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
    gapSize (int): series int Number of bins allowed to violate monotonicity
  Returns: Prof `self` (chaining)

method getBins(self)
  Returns the current number of bins in the profile.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof The profile object.
  Returns: series int The number of bins.

method getBounds(self)
  Returns the current level bounds of the profile.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof The profile object.
  Returns: [upper, lower]
upper series float The upper level bound of the profile.
lower series float The lower level bound of the profile.

method getBinWidth(self)
  Get Width of a bin.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
  Returns: series float The width of a bin

method getBinIdx(self, level)
  Get Index of a bin.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
    level (float): series float absolute coordinate to locate
  Returns: series int bin index 0…bins‑1 (clamped)

method getBinBnds(self, idx)
  Get Bounds of a bin.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
    idx (int): series int Bin index
  Returns: [up, lo]
up series float The upper level bound of the bin.
lo series float The lower level bound of the bin.

method getBinMid(self, idx)
  Get Mid level of a bin.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
    idx (int): series int Bin index
  Returns: series float Mid level

method getMassA(self)
  Returns a copy of the internal raw data array A (Mass A).
  Namespace types: Prof
  Parameters:
    self (Prof): Prof The profile object.
  Returns: array<float> The internal array for mass A.

method getMassB(self)
  Returns a copy of the internal raw data array B (Mass B).
  Namespace types: Prof
  Parameters:
    self (Prof): Prof The profile object.
  Returns: array<float> The internal array for mass B.

method getBinMassA(self, idx)
  Get Mass A of a bin.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
    idx (int): series int Bin index
  Returns: series float mass A

method getBinMassB(self, idx)
  Get Mass B of a bin.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
    idx (int): series int Bin index
  Returns: series float mass B

method getPeak(self)
  Get Peak information.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
  Returns: [peakIndex, peakLevel]
peakIndex series int The index of the Peak bin.
peakLevel. series float The mid-level of the Peak bin.

method getCoverage(self)
  Get Coverage information.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object
  Returns: [covUpIndex, covUpLevel, covLoIndex, covLoLevel]
covUpIndex series int The index of the upper bound bin of the Coverage Area.
covUpLevel series float The upper level bound of the Coverage Area.
covLoIndex series int The index of the lower bound bin of the Coverage Area.
covLoLevel series float The lower level bound of the Coverage Area.

method getMedian(self)
  Get the profile's median level and its bin index. Calculates the value on-demand if stale.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object.
  Returns: [series int, series float] [medianIndex, medianLevel]
medianIndex series int The index of the bin containing the Median.
medianLevel series float The Median level of the profile.

method getMean(self)
  Get the profile's mean and its bin index. Calculates the value on-demand if stale.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object.
  Returns: [series int, series float] [meanIndex, meanLevel]
meanIndex series int The index of the bin containing the mean.
meanLevel series float The mean of the profile.

method getStdDev(self)
  Get the profile's standard deviation. Calculates the value on-demand if stale.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object.
  Returns: series float The Standard deviation of the profile.

method getSkewness(self)
  Get the profile's skewness. Calculates the value on-demand if stale.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object.
  Returns: series float The Skewness of the profile.

method getKurtosis(self)
  Get the profile's excess kurtosis. Calculates the value on-demand if stale.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof Profile object.
  Returns: series float The Kurtosis of the profile.

method getSegments(self)
  Get the profile's fundamental unimodal segments. Calculates on-demand if stale.
Uses a pivot-based recursive algorithm configured by gapSize.
  Namespace types: Prof
  Parameters:
    self (Prof): Prof The profile object.
  Returns: matrix<int> A 2-column matrix where each row is an [startIndex, endIndex] pair.

Prof
  Prof Generic Profile object containing the grid and two data arrays.
  Fields:
    _bins (series int): int Number of discrete containers (bins).
    _upper (series float): float Upper boundary of the domain.
    _lower (series float): float Lower boundary of the domain.
    _resolution (series float): float Smallest atomic grid unit (Resolution).
    _isLog (series bool): bool If true, the grid uses logarithmic scaling.
    _logFactor (series float): float Cached multiplier for log iteration (k = (up/lo)^(1/n)).
    _logStep (series float): float Cached natural logarithm of the factor (ln(k)) for optimized index calculation.
    _dynamic (series bool): bool Flag for dynamic resizing/resampling.
    _coverage (series int): int Target Mass Coverage Percentage (Input for Coverage).
    _gapSize (series int): int Tolerance against trend violations (Noise filter).
    _maxBins (series int): int Hard capacity limit for bins.
    _massA (array<float>): array<float> Generic Mass Array A.
    _massB (array<float>): array<float> Generic Mass Array B.
    _peak (series int): int Index of max mass (Mode).
    _covUp (series int): int Index of Coverage Upper Bound.
    _covLo (series int): int Index of Coverage Lower Bound.
    _median (series float): float Median level of distribution.
    _mean (series float): float Weighted Average Level (Center of Gravity).
    _stdDev (series float): float Population Standard Deviation.
    _skewness (series float): float Asymmetry measure.
    _kurtosis (series float): float Tail heaviness measure.
    _segments (matrix<int>): matrix<int> Identified unimodal segments.

免责声明

这些信息和出版物并非旨在提供,也不构成TradingView提供或认可的任何形式的财务、投资、交易或其他类型的建议或推荐。请阅读使用条款了解更多信息。