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.
Göstergeler ve stratejiler
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
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
ZScoreAnalysisLibrary "ZScoreAnalysis"
Z-score analysis for detecting statistical deviations and excess market behavior
calculate_zscore(source, lookback, threshold, switch_enabled)
Calculate Z-score and related metrics with history tracking
Parameters:
source (float) : Data source for Z-score calculation
lookback (int) : Lookback period for mean and standard deviation
threshold (float) : Z-score threshold for significance
switch_enabled (string) : Enable/disable switch ("Enabled"/"Disabled")
Returns: Z-score, historical significant values, and running average
get_zscore_threshold(opt, input_thr, avg)
Get threshold based on threshold option
Parameters:
opt (string) : Threshold option ("User Input Threshold", "Average as Threshold", or other)
input_thr (float) : User input threshold
avg (float) : Average threshold
Returns: Calculated threshold value
is_zscore_filtered(switch_enabled, zscore, threshold)
Check if a metric passes the Z-score filter
Parameters:
switch_enabled (string) : Enable/disable switch
zscore (float) : Current Z-score value
threshold (float) : Z-score threshold
Returns: True if filtered (exceeds threshold)
get_consecutive_distances(body_dir, breakout_dir, is_inside_bar)
Calculate consecutive distances for Z-score analysis
Parameters:
body_dir (int) : Body direction
breakout_dir (int) : Breakout direction
is_inside_bar (bool) : Inside bar flag
Returns:
get_trend_to_mean_distance()
Calculate distance from trend to mean for momentum analysis
Returns: Distance between trend and mean
get_all_zscores(lookback, threshold, bar_dist_switch, body_dist_switch, chl_dist_switch, cc_dist_switch, m_dist_switch, body_dir, breakout_dir, is_inside_bar)
Get all Z-score calculations for the indicator
Parameters:
lookback (int) : Z-score lookback period
threshold (float) : Z-score threshold
bar_dist_switch (string) : Enable bar distance Z-score
body_dist_switch (string) : Enable body distance Z-score
chl_dist_switch (string) : Enable consecutive highs/lows Z-score
cc_dist_switch (string) : Enable consecutive closes Z-score
m_dist_switch (string) : Enable momentum distance Z-score
body_dir (int) : Body direction
breakout_dir (int) : Breakout direction
is_inside_bar (bool) : Inside bar flag
Returns: Array of Z-score results and filters
get_combined_zscore_filters(z_filters)
Get combined Z-score filters
Parameters:
z_filters (map) : Map of individual Z-score filters
Returns: Various combinations of Z-score filters
get_basic_distances()
Calculate basic distances used in Z-score analysis
Returns: Bar range and body range
get_individual_zscore_filter(z_filters, filter_name)
Get individual Z-score filter by name
Parameters:
z_filters (map) : Map of Z-score filters
filter_name (string) : Name of the filter ("bar_dist", "body_dist", etc.)
Returns: Boolean filter result
has_any_zscore_signal(z_filters)
Check if any Z-score filter is active
Parameters:
z_filters (map) : Map of individual Z-score filters
Returns: True if any Z-score exceeds threshold
StrengthFactorsLibrary "StrengthFactors"
Strength factor calculations for various market analysis metrics
get_threshold(opt, input_val, avg_val, lineancy)
Calculate threshold based on options
Parameters:
opt (string) : Threshold option ("Disabled", "User Input Threshold", "Average as Threshold")
input_val (float) : User input threshold value
avg_val (float) : Average value for threshold
lineancy (float) : Lineancy adjustment percentage
Returns: Calculated threshold
get_percentage_of_threshold(value, threshold)
Calculate percentage of threshold
Parameters:
value (float) : Current value
threshold (float) : Threshold value
Returns: Percentage of threshold
get_distance_sf(lookback, thr_opt, thr_inp, lineancy)
Calculate Distance Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_uniformity_sf(lookback, thr_opt, thr_inp, stddev_mult, lineancy)
Calculate Uniformity Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
stddev_mult (float) : Standard deviation multiplier
lineancy (float) : Lineancy adjustment
Returns:
get_overlap_sf(lookback, thr_opt, thr_inp, lineancy)
Calculate Overlap Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_body_sf(lookback, thr_opt, thr_inp, lineancy)
Calculate Body Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_close_sf(lookback, thr_opt, thr_inp, lineancy)
Calculate Close Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_breakout_sf(lookback, thr_opt, thr_inp, lineancy, bro_dir, is_inside_bar)
Calculate Breakout Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
bro_dir (int) : Breakout direction
is_inside_bar (bool) : Is inside bar flag
Returns:
get_always_in_sf(thr_opt, thr_inp, lineancy)
Calculate Always-In Strength Factor
Parameters:
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_directional_sf(overlap_prc, distance_prc, body_prc, close_prc, breakout_prc, lookback, thr_opt, thr_inp, lineancy)
Calculate Directional Strength Factor (composite)
Parameters:
overlap_prc (float) : Overlap SF as percentage of threshold
distance_prc (float) : Distance SF as percentage of threshold
body_prc (float) : Body SF as percentage of threshold
close_prc (float) : Close SF as percentage of threshold
breakout_prc (float) : Breakout SF as percentage of threshold
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_combined_direction_sf(body_prc, close_prc, breakout_prc, lookback, thr_opt, thr_inp, lineancy)
Calculate Combined Direction Strength Factor
Parameters:
body_prc (float) : Body SF as percentage of threshold
close_prc (float) : Close SF as percentage of threshold
breakout_prc (float) : Breakout SF as percentage of threshold
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_all_strength_factors(lookback, lineancy, dist_thr_opt, dist_thr_inp, body_thr_opt, body_thr_inp, close_thr_opt, close_thr_inp, breakout_thr_opt, breakout_thr_inp, bro_dir, is_inside_bar)
Get all strength factors at once (convenience function)
Parameters:
lookback (int) : Lookback period for averages
lineancy (float) : Lineancy adjustment percentage
dist_thr_opt (string) : Distance threshold option
dist_thr_inp (float) : Distance threshold input
body_thr_opt (string) : Body threshold option
body_thr_inp (float) : Body threshold input
close_thr_opt (string) : Close threshold option
close_thr_inp (float) : Close threshold input
breakout_thr_opt (string) : Breakout threshold option
breakout_thr_inp (float) : Breakout threshold input
bro_dir (int) : Breakout direction
is_inside_bar (bool) : Is inside bar flag
Returns: Map containing all strength factor results
DirectionCalculationsLibrary "DirectionCalculations"
Direction calculation algorithms for body, bar, and breakout directions
get_body_direction()
Calculate body direction based on open vs close
Returns: Body direction: 1 (bullish), -1 (bearish), 0 (doji)
get_bar_direction()
Calculate bar direction based on close position relative to hl2
Returns: Bar direction: 1 (upper half), -1 (lower half), 0 (middle)
get_breakout_direction()
Calculate breakout direction with outside/inside bar logic
Returns:
get_combined_direction(bod_dir, bar_dir, bro_dir, bro_ob_dir)
Calculate combined direction from body and bar directions
Parameters:
bod_dir (int) : Body direction
bar_dir (int) : Bar direction
bro_dir (int) : Breakout direction
bro_ob_dir (int) : Outside bar direction
Returns: Combined direction
is_consecutive_direction(current_dir, previous_dir)
Check if directions are consecutive (no reversal)
Parameters:
current_dir (int) : Current direction
previous_dir (int) : Previous direction
Returns: True if consecutive (no reversal from +1 to -1 or -1 to +1)
get_all_directions()
Get all direction calculations at once
Returns:
get_breakout_distances()
Get distance calculations for breakout analysis
Returns: High-to-high and low-to-low distances
get_bar_patterns()
Check for specific bar patterns
Returns:
WeightedVolumeUtilsLibrary "WeightedVolumeUtils"
fun(x)
Returns the input value (placeholder function).
Parameters:
x (float) : A float value.
Returns: The same float value passed as input.
weightedBSEVolume()
Calculates the weighted volume for BSE index based on top constituent stocks.
Returns: Weighted volume value based on fixed weights for BSE SENSEX stocks.
getAdjustedVolume()
Returns the adjusted volume for SENSEX or regular volume otherwise.
Returns: Weighted BSE volume if current symbol is SENSEX, else raw volume.
MathSpecialFunctionsConvolve1DLibrary "MathSpecialFunctionsConvolve1D"
Convolution is one of the most important mathematical operations used in signal processing. This simple mathematical operation pops up in many scientific and industrial applications, from its use in a billion-layer large CNN to simple image denoising.
___
Reference:
www.algorithm-archive.org
numpy.org
lloydrochester.com
www.geeksforgeeks.org
f(signal, filter)
Convolve
Parameters:
signal (array) : List with signal data.
filter (array) : List with weights to apply to the signal data.
Returns: Discrete, linear convolution of `signal` and `filter`.
BTC_News_2025Library "BTC_News_2025"
This library contains the tooltips used in the script "Bitcoin History Events (BTC Story)"
V1 News from January to May
tt_020125()
tt_070125()
tt_200125()
tt_270125()
tt_300125()
tt_030225()
tt_260225()
tt_240225()
tt_020325()
tt_030325()
tt_090325()
tt_110325()
tt_190325()
tt_280325()
tt_310325()
tt_020425()
tt_060425()
tt_090425()
tt_150425()
tt_190425()
tt_220425()
tt_050525()
tt_080525()
tt_130525()
tt_200525()
tt_220525()