Dhan_libLibrary "Dhan_lib"
Overview
Dhan_lib is a Pine Script v6 library designed to help traders automate trading orders via TradingView alerts and webhook integration with the Dhan broker API.
This library generates JSON-formatted alert messages for the following instruments.
Equity (Intraday and Delivery)
Options (CE and PE Buy and Sell)
Futures (Buy and Sell)
These alert strings can be directly used inside TradingView alerts to place live orders through an external webhook setup.
🔹 Supported Instruments
Equity
Intraday Buy and Sell
Delivery Buy and Sell
Options
Call (CE) Buy and Sell
Put (PE) Buy and Sell
ATM, ITM, and OTM strike selection
Intraday and Carry Forward
Futures
Buy and Sell
Intraday and Carry Forward
🔹 Key Features
✅ Pine Script v6 compatible
✅ Clean and reusable library functions
✅ Automatic ATM, ITM, and OTM strike calculation
✅ Expiry date handled via string format YYYY-MM-DD
✅ Fully webhook-ready JSON alert structure
✅ Supports multi-leg order format
✅ Designed for TradingView to Dhan automation
🔹 How to Use
Import the library in your strategy or indicator.
import Shivam_Mandrai/Dhan_lib/1
Call the required function.
order_msg = buy_CE_option("YOUR_SECRET_KEY", "NIFTY", 1)
Use the returned string as the alert message.
alert(order_msg, alert.freq_once_per_bar)
Connect TradingView alerts to your Dhan webhook receiver.
---
🔹 Important Notes
Strike prices are calculated dynamically based on the current chart price (close).
Futures symbols use TradingView continuous contract format such as NIFTY1!.
Quantity refers to the number of lots, not the lot size.
Expiry date must be provided in YYYY-MM-DD format.
⚠️ DISCLAIMER (PLEASE READ CAREFULLY)
This library is provided strictly for educational and automation purposes only.
I am not a SEBI-registered advisor.
I do not guarantee any profit or accuracy of orders.
I am not responsible for any financial loss, missed trades, execution errors, or broker-side issues.
Trading in stocks, options, and futures involves significant risk.
Automated trading can fail due to internet issues, broker API downtime, incorrect webhook configuration, slippage, or market volatility.
👉 Use this library entirely at your own risk.
👉 Always test thoroughly using paper trading or simulation before deploying with real capital.
If you want, I can also:
* Shrink this further for TradingView character limits
* Convert it into a single-paragraph version
* Localize it for Indian retail traders
buy_stock_intraday(secret_key, symbol, qty, exchange)
to buy the stock Intraday
Parameters:
secret_key (string) : string Secret Key of the Dhan Account eg-> "S1HgS".
symbol (string) : string Stock symbol eg-> "TATASTEEL".
qty (int) : int quantity for the order eg-> 1.
exchange (string) : string Trading Exchange eg-> "NSE".
Returns: order string.
sell_stock_intraday(secret_key, symbol, qty, exchange)
to sell the stock Intraday
Parameters:
secret_key (string) : string Secret Key of the Dhan Account eg-> "S1HgS".
symbol (string) : string Stock symbol eg-> "TATASTEEL".
qty (int) : int quantity for the order eg-> 1.
exchange (string) : string Trading Exchange eg-> "NSE".
Returns: order string.
buy_stock_delivery(secret_key, symbol, qty, exchange)
to buy the stock delivery
Parameters:
secret_key (string) : string Secret Key of the Dhan Account eg-> "S1HgS".
symbol (string) : string Stock symbol eg-> "TATASTEEL".
qty (int) : int quantity for the order eg-> 1.
exchange (string) : string Trading Exchange eg-> "NSE".
Returns: order string.
sell_stock_delivery(secret_key, symbol, qty, exchange)
to sell the stock delivery
Parameters:
secret_key (string) : string Secret Key of the Dhan Account eg-> "S1HgS".
symbol (string) : string Stock symbol eg-> "TATASTEEL".
qty (int) : int quantity for the order eg-> 1.
exchange (string) : string Trading Exchange eg-> "NSE".
Returns: order string.
buy_CE_option(secret_key, symbol, lots, expiry_date, intraday, strike_price_base, ITM_points, OTM_points, exchange)
to buy CE option
Parameters:
secret_key (string) : string Secret Key of the Dhan Account eg-> "S1HgS".
symbol (string) : string Index / Stock symbol eg-> "NIFTY", "BANKNIFTY".
lots (int) : int Number of lots eg-> 1.
expiry_date (string) : string Option expiry date in YYYY-MM-DD format eg-> "2026-01-20".
intraday (bool) : bool Set true for intraday order, set false for delivery order eg-> true.
strike_price_base (float) : float Strike price step size eg-> 50, 100 (default is 100).
ITM_points (float) : float Points below CMP to select ITM strike eg-> 100 (default is 0).
OTM_points (float) : float Points above CMP to select OTM strike eg-> 100 (default is 0).
exchange (string) : string Trading Exchange eg-> "NSE" (default is NSE).
Returns: order string.
buy_PE_option(secret_key, symbol, lots, expiry_date, intraday, strike_price_base, ITM_points, OTM_points, exchange)
to buy PE option
Parameters:
secret_key (string) : string Secret Key of the Dhan Account eg-> "S1HgS".
symbol (string) : string Index / Stock symbol eg-> "NIFTY", "BANKNIFTY".
lots (int) : int Number of lots eg-> 1.
expiry_date (string) : string Option expiry date in YYYY-MM-DD format eg-> "2026-01-20".
intraday (bool) : bool Set true for intraday order, set false for delivery order eg-> true.
strike_price_base (float) : float Strike price step size eg-> 50, 100 (default is 100).
ITM_points (float) : float Points below CMP to select ITM strike eg-> 100 (default is 0).
OTM_points (float) : float Points above CMP to select OTM strike eg-> 100 (default is 0).
exchange (string) : string Trading Exchange eg-> "NSE" (default is NSE).
Returns: order string.
sell_CE_option(secret_key, symbol, lots, expiry_date, intraday, strike_price_base, ITM_points, OTM_points, exchange)
to Sell CE option
Parameters:
secret_key (string) : string Secret Key of the Dhan Account eg-> "S1HgS".
symbol (string) : string Index / Stock symbol eg-> "NIFTY", "BANKNIFTY".
lots (int) : int Number of lots eg-> 1.
expiry_date (string) : string Option expiry date in YYYY-MM-DD format eg-> "2026-01-20".
intraday (bool) : bool Set true for intraday order, set false for delivery order eg-> true.
strike_price_base (float) : float Strike price step size eg-> 50, 100 (default is 100).
ITM_points (float) : float Points below CMP to select ITM strike eg-> 100 (default is 0).
OTM_points (float) : float Points above CMP to select OTM strike eg-> 100 (default is 0).
exchange (string) : string Trading Exchange eg-> "NSE" (default is NSE).
Returns: order string.
sell_PE_option(secret_key, symbol, lots, expiry_date, intraday, strike_price_base, ITM_points, OTM_points, exchange)
to sell PE option
Parameters:
secret_key (string) : string Secret Key of the Dhan Account eg-> "S1HgS".
symbol (string) : string Index / Stock symbol eg-> "NIFTY", "BANKNIFTY".
lots (int) : int Number of lots eg-> 1.
expiry_date (string) : string Option expiry date in YYYY-MM-DD format eg-> "2026-01-20".
intraday (bool) : bool Set true for intraday order, set false for delivery order eg-> true.
strike_price_base (float) : float Strike price step size eg-> 50, 100 (default is 100).
ITM_points (float) : float Points below CMP to select ITM strike eg-> 100 (default is 0).
OTM_points (float) : float Points above CMP to select OTM strike eg-> 100 (default is 0).
exchange (string) : string Trading Exchange eg-> "NSE" (default is NSE).
Returns: order string.
buy_future(secret_key, symbol, lot, intraday, exchange)
to buy the Future
Parameters:
secret_key (string) : string Secret Key of the Dhan Account eg-> "S1HgS".
symbol (string) : string Stock symbol eg-> "NIFTY".
lot (int) : int quantity for the order eg-> 1.
intraday (bool) : bool Set true for intraday order, set false for delivery order eg-> true.
exchange (string) : string Trading Exchange eg-> "NSE".
Returns: order string.
sell_future(secret_key, symbol, lot, intraday, exchange)
to sell the Future
Parameters:
secret_key (string) : string Secret Key of the Dhan Account eg-> "S1HgS".
symbol (string) : string Stock symbol eg-> "NIFTY".
lot (int) : int quantity for the order eg-> 1.
intraday (bool) : bool Set true for intraday order, set false for delivery order eg-> true.
exchange (string) : string Trading Exchange eg-> "NSE".
Returns: order string.
Indicators and strategies
RVOL_Core_NSELibrary "RVOL_Core_NSE"
f_rvol(lookbackDays, isNewDay, msSinceSessionStart, volume)
Parameters:
lookbackDays (int)
isNewDay (bool)
msSinceSessionStart (int)
volume (float)
T5_TradeEngineLibrary "T5_TradeEngine"
tick(close_, high_, low_, ema21, ema50, ema200, atrPct, emaGapPct, btcEma50, btcEma200, btcFilterEffective, isBarClose, crossUp21_50, crossDown21_50, allowEntries, exitOnOppositeCross, feeBps, useSR_TPSL, srLeft, srRight, srLookbackPivots, srBufferPct, srMinDistPct, srMinNetAfterFeesPct, srFallbackToATR, tp1CapPct, slCapPct, useTP2Trail, trailExitOnCloseOnly, tp2CapPct, trailCapPct, holdBars)
Parameters:
close_ (float)
high_ (float)
low_ (float)
ema21 (float)
ema50 (float)
ema200 (float)
atrPct (float)
emaGapPct (float)
btcEma50 (float)
btcEma200 (float)
btcFilterEffective (bool)
isBarClose (bool)
crossUp21_50 (bool)
crossDown21_50 (bool)
allowEntries (bool)
exitOnOppositeCross (bool)
feeBps (float)
useSR_TPSL (bool)
srLeft (int)
srRight (int)
srLookbackPivots (int)
srBufferPct (float)
srMinDistPct (float)
srMinNetAfterFeesPct (float)
srFallbackToATR (bool)
tp1CapPct (float)
slCapPct (float)
useTP2Trail (bool)
trailExitOnCloseOnly (bool)
tp2CapPct (float)
trailCapPct (float)
holdBars (int)
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.
BarCoreLibrary "BarCore"
BarCore is a foundational library for technical analysis, providing essential functions for evaluating the structural properties of candlesticks and inter-bar relationships.
It prioritizes ratio-based metrics (0.0 to 1.0) over absolute prices, making it asset-agnostic and ideal for robust pattern recognition, momentum analysis, and volume-weighted pressure evaluation.
Key modules:
- Structure & Range: High-precision bar and body metrics with relative positioning.
- Wick Dynamics: Absolute and relative wick analysis for identifying price rejection.
- Inter-bar Logic: Containment, coverage, and quantitative price overlap (Ratio-based).
- Gap Intelligence: Real body and price gaps with customizable significance thresholds.
- Flow & Pressure: Volume-weighted buying/selling pressure and Money Flow metrics.
isBuyingBar()
Checks if the bar is a bullish (up) bar, where close is greater than open.
Returns: bool True if the bar closed higher than it opened.
isSellingBar()
Checks if the bar is a bearish (down) bar, where close is less than open.
Returns: bool True if the bar closed lower than it opened.
barMidpoint()
Calculates the absolute midpoint of the bar's total range (High + Low) / 2.
Returns: float The midpoint price of the bar.
barRange()
Calculates the absolute size of the bar's total range (High to Low).
Returns: float The absolute difference between high and low.
barRangeMidpoint()
Calculates half of the bar's total range size.
Returns: float Half the bar's range size.
realBodyHigh()
Returns the higher price between the open and close.
Returns: float The top of the real body.
realBodyLow()
Returns the lower price between the open and close.
Returns: float The bottom of the real body.
realBodyMidpoint()
Calculates the absolute midpoint of the bar's real body.
Returns: float The midpoint price of the real body.
realBodyRange()
Calculates the absolute size of the bar's real body.
Returns: float The absolute difference between open and close.
realBodyRangeMidpoint()
Calculates half of the bar's real body size.
Returns: float Half the real body size.
upperWickRange()
Calculates the absolute size of the upper wick.
Returns: float The range from high to the real body high.
lowerWickRange()
Calculates the absolute size of the lower wick.
Returns: float The range from the real body low to low.
openRatio()
Returns the location of the open price relative to the bar's total range (0.0 at low to 1.0 at high).
Returns: float The ratio of the distance from low to open, divided by the total range.
closeRatio()
Returns the location of the close price relative to the bar's total range (0.0 at low to 1.0 at high).
Returns: float The ratio of the distance from low to close, divided by the total range.
realBodyRatio()
Calculates the ratio of the real body size to the total bar range.
Returns: float The real body size divided by the bar range. Returns 0 if barRange is 0.
upperWickRatio()
Calculates the ratio of the upper wick size to the total bar range.
Returns: float The upper wick size divided by the bar range. Returns 0 if barRange is 0.
lowerWickRatio()
Calculates the ratio of the lower wick size to the total bar range.
Returns: float The lower wick size divided by the bar range. Returns 0 if barRange is 0.
upperWickToBodyRatio()
Calculates the ratio of the upper wick size to the real body size.
Returns: float The upper wick size divided by the real body size. Returns 0 if realBodyRange is 0.
lowerWickToBodyRatio()
Calculates the ratio of the lower wick size to the real body size.
Returns: float The lower wick size divided by the real body size. Returns 0 if realBodyRange is 0.
totalWickRatio()
Calculates the ratio of the total wick range (Upper Wick + Lower Wick) to the total bar range.
Returns: float The total wick range expressed as a ratio of the bar's total range. Returns 0 if barRange is 0.
isBodyExpansion()
Checks if the current bar's real body range is larger than the previous bar's real body range (body expansion).
Returns: bool True if realBodyRange() > realBodyRange() .
isBodyContraction()
Checks if the current bar's real body range is smaller than the previous bar's real body range (body contraction).
Returns: bool True if realBodyRange() < realBodyRange() .
isWithinPrevBar(inclusive)
Checks if the current bar's range is entirely within the previous bar's range.
Parameters:
inclusive (bool) : If true, allows equality (<=, >=). Default is false.
Returns: bool True if High < High AND Low > Low .
isCoveringPrevBar(inclusive)
Checks if the current bar's range fully covers the entire previous bar's range.
Parameters:
inclusive (bool) : If true, allows equality (<=, >=). Default is false.
Returns: bool True if High > High AND Low < Low .
isWithinPrevBody(inclusive)
Checks if the current bar's real body is entirely inside the previous bar's real body.
Parameters:
inclusive (bool) : If true, allows equality (<=, >=). Default is false.
Returns: bool True if the current body is contained inside the previous body.
isCoveringPrevBody(inclusive)
Checks if the current bar's real body fully covers the previous bar's real body.
Parameters:
inclusive (bool) : If true, allows equality (<=, >=). Default is false.
Returns: bool True if the current body fully covers the previous body.
isOpenWithinPrevBody(inclusive)
Checks if the current bar's open price falls within the real body range of the previous bar.
Parameters:
inclusive (bool) : If true, includes the boundary prices. Default is false.
Returns: bool True if the open price is between the previous bar's real body high and real body low.
isCloseWithinPrevBody(inclusive)
Checks if the current bar's close price falls within the real body range of the previous bar.
Parameters:
inclusive (bool) : If true, includes the boundary prices. Default is false.
Returns: bool True if the close price is between the previous bar's real body high and real body low.
isPrevOpenWithinBody(inclusive)
Checks if the previous bar's open price falls within the current bar's real body range.
Parameters:
inclusive (bool) : If true, includes the boundary prices. Default is false.
Returns: bool True if open is between the current bar's real body high and real body low.
isPrevCloseWithinBody(inclusive)
Checks if the previous bar's closing price falls within the current bar's real body range.
Parameters:
inclusive (bool) : If true, includes the boundary prices. Default is false.
Returns: bool True if close is between the current bar's real body high and real body low.
isOverlappingPrevBar()
Checks if there is any price overlap between the current bar's range and the previous bar's range.
Returns: bool True if the current bar's range has any intersection with the previous bar's range.
bodyOverlapRatio()
Calculates the percentage of the current real body that overlaps with the previous real body.
Returns: float The overlap ratio (0.0 to 1.0). 1.0 means the current body is entirely within the previous body's price range.
isCompletePriceGapUp()
Checks for a complete price gap up where the current bar's low is strictly above the previous bar's high, meaning there is zero price overlap between the two bars.
Returns: bool True if the current low is greater than the previous high.
isCompletePriceGapDown()
Checks for a complete price gap down where the current bar's high is strictly below the previous bar's low, meaning there is zero price overlap between the two bars.
Returns: bool True if the current high is less than the previous low.
isRealBodyGapUp()
Checks for a gap between the current and previous real bodies.
Returns: bool True if the current body is completely above the previous body.
isRealBodyGapDown()
Checks for a gap between the current and previous real bodies.
Returns: bool True if the current body is completely below the previous body.
gapRatio()
Calculates the percentage difference between the current open and the previous close, expressed as a decimal ratio.
Returns: float The gap ratio (positive for gap up, negative for gap down). Returns 0 if the previous close is 0.
gapPercentage()
Calculates the percentage difference between the current open and the previous close.
Returns: float The gap percentage (positive for gap up, negative for gap down). Returns 0 if previous close is 0.
isGapUp()
Checks for a basic gap up, where the current bar's open is strictly higher than the previous bar's close. This is the minimum condition for a gap up.
Returns: bool True if the current open is greater than the previous close (i.e., gapRatio is positive).
isGapDown()
Checks for a basic gap down, where the current bar's open is strictly lower than the previous bar's close. This is the minimum condition for a gap down.
Returns: bool True if the current open is less than the previous close (i.e., gapRatio is negative).
isSignificantGapUp(minRatio)
Checks if the current bar opened significantly higher than the previous close, as defined by a minimum percentage ratio.
Parameters:
minRatio (float) : The minimum required gap percentage ratio. Default is 0.03 (3%).
Returns: bool True if the gap ratio (open vs. previous close) is greater than or equal to the minimum ratio.
isSignificantGapDown(minRatio)
Checks if the current bar opened significantly lower than the previous close, as defined by a minimum percentage ratio.
Parameters:
minRatio (float) : The minimum required gap percentage ratio. Default is 0.03 (3%).
Returns: bool True if the absolute value of the gap ratio (open vs. previous close) is greater than or equal to the minimum ratio.
trueRangeComponentHigh()
Calculates the absolute distance from the current bar's High to the previous bar's Close, representing one of the components of the True Range.
Returns: float The absolute difference: |High - Close |.
trueRangeComponentLow()
Calculates the absolute distance from the current bar's Low to the previous bar's Close, representing one of the components of the True Range.
Returns: float The absolute difference: |Low - Close |.
isUpperWickDominant(minRatio)
Checks if the upper wick is significantly long relative to the total range.
Parameters:
minRatio (float) : Minimum ratio of the wick to the total bar range. Default is 0.7 (70%).
Returns: bool True if the upper wick dominates the bar's range.
isUpperWickNegligible(maxRatio)
Checks if the upper wick is very small relative to the total range.
Parameters:
maxRatio (float) : Maximum ratio of the wick to the total bar range. Default is 0.05 (5%).
Returns: bool True if the upper wick is negligible.
isLowerWickDominant(minRatio)
Checks if the lower wick is significantly long relative to the total range.
Parameters:
minRatio (float) : Minimum ratio of the wick to the total bar range. Default is 0.7 (70%).
Returns: bool True if the lower wick dominates the bar's range.
isLowerWickNegligible(maxRatio)
Checks if the lower wick is very small relative to the total range.
Parameters:
maxRatio (float) : Maximum ratio of the wick to the total bar range. Default is 0.05 (5%).
Returns: bool True if the lower wick is negligible.
isSymmetric(maxTolerance)
Checks if the upper and lower wicks are roughly equal in length.
Parameters:
maxTolerance (float) : Maximum allowable percentage difference between the two wicks. Default is 0.15 (15%).
Returns: bool True if wicks are symmetric within the tolerance level.
isMarubozuBody(minRatio)
Candle with a very large body relative to the total range (minimal wicks).
Parameters:
minRatio (float) : Minimum body size ratio. Default is 0.9 (90%).
Returns: bool True if the bar has minimal wicks (Marubozu body).
isLargeBody(minRatio)
Candle with a large body relative to the total range.
Parameters:
minRatio (float) : Minimum body size ratio. Default is 0.6 (60%).
Returns: bool True if the bar has a large body.
isSmallBody(maxRatio)
Candle with a small body relative to the total range.
Parameters:
maxRatio (float) : Maximum body size ratio. Default is 0.4 (40%).
Returns: bool True if the bar has small body.
isDojiBody(maxRatio)
Candle with a very small body relative to the total range (indecision).
Parameters:
maxRatio (float) : Maximum body size ratio. Default is 0.1 (10%).
Returns: bool True if the bar has a very small body.
isLowerWickExtended(minRatio)
Checks if the lower wick is significantly extended relative to the real body size.
Parameters:
minRatio (float) : Minimum required ratio of the lower wick length to the real body size. Default is 2.0 (Lower wick must be at least twice the body's size).
Returns: bool True if the lower wick's length is at least `minRatio` times the size of the real body.
isUpperWickExtended(minRatio)
Checks if the upper wick is significantly extended relative to the real body size.
Parameters:
minRatio (float) : Minimum required ratio of the upper wick length to the real body size. Default is 2.0 (Upper wick must be at least twice the body's size).
Returns: bool True if the upper wick's length is at least `minRatio` times the size of the real body.
isStrongBuyingBar(minCloseRatio, maxOpenRatio)
Checks for a bar with strong bullish momentum (open near low, close near high), indicating high conviction.
Parameters:
minCloseRatio (float) : Minimum required ratio for the close location (relative to range, e.g., 0.7 means close must be in the top 30%). Default is 0.7 (70%).
maxOpenRatio (float) : Maximum allowed ratio for the open location (relative to range, e.g., 0.3 means open must be in the bottom 30%). Default is 0.3 (30%).
Returns: bool True if the bar is bullish, opened in the low extreme, and closed in the high extreme.
isStrongSellingBar(maxCloseRatio, minOpenRatio)
Checks for a bar with strong bearish momentum (open near high, close near low), indicating high conviction.
Parameters:
maxCloseRatio (float) : Maximum allowed ratio for the close location (relative to range, e.g., 0.3 means close must be in the bottom 30%). Default is 0.3 (30%).
minOpenRatio (float) : Minimum required ratio for the open location (relative to range, e.g., 0.7 means open must be in the top 30%). Default is 0.7 (70%).
Returns: bool True if the bar is bearish, opened in the high extreme, and closed in the low extreme.
isWeakBuyingBar(maxCloseRatio, maxBodyRatio)
Identifies a bar that is technically bullish but shows significant weakness, characterized by a failure to close near the high and a small body size.
Parameters:
maxCloseRatio (float) : Maximum allowed ratio for the close location relative to the range (e.g., 0.6 means the close must be in the bottom 60% of the bar's range). Default is 0.6 (60%).
maxBodyRatio (float) : Maximum allowed ratio for the real body size relative to the bar's range (e.g., 0.4 means the body is small). Default is 0.4 (40%).
Returns: bool True if the bar is bullish, but its close is weak and its body is small.
isWeakSellingBar(minCloseRatio, maxBodyRatio)
Identifies a bar that is technically bearish but shows significant weakness, characterized by a failure to close near the low and a small body size.
Parameters:
minCloseRatio (float) : Minimum required ratio for the close location relative to the range (e.g., 0.4 means the close must be in the top 60% of the bar's range). Default is 0.4 (40%).
maxBodyRatio (float) : Maximum allowed ratio for the real body size relative to the bar's range (e.g., 0.4 means the body is small). Default is 0.4 (40%).
Returns: bool True if the bar is bearish, but its close is weak and its body is small.
balanceOfPower()
Measures the net pressure of buyers vs. sellers within the bar, normalized to the bar's range.
Returns: float A value between -1.0 (strong selling) and +1.0 (strong buying), representing the strength and direction of the close relative to the open.
buyingPressure()
Measures the net buying volume pressure based on the close location and volume.
Returns: float A numerical value representing the volume weighted buying pressure.
sellingPressure()
Measures the net selling volume pressure based on the close location and volume.
Returns: float A numerical value representing the volume weighted selling pressure.
moneyFlowMultiplier()
Calculates the Money Flow Multiplier (MFM), which is the price component of Money Flow and CMF.
Returns: float A normalized value from -1.0 (strong selling) to +1.0 (strong buying), representing the net directional pressure.
moneyFlowVolume()
Calculates the Money Flow Volume (MFV), which is the Money Flow Multiplier weighted by the bar's volume.
Returns: float A numerical value representing the volume-weighted money flow. Positive = buying dominance; negative = selling dominance.
isAccumulationBar()
Checks for basic accumulation on the current bar, requiring both positive Money Flow Volume and a buying bar (closing higher than opening).
Returns: bool True if the bar exhibits buying dominance through its internal range location and is a buying bar.
isDistributionBar()
Checks for basic distribution on the current bar, requiring both negative Money Flow Volume and a selling bar (closing lower than opening).
Returns: bool True if the bar exhibits selling dominance through its internal range location and is a selling bar.
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)
T5_EngineLibrary "T5_Engine"
run(ema50, ema200, atrPct, emaGapPct, btcEma50, btcEma200, isBarClose, crossUp21_50, crossDown21_50, useBTCFilter, useSpreadFilter, minSpreadPctFixed, useAdaptiveSpread, spreadBaseMinPct, spreadAtrK, atrLowTh, atrHighTh)
Parameters:
ema50 (float)
ema200 (float)
atrPct (float)
emaGapPct (float)
btcEma50 (float)
btcEma200 (float)
isBarClose (bool)
crossUp21_50 (bool)
crossDown21_50 (bool)
useBTCFilter (bool)
useSpreadFilter (bool)
minSpreadPctFixed (float)
useAdaptiveSpread (bool)
spreadBaseMinPct (float)
spreadAtrK (float)
atrLowTh (float)
atrHighTh (float)
demark_poolLibrary "demark_pool"
f_labelArrayClear(pool, run)
Parameters:
pool (array)
run (bool)
f_labelPushCap(pool, l, cap)
Parameters:
pool (array)
l (label)
cap (int)
f_labelTrimCap(pool, run, cap)
Parameters:
pool (array)
run (bool)
cap (int)
demark_uiLibrary "demark_ui"
f_dashUpdate6x2(dash, c00, c10, c01, c11, c02, c12, c12TextColor, c03, c13, c04, c14, c05, c15, bg, tc, ts)
Parameters:
dash (table)
c00 (string)
c10 (string)
c01 (string)
c11 (string)
c02 (string)
c12 (string)
c12TextColor (color)
c03 (string)
c13 (string)
c04 (string)
c14 (string)
c05 (string)
c15 (string)
bg (color)
tc (color)
ts (string)
demark_utilsLibrary "demark_utils"
f_grade(score)
Parameters:
score (float)
f_clampScore(score)
Parameters:
score (float)
f_px(v)
Parameters:
v (float)
f_pxOrDash(v)
Parameters:
v (float)
f_sum(src, length)
Parameters:
src (float)
length (int)
f_hasAnyBits(bus, mask)
Parameters:
bus (int)
mask (int)
f_busSetMask(bus, mask)
Parameters:
bus (int)
mask (int)
f_evSet(bus, flag)
Parameters:
bus (int)
flag (int)
f_evSet2(bus, flag)
Parameters:
bus (int)
flag (int)
demark_renderLibrary "demark_render"
f_renderMaxBack(lookbackBars)
Parameters:
lookbackBars (float)
f_renderExtendBars(levelLineExtendBarsMax)
Parameters:
levelLineExtendBarsMax (int)
f_upsertLevelLine(lnIn, show, y, col, width, style, levelLineExtendBarsMax)
Parameters:
lnIn (line)
show (bool)
y (float)
col (color)
width (int)
style (string)
levelLineExtendBarsMax (int)
f_upsertZoneBox(bxIn, show, x1, lo, hi, bg, brd, brdW, lookbackBars, levelLineExtendBarsMax)
Parameters:
bxIn (box)
show (bool)
x1 (int)
lo (float)
hi (float)
bg (color)
brd (color)
brdW (int)
lookbackBars (float)
levelLineExtendBarsMax (int)
f_upsertTdLine(lnIn, show, p1Idx, p1Price, p0Idx, p0Price, col, width, style, lookbackBars, levelLineExtendBarsMax)
Parameters:
lnIn (line)
show (bool)
p1Idx (int)
p1Price (float)
p0Idx (int)
p0Price (float)
col (color)
width (int)
style (string)
lookbackBars (float)
levelLineExtendBarsMax (int)
f_levelTagX(levelLineExtendBarsMax)
Parameters:
levelLineExtendBarsMax (int)
f_stackY(baseY, step, idx, stackUp)
Parameters:
baseY (float)
step (float)
idx (int)
stackUp (bool)
f_upsertLevelTag(lbIn, show, y, txt, bg, tc, sz, levelLineExtendBarsMax)
Parameters:
lbIn (label)
show (bool)
y (float)
txt (string)
bg (color)
tc (color)
sz (string)
levelLineExtendBarsMax (int)
f_upsertPointTag(lbIn, show, x, y, txt, bg, tc, sz, sty)
Parameters:
lbIn (label)
show (bool)
x (int)
y (float)
txt (string)
bg (color)
tc (color)
sz (string)
sty (string)
HelperScriptA Personal Helper Script based on FFriZz/Holiday/2
Only change the font size and language
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`.






















