FVG Premium [no1x]█ OVERVIEW
This indicator provides a comprehensive toolkit for identifying, visualizing, and tracking Fair Value Gaps (FVGs) across three distinct timeframes (current chart, a user-defined Medium Timeframe - MTF, and a user-defined High Timeframe - HTF). It is designed to offer traders enhanced insight into FVG dynamics through detailed state monitoring (formation, partial fill, full mitigation, midline touch), extensive visual customization for FVG representation, and a rich alert system for timely notifications on FVG-related events.
█ CONCEPTS
This indicator is built upon the core concept of Fair Value Gaps (FVGs) and their significance in price action analysis, offering a multi-layered approach to their detection and interpretation across different timeframes.
Fair Value Gaps (FVGs)
A Fair Value Gap (FVG), also known as an imbalance, represents a range in price delivery where one side of the market (buying or selling) was more aggressive, leaving an inefficiency or an "imbalance" in the price action. This concept is prominently featured within Smart Money Concepts (SMC) and Inner Circle Trader (ICT) methodologies, where such gaps are often interpreted as footprints left by "smart money" due to rapid, forceful price movements. These methodologies suggest that price may later revisit these FVG zones to rebalance a prior inefficiency or to seek liquidity before continuing its path. These gaps are typically identified by a three-bar pattern:
Bullish FVG : This is a three-candle formation where the second candle shows a strong upward move. The FVG is the space created between the high of the first candle (bottom of FVG) and the low of the third candle (top of FVG). This indicates a strong upward impulsive move.
Bearish FVG : This is a three-candle formation where the second candle shows a strong downward move. The FVG is the space created between the low of the first candle (top of FVG) and the high of the third candle (bottom of FVG). This indicates a strong downward impulsive move.
FVGs are often watched by traders as potential areas where price might return to "rebalance" or find support/resistance.
Multi-Timeframe (MTF) Analysis
The indicator extends FVG detection beyond the current chart's timeframe (Low Timeframe - LTF) to two higher user-defined timeframes: Medium Timeframe (MTF) and High Timeframe (HTF). This allows traders to:
Identify FVGs that might be significant on a broader market structure.
Observe how FVGs from different timeframes align or interact.
Gain a more comprehensive perspective on potential support and resistance zones.
FVG State and Lifecycle Management
The indicator actively tracks the lifecycle of each detected FVG:
Formation : The initial identification of an FVG.
Partial Fill (Entry) : When price enters but does not completely pass through the FVG. The indicator updates the "current" top/bottom of the FVG to reflect the filled portion.
Midline (Equilibrium) Touch : When price touches the 50% level of the FVG.
Full Mitigation : When price completely trades through the FVG, effectively "filling" or "rebalancing" the gap. The indicator records the mitigation time.
This state tracking is crucial for understanding how price interacts with these zones.
FVG Classification (Large FVG)
FVGs can be optionally classified as "Large FVGs" (LV) if their size (top to bottom range) exceeds a user-defined multiple of the Average True Range (ATR) for that FVG's timeframe. This helps distinguish FVGs that are significantly larger relative to recent volatility.
Visual Customization and Information Delivery
A key concept is providing extensive control over how FVGs are displayed. This control is achieved through a centralized set of visual parameters within the indicator, allowing users to configure numerous aspects (colors, line styles, visibility of boxes, midlines, mitigation lines, labels, etc.) for each timeframe. Additionally, an on-chart information panel summarizes the nearest unmitigated bullish and bearish FVG levels for each active timeframe, providing a quick glance at key price points.
█ FEATURES
This indicator offers a rich set of features designed to provide a highly customizable and comprehensive Fair Value Gap (FVG) analysis experience. Users can tailor the FVG detection, visual representation, and alerting mechanisms across three distinct timeframes: the current chart (Low Timeframe - LTF), a user-defined Medium Timeframe (MTF), and a user-defined High Timeframe (HTF).
Multi-Timeframe FVG Detection and Display
The core strength of this indicator lies in its ability to identify and display FVGs from not only the current chart's timeframe (LTF) but also from two higher, user-selectable timeframes (MTF and HTF).
Timeframe Selection: Users can specify the exact MTF (e.g., "60", "240") and HTF (e.g., "D", "W") through dedicated inputs in the "MTF (Medium Timeframe)" and "HTF (High Timeframe)" settings groups. The visibility of FVGs from these higher timeframes can be toggled independently using the "Show MTF FVGs" and "Show HTF FVGs" checkboxes.
Consistent Detection Logic: The FVG detection logic, based on the classic three-bar imbalance pattern detailed in the 'Concepts' section, is applied consistently across all selected timeframes (LTF, MTF, HTF)
Timeframe-Specific Visuals: Each timeframe's FVGs (LTF, MTF, HTF) can be customized with unique colors for bullish/bearish states and their mitigated counterparts. This allows for easy visual differentiation of FVGs originating from different market perspectives.
Comprehensive FVG Visualization Options
The indicator provides extensive control over how FVGs are visually represented on the chart for each timeframe (LTF, MTF, HTF).
FVG Boxes:
Visibility: Main FVG boxes can be shown or hidden per timeframe using the "Show FVG Boxes" (for LTF), "Show Boxes" (for MTF/HTF) inputs.
Color Customization: Colors for bullish, bearish, active, and mitigated FVG boxes (including Large FVGs, if classified) are fully customizable for each timeframe.
Box Extension & Length: FVG boxes can either be extended to the right indefinitely ("Extend Boxes Right") or set to a fixed length in bars ("Short Box Length" or "Box Length" equivalent inputs).
Box Labels: Optional labels can display the FVG's timeframe and fill percentage on the box. These labels are configurable for all timeframes (LTF, MTF, and HTF). Please note: If FVGs are positioned very close to each other on the chart, their respective labels may overlap. This can potentially lead to visual clutter, and it is a known behavior in the current version of the indicator.
Box Borders: Visibility, width, style (solid, dashed, dotted), and color of FVG box borders are customizable per timeframe.
Midlines (Equilibrium/EQ):
Visibility: The 50% level (midline or EQ) of FVGs can be shown or hidden for each timeframe.
Style Customization: Width, style, and color of the midline are customizable per timeframe. The indicator tracks if this midline has been touched by price.
Mitigation Lines:
Visibility: Mitigation lines (representing the FVG's opening level that needs to be breached for full mitigation) can be shown or hidden for each timeframe. If shown, these lines are always extended to the right.
Style Customization: Width, style, and color of the mitigation line are customizable per timeframe.
Mitigation Line Labels: Optional price labels can be displayed on mitigation lines, with a customizable horizontal bar offset for positioning. For optimal label placement, the following horizontal bar offsets are recommended: 4 for LTF, 8 for MTF, and 12 for HTF.
Persistence After Mitigation: Users can choose to keep mitigation lines visible even after an FVG is fully mitigated, with a distinct color for such lines. Importantly, this option is only effective if the general setting 'Hide Fully Mitigated FVGs' is disabled, as otherwise, the entire FVG and its lines will be removed upon mitigation.
FVG State Management and Behavior
The indicator tracks and visually responds to changes in FVG states.
Hide Fully Mitigated FVGs: This option, typically found in the indicator's general settings, allows users to automatically remove all visual elements of an FVG from the chart once price has fully mitigated it. This helps maintain chart clarity by focusing on active FVGs.
Partial Fill Visualization: When price enters an FVG, the indicator offers a dynamic visual representation: the portion of the FVG that has been filled is shown as a "mitigated box" (typically with a distinct color), while the original FVG box shrinks to clearly highlight the remaining, unfilled portion. This two-part display provides an immediate visual cue about how much of the FVG's imbalance has been addressed and what potential remains within the gap.
Visual Filtering by ATR Proximity: To help users focus on the most relevant price action, FVGs can be dynamically hidden if they are located further from the current price than a user-defined multiple of the Average True Range (ATR). This behavior is controlled by the "Filter Band Width (ATR Multiple)" input; setting this to zero disables the filter entirely, ensuring all detected FVGs remain visible regardless of their proximity to price.
Alternative Usage Example: Mitigation Lines as Key Support/Resistance Levels
For traders preferring a minimalist chart focused on key Fair Value Gap (FVG) levels, the indicator's visualization settings can be customized to display only FVG mitigation lines. This approach leverages these lines as potential support and resistance zones, reflecting areas where price might revisit to address imbalances.
To configure this view:
Disable FVG Boxes: Turn off "Show FVG Boxes" (for LTF) or "Show Boxes" (for MTF/HTF) for the desired timeframes.
Hide Midlines: Disable the visibility of the 50% FVG Midlines (Equilibrium/EQ).
Ensure Mitigation Lines are Visible: Keep "Mitigation Lines" enabled.
Retain All Mitigation Lines:
Disable the "Hide Fully Mitigated FVGs" option in the general settings.
Enable the feature to "keep mitigation lines visible even after an FVG is fully mitigated". This ensures lines from all FVGs (active or fully mitigated) remain on the chart, which is only effective if "Hide Fully Mitigated FVGs" is disabled.
This setup offers:
A Decluttered Chart: Focuses solely on the FVG opening levels.
Precise S/R Zones: Treats mitigation lines as specific points for potential price reactions.
Historical Level Analysis: Includes lines from past, fully mitigated FVGs for a comprehensive view of significant price levels.
For enhanced usability with this focused view, consider these optional additions:
The on-chart Information Panel can be activated to display a quick summary of the nearest unmitigated FVG levels.
Mitigation Line Labels can also be activated for clear price level identification. A customizable horizontal bar offset is available for positioning these labels; for example, offsets of 4 for LTF, 8 for MTF, and 12 for HTF can be effective.
FVG Classification (Large FVG)
This feature allows for distinguishing FVGs based on their size relative to market volatility.
Enable Classification: Users can enable "Classify FVG (Large FVG)" to identify FVGs that are significantly larger than average.
ATR-Based Threshold: An FVG is classified as "Large" if its height (price range) is greater than or equal to the Average True Range (ATR) of its timeframe multiplied by a user-defined "Large FVG Threshold (ATR Multiple)". The ATR period for this calculation is also configurable.
Dedicated Colors: Large FVGs (both bullish/bearish and active/mitigated) can be assigned unique colors, making them easily distinguishable on the chart.
Panel Icon: Large FVGs are marked with a special icon in the Info Panel.
Information Panel
An on-chart panel provides a quick summary of the nearest unmitigated FVG levels.
Visibility and Position: The panel can be shown/hidden and positioned in any of the nine standard locations on the chart (e.g., Top Right, Middle Center).
Content: It displays the price levels of the nearest unmitigated bullish and bearish FVGs for LTF, MTF (if active), and HTF (if active). It also indicates if these nearest FVGs are Large FVGs (if classification is enabled) using a selectable icon.
Styling: Text size, border color, header background/text colors, default text color, and "N/A" cell background color are customizable.
Highlighting: Background and text colors for the cells displaying the overall nearest bullish and bearish FVG levels (across all active timeframes) can be customized to draw attention to the most proximate FVG.
Comprehensive Alert System
The indicator offers a granular alert system for various FVG-related events, configurable for each timeframe (LTF, MTF, HTF) independently. Users can enable alerts for:
New FVG Formation: Separate alerts for new bullish and new bearish FVG formations.
FVG Entry/Partial Fill: Separate alerts for price entering a bullish FVG or a bearish FVG.
FVG Full Mitigation: Separate alerts for full mitigation of bullish and bearish FVGs.
FVG Midline (EQ) Touch: Separate alerts for price touching the midline of a bullish or bearish FVG.
Alert messages are detailed, providing information such as the timeframe, FVG type (bull/bear, Large FVG), relevant price levels, and timestamps.
█ NOTES
This section provides additional information regarding the indicator's usage, performance considerations, and potential interactions with the TradingView platform. Understanding these points can help users optimize their experience and troubleshoot effectively.
Performance and Resource Management
Maximum FVGs to Track : The "Max FVGs to Track" input (defaulting to 25) limits the number of FVG objects processed for each category (e.g., LTF Bullish, MTF Bearish). Increasing this value significantly can impact performance due to more objects being iterated over and potentially drawn, especially when multiple timeframes are active.
Drawing Object Limits : To manage performance, this script sets its own internal limits on the number of drawing objects it displays. While it allows for up to approximately 500 lines (max_lines_count=500) and 500 labels (max_labels_count=500), the number of FVG boxes is deliberately restricted to a maximum of 150 (max_boxes_count=150). This specific limit for boxes is a key performance consideration: displaying too many boxes can significantly slow down the indicator, and a very high number is often not essential for analysis. Enabling all visual elements for many FVGs across all three timeframes can cause the indicator to reach these internal limits, especially the stricter box limit
Optimization Strategies : To help you manage performance, reduce visual clutter, and avoid exceeding drawing limits when using this indicator, I recommend the following strategies:
Maintain or Lower FVG Tracking Count: The "Max FVGs to Track" input defaults to 25. I find this value generally sufficient for effective analysis and balanced performance. You can keep this default or consider reducing it further if you experience performance issues or prefer a less dense FVG display.
Utilize Proximity Filtering: I suggest activating the "Filter Band Width (ATR Multiple)" option (found under "General Settings") to display only those FVGs closer to the current price. From my experience, a value of 5 for the ATR multiple often provides a good starting point for balanced performance, but you should feel free to adjust this based on market volatility and your specific trading needs.
Hide Fully Mitigated FVGs: I strongly recommend enabling the "Hide Fully Mitigated FVGs" option. This setting automatically removes all visual elements of an FVG from the chart once it has been fully mitigated by price. Doing so significantly reduces the number of active drawing objects, lessens computational load, and helps maintain chart clarity by focusing only on active, relevant FVGs.
Disable FVG Display for Unused Timeframes: If you are not actively monitoring certain higher timeframes (MTF or HTF) for FVG analysis, I advise disabling their display by unchecking "Show MTF FVGs" or "Show HTF FVGs" respectively. This can provide a significant performance boost.
Simplify Visual Elements: For active FVGs, consider hiding less critical visual elements if they are not essential for your specific analysis. This could include box labels, borders, or even entire FVG boxes if, for example, only the mitigation lines are of interest for a particular timeframe.
Settings Changes and Platform Limits : This indicator is comprehensive and involves numerous calculations and drawings. When multiple settings are changed rapidly in quick succession, it is possible, on occasion, for TradingView to issue a "Runtime error: modify_study_limit_exceeding" or similar. This can cause the indicator to temporarily stop updating or display errors.
Recommended Approach : When adjusting settings, it is advisable to wait a brief moment (a few seconds) after each significant change. This allows the indicator to reprocess and update on the chart before another change is made
Error Recovery : Should such a runtime error occur, making a minor, different adjustment in the settings (e.g., toggling a checkbox off and then on again) and waiting briefly will typically allow the indicator to recover and resume correct operation. This behavior is related to platform limitations when handling complex scripts with many inputs and drawing objects.
Multi-Timeframe (MTF/HTF) Data and Behavior
HTF FVG Confirmation is Essential: : For an FVG from a higher timeframe (MTF or HTF) to be identified and displayed on your current chart (LTF), the three-bar pattern forming the FVG on that higher timeframe must consist of fully closed bars. The indicator does not draw speculative FVGs based on incomplete/forming bars from higher timeframes.
Data Retrieval and LTF Processing: The indicator may use techniques like lookahead = barmerge.lookahead_on for timely data retrieval from higher timeframes. However, the actual detection of an FVG occurs after all its constituent bars on the HTF have closed.
Appearance Timing on LTF (1 LTF Candle Delay): As a natural consequence of this, an FVG that is confirmed on an HTF (i.e., its third bar closes) will typically become visible on your LTF chart one LTF bar after its confirmation on the HTF.
Example: Assume an FVG forms on a 30-minute chart at 15:30 (i.e., with the close of the 30-minute bar that covers the 15:00-15:30 period). If you are monitoring this FVG on a 15-minute chart, the indicator will detect this newly formed 30-minute FVG while processing the data for the 15-minute bar that starts at 15:30 and closes at 15:45. Therefore, the 30-minute FVG will become visible on your 15-minute chart at the earliest by 15:45 (i.e., with the close of that relevant 15-minute LTF candle). This means the HTF FVG is reflected on the LTF chart with a delay equivalent to one LTF candle.
FVG Detection and Display Logic
Fair Value Gaps (FVGs) on the current chart timeframe (LTF) are detected based on barstate.isconfirmed. This means the three-bar pattern must be complete with closed bars before an FVG is identified. This confirmation method prevents FVGs from being prematurely identified on the forming bar.
Alerts
Alert Setup : To receive alerts from this indicator, you must first ensure you have enabled the specific alert conditions you are interested in within the indicator's own settings (see 'Comprehensive Alert System' under the 'FEATURES' section). Once configured, open TradingView's 'Create Alert' dialog. In the 'Condition' tab, select this indicator's name, and crucially, choose the 'Any alert() function call' option from the dropdown list. This setup allows the indicator to trigger alerts based on the precise event conditions you have activated in its settings
Alert Frequency : Alerts are designed to trigger once per bar close (alert.freq_once_per_bar_close) for the specific event.
User Interface (UI) Tips
Settings Group Icons: In the indicator settings menu, timeframe-specific groups are marked with star icons for easier navigation: 🌟 for LTF (Current Chart Timeframe), 🌟🌟 for MTF (Medium Timeframe), and 🌟🌟🌟 for HTF (High Timeframe).
Dependent Inputs: Some input settings are dependent on others being enabled. These dependencies are visually indicated in the settings menu using symbols like "↳" (dependent setting on the next line), "⟷" (mutually exclusive inline options), or "➜" (directly dependent inline option).
Settings Layout Overview: The indicator settings are organized into logical groups for ease of use. Key global display controls – such as toggles for MTF FVGs, HTF FVGs (along with their respective timeframe selectors), and the Information Panel – are conveniently located at the very top within the '⚙️ General Settings' group. This placement allows for quick access to frequently adjusted settings. Other sections provide detailed customization options for each timeframe (LTF, MTF, HTF), specific FVG components, and alert configurations.
█ FOR Pine Script® CODERS
This section provides a high-level overview of the FVG Premium indicator's internal architecture, data flow, and the interaction between its various library components. It is intended for Pine Script™ programmers who wish to understand the indicator's design, potentially extend its functionality, or learn from its structure.
System Architecture and Modular Design
The indicator is architected moduarly, leveraging several custom libraries to separate concerns and enhance code organization and reusability. Each library has a distinct responsibility:
FvgTypes: Serves as the foundational data definition layer. It defines core User-Defined Types (UDTs) like fvgObject (for storing all attributes of an FVG) and drawSettings (for visual configurations), along with enumerations like tfType.
CommonUtils: Provides utility functions for common tasks like mapping user string inputs (e.g., "Dashed" for line style) to their corresponding Pine Script™ constants (e.g., line.style_dashed) and formatting timeframe strings for display.
FvgCalculations: Contains the core logic for FVG detection (both LTF and MTF/HTF via requestMultiTFBarData), FVG classification (Large FVGs based on ATR), and checking FVG interactions with price (mitigation, partial fill).
FvgObject: Implements an object-oriented approach by attaching methods to the fvgObject UDT. These methods manage the entire visual lifecycle of an FVG on the chart, including drawing, updating based on state changes (e.g., mitigation), and deleting drawing objects. It's responsible for applying the visual configurations defined in drawSettings.
FvgPanel: Manages the creation and dynamic updates of the on-chart information panel, which displays key FVG levels.
The main indicator script acts as the orchestrator, initializing these libraries, managing user inputs, processing data flow between libraries, and handling the main event loop (bar updates) for FVG state management and alerts.
Core Data Flow and FVG Lifecycle Management
The general data flow and FVG lifecycle can be summarized as follows:
Input Processing: User inputs from the "Settings" dialog are read by the main indicator script. Visual style inputs (colors, line styles, etc.) are consolidated into a types.drawSettings object (defined in FvgTypes). Other inputs (timeframes, filter settings, alert toggles) control the behavior of different modules. CommonUtils assists in mapping some string inputs to Pine constants.
FVG Detection:
For the current chart timeframe (LTF), FvgCalculations.detectFvg() identifies potential FVGs based on bar patterns.
For MTF/HTF, the main indicator script calls FvgCalculations.requestMultiTFBarData() to fetch necessary bar data from higher timeframes, then FvgCalculations.detectMultiTFFvg() identifies FVGs.
Newly detected FVGs are instantiated as types.fvgObject and stored in arrays within the main script. These objects also undergo classification (e.g., Large FVG) by FvgCalculations.
State Update & Interaction: On each bar, the main indicator script iterates through active FVG objects to manage their state based on price interaction:
Initially, the main script calls FvgCalculations.fvgInteractionCheck() to efficiently determine if the current bar's price might be interacting with a given FVG.
If a potential interaction is flagged, the main script then invokes methods directly on the fvgObject instance (e.g., updateMitigation(), updatePartialFill(), checkMidlineTouch(), which are part of FvgObject).
These fvgObject methods are responsible for the detailed condition checking and the actual modification of the FVG's state. For instance, the updateMitigation() and updatePartialFill() methods internally utilize specific helper functions from FvgCalculations (like checkMitigation() and checkPartialMitigation()) to confirm the precise nature of the interaction before updating the fvgObject’s state fields (such as isMitigated, currentTop, currentBottom, or isMidlineTouched).
Visual Rendering:
The FvgObject.updateDrawings() method is called for each fvgObject. This method is central to drawing management; it creates, updates, or deletes chart drawings (boxes, lines, labels) based on the FVG's current state, its prev_* (previous bar state) fields for optimization, and the visual settings passed via the drawSettings object.
Information Panel Update: The main indicator script determines the nearest FVG levels, populates a panelData object (defined in FvgPanelLib), and calls FvgPanel.updatePanel() to refresh the on-chart display.
Alert Generation: Based on the updated FVG states and user-enabled alert settings, the main indicator script constructs and triggers alerts using Pine Script's alert() function."
Key Design Considerations
UDT-Centric Design: The fvgObject UDT is pivotal, acting as a stateful container for all information related to a single FVG. Most operations revolve around creating, updating, or querying these objects.
State Management: To optimize drawing updates and manage FVG lifecycles, fvgObject instances store their previous bar's state (e.g., prevIsVisible, prevCurrentTop). The FvgObject.updateDrawings() method uses this to determine if a redraw is necessary, minimizing redundant drawing calls.
Settings Object: A drawSettings object is populated once (or when inputs change) and passed to drawing functions. This avoids repeatedly reading numerous input() values on every bar or within loops, improving performance.
Dynamic Arrays for FVG Storage: Arrays are used to store collections of fvgObject instances, allowing for dynamic management (adding new FVGs, iterating for updates).
Göstergeler ve stratejiler
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").
Multi-Indicator Trend-Following Strategy v6Multi-Indicator Trend-Following Strategy v6
This strategy uses a combination of technical indicators to identify potential trend-following trade entries and exits. It is intended for educational and research purposes.
How it works:
Moving Averages (EMA): Entry signals are generated on crossovers between a fast and slow exponential moving average.
RSI Filter: Confirms momentum with a threshold above/below 50 for long/short entries.
Volume Confirmation: Requires volume to exceed a moving average multiplied by a user-defined factor.
ATR-Based Risk Management: Stop loss and take profit levels are calculated using the Average True Range (ATR), allowing for dynamic risk control based on market volatility.
Customizable Inputs:
Fast/Slow MA lengths
RSI length and levels
MACD settings (used in calculation, not directly in signal)
Volume MA and multiplier
ATR period and multipliers for stop loss and take profit
Notes:
This strategy does not guarantee future results.
It is provided for analysis and backtesting only.
Alerts are available for buy/sell conditions.
Feel free to adjust parameters to explore different market conditions and asset classes.
Last Week's APM FX pairs only📖 Description:
This script is designed for precision-focused forex traders who understand the power of volatility measurement. It calculates the Average Price Movement (APM) from the previous week by measuring the full wick-to-wick range (high to low) of each daily candle from Monday to Friday, then averaging them across the five sessions.
🔍 Core Features:
✅ Accurate APM Calculation:
Pulls daily high-low ranges from last week using locked daily timeframe data, ensuring stable and reliable pip range measurements across all chart timeframes.
✅ Auto-Adjusts for Pip Precision:
Detects whether the pair is JPY-based or not, and automatically adjusts the pip multiplier (100 for JPY pairs, 10,000 for all others) to give true pip values.
✅ Visual Display in Clean UI:
The calculated APM is displayed in a non-intrusive, fixed-position table in the top-right corner of the chart — making it ideal for traders who want continuous awareness of recent market behavior without visual clutter.
✅ Timeless on Any Timeframe:
Whether you’re on the 1-minute chart or the daily, the script remains anchored and accurate because it sources raw data from the daily chart internally.
📈 How It Helps Your Trading:
🧠 Volatility Awareness: Know how much a pair typically moves per day based on recent historical behavior — great for range analysis, target setting, or session biasing.
📊 Week-to-Week Comparison: Use it as a benchmark to compare current volatility to last week’s. Great for identifying if the market is expanding, contracting, or stabilizing.
🔗 Perfect for Confluence: APM can serve as a supporting metric when combined with order blocks, liquidity zones, news catalysts, or other volatility-based tools like ATR.
🛠️ Ideal For:
Professional and prop firm traders
Institutional model traders (ICT-style or SMC)
Volatility scalpers and range-based intraday traders
Anyone building a rules-based trading system with data-driven logic
🔐 Clean. Reliable. Focused.
If you value structure, volatility awareness, and pip precision — this tool belongs in your chart workspace.
200 EMA Cross with Optional Second EMA and CooldownThis indicator uses two EMA lengths of your choosing.
1. This indicator is similar to the most recent published indicator.
2. There is also an alert when price crosses the faster EMA. But not the slower EMA.
3. You will receive all alerts as price crosses the main EMA, not the optional EMA.
6. The is also a "Cooldown" period between alerts so we do not see too many alerts at the same time. Set it to your own number of candles. On the 3m chart I have it set on 25.
8. All the alerts have been combined into one alert. The buy and sell alerts.
9. I use this on the 3m chart with a 30m Williams %r and a 3H Williams %r. The 30 minute WPR should be enough.
10. This indicator is not designed to catch the tops or bottoms of a trend. It is designed to catch the continuation moves. This indicator need a trending market. The trend is your friend. Do not just take any signal from the indicator, it is best to sell when the higher timeframes are trending down.
11. Use at your own risk. Do your own due diligence before taking a trade and do not rely entirely on this indicator.
12. I have not tested this indicator for repainting.
13. Have fun with the indicator and leave a message and vote it up if you like it.
[Remora] Previous Day Value This TradingView script plots horizontal lines showing the previous day’s high, low, and midpoint levels on your current chart. These lines help traders identify key support and resistance zones based on the last day’s price range.
🛠️ Features:
Previous Day High Line (🔴 Red):
Shows the highest price from the previous trading day.
Previous Day Low Line (🟢 Green):
Shows the lowest price from the previous trading day.
Previous Day Midpoint Line (🟣 Fuchsia, Dashed):
Shows the average of the previous day’s high and low — a useful reference for intraday bias or fair value.
Customizable Display:
You can turn each of these lines on or off using checkboxes in the settings.
This script will help traders make decisions like:
Watching for price rejection or breakout at these levels.
Identifying areas to take profits or set stops.
Delta Magnet Zone LiteDelta Magnet Zone Lite is exactly what it sounds like. It is areas where price cold potentially act as a magnet zone for price. Delta Magnet Zone Lite is a lightweight yet powerful visual tool that highlights potential liquidity traps and high-probability reversal zones based on volume spikes and wick imbalances. Designed for precision traders, this indicator visually marks key “magnet” zones where price may react, reverse, or consolidate due to prior aggressive buying or selling activity.
🔹 Core Logic:
Volume Spike Detection
Identifies candles with significantly higher volume than the moving average (customizable). These are likely areas of institutional interest or stop-hunt events.
Wick Ratio Analysis
Measures the size of the upper or lower wick relative to the total candle range. When combined with volume spikes, this helps detect:
Bullish Traps: Large lower wicks with strong buying volume
Bearish Traps: Large upper wicks with strong selling volume
Smart Zone Marking
When trap conditions are met, the script draws a semi-transparent colored box (green for bullish, red for bearish) that extends forward in time, highlighting a magnet zone—a price area likely to be retested or respected by future price action.
🛠 Customization Options:
Volume Spike Threshold
Adjust the multiplier for defining what qualifies as "high volume" relative to the average.
Wick Ratio Sensitivity
Fine-tune how extreme the wick size must be to qualify as a trap.
Zone Lifetime (Lookback)
Control how many bars each zone remains active on the chart.
Toggle Visibility
Turn bullish or bearish zones on/off independently for clean charting.
Ideal Use Cases:
Spotting hidden liquidity zones
Identifying exhaustion points in fast markets
Tracking institutional order imbalances
Enhancing confirmation for entry/exit signals
Whether you're trading intraday breakouts or swing-level reversals, Delta Magnet Zone Lite brings clarity to key reaction levels derived from raw price and volume behavior.
ICT Confluence Signals [v1.1]OXO top ticka, i coded this first try idk might work might not, based on ict conflunces and a.I algo that tardes like banks happy tarding view
EMA Trend Filter Alert + CooldownThis indicator uses two EMA lengths of your choosing.
1. There is an alert when price crosses the long EMA which I put in Flags at the top and bottom.
2. There is also an alert when price crosses the second faster EMA.
3. When price is above the slow EMA then only BUY signals will be shown as price crosses the fast EMA.
4. When price is below the fast EMA then only sell signals will be shown as price crosses below the fast EMA.
5. I included colour changing EMAs for both the fast and slow EMA.
6. The is also a "Cooldown" period between alerts so we do not see too many alerts at the same time. Set it to your own number of candles. On the 3m chart I have it set on 25.
7. This indicator is designed to be a trend following indicator. When the market is trending down then price will be under the slow EMA and then only sell signals will appear on the price cross of the fast EMA. During the turning points in the trend we might not see signals on the fast EMA so I added the alert for the cross of the slow EMA.
8. All the alerts have been combined into one alert. The buy and sell alerts and also the cross of the slow EMA.
9. I use this on the 3m chart with a 30m Williams %r and a 3H Williams %r. The 30 minute should be enough.
10. This indicator is not designed to catch the tops or bottoms of a trend. It is designed to catch the continuation moves. This indicator need a trending market. The trend is your friend.
11. Use at your own risk. Do your own due diligence before taking a trade and do not rely entirely on this indicator.
12. I have not tested this indicator for repainting.
13. Have fun with the indicator and leave a message and vote it up if you like it.
5-Day APM for Forex PairsThis script calculates the 5-Day Average Pip Movement (APM) for major Forex pairs.
It displays the average daily range (in pips) over the past 5 trading days using true high-low price movement.
The script is optimized for clarity and minimalism — showing a single floating label on the main chart for pairs like GBPUSD, USDJPY, EURUSD, etc.
Automatically adjusts pip calculation for JPY pairs (×100) and other pairs (×10000).
✅ Great for identifying high-volatility vs low-volatility conditions
✅ Clean design with no clutter
✅ Only works on major FX pairs (whitelisted)
The Ultimate Trend FinderThe Ultimate Trend Finder is an advanced all-in-one trend analysis toolkit built for traders who want deeper insights into price structure, trend strength, and reversal patterns. It combines traditional pivot-based analysis with dynamic trendline projections and candlestick pattern recognition.
🔹 Core Features:
Swing High/Low Detection
Automatically identifies significant swing highs and lows using customizable pivot length.
Trendline Connections
Connects pivots with color-coded trendlines to visualize higher highs/lows or lower highs/lows.
Green lines: Uptrend connections
Maroon lines: Downtrend connections
Extended Trendline Projections
Projects support/resistance zones forward using slope analysis based on:
ATR
Standard Deviation
Linear Regression
Or a Combined Method with custom weightings
Candlestick Pattern Labels
Recognizes key reversal patterns like Hammers, Engulfings, Shooting Stars, and more—displayed directly on pivot points for quick interpretation.
ADX-Based Filtering
Optionally filters extended trendlines by trend strength using Average Directional Index (ADX). Breakouts through these lines dynamically change their color and style, signaling potential momentum shifts.
🛠 Customization:
Choose pivot sensitivity
Customize colors, trendline width, and visibility
Enable/disable pattern detection, backpainting, and filtering logic
This tool is ideal for traders seeking an edge in both trending and ranging markets. Whether you're identifying potential breakout zones, confirming trend direction, or spotting early reversals, The Ultimate Trend Finder delivers powerful visual clarity and adaptability.
Bull & Bear Power Separados📄 English Description for TradingView
Bull & Bear Power – Elder Style
This indicator displays the strength of buyers (Bull Power) and sellers (Bear Power) separately, based on Alexander Elder’s original concept.
It uses a 13-period Exponential Moving Average (EMA) as the baseline, calculating:
Bull Power = High – EMA
Bear Power = Low – EMA
✔️ Bull Power (green) shows buying pressure.
✔️ Bear Power (red) shows selling pressure.
Great for analyzing true market momentum and spotting early signs of potential trend reversals.
Can be used as confirmation together with moving averages (e.g., MMA30 and MMA50) or price action signals.
✅ On 1H gold charts (XAUUSD), it has shown solid behavior in filtering entries during clear trends.
Developed and shared for educational purposes by El Bit Criollo.
12/25 EMA Trend ColorPlots 12 EMA (close) and 25 EMA (close)
• Colors the EMAs green if the trend is up (12 EMA above 25 EMA), and red if the trend is down (12 EMA below 25 EMA)
MVRV Ratio [Alpha Extract]The MVRV Ratio Indicator provides valuable insights into Bitcoin market cycles by tracking the relationship between market value and realized value. This powerful on-chain metric helps traders identify potential market tops and bottoms, offering clear buy and sell signals based on historical patterns of Bitcoin valuation.
🔶 CALCULATION The indicator processes MVRV ratio data through several analytical methods:
Raw MVRV Data: Collects MVRV data directly from INTOTHEBLOCK for Bitcoin
Optional Smoothing: Applies simple moving average (SMA) to reduce noise
Status Classification: Categorizes market conditions into four distinct states
Signal Generation: Produces trading signals based on MVRV thresholds
Price Estimation: Calculates estimated realized price (Current price / MVRV ratio)
Historical Context: Compares current values to historical extremes
Formula:
MVRV Ratio = Market Value / Realized Value
Smoothed MVRV = SMA(MVRV Ratio, Smoothing Length)
Estimated Realized Price = Current Price / MVRV Ratio
Distance to Top = ((3.5 / MVRV Ratio) - 1) * 100
Distance to Bottom = ((MVRV Ratio / 0.8) - 1) * 100
🔶 DETAILS Visual Features:
MVRV Plot: Color-coded line showing current MVRV value (red for overvalued, orange for moderately overvalued, blue for fair value, teal for undervalued)
Reference Levels: Horizontal lines indicating key MVRV thresholds (3.5, 2.5, 1.0, 0.8)
Zone Highlighting: Background color changes to highlight extreme market conditions (red for potentially overvalued, blue for potentially undervalued)
Information Table: Comprehensive dashboard showing current MVRV value, market status, trading signal, price information, and historical context
Interpretation:
MVRV ≥ 3.5: Potential market top, strong sell signal
MVRV ≥ 2.5: Overvalued market, consider selling
MVRV 1.5-2.5: Neutral market conditions
MVRV 1.0-1.5: Fair value, consider buying
MVRV < 1.0: Potential market bottom, strong buy signal
🔶 EXAMPLES
Market Top Identification: When MVRV ratio exceeds 3.5, the indicator signals potential market tops, highlighting periods where Bitcoin may be significantly overvalued.
Example: During bull market peaks, MVRV exceeding 3.5 has historically preceded major corrections, helping traders time their exits.
Bottom Detection: MVRV values below 1.0, especially approaching 0.8, have historically marked excellent buying opportunities.
Example: During bear market bottoms, MVRV falling below 1.0 has identified the most profitable entry points for long-term Bitcoin accumulation.
Tracking Market Cycles: The indicator provides a clear visualization of Bitcoin's market cycles from undervalued to overvalued states.
Example: Following the progression of MVRV from below 1.0 through fair value and eventually to overvalued territory helps traders position themselves appropriately throughout Bitcoin's market cycle.
Realized Price Support: The estimated realized price often acts as a significant
support/resistance level during market transitions.
Example: During corrections, price often finds support near the realized price level calculated by the indicator, providing potential entry points.
🔶 SETTINGS
Customization Options:
Smoothing: Toggle smoothing option and adjust smoothing length (1-50)
Table Display: Show/hide the information table
Table Position: Choose between top right, top left, bottom right, or bottom left positions
Visual Elements: All plots, lines, and background highlights can be customized for color and style
The MVRV Ratio Indicator provides traders with a powerful on-chain metric to identify potential market tops and bottoms in Bitcoin. By tracking the relationship between market value and realized value, this indicator helps identify periods of overvaluation and undervaluation, offering clear buy and sell signals based on historical patterns. The comprehensive information table delivers valuable context about current market conditions, helping traders make more informed decisions about market positioning throughout Bitcoin's cyclical patterns.
Long Explosive V1The “Long Explosive V1” strategy calculates the percentage change in price from the last closing price of the candlestick, so that if it increases by a certain percentage it goes long, but if it decreases by another percentage it sends an exit order, so that the percentage limits above and below the current price function as inherent stop loss and take profit, with the benefit of taking advantage of the volatility of the bull market.
Entries and exits are always at the market and based on percentage changes in the price. Of course, the default configuration of the strategy considers a position with a 5% risk control, modest initial capital and standard commissions, which helps to obtain realistic results and protect the user from unexpectedly controlled potential losses.
It is again emphasized that it is always advisable to adjust the parameters of the strategy well, so that the risk-reward is well controlled.
Super Oscilador by RouroSuper Oscillator by Rouro
A high-precision composite momentum indicator that brings together five classic oscillators—RSI, Stochastic %K, CCI, Rate of Change (ROC) with ATR-based dynamic thresholds, and Williams %R—into a single, unified tool:
Normalized & Smoothed
• Each oscillator is scored (+1 overbought, –1 oversold, 0 neutral), averaged into a –1…+1 range and smoothed with an EMA for a clean, comparable line.
Intuitive Color Coding
• Oscillator line turns red in overbought territory, green in oversold, and blue in neutral zones.
Traffic-Light State Table
• A compact on-chart table shows each indicator’s real-time status (green/red/gray), so you can verify which signals are aligned.
Non-Repainting Buy/Sell Signals
• Arrows appear on confirmed exits from overbought/oversold levels (using barstate.isconfirmed), and can be hooked to TradingView alerts via built-in alertcondition.
Fully Customizable
• Choose manual ROC thresholds or let ATR dynamically adjust sensitivity. You get full control over periods, levels and smoothing to fit any asset or timeframe.
This all-in-one oscillator helps you spot confluence across multiple momentum tools at a glance, with zero repaint. Great for entries, exits and automated alerting.
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 类型名称