HelperScriptA Personal Helper Script based on FFriZz/Holiday/2
Only change the font size and language
Indicateurs et stratégies
LunarSolverLunarSolver Library
Implements analytical approximations from Éphéméride Lunaire Parisienne (ELP2000-82B) lunar theory (Chapront-Touzé & Chapront). Uses truncated Fourier series of the main problem in Delaunay arguments D, l, l', F.
Exported functions:
delta_t(t_ms) → ΔT (seconds); polynomial fit valid ~1950–2050.
julian_day_tt(t_ms) → JD in Terrestrial Time from UTC millisecond timestamp.
jde_tt_to_utc_ms(jde_tt) → Approximate UTC millisecond timestamp from JD TT.
elp_true_distance_km_50(jd_tt) → Geocentric distance (km); 50 largest-amplitude terms.
elp_new_moon_solver_50(k) → JDE TT of new moon nearest lunation number k (k=0 ≈ 2000-01-06); 50-term longitude series + Newton-Raphson iteration (convergence <0.005 days).
elp_full_moon_solver_50(k) → JDE TT of full moon nearest k (k=0 ≈ 2000-01-21); 50-term longitude series + nutation correction + damped iteration (convergence <0.001 days).
Accuracy (truncation-limited):
- Distance: typically ± 10 - 100 km.
- Syzygy times: typically ± few minutes.
Import:
import telephonejack/LunarSolver/1 as lunar
Usage examples:
//@version=6
indicator("Lunar Distance Demo")
float jd_tt = lunar.julian_day_tt(time)
float dist_km = lunar.elp_true_distance_km_50(jd_tt)
plot(dist_km, "Distance (km)")
// Approximate lunation k for current bar
float k_approx = (lunar.julian_day_tt(time) - 2451550.25977) / 29.530588861
int k = math.round(k_approx)
float new_jde = lunar.elp_new_moon_solver_50(k)
float full_jde = lunar.elp_full_moon_solver_50(k)
Coefficients: top 50 terms by amplitude from ELP main problem series (radius vector & longitude). Phase solvers use longitude terms only. Library contains no latitude series.
Disclaimer: The library was developed with assistance from Grok 4.1, always under human supervision and decision-making.
ArgentinaBondsLib - Argentina Sovereign Bonds Cashflow LibraryArgentinaBondsLib
A Pine Script v6 library providing cashflow data and financial calculation functions for Argentine sovereign bonds (Bonares and Globales).
## Supported Bonds
**Bonares** (Argentina legislation, USD MEP): AE38, AL29, AL30, AL35, AL41, AN29
**Globales** (Foreign legislation, USD Cable): GD29, GD30, GD35, GD38, GD41, GD46
## Exported Functions
### Cashflow Data
- `getCashflows_ ()` - Returns timestamps, cashflows, and count for each bond
### Bond Identification
- `getBondType(ticker)` - Returns BONAR() or GLOBAL()
- `getBaseTicker(ticker)` - Extracts base ticker without prefix/suffix
- `getCurrencyType(ticker)` - Returns 0=ARS, 1=MEP, 2=Cable
- `isSupported(baseTicker)` - Checks if bond is supported
### Financial Calculations
- `calcPV()` - Present Value calculation
- `calcIRR()` - Internal Rate of Return using Newton-Raphson method
- `calcPriceFromIRR()` - Calculate price from target IRR
### Currency Conversion
- `convertToNativeCurrency()` - Converts price to cashflow currency (MEP for Bonares, Cable for Globales)
### Utilities
- `getSettlementDate()` - Returns T+1 timestamp
- `BONAR()` / `GLOBAL()` - Bond type constants
## Methodology
- Day count convention: Actual/365
- Settlement: T+1
- IRR solver: Newton-Raphson iterative method
## Usage Example
```
import EcoValores/ArgentinaBondsLib/1 as Bonds
= Bonds.getCashflows_AL30()
settlementDate = Bonds.getSettlementDate()
irr = Bonds.calcIRR(ts, cf, count, settlementDate, close)
```
---
## Español
Librería Pine Script v6 con datos de flujos de fondos y funciones de cálculo financiero para bonos soberanos argentinos.
### Bonos Soportados
- **Bonares** (Legislación argentina, USD MEP): AE38, AL29, AL30, AL35, AL41, AN29
- **Globales** (Legislación extranjera, USD Cable): GD29, GD30, GD35, GD38, GD41, GD46
### Metodología
- Convención de días: Actual/365
- Liquidación: T+1
- Solver TIR: Método iterativo Newton-Raphson
---
**DISCLAIMER**: This library is for informational and educational purposes only. Eco Valores S.A. does NOT provide investment advice or recommendations. Consult a qualified financial advisor before making investment decisions.
**AVISO LEGAL**: Esta librería es solo para fines informativos y educativos. Eco Valores S.A. NO brinda asesoramiento ni recomendaciones de inversión. Consulte con un asesor financiero calificado antes de invertir.
HTFStructCore_v2Library "HTFStructCore_v2"
f_structure_from_pivots(phSeries, plSeries)
Parameters:
phSeries (float)
plSeries (float)
f_adx_from_series(plusDMSeries, minusDMSeries, trSeries, adxLen)
Parameters:
plusDMSeries (float)
minusDMSeries (float)
trSeries (float)
adxLen (simple int)
f_retest_triggers(trendRaw, lastHigh, lastLow, retestTol, enableRetest)
Parameters:
trendRaw (int)
lastHigh (float)
lastLow (float)
retestTol (float)
enableRetest (bool)
f_sweep_triggers(trendRaw, sweepLookback, enableSweep)
Parameters:
trendRaw (int)
sweepLookback (int)
enableSweep (bool)
f_risk(lastLow, lastHigh, atrLen, atrStopMult, atrTpMult, preferTightStop)
Parameters:
lastLow (float)
lastHigh (float)
atrLen (simple int)
atrStopMult (float)
atrTpMult (float)
preferTightStop (bool)
HSLevelsLibPubLibrary "HSLevelsLibPub"
Centralized levels library for Heatseeker trading system.
Update levels HERE ONCE - all consuming scripts auto-refresh.
getVIXThresholds()
Returns VIX threshold levels for regime determination
Returns: as tuple of floats
getVIXThresholdsCSV()
Returns VIX thresholds as CSV strings
Returns: as tuple of strings
getExpiry()
Returns current options expiry date in YYMMDD format
Returns: string in YYMMDD format (e.g., "260108" for Jan 8, 2026)
getAnchorStrike(symbol)
Returns the anchor strike price for a given symbol
Parameters:
symbol (simple string) : The ticker symbol (SPY, QQQ, SPX, VIX)
Returns: float anchor strike price
getFractalPrices(symbol)
Returns fractal level prices as CSV for a symbol
Parameters:
symbol (simple string) : The ticker symbol (SPY, QQQ, SPX)
Returns: string of comma-separated prices
getFractalLabels(symbol)
Returns fractal level labels as CSV for a symbol
Parameters:
symbol (simple string) : The ticker symbol (SPY, QQQ, SPX)
Returns: string of comma-separated labels
getFractalLevels(symbol)
Returns both fractal prices and labels as CSV tuple
Parameters:
symbol (simple string) : The ticker symbol
Returns: tuple
getAnchorStrikeAuto()
Auto-detect symbol and return appropriate anchor strike
Returns: float anchor strike for current chart symbol
getFractalLevelsAuto()
Auto-detect symbol and return fractal levels
Returns: for current chart symbol
getAllData(symbol)
Get all data for a symbol in one call
Parameters:
symbol (simple string) : The ticker symbol
Returns:
getVersion()
Returns library version and last update timestamp
Returns: string with version info
CoreLibrary "Core"
inRTH()
gapFlags(prevDayClose, gapPct)
Parameters:
prevDayClose (float)
gapPct (float)
gapInfo(prevClose)
Parameters:
prevClose (float)
relativeVolume(len)
Parameters:
len (int)
barSeconds()
barSecondsOpt(rthSecondsDefault)
Parameters:
rthSecondsDefault (int)
relVolRealtime(len)
Parameters:
len (int)
mtfAlign(htfEma, tol)
Parameters:
htfEma (float)
tol (float)
htfDistanceAbs(htfEma, fallback)
Parameters:
htfEma (float)
fallback (float)
mtfState(htfEma, tol)
Parameters:
htfEma (float)
tol (float)
adaptiveLength(rocLen, minSmooth, maxSmooth, useAdaptive, baseSmoothing, speedLookback)
Parameters:
rocLen (int)
minSmooth (int)
maxSmooth (int)
useAdaptive (bool)
baseSmoothing (int)
speedLookback (int)
adaptiveTrend(src, adaptiveLen)
Parameters:
src (float)
adaptiveLen (float)
atrBands(atrLen, atrMult, basis)
Parameters:
atrLen (simple int)
atrMult (float)
basis (float)
calcTrendStrength(closePrice, fastEMA, slowEMA, volumeConfirmed, speedConfirmed)
Parameters:
closePrice (float)
fastEMA (float)
slowEMA (float)
volumeConfirmed (bool)
speedConfirmed (bool)
calcMovementPotential(inExpansionZone, trendStrength, speedConfirmed)
Parameters:
inExpansionZone (bool)
trendStrength (int)
speedConfirmed (bool)
combineSignalScore(trendStrength, movementPotential, mtfBonus, volumeSurgeBonus)
Parameters:
trendStrength (int)
movementPotential (int)
mtfBonus (int)
volumeSurgeBonus (int)
strength10(dirLong, volRatio, htfDistance, isTraditional, isAltPattern, bodySize, rsi)
Parameters:
dirLong (bool)
volRatio (float)
htfDistance (float)
isTraditional (bool)
isAltPattern (bool)
bodySize (float)
rsi (float)
sessionProfile()
microstructure(lookback)
Parameters:
lookback (int)
normalizePressure(pressure, lookback)
Parameters:
pressure (float)
lookback (int)
tickPressureNorm(lb)
Parameters:
lb (int)
zscore(x, lb)
Parameters:
x (float)
lb (int)
tickPressureZ(lb)
Parameters:
lb (int)
strength10DayTrade(dirLong, volRatio, htfDistance, isTraditional, isAltPattern, bodySize, rsi, sessionBonus, tickPressure)
Parameters:
dirLong (bool)
volRatio (float)
htfDistance (float)
isTraditional (bool)
isAltPattern (bool)
bodySize (float)
rsi (float)
sessionBonus (bool)
tickPressure (float)
vwapBands(vwap, length)
Parameters:
vwap (float)
length (int)
vwapChop(vwap, dev, atrPct, rsi)
Parameters:
vwap (float)
dev (float)
atrPct (float)
rsi (float)
calcRiskReward(entry, stop, tp1, tp2, tp3, shares)
Parameters:
entry (float)
stop (float)
tp1 (float)
tp2 (float)
tp3 (float)
shares (float)
squeezeBBKC()
marketRegime(lookback)
Parameters:
lookback (int)
squeezeBucket(ratio)
Parameters:
ratio (float)
dynamicCooldown(baseBars, atrPct, inChop, maxBars)
Parameters:
baseBars (int)
atrPct (float)
inChop (bool)
maxBars (int)
vwapMode(inChop)
Parameters:
inChop (bool)
toPctStr(x)
Parameters:
x (float)
yesNo(b)
Parameters:
b (bool)
trendLabel(state)
Parameters:
state (int)
minRByPct(price, pct)
Parameters:
price (float)
pct (float)
vwapChopScore(vwap, dev, atrPct, rsi)
Parameters:
vwap (float)
dev (float)
atrPct (float)
rsi (float)
strengthGateSuggest(isQualityTime, inChop, baseGate)
Parameters:
isQualityTime (bool)
inChop (bool)
baseGate (int)
cooldownReason(atrPct, inChop)
Parameters:
atrPct (float)
inChop (bool)
readyGates(isQualityTime, inChop, relVol, atrPct, baseGate)
Parameters:
isQualityTime (bool)
inChop (bool)
relVol (float)
atrPct (float)
baseGate (int)
readyVerdict(isLong, mtfStateVal, relVol, atrPercent, strengthScore, strengthGate)
Parameters:
isLong (bool)
mtfStateVal (int)
relVol (float)
atrPercent (float)
strengthScore (int)
strengthGate (int)
structuralStops(isLong, sigLow, sigHigh, vwap, dev, atr, stopBufAtr)
Parameters:
isLong (bool)
sigLow (float)
sigHigh (float)
vwap (float)
dev (float)
atr (float)
stopBufAtr (float)
emaSlopePct(ema, bars)
Parameters:
ema (float)
bars (int)
atrPct(len)
Parameters:
len (simple int)
cooldownStatus(lastSigBar, cooldownBars)
Parameters:
lastSigBar (int)
cooldownBars (int)
emaSlopeSign(ema, bars)
Parameters:
ema (float)
bars (int)
barProgress()
rthMarkers()
badge(ok)
Parameters:
ok (bool)
triBadge(x)
Parameters:
x (int)
priceAcceptanceAdaptive(minBodyFrac)
Parameters:
minBodyFrac (float)
speedConfirmed(rocLen, emaLen, smaLen)
Parameters:
rocLen (int)
emaLen (simple int)
smaLen (int)
setupScore(isLoose, isNormal, vwapTrend, emaUp, mtfBull, relVolOK, microOK, cooldownOK)
Parameters:
isLoose (bool)
isNormal (bool)
vwapTrend (bool)
emaUp (bool)
mtfBull (bool)
relVolOK (bool)
microOK (bool)
cooldownOK (bool)
setupTier(score)
Parameters:
score (int)
setupQuality(score)
Parameters:
score (int)
setupQualityColor(score)
Parameters:
score (int)
setupScoreDir(isLong, isLoose, isNormal, vwapTrend, emaUp, mtfBull, relVolOK, priceAccept, tickNorm, cooldownOK)
Parameters:
isLong (bool)
isLoose (bool)
isNormal (bool)
vwapTrend (bool)
emaUp (bool)
mtfBull (bool)
relVolOK (bool)
priceAccept (bool)
tickNorm (float)
cooldownOK (bool)
setupScoresBoth(isLoose, isNormal, vwapTrend, emaUp, mtfBull, relVolOK, priceAccept, tickNorm, cooldownOK)
Parameters:
isLoose (bool)
isNormal (bool)
vwapTrend (bool)
emaUp (bool)
mtfBull (bool)
relVolOK (bool)
priceAccept (bool)
tickNorm (float)
cooldownOK (bool)
ruleGatesDir(isLong, squeezeTight, emaUp, vwapTrend, relVol, relVolThresh, tickNorm, useSqzGate, useEmaGate, useVwapGate, useVolGate, useMicroGate)
Parameters:
isLong (bool)
squeezeTight (bool)
emaUp (bool)
vwapTrend (bool)
relVol (float)
relVolThresh (float)
tickNorm (float)
useSqzGate (bool)
useEmaGate (bool)
useVwapGate (bool)
useVolGate (bool)
useMicroGate (bool)
ruleGates(squeezeTight, emaUp, vwapTrend, relVol, relVolThresh, tickNorm, useSqzGate, useVwapGate, useVolGate, useMicroGate)
Parameters:
squeezeTight (bool)
emaUp (bool)
vwapTrend (bool)
relVol (float)
relVolThresh (float)
tickNorm (float)
useSqzGate (bool)
useVwapGate (bool)
useVolGate (bool)
useMicroGate (bool)
arrowColor(bucket, baseColor, useRegimeColor)
Parameters:
bucket (string)
baseColor (color)
useRegimeColor (bool)
orbHiLo(minutes)
Parameters:
minutes (int)
prevDayHL()
GATS_LibLibrary "GATS_Lib"
GATS 선물/현물 자동매매를 위한 신호 생성 라이브러리
init(password, exchange, ticker, leverage, start_time, end_time)
Parameters:
password (string)
exchange (string)
ticker (string)
leverage (int)
start_time (int)
end_time (int)
method entry_long(bot, id, qty, comment)
Namespace types: Bot
Parameters:
bot (Bot)
id (string)
qty (float)
comment (string)
method entry_short(bot, id, qty, comment)
Namespace types: Bot
Parameters:
bot (Bot)
id (string)
qty (float)
comment (string)
method close(bot, id, comment)
Namespace types: Bot
Parameters:
bot (Bot)
id (string)
comment (string)
method close_all(bot, comment)
Namespace types: Bot
Parameters:
bot (Bot)
comment (string)
Bot
Fields:
password (series string)
exchange (series string)
ticker (series string)
leverage (series int)
start_time (series int)
end_time (series int)
[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.
EMTIA_MASTER_LIBLibrary "EMTIA_MASTER_LIB"
trendUp(emaFast, emaSlow)
Parameters:
emaFast (float)
emaSlow (float)
rsiHealthy(rsi)
Parameters:
rsi (float)
adxStrong(adx, diPlus, diMinus)
Parameters:
adx (float)
diPlus (float)
diMinus (float)
macroSlope(emaFast, emaSlow)
Parameters:
emaFast (float)
emaSlow (float)
structureBull(hh, hl)
Parameters:
hh (bool)
hl (bool)
calcScore(weeklyTrend, dailyTrend, adxOk, rsiOk, structureOk, macroOk)
Parameters:
weeklyTrend (bool)
dailyTrend (bool)
adxOk (bool)
rsiOk (bool)
structureOk (bool)
macroOk (bool)
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)
News2024H1Library "News2024H1" - This contains news events from 2024 H1 News Events
f_loadNewsRows()
f_loadExcSevByTypeId()
f_loadExcTagByTypeId()
SPX_0DTE_EngineLibrary "SPX_0DTE_Engine"
getATM(price)
Parameters:
price (float)
getCallStrikes(atmStrike, count)
Parameters:
atmStrike (int)
count (int)
getPutStrikes(atmStrike, count)
Parameters:
atmStrike (int)
count (int)
generateOCCSymbol(underlying, year, month, day, optionType, strike)
Parameters:
underlying (string)
year (int)
month (int)
day (int)
optionType (string)
strike (int)
getAdaptiveReference(src, lookback)
Parameters:
src (float)
lookback (int)
detectLiquidityGrabHigh(high, low, close, volume, lookback)
Parameters:
high (float)
low (float)
close (float)
volume (float)
lookback (int)
detectLiquidityGrabLow(high, low, close, volume, lookback)
Parameters:
high (float)
low (float)
close (float)
volume (float)
lookback (int)
getVolatilityRegime(src, bbLength, bbMult)
Parameters:
src (float)
bbLength (int)
bbMult (float)
getESConfirmation(spxClose, esClose, spxHigh, esHigh, spxLow, esLow, lookback)
Parameters:
spxClose (float)
esClose (float)
spxHigh (float)
esHigh (float)
spxLow (float)
esLow (float)
lookback (int)
getDeltaBias(src, adaptiveRef, esClose, spxClose)
Parameters:
src (float)
adaptiveRef (float)
esClose (float)
spxClose (float)
getGammaZone(src, atmStrike)
Parameters:
src (float)
atmStrike (int)
getVegaRegime(vixSymbol)
Parameters:
vixSymbol (simple string)
isFailState(volRegime, hour, minute, vix, atr)
Parameters:
volRegime (int)
hour (int)
minute (int)
vix (float)
atr (float)
checkCallConfluence(liquidityGrabLow, volRegime, esConfirmation, failState, deltaBias, lowGamma)
Parameters:
liquidityGrabLow (bool)
volRegime (int)
esConfirmation (int)
failState (bool)
deltaBias (int)
lowGamma (bool)
checkPutConfluence(liquidityGrabHigh, volRegime, esConfirmation, failState, deltaBias, lowGamma)
Parameters:
liquidityGrabHigh (bool)
volRegime (int)
esConfirmation (int)
failState (bool)
deltaBias (int)
lowGamma (bool)
checkProfitTarget(entryPrice, currentPrice, targetPercent, isCall)
Parameters:
entryPrice (float)
currentPrice (float)
targetPercent (float)
isCall (bool)
checkStopLoss(entryPrice, currentPrice, stopPercent, isCall)
Parameters:
entryPrice (float)
currentPrice (float)
stopPercent (float)
isCall (bool)
checkTimeExit(hour, minute)
Parameters:
hour (int)
minute (int)
checkInvalidation(esConfirmation, isCallPosition)
Parameters:
esConfirmation (int)
isCallPosition (bool)
GaussianWavePacketLibrary "GaussianWavePacket"
gaussianEnvelope(gamma, t, t0)
Parameters:
gamma (float)
t (int)
t0 (int)
oscillatorReal(omega, t, phase)
Parameters:
omega (float)
t (int)
phase (float)
oscillatorImag(omega, t, phase)
Parameters:
omega (float)
t (int)
phase (float)
wavePacket(amplitude, gamma, omega, t, t0, phase)
Parameters:
amplitude (float)
gamma (float)
omega (float)
t (int)
t0 (int)
phase (float)
estimateGamma(amplitudeCurrent, amplitudePast, timeDelta)
Parameters:
amplitudeCurrent (float)
amplitudePast (float)
timeDelta (int)
periodToOmega(period)
Parameters:
period (float)
omegaToPeriod(omega)
Parameters:
omega (float)






















