moving_averages# MovingAverages Library - PineScript v6
A comprehensive PineScript v6 library containing **50+ Moving Average calculations** for TradingView.
---
## 📦 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+
Techindicator
LibProfLibrary "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) : array float The source profile's mass A bin array.
massB (array) : 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 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 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 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 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 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 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:
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:
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 A 2-column matrix where each row is an 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) : array Generic Mass Array A.
_massB (array) : array 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) : matrix Identified unimodal segments.
LO1_News2023H2Library "LO1_News2023H2" - Contains the news events for 2023 H2
f_loadNewsRows()
f_loadExcSevByTypeId()
f_loadExcTagByTypeId()
f_loadExcDelayAfterNewsMins()
LO1_News2023H1Library "LO1_News2023H1" - Contains the news events for 2023
f_loadNewsRows()
f_loadExcSevByTypeId()
f_loadExcTagByTypeId()
f_loadExcDelayAfterNewsMins()
labConfigCoreLibrary "labConfigCore"
Configuration centrale pour tous les indicateurs LAB (Kijun + EMA + S/R)
Centralise les valeurs par défaut pour éviter les désynchronisations entre indicateurs
getTFFast()
Retourne le timeframe Fast par défaut
Returns: String - Timeframe Fast ("15" par défaut)
getTFMid()
Retourne le timeframe Mid par défaut
Returns: String - Timeframe Mid ("60" par défaut)
getTFSlow()
Retourne le timeframe Slow par défaut
Returns: String - Timeframe Slow ("240" par défaut)
getTFATR()
Retourne le timeframe ATR par défaut
Returns: String - Timeframe ATR ("60" par défaut)
getKijunLength()
Retourne la longueur Kijun par défaut
Returns: Int - Longueur Kijun (26 par défaut)
getShowKijun()
Retourne l'état d'affichage Kijun par défaut
Returns: Bool - Afficher Kijun (true par défaut)
getEMALength()
Retourne la longueur EMA par défaut
Returns: Int - Longueur EMA (50 par défaut)
getChannelWidth()
Retourne la largeur des canaux EMA par défaut
Returns: Float - Largeur canal en % (2.0 par défaut)
getChannelAlpha()
Retourne la transparence des canaux par défaut
Returns: Int - Alpha channel (93 par défaut)
getShowChannelFast()
Retourne l'état d'affichage canal Fast par défaut
Returns: Bool - Afficher canal Fast (false par défaut)
getShowChannelMid()
Retourne l'état d'affichage canal Mid par défaut
Returns: Bool - Afficher canal Mid (true par défaut)
getShowChannelSlow()
Retourne l'état d'affichage canal Slow par défaut
Returns: Bool - Afficher canal Slow (true par défaut)
getChannelColorFast()
Retourne la couleur canal Fast par défaut
Returns: Color - Couleur Fast (#00BCD4 par défaut)
getChannelColorMid()
Retourne la couleur canal Mid par défaut
Returns: Color - Couleur Mid (#4CAF50 par défaut)
getChannelColorSlow()
Retourne la couleur canal Slow par défaut
Returns: Color - Couleur Slow (#FF9800 par défaut)
getSRDisplayMode()
Retourne le mode d'affichage S/R par défaut
Returns: String - Mode ('S/R Zones' par défaut)
getSRTimeframe()
Retourne le timeframe S/R par défaut
Returns: String - Timeframe S/R ('Chart' par défaut)
getSRVolMA()
Retourne la longueur Volume MA par défaut
Returns: Int - Longueur Vol MA (6 par défaut)
getSRNumZones()
Retourne le nombre de zones back par défaut
Returns: Int - Zones back (10 par défaut)
getSRExtendLines()
Retourne l'état extend lines par défaut
Returns: Bool - Extend to next zone (true par défaut)
getSRExtendActive()
Retourne l'état extend active par défaut
Returns: Bool - Extend active right (true par défaut)
getSRExtendRight()
Retourne l'état extend right par défaut
Returns: Bool - Extend right (false par défaut)
getSRShowLabels()
Retourne l'état affichage labels par défaut
Returns: Bool - Show labels (true par défaut)
getSRLabelLocation()
Retourne la position labels par défaut
Returns: String - Position ('Right' par défaut)
getSRLabelOffset()
Retourne l'offset labels par défaut
Returns: Int - Offset (15 par défaut)
getSRShowHL()
Retourne l'état affichage H/L par défaut
Returns: Bool - Show H/L lines (true par défaut)
getSRShowOC()
Retourne l'état affichage O/C par défaut
Returns: Bool - Show O/C lines (true par défaut)
getSRLineStyleHL()
Retourne le style ligne H/L par défaut
Returns: String - Style ('Solid' par défaut)
getSRLineWidthHL()
Retourne l'épaisseur ligne H/L par défaut
Returns: Int - Width (1 par défaut)
getSRLineStyleOC()
Retourne le style ligne O/C par défaut
Returns: String - Style ('Solid' par défaut)
getSRLineWidthOC()
Retourne l'épaisseur ligne O/C par défaut
Returns: Int - Width (1 par défaut)
getSRResLinesColor()
Retourne la couleur lignes résistance par défaut
Returns: Color - Couleur (rouge 20% transparent)
getSRResZoneColor()
Retourne la couleur zone résistance par défaut
Returns: Color - Couleur (rouge 90% transparent)
getSRSupLinesColor()
Retourne la couleur lignes support par défaut
Returns: Color - Couleur (lime 20% transparent)
getSRSupZoneColor()
Retourne la couleur zone support par défaut
Returns: Color - Couleur (lime 90% transparent)
getNormMode()
Retourne le mode de normalisation par défaut
Returns: String - Mode ('ATR' par défaut)
getATRLength()
Retourne la longueur ATR par défaut
Returns: Int - Longueur ATR (14 par défaut)
getTolEqual()
Retourne la tolérance égalité par défaut
Returns: Float - Tolérance (0.10 par défaut)
getThresholdTight()
Retourne le seuil compression par défaut
Returns: Float - Seuil tight (0.25 par défaut)
getThresholdWide()
Retourne le seuil extension par défaut
Returns: Float - Seuil wide (1.50 par défaut)
getShowDashboard()
Retourne l'état d'affichage dashboard par défaut
Returns: Bool - Show table (true par défaut)
getDashboardPosition()
Retourne la position dashboard par défaut
Returns: String - Position ('Top Right' par défaut)
getDashboardSize()
Retourne la taille dashboard par défaut
Returns: String - Size ('Small' par défaut)
getProbBarsForward()
Retourne le nombre de barres forward par défaut
Returns: Int - Bars forward (20 par défaut)
getProbWinThreshold()
Retourne le seuil win par défaut
Returns: Float - Win threshold % (1.5 par défaut)
getProbLossThreshold()
Retourne le seuil loss par défaut
Returns: Float - Loss threshold % (1.0 par défaut)
getProbHistorySize()
Retourne la taille historique par défaut
Returns: Int - History size (500 par défaut)
getStrategyTPSLMode()
Retourne le mode TP/SL par défaut
Returns: String - Mode ('% Fixed' ou 'ATR Multiple')
getStrategyTPPercent()
Retourne le take profit % par défaut
Returns: Float - TP % (2.0 par défaut)
getStrategySLPercent()
Retourne le stop loss % par défaut
Returns: Float - SL % (1.0 par défaut)
getStrategyTPATRMultiple()
Retourne le multiple ATR pour TP par défaut
Returns: Float - TP ATR multiple (2.0 par défaut)
getStrategySLATRMultiple()
Retourne le multiple ATR pour SL par défaut
Returns: Float - SL ATR multiple (1.5 par défaut)
getStrategyUseTrailing()
Retourne l'état trailing stop par défaut
Returns: Bool - Use trailing stop (false par défaut)
getStrategyTrailingActivation()
Retourne l'activation trailing % par défaut
Returns: Float - Trailing activation % (1.0 par défaut)
getStrategyTrailingOffset()
Retourne le trailing offset % par défaut
Returns: Float - Trailing offset % (0.5 par défaut)
getStrategyPositionSize()
Retourne la taille position par défaut
Returns: Float - Position size % equity (100 par défaut)
getStrategyInitialCapital()
Retourne le capital initial par défaut
Returns: Float - Initial capital (10000 par défaut)
getStrategyCommission()
Retourne la commission par défaut
Returns: Float - Commission % (0.1 par défaut)
getStrategySlippage()
Retourne le slippage par défaut
Returns: Int - Slippage ticks (2 par défaut)
getAllKijunDefaults()
Retourne TOUS les paramètres Kijun sous forme de tuple
Returns: - TF Fast, Mid, Slow, Length, Show
getAllEMADefaults()
Retourne TOUS les paramètres EMA sous forme de tuple
Returns: - Length, Width, Alpha, Show Fast, Mid, Slow
getAllNormDefaults()
Retourne TOUS les paramètres Normalisation sous forme de tuple
Returns: - Mode, TF ATR, Length, Tol, Tight, Wide
getAllDashboardDefaults()
Retourne TOUS les paramètres Dashboard sous forme de tuple
Returns: - Show, Position, Size
volSRCoreLibrary volSRCore
Library to compute volume-based support and resistance zones using fractal logic.
tfStringToFormat(tfInput)
Converts a timeframe string into Pine Script format.
Parameters:
tfInput (string): Timeframe string ("Chart", "1m", "5m", "1h", "D", etc.)
Returns:
string — Pine Script–formatted timeframe
resInMinutes()
Converts the current chart timeframe into minutes.
Returns:
float — number of minutes of the current timeframe
fractalUp(tfHigh, tfVol, tfVolMA)
Detects a bullish fractal (potential resistance).
Parameters:
tfHigh (float): High series of the timeframe
tfVol (float): Volume series of the timeframe
tfVolMA (float): Volume moving average series
Returns:
bool — true if a bullish fractal is detected
fractalDown(tfLow, tfVol, tfVolMA)
Detects a bearish fractal (potential support).
Parameters:
tfLow (float): Low series of the timeframe
tfVol (float): Volume series of the timeframe
tfVolMA (float): Volume moving average series
Returns:
bool — true if a bearish fractal is detected
calcFractalUpLevel(tfHigh, tfVol, tfVolMA)
Computes the resistance level from a bullish fractal.
Parameters:
tfHigh (float): High series
tfVol (float): Volume series
tfVolMA (float): Volume MA series
Returns:
float — resistance level
calcFractalDownLevel(tfLow, tfVol, tfVolMA)
Computes the support level from a bearish fractal.
Parameters:
tfLow (float): Low series
tfVol (float): Volume series
tfVolMA (float): Volume MA series
Returns:
float — support level
calcResistanceZone(tfHigh, tfOpen, tfClose, tfVol, tfVolMA)
Computes the resistance zone (between High and Open/Close).
Parameters:
tfHigh (float): High series
tfOpen (float): Open series
tfClose (float): Close series
tfVol (float): Volume series
tfVolMA (float): Volume MA series
Returns:
float — lower boundary of the resistance zone
calcSupportZone(tfLow, tfOpen, tfClose, tfVol, tfVolMA)
Computes the support zone (between Low and Open/Close).
Parameters:
tfLow (float): Low series
tfOpen (float): Open series
tfClose (float): Close series
tfVol (float): Volume series
tfVolMA (float): Volume MA series
Returns:
float — upper boundary of the support zone
tfNewBar(tfRes)
Detects a new bar on a given timeframe.
Parameters:
tfRes (simple string): Timeframe string
Returns:
bool — true if a new bar is detected
tfBarIndexBack(tfRes, barsBack)
Computes the bar_index N bars back on a target timeframe.
Parameters:
tfRes (simple string): Timeframe string
barsBack (simple int): Number of bars back (1, 3, 5, etc.)
Returns:
int — bar_index at that point in time
tfBarsRange(tfRes, startBar, endBar)
Computes the number of chart bars between two bars of a target timeframe.
Parameters:
tfRes (simple string): Timeframe string
startBar (simple int): Start bar (e.g., 1)
endBar (simple int): End bar (e.g., 5)
Returns:
int — number of chart bars in that range
calcPivotHighBarIndex(startBarsBack, rangeSize, maxBarsBack)
Finds the exact bar_index of the highest high within a given range.
Parameters:
startBarsBack (simple int): Start of the scan (bars back)
rangeSize (simple int): Size of the scan range
maxBarsBack (simple int): max_bars_back limit (e.g., 4999)
Returns:
int — bar_index of the highest high, or maxBarsBack if out of bounds
calcPivotLowBarIndex(startBarsBack, rangeSize, maxBarsBack)
Finds the exact bar_index of the lowest low within a given range.
Parameters:
startBarsBack (simple int): Start of the scan (bars back)
rangeSize (simple int): Size of the scan range
maxBarsBack (simple int): max_bars_back limit (e.g., 4999)
Returns:
int — bar_index of the lowest low, or maxBarsBack if out of bounds
detectPriceInteraction(resLevel, resZone, supLevel, supZone)
Detects price interactions with support/resistance zones.
Parameters:
resLevel (float): Resistance level
resZone (float): Resistance zone
supLevel (float): Support level
supZone (float): Support zone
Returns:
EntersResZone
TestsResAsSupport
EntersSupZone
TestsSupAsResistance
BreaksResistance
BreaksSupport
calcSRLevelsFromData(tfOpen, tfHigh, tfLow, tfClose, tfVol, volMaLength)
Computes all support/resistance levels from already-fetched MTF data.
Parameters:
tfOpen (float): TF open
tfHigh (float): TF high
tfLow (float): TF low
tfClose (float): TF close
tfVol (float): TF volume
volMaLength (simple int): Volume MA length
Returns:
ResistanceLevel
ResistanceZone
SupportLevel
SupportZone
IsFractalUp
IsFractalDown
detectNewSR(resLevel, supLevel)
Detects a new fractal event (new support or resistance found).
Parameters:
resLevel (float): Current resistance level
supLevel (float): Current support level
Returns:
NewResistance
NewSupport
emaStackCoreLibrary "emaStackCore"
emaCalc(source, length)
Calculate EMA
Parameters:
source (float) : Price source (close, hl2, etc.)
length (simple int) : EMA period
Returns: EMA value
emaSlope(emaValue, lookback)
Calculate EMA slope (% change over lookback period)
Parameters:
emaValue (float) : Current EMA value
lookback (int) : Number of bars to look back
Returns: Slope in percentage
emaDist(ema1, ema2, mode, atrVal, price)
Calculate distance between 2 EMAs (normalized)
Parameters:
ema1 (float) : First EMA value
ema2 (float) : Second EMA value
mode (string) : Normalization mode ("ATR" or "%")
atrVal (float) : ATR value for ATR mode
price (float) : Reference price for % mode
Returns: Normalized distance
slopeClass(slope, thresholdFlat)
Classify EMA slope
Parameters:
slope (float) : EMA slope in %
thresholdFlat (float) : Threshold to consider slope as flat
Returns: +1 (rising), 0 (flat), -1 (falling)
slopeScore5(slope10, slope20, slope50, slope100, slope200, threshold)
Calculate combined slope score for 5 EMAs
Parameters:
slope10 (float) : EMA10 slope
slope20 (float) : EMA20 slope
slope50 (float) : EMA50 slope
slope100 (float) : EMA100 slope
slope200 (float) : EMA200 slope
threshold (float) : Flat threshold
Returns: Sum of slope classes (-5 to +5)
emaStack5Score(e10, e20, e50, e100, e200, tolEq)
Calculate EMA stack score (5 EMAs)
Parameters:
e10 (float) : EMA 10 value
e20 (float) : EMA 20 value
e50 (float) : EMA 50 value
e100 (float) : EMA 100 value
e200 (float) : EMA 200 value
tolEq (float) : Tolerance for equality (%)
Returns: Stack score (-4 to +4)
emaStack5ScoreWithSlope(e10, e20, e50, e100, e200, slope10, slope20, slope50, slope100, slope200, tolEq, slopeThreshold)
Enhanced EMA stack with slope
Parameters:
e10 (float)
e20 (float)
e50 (float)
e100 (float)
e200 (float)
slope10 (float)
slope20 (float)
slope50 (float)
slope100 (float)
slope200 (float)
tolEq (float)
slopeThreshold (float)
Returns:
emaRegimeChange(currentScore, previousScore, threshold)
Detect regime change in EMA stack
Parameters:
currentScore (int) : Current stack score
previousScore (int) : Previous stack score
threshold (int) : Minimum change to consider significant
Returns:
emaCompressed(e10, e20, e50, e100, e200, threshold)
Detect EMA compression (squeeze)
Parameters:
e10 (float) : EMA 10 value
e20 (float) : EMA 20 value
e50 (float) : EMA 50 value
e100 (float) : EMA 100 value
e200 (float) : EMA 200 value
threshold (float) : Max spread % to consider compressed
Returns:
emaConfluence9(price, e10_tf1, e20_tf1, e50_tf1, e10_tf2, e20_tf2, e50_tf2, e10_tf3, e20_tf3, e50_tf3, threshold)
Calculate confluence score (how many EMAs are near price)
Parameters:
price (float) : Current price
e10_tf1 (float) : EMA10 on timeframe 1
e20_tf1 (float) : EMA20 on timeframe 1
e50_tf1 (float) : EMA50 on timeframe 1
e10_tf2 (float) : EMA10 on timeframe 2
e20_tf2 (float) : EMA20 on timeframe 2
e50_tf2 (float) : EMA50 on timeframe 2
e10_tf3 (float) : EMA10 on timeframe 3
e20_tf3 (float) : EMA20 on timeframe 3
e50_tf3 (float) : EMA50 on timeframe 3
threshold (float) : Max distance % to consider "near"
Returns: Confluence count (0-9)
emaConfluence3(price, e10, e20, e50, threshold)
Simplified confluence for 3 EMAs on single TF
Parameters:
price (float)
e10 (float)
e20 (float)
e50 (float)
threshold (float)
Returns: Confluence count (0-3)
emaLeadLag(score15m, score1H, score4H, lookback)
Determine which timeframe is leading the move
Parameters:
score15m (int) : Stack score on 15m
score1H (int) : Stack score on 1H
score4H (int) : Stack score on 4H
lookback (int) : Bars to look back for change detection
Returns: Leader timeframe ("15m", "1H", "4H", "ALIGNED", "MIXED")
emaPriceDivergence(price, emaValue, lookback)
Detect divergence between price and EMA direction
Parameters:
price (float) : Current price
emaValue (float) : EMA value (typically EMA20)
lookback (int) : Bars to compare
Returns:
emaOrderStrength(e10, e20, e50, e100, e200)
Calculate EMA order strength (weighted by distance)
Parameters:
e10 (float) : EMA 10
e20 (float) : EMA 20
e50 (float) : EMA 50
e100 (float) : EMA 100
e200 (float) : EMA 200
Returns: Strength score (higher = stronger trend)
emaPriceZone(price, e10, e20, e50, e100, e200)
Determine which EMA zone price is in
Parameters:
price (float) : Current price
e10 (float) : EMA 10
e20 (float) : EMA 20
e50 (float) : EMA 50
e100 (float) : EMA 100
e200 (float) : EMA 200
Returns: Zone code (5=above all, 0=below all, -1=mixed)
kijunStackCoreLibrary "kijunStackCore"
kijun(highSeries, lowSeries, length)
Parameters:
highSeries (float)
lowSeries (float)
length (int)
distNormAtr(a, b, atrValue)
Parameters:
a (float)
b (float)
atrValue (float)
distNormPct(a, b, price)
Parameters:
a (float)
b (float)
price (float)
stack3Code(kFast, kMid, kSlow, distFastMid, distMidSlow, tolEq)
Parameters:
kFast (float)
kMid (float)
kSlow (float)
distFastMid (float)
distMidSlow (float)
tolEq (float)
stack3Compressed(distFastMid, distMidSlow, tight)
Parameters:
distFastMid (float)
distMidSlow (float)
tight (float)
stack3Stretched(distFastMid, distMidSlow, wide)
Parameters:
distFastMid (float)
distMidSlow (float)
wide (float)
InfinityCandlePatternsLibrary "InfinityCandlePatterns"
isMorningStar(o, c, atr)
Parameters:
o (float)
c (float)
atr (float)
isEveningStar(o, c, atr)
Parameters:
o (float)
c (float)
atr (float)
isThreeWhiteSoldiers(o, h, c, atr)
Parameters:
o (float)
h (float)
c (float)
atr (float)
isThreeBlackCrows(o, l, c, atr)
Parameters:
o (float)
l (float)
c (float)
atr (float)
isBullishHarami(o, c, atr)
Parameters:
o (float)
c (float)
atr (float)
isBearishHarami(o, c, atr)
Parameters:
o (float)
c (float)
atr (float)
isBullishEngulfing(o, c)
Parameters:
o (float)
c (float)
isBearishEngulfing(o, c)
Parameters:
o (float)
c (float)
isThreeInsideUp(o, h, c, atr)
Parameters:
o (float)
h (float)
c (float)
atr (float)
isThreeInsideDown(o, l, c, atr)
Parameters:
o (float)
l (float)
c (float)
atr (float)
isTweezerBottom(o, l, c, atr)
Parameters:
o (float)
l (float)
c (float)
atr (float)
isTweezerTop(o, h, c, atr)
Parameters:
o (float)
h (float)
c (float)
atr (float)
isBullishKicker(o, c)
Parameters:
o (float)
c (float)
isBearishKicker(o, c)
Parameters:
o (float)
c (float)
isBullishBreakaway(o, c, atr)
Parameters:
o (float)
c (float)
atr (float)
isBearishBreakaway(o, c, atr)
Parameters:
o (float)
c (float)
atr (float)
isHammer(o, h, l, c, atr)
Parameters:
o (float)
h (float)
l (float)
c (float)
atr (float)
isShootingStar(o, h, l, c, atr)
Parameters:
o (float)
h (float)
l (float)
c (float)
atr (float)
isStandardDoji(o, c, atr)
Parameters:
o (float)
c (float)
atr (float)
isDragonflyDoji(o, h, l, c, atr)
Parameters:
o (float)
h (float)
l (float)
c (float)
atr (float)
isGravestoneDoji(o, h, l, c, atr)
Parameters:
o (float)
h (float)
l (float)
c (float)
atr (float)
isBullishMarubozu(o, h, l, c, atr)
Parameters:
o (float)
h (float)
l (float)
c (float)
atr (float)
isBearishMarubozu(o, h, l, c, atr)
Parameters:
o (float)
h (float)
l (float)
c (float)
atr (float)
isSpinningTop(o, h, l, c, atr)
Parameters:
o (float)
h (float)
l (float)
c (float)
atr (float)
bullAny(o, h, l, c, atr)
Parameters:
o (float)
h (float)
l (float)
c (float)
atr (float)
bearAny(o, h, l, c, atr)
Parameters:
o (float)
h (float)
l (float)
c (float)
atr (float)
neutralAny(o, h, l, c, atr)
Parameters:
o (float)
h (float)
l (float)
c (float)
atr (float)
bullStrong(o, h, c, atr)
Parameters:
o (float)
h (float)
c (float)
atr (float)
bearStrong(o, l, c, atr)
Parameters:
o (float)
l (float)
c (float)
atr (float)
RVOL_Core_NSELibrary "RVOL_Core_NSE"
f_rvol(lookbackDays, isNewDay, msSinceSessionStart, volume)
Parameters:
lookbackDays (int)
isNewDay (bool)
msSinceSessionStart (int)
volume (float)
ZigZag ATR PctZigZag ATR % Library
A PineScript v6 library for detecting price pivots based on ATR percentage change (volatility shifts) rather than fixed ATR multiples.
How It Works
Traditional ZigZag indicators use a fixed price threshold to detect pivots. This library takes a different approach: pivots are detected when volatility is changing significantly .
The ATR % change measures how much the Average True Range has shifted over a lookback period:
atrPct = 100 * (atr / atr - 1)
Positive ATR % = Volatility expanding (market becoming more volatile)
Negative ATR % = Volatility contracting (market calming down)
Pivots form when |ATR %| exceeds your threshold, capturing turning points during volatility transitions.
Exported Types
Settings - Configuration (ATR length, lookback, threshold, display options)
Pivot - Pivot point data (price, time, direction, volume, ATR %)
ZigZag - Main state container
Exported Functions
newInstance(settings) - Create a new ZigZag instance
update(zz, atr, atrPct) - Update on each bar
getLastPivot(zz) - Get the most recent pivot
getPivot(zz, index) - Get pivot at specific index
getPivotCount(zz) - Get total number of pivots
calcTR() - Calculate True Range
calcATR(length) - Calculate ATR using EMA
calcATRPct(atr, atrPrev) - Calculate ATR % change
calcPricePct(startPrice, endPrice) - Calculate price % change
Usage Example
//@version=6
indicator("My ZigZag", overlay = true)
import DeepEntropy/ZigZagATRPct/1 as zz
// Settings
var zz.Settings settings = zz.Settings.new(
atrLength = 14,
atrLookback = 14,
atrPctThreshold = 5.0,
depth = 10
)
var zz.ZigZag zigZag = zz.newInstance(settings)
// Calculate ATR %
float atr = zz.calcATR(14)
float atrPct = zz.calcATRPct(atr, atr )
// Update
zigZag := zz.update(zigZag, atr, atrPct)
// Access pivots
int count = zz.getPivotCount(zigZag)
if count > 0
zz.Pivot last = zz.getLastPivot(zigZag)
label.new(last.point, text = str.tostring(last.atrPct, "#.##") + "%")
Parameters
ATR Length - Period for ATR calculation (default: 14)
ATR Lookback - Bars to look back for ATR % change (default: 14)
ATR % Threshold - Minimum |ATR %| to trigger pivot detection (default: 5.0)
Depth - Minimum bars between pivots (default: 10)
Use Cases
Identify reversals during volatility regime changes
Filter noise during low-volatility consolidation
Detect breakout pivots when volatility expands
Build volatility-aware trading systems
This library detects when the market's behavior is changing, not just how much price has moved.
ZigZag ATRZigZag ATR Library
A volatility-adaptive ZigZag indicator that uses Average True Range (ATR) instead of fixed percentage deviation to detect pivot points. This makes the ZigZag dynamically adjust to market conditions — tighter during low volatility, wider during high volatility.
Why ATR instead of Percentage?
The standard ZigZag uses a fixed percentage threshold (e.g., 5%) to determine when price has reversed enough to form a new pivot. This approach has limitations:
A 5% move means very different things for a $10 stock vs a $500 stock
During high volatility, fixed percentages create too many pivots (noise)
During low volatility, fixed percentages may miss significant structure
ATR-based deviation solves these issues by measuring reversals in terms of actual volatility , not arbitrary percentages.
Key Features
Volatility-adaptive pivot detection using ATR × multiplier threshold
Automatic adjustment to changing market conditions
Full customization of ATR length and multiplier
Optional line extension to current price
Pivot labels showing price, volume, and price change
Clean library structure for easy integration
Settings
ATR Length — Period for ATR calculation (default: 14)
ATR Multiplier — How many ATRs price must move to confirm a new pivot (default: 2.0)
Depth — Bars required for pivot detection (default: 10)
Extend to Last Bar — Draw provisional line to current price
Display options — Toggle price, volume, and change labels
How to Use
import YourUsername/ZigZagATR/1 as zz
// Create settings
var zz.Settings settings = zz.Settings.new(
14, // ATR length
2.0, // ATR multiplier
10 // Depth
)
// Create ZigZag instance
var zz.ZigZag zigZag = zz.newInstance(settings)
// Calculate ATR and update on each bar
float atrValue = ta.atr(14)
zigZag.update(atrValue)
Exported Types
Settings — Configuration for calculation and display
Pivot — Stores pivot point data, lines, and labels
ZigZag — Main object maintaining state and pivot history
Exported Functions
newInstance(settings) — Creates a new ZigZag object
update(atrValue) — Updates the ZigZag with current ATR (call once per bar)
lastPivot() — Returns the most recent pivot point
Recommended Multiplier Values
1.0 - 1.5 → More sensitive, more pivots, better for scalping
2.0 - 2.5 → Balanced, good for swing trading (default)
3.0+ → Less sensitive, major pivots only, better for position trading
Based on TradingView's official ZigZag library, modified to use ATR-based deviation threshold.
CausalityLib - granger casuality and transfer entropy helpersLibrary "CausalityLib"
Causality Analysis Library - Transfer Entropy, Granger Causality, and Causality Filtering
f_shannon_entropy(data, num_bins)
Calculate Shannon entropy of data distribution
Parameters:
data (array) : Array of continuous values
num_bins (int) : Number of bins for discretization
Returns: Entropy value (higher = more randomness)
f_calculate_te_score(primary_arr, ticker_arr, window, bins, lag)
Calculate Transfer Entropy from source to target
Parameters:
primary_arr (array) : Target series (e.g., primary ticker returns)
ticker_arr (array) : Source series (e.g., basket ticker returns)
window (int) : Window size for TE calculation
bins (int) : Number of bins for discretization
lag (int) : Lag for source series
Returns: - TE score and direction (-1 or 1)
f_correlation_at_lag(primary_arr, ticker_arr, lag, window, correlation_method)
Calculate Pearson correlation at specific lag
Parameters:
primary_arr (array) : Primary series
ticker_arr (array) : Ticker series
lag (int) : Lag value (positive = ticker lags primary)
window (int) : Window size for correlation
correlation_method (string) : Correlation method to use ("Pearson", "Spearman", "Kendall")
Returns: Correlation coefficient
f_calculate_granger_score(primary_arr, ticker_arr, window, max_lag, correlation_method)
Calculate Granger causality score with lag testing
Parameters:
primary_arr (array) : Primary series
ticker_arr (array) : Ticker series
window (int) : Window size for correlation
max_lag (int) : Maximum lag to test
correlation_method (string) : Correlation method to use
Returns: - Granger score and directional beta
f_partial_correlation(x_arr, y_arr, z_arr, window)
Calculate partial correlation between X and Y controlling for Z
Parameters:
x_arr (array) : First series
y_arr (array) : Second series
z_arr (array) : Mediator series
window (int) : Window size for correlation
Returns: Partial correlation coefficient
f_pcmci_filter_score(raw_score, primary_arr, ticker_arr, mediator1, mediator2, mediator3, mediator4, window)
PCMCI Filter: Adjust Granger score by checking for mediating tickers
Parameters:
raw_score (float) : Original Granger score
primary_arr (array) : Primary series
ticker_arr (array) : Ticker series
mediator1 (array) : First potential mediator series
mediator2 (array) : Second potential mediator series
mediator3 (array) : Third potential mediator series
mediator4 (array) : Fourth potential mediator series
window (int) : Window size for correlation
Returns: Filtered score (reduced if causality is indirect/spurious)
[GYTS] VolatilityToolkit LibraryVolatilityToolkit Library
🌸 Part of GoemonYae Trading System (GYTS) 🌸
🌸 --------- INTRODUCTION --------- 🌸
💮 What Does This Library Contain?
VolatilityToolkit provides a comprehensive suite of volatility estimation functions derived from academic research in financial econometrics. Rather than relying on simplistic measures, this library implements range-based estimators that extract maximum information from OHLC data — delivering estimates that are 5–14× more efficient than traditional close-to-close methods.
The library spans the full volatility workflow: estimation, smoothing, and regime detection.
💮 Key Categories
• Range-Based Estimators — Parkinson, Garman-Klass, Rogers-Satchell, Yang-Zhang (academically-grounded variance estimators)
• Classical Measures — Close-to-Close, ATR, Chaikin Volatility (baseline and price-unit measures)
• Smoothing & Post-Processing — Asymmetric EWMA for differential decay rates
• Aggregation & Regime Detection — Multi-horizon blending, MTF aggregation, Volatility Burst Ratio
💮 Originality
To the best of our knowledge, no other TradingView script combines range-based estimators (Parkinson, Garman-Klass, Rogers-Satchell, Yang-Zhang), classical measures, and regime detection tools in a single package. Unlike typical volatility implementations that offer only a single method, this library:
• Implements four academically-grounded range-based estimators with proper mathematical foundations
• Handles drift bias and overnight gaps, issues that plague simpler estimators in trending markets
• Integrates with GYTS FiltersToolkit for advanced smoothing (10 filter types vs. typical SMA-only)
• Provides regime detection tools (Burst Ratio, MTF aggregation) for systematic strategy integration
• Standardises output units for seamless estimator comparison and swapping
🌸 --------- ADDED VALUE --------- 🌸
💮 Academic Rigour
Each estimator implements peer-reviewed methodologies with proper mathematical foundations. The library handles aspects that are easily missed, e.g. drift independence, overnight gap adjustment, and optimal weighting factors. All functions include guards against edge cases (division by zero, negative variance floors, warmup handling).
💮 Statistical Efficiency
Range-based estimators extract more information from the same data. Yang-Zhang achieves up to 14× the efficiency of close-to-close variance, meaning you can achieve the same estimation accuracy with far fewer bars — critical for adapting quickly to changing market conditions.
💮 Flexible Smoothing
All estimators support configurable smoothing via the GYTS FiltersToolkit integration. Choose from 10 filter types to balance responsiveness against noise reduction:
• Ultimate Smoother (2-Pole / 3-Pole) — Near-zero lag; the 3-pole variant is a GYTS design with tunable overshoot
• Super Smoother (2-Pole / 3-Pole) — Excellent noise reduction with minimal lag
• BiQuad — Second-order IIR filter with quality factor control
• ADXvma — Adaptive smoothing based on directional volatility
• MAMA — Cycle-adaptive moving average
• A2RMA — Adaptive autonomous recursive moving average
• SMA / EMA — Classical averages (SMA is default for most estimators)
Using Infinite Impulse Response (IIR) filters (e.g. Super Smoother, Ultimate Smoother) instead of SMA avoids the "drop-off artefact" where volatility readings crash when old spikes exit the window.
💮 Plug-and-Play Integration
Standardised output units (per-bar log-return volatility) make it trivial to swap estimators. The annualize() helper converts to yearly volatility with a single call. All functions work seamlessly with other GYTS components.
🌸 --------- RANGE-BASED ESTIMATORS --------- 🌸
These estimators utilise High, Low, Open, and Close prices to extract significantly more information about the underlying diffusion process than close-only methods.
💮 parkinson()
The Extreme Value Method -- approximately 5× more efficient than close-to-close, requiring about 80% less data for equivalent accuracy. Uses only the High-Low range, making it simple and robust.
• Assumption: Zero drift (random walk). May be biased in strongly trending markets.
• Best for: Quick volatility reads when drift is minimal.
• Parameters: smoothing_length (default 14), filter_type (default SMA), smoothing_factor (default 0.7)
Source: Parkinson, M. (1980). The Extreme Value Method for Estimating the Variance of the Rate of Return. Journal of Business, 53 (1), 61–65. DOI
💮 garman_klass()
Extends Parkinson by incorporating Open and Close prices, achieving approximately 7.4× efficiency over close-to-close. Implements the "practical" analytic estimator (σ̂²₅) which avoids cross-product terms whilst maintaining near-optimal efficiency.
• Assumption: Zero drift, continuous trading (no gaps).
• Best for: Markets with minimal overnight gaps and ranging conditions.
• Parameters: smoothing_length (default 14), filter_type (default SMA), smoothing_factor (default 0.7)
Source: Garman, M.B. & Klass, M.J. (1980). On the Estimation of Security Price Volatilities from Historical Data. Journal of Business, 53 (1), 67–78. DOI
💮 rogers_satchell()
The drift-independent estimator correctly isolates variance even in strongly trending markets where Parkinson and Garman-Klass become significantly biased. Uses the formula: ln(H/C)·ln(H/O) + ln(L/C)·ln(L/O).
• Key advantage: Unbiased regardless of trend direction or magnitude.
• Best for: Trending markets, crypto (24/7 trading with minimal gaps), general-purpose use.
• Parameters: smoothing_length (default 14), filter_type (default SMA), smoothing_factor (default 0.7)
Source: Rogers, L.C.G. & Satchell, S.E. (1991). Estimating Variance from High, Low and Closing Prices. Annals of Applied Probability, 1 (4), 504–512. DOI
💮 yang_zhang()
The minimum-variance composite estimator — both drift-independent AND gap-aware. Combines overnight returns, open-to-close returns, and the Rogers-Satchell component with optimal weighting to minimise estimator variance. Up to 14× more efficient than close-to-close.
• Parameters: lookback (default 14, minimum 2), alpha (default 1.34, optimised for equities).
• Best for: Equity markets with significant overnight gaps, highest-quality volatility estimation.
• Note: Unlike other estimators, Yang-Zhang does not support custom filter types — it uses rolling sample variance internally.
Source: Yang, D. & Zhang, Q. (2000). Drift-Independent Volatility Estimation Based on High, Low, Open, and Close Prices. Journal of Business, 73 (3), 477–491. DOI
🌸 --------- CLASSICAL MEASURES --------- 🌸
💮 close_to_close()
Classical sample variance of logarithmic returns. Provided primarily as a baseline benchmark — it is approximately 5–8× less efficient than range-based estimators, requiring proportionally more data for the same accuracy.
• Parameters: lookback (default 14), filter_type (default SMA), smoothing_factor (default 0.7)
• Use case: Comparison baseline, situations requiring strict methodological consistency with academic literature.
💮 atr()
Average True Range -- measures volatility in price units rather than log-returns. Directly interpretable for stop-loss placement (e.g., "2× ATR trailing stop") and handles gaps naturally via the True Range formula.
• Output: Price units (not comparable across different price levels).
• Parameters: smoothing_length (default 14), filter_type (default SMA), smoothing_factor (default 0.7)
• Best for: Position sizing, trailing stops, any application requiring volatility in currency terms.
Source: Wilder, J.W. (1978). New Concepts in Technical Trading Systems . Trend Research.
💮 chaikin_volatility()
Rate of Change of the smoothed trading range. Unlike level-based measures, Chaikin Volatility shows whether volatility is expanding or contracting relative to recent history.
• Output: Percentage change (oscillates around zero).
• Parameters: length (default 10), roc_length (default 10), filter_type (default EMA), smoothing_factor (default 0.7)
• Interpretation: High values suggest nervous, wide-ranging markets; low values indicate compression.
• Best for: Detecting volatility regime shifts, breakout anticipation.
🌸 --------- SMOOTHING & POST-PROCESSING --------- 🌸
💮 asymmetric_ewma()
Differential smoothing with separate alphas for rising versus falling volatility. Allows volatility to spike quickly (fast reaction to shocks) whilst decaying slowly (stability). Essential for trailing stops that should widen rapidly during turbulence but narrow gradually.
• Parameters: alpha_up (default 0.1), alpha_down (default 0.02).
• Note: Stateful function — call exactly once per bar.
💮 annualize()
Converts per-bar volatility to annualised volatility using the square-root-of-time rule: σ_annual = σ_bar × √(periods_per_year).
• Parameters: vol (series float), periods (default 252 for daily equity bars).
• Common values: 365 (crypto), 52 (weekly), 12 (monthly).
🌸 --------- AGGREGATION & REGIME DETECTION --------- 🌸
💮 weighted_horizon_volatility()
Blends volatility readings across short, medium, and long lookback horizons. Inspired by the Heterogeneous Autoregressive (HAR-RV) model's recognition that market participants operate on different time scales.
• Default horizons: 1-bar (short), 5-bar (medium), 22-bar (long).
• Default weights: 0.5, 0.3, 0.2.
• Note: This is a weighted trailing average, not a forecasting regression. For true HAR-RV forecasting, it would be required to fit regression coefficients.
Inspired by: Corsi, F. (2009). A Simple Approximate Long-Memory Model of Realized Volatility. Journal of Financial Econometrics .
💮 volatility_mtf()
Multi-timeframe aggregation for intraday charts. Combines base volatility with higher-timeframe (Daily, Weekly, Monthly) readings, automatically scaling HTF volatilities down to the current timeframe's magnitude using the square-root-of-time rule.
• Usage: Calculate HTF volatilities via request.security() externally, then pass to this function.
• Behaviour: Returns base volatility unchanged on Daily+ timeframes (MTF aggregation not applicable).
💮 volatility_burst_ratio()
Regime shift detector comparing short-term to long-term volatility.
• Parameters: short_period (default 8), long_period (default 50), filter_type (default Super Smoother 2-Pole), smoothing_factor (default 0.7)
• Interpretation: Ratio > 1.0 indicates expanding volatility; values > 1.5 often precede or accompany explosive breakouts.
• Best for: Filtering entries (e.g., "only enter if volatility is expanding"), dynamic risk adjustment, breakout confirmation.
🌸 --------- PRACTICAL USAGE NOTES --------- 🌸
💮 Choosing an Estimator
• Trending equities with gaps: yang_zhang() — handles both drift and overnight gaps optimally.
• Crypto (24/7 trading): rogers_satchell() — drift-independent without the lag of Yang-Zhang's multi-period window.
• Ranging markets: garman_klass() or parkinson() — simpler, no drift adjustment needed.
• Price-based stops: atr() — output in price units, directly usable for stop distances.
• Regime detection: Combine any estimator with volatility_burst_ratio().
💮 Output Units
All range-based estimators output per-bar volatility in log-return units (standard deviation). To convert to annualised percentage volatility (the convention in options and risk management), use:
vol_annual = annualize(yang_zhang(14), 252) // For daily bars
vol_percent = vol_annual * 100 // Express as percentage
💮 Smoothing Selection
The library integrates with FiltersToolkit for flexible smoothing. General guidance:
• SMA: Classical, statistically valid, but suffers from "drop-off" artefacts when spikes exit the window.
• Super Smoother / Ultimate Smoother / BiQuad: Natural decay, reduced lag — preferred for trading applications.
• MAMA / ADXvma / A2RMA: Adaptive smoothing, sometimes interesting for highly dynamic environments.
💮 Edge Cases and Limitations
• Flat candles: Guards prevent log(0) errors, but single-tick bars produce near-zero variance readings.
• Illiquid assets: Discretisation bias causes underestimation when ticks-per-bar is small. Use higher timeframes for more reliable estimates.
• Yang-Zhang minimum: Requires lookback ≥ 2 (enforced internally). Cannot produce instantaneous readings.
• Drift in Parkinson/GK: These estimators overestimate variance in trending conditions — switch to Rogers-Satchell or Yang-Zhang.
Note: This library is actively maintained. Suggestions for additional estimators or improvements are welcome.
WYCKOFF_SHARED_LIBLibrary "WYCKOFF_SHARED_LIB"
EPS()
nz0(x)
Parameters:
x (float)
safe_div(num, den)
Parameters:
num (float)
den (float)
safe_div_eps(num, den)
Parameters:
num (float)
den (float)
safe_ratio(a, b)
Parameters:
a (float)
b (float)
clamp(x, lo, hi)
Parameters:
x (float)
lo (float)
hi (float)
wave_dir(startPx, endPx)
Parameters:
startPx (float)
endPx (float)
wave_amp(startPx, endPx)
Parameters:
startPx (float)
endPx (float)
wave_amp_atr(amp, atr)
Parameters:
amp (float)
atr (float)
wave_speed(ampATR, lenBars)
Parameters:
ampATR (float)
lenBars (int)
wave_eff(amp, path)
Parameters:
amp (float)
path (float)
build_wave_metrics(dir, lenBars, startPx, endPx, ampATR, speed, eff, volRel, epr)
Parameters:
dir (int)
lenBars (int)
startPx (float)
endPx (float)
ampATR (float)
speed (float)
eff (float)
volRel (float)
epr (float)
compare_waves(w0, w1)
Parameters:
w0 (WaveMetrics)
w1 (WaveMetrics)
strengthening_same_dir(c)
Parameters:
c (WaveCompare)
weakening_same_dir(c)
Parameters:
c (WaveCompare)
evr_by_waves(volSum0, ampATR0, volSum1, ampATR1)
Parameters:
volSum0 (float)
ampATR0 (float)
volSum1 (float)
ampATR1 (float)
WaveMetrics
Fields:
dir (series int)
lenBars (series int)
startPx (series float)
endPx (series float)
amp (series float)
ampATR (series float)
speed (series float)
eff (series float)
volRel (series float)
effortPerResult (series float)
WaveCompare
Fields:
amp_ratio (series float)
speed_ratio (series float)
eff_ratio (series float)
volRel_ratio (series float)
epr_ratio (series float)
EVR
Fields:
state (series int)
ZigZag forceLibrary "ZigZag"
method lastPivot(this)
Retrieves the last `Pivot` object's reference from a `ZigZag` object's `pivots`
array if it contains at least one element, or `na` if the array is empty.
Callable as a method or a function.
Namespace types: ZigZag
Parameters:
this (ZigZag) : (series ZigZag) The `ZigZag` object's reference.
Returns: (Pivot) The reference of the last `Pivot` instance in the `ZigZag` object's
`pivots` array, or `na` if the array is empty.
method update(this)
Updates a `ZigZag` object's pivot information, volume data, lines, and
labels when it detects new pivot points.
NOTE: This function requires a single execution on each bar for accurate
calculations.
Callable as a method or a function.
Namespace types: ZigZag
Parameters:
this (ZigZag) : (series ZigZag) The `ZigZag` object's reference.
Returns: (bool) `true` if the function detects a new pivot point and updates the
`ZigZag` object's data, `false` otherwise.
newInstance(settings)
Creates a new `ZigZag` instance with optional settings.
Parameters:
settings (Settings) : (series Settings) Optional. A `Settings` object's reference for the new
`ZigZag` instance's `settings` field. If `na`, the `ZigZag` instance
uses a new `Settings` object with default properties. The default is `na`.
Returns: (ZigZag) A new `ZigZag` object's reference.
Settings
A structure for objects that store calculation and display properties for `ZigZag` instances.
Fields:
devThreshold (series float) : The minimum percentage deviation from a previous pivot point required to change the Zig Zag's direction.
depth (series int) : The number of bars required for pivot point detection.
lineColor (series color) : The color of each line in the Zig Zag drawing.
extendLast (series bool) : Specifies whether the Zig Zag drawing includes a line connecting the most recent pivot point to the latest bar's `close`.
displayReversalPrice (series bool) : Specifies whether the Zig Zag drawing shows pivot prices in its labels.
displayCumulativeVolume (series bool) : Specifies whether the Zig Zag drawing shows the cumulative volume between pivot points in its labels.
displayReversalPriceChange (series bool) : Specifies whether the Zig Zag drawing shows the reversal amount from the previous pivot point in each label.
differencePriceMode (series string) : The reversal amount display mode. Possible values: `"Absolute"` for price change or `"Percent"` for percentage change.
draw (series bool) : Specifies whether the Zig Zag drawing displays its lines and labels.
allowZigZagOnOneBar (series bool) : Specifies whether the Zig Zag calculation can register a pivot high *and* pivot low on the same bar.
Pivot
A structure for objects that store chart point references, drawing references, and volume information for `ZigZag` instances.
Fields:
ln (series line) : References a `line` object that connects the coordinates from the `start` and `end` chart points.
lb (series label) : References a `label` object that displays pivot data at the `end` chart point's coordinates.
isHigh (series bool) : Specifies whether the pivot at the `end` chart point's coordinates is a pivot high.
vol (series float) : The cumulative volume across the bars between the `start` and `end` chart points.
start (chart.point) : References a `chart.point` object containing the coordinates of the previous pivot point.
end (chart.point) : References a `chart.point` object containing the coordinates of the current pivot point.
ZigZag
A structure for objects that maintain Zig Zag drawing settings, pivots, and cumulative volume data.
Fields:
settings (Settings) : References a `Settings` object that specifies the Zig Zag drawing's calculation and display properties.
pivots (array) : References an array of `Pivot` objects that store pivot point, drawing, and volume information.
sumVol (series float) : The cumulative volume across bars covered by the latest `Pivot` object's line segment.
extend (Pivot) : References a `Pivot` object that projects a line from the last confirmed pivot point to the current bar's `close`.
LO1_News2024H1Library "LO1_News2024H1"
Support Library for News Events
f_loadNewsRows()
f_loadExcSevByTypeId()
f_loadExcTagByTypeId()
f_loadExcDelayAfterNewsMins()
LO1_News2026H1Library "LO1_News2026H1"
Support Library for News Events
f_loadNewsRows()
f_loadExcSevByTypeId()
f_loadExcTagByTypeId()
f_loadExcDelayAfterNewsMins()
LO1_News2025H2Library "LO1_News2025H2"
Support Library for News Events
f_loadNewsRows()
f_loadExcSevByTypeId()
f_loadExcTagByTypeId()
f_loadExcDelayAfterNewsMins()
LO1_News2025H1Library "LO1_News2025H1"
Support Library for News Events
f_loadNewsRows()
f_loadExcSevByTypeId()
f_loadExcTagByTypeId()
f_loadExcDelayAfterNewsMins()
LO1_News2024H2Library "LO1_News2024H2"
Support Library for News Events
f_loadNewsRows()
f_loadExcSevByTypeId()
f_loadExcTagByTypeId()
f_loadExcDelayAfterNewsMins()
LO1_NewsTypesLibrary "LO1_NewsTypes" -
Support library for news system, allow selectable news events.
f_hhmmToMs(_hhmm)
Parameters:
_hhmm (int)
f_addNews(_d, _hhmm, _tid, _dArr, _tArr, _idArr)
Parameters:
_d (string)
_hhmm (int)
_tid (int)
_dArr (array)
_tArr (array)
_idArr (array)
f_addNewsMs(_d, _ms, _tid, _dArr, _tArr, _idArr)
Parameters:
_d (string)
_ms (int)
_tid (int)
_dArr (array)
_tArr (array)
_idArr (array)
f_loadTypeSevByTypeId()
LO1_TradersPostLibrary "LO1_TradersPost"
Enhanced TradersPost integration library with comprehensive order management
_buildJSONField(key, value, required)
Build a JSON field with proper handling of required vs optional fields
Parameters:
key (string) : The JSON key name
value (string) : The value to include (any type, will be converted to string)
required (bool) : If true, field is always included even if value is na/empty
Returns: String containing JSON field or empty string if optional and na/empty
_buildConditionalField(key, value)
Build a conditional JSON field that's only included if value is valid
Parameters:
key (string) : The JSON key name
value (string) : The value to include
Returns: String containing JSON field or empty string if value is na/empty
_buildConditionalNumericField(key, value)
Build a conditional JSON field for numeric values
Parameters:
key (string) : The JSON key name
value (float) : The numeric value
Returns: String containing JSON field or empty string if value is na
_buildNestedObject(objectType, price, amount, percent, stopType, limitPrice, trailAmount, trailPercent)
Build nested JSON objects for takeProfit/stopLoss
Parameters:
objectType (string) : The type of object being built ("takeProfit" or "stopLoss")
price (float) : The limit price for TP or stop price for SL
amount (float) : The dollar amount (optional)
percent (float) : The percentage (optional)
stopType (series StopLossType) : The stop loss type - only for stopLoss
limitPrice (float) : The limit price for stop_limit orders - only for stopLoss
trailAmount (float) : Trailing amount for trailing stops - only for stopLoss
trailPercent (float) : Trailing percent for trailing stops - only for stopLoss
Returns: String containing nested JSON object or empty string if no valid data
_validateAndBuildJSON(ticker, action, quantity, quantityType, orderType, sentiment, cancel, timeInForce, limitPrice, stopPrice, trailAmount, trailPercent, takeProfitPrice, takeProfitAmount, takeProfitPercent, stopLossPrice, stopLossAmount, stopLossPercent, stopLossType, stopLossLimitPrice, extendedHours, optionType, intrinsicValue, expiration, strikePrice, signalPrice, comment)
Master JSON builder that validates parameters and constructs JSON
Parameters:
ticker (string) : The trading symbol
action (series Action) : The order action (buy, sell, exit, etc.)
quantity (float) : The order quantity
quantityType (series QuantityType) : The type of quantity (fixed, dollar, percent)
orderType (series OrderType) : The order type (market, limit, stop, etc.)
sentiment (series Sentiment) : The position sentiment (long, short, flat) - optional
cancel (bool) : Controls order cancellation (true = cancel existing orders, false = don't cancel)
timeInForce (series TimeInForce) : Time in force for the order (DAY, GTC, IOC, FOK)
limitPrice (float) : Price for limit orders
stopPrice (float) : Price for stop orders
trailAmount (float) : Trailing amount for trailing stops
trailPercent (float) : Trailing percent for trailing stops
takeProfitPrice (float) : Take profit limit price (absolute)
takeProfitAmount (float) : Take profit dollar amount (relative)
takeProfitPercent (float) : Take profit percentage (relative)
stopLossPrice (float) : Stop loss price (absolute)
stopLossAmount (float) : Stop loss dollar amount (relative)
stopLossPercent (float) : Stop loss percentage (relative)
stopLossType (series StopLossType) : Stop loss order type
stopLossLimitPrice (float) : Limit price for stop_limit orders
extendedHours (bool) : Enable extended hours trading (boolean)
optionType (series OptionType) : Option type for options trading (both/call/put)
intrinsicValue (series IntrinsicValue) : Intrinsic value filter for options (itm/otm)
expiration (string) : Option expiration (date string)
strikePrice (float) : Option strike price
signalPrice (float) : The market price at alert time (for slippage tracking)
comment (string) : Optional comment for the order (shows in TradersPost UI for debugging)
Returns: ErrorResponse with success status and JSON string or error details
ValidateOrder(ticker, action, orderType, limitPrice, stopPrice)
Validate order parameters before JSON construction
Parameters:
ticker (string) : Trading symbol
action (series Action) : Order action
orderType (series OrderType) : Order type (market, limit, stop, etc.)
limitPrice (float) : Limit price for limit orders
stopPrice (float) : Stop price for stop orders
Returns: ErrorResponse with validation results
ValidateQuantity(quantity, quantityType)
Validate quantity based on type and constraints
Parameters:
quantity (float) : The quantity value
quantityType (series QuantityType) : The type of quantity
Returns: ErrorResponse with validation results
ValidatePrices(entryPrice, stopPrice, takeProfitPrice, action)
Validate price relationships and values
Parameters:
entryPrice (float) : Entry price for the order
stopPrice (float) : Stop loss price
takeProfitPrice (float) : Take profit price
action (series Action) : Order action (buy/sell)
Returns: ErrorResponse with validation results
ValidateSymbol(ticker)
Validate trading symbol format
Parameters:
ticker (string) : The symbol to validate
Returns: ErrorResponse with validation results
CombineValidationResults(validationResults)
Create validation error collection and reporting system
Parameters:
validationResults (array) : Array of ErrorResponse objects from multiple validations
Returns: Combined ErrorResponse with all validation results
ValidateCompleteOrder(ticker, action, quantity, quantityType, orderType, limitPrice, stopPrice, takeProfitPrice)
Comprehensive validation for all order parameters
Parameters:
ticker (string) : Trading symbol
action (series Action) : Order action
quantity (float) : Order quantity
quantityType (series QuantityType) : Type of quantity
orderType (series OrderType) : Order type
limitPrice (float) : Limit price (optional)
stopPrice (float) : Stop price (optional)
takeProfitPrice (float) : Take profit price (optional)
Returns: ErrorResponse with complete validation results
CreateErrorResponse(success, errorMessages, message, severity, context, functionName)
Create standardized error response
Parameters:
success (bool) : Whether the operation succeeded
errorMessages (array) : Array of error messages
message (string) : Summary message
severity (series ErrorSeverity) : Error severity level
context (string) : Context where error occurred
functionName (string) : Name of function that generated error
Returns: EnhancedErrorResponse with all error details
HandleValidationError(validationResult, context, functionName)
Handle validation errors with context
Parameters:
validationResult (ErrorResponse) : The validation result to handle
context (string) : Description of what was being validated
functionName (string) : Name of calling function
Returns: Processed error response with enhanced context
LogError(errorResponse, displayOnChart)
Log error with appropriate level
Parameters:
errorResponse (EnhancedErrorResponse) : The error response to log
displayOnChart (bool) : Whether to show error on chart
CreateSuccessResponse(message, context, functionName)
Create success response
Parameters:
message (string) : Success message
context (string) : Context of successful operation
functionName (string) : Name of function
Returns: Success response
_validateJSONConstruction(jsonString)
Validate JSON construction and handle malformed data
Parameters:
jsonString (string) : The constructed JSON string
Returns: ErrorResponse indicating if JSON is valid
CreateDetailedError(success, errors, warnings, severity, context)
Create detailed error response with context
Parameters:
success (bool) : Operation success status
errors (array) : Array of error messages
warnings (array) : Array of warning messages
severity (series ErrorSeverity) : Error severity level
context (string) : Context where error occurred
Returns: DetailedErrorResponse object
LogDetailedError(response)
Log detailed error response with appropriate severity
Parameters:
response (DetailedErrorResponse) : DetailedErrorResponse to log
Returns: Nothing - logs to Pine Script console
CombineIntoDetailedResponse(responses, context)
Combine multiple error responses into detailed response
Parameters:
responses (array) : Array of ErrorResponse objects to combine
context (string) : Context for the combined operation
Returns: DetailedErrorResponse with combined results
SendAdvancedOrder(ticker, action, quantity, quantityType, orderType, sentiment, cancel, limitPrice, stopPrice, trailAmount, trailPercent, takeProfitPrice, takeProfitAmount, takeProfitPercent, stopLossPrice, stopLossAmount, stopLossPercent, stopLossType, stopLossLimitPrice, extendedHours, optionType, intrinsicValue, expiration, strikePrice, signalPrice, comment)
Send advanced order with comprehensive parameter validation and JSON construction
Parameters:
ticker (string) : Symbol to trade (defaults to syminfo.ticker)
action (series Action) : Order action (buy/sell/exit/cancel/add)
quantity (float) : Order quantity
quantityType (series QuantityType) : Type of quantity (fixed/dollar/percent)
orderType (series OrderType) : Type of order (market/limit/stop/stop_limit/trailing_stop)
sentiment (series Sentiment) : Position sentiment (long/short/flat, optional)
cancel (bool) : Controls order cancellation (true = cancel existing, false = don't cancel, na = use defaults)
limitPrice (float) : Limit price for limit orders
stopPrice (float) : Stop price for stop orders
trailAmount (float) : Trailing amount for trailing stops
trailPercent (float) : Trailing percent for trailing stops
takeProfitPrice (float) : Take profit limit price (absolute)
takeProfitAmount (float) : Take profit dollar amount (relative)
takeProfitPercent (float) : Take profit percentage (relative)
stopLossPrice (float) : Stop loss price (absolute)
stopLossAmount (float) : Stop loss dollar amount (relative)
stopLossPercent (float) : Stop loss percentage (relative)
stopLossType (series StopLossType) : Stop loss order type
stopLossLimitPrice (float) : Limit price for stop_limit orders
extendedHours (bool) : Enable extended hours trading (boolean)
optionType (series OptionType) : Option type for options trading (both/call/put)
intrinsicValue (series IntrinsicValue) : Intrinsic value filter for options (itm/otm)
expiration (string) : Option expiration (date string)
strikePrice (float) : Option strike price
signalPrice (float) : The market price at alert time (for slippage tracking)
comment (string) : Optional comment for the order (shows in TradersPost UI for debugging)
Returns: ErrorResponse with success status and JSON or error details
SendSentiment(ticker, sentiment, quantity, quantityType, signalPrice, comment)
Send sentiment-based position management order
Parameters:
ticker (string) : Symbol to manage (defaults to syminfo.ticker)
sentiment (series Sentiment) : Target position sentiment (long/short/flat)
quantity (float) : Position size (optional, uses account default if not specified)
quantityType (series QuantityType) : Type of quantity specification
signalPrice (float) : The market price at alert time (for slippage tracking)
comment (string) : Optional comment
Returns: ErrorResponse with success status
SendCancelAll(ticker, comment)
Cancel all open orders for the specified symbol
Parameters:
ticker (string) : Symbol to cancel orders for (defaults to syminfo.ticker)
comment (string) : Optional comment for the cancellation
Returns: ErrorResponse with success status
SendOrderNoCancelExisting(ticker, action, quantity, quantityType, orderType, sentiment, limitPrice, stopPrice, takeProfitPrice, takeProfitAmount, takeProfitPercent, stopLossPrice, stopLossAmount, stopLossPercent, stopLossType, stopLossLimitPrice, signalPrice, comment)
Send order without canceling existing orders
Parameters:
ticker (string) : Symbol to trade (defaults to syminfo.ticker)
action (series Action) : Order action (buy/sell/exit)
quantity (float) : Order quantity
quantityType (series QuantityType) : Type of quantity (fixed/dollar/percent)
orderType (series OrderType) : Type of order (market/limit/stop/stop_limit)
sentiment (series Sentiment) : Position sentiment (long/short/flat, optional)
limitPrice (float) : Limit price for limit orders
stopPrice (float) : Stop price for stop orders
takeProfitPrice (float) : Take profit price
takeProfitAmount (float) : Take profit amount (optional)
takeProfitPercent (float)
stopLossPrice (float) : Stop loss price
stopLossAmount (float) : Stop loss amount (optional)
stopLossPercent (float) : Stop loss percentage (optional)
stopLossType (series StopLossType) : Stop loss order type
stopLossLimitPrice (float) : Limit price for stop_limit orders
signalPrice (float) : The market price at alert time (for slippage tracking)
comment (string) : Optional comment
Returns: ErrorResponse with success status
_buildBracketOrderParams(orderType, entryPrice, entryLimitPrice)
Build bracket order parameters by routing entryPrice to correct parameter based on orderType
This helper function maps the conceptual "entryPrice" to the technical parameters needed
Parameters:
orderType (series OrderType) : The order type for the entry order
entryPrice (float) : The desired entry price (trigger for stops, limit for limits)
entryLimitPrice (float) : The limit price for stop_limit orders (optional)
Returns: array with correct routing
SendBracketOrder(ticker, action, quantity, quantityType, orderType, entryPrice, entryLimitPrice, takeProfitPrice, stopLossPrice, takeProfitAmount, takeProfitPercent, stopLossAmount, stopLossPercent, stopLossType, stopLossLimitPrice, signalPrice, comment)
Send bracket order (entry + take profit + stop loss)
Parameters:
ticker (string) : Symbol to trade
action (series Action) : Entry action (buy/sell)
quantity (float) : Order quantity
quantityType (series QuantityType) : Type of quantity specification
orderType (series OrderType) : Type of entry order
entryPrice (float) : Entry price (trigger price for stop orders, limit price for limit orders)
entryLimitPrice (float) : Entry limit price (only for stop_limit orders, defaults to entryPrice if na)
takeProfitPrice (float) : Take profit price
stopLossPrice (float) : Stop loss price
takeProfitAmount (float) : Take profit dollar amount (alternative to price)
takeProfitPercent (float) : Take profit percentage (alternative to price)
stopLossAmount (float) : Stop loss dollar amount (alternative to price)
stopLossPercent (float) : Stop loss percentage (alternative to price)
stopLossType (series StopLossType) : Stop loss order type
stopLossLimitPrice (float) : Limit price for stop_limit orders
signalPrice (float) : The market price at alert time (for slippage tracking)
comment (string) : Optional comment
Returns: ErrorResponse with success status
SendOTOOrder(primaryTicker, primaryAction, primaryQuantity, primaryOrderType, primaryPrice, secondaryTicker, secondaryAction, secondaryQuantity, secondaryOrderType, secondaryPrice, signalPrice, comment)
Send One-Triggers-Other (OTO) order sequence
Note: OTO linking must be configured in TradersPost strategy settings
This sends two separate orders - TradersPost handles the OTO logic
Parameters:
primaryTicker (string) : Primary order ticker
primaryAction (series Action) : Primary order action
primaryQuantity (float) : Primary order quantity
primaryOrderType (series OrderType) : Primary entry type
primaryPrice (float) : Primary order price
secondaryTicker (string) : Secondary order ticker (defaults to primary ticker)
secondaryAction (series Action) : Secondary order action
secondaryQuantity (float) : Secondary order quantity
secondaryOrderType (series OrderType) : Secondary entry type
secondaryPrice (float) : Secondary order price
signalPrice (float) : The market price at alert time (for slippage tracking)
comment (string) : Optional comment for both orders
Returns: ErrorResponse with success status
SendOCOOrder(ticker, firstAction, firstQuantity, firstOrderType, firstPrice, secondAction, secondQuantity, secondOrderType, secondPrice, signalPrice, comment)
Send One-Cancels-Other (OCO) order pair
Note: OCO linking must be configured in TradersPost strategy settings
This sends two separate orders - TradersPost handles the OCO logic
Parameters:
ticker (string) : Symbol for both orders
firstAction (series Action) : Action for first order
firstQuantity (float) : Quantity for first order
firstOrderType (series OrderType) : Order type for first order
firstPrice (float) : Price for first order
secondAction (series Action) : Action for second order
secondQuantity (float) : Quantity for second order
secondOrderType (series OrderType) : Order type for second order
secondPrice (float) : Price for second order
signalPrice (float) : The market price at alert time (for slippage tracking)
comment (string) : Optional comment
Returns: ErrorResponse with success status
ErrorResponse
Fields:
success (series bool)
errors (array)
message (series string)
EnhancedErrorResponse
Fields:
success (series bool)
errors (array)
message (series string)
severity (series ErrorSeverity)
context (series string)
timestamp (series int)
functionName (series string)
DetailedErrorResponse
Fields:
success (series bool)
errors (array)
warnings (array)
severity (series ErrorSeverity)
context (series string)
message (series string)






















