DrawZigZag🟩 OVERVIEW
This library draws zigzag lines for existing pivots. It is designed to be simple to use. If your script creates pivots and you want to join them up while handling edge cases, this library does that quickly and efficiently. If you want your pivots created for you, choose one of the many other zigzag libraries that do that.
🟩 HOW TO USE
Pine Script libraries contain reusable code for importing into indicators. You do not need to copy any code out of here. Just import the library and call the function you want.
For example, for version 1 of this library, import it like this:
import SimpleCryptoLife/DrawZigZag/1
See the EXAMPLE USAGE sections within the library for examples of calling the functions.
For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script User Manual.
🟩 WHAT IT DOES
I looked at every zigzag library on TradingView, after finishing this one. They all seemed to fall into two groups in terms of functionality:
• Create the pivots themselves, using a combination of Williams-style pivots and sometimes price distance.
• Require an array of pivot information, often in a format that uses user-defined types.
My library takes a completely different approach.
Firstly, it only does the drawing. It doesn't calculate the pivots for you. This isn't laziness. There are so many ways to define pivots and that should be up to you. If you've followed my work on market structure you know what I think of Williams pivots.
Secondly, when you pass information about your pivots to the library function, you only need the minimum of pivot information -- whether it's a High or Low pivot, the price, and the bar index. Pass these as normal variables -- bools, ints, and floats -- on the fly as your pivots confirm. It is completely agnostic as to how you derive your pivots. If they are confirmed an arbitrary number of bars after they happen, that's fine.
So why even bother using it if all it does it draw some lines?
Turns out there is quite some logic needed in order to connect highs and lows in the right way, and to handle edge cases. This is the kind of thing one can happily outsource.
🟩 THE RULES
• Zigs and zags must alternate between Highs and Lows. We never connect a High to a High or a Low to a Low.
• If a candle has both a High and Low pivot confirmed on it, the first line is drawn to the end of the candle that is the opposite to the previous pivot. Then the next line goes vertically through the candle to the other end, and then after that continues normally.
• If we draw a line up from a Low to a High pivot, and another High pivot comes in higher, we *extend* the line up, and the same for lines down. Yes this is a form of repainting. It is in my opinion the only way to end up with a correct structure.
• We ignore lower highs on the way up and higher lows on the way down.
🟩 WHAT'S COOL ABOUT THIS LIBRARY
• It's simple and lightweight: no exported user-defined types, no helper methods, no matrices.
• It's really fast. In my profiling it runs at about ~50ms, and changing the options (e.g., trimming the array) doesn't make very much difference.
• You only need to call one function, which does all the calculations and draws all lines.
• There are two variations of this function though -- one simple function that just draws lines, and one slightly more advanced method that modifies an array containing the lines. If you don't know which one you want, use the simpler one.
🟩 GEEK STUFF
• There are no dependencies on other libraries.
• I tried to make the logic as clear as I could and comment it appropriately.
• In the `f_drawZigZags` function, the line variable is declared using the `var` keyword *inside* the function, for simplicity. For this reason, it persists between function calls *only* if the function is called from the global scope or a local if block. In general, if a function is called from inside a loop , or multiple times from different contexts, persistent variables inside that function are re-initialised on each call. In this case, this re-initialisation would mean that the function loses track of the previous line, resulting in incorrect drawings. This is why you cannot call the `f_drawZigZags` function from a loop (not that there's any reason to). The `m_drawZigZagsArray` does not use any internal `var` variables.
• The function itself takes a Boolean parameter `_showZigZag`, which turns the drawings on and off, so there is no need to call the function conditionally. In the examples, we do call the functions from an if block, purely as an illustration of how to increase performance by restricting the amount of code that needs to be run.
🟩 BRING ON THE FUNCTIONS
f_drawZigZags(_showZigZag, _isHighPivot, _isLowPivot, _highPivotPrice, _lowPivotPrice, _pivotIndex, _zigzagWidth, _lineStyle, _upZigColour, _downZagColour)
This function creates or extends the latest zigzag line. Takes real-time information about pivots and draws lines. It does not calculate the pivots. It must be called once per script and cannot be called from a loop.
Parameters:
_showZigZag (bool) : Whether to show the zigzag lines.
_isHighPivot (bool) : Whether the current bar confirms a high pivot. Note that pivots are confirmed after the bar in which they occur.
_isLowPivot (bool) : Whether the current bar confirms a low pivot.
_highPivotPrice (float) : The price of the high pivot that was confirmed this bar. It is NOT the high price of the current bar.
_lowPivotPrice (float) : The price of the low pivot that was confirmed this bar. It is NOT the low price of the current bar.
_pivotIndex (int) : The bar index of the pivot that was confirmed this bar. This is not an offset. It's the `bar_index` value of the pivot.
_zigzagWidth (int) : The width of the zigzag lines.
_lineStyle (string) : The style of the zigzag lines.
_upZigColour (color) : The colour of the up zigzag lines.
_downZagColour (color) : The colour of the down zigzag lines.
Returns: The function has no explicit returns. As a side effect, it draws or updates zigzag lines.
method m_drawZigZagsArray(_a_zigZagLines, _showZigZag, _isHighPivot, _isLowPivot, _highPivotPrice, _lowPivotPrice, _pivotIndex, _zigzagWidth, _lineStyle, _upZigColour, _downZagColour, _trimArray)
Namespace types: array
Parameters:
_a_zigZagLines (array)
_showZigZag (bool) : Whether to show the zigzag lines.
_isHighPivot (bool) : Whether the current bar confirms a high pivot. Note that pivots are usually confirmed after the bar in which they occur.
_isLowPivot (bool) : Whether the current bar confirms a low pivot.
_highPivotPrice (float) : The price of the high pivot that was confirmed this bar. It is NOT the high price of the current bar.
_lowPivotPrice (float) : The price of the low pivot that was confirmed this bar. It is NOT the low price of the current bar.
_pivotIndex (int) : The bar index of the pivot that was confirmed this bar. This is not an offset. It's the `bar_index` value of the pivot.
_zigzagWidth (int) : The width of the zigzag lines.
_lineStyle (string) : The style of the zigzag lines.
_upZigColour (color) : The colour of the up zigzag lines.
_downZagColour (color) : The colour of the down zigzag lines.
_trimArray (bool) : If true, the array of lines is kept to a maximum size of two lines (the line elements are not deleted). If false (the default), the array is kept to a maximum of 500 lines (the maximum number of line objects a single Pine script can display).
Returns: This function has no explicit returns but it modifies a global array of zigzag lines.
Indicatori e strategie
CCO_LibraryLibrary "CCO_Library"
Contrarian Crowd Oscillator (CCO) Library - Multi-oscillator consensus indicator for contrarian trading signals
@author B3AR_Trades
calculate_oscillators(rsi_length, stoch_length, cci_length, williams_length, roc_length, mfi_length, percentile_lookback, use_rsi, use_stochastic, use_williams, use_cci, use_roc, use_mfi)
Calculate normalized oscillator values
Parameters:
rsi_length (simple int) : (int) RSI calculation period
stoch_length (int) : (int) Stochastic calculation period
cci_length (int) : (int) CCI calculation period
williams_length (int) : (int) Williams %R calculation period
roc_length (int) : (int) ROC calculation period
mfi_length (int) : (int) MFI calculation period
percentile_lookback (int) : (int) Lookback period for CCI/ROC percentile ranking
use_rsi (bool) : (bool) Include RSI in calculations
use_stochastic (bool) : (bool) Include Stochastic in calculations
use_williams (bool) : (bool) Include Williams %R in calculations
use_cci (bool) : (bool) Include CCI in calculations
use_roc (bool) : (bool) Include ROC in calculations
use_mfi (bool) : (bool) Include MFI in calculations
Returns: (OscillatorValues) Normalized oscillator values
calculate_consensus_score(oscillators, use_rsi, use_stochastic, use_williams, use_cci, use_roc, use_mfi, weight_by_reliability, consensus_smoothing)
Calculate weighted consensus score
Parameters:
oscillators (OscillatorValues) : (OscillatorValues) Individual oscillator values
use_rsi (bool) : (bool) Include RSI in consensus
use_stochastic (bool) : (bool) Include Stochastic in consensus
use_williams (bool) : (bool) Include Williams %R in consensus
use_cci (bool) : (bool) Include CCI in consensus
use_roc (bool) : (bool) Include ROC in consensus
use_mfi (bool) : (bool) Include MFI in consensus
weight_by_reliability (bool) : (bool) Apply reliability-based weights
consensus_smoothing (int) : (int) Smoothing period for consensus
Returns: (float) Weighted consensus score (0-100)
calculate_consensus_strength(oscillators, consensus_score, use_rsi, use_stochastic, use_williams, use_cci, use_roc, use_mfi)
Calculate consensus strength (agreement between oscillators)
Parameters:
oscillators (OscillatorValues) : (OscillatorValues) Individual oscillator values
consensus_score (float) : (float) Current consensus score
use_rsi (bool) : (bool) Include RSI in strength calculation
use_stochastic (bool) : (bool) Include Stochastic in strength calculation
use_williams (bool) : (bool) Include Williams %R in strength calculation
use_cci (bool) : (bool) Include CCI in strength calculation
use_roc (bool) : (bool) Include ROC in strength calculation
use_mfi (bool) : (bool) Include MFI in strength calculation
Returns: (float) Consensus strength (0-100)
classify_regime(consensus_score)
Classify consensus regime
Parameters:
consensus_score (float) : (float) Current consensus score
Returns: (ConsensusRegime) Regime classification
detect_signals(consensus_score, consensus_strength, consensus_momentum, regime)
Detect trading signals
Parameters:
consensus_score (float) : (float) Current consensus score
consensus_strength (float) : (float) Current consensus strength
consensus_momentum (float) : (float) Consensus momentum
regime (ConsensusRegime) : (ConsensusRegime) Current regime classification
Returns: (TradingSignals) Trading signal conditions
calculate_cco(rsi_length, stoch_length, cci_length, williams_length, roc_length, mfi_length, consensus_smoothing, percentile_lookback, use_rsi, use_stochastic, use_williams, use_cci, use_roc, use_mfi, weight_by_reliability, detect_momentum)
Calculate complete CCO analysis
Parameters:
rsi_length (simple int) : (int) RSI calculation period
stoch_length (int) : (int) Stochastic calculation period
cci_length (int) : (int) CCI calculation period
williams_length (int) : (int) Williams %R calculation period
roc_length (int) : (int) ROC calculation period
mfi_length (int) : (int) MFI calculation period
consensus_smoothing (int) : (int) Consensus smoothing period
percentile_lookback (int) : (int) Percentile ranking lookback
use_rsi (bool) : (bool) Include RSI
use_stochastic (bool) : (bool) Include Stochastic
use_williams (bool) : (bool) Include Williams %R
use_cci (bool) : (bool) Include CCI
use_roc (bool) : (bool) Include ROC
use_mfi (bool) : (bool) Include MFI
weight_by_reliability (bool) : (bool) Apply reliability weights
detect_momentum (bool) : (bool) Calculate momentum and acceleration
Returns: (CCOResult) Complete CCO analysis results
calculate_cco_default()
Calculate CCO with default parameters
Returns: (CCOResult) CCO result with standard settings
cco_consensus_score()
Get just the consensus score with default parameters
Returns: (float) Consensus score (0-100)
cco_consensus_strength()
Get just the consensus strength with default parameters
Returns: (float) Consensus strength (0-100)
is_panic_bottom()
Check if in panic bottom condition
Returns: (bool) True if panic bottom signal active
is_euphoric_top()
Check if in euphoric top condition
Returns: (bool) True if euphoric top signal active
bullish_consensus_reversal()
Check for bullish consensus reversal
Returns: (bool) True if bullish reversal detected
bearish_consensus_reversal()
Check for bearish consensus reversal
Returns: (bool) True if bearish reversal detected
bearish_divergence()
Check for bearish divergence
Returns: (bool) True if bearish divergence detected
bullish_divergence()
Check for bullish divergence
Returns: (bool) True if bullish divergence detected
get_regime_name()
Get current regime name
Returns: (string) Current consensus regime name
get_contrarian_signal()
Get contrarian signal
Returns: (string) Current contrarian trading signal
get_position_multiplier()
Get position size multiplier
Returns: (float) Recommended position sizing multiplier
OscillatorValues
Individual oscillator values
Fields:
rsi (series float) : RSI value (0-100)
stochastic (series float) : Stochastic value (0-100)
williams (series float) : Williams %R value (0-100, normalized)
cci (series float) : CCI percentile value (0-100)
roc (series float) : ROC percentile value (0-100)
mfi (series float) : Money Flow Index value (0-100)
ConsensusRegime
Consensus regime classification
Fields:
extreme_bearish (series bool) : Extreme bearish consensus (<= 20)
moderate_bearish (series bool) : Moderate bearish consensus (20-40)
mixed (series bool) : Mixed consensus (40-60)
moderate_bullish (series bool) : Moderate bullish consensus (60-80)
extreme_bullish (series bool) : Extreme bullish consensus (>= 80)
regime_name (series string) : Text description of current regime
contrarian_signal (series string) : Contrarian trading signal
TradingSignals
Trading signals
Fields:
panic_bottom_signal (series bool) : Extreme bearish consensus with high strength
euphoric_top_signal (series bool) : Extreme bullish consensus with high strength
consensus_reversal_bullish (series bool) : Bullish consensus reversal
consensus_reversal_bearish (series bool) : Bearish consensus reversal
bearish_divergence (series bool) : Bearish price-consensus divergence
bullish_divergence (series bool) : Bullish price-consensus divergence
strong_consensus (series bool) : High consensus strength signal
CCOResult
Complete CCO calculation results
Fields:
consensus_score (series float) : Main consensus score (0-100)
consensus_strength (series float) : Consensus strength (0-100)
consensus_momentum (series float) : Rate of consensus change
consensus_acceleration (series float) : Rate of momentum change
oscillators (OscillatorValues) : Individual oscillator values
regime (ConsensusRegime) : Regime classification
signals (TradingSignals) : Trading signals
position_multiplier (series float) : Recommended position sizing multiplier
BigCandleLibrary "BigCandle"
init()
method bigGreenCandleTail(state, i)
Namespace types: BigCandleState
Parameters:
state (BigCandleState)
i (int)
method bigRedCandleTail(state, i)
Namespace types: BigCandleState
Parameters:
state (BigCandleState)
i (int)
method removeCrossedGreenCandleIndexes(state)
Namespace types: BigCandleState
Parameters:
state (BigCandleState)
method removeCrossedRedCandleIndexes(state)
Namespace types: BigCandleState
Parameters:
state (BigCandleState)
method run(state, opts)
Namespace types: BigCandleState
Parameters:
state (BigCandleState)
opts (BigCandleOpts)
method lastGreenCandleIndex(state)
Namespace types: BigCandleState
Parameters:
state (BigCandleState)
method lastRedCandleIndex(state)
Namespace types: BigCandleState
Parameters:
state (BigCandleState)
method lastGreenCandleTail(state)
Namespace types: BigCandleState
Parameters:
state (BigCandleState)
method lastRedCandleTail(state)
Namespace types: BigCandleState
Parameters:
state (BigCandleState)
method lastGreenCandleStrength(state)
Namespace types: BigCandleState
Parameters:
state (BigCandleState)
method lastRedCandleStrength(state)
Namespace types: BigCandleState
Parameters:
state (BigCandleState)
method reset(state, direction)
Namespace types: BigCandleState
Parameters:
state (BigCandleState)
direction (int)
BigCandleState
Fields:
greenCandleIndexes (array)
redCandleIndexes (array)
greenCandleStrength (array)
redCandleStrength (array)
averageHeight (series float)
averageBodyHeight (series float)
heightPercentage (series float)
bodyHeightPercentage (series float)
BigCandleOpts
Fields:
averageHeightPeriod (series int)
minCandleHeight (series float)
minCandleBodyHeight (series float)
minCandleHeight2 (series float)
minCandleBodyHeight2 (series float)
AMF_LibraryLibrary "AMF_Library"
Adaptive Momentum Flow (AMF) Library - A comprehensive momentum oscillator that adapts to market volatility
@author B3AR_Trades
f_ema(source, length)
Custom EMA calculation that accepts a series length
Parameters:
source (float) : (float) Source data for calculation
length (float) : (float) EMA length (can be series)
Returns: (float) EMA value
f_dema(source, length)
Custom DEMA calculation that accepts a series length
Parameters:
source (float) : (float) Source data for calculation
length (float) : (float) DEMA length (can be series)
Returns: (float) DEMA value
f_sum(source, length)
Custom sum function for rolling sum calculation
Parameters:
source (float) : (float) Source data for summation
length (int) : (int) Number of periods to sum
Returns: (float) Sum value
get_average(data, length, ma_type)
Get various moving average types for fixed lengths
Parameters:
data (float) : (float) Source data
length (simple int) : (int) MA length
ma_type (string) : (string) MA type: "SMA", "EMA", "WMA", "DEMA"
Returns: (float) Moving average value
calculate_adaptive_lookback(base_length, min_lookback, max_lookback, volatility_sensitivity)
Calculate adaptive lookback length based on volatility
Parameters:
base_length (int) : (int) Base lookback length
min_lookback (int) : (int) Minimum allowed lookback
max_lookback (int) : (int) Maximum allowed lookback
volatility_sensitivity (float) : (float) Sensitivity to volatility changes
Returns: (int) Adaptive lookback length
get_volatility_ratio()
Get current volatility ratio
Returns: (float) Current volatility ratio vs 50-period average
calculate_volume_analysis(vzo_length, smooth_length, smooth_type)
Calculate volume-based buying/selling pressure
Parameters:
vzo_length (int) : (int) Lookback length for volume analysis
smooth_length (simple int) : (int) Smoothing length
smooth_type (string) : (string) Smoothing MA type
Returns: (float) Volume analysis value (-100 to 100)
calculate_amf(base_length, smooth_length, smooth_type, signal_length, signal_type, min_lookback, max_lookback, volatility_sensitivity, medium_multiplier, slow_multiplier, vzo_length, vzo_smooth_length, vzo_smooth_type, price_vs_fast_weight, fast_vs_medium_weight, medium_vs_slow_weight, vzo_weight)
Calculate complete AMF oscillator
Parameters:
base_length (int) : (int) Base lookback length
smooth_length (simple int) : (int) Final smoothing length
smooth_type (string) : (string) Final smoothing MA type
signal_length (simple int) : (int) Signal line length
signal_type (string) : (string) Signal line MA type
min_lookback (int) : (int) Minimum adaptive lookback
max_lookback (int) : (int) Maximum adaptive lookback
volatility_sensitivity (float) : (float) Volatility adaptation sensitivity
medium_multiplier (float) : (float) Medium DEMA length multiplier
slow_multiplier (float) : (float) Slow DEMA length multiplier
vzo_length (int) : (int) Volume analysis lookback
vzo_smooth_length (simple int) : (int) Volume analysis smoothing
vzo_smooth_type (string) : (string) Volume analysis smoothing type
price_vs_fast_weight (float) : (float) Weight for price vs fast DEMA
fast_vs_medium_weight (float) : (float) Weight for fast vs medium DEMA
medium_vs_slow_weight (float) : (float) Weight for medium vs slow DEMA
vzo_weight (float) : (float) Weight for volume analysis component
Returns: (AMFResult) Complete AMF calculation results
calculate_amf_default()
Calculate AMF with default parameters
Returns: (AMFResult) AMF result with standard settings
amf_oscillator()
Get just the main AMF oscillator value with default parameters
Returns: (float) Main AMF oscillator value
amf_signal()
Get just the AMF signal line with default parameters
Returns: (float) AMF signal line value
is_overbought(overbought_level)
Check if AMF is in overbought condition
Parameters:
overbought_level (float) : (float) Overbought threshold (default 70)
Returns: (bool) True if overbought
is_oversold(oversold_level)
Check if AMF is in oversold condition
Parameters:
oversold_level (float) : (float) Oversold threshold (default -70)
Returns: (bool) True if oversold
bullish_crossover()
Detect bullish crossover (main line crosses above signal)
Returns: (bool) True on bullish crossover
bearish_crossover()
Detect bearish crossover (main line crosses below signal)
Returns: (bool) True on bearish crossover
AMFResult
AMF calculation results
Fields:
main_oscillator (series float) : The main AMF oscillator value (-100 to 100)
signal_line (series float) : The signal line for crossover signals
dema_fast (series float) : Fast adaptive DEMA value
dema_medium (series float) : Medium adaptive DEMA value
dema_slow (series float) : Slow adaptive DEMA value
volume_analysis (series float) : Volume-based buying/selling pressure (-100 to 100)
adaptive_lookback (series int) : Current adaptive lookback length
volatility_ratio (series float) : Current volatility ratio vs average
BreakoutLibrary "Breakout"
init()
method run(state, opts)
Namespace types: BreakoutState
Parameters:
state (BreakoutState)
opts (BreakoutOpts)
BreakoutState
Fields:
levelUps (array)
levelDowns (array)
levelUpTargets (array)
levelDownTargets (array)
levelUpConfirmed (array)
levelDownConfirmed (array)
levelUpNumLevels (array)
levelDownNumLevels (array)
breakoutSignalUp (series bool)
breakoutSignalDown (series bool)
BreakoutOpts
Fields:
canConfirmUp (series bool)
canConfirmDown (series bool)
numLevelMinToConfirm (series int)
numLevelMaxToConfirm (series int)
zigZagPeriod (series int)
rsi (series float)
rsiMA (series float)
SDCALibraryMy Valuation Library for mostly crypto currency use, but some can be applied to other assets.
There are technical and on-chain indicator functions for use.
Technical Indicators:
1. **drawdown_zscore**
- **Summary**: Calculates the z-score of drawdowns over a specified lookback period.
- **Inputs**:
- `lookback_length` (int): Period for drawdown calculation.
- `zScoreLen` (int): Length for z-score calculation.
2. **sharpe_zscore**
- **Summary**: Computes the z-score of the Sharpe ratio using returns over a period and a smoothing length.
- **Inputs**:
- `length` (int): Period for returns calculation.
- `smalen` (int): Smoothing length for returns.
- `zScoreLen` (int): Length for z-score calculation.
3. **rsi_zscore**
- **Summary**: Calculates the z-score of the Relative Strength Index (RSI) with smoothing.
- **Inputs**:
- `length` (int): Period for RSI calculation.
- `smalen` (int): Smoothing length for RSI.
- `zScoreLen` (int): Length for z-score calculation.
4. **DFATH_zscore**
- **Summary**: Computes the z-score for a specific DFATH metric (details not specified).
- **Inputs**:
- `zScoreLen` (int): Length for z-score calculation.
5. **RTI_zscore**
- **Summary**: Calculates the z-score of a trend indicator based on data count and sensitivity.
- **Inputs**:
- `trend_data_count` (int): Number of data points for trend analysis.
- `trend_sensitivity_percentage` (int): Sensitivity threshold for trend detection.
- `zScoreLen` (int): Length for z-score calculation.
On-Chain (Crypto only, mostly BTC, ETH)
6. **SOPR_zscore**
- **Summary**: Computes the z-score of Spent Output Profit Ratio (SOPR) for a specific coin.
- **Inputs**:
- `zScoreLen` (int): Length for z-score calculation.
- `coin_sopr` (string): SOPR data for the specified coin.
7. **thermocap_zscore**
- **Summary**: Calculates the z-score of the Thermocap metric using moving average and coin-specific data.
- **Inputs**:
- `ma_len` (int): Length of the moving average.
- `ma_type` (string): Type of moving average.
- `zScoreLen` (int): Length for z-score calculation.
- `coin_index` (string): Coin index data.
- `coin_blocks_mined` (string): Data on blocks mined for the coin.
8. **MVRV_zscore**
- **Summary**: Computes the z-score of the Market Value to Realized Value (MVRV) ratio.
- **Inputs**:
- `zScoreLen` (int): Length for z-score calculation.
- `coin_MC` (string): Market capitalization data.
- `coin_MC_real` (string): Realized market capitalization data.
9. **supplyinprofit_zscore**
- **Summary**: Calculates the z-score of the percentage of coin supply in profit or loss, optionally adjusted for alpha decay.
- **Inputs**:
- `isAlphaDecayAdjusted` (bool): Whether to apply alpha decay adjustment.
- `zScoreLen` (int): Length for z-score calculation.
- `coin_profit_address_percent` (string): Percentage of addresses in profit.
- `coin_loss_address_percent` (string): Percentage of addresses in loss.
10. **realized_price_zscore**
- **Summary**: Computes the z-score of the realized price based on realized market cap and supply.
- **Inputs**:
- `zScoreLen` (int): Length for z-score calculation.
- `coin_MC_real` (string): Realized market capitalization data.
- `coin_supply` (string): Coin supply data.
11. **CVVD_zscore**
- **Summary**: Calculates the z-score of Cumulative Value Days Destroyed (CVVD) metric.
- **Inputs**:
- `zScoreLen` (int): Length for z-score calculation.
- `coin_MC_real` (string): Realized market capitalization data.
- `coin_total_volume` (string): Total volume data for the coin.
12. **NUPL_zscore**
- **Summary**: Computes the z-score of Net Unrealized Profit and Loss (NUPL) metric.
- **Inputs**:
- `zScoreLen` (int): Length for z-score calculation.
- `coin_MC` (string): Market capitalization data.
- `coin_MC_real` (string): Realized market capitalization data.
RejectionLibrary "Rejection"
method mergeCandle(h1, l1, c1, h2, l2, o2)
Namespace types: series float, simple float, input float, const float
Parameters:
h1 (float)
l1 (float)
c1 (float)
h2 (float)
l2 (float)
o2 (float)
method isRejectionCandle(candleHigh, candleLow, candleOpen, candleClose)
Namespace types: series float, simple float, input float, const float
Parameters:
candleHigh (float)
candleLow (float)
candleOpen (float)
candleClose (float)
method mergeCandlesForRejection(_numCandles, direction)
Namespace types: series int, simple int, input int, const int
Parameters:
_numCandles (int)
direction (int)
method hasRejection(direction)
Namespace types: series int, simple int, input int, const int
Parameters:
direction (int)
PineTraderOT_V6Library "PineTraderOT_V6"
TODO: Simplify the order ticket generation for Pinetrader.io
GenerateOT(license_id, symbol, action, order_type, trade_type, size, price, tp, sl, risk, trailPrice, trailOffset)
CreateOrderTicket: Establishes a order ticket following appropriate guidelines.
Parameters:
license_id (string) : Provide your license index
symbol (string) : Symbol on which to execute the trade
action (string) : Execution method of the trade : "MRKT" or "PENDING"
order_type (string) : Direction type of the order: "BUY" or "SELL"
trade_type (string) : Is it a "SPREAD" trade or a "SINGLE" symbol execution?
size (float) : Size of the trade, in units
price (float) : If the order is pending you must specify the execution price
tp (float) : (Optional) Take profit of the order
sl (float) : (Optional) Stop loss of the order
risk (float) : Percent to risk for the trade, if size not specified
trailPrice (float) : (Optional) Price at which trailing stop is starting
trailOffset (float) : (Optional) Amount to trail by
Returns: Return Order string
LyroMAsLibrary "LyroMAs"
Custom Dynamic MA's that allow a dynamic calculation beginning from the first bar\ use getDynamicLength(maxLength) =>\\tmath.min(maxLength, bar_index + 1) \as length
SMA(sourceData, maxLength)
Dynamic SMA
Parameters:
sourceData (float)
maxLength (int)
EMA(src, length)
Dynamic EMA
Parameters:
src (float)
length (int)
DEMA(src, length)
Dynamic DEMA
Parameters:
src (float)
length (int)
TEMA(src, length)
Dynamic TEMA
Parameters:
src (float)
length (int)
WMA(src, length)
Dynamic WMA
Parameters:
src (float)
length (int)
HMA(src, length)
Dynamic HMA
Parameters:
src (float)
length (int)
VWMA(src, volsrc, length)
Dynamic VWMA
Parameters:
src (float)
volsrc (float)
length (int)
SMMA(src, length)
Dynamic SMMA
Parameters:
src (float)
length (int)
LSMA(src, length, offset)
Dynamic LSMA
Parameters:
src (float)
length (int)
offset (int)
RMA(src, length)
Dynamic RMA
Parameters:
src (float)
length (int)
ALMA(src, length, offset_sigma, sigma)
Dynamic ALMA
Parameters:
src (float)
length (int)
offset_sigma (float)
sigma (float)
ZLSMA(src, length)
Dynamic Zlsma
Parameters:
src (float)
length (int)
Thank you to @QuantraSystems for the dynamic codes.
PeekLevelLibrary "PeekLevel"
init()
run(state, zigZagPeriod, rsi, rsiMA)
Parameters:
state (ZigZagState)
zigZagPeriod (int)
rsi (float)
rsiMA (float)
method stableLevel(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method secondStableLevel(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method stableLevelTarget(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method secondStableLevelTarget(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method stableLevelRSI(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method secondStableLevelRSI(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method lastLevelRSI(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method lastLevel(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method lastLevelIndex(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method lastLevelTarget(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method lastLevelRSISignal(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method lastPriceJump(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
ZigZagState
Fields:
levelPrices (array)
levelRSI (array)
levelTarget (array)
levelTypes (array)
levelIndices (array)
levelRSISignal (array)
levelPriceJumps (array)
lastLevelPrice (series float)
lastLevelType (series int)
lastLevelIndex (series int)
lastLevelRSI (series float)
numUndirectedLevels (series int)
zigZagDirection (series int)
ATHLibrary "ATH"
TODO: add library description here
getMonthlyATH(symbol, lookbackBars)
TODO: add function description here
Parameters:
symbol (string)
lookbackBars (int)
Returns: TODO: add what function returns
回傳指定 symbol 的月線 ATH
jsonSignalBuilderV2🧩 jsonSignalBuilder – Pine Script JSON Alert Builder
Create structured JSON payloads for Pine Script alerts, ready to send to trading bots or automation platforms.
Use it to build webhook-compatible alerts for platforms like <> – a real-time trading signal platform.
🔗 Send alerts to: <>
MirPapa_Library_ICTLibrary "MirPapa_Library_ICT"
GetHTFoffsetToLTFoffset(_offset, _chartTf, _htfTf)
GetHTFoffsetToLTFoffset
@description Adjust an HTF offset to an LTF offset by calculating the ratio of timeframes.
Parameters:
_offset (int) : int The HTF bar offset (0 means current HTF bar).
_chartTf (string) : string The current chart’s timeframe (e.g., "5", "15", "1D").
_htfTf (string) : string The High Time Frame string (e.g., "60", "1D").
@return int The corresponding LTF bar index. Returns 0 if the result is negative.
IsConditionState(_type, _isBull, _level, _open, _close, _open1, _close1, _low1, _low2, _low3, _low4, _high1, _high2, _high3, _high4)
IsConditionState
@description Evaluate a condition state based on type for COB, FVG, or FOB.
Overloaded: first signature handles COB, second handles FVG/FOB.
Parameters:
_type (string) : string Condition type ("cob", "fvg", "fob").
_isBull (bool) : bool Direction flag: true for bullish, false for bearish.
_level (int) : int Swing level (only used for COB).
_open (float) : float Current bar open price (only for COB).
_close (float) : float Current bar close price (only for COB).
_open1 (float) : float Previous bar open price (only for COB).
_close1 (float) : float Previous bar close price (only for COB).
_low1 (float) : float Low 1 bar ago (only for COB).
_low2 (float) : float Low 2 bars ago (only for COB).
_low3 (float) : float Low 3 bars ago (only for COB).
_low4 (float) : float Low 4 bars ago (only for COB).
_high1 (float) : float High 1 bar ago (only for COB).
_high2 (float) : float High 2 bars ago (only for COB).
_high3 (float) : float High 3 bars ago (only for COB).
_high4 (float) : float High 4 bars ago (only for COB).
@return bool True if the specified condition is met, false otherwise.
IsConditionState(_type, _isBull, _pricePrev, _priceNow)
IsConditionState
@description Evaluate FVG or FOB condition based on price movement.
Parameters:
_type (string) : string Condition type ("fvg", "fob").
_isBull (bool) : bool Direction flag: true for bullish, false for bearish.
_pricePrev (float) : float Previous price (for FVG/FOB).
_priceNow (float) : float Current price (for FVG/FOB).
@return bool True if the specified condition is met, false otherwise.
IsSwingHighLow(_isBull, _level, _open, _close, _open1, _close1, _low1, _low2, _low3, _low4, _high1, _high2, _high3, _high4)
IsSwingHighLow
@description Public wrapper for isSwingHighLow.
Parameters:
_isBull (bool) : bool Direction flag: true for bullish, false for bearish.
_level (int) : int Swing level (1 or 2).
_open (float) : float Current bar open price.
_close (float) : float Current bar close price.
_open1 (float) : float Previous bar open price.
_close1 (float) : float Previous bar close price.
_low1 (float) : float Low 1 bar ago.
_low2 (float) : float Low 2 bars ago.
_low3 (float) : float Low 3 bars ago.
_low4 (float) : float Low 4 bars ago.
_high1 (float) : float High 1 bar ago.
_high2 (float) : float High 2 bars ago.
_high3 (float) : float High 3 bars ago.
_high4 (float) : float High 4 bars ago.
@return bool True if swing condition is met, false otherwise.
AddBox(_left, _right, _top, _bot, _xloc, _colorBG, _colorBD)
AddBox
@description Draw a rectangular box on the chart with specified coordinates and colors.
Parameters:
_left (int) : int Left bar index for the box.
_right (int) : int Right bar index for the box.
_top (float) : float Top price coordinate for the box.
_bot (float) : float Bottom price coordinate for the box.
_xloc (string) : string X-axis location type (e.g., xloc.bar_index).
_colorBG (color) : color Background color for the box.
_colorBD (color) : color Border color for the box.
@return box Returns the created box object.
Addline(_x, _y, _xloc, _color, _width)
Addline
@description Draw a vertical or horizontal line at specified coordinates.
Parameters:
_x (int) : int X-coordinate for start (bar index).
_y (int) : float Y-coordinate for start (price).
_xloc (string) : string X-axis location type (e.g., xloc.bar_index).
_color (color) : color Line color.
_width (int) : int Line width.
@return line Returns the created line object.
Addline(_x, _y, _xloc, _color, _width)
Parameters:
_x (int)
_y (float)
_xloc (string)
_color (color)
_width (int)
Addline(_x1, _y1, _x2, _y2, _xloc, _color, _width)
Parameters:
_x1 (int)
_y1 (int)
_x2 (int)
_y2 (int)
_xloc (string)
_color (color)
_width (int)
Addline(_x1, _y1, _x2, _y2, _xloc, _color, _width)
Parameters:
_x1 (int)
_y1 (int)
_x2 (int)
_y2 (float)
_xloc (string)
_color (color)
_width (int)
Addline(_x1, _y1, _x2, _y2, _xloc, _color, _width)
Parameters:
_x1 (int)
_y1 (float)
_x2 (int)
_y2 (int)
_xloc (string)
_color (color)
_width (int)
Addline(_x1, _y1, _x2, _y2, _xloc, _color, _width)
Parameters:
_x1 (int)
_y1 (float)
_x2 (int)
_y2 (float)
_xloc (string)
_color (color)
_width (int)
AddlineMid(_type, _left, _right, _top, _bot, _xloc, _color, _width)
AddlineMid
@description Draw a midline between top and bottom for FVG or FOB types.
Parameters:
_type (string) : string Type identifier: "fvg" or "fob".
_left (int) : int Left bar index for midline start.
_right (int) : int Right bar index for midline end.
_top (float) : float Top price of the region.
_bot (float) : float Bottom price of the region.
_xloc (string) : string X-axis location type (e.g., xloc.bar_index).
_color (color) : color Line color.
_width (int) : int Line width.
@return line or na Returns the created line or na if type is not recognized.
GetHtfFromLabel(_label)
GetHtfFromLabel
@description Convert a Korean HTF label into a Pine Script timeframe string via handler library.
Parameters:
_label (string) : string The Korean label (e.g., "5분", "1시간").
@return string Returns the corresponding Pine Script timeframe (e.g., "5", "60").
IsChartTFcomparisonHTF(_chartTf, _htfTf)
IsChartTFcomparisonHTF
@description Determine whether a given HTF is greater than or equal to the current chart timeframe.
Parameters:
_chartTf (string) : string Current chart timeframe (e.g., "5", "15", "1D").
_htfTf (string) : string HTF timeframe (e.g., "60", "1D").
@return bool True if HTF ≥ chartTF, false otherwise.
CreateBoxData(_type, _isBull, _useLine, _top, _bot, _xloc, _colorBG, _colorBD, _offset, _htfTf, htfBarIdx, _basePoint)
CreateBoxData
@description Create and draw a box and optional midline for given type and parameters. Returns success flag and BoxData.
Parameters:
_type (string) : string Type identifier: "fvg", "fob", "cob", or "sweep".
_isBull (bool) : bool Direction flag: true for bullish, false for bearish.
_useLine (bool) : bool Whether to draw a midline inside the box.
_top (float) : float Top price of the box region.
_bot (float) : float Bottom price of the box region.
_xloc (string) : string X-axis location type (e.g., xloc.bar_index).
_colorBG (color) : color Background color for the box.
_colorBD (color) : color Border color for the box.
_offset (int) : int HTF bar offset (0 means current HTF bar).
_htfTf (string) : string HTF timeframe string (e.g., "60", "1D").
htfBarIdx (int) : int HTF bar_index (passed from HTF request).
_basePoint (float) : float Base point for breakout checks.
@return tuple(bool, BoxData) Returns a boolean indicating success and the created BoxData struct.
ProcessBoxDatas(_datas, _useMidLine, _closeCount, _colorClose)
ProcessBoxDatas
@description Process an array of BoxData structs: extend, record volume, update stage, and finalize boxes.
Parameters:
_datas (array) : array Array of BoxData objects to process.
_useMidLine (bool) : bool Whether to update the midline endpoint.
_closeCount (int) : int Number of touches required to close the box.
_colorClose (color) : color Color to apply when a box closes.
@return void No return value; updates are in-place.
BoxData
Fields:
_isActive (series bool)
_isBull (series bool)
_box (series box)
_line (series line)
_basePoint (series float)
_boxTop (series float)
_boxBot (series float)
_stage (series int)
_isStay (series bool)
_volBuy (series float)
_volSell (series float)
_result (series string)
LineData
Fields:
_isActive (series bool)
_isBull (series bool)
_line (series line)
_basePoint (series float)
_stage (series int)
_isStay (series bool)
_result (series string)
MirPapa_Handler_HTFLibrary "MirPapa_Handler_HTF"
High Time Frame Handler Library:
Provides utilities for working with High Time Frame (HTF) and chart (LTF) conversions and data retrieval.
IsChartTFcomparisonHTF(_chartTf, _htfTf)
IsChartTFcomparisonHTF
@description
Determine whether the given High Time Frame (HTF) is greater than or equal to the current chart timeframe.
Parameters:
_chartTf (string) : The current chart’s timeframe string (examples: "5", "15", "1D").
_htfTf (string) : The High Time Frame string to compare (examples: "60", "1D").
@return
Returns true if HTF minutes ≥ chart minutes, false otherwise or na if conversion fails.
GetHTFrevised(_tf, _case)
GetHTFrevised
@description
Retrieve a specific bar value from a Higher Time Frame (HTF) series.
Supports current and historical OHLC values, based on a case identifier.
Parameters:
_tf (string) : The target HTF string (examples: "60", "1D").
_case (string) : A case string determining which OHLC value and bar offset to request:
"b" → HTF bar_index
"o" → HTF open
"h" → HTF high
"l" → HTF low
"c" → HTF close
"o1" → HTF open one bar ago
"h1" → HTF high one bar ago
"l1" → HTF low one bar ago
"c1" → HTF close one bar ago
… up to "o5", "h5", "l5", "c5" for five bars ago.
@return
Returns the requested HTF value or na if _case does not match any condition.
GetHTFfromLabel(_label)
GetHTFfromLabel
@description
Convert a Korean HTF label into a Pine Script-recognizable timeframe string.
Examples:
"5분" → "5"
"1시간" → "60"
"일봉" → "1D"
"주봉" → "1W"
"월봉" → "1M"
"연봉" → "12M"
Parameters:
_label (string) : The Korean HTF label string (examples: "5분", "1시간", "일봉").
@return
Returns the Pine Script timeframe string corresponding to the label, or "1W" if no match is found.
GetHTFoffsetToLTFoffset(_offset, _chartTf, _htfTf)
GetHTFoffsetToLTFoffset
@description
Adjust an HTF bar index and offset so that it aligns with the current chart’s bar index.
Useful for retrieving historical HTF data on an LTF chart.
Parameters:
_offset (int) : The HTF bar offset (0 means current HTF bar, 1 means one bar ago, etc.).
_chartTf (string) : The current chart’s timeframe string (examples: "5", "15", "1D").
_htfTf (string) : The High Time Frame string to align (examples: "60", "1D").
@return
Returns the corresponding LTF bar index after applying HTF offset. If result is negative, returns 0.
CommonUtils█ OVERVIEW
This library is a utility tool for Pine Script™ developers. It provides a collection of helper functions designed to simplify common tasks such as mapping user-friendly string inputs to Pine Script™ constants and formatting timeframe strings for display. The primary goal is to make main scripts cleaner, more readable, and reduce repetitive boilerplate code. It is envisioned as an evolving resource, with potential for new utilities to be added over time based on community needs and feedback.
█ CONCEPTS
The library primarily focuses on two main concepts:
Input Mapping
Pine Script™ often requires specific constants for function parameters (e.g., `line.style_dashed` for line styles, `position.top_center` for table positions). However, presenting these technical constants directly to users in script inputs can be confusing. Input mapping involves:
Allowing users to select options from more descriptive, human-readable strings (e.g., "Dashed", "Top Center") in the script's settings.
Providing functions within this library (e.g., `mapLineStyle`, `mapTablePosition`) that take these user-friendly strings as input.
Internally, these functions use switch statements or similar logic to convert (map) the input string to the corresponding Pine Script™ constant required by built-in functions.
This approach enhances user experience and simplifies the main script's logic by centralizing the mapping process.
Timeframe Formatting
Raw timeframe strings obtained from variables like `timeframe.period` (e.g., "1", "60", "D", "W") or user inputs are not always ideal for direct display in labels or panels. The `formatTimeframe` function addresses this by:
Taking a raw timeframe string as input.
Parsing this string to identify its numerical part and unit (e.g., minutes, hours, days, weeks, months, seconds, milliseconds).
Converting it into a more standardized and readable format (e.g., "1min", "60min", "Daily", "Weekly", "1s", "10M").
Offering an optional `customSuffix` parameter (e.g., " FVG", " Period") to append to the formatted string, making labels more descriptive, especially in multi-timeframe contexts.
The function is designed to correctly interpret various common timeframe notations used in TradingView.
█ NOTES
Ease of Use: The library functions are designed with simple and understandable signatures. They typically take a string input and return the corresponding Pine Script™ constant or a formatted string.
Default Behaviors: Mapping functions (`mapLineStyle`, `mapTablePosition`, `mapTextSize`) generally return a sensible default value (e.g., `line.style_solid` for `mapLineStyle`) in case of a non-matching input. This helps prevent errors in the main script.
Extensibility of Formatting: The `formatTimeframe` function, with its `customSuffix` parameter, allows for flexible customization of timeframe labels to suit the specific descriptive needs of different indicators or contexts.
Performance Considerations: These utility functions primarily use basic string operations and switch statements. For typical use cases, their impact on overall script performance is negligible. However, if a function like `formatTimeframe` were to be called excessively in a loop with dynamic inputs (which is generally not its intended use), performance should be monitored.
No Dependencies: This library is self-contained and does not depend on any other external Pine Script™ libraries.
█ EXPORTED FUNCTIONS
mapLineStyle(styleString)
Maps a user-provided line style string to its corresponding Pine Script™ line style constant.
Parameters:
styleString (simple string) : The input string representing the desired line style (e.g., "Solid", "Dashed", "Dotted" - typically from constants like LS1, LS2, LS3).
Returns: The Pine Script™ constant for the line style (e.g., line.style_solid). Defaults to line.style_solid if no match.
mapTablePosition(positionString)
Maps a user-provided table position string to its corresponding Pine Script™ position constant.
Parameters:
positionString (simple string) : The input string representing the desired table position (e.g., "Top Right", "Top Center" - typically from constants like PP1, PP2).
Returns: The Pine Script™ constant for the table position (e.g., position.top_right). Defaults to position.top_right if no match.
mapTextSize(sizeString)
Maps a user-provided text size string to its corresponding Pine Script™ size constant.
Parameters:
sizeString (simple string) : The input string representing the desired text size (e.g., "Tiny", "Small" - typically from constants like PTS1, PTS2).
Returns: The Pine Script™ constant for the text size (e.g., size.tiny). Defaults to size.small if no match.
formatTimeframe(tfInput, customSuffix)
Formats a raw timeframe string into a more display-friendly string, optionally appending a custom suffix.
Parameters:
tfInput (simple string) : The raw timeframe string from user input or timeframe.period (e.g., "1", "60", "D", "W", "1S", "10M", "2H").
customSuffix (simple string) : An optional suffix to append to the formatted timeframe string (e.g., " FVG", " Period"). Defaults to an empty string.
Returns: The formatted timeframe string (e.g., "1min", "60min", "Daily", "Weekly", "1s", "10min", "2h") with the custom suffix appended.
FvgPanel█ OVERVIEW
This library provides functionalities for creating and managing a display panel within a Pine Script™ indicator. Its primary purpose is to offer a structured way to present Fair Value Gap (FVG) information, specifically the nearest bullish and bearish FVG levels across different timeframes (Current, MTF, HTF), directly on the chart. The library handles the table's structure, header initialization, and dynamic cell content updates.
█ CONCEPTS
The core of this library revolves around presenting summarized FVG data in a clear, tabular format. Key concepts include:
FVG Data Aggregation and Display
The panel is designed to show at-a-glance information about the closest active FVG mitigation levels. It doesn't calculate these FVGs itself but relies on the main script to provide this data. The panel is structured with columns for timeframes (TF), Bullish FVGs, and Bearish FVGs, and rows for "Current" (LTF), "MTF" (Medium Timeframe), and "HTF" (High Timeframe).
The `panelData` User-Defined Type (UDT)
To facilitate the transfer of information to be displayed, the library defines a UDT named `panelData`. This structure is central to the library's operation and is designed to hold all necessary values for populating the panel's data cells for each relevant FVG. Its fields include:
Price levels for the nearest bullish and bearish FVGs for LTF, MTF, and HTF (e.g., `nearestBullMitLvl`, `nearestMtfBearMitLvl`).
Boolean flags to indicate if these FVGs are classified as "Large Volume" (LV) (e.g., `isNearestBullLV`, `isNearestMtfBearLV`).
Color information for the background and text of each data cell, allowing for conditional styling based on the FVG's status or proximity (e.g., `ltfBullBgColor`, `mtfBearTextColor`).
The design of `panelData` allows the main script to prepare all display-related data and styling cues in one object, which is then passed to the `updatePanel` function for rendering. This separation of data preparation and display logic keeps the library focused on its presentation task.
Visual Cues and Formatting
Price Formatting: Price levels are formatted to match the instrument's minimum tick size using an internal `formatPrice` helper function, ensuring consistent and accurate display.
Large FVG Icon: If an FVG is marked as a "Large Volume" FVG in the `panelData` object, a user-specified icon (e.g., an emoji) is prepended to its price level in the panel, providing an immediate visual distinction.
Conditional Styling: The background and text colors for each FVG level displayed in the panel can be individually controlled via the `panelData` object, enabling the main script to implement custom styling rules (e.g., highlighting the overall nearest FVG across all timeframes).
Handling Missing Data: If no FVG data is available for a particular cell (i.e., the corresponding level in `panelData` is `na`), the panel displays "---" and uses a specified background color for "Not Available" cells.
█ CALCULATIONS AND USE
Using the `FvgPanel` typically involves a two-stage process: initialization and dynamic updates.
Step 1: Panel Creation
First, an instance of the panel table is created once, usually during the script's initial setup. This is done using the `createPanel` function.
Call `createPanel()` with parameters defining its position on the chart, border color, border width, header background color, header text color, and header text size.
This function initializes the table with three columns ("TF", "Bull FVG", "Bear FVG") and three data rows labeled "Current", "MTF", and "HTF", plus a header row.
Store the returned `table` object in a `var` variable to persist it across bars.
// Example:
var table infoPanel = na
if barstate.isfirst
infoPanel := panel.createPanel(
position.top_right,
color.gray,
1,
color.new(color.gray, 50),
color.white,
size.small
)
Step 2: Panel Updates
On each bar, or whenever the FVG data changes (typically on `barstate.islast` or `barstate.isrealtime` for efficiency), the panel's content needs to be refreshed. This is done using the `updatePanel` function.
Populate an instance of the `panelData` UDT with the latest FVG information. This includes setting the nearest bullish/bearish mitigation levels for LTF, MTF, and HTF, their LV status, and their desired background and text colors.
Call `updatePanel()`, passing the persistent `table` object (from Step 1), the populated `panelData` object, the icon string for LV FVGs, the default text color for FVG levels, the background color for "N/A" cells, and the general text size for the data cells.
The `updatePanel` function will then clear previous data and fill the table cells with the new values and styles provided in the `panelData` object.
// Example (inside a conditional block like 'if barstate.islast'):
var panelData fvgDisplayData = panelData.new()
// ... (logic to populate fvgDisplayData fields) ...
// fvgDisplayData.nearestBullMitLvl = ...
// fvgDisplayData.ltfBullBgColor = ...
// ... etc.
if not na(infoPanel)
panel.updatePanel(
infoPanel,
fvgDisplayData,
"🔥", // LV FVG Icon
color.white,
color.new(color.gray, 70), // NA Cell Color
size.small
)
This workflow ensures that the panel is drawn only once and its cells are efficiently updated as new data becomes available.
█ NOTES
Data Source: This library is solely responsible for the visual presentation of FVG data in a table. It does not perform any FVG detection or calculation. The calling script must compute or retrieve the FVG levels, LV status, and desired styling to populate the `panelData` object.
Styling Responsibility: While `updatePanel` applies colors passed via the `panelData` object, the logic for *determining* those colors (e.g., highlighting the closest FVG to the current price) resides in the calling script.
Performance: The library uses `table.cell()` to update individual cells, which is generally more efficient than deleting and recreating the table on each update. However, the frequency of `updatePanel` calls should be managed by the main script (e.g., using `barstate.islast` or `barstate.isrealtime`) to avoid excessive processing on historical bars.
`series float` Handling: The price level fields within the `panelData` UDT (e.g., `nearestBullMitLvl`) can accept `series float` values, as these are typically derived from price data. The internal `formatPrice` function correctly handles `series float` for display.
Dependencies: The `FvgPanel` itself is self-contained and does not import other user libraries. It uses standard Pine Script™ table and string functionalities.
█ EXPORTED TYPES
panelData
Represents the data structure for populating the FVG information panel.
Fields:
nearestBullMitLvl (series float) : The price level of the nearest bullish FVG's mitigation point (bottom for bull) on the LTF.
isNearestBullLV (series bool) : True if the nearest bullish FVG on the LTF is a Large Volume FVG.
ltfBullBgColor (series color) : Background color for the LTF bullish FVG cell in the panel.
ltfBullTextColor (series color) : Text color for the LTF bullish FVG cell in the panel.
nearestBearMitLvl (series float) : The price level of the nearest bearish FVG's mitigation point (top for bear) on the LTF.
isNearestBearLV (series bool) : True if the nearest bearish FVG on the LTF is a Large Volume FVG.
ltfBearBgColor (series color) : Background color for the LTF bearish FVG cell in the panel.
ltfBearTextColor (series color) : Text color for the LTF bearish FVG cell in the panel.
nearestMtfBullMitLvl (series float) : The price level of the nearest bullish FVG's mitigation point on the MTF.
isNearestMtfBullLV (series bool) : True if the nearest bullish FVG on the MTF is a Large Volume FVG.
mtfBullBgColor (series color) : Background color for the MTF bullish FVG cell.
mtfBullTextColor (series color) : Text color for the MTF bullish FVG cell.
nearestMtfBearMitLvl (series float) : The price level of the nearest bearish FVG's mitigation point on the MTF.
isNearestMtfBearLV (series bool) : True if the nearest bearish FVG on the MTF is a Large Volume FVG.
mtfBearBgColor (series color) : Background color for the MTF bearish FVG cell.
mtfBearTextColor (series color) : Text color for the MTF bearish FVG cell.
nearestHtfBullMitLvl (series float) : The price level of the nearest bullish FVG's mitigation point on the HTF.
isNearestHtfBullLV (series bool) : True if the nearest bullish FVG on the HTF is a Large Volume FVG.
htfBullBgColor (series color) : Background color for the HTF bullish FVG cell.
htfBullTextColor (series color) : Text color for the HTF bullish FVG cell.
nearestHtfBearMitLvl (series float) : The price level of the nearest bearish FVG's mitigation point on the HTF.
isNearestHtfBearLV (series bool) : True if the nearest bearish FVG on the HTF is a Large Volume FVG.
htfBearBgColor (series color) : Background color for the HTF bearish FVG cell.
htfBearTextColor (series color) : Text color for the HTF bearish FVG cell.
█ EXPORTED FUNCTIONS
createPanel(position, borderColor, borderWidth, headerBgColor, headerTextColor, headerTextSize)
Creates and initializes the FVG information panel (table). Sets up the header rows and timeframe labels.
Parameters:
position (simple string) : The position of the panel on the chart (e.g., position.top_right). Uses position.* constants.
borderColor (simple color) : The color of the panel's border.
borderWidth (simple int) : The width of the panel's border.
headerBgColor (simple color) : The background color for the header cells.
headerTextColor (simple color) : The text color for the header cells.
headerTextSize (simple string) : The text size for the header cells (e.g., size.small). Uses size.* constants.
Returns: The newly created table object representing the panel.
updatePanel(panelTable, data, lvIcon, defaultTextColor, naCellColor, textSize)
Updates the content of the FVG information panel with the latest FVG data.
Parameters:
panelTable (table) : The table object representing the panel to be updated.
data (panelData) : An object containing the FVG data to display.
lvIcon (simple string) : The icon (e.g., emoji) to display next to Large Volume FVGs.
defaultTextColor (simple color) : The default text color for FVG levels if not highlighted.
naCellColor (simple color) : The background color for cells where no FVG data is available ("---").
textSize (simple string) : The text size for the FVG level data (e.g., size.small).
Returns: _void
FvgObject█ OVERVIEW
This library provides a suite of methods designed to manage the visual representation and lifecycle of Fair Value Gap (FVG) objects on a Pine Script™ chart. It extends the `fvgObject` User-Defined Type (UDT) by attaching object-oriented functionalities for drawing, updating, and deleting FVG-related graphical elements. The primary goal is to encapsulate complex drawing logic, making the main indicator script cleaner and more focused on FVG detection and state management.
█ CONCEPTS
This library is built around the idea of treating each Fair Value Gap as an "object" with its own visual lifecycle on the chart. This is achieved by defining methods that operate directly on instances of the `fvgObject` UDT.
Object-Oriented Approach for FVGs
Pine Script™ v6 introduced the ability to define methods for User-Defined Types (UDTs). This library leverages this feature by attaching specific drawing and state management functions (methods) directly to the `fvgObject` type. This means that instead of calling global functions with an FVG object as a parameter, you call methods *on* the FVG object itself (e.g., `myFvg.updateDrawings(...)`). This approach promotes better code organization and a more intuitive way to interact with FVG data.
FVG Visual Lifecycle Management
The core purpose of this library is to manage the complete visual journey of an FVG on the chart. This lifecycle includes:
Initial Drawing: Creating the first visual representation of a newly detected FVG, including its main box and optionally its midline and labels.
State Updates & Partial Fills: Modifying the FVG's appearance as it gets partially filled by price. This involves drawing a "mitigated" portion of the box and adjusting the `currentTop` or `currentBottom` of the remaining FVG.
Full Mitigation & Tested State: Handling how an FVG is displayed once fully mitigated. Depending on user settings, it might be hidden, or its box might change color/style to indicate it has been "tested." Mitigation lines can also be managed (kept or deleted).
Midline Interaction: Visually tracking if the price has touched the FVG's 50% equilibrium level (midline).
Visibility Control: Dynamically showing or hiding FVG drawings based on various criteria, such as user settings (e.g., hide mitigated FVGs, timeframe-specific visibility) or external filters (e.g., proximity to current price).
Deletion: Cleaning up all drawing objects associated with an FVG when it's no longer needed or when settings dictate its removal.
Centralized Drawing Logic
By encapsulating all drawing-related operations within the methods of this library, the main indicator script is significantly simplified. The main script can focus on detecting FVGs and managing their state (e.g., in arrays), while delegating the complex task of rendering and updating them on the chart to the methods herein.
Interaction with `fvgObject` and `drawSettings` UDTs
All methods within this library operate on an instance of the `fvgObject` UDT. This `fvgObject` holds not only the FVG's price/time data and state (like `isMitigated`, `currentTop`) but also the IDs of its associated drawing elements (e.g., `boxId`, `midLineId`).
The appearance of these drawings (colors, styles, visibility, etc.) is dictated by a `drawSettings` UDT instance, which is passed as a parameter to most drawing-related methods. This `drawSettings` object is typically populated from user inputs in the main script, allowing for extensive customization.
Stateful Drawing Object Management
The library's methods manage Pine Script™ drawing objects (boxes, lines, labels) by storing their IDs within the `fvgObject` itself (e.g., `fvgObject.boxId`, `fvgObject.mitigatedBoxId`, etc.). Methods like `draw()` create these objects and store their IDs, while methods like `updateDrawings()` modify them, and `deleteDrawings()` removes them using these stored IDs.
Drawing Optimization
The `updateDrawings()` method, which is the most comprehensive drawing management function, incorporates optimization logic. It uses `prev_*` fields within the `fvgObject` (e.g., `prevIsMitigated`, `prevCurrentTop`) to store the FVG's state from the previous bar. By comparing the current state with the previous state, and also considering changes in visibility or relevant drawing settings, it can avoid redundant and performance-intensive drawing operations if nothing visually significant has changed for that FVG.
█ METHOD USAGE AND WORKFLOW
The methods in this library are designed to be called in a logical sequence as an FVG progresses through its lifecycle. A crucial prerequisite for all visual methods in this library is a properly populated `drawSettings` UDT instance, which dictates every aspect of an FVG's appearance, from colors and styles to visibility and labels. This `settings` object must be carefully prepared in the main indicator script, typically based on user inputs, before being passed to these methods.
Here’s a typical workflow within a main indicator script:
1. FVG Instance Creation (External to this library)
An `fvgObject` instance is typically created by functions in another library (e.g., `FvgCalculations`) when a new FVG pattern is identified. This object will have its core properties (top, bottom, startTime, isBullish, tfType) initialized.
2. Initial Drawing (`draw` method)
Once a new `fvgObject` is created and its initial visibility is determined:
Call the `myFvg.draw(settings)` method on the new FVG object.
`settings` is an instance of the `drawSettings` UDT, containing all relevant visual configurations.
This method draws the primary FVG box, its midline (if enabled in `settings`), and any initial labels. It also initializes the `currentTop` and `currentBottom` fields of the `fvgObject` if they are `na`, and stores the IDs of the created drawing objects within the `fvgObject`.
3. Per-Bar State Updates & Interaction Checks
On each subsequent bar, for every active `fvgObject`:
Interaction Check (External Logic): It's common to first use logic (e.g., from `FvgCalculations`' `fvgInteractionCheck` function) to determine if the current bar's price interacts with the FVG.
State Field Updates (External Logic): Before calling the `FvgObjectLib` methods below, ensure that your `fvgObject`'s state fields (such as `isMitigated`, `currentTop`, `currentBottom`, `isMidlineTouched`) are updated using the current bar's price data and relevant functions from other libraries (e.g., `FvgCalculations`' `checkMitigation`, `checkPartialMitigation`, etc.). This library's methods render the FVG based on these pre-updated state fields.
If interaction occurs and the FVG is not yet fully mitigated:
Full Mitigation Update (`updateMitigation` method): Call `myFvg.updateMitigation(high, low)`. This method updates `myFvg.isMitigated` and `myFvg.mitigationTime` if full mitigation occurs, based on the interaction determined by external logic.
Partial Fill Update (`updatePartialFill` method): If not fully mitigated, call `myFvg.updatePartialFill(high, low, settings)`. This method updates `myFvg.currentTop` or `myFvg.currentBottom` and adjusts drawings to show the filled portion, again based on prior interaction checks and fill level calculations.
Midline Touch Check (`checkMidlineTouch` method): Call `myFvg.checkMidlineTouch(high, low)`. This method updates `myFvg.isMidlineTouched` if the price touches the FVG's 50% level.
4. Comprehensive Visual Update (`updateDrawings` method)
After the FVG's state fields have been potentially updated by external logic and the methods in step 3:
Call `myFvg.updateDrawings(isVisibleNow, settings)` on each FVG object.
`isVisibleNow` is a boolean indicating if the FVG should currently be visible.
`settings` is the `drawSettings` UDT instance.
This method synchronizes the FVG's visual appearance with its current state and settings, managing all drawing elements (boxes, lines, labels), their styles, and visibility. It efficiently skips redundant drawing operations if the FVG's state or visibility has not changed, thanks to its internal optimization using `prev_*` fields, which are also updated by this method.
5. Deleting Drawings (`deleteDrawings` method)
When an FVG object is no longer tracked:
Call `myFvg.deleteDrawings(deleteTestedToo)`.
This method removes all drawing objects associated with that `fvgObject`.
This workflow ensures that FVG visuals are accurately maintained throughout their existence on the chart.
█ NOTES
Dependencies: This library relies on `FvgTypes` for `fvgObject` and `drawSettings` definitions, and its methods (`updateMitigation`, `updatePartialFill`) internally call functions from `FvgCalculations`.
Drawing Object Management: Be mindful of TradingView's limits on drawing objects per script. The main script should manage the number of active FVG objects.
Performance and `updateDrawings()`: The `updateDrawings()` method is comprehensive. Its internal optimization (checking `hasStateChanged` based on `prev_*` fields) is crucial for performance. Call it judiciously.
Role of `settings.currentTime`: The `currentTime` field in `drawSettings` is key for positioning time-dependent elements like labels and the right edge of non-extended drawings.
Mutability of `fvgObject` Instances: Methods in this library directly modify the `fvgObject` instance they are called upon (e.g., its state fields and drawing IDs).
Drawing ID Checks: Methods generally check if drawing IDs are `na` before acting on them, preventing runtime errors.
█ EXPORTED FUNCTIONS
method draw(this, settings)
Draws the initial visual representation of the FVG object on the chart. This includes the main FVG box, its midline (if enabled), and a label
(if enabled for the specific timeframe). This method is typically invoked
immediately after an FVG is first detected and its initial properties are set. It uses drawing settings to customize the appearance based on the FVG's timeframe type.
Namespace types: types.fvgObject
Parameters:
this (fvgObject type from no1x/FvgTypes/1) : The FVG object instance to be drawn. Core properties (top, bottom,
startTime, isBullish, tfType) should be pre-initialized. This method will
initialize boxId, midLineId, boxLabelId (if applicable), and
currentTop/currentBottom (if currently na) on this object.
settings (drawSettings type from no1x/FvgTypes/1) : A drawSettings object providing all visual parameters. Reads display settings (colors, styles, visibility for boxes, midlines, labels,
box extension) relevant to this.tfType. settings.currentTime is used for
positioning labels and the right boundary of non-extended boxes.
method updateMitigation(this, highVal, lowVal)
Checks if the FVG has been fully mitigated by the current bar's price action.
Namespace types: types.fvgObject
Parameters:
this (fvgObject type from no1x/FvgTypes/1) : The FVG object instance. Reads this.isMitigated, this.isVisible,
this.isBullish, this.top, this.bottom. Updates this.isMitigated and
this.mitigationTime if full mitigation occurs.
highVal (float) : The high price of the current bar, used for mitigation check.
lowVal (float) : The low price of the current bar, used for mitigation check.
method updatePartialFill(this, highVal, lowVal, settings)
Checks for and processes partial fills of the FVG.
Namespace types: types.fvgObject
Parameters:
this (fvgObject type from no1x/FvgTypes/1) : The FVG object instance. Reads this.isMitigated, this.isVisible,
this.isBullish, this.currentTop, this.currentBottom, original this.top/this.bottom,
this.startTime, this.tfType, this.isLV. Updates this.currentTop or
this.currentBottom, creates/updates this.mitigatedBoxId, and may update this.boxId's
top/bottom to reflect the filled portion.
highVal (float) : The high price of the current bar, used for partial fill check.
lowVal (float) : The low price of the current bar, used for partial fill check.
settings (drawSettings type from no1x/FvgTypes/1) : The drawing settings. Reads timeframe-specific colors for mitigated
boxes (e.g., settings.mitigatedBullBoxColor, settings.mitigatedLvBullColor),
box extension settings (settings.shouldExtendBoxes, settings.shouldExtendMtfBoxes, etc.),
and settings.currentTime to style and position the mitigatedBoxId and potentially adjust the main boxId.
method checkMidlineTouch(this, highVal, lowVal)
Checks if the FVG's midline (50% level or Equilibrium) has been touched.
Namespace types: types.fvgObject
Parameters:
this (fvgObject type from no1x/FvgTypes/1) : The FVG object instance. Reads this.midLineId, this.isMidlineTouched,
this.top, this.bottom. Updates this.isMidlineTouched if a touch occurs.
highVal (float) : The high price of the current bar, used for midline touch check.
lowVal (float) : The low price of the current bar, used for midline touch check.
method deleteDrawings(this, deleteTestedToo)
Deletes all visual drawing objects associated with this FVG object.
Namespace types: types.fvgObject
Parameters:
this (fvgObject type from no1x/FvgTypes/1) : The FVG object instance. Deletes drawings referenced by boxId,
mitigatedBoxId, midLineId, mitLineId, boxLabelId, mitLineLabelId,
and potentially testedBoxId, keptMitLineId. Sets these ID fields to na.
deleteTestedToo (simple bool) : If true, also deletes drawings for "tested" FVGs
(i.e., testedBoxId and keptMitLineId).
method updateDrawings(this, isVisibleNow, settings)
Manages the comprehensive update of all visual elements of an FVG object
based on its current state (e.g., active, mitigated, partially filled) and visibility. It handles the drawing, updating, or deletion of FVG boxes (main and mitigated part),
midlines, mitigation lines, and their associated labels. Visibility is determined by the isVisibleNow parameter and relevant settings
(like settings.shouldHideMitigated or timeframe-specific show flags). This method is central to the FVG's visual lifecycle and includes optimization
to avoid redundant drawing operations if the FVG's relevant state or appearance
settings have not changed since the last bar. It also updates the FVG object's internal prev_* state fields for future optimization checks.
Namespace types: types.fvgObject
Parameters:
this (fvgObject type from no1x/FvgTypes/1) : The FVG object instance to update. Reads most state fields (e.g.,
isMitigated, currentTop, tfType, etc.) and updates all drawing ID fields
(boxId, midLineId, etc.), this.isVisible, and all this.prev_* state fields.
isVisibleNow (bool) : A flag indicating whether the FVG should be currently visible. Typically determined by external logic (e.g., visual range filter). Affects
whether active FVG drawings are created/updated or deleted by this method.
settings (drawSettings type from no1x/FvgTypes/1) : A fully populated drawSettings object. This method extensively
reads its fields (colors, styles, visibility toggles, timeframe strings, etc.)
to render FVG components according to this.tfType and current state. settings.currentTime is critical for positioning elements like labels and extending drawings.
FvgCalculations█ OVERVIEW
This library provides the core calculation engine for identifying Fair Value Gaps (FVGs) across different timeframes and for processing their interaction with price. It includes functions to detect FVGs on both the current chart and higher timeframes, as well as to check for their full or partial mitigation.
█ CONCEPTS
The library's primary functions revolve around the concept of Fair Value Gaps and their lifecycle.
Fair Value Gap (FVG) Identification
An FVG, or imbalance, represents a price range where buying or selling pressure was significant enough to cause a rapid price movement, leaving an "inefficiency" in the market. This library identifies FVGs based on three-bar patterns:
Bullish FVG: Forms when the low of the current bar (bar 3) is higher than the high of the bar two periods prior (bar 1). The FVG is the space between the high of bar 1 and the low of bar 3.
Bearish FVG: Forms when the high of the current bar (bar 3) is lower than the low of the bar two periods prior (bar 1). The FVG is the space between the low of bar 1 and the high of bar 3.
The library provides distinct functions for detecting FVGs on the current (Low Timeframe - LTF) and specified higher timeframes (Medium Timeframe - MTF / High Timeframe - HTF).
FVG Mitigation
Mitigation refers to price revisiting an FVG.
Full Mitigation: An FVG is considered fully mitigated when price completely closes the gap. For a bullish FVG, this occurs if the current low price moves below or touches the FVG's bottom. For a bearish FVG, it occurs if the current high price moves above or touches the FVG's top.
Partial Mitigation (Entry/Fill): An FVG is partially mitigated when price enters the FVG's range but does not fully close it. The library tracks the extent of this fill. For a bullish FVG, if the current low price enters the FVG from above, that low becomes the new effective top of the remaining FVG. For a bearish FVG, if the current high price enters the FVG from below, that high becomes the new effective bottom of the remaining FVG.
FVG Interaction
This refers to any instance where the current bar's price range (high to low) touches or crosses into the currently unfilled portion of an active (visible and not fully mitigated) FVG.
Multi-Timeframe Data Acquisition
To detect FVGs on higher timeframes, specific historical bar data (high, low, and time of bars at indices and relative to the higher timeframe's last completed bar) is required. The requestMultiTFBarData function is designed to fetch this data efficiently.
█ CALCULATIONS AND USE
The functions in this library are typically used in a sequence to manage FVGs:
1. Data Retrieval (for MTF/HTF FVGs):
Call requestMultiTFBarData() with the desired higher timeframe string (e.g., "60", "D").
This returns a tuple of htfHigh1, htfLow1, htfTime1, htfHigh3, htfLow3, htfTime3.
2. FVG Detection:
For LTF FVGs: Call detectFvg() on each confirmed bar. It uses high , low, low , and high along with barstate.isconfirmed.
For MTF/HTF FVGs: Call detectMultiTFFvg() using the data obtained from requestMultiTFBarData().
Both detection functions return an fvgObject (defined in FvgTypes) if an FVG is found, otherwise na. They also can classify FVGs as "Large Volume" (LV) if classifyLV is true and the FVG size (top - bottom) relative to the tfAtr (Average True Range of the respective timeframe) meets the lvAtrMultiplier.
3. FVG State Updates (on each new bar for existing FVGs):
First, check for overall price interaction using fvgInteractionCheck(). This function determines if the current bar's high/low has touched or entered the FVG's currentTop or currentBottom.
If interaction occurs and the FVG is not already mitigated:
Call checkMitigation() to determine if the FVG has been fully mitigated by the current bar's currentHigh and currentLow. If true, the FVG's isMitigated status is updated.
If not fully mitigated, call checkPartialMitigation() to see if the price has further entered the FVG. This function returns the newLevel to which the FVG has been filled (e.g., currentLow for a bullish FVG, currentHigh for bearish). This newLevel is then used to update the FVG's currentTop or currentBottom.
The calling script (e.g., fvgMain.c) is responsible for storing and managing the array of fvgObject instances and passing them to these update functions.
█ NOTES
Bar State for LTF Detection: The detectFvg() function relies on barstate.isconfirmed to ensure FVG detection is based on closed bars, preventing FVGs from being detected prematurely on the currently forming bar.
Higher Timeframe Data (lookahead): The requestMultiTFBarData() function uses lookahead = barmerge.lookahead_on. This means it can access historical data from the higher timeframe that corresponds to the current bar on the chart, even if the higher timeframe bar has not officially closed. This is standard for multi-timeframe analysis aiming to plot historical HTF data accurately on a lower timeframe chart.
Parameter Typing: Functions like detectMultiTFFvg and detectFvg infer the type for boolean (classifyLV) and numeric (lvAtrMultiplier) parameters passed from the main script, while explicitly typed series parameters (like htfHigh1, currentAtr) expect series data.
fvgObject Dependency: The FVG detection functions return fvgObject instances, and fvgInteractionCheck takes an fvgObject as a parameter. This UDT is defined in the FvgTypes library, making it a dependency for using FvgCalculations.
ATR for LV Classification: The tfAtr (for MTF/HTF) and currentAtr (for LTF) parameters are expected to be the Average True Range values for the respective timeframes. These are used, if classifyLV is enabled, to determine if an FVG's size qualifies it as a "Large Volume" FVG based on the lvAtrMultiplier.
MTF/HTF FVG Appearance Timing: When displaying FVGs from a higher timeframe (MTF/HTF) on a lower timeframe (LTF) chart, users might observe that the most recent MTF/HTF FVG appears one LTF bar later compared to its appearance on a native MTF/HTF chart. This is an expected behavior due to the detection mechanism in `detectMultiTFFvg`. This function uses historical bar data from the MTF/HTF (specifically, data equivalent to `HTF_bar ` and `HTF_bar `) to identify an FVG. Therefore, all three bars forming the FVG on the MTF/HTF must be fully closed and have shifted into these historical index positions relative to the `request.security` call from the LTF chart before the FVG can be detected and displayed on the LTF. This ensures that the MTF/HTF FVG is identified based on confirmed, closed bars from the higher timeframe.
█ EXPORTED FUNCTIONS
requestMultiTFBarData(timeframe)
Requests historical bar data for specific previous bars from a specified higher timeframe.
It fetches H , L , T (for the bar before last) and H , L , T (for the bar three periods prior)
from the requested timeframe.
This is typically used to identify FVG patterns on MTF/HTF.
Parameters:
timeframe (simple string) : The higher timeframe to request data from (e.g., "60" for 1-hour, "D" for Daily).
Returns: A tuple containing: .
- htfHigh1 (series float): High of the bar at index 1 (one bar before the last completed bar on timeframe).
- htfLow1 (series float): Low of the bar at index 1.
- htfTime1 (series int) : Time of the bar at index 1.
- htfHigh3 (series float): High of the bar at index 3 (three bars before the last completed bar on timeframe).
- htfLow3 (series float): Low of the bar at index 3.
- htfTime3 (series int) : Time of the bar at index 3.
detectMultiTFFvg(htfHigh1, htfLow1, htfTime1, htfHigh3, htfLow3, htfTime3, tfAtr, classifyLV, lvAtrMultiplier, tfType)
Detects a Fair Value Gap (FVG) on a higher timeframe (MTF/HTF) using pre-fetched bar data.
Parameters:
htfHigh1 (float) : High of the first relevant bar (typically high ) from the higher timeframe.
htfLow1 (float) : Low of the first relevant bar (typically low ) from the higher timeframe.
htfTime1 (int) : Time of the first relevant bar (typically time ) from the higher timeframe.
htfHigh3 (float) : High of the third relevant bar (typically high ) from the higher timeframe.
htfLow3 (float) : Low of the third relevant bar (typically low ) from the higher timeframe.
htfTime3 (int) : Time of the third relevant bar (typically time ) from the higher timeframe.
tfAtr (float) : ATR value for the higher timeframe, used for Large Volume (LV) FVG classification.
classifyLV (bool) : If true, FVGs will be assessed to see if they qualify as Large Volume.
lvAtrMultiplier (float) : The ATR multiplier used to define if an FVG is Large Volume.
tfType (series tfType enum from no1x/FvgTypes/1) : The timeframe type (e.g., types.tfType.MTF, types.tfType.HTF) of the FVG being detected.
Returns: An fvgObject instance if an FVG is detected, otherwise na.
detectFvg(classifyLV, lvAtrMultiplier, currentAtr)
Detects a Fair Value Gap (FVG) on the current (LTF - Low Timeframe) chart.
Parameters:
classifyLV (bool) : If true, FVGs will be assessed to see if they qualify as Large Volume.
lvAtrMultiplier (float) : The ATR multiplier used to define if an FVG is Large Volume.
currentAtr (float) : ATR value for the current timeframe, used for LV FVG classification.
Returns: An fvgObject instance if an FVG is detected, otherwise na.
checkMitigation(isBullish, fvgTop, fvgBottom, currentHigh, currentLow)
Checks if an FVG has been fully mitigated by the current bar's price action.
Parameters:
isBullish (bool) : True if the FVG being checked is bullish, false if bearish.
fvgTop (float) : The top price level of the FVG.
fvgBottom (float) : The bottom price level of the FVG.
currentHigh (float) : The high price of the current bar.
currentLow (float) : The low price of the current bar.
Returns: True if the FVG is considered fully mitigated, false otherwise.
checkPartialMitigation(isBullish, currentBoxTop, currentBoxBottom, currentHigh, currentLow)
Checks for partial mitigation of an FVG by the current bar's price action.
It determines if the price has entered the FVG and returns the new fill level.
Parameters:
isBullish (bool) : True if the FVG being checked is bullish, false if bearish.
currentBoxTop (float) : The current top of the FVG box (this might have been adjusted by previous partial fills).
currentBoxBottom (float) : The current bottom of the FVG box (similarly, might be adjusted).
currentHigh (float) : The high price of the current bar.
currentLow (float) : The low price of the current bar.
Returns: The new price level to which the FVG has been filled (e.g., currentLow for a bullish FVG).
Returns na if no new partial fill occurred on this bar.
fvgInteractionCheck(fvg, highVal, lowVal)
Checks if the current bar's price interacts with the given FVG.
Interaction means the price touches or crosses into the FVG's
current (possibly partially filled) range.
Parameters:
fvg (fvgObject type from no1x/FvgTypes/1) : The FVG object to check.
Its isMitigated, isVisible, isBullish, currentTop, and currentBottom fields are used.
highVal (float) : The high price of the current bar.
lowVal (float) : The low price of the current bar.
Returns: True if price interacts with the FVG, false otherwise.
FvgTypes█ OVERVIEW
This library serves as a foundational module for Pine Script™ projects focused on Fair Value Gaps (FVGs). Its primary purpose is to define and centralize custom data structures (User-Defined Types - UDTs) and enumerations that are utilized across various components of an FVG analysis system. By providing standardized types for FVG characteristics and drawing configurations, it promotes code consistency, readability, and easier maintenance within a larger FVG indicator or strategy.
█ CONCEPTS
The library introduces several key data structures (User-Defined Types - UDTs) and an enumeration to organize Fair Value Gap (FVG) related data logically. These types are central to the functioning of FVG analysis tools built upon this library.
Timeframe Categorization (`tfType` Enum)
To manage and differentiate FVGs based on their timeframe of origin, the `tfType` enumeration is defined. It includes:
`LTF`: Low Timeframe (typically the current chart).
`MTF`: Medium Timeframe.
`HTF`: High Timeframe.
This allows for distinct logic and visual settings to be applied depending on the FVG's source timeframe.
FVG Data Encapsulation (`fvgObject` UDT)
The `fvgObject` is a comprehensive UDT designed to encapsulate all pertinent information and state for an individual Fair Value Gap throughout its lifecycle. Instead of listing every field, its conceptual structure can be understood as holding:
Core Definition: The FVG's fundamental price levels (top, bottom) and its formation time (`startTime`).
Classification Attributes: Characteristics such as its direction (`isBullish`) and whether it qualifies as a Large Volume FVG (`isLV`), along with its originating timeframe category (`tfType`).
Lifecycle State: Current status indicators including full mitigation (`isMitigated`, `mitigationTime`), partial fill levels (`currentTop`, `currentBottom`), midline interaction (`isMidlineTouched`), and overall visibility (`isVisible`).
Drawing Identifiers: References (`boxId`, `midLineId`, `mitLineLabelId`, etc.) to the actual graphical objects drawn on the chart to represent the FVG and its components.
Optimization Cache: Previous-bar state values (`prevIsMitigated`, `prevCurrentTop`, etc.) crucial for optimizing drawing updates by avoiding redundant operations.
This comprehensive structure facilitates easy access to all FVG-related information through a single object, reducing code complexity and improving manageability.
Drawing Configuration (`drawSettings` UDT)
The `drawSettings` UDT centralizes all user-configurable parameters that dictate the visual appearance of FVGs across different timeframes. It's typically populated from script inputs and conceptually groups settings for:
General Behavior: Global FVG classification toggles (e.g., `shouldClassifyLV`) and general display rules (e.g., `shouldHideMitigated`).
FVG Type Specific Colors: Colors for standard and Large Volume FVGs, both active and mitigated (e.g., `lvBullColor`, `mitigatedBearBoxColor`).
Timeframe-Specific Visuals (LTF, MTF, HTF): Detailed parameters for each timeframe category, covering FVG boxes (visibility, colors, extension, borders, labels), midlines (visibility, style, color), and mitigation lines (visibility, style, color, labels, persistence after mitigation).
Contextual Information: The current bar's time (`currentTime`) for accurate positioning of time-dependent drawing elements and timeframe display strings (`tfString`, `mtfTfString`, `htfTfString`).
This centralized approach allows for extensive customization of FVG visuals and simplifies the management of drawing parameters within the main script. Such centralization also enhances the maintainability of the visual aspects of the FVG system.
█ NOTES
User-Defined Types (UDTs): This library extensively uses UDTs (`fvgObject`, `drawSettings`) to group related data. This improves code organization and makes it easier to pass complex data between functions and libraries.
Mutability and Reference Behavior of UDTs: When UDT instances are passed to functions or methods in other libraries (like `fvgObjectLib`), those functions might modify the fields of the passed object if they are not explicitly designed to return new instances. This is because UDTs are passed by reference and are mutable in Pine Script™. Users should be aware of this standard behavior to prevent unintended side effects.
Optimization Fields: The `prev_*` fields in `fvgObject` are crucial for performance optimization in the drawing logic. They help avoid unnecessary redrawing of FVG elements if their state or relevant settings haven't changed.
No Direct Drawing Logic: `FvgTypes` itself does not contain any drawing logic. It solely defines the data structures. The actual drawing and manipulation of these objects are handled by other libraries (e.g., `fvgObjectLib`).
Centralized Definitions: By defining these types in a separate library, any changes to the structure of FVG data or settings can be made in one place, ensuring consistency across all dependent scripts and libraries.
█ EXPORTED TYPES
fvgObject
fvgObject Represents a Fair Value Gap (FVG) object.
Fields:
top (series float) : The top price level of the FVG.
bottom (series float) : The bottom price level of the FVG.
startTime (series int) : The start time (timestamp) of the bar where the FVG formed.
isBullish (series bool) : Indicates if the FVG is bullish (true) or bearish (false).
isLV (series bool) : Indicates if the FVG is a Large Volume FVG.
tfType (series tfType) : The timeframe type (LTF, MTF, HTF) to which this FVG belongs.
isMitigated (series bool) : Indicates if the FVG has been fully mitigated.
mitigationTime (series int) : The time (timestamp) when the FVG was mitigated.
isVisible (series bool) : The current visibility status of the FVG, typically managed by drawing logic based on filters.
isMidlineTouched (series bool) : Indicates if the price has touched the FVG's midline (50% level).
currentTop (series float) : The current top level of the FVG after partial fills.
currentBottom (series float) : The current bottom level of the FVG after partial fills.
boxId (series box) : The drawing ID for the main FVG box.
mitigatedBoxId (series box) : The drawing ID for the box representing the partially filled (mitigated) area.
midLineId (series line) : The drawing ID for the FVG's midline.
mitLineId (series line) : The drawing ID for the FVG's mitigation line.
boxLabelId (series label) : The drawing ID for the FVG box label.
mitLineLabelId (series label) : The drawing ID for the mitigation line label.
testedBoxId (series box) : The drawing ID for the box of a fully mitigated (tested) FVG, if kept visible.
keptMitLineId (series line) : The drawing ID for a mitigation line that is kept after full mitigation.
prevIsMitigated (series bool) : Stores the isMitigated state from the previous bar for optimization.
prevCurrentTop (series float) : Stores the currentTop value from the previous bar for optimization.
prevCurrentBottom (series float) : Stores the currentBottom value from the previous bar for optimization.
prevIsVisible (series bool) : Stores the visibility status from the previous bar for optimization (derived from isVisibleNow passed to updateDrawings).
prevIsMidlineTouched (series bool) : Stores the isMidlineTouched status from the previous bar for optimization.
drawSettings
drawSettings A structure containing settings for drawing FVGs.
Fields:
shouldClassifyLV (series bool) : Whether to classify FVGs as Large Volume (LV) based on ATR.
shouldHideMitigated (series bool) : Whether to hide FVG boxes once they are fully mitigated.
currentTime (series int) : The current bar's time, used for extending drawings.
lvBullColor (series color) : Color for Large Volume Bullish FVGs.
mitigatedLvBullColor (series color) : Color for mitigated Large Volume Bullish FVGs.
lvBearColor (series color) : Color for Large Volume Bearish FVGs.
mitigatedLvBearColor (series color) : Color for mitigated Large Volume Bearish FVGs.
shouldShowBoxes (series bool) : Whether to show FVG boxes for the LTF.
bullBoxColor (series color) : Color for LTF Bullish FVG boxes.
mitigatedBullBoxColor (series color) : Color for mitigated LTF Bullish FVG boxes.
bearBoxColor (series color) : Color for LTF Bearish FVG boxes.
mitigatedBearBoxColor (series color) : Color for mitigated LTF Bearish FVG boxes.
boxLengthBars (series int) : Length of LTF FVG boxes in bars (if not extended).
shouldExtendBoxes (series bool) : Whether to extend LTF FVG boxes to the right.
shouldShowCurrentTfBoxLabels (series bool) : Whether to show labels on LTF FVG boxes.
shouldShowBoxBorder (series bool) : Whether to show a border for LTF FVG boxes.
boxBorderWidth (series int) : Border width for LTF FVG boxes.
boxBorderStyle (series string) : Border style for LTF FVG boxes (e.g., line.style_solid).
boxBorderColor (series color) : Border color for LTF FVG boxes.
shouldShowMidpoint (series bool) : Whether to show the midline (50% level) for LTF FVGs.
midLineWidthInput (series int) : Width of the LTF FVG midline.
midpointLineStyleInput (series string) : Style of the LTF FVG midline.
midpointColorInput (series color) : Color of the LTF FVG midline.
shouldShowMitigationLine (series bool) : Whether to show the mitigation line for LTF FVGs.
(Line always extends if shown)
mitLineWidthInput (series int) : Width of the LTF FVG mitigation line.
mitigationLineStyleInput (series string) : Style of the LTF FVG mitigation line.
mitigationLineColorInput (series color) : Color of the LTF FVG mitigation line.
shouldShowCurrentTfMitLineLabels (series bool) : Whether to show labels on LTF FVG mitigation lines.
currentTfMitLineLabelOffsetX (series float) : The horizontal offset value for the LTF mitigation line's label.
shouldKeepMitigatedLines (series bool) : Whether to keep showing mitigation lines of fully mitigated LTF FVGs.
mitigatedMitLineColor (series color) : Color for kept mitigation lines of mitigated LTF FVGs.
tfString (series string) : Display string for the LTF (e.g., "Current TF").
shouldShowMtfBoxes (series bool) : Whether to show FVG boxes for the MTF.
mtfBullBoxColor (series color) : Color for MTF Bullish FVG boxes.
mtfMitigatedBullBoxColor (series color) : Color for mitigated MTF Bullish FVG boxes.
mtfBearBoxColor (series color) : Color for MTF Bearish FVG boxes.
mtfMitigatedBearBoxColor (series color) : Color for mitigated MTF Bearish FVG boxes.
mtfBoxLengthBars (series int) : Length of MTF FVG boxes in bars (if not extended).
shouldExtendMtfBoxes (series bool) : Whether to extend MTF FVG boxes to the right.
shouldShowMtfBoxLabels (series bool) : Whether to show labels on MTF FVG boxes.
shouldShowMtfBoxBorder (series bool) : Whether to show a border for MTF FVG boxes.
mtfBoxBorderWidth (series int) : Border width for MTF FVG boxes.
mtfBoxBorderStyle (series string) : Border style for MTF FVG boxes.
mtfBoxBorderColor (series color) : Border color for MTF FVG boxes.
shouldShowMtfMidpoint (series bool) : Whether to show the midline for MTF FVGs.
mtfMidLineWidthInput (series int) : Width of the MTF FVG midline.
mtfMidpointLineStyleInput (series string) : Style of the MTF FVG midline.
mtfMidpointColorInput (series color) : Color of the MTF FVG midline.
shouldShowMtfMitigationLine (series bool) : Whether to show the mitigation line for MTF FVGs.
(Line always extends if shown)
mtfMitLineWidthInput (series int) : Width of the MTF FVG mitigation line.
mtfMitigationLineStyleInput (series string) : Style of the MTF FVG mitigation line.
mtfMitigationLineColorInput (series color) : Color of the MTF FVG mitigation line.
shouldShowMtfMitLineLabels (series bool) : Whether to show labels on MTF FVG mitigation lines.
mtfMitLineLabelOffsetX (series float) : The horizontal offset value for the MTF mitigation line's label.
shouldKeepMtfMitigatedLines (series bool) : Whether to keep showing mitigation lines of fully mitigated MTF FVGs.
mtfMitigatedMitLineColor (series color) : Color for kept mitigation lines of mitigated MTF FVGs.
mtfTfString (series string) : Display string for the MTF (e.g., "MTF").
shouldShowHtfBoxes (series bool) : Whether to show FVG boxes for the HTF.
htfBullBoxColor (series color) : Color for HTF Bullish FVG boxes.
htfMitigatedBullBoxColor (series color) : Color for mitigated HTF Bullish FVG boxes.
htfBearBoxColor (series color) : Color for HTF Bearish FVG boxes.
htfMitigatedBearBoxColor (series color) : Color for mitigated HTF Bearish FVG boxes.
htfBoxLengthBars (series int) : Length of HTF FVG boxes in bars (if not extended).
shouldExtendHtfBoxes (series bool) : Whether to extend HTF FVG boxes to the right.
shouldShowHtfBoxLabels (series bool) : Whether to show labels on HTF FVG boxes.
shouldShowHtfBoxBorder (series bool) : Whether to show a border for HTF FVG boxes.
htfBoxBorderWidth (series int) : Border width for HTF FVG boxes.
htfBoxBorderStyle (series string) : Border style for HTF FVG boxes.
htfBoxBorderColor (series color) : Border color for HTF FVG boxes.
shouldShowHtfMidpoint (series bool) : Whether to show the midline for HTF FVGs.
htfMidLineWidthInput (series int) : Width of the HTF FVG midline.
htfMidpointLineStyleInput (series string) : Style of the HTF FVG midline.
htfMidpointColorInput (series color) : Color of the HTF FVG midline.
shouldShowHtfMitigationLine (series bool) : Whether to show the mitigation line for HTF FVGs.
(Line always extends if shown)
htfMitLineWidthInput (series int) : Width of the HTF FVG mitigation line.
htfMitigationLineStyleInput (series string) : Style of the HTF FVG mitigation line.
htfMitigationLineColorInput (series color) : Color of the HTF FVG mitigation line.
shouldShowHtfMitLineLabels (series bool) : Whether to show labels on HTF FVG mitigation lines.
htfMitLineLabelOffsetX (series float) : The horizontal offset value for the HTF mitigation line's label.
shouldKeepHtfMitigatedLines (series bool) : Whether to keep showing mitigation lines of fully mitigated HTF FVGs.
htfMitigatedMitLineColor (series color) : Color for kept mitigation lines of mitigated HTF FVGs.
htfTfString (series string) : Display string for the HTF (e.g., "HTF").
utilsLibrary "utils"
TODO: add library description here
method getType(this)
Namespace types: series int, simple int, input int, const int
Parameters:
this (int) : int 待检测对象
Returns: string 类型名称
method getType(this)
Namespace types: series float, simple float, input float, const float
Parameters:
this (float) : float 待检测对象
Returns: string 类型名称
method getType(this)
Namespace types: series color, simple color, input color, const color
Parameters:
this (color) : color 待检测对象
Returns: string 类型名称
method getType(this)
Namespace types: series string, simple string, input string, const string
Parameters:
this (string) : string 待检测对象
Returns: string 类型名称
method getType(this)
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
this (bool) : bool 待检测对象
Returns: string 类型名称
MonthlyPnLTableLibrary "MonthlyPnLTable"
monthlyPnL(currentClose, initialOpenPrice, monthsToDisplay)
Parameters:
currentClose (float)
initialOpenPrice (float)
monthsToDisplay (int)
displayPnLTable(pnls, pnlMonths, pnlYears, textSizeOption, labelColor)
Parameters:
pnls (array)
pnlMonths (array)
pnlYears (array)
textSizeOption (string)
labelColor (color)
DisplayUtilitiesLibrary "DisplayUtilities"
Display utilities for color management and visual presentation
get_direction_color(direction, up_excessive, up_normal, neutral, down_normal, down_excessive)
Get candle color based on direction and color scheme
Parameters:
direction (int) : Direction value (-2, -1, 0, 1, 2)
up_excessive (color) : Color for +2 direction
up_normal (color) : Color for +1 direction
neutral (color) : Color for 0 direction
down_normal (color) : Color for -1 direction
down_excessive (color) : Color for -2 direction
Returns: Appropriate color for the direction
get_candle_paint_directions(paint_opt, body_dir, bar_dir, breakout_dir, combined_dir)
Get candle directions for different painting algorithms
Parameters:
paint_opt (string) : Painting option algorithm
body_dir (int) : Body direction
bar_dir (int) : Bar direction
breakout_dir (int) : Breakout direction
combined_dir (int) : Combined direction
Returns:
get_bias_paint_directions(paint_bias, unified_dir)
Get paint directions based on bias filter
Parameters:
paint_bias (string) : Paint bias option ("All", "Bull Bias", "Bear Bias")
unified_dir (int) : Unified direction
Returns: Directions for two plotcandle series
get_transparency_levels(sf_filtered, fade_option, fade_opacity)
Calculate transparency levels for strength factor filtering
Parameters:
sf_filtered (bool) : Is strength factor filtered
fade_option (string) : Fade option ("Disabled", "Fade Candle", "Do Not Fade Wick", "Do Not Fade Wick and Border")
fade_opacity (int) : Fade opacity percentage
Returns:
get_strength_factor_filter(filter_option, individual_filters)
Generate strength factor filter conditions
Parameters:
filter_option (string) : Filter option string
individual_filters (map) : Map of individual filter conditions
Returns: Boolean filter result
get_signal_bar_condition(signal_option, individual_filters)
Generate signal bar conditions (inverted filters)
Parameters:
signal_option (string) : Signal bar option string
individual_filters (map) : Map of individual filter conditions
Returns: Boolean signal bar result
get_zscore_signal_condition(z_signal_option, z_filters)
Get Z-score signal bar conditions
Parameters:
z_signal_option (string) : Z-score signal option
z_filters (map) : Map of Z-score filters
Returns: Boolean Z-score signal condition
get_standard_colors()
Create a standard color scheme for directions
Returns: Standard color set
apply_zscore_modification(original_dir, z_filtered)
Modify directions for Z-score excess display
Parameters:
original_dir (int) : Original direction
z_filtered (bool) : Is Z-score filtered (shows excess)
Returns: Modified direction (doubled if excess detected)
get_default_fade_colors()
Get default fade colors for strength factor overlay
Returns: Default colors for TV overlay
should_paint_candles(paint_algo)
Check if paint algorithm should show candles
Parameters:
paint_algo (string) : Paint algorithm option
Returns: True if algorithm should display candles
get_signal_bar_char(signal_type, is_bullish)
Get signal bar character based on signal type
Parameters:
signal_type (string) : Signal type ("strength_factor" or "zscore")
is_bullish (bool) : Direction is bullish
Returns: Character and location for plotchar
get_signal_bar_color(signal_type, is_bullish)
Get signal bar colors
Parameters:
signal_type (string) : Signal type ("strength_factor" or "zscore")
is_bullish (bool) : Direction is bullish
Returns: Signal bar color