在腳本中搜尋"mtf"
MTF MAA multi timeframe version of the SMA.
You can select one of the proposed timeframes in the input box or you can modify the code at line 5 :
>>>
>>> tf = input("D", title = "TimeFrame", type = resolution)
>>>
Change the D by your desired timeframe => 1, 7, 555 (minutes up to 1440) => D, 2D... => W, 2W... => M, 2M....
MTF EMA Combo with Background ColorDaily/Weekly EMA combo for longer term trend direction, with combo background color for varying trend direction.
MTF Polarity Grid [DW]This is an experimental study designed to track directional polarities across multiple timeframes and express them as a simple two color grid.
The polarity in this calculation is determined by divergence between a fast and slow McGinley Dynamic.
Your current resolution's polarity is the top row, the rows below are are for higher timeframes of your choice.
MTF EMAExponential Moving Average indicator that can be configured to display different timeframe EMA's.
Timeframe is set in minutes. Max timeframe currently is the daily (1440 minutes). Any value higher than 1440 will result in no plot.
Examples:
Daily 50 EMA plotted on 4H chart
4H 50 EMA and Daily 50 EMA plotted on 1H chart
Can also work in reverse if needed.
Example, Daily 50 EMA plotted on Weekly Chart
MTF CCI_8_34_5m_30minThis indicator is used in NimblrTA for plotting the following:
CCI-8 on 5 minutes
CCI-34 on 5 minutes
CCI-34 on 30 minutes interval on 5 minutes
MTF Previous Open/Close/RangeThis indicator will simply plot on your chart the Daily/Weekly/Monthly previous candle levels.
The "Auto" mode will allow automatic adjustment of timeframe displayed according to your chart.
Otherwise you can select manually.
Indicator plots the open/close and colors the high-low range area in the background.
Hope this simple indicator will help you !
You can check my indicators via my TradingView's Profile : @PRO_Indicators
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).
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-Fibonacci Trend Average[FibonacciFlux]Multi-Fibonacci Trend Average (MFTA): An Institutional-Grade Trend Confluence Indicator for Discerning Market Participants
My original indicator/Strategy:
Engineered for the sophisticated demands of institutional and advanced traders, the Multi-Fibonacci Trend Average (MFTA) indicator represents a paradigm shift in technical analysis. This meticulously crafted tool is designed to furnish high-definition trend signals within the complexities of modern financial markets. Anchored in the rigorous principles of Fibonacci ratios and augmented by advanced averaging methodologies, MFTA delivers a granular perspective on trend dynamics. Its integration of Multi-Timeframe (MTF) filters provides unparalleled signal robustness, empowering strategic decision-making with a heightened degree of confidence.
MFTA indicator on BTCUSDT 15min chart with 1min RSI and MACD filters enabled. Note the refined signal generation with reduced noise.
MFTA indicator on BTCUSDT 15min chart without MTF filters. While capturing more potential trading opportunities, it also generates a higher frequency of signals, including potential false positives.
Core Innovation: Proprietary Fibonacci-Enhanced Supertrend Averaging Engine
The MFTA indicator’s core innovation lies in its proprietary implementation of Supertrend analysis, strategically fortified by Fibonacci ratios to construct a truly dynamic volatility envelope. Departing from conventional Supertrend methodologies, MFTA autonomously computes not one, but three distinct Supertrend lines. Each of these lines is uniquely parameterized by a specific Fibonacci factor: 0.618 (Weak), 1.618 (Medium/Golden Ratio), and 2.618 (Strong/Extended Fibonacci).
// Fibonacci-based factors for multiple Supertrend calculations
factor1 = input.float(0.618, 'Factor 1 (Weak/Fibonacci)', minval=0.01, step=0.01, tooltip='Factor 1 (Weak/Fibonacci)', group="Fibonacci Supertrend")
factor2 = input.float(1.618, 'Factor 2 (Medium/Golden Ratio)', minval=0.01, step=0.01, tooltip='Factor 2 (Medium/Golden Ratio)', group="Fibonacci Supertrend")
factor3 = input.float(2.618, 'Factor 3 (Strong/Extended Fib)', minval=0.01, step=0.01, tooltip='Factor 3 (Strong/Extended Fib)', group="Fibonacci Supertrend")
This multi-faceted architecture adeptly captures a spectrum of market volatility sensitivities, ensuring a comprehensive assessment of prevailing conditions. Subsequently, the indicator algorithmically synthesizes these disparate Supertrend lines through arithmetic averaging. To achieve optimal signal fidelity and mitigate inherent market noise, this composite average is further refined utilizing an Exponential Moving Average (EMA).
// Calculate average of the three supertends and a smoothed version
superlength = input.int(21, 'Smoothing Length', tooltip='Smoothing Length for Average Supertrend', group="Fibonacci Supertrend")
average_trend = (supertrend1 + supertrend2 + supertrend3) / 3
smoothed_trend = ta.ema(average_trend, superlength)
The resultant ‘Smoothed Trend’ line emerges as a remarkably responsive yet stable trend demarcation, offering demonstrably superior clarity and precision compared to singular Supertrend implementations, particularly within the turbulent dynamics of high-volatility markets.
Elevated Signal Confluence: Integrated Multi-Timeframe (MTF) Validation Suite
MFTA transcends the limitations of conventional trend indicators by incorporating an advanced suite of three independent MTF filters: RSI, MACD, and Volume. These filters function as sophisticated validation protocols, rigorously ensuring that only signals exhibiting a confluence of high-probability factors are brought to the forefront.
1. Granular Lower Timeframe RSI Momentum Filter
The Relative Strength Index (RSI) filter, computed from a user-defined lower timeframe, furnishes critical momentum-based signal validation. By meticulously monitoring RSI dynamics on an accelerated timeframe, traders gain the capacity to evaluate underlying momentum strength with precision, prior to committing to signal execution on the primary chart timeframe.
// --- Lower Timeframe RSI Filter ---
ltf_rsi_filter_enable = input.bool(false, title="Enable RSI Filter", group="MTF Filters", tooltip="Use RSI from lower timeframe as a filter")
ltf_rsi_timeframe = input.timeframe("1", title="RSI Timeframe", group="MTF Filters", tooltip="Timeframe for RSI calculation")
ltf_rsi_length = input.int(14, title="RSI Length", minval=1, group="MTF Filters", tooltip="Length for RSI calculation")
ltf_rsi_threshold = input.int(30, title="RSI Threshold", minval=0, maxval=100, group="MTF Filters", tooltip="RSI value threshold for filtering signals")
2. Convergent Lower Timeframe MACD Trend-Momentum Filter
The Moving Average Convergence Divergence (MACD) filter, also calculated on a lower timeframe basis, introduces a critical layer of trend-momentum convergence confirmation. The bullish signal configuration rigorously mandates that the MACD line be definitively positioned above the Signal line on the designated lower timeframe. This stringent condition ensures a robust indication of converging momentum that aligns synergistically with the prevailing trend identified on the primary timeframe.
// --- Lower Timeframe MACD Filter ---
ltf_macd_filter_enable = input.bool(false, title="Enable MACD Filter", group="MTF Filters", tooltip="Use MACD from lower timeframe as a filter")
ltf_macd_timeframe = input.timeframe("1", title="MACD Timeframe", group="MTF Filters", tooltip="Timeframe for MACD calculation")
ltf_macd_fast_length = input.int(12, title="MACD Fast Length", minval=1, group="MTF Filters", tooltip="Fast EMA length for MACD")
ltf_macd_slow_length = input.int(26, title="MACD Slow Length", minval=1, group="MTF Filters", tooltip="Slow EMA length for MACD")
ltf_macd_signal_length = input.int(9, title="MACD Signal Length", minval=1, group="MTF Filters", tooltip="Signal SMA length for MACD")
3. Definitive Volume Confirmation Filter
The Volume Filter functions as an indispensable arbiter of trade conviction. By establishing a dynamic volume threshold, defined as a percentage relative to the average volume over a user-specified lookback period, traders can effectively ensure that all generated signals are rigorously validated by demonstrably increased trading activity. This pivotal validation step signifies robust market participation, substantially diminishing the potential for spurious or false breakout signals.
// --- Volume Filter ---
volume_filter_enable = input.bool(false, title="Enable Volume Filter", group="MTF Filters", tooltip="Use volume level as a filter")
volume_threshold_percent = input.int(title="Volume Threshold (%)", defval=150, minval=100, group="MTF Filters", tooltip="Minimum volume percentage compared to average volume to allow signal (100% = average)")
These meticulously engineered filters operate in synergistic confluence, requiring all enabled filters to definitively satisfy their pre-defined conditions before a Buy or Sell signal is generated. This stringent multi-layered validation process drastically minimizes the incidence of false positive signals, thereby significantly enhancing entry precision and overall signal reliability.
Intuitive Visual Architecture & Actionable Intelligence
MFTA provides a demonstrably intuitive and visually rich charting environment, meticulously delineating trend direction and momentum through precisely color-coded plots:
Average Supertrend: Thin line, green/red for uptrend/downtrend, immediate directional bias.
Smoothed Supertrend: Bold line, teal/purple for uptrend/downtrend, cleaner, institutionally robust trend.
Dynamic Trend Fill: Green/red fill between Supertrends quantifies trend strength and momentum.
Adaptive Background Coloring: Light green/red background mirrors Smoothed Supertrend direction, holistic trend perspective.
Precision Buy/Sell Signals: ‘BUY’/‘SELL’ labels appear on chart when trend touch and MTF filter confluence are satisfied, facilitating high-conviction trade action.
MFTA indicator applied to BTCUSDT 4-hour chart, showcasing its effectiveness on higher timeframes. The Smoothed Length parameter is increased to 200 for enhanced smoothness on this timeframe, coupled with 1min RSI and Volume filters for signal refinement. This illustrates the indicator's adaptability across different timeframes and market conditions.
Strategic Applications for Institutional Mandates
MFTA’s sophisticated design provides distinct advantages for advanced trading operations and institutional investment mandates. Key strategic applications include:
High-Probability Trend Identification: Fibonacci-averaged Supertrend with MTF filters robustly identifies high-probability trend continuations and reversals, enhancing alpha generation.
Precision Entry/Exit Signals: Volume and momentum-filtered signals enable institutional-grade precision for optimized risk-adjusted returns.
Algorithmic Trading Integration: Clear signal logic facilitates seamless integration into automated trading systems for scalable strategy deployment.
Multi-Asset/Timeframe Versatility: Adaptable parameters ensure applicability across diverse asset classes and timeframes, catering to varied trading mandates.
Enhanced Risk Management: Superior signal fidelity from MTF filters inherently reduces false signals, supporting robust risk management protocols.
Granular Customization and Parameterized Control
MFTA offers unparalleled customization, empowering users to fine-tune parameters for precise alignment with specific trading styles and market conditions. Key adjustable parameters include:
Fibonacci Factors: Adjust Supertrend sensitivity to volatility regimes.
ATR Length: Control volatility responsiveness in Supertrend calculations.
Smoothing Length: Refine Smoothed Trend line responsiveness and noise reduction.
MTF Filter Parameters: Independently configure timeframes, lookback periods, and thresholds for RSI, MACD, and Volume filters for optimal signal filtering.
Disclaimer
MFTA is meticulously engineered for high-quality trend signals; however, no indicator guarantees profit. Market conditions are unpredictable, and trading involves substantial risk. Rigorous backtesting and forward testing across diverse datasets, alongside a comprehensive understanding of the indicator's logic, are essential before live deployment. Past performance is not indicative of future results. MFTA is for informational and analytical purposes only and is not financial or investment advice.
Trend Gazer v2English Follows;
---
# Trend Gazer v2 - マルチタイムフレーム トレーディング インジケータ
## 📊 概要
**Trend Gazer v2** は、**ボリューメトリックウェイテッドクラウド(VWC)**、**リバースRSIシグナル**、**ICTドンチアンスマートマネーストラクチャー**、**マルチタイムフレームボリンジャーバンド**、**EMA分析**を組み合わせた高度なトレーディングインジケータです。
**7種類のシグナルタイプ**と**4つの設定可能なフィルター**を搭載し、特にEMA塗りつぶし色遷移期間中のフィルタリング機能(**フィルター4**)により、トレンド変化時の偽シグナルを削減します。
---
## ✨ 主要機能
### v2の新機能: フィルター4 - EMA塗りつぶし遷移期間フィルター(デフォルト有効)
**フィルター4**は、EMA塗りつぶし色の遷移期間中に方向性バイアスを作成し、偽シグナルを削減します:
**動作ロジック:**
1. **すべて青 → 遷移開始(一部が赤に)→ BUYのみ表示 → すべて赤 OR 青に戻る(期間終了)**
- 遷移期間中はSELLシグナルをすべてブロック
2. **すべて赤 → 遷移開始(一部が青に)→ SELLのみ表示 → すべて青 OR 赤に戻る(期間終了)**
- 遷移期間中はBUYシグナルをすべてブロック
**終了条件:**
- 遷移が完了(すべて目標色になる)
- 元の色に戻る(遷移失敗)
**⭐ 特徴:** 他のフィルター(1,2,3)はシグナル1-5のみに適用されますが、**フィルター4はすべてのシグナル(S1-7)に適用**されます。これにより、トレンド変化時の一貫したフィルタリングを実現し、勝率向上に貢献します。
---
### 1. **複数シグナルタイプ(7種類)**
**シグナル1:** マーケットストラクチャーが強気(Bullish Structure) かつ リバースRSIが強気にシフト
**シグナル2:** (マーケットストラクチャーが強気 または リバースRSIが強気) かつ VWC UPシグナル検知
**シグナル3:** リバースRSIが強気 かつ マーケットストラクチャーが弱気から強気に変化(ストラクチャースイッチ)
**シグナル4:** マーケットストラクチャーが強気 かつ VWCシグナルがUP状態(初回のみ)
**シグナル5:** 15分足下部ボリンジャーバンドを上抜けた後、リバースRSI強気シグナル検知
**シグナル6:** 15分足下部BB または EMA50を上抜けた後、初回のリバースRSI強気シグナル(フィルター1,2,3をバイパス、フィルター4のみ適用)
**シグナル7:** マーケットストラクチャーが強気 かつ EMA20またはEMA50から上に反発後、最初のBUY検知(フィルター1,2,3をバイパス、フィルター4のみ適用)
*(SELLシグナルは逆ロジックに従う)*
---
### 2. **高度なフィルタリングシステム**
**フィルター1: RSI方向フィルター(デフォルト:ON) - シグナル1-5のみ**
- リバースRSIが強気 または マーケットストラクチャーが強気の時のみBUYを表示
- リバースRSIが弱気 または マーケットストラクチャーが弱気の時のみSELLを表示
- 強い方向性のある動きでの逆張りシグナルを防止
**フィルター2: EMA配列フィルター(デフォルト:ON) - シグナル1-5のみ**
- SELLシグナルはEMA配列が確認された時のみ表示:
- `ema20 > ema50 > ema100 > ema200`(強い下降トレンド)、または
- `ema20 < ema50 < ema100 < ema200`(強い上昇トレンド)
- レンジ相場での偽シグナルを削減
**フィルター3: ボリンジャーバンド方向フィルター(デフォルト:ON) - シグナル1-5のみ**
- 15分足上部BB かつ 60分足上部BBを下抜け後 → 15分足下部BBにタッチするまでSELLのみ表示
- 15分足下部BB かつ 60分足下部BBを上抜け後 → 15分足上部BBにタッチするまでBUYのみ表示
- 高確率エントリーのための方向バイアスゾーンを作成
**⭐ フィルター4: EMA塗りつぶし遷移期間フィルター(デフォルト:ON) - 全シグナル1-7に適用**
- すべてのEMA塗りつぶしが青から赤に遷移中 → BUYのみ表示(SELLブロック)
- すべてのEMA塗りつぶしが赤から青に遷移中 → SELLのみ表示(BUYブロック)
- 遷移が完了または元の色に戻ると期間終了
- トレンド変化時の偽シグナルを削減し、勝率向上に貢献
**注意:** シグナル6, 7はフィルター1,2,3をバイパスしますが、フィルター4は適用されます。
---
### 3. **マルチタイムフレームボリンジャーバンド**
- **15分足ボリンジャーバンド**(黒い点線): 短期ボラティリティゾーン
- **60分足ボリンジャーバンド**(黒/カスタマイズ可能): 長期サポート/レジスタンス
これらのバンドは以下を識別:
- **買われ過ぎ/売られ過ぎの状態**
- **ブレイクアウト確認**(シグナル5,6)
- **平均回帰の機会**
---
### 4. **7本の指数移動平均(EMA)**
- **EMA 7, 20, 50, 100, 200, 400, 800**
- EMA20-50間とEMA50-200間の動的**EMA塗りつぶし**でトレンドバイアスを色分け:
- **赤色塗りつぶし:** 弱気配列(ema20 > ema50 > ema200)
- **青色塗りつぶし:** 強気配列(ema20 < ema50 < ema200)
- EMAはシグナル7の反発検知のための動的サポート/レジスタンスとして機能
- **フィルター4はEMA塗りつぶし**の遷移を監視して方向性バイアスを作成
---
### 5. **ICTドンチアンスマートマネーストラクチャー**
- ローソク足の枠に色を付けてマーケットストラクチャーを可視化:
- **赤枠(Bullish Structure):** 強気ストラクチャー(買い手が優勢)
- **緑枠(Bearish Structure):** 弱気ストラクチャー(売り手が優勢)
- ドンチアンチャネルとピボットベースのストラクチャーブレイクに基づく
- シグナル1, 3, 4, 7の検知に不可欠
---
### 6. **リバースRSIシグナル**
- RSI計算を反転させてオシレーター値ではなく価格レベルを導出
- **RSIミッドラインのスーパートレンド**がトレンドシフトを判定:
- **強気シフト:** 上昇モメンタムの可能性
- **弱気シフト:** 下降モメンタムの可能性
- 半透明ラベル("Bullish"/"Bearish")として価格の上下に表示
---
### 7. **VWC(ボリューメトリックウェイテッドクラウド)トレンド検知器**
- 市場状況に応じて拡大/縮小する適応型ボラティリティベースバンド
- 価格がバンド内に入ると**UP/DOWNシグナル**を提供
- VWCステータステーブルには以下を表示:
- 現在のトレンド方向(BULLISH/BEARISH)
- EMA配列ステータス
- 最後に表示したシグナル(BUY/SELL)とシグナル以降のバー数
---
## 🎯 トレード戦略
### 推奨アプローチ
**1. トレンドフォロー(シグナル1, 2, 4)**
- 明確なマーケットストラクチャー(強気または弱気ストラクチャー)を待つ
- VWCトレンド + RSI方向 + ストラクチャー配列の合致でエントリー
- EMA塗りつぶしを動的ストップロスゾーンとして使用
**2. 反転トレード(シグナル5, 6, 7, 8)**
- **シグナル5,6**: ボリンジャーバンドブレイクアウトと反転を特定
- **シグナル7**: ストラクチャー確認を伴うEMA反発を探す
- **シグナル8**: **早期トレンド反転** - トレンド変化の最初期でエントリー
- これらのシグナルは特定フィルターをバイパスし早期エントリー機会を提供
**3. シグナル8 - 早期トレンド反転戦略 (v2新機能)**
**最適な使用ケース:**
- **上位時間軸(15分足〜1時間足)**: 主要なトレンド反転の捕捉に最も信頼性が高い
- **スイングトレード**: 数日間のポジションエントリーに最適
- **確認トレード**: 他のシグナルと組み合わせて高信頼度エントリー
**シグナル8のトレード方法:**
- **BUY(青→赤遷移)**:
- すべてのEMA塗りつぶしが青から赤に変化するのを監視
- エントリー: シグナル8 BUYラベルが出現した時
- ストップロス: 直近スイング安値またはEMA200の下
- 利確: 次のレジスタンスを目標、またはEMA50でトレーリングストップ
- **SELL(赤→青遷移)**:
- すべてのEMA塗りつぶしが赤から青に変化するのを監視
- エントリー: シグナル8 SELLラベルが出現した時
- ストップロス: 直近スイング高値またはEMA200の上
- 利確: 次のサポートを目標、またはEMA50でトレーリングストップ
**シグナル8の利点:**
- 他のシグナルより5-10バー早くトレンド反転を捕捉
- 新トレンド開始時の低リスクエントリー
- より高いリワード可能性(トレンド初期でのエントリー)
**シグナル8のリスク:**
- レンジ/不規則相場では偽シグナルを生成する可能性
- 上位時間軸での確認と組み合わせるのがベスト
- 早期エントリーのため、より大きなストップロスの使用を検討
---
### リスク管理
- **EMA20/EMA50**をトレーリングストップロスレベルとして使用
- シグナル8では:**EMA200**を主要トレンドストップロスとして使用
- 反対シグナルまたは主要EMAクロス時に決済
- 上位時間軸のトレンド確認と組み合わせ(60分足以上チャート)
- VWCステータステーブルが矛盾するシグナルを示す時は取引を避ける
### 推奨時間軸
- **シグナル8最適時間軸:** 15分足〜1時間足(早期トレンド反転用)
- **他のシグナル:** 1分足~15分足(スキャルピング/デイトレード)
- **上位時間軸:** 1時間足以上でも機能するがシグナル数は減少
- **補完的使用:** 4時間足/日足チャートで全体トレンド方向を確認
---
## 🔄 MTF OB & FVG Detectorとの統合トレード戦略
**Trend Gazer v2**と**MTF OB & FVG Detector**を組み合わせることで、機関投資家のオーダーフロー(OB)と市場の需給ギャップ(FVG)を活用した高度なトレーディング戦略を実現できます。
### 統合戦略の利点
**1. 最高確率エントリーポイントの特定**
- Trend GazerのBUY/SELLシグナル + OB/FVGゾーン = **最高確率エントリーポイント**
- 複数の時間足(5分、15分、60分)からのOB統合 + Trend Gazerシグナル = **機関投資家とトレンドの合致**
**2. 精密なエントリー価格の決定**
- Trend Gazerでトレンド方向と市場バイアスを確認
- OB/FVGゾーンで正確なエントリー価格を特定
- 不要なリスクを削減し、リワード比率を最大化
**3. 強化されたストップロス管理**
- EMA20/50(Trend Gazer)をトレーリングストップロスとして使用
- OBゾーン(MTF OB & FVG)を追加の防御ラインとして設定
- 多層防御によるリスク管理
---
### 推奨統合戦略
#### 戦略1: 高確率コンフルエンスエントリー 【最推奨】
**セットアップ:**
1. Trend Gazer v2でBUY/SELLシグナルを監視
2. MTF OB & FVG Detectorで統合OB/FVGゾーン(3つ以上の時間足)を特定
3. 両者が同じ価格ゾーンで一致するのを待つ
**エントリー条件(BUY例):**
- ✅ Trend Gazer: BUYシグナル発生(シグナル1-7のいずれか)
- ✅ MTF OB & FVG: ブリッシュOBゾーン(特に統合ゾーン)に価格がタッチ
- ✅ フィルター4(EMA遷移期間): 青→赤遷移中(BUYのみ期間)
- ✅ マーケットストラクチャー: 強気(赤枠)
- ✅ 高ボリューム: OBゾーンのボリュームパーセンテージが75%以上
**エントリー:**
- 価格がOBゾーン内でTrend GazerのBUYシグナルが点灯したバーの終値でエントリー
- または、次バーの始値でエントリー
**ストップロス:**
1. **初期SL**: OBゾーンの下端 - (5-10 pips/ポイント)
2. **代替SL**: EMA50の下(より広いSL、スイングトレード向け)
3. **タイトSL**: 直近安値 - (3-5 pips/ポイント)(スキャルピング向け)
**利確ターゲット:**
1. **T1(50%)**: 次の上位時間足ベアリッシュOB/FVGゾーン
2. **T2(30%)**: 60分足ボリンジャーバンド上限
3. **T3(20%)**: EMA20/50でトレーリング、逆シグナルまで保持
**SELL例は逆ロジック適用**
---
#### 戦略2: 精密反転エントリー【中級者向け】
**最適使用場面:**
- 強いトレンドの終了時
- 重要な統合OB/FVGゾーンでの反転
- 上位時間足のサポート/レジスタンスレベル
**エントリー条件(SELL例):**
1. **上位時間足確認:**
- 60分足でベアリッシュOB統合ゾーンを特定
- 価格が統合ゾーンに到達
2. **Trend Gazerシグナル:**
- **シグナル5**: 15分足上部BBを下抜け + リバースRSI弱気シフト、または
- **シグナル6**: 15分足上部BB/EMA50下抜け後の初回RSI弱気シグナル、または
- **シグナル7**: マーケットストラクチャー弱気 + EMA20/50からの下方反発
3. **OB/FVG確認:**
- 15分足または60分足のベアリッシュOBゾーンで反発確認
- FVGが上方に残っている(価格磁石効果)
**エントリー:**
- Trend Gazerシグナル + OBゾーン反発の両方確認後
- ローソク足パターン確認(ピンバー、エンガルフィング等)推奨
**ストップロス:**
- OBゾーン上端 + 10-15 pips/ポイント
- または60分足上部BBの上
**利確:**
- **T1**: 下位時間足ブリッシュOB/FVGゾーン(未充填FVG優先)
- **T2**: 15分足下部BB
- **T3**: 逆シグナルまたはEMA20/50タッチ
**BUY例は逆ロジック適用**
---
#### 戦略3: トレンドフォロー with OBサポート【初心者向け】
**シンプルなアプローチ:**
**BUY戦略:**
1. **トレンド確認(Trend Gazer):**
- EMA塗りつぶしが赤色(弱気配列)
- VWCステータスがBULLISH
- マーケットストラクチャーが強気(赤枠)
2. **押し目待ち:**
- 価格が下位時間足(5分または15分)のブリッシュOBゾーンまで調整
- Trend Gazerの**シグナル1, 2, または4**が発生
3. **エントリー:**
- OBゾーン内でBUYシグナル点灯時
- ローソク足の実体終値でエントリー
4. **ストップロス:**
- OBゾーン下端 - 10 pips/ポイント
5. **利確:**
- **簡易**: リスクの2倍(1:2 R:R)
- **動的**: 次のベアリッシュOBまたは逆シグナルまで
**SELL戦略は逆ロジック適用**
---
#### 戦略4: FVGフィリング with Trend Gazer確認【スキャルピング】
**短期トレーダー向け:**
**セットアップ:**
- 未充填のFVG(ブリッシュまたはベアリッシュ)を特定
- FVGが現在価格から離れている(最低20-30 pips/ポイント)
**BUY例(ブリッシュFVG下方):**
1. **FVG識別:**
- 下方に未充填のブリッシュFVG(オレンジボックス)
- 高ボリュームFVG優先(75%以上)
2. **Trend Gazer確認:**
- 価格がFVGに近づく
- マーケットストラクチャーが強気に転換
- **シグナル3, 4, または7**がFVGゾーン近辺で発生
3. **エントリー:**
- 価格がFVG内に入り、Trend GazerシグナルでFVGからの反発確認
- ローソク足の実体終値でエントリー
4. **ストップロス:**
- FVG下端 - 5-7 pips/ポイント(タイト)
5. **利確:**
- **T1(70%)**: FVG上端(ギャップ充填)
- **T2(30%)**: 次のレジスタンスまたは逆シグナル
**SELL例(ベアリッシュFVG上方)は逆ロジック適用**
---
### 統合使用のベストプラクティス
**1. チャート設定:**
- **メインチャート時間足**: 5分足または15分足
- **Trend Gazer v2**: すべてのシグナルとフィルター有効
- **MTF OB & FVG Detector**: 5分、15分、60分を有効化、統合機能ON
**2. アラート設定:**
- Trend Gazer: BUY/SELLシグナルアラート有効
- MTF OB & FVG: 反発アラート + 統合ゾーンアラート有効(Min 3 OBs)
- 両方のアラートが同時に鳴る = 最高確率エントリー
**3. 確認チェックリスト(エントリー前):**
- Trend GazerのBUY/SELLシグナル確認
- OB/FVGゾーンが価格に重なっている
- フィルター4が方向を支持(遷移期間中)
- マーケットストラクチャーが一致
- OB/FVGの高ボリューム確認(70%以上推奨)
- 上位時間足のトレンドが矛盾していない
- リスク:リワード比率が最低1:1.5以上
**4. リスク管理ルール:**
- 1トレードあたりの資金リスク: 口座残高の0.5-1%
- 同時ポジション: 最大2-3(相関性の低い銘柄のみ)
- 連続損失後: 3連敗後は休憩、戦略見直し
- 日次損失上限: 口座残高の2-3%
**5. 避けるべき状況:**
- ❌ Trend Gazerシグナルなしで、OB/FVGのみでエントリー
- ❌ 重要経済指標発表の直前/直後(ボラティリティスパイク)
- ❌ 複数フィルターが矛盾している時
- ❌ OB/FVGゾーンが既に複数回テストされている(弱体化)
- ❌ 流動性が低い時間帯(アジア早朝等)
---
### 統合戦略のパフォーマンス向上Tips
**1. 時間足の選択:**
- **スキャルピング**: 1分/3分足OB + 5分足Trend Gazerシグナル
- **デイトレード**: 5分/15分足OB + 15分足Trend Gazerシグナル
- **スイングトレード**: 15分/60分足OB + 60分足Trend Gazerシグナル
**2. 統合ゾーンの優先順位:**
- **最高優先**: 60分足OB統合(3つ以上)+ Trend Gazer Signal 6 or 7
- **高優先**: 15分足OB統合 + フィルター4遷移期間 + Signal 1-5
- **中優先**: 5分足OB + マーケットストラクチャー一致 + Signal 1-4
- **低優先**: 単一時間足OB + 基本シグナル(確認重視)
**3. バックテスト推奨:**
- 過去1-3ヶ月のデータで各戦略をテスト
- 勝率、平均R:R、最大ドローダウンを記録
- 自分のトレードスタイルに最適な組み合わせを発見
**4. 継続的改善:**
- トレード日誌を記録(スクリーンショット含む)
- 週次でパフォーマンスレビュー
- 有効な組み合わせパターンを文書化
- 市場環境の変化に応じて調整
---
### 統合戦略の実例
**実例1: 完璧なコンフルエンスBUY**
```
状況:
- 15分足チャート、EUR/USD
- 価格が60分足ブリッシュOB統合ゾーン(5分+15分+60分)にタッチ
- Trend Gazer Signal 6発生: 15分足下部BB上抜け後、初回RSI強気シグナル
- フィルター4: EMA塗りつぶし青→赤遷移中(BUYのみ期間)
- マーケットストラクチャー: 強気(赤枠)に転換
- OBボリューム: 82%(強い買い圧力)
エントリー: 1.0850(OBゾーン中央)
ストップロス: 1.0835(OBゾーン下端 - 5 pips)
利確T1: 1.0875(次の15分足ベアリッシュOB)- 達成
利確T2: 1.0895(60分足上部BB)- 達成
利確T3: 1.0920(EMA20トレーリング)- 逆シグナル手前で決済
結果: +70 pips、リスク15 pips = 4.67:1 R:R
```
**実例2: FVGフィリング with 反転確認SELL**
```
状況:
- 5分足チャート、GBP/JPY
- 上方に未充填ベアリッシュFVG(アクアボックス、15分足)
- 価格が急騰してFVGに到達
- Trend Gazer Signal 7発生: マーケットストラクチャー弱気 + EMA50からの下方反発
- リバースRSI: 弱気シフト
- FVGボリューム: 78%(強い売り圧力)
エントリー: 191.50(FVG上端での反発確認)
ストップロス: 191.75(FVG上端 + 25 pips)
利確T1: 191.00(FVG下端、ギャップ充填)- 達成
利確T2: 190.70(次のブリッシュOB)- 部分達成
結果: +50 pips(加重平均)、リスク25 pips = 2:1 R:R
```
---
### まとめ: なぜこの統合が強力なのか
**Trend Gazer v2の役割:**
- ✅ トレンド方向の確認(VWC、EMA、ストラクチャー)
- ✅ タイミングシグナル(7種類のエントリー機会)
- ✅ 複数フィルターによる偽シグナル削減
- ✅ 動的ストップロス管理(EMA、BB)
**MTF OB & FVG Detectorの役割:**
- ✅ 機関投資家のオーダーフロー可視化
- ✅ 正確な価格ゾーン特定(精密エントリー)
- ✅ 高確率サポート/レジスタンスレベル
- ✅ ボリューム分析による強度確認
**統合による相乗効果:**
- 🎯 **確率の掛け算**: 各インジケーター単独でも有効だが、両者の一致で確率が大幅向上
- 🎯 **リスク削減**: より精密なストップロス設定で損失を最小化
- 🎯 **リワード最大化**: 最適なエントリー価格で利益幅を拡大
- 🎯 **多様な戦略**: トレンドフォロー、反転、スキャルピング、スイング全てに対応
**推奨開始手順:**
1. デモ口座で戦略1(コンフルエンスエントリー)を2週間テスト
2. トレード日誌を記録し、パターンを学習
3. 小額リアル口座で同じ戦略を実践(最小ロット)
4. 自信がついたら戦略2, 3に拡張
5. 継続的にバックテストと改善を実施
この統合アプローチにより、市場の**需給ゾーン(OB/FVG)**と**トレンドモメンタム(Trend Gazer)**の両方を活用した、プロフェッショナルレベルのトレーディング戦略を実現できます。
---
## ⚙️ 入力パラメータ
### シグナル8設定 (v2新機能)
- **シグナル8を有効化: EMA塗りつぶし色遷移:** シグナル8のオン/オフ切り替え(デフォルト:OFF)
- **EMA傾きルックバック:** EMA傾き計算の期間(デフォルト:5、範囲:2-20)
- 低い値: より敏感、早期シグナル
- 高い値: より安定、偽シグナル減少
### シグナル表示設定
- **BUY/SELLラベルを表示:** メインエントリーシグナルの切り替え
- **RSIトレンドシフトラベルを表示:** Bullish/Bearish RSIシフトの表示
- **ラベルサイズ:** Small、Normal、Large、Huge
- **ラベル位置:** バー上またはATRでオフセット
### フィルター設定
- **RSI方向フィルターを有効化:** RSIトレンドでシグナルをフィルター(デフォルト:ON)
- **EMA配列フィルターを有効化:** SELLシグナルにEMA配列を要求(デフォルト:ON)
- **BB方向フィルターを有効化:** BBブレイクアウト後に方向バイアスゾーンを作成(デフォルト:ON)
### ビジュアル設定
- **ストラクチャーキャンドルを表示:** マーケットストラクチャーでキャンドルの枠に色付け
- **EMAを表示:** 7本の指数移動平均を表示
- **EMA塗りつぶしを表示:** 主要EMA間の色付き塗りつぶしを表示(シグナル8に重要)
- **15分足ボリンジャーバンドを表示:** 短期BBを表示
- **60分足ボリンジャーバンドを表示:** 長期BBを表示
- **VWCステータステーブル:** ステータステーブル表示の切り替え
---
## 🆕 v2の新機能
1. **シグナル8 - EMA塗りつぶし色遷移検知**
- 早期トレンド反転識別
- EMA傾きフラット化分析
- EMA収束パターン認識
- ATRを使用した正規化傾き計算
2. **強化されたツールチップドキュメント**
- すべてのシグナルが入力ツールチップに明確に文書化
- シグナル8の説明を含む
3. **改善されたアラートシステム**
- シグナル8 BUY/SELL用の新しいアラート
- EMA塗りつぶし色遷移専用アラート
4. **より優れた視覚的明瞭性**
- EMA塗りつぶしはシグナル8可視化に重要
- すべての塗りつぶしが色遷移している時が見やすい
---
## ⚠️ 免責事項
本インジケータは**教育および情報提供のみを目的**として提供されています。**金融アドバイスではありません**。
取引には多大な損失リスクが伴い、すべての投資家に適しているわけではありません。過去の実績は将来の結果を保証するものではありません。ユーザーは独自の調査を行い、取引決定を行う前に資格のある金融アドバイザーに相談することを検討してください。
作成者は本インジケータを使用して発生したいかなる損失についても責任を負いません。
---
## 📝 クレジット
- **リバースRSIシグナル:** AlgoAlphaのコンセプトに基づく
- **VWCトレンド検知器:** オリジナル実装
- **ICTドンチアンストラクチャー:** ICTコンセプトとドンチアンチャネルからインスピレーション
- **ボリンジャーバンド:** ジョン・ボリンジャー開発
- **EMA分析:** 標準的なテクニカル分析ツール
- **シグナル8 EMA遷移:** Trend Gazer v2のためのオリジナル実装
---
## 📜 ライセンス
このPine Script™コードは、https://mozilla.org/MPL/2.0/ の**Mozilla Public License 2.0**の条項に従います
---
## 🔔 アラート
インジケータには以下の内蔵アラート条件が含まれます:
- BUYシグナル(全8タイプ)
- SELLシグナル(全8タイプ)
- **新機能: シグナル8 EMA塗りつぶし色遷移アラート**
- リバースRSI強気/弱気シフト
- VWC UP/DOWNシグナル
TradingViewのアラート作成メニューからアラートを設定してください。
---
**バージョン:** 2.0
**プラットフォーム:** TradingView Pine Script™
**タイプ:** インジケータ(オーバーレイ)
---
## 🚀 最良の結果を得るためのヒント
1. **シグナルを組み合わせる:** シグナル8を他のシグナルと組み合わせて合致を確認
2. **シグナル8は上位時間軸で:** 15分足〜1時間足で最も信頼性が高い
3. **EMA塗りつぶしを使用:** シグナル8の遷移を見るためEMA塗りつぶしを表示
4. **マーケットストラクチャーを尊重:** 大きな時間軸のトレンドに逆らわない
5. **シグナル8をバックテスト:** 過去データでテストして動作を理解
6. **EMA傾きルックバックを調整:** トレードスタイルと時間軸に合わせて微調整
7. **テーブルを監視:** VWCステータステーブルで迅速なトレンド評価
8. **シグナル8 + ストラクチャー:** シグナル8がストラクチャー変化と一致する時に最良の結果
---
**ハッピートレーディング! 📊💹**
**v2アップグレード: シグナル8でトレンド反転をより早く捕捉!**
ーーー
# Trend Gazer v2 - Multi-Timeframe Trading Indicator
## 📊 Overview
**Trend Gazer v2** is an advanced trading indicator that combines **Volumetric Weighted Cloud (VWC)**, **Reverse RSI Signals**, **ICT Donchian Smart Money Structure**, **Multi-Timeframe Bollinger Bands**, and **EMA Analysis** for comprehensive market analysis.
**7 signal types** with **4 customizable filters**, featuring the **Filter 4 (EMA Fill Transition Period Filter)** which reduces false signals during trend changes by default.
---
## ✨ Key Features
### NEW in v2: Filter 4 - EMA Fill Transition Period Filter (Default ON)
**Filter 4** creates directional bias during EMA fill color transition periods to reduce false signals:
**Operation Logic:**
1. **ALL Blue → Transition Starts (some turn red) → BUY ONLY → ALL Red OR Back to Blue (period ends)**
- Blocks all SELL signals during transition period
2. **ALL Red → Transition Starts (some turn blue) → SELL ONLY → ALL Blue OR Back to Red (period ends)**
- Blocks all BUY signals during transition period
**Termination Conditions:**
- Transition completes (all fills become target color)
- Reverts to original color (transition fails)
**⭐ Key Feature:** While other filters (1,2,3) only apply to Signals 1-5, **Filter 4 applies to ALL signals (S1-7)**. This provides consistent filtering during trend changes and improves win rate.
---
### 1. **Multiple Signal Types (7 Types)**
**Signal 1:** Market Structure is Bullish (Bullish Structure) AND Reverse RSI shifts to Bullish
**Signal 2:** (Market Structure is Bullish OR Reverse RSI is Bullish) AND VWC UP signal detected
**Signal 3:** Reverse RSI is Bullish AND Market Structure changes from Bearish to Bullish (Structure Switch)
**Signal 4:** Market Structure is Bullish AND VWC Signal is in UP state (first time only)
**Signal 5:** Reverse RSI Bullish signal detected AFTER breaking above 15min Lower Bollinger Band
**Signal 6:** First Reverse RSI Bullish signal AFTER breaking above 15min Lower BB OR EMA50 (Bypasses Filter 1,2,3, Filter 4 still applies)
**Signal 7:** Market Structure is Bullish AND price bounces from EMA20 or EMA50, then first BUY detected (Bypasses Filter 1,2,3, Filter 4 still applies)
*(SELL signals follow inverse logic)*
---
### 2. **Advanced Filtering System**
**Filter 1: RSI Direction Filter (Default: ON) - Signals 1-5 Only**
- Only displays BUY when Reverse RSI is Bullish OR Market Structure is Bullish
- Only displays SELL when Reverse RSI is Bearish OR Market Structure is Bearish
- Prevents counter-trend signals in strong directional moves
**Filter 2: EMA Order Filter (Default: ON) - Signals 1-5 Only**
- SELL signals only appear when EMA alignment is confirmed:
- `ema20 > ema50 > ema100 > ema200` (Strong downtrend), OR
- `ema20 < ema50 < ema100 < ema200` (Strong uptrend)
- Reduces false signals during choppy/ranging markets
**Filter 3: Bollinger Band Direction Filter (Default: ON) - Signals 1-5 Only**
- After breaking below 15min Upper BB AND 60min Upper BB → Only SELL signals until touching 15min Lower BB
- After breaking above 15min Lower BB AND 60min Lower BB → Only BUY signals until touching 15min Upper BB
- Creates directional bias zones for high-probability entries
**⭐ Filter 4: EMA Fill Transition Period Filter (Default: ON) - ALL Signals 1-7**
- During ALL EMA fills transitioning blue→red → Show BUY only (block SELL)
- During ALL EMA fills transitioning red→blue → Show SELL only (block BUY)
- Period ends when transition completes OR reverts to original color
- Reduces false signals during trend changes and improves win rate
**Note:** Signals 6, 7 bypass Filters 1,2,3 but Filter 4 still applies.
---
### 3. **Multi-Timeframe Bollinger Bands**
- **15-Minute Bollinger Bands** (Black dotted lines): Short-term volatility zones
- **60-Minute Bollinger Bands** (Black/customizable): Longer-term support/resistance
These bands identify:
- **Overbought/Oversold Conditions**
- **Breakout Confirmations** (Signal 5 & 6)
- **Mean Reversion Opportunities**
---
### 4. **7 Exponential Moving Averages (EMA)**
- **EMA 7, 20, 50, 100, 200, 400, 800**
- Dynamic **EMA Fills** between EMA20-50 and EMA50-200 with color-coded trend bias:
- **Red Fill:** Bearish alignment (ema20 > ema50 > ema200)
- **Blue Fill:** Bullish alignment (ema20 < ema50 < ema200)
- EMAs act as dynamic support/resistance for Signal 7 bounce detection
- **Filter 4 monitors EMA fills** to create directional bias during transitions
---
### 5. **ICT Donchian Smart Money Structure**
- Colors candle borders to visualize market structure:
- **RED Border (Bullish Structure):** Bullish structure (buyers in control)
- **GREEN Border (Bearish Structure):** Bearish structure (sellers in control)
- Based on Donchian channels and pivot-based structure breaks
- Critical for Signal 1, 3, 4, and 7 detection
---
### 6. **Reverse RSI Signals**
- Inverts RSI calculations to derive price levels rather than oscillator values
- **Supertrend on RSI Midline** determines trend shifts:
- **Bullish Shift:** Potential upward momentum
- **Bearish Shift:** Potential downward momentum
- Displayed as semi-transparent labels ("Bullish"/"Bearish") above/below price
---
### 7. **VWC (Volumetric Weighted Cloud) Trend Detector**
- Adaptive volatility-based bands that expand/contract with market conditions
- Provides **UP/DOWN signals** when price enters the bands
- VWC Status Table displays:
- Current trend direction (BULLISH/BEARISH)
- EMA alignment status
- Last displayed signal (BUY/SELL) and bars since signal
---
## 🎯 Trading Strategy
### Recommended Approach
**1. Trend Following (Signals 1, 2, 4)**
- Wait for clear market structure (Bullish or Bearish Structure)
- Enter on confluence of VWC trend + RSI direction + Structure alignment
- Use EMA fills as dynamic stop-loss zones
**2. Reversal Trading (Signals 5, 6, 7, 8)**
- **Signal 5 & 6**: Identify Bollinger Band breakouts and reversals
- **Signal 7**: Look for EMA bounces with structure confirmation
- **Signal 8**: **EARLY TREND REVERSAL** - Enter at the very beginning of trend changes
- These signals bypass certain filters for early entry opportunities
**3. Signal 8 - Early Trend Reversal Strategy (NEW in v2)**
**Best Use Cases:**
- **Higher Timeframes (15m-1H)**: Most reliable for catching major trend reversals
- **Swing Trading**: Perfect for multi-day position entries
- **Confirmation Trading**: Use with other signals for high-confidence entries
**How to Trade Signal 8:**
- **BUY (Blue→Red transition)**:
- Watch for all EMA fills turning from blue to red
- Entry: When Signal 8 BUY label appears
- Stop Loss: Below recent swing low or EMA200
- Take Profit: Target next resistance or use trailing stop with EMA50
- **SELL (Red→Blue transition)**:
- Watch for all EMA fills turning from red to blue
- Entry: When Signal 8 SELL label appears
- Stop Loss: Above recent swing high or EMA200
- Take Profit: Target next support or use trailing stop with EMA50
**Signal 8 Advantages:**
- Catches trend reversals 5-10 bars BEFORE other signals
- Lower risk entry at the start of new trends
- Higher reward potential (entering at trend inception)
**Signal 8 Risks:**
- May produce false signals in choppy/ranging markets
- Best combined with higher timeframe confirmation
- Consider using larger stop losses due to early entry
---
### Risk Management
- Use **EMA20/EMA50** as trailing stop-loss levels
- For Signal 8: Use **EMA200** as major trend stop-loss
- Exit on opposite signal or when price crosses major EMA
- Combine with higher timeframe trend confirmation (60min+ chart)
- Avoid trading when VWC Status Table shows conflicting signals
### Timeframe Recommendations
- **Signal 8 Best Timeframes:** 15min to 1H (for early trend reversal)
- **Other Signals:** 1-minute to 15-minute charts (scalping/day trading)
- **Higher timeframes:** Works on 1H+ but may produce fewer signals
- **Complementary:** Use 4H/Daily chart for overall trend direction
---
## 🔄 Integrated Trading Strategy with MTF OB & FVG Detector
Combining **Trend Gazer v2** with **MTF OB & FVG Detector** creates a powerful trading approach that leverages institutional order flow (OB) and market supply-demand imbalances (FVG) alongside trend momentum.
### Benefits of Integration
**1. Highest Probability Entry Points**
- Trend Gazer BUY/SELL signals + OB/FVG zones = **Highest probability entry points**
- Multi-timeframe OB confluence (5m, 15m, 60m) + Trend Gazer signals = **Institutional + trend alignment**
**2. Precise Entry Price Determination**
- Trend Gazer confirms trend direction and market bias
- OB/FVG zones pinpoint exact entry prices
- Reduces unnecessary risk and maximizes reward ratios
**3. Enhanced Stop Loss Management**
- Use EMA20/50 (Trend Gazer) as trailing stop loss levels
- Set OB zones (MTF OB & FVG) as additional defensive lines
- Multi-layer risk protection
---
### Recommended Integration Strategies
#### Strategy 1: High-Probability Confluence Entry 【MOST RECOMMENDED】
**Setup:**
1. Monitor Trend Gazer v2 for BUY/SELL signals
2. Identify combined OB/FVG zones (3+ timeframes) on MTF OB & FVG Detector
3. Wait for both to align at the same price zone
**Entry Conditions (BUY example):**
- ✅ Trend Gazer: BUY signal triggered (any Signal 1-7)
- ✅ MTF OB & FVG: Price touches Bullish OB zone (especially combined zones)
- ✅ Filter 4 (EMA Transition Period): Blue→Red transition active (BUY-only period)
- ✅ Market Structure: Bullish (red border)
- ✅ High Volume: OB zone volume percentage ≥75%
**Entry:**
- Enter at close of bar when Trend Gazer BUY signal appears within OB zone
- Or enter at open of next bar
**Stop Loss:**
1. **Initial SL**: OB zone lower edge - (5-10 pips/points)
2. **Alternative SL**: Below EMA50 (wider SL, for swing trades)
3. **Tight SL**: Below recent low - (3-5 pips/points) (for scalping)
**Take Profit Targets:**
1. **T1 (50%)**: Next higher timeframe Bearish OB/FVG zone
2. **T2 (30%)**: 60min Bollinger Band upper limit
3. **T3 (20%)**: Trail with EMA20/50, hold until opposite signal
**SELL example follows inverse logic**
---
#### Strategy 2: Precise Reversal Entry 【INTERMEDIATE】
**Best Use Cases:**
- End of strong trends
- Reversals at significant combined OB/FVG zones
- Higher timeframe support/resistance levels
**Entry Conditions (SELL example):**
1. **Higher Timeframe Confirmation:**
- Identify Bearish OB confluence zone on 60min chart
- Price reaches confluence zone
2. **Trend Gazer Signals:**
- **Signal 5**: Break below 15min upper BB + Reverse RSI bearish shift, OR
- **Signal 6**: First RSI bearish signal after breaking 15min upper BB/EMA50, OR
- **Signal 7**: Market Structure bearish + bounce down from EMA20/50
3. **OB/FVG Confirmation:**
- Confirm bounce at 15min or 60min Bearish OB zone
- FVG remains above (price magnet effect)
**Entry:**
- Enter after confirming both Trend Gazer signal + OB zone bounce
- Candlestick pattern confirmation recommended (pin bar, engulfing, etc.)
**Stop Loss:**
- Above OB zone upper edge + 10-15 pips/points
- Or above 60min upper BB
**Take Profit:**
- **T1**: Lower timeframe Bullish OB/FVG zone (unfilled FVG preferred)
- **T2**: 15min lower BB
- **T3**: Until opposite signal or EMA20/50 touch
**BUY example follows inverse logic**
---
#### Strategy 3: Trend Following with OB Support 【BEGINNER-FRIENDLY】
**Simple Approach:**
**BUY Strategy:**
1. **Trend Confirmation (Trend Gazer):**
- EMA fills are red (bullish alignment)
- VWC Status shows BULLISH
- Market Structure is Bullish (red border)
2. **Wait for Pullback:**
- Price retraces to lower timeframe (5m or 15m) Bullish OB zone
- Trend Gazer **Signal 1, 2, or 4** triggers
3. **Entry:**
- Enter when BUY signal appears within OB zone
- Enter at candle body close
4. **Stop Loss:**
- Below OB zone lower edge - 10 pips/points
5. **Take Profit:**
- **Simple**: 2x risk (1:2 R:R)
- **Dynamic**: Until next Bearish OB or opposite signal
**SELL Strategy follows inverse logic**
---
#### Strategy 4: FVG Filling with Trend Gazer Confirmation 【SCALPING】
**For Short-Term Traders:**
**Setup:**
- Identify unfilled FVG (Bullish or Bearish)
- FVG should be away from current price (minimum 20-30 pips/points)
**BUY Example (Bullish FVG below):**
1. **FVG Identification:**
- Unfilled Bullish FVG below current price (Orange box)
- Prefer high-volume FVG (75%+)
2. **Trend Gazer Confirmation:**
- Price approaches FVG
- Market Structure turns Bullish
- **Signal 3, 4, or 7** triggers near FVG zone
3. **Entry:**
- Price enters FVG and Trend Gazer signal confirms bounce from FVG
- Enter at candle body close
4. **Stop Loss:**
- Below FVG lower edge - 5-7 pips/points (tight)
5. **Take Profit:**
- **T1 (70%)**: FVG upper edge (gap fill)
- **T2 (30%)**: Next resistance or opposite signal
**SELL Example (Bearish FVG above) follows inverse logic**
---
### Best Practices for Integrated Usage
**1. Chart Setup:**
- **Main Chart Timeframe**: 5min or 15min
- **Trend Gazer v2**: All signals and filters enabled
- **MTF OB & FVG Detector**: Enable 5m, 15m, 60m; Combine Overlapping OBs = ON
**2. Alert Configuration:**
- Trend Gazer: BUY/SELL signal alerts enabled
- MTF OB & FVG: Bounce alerts + Combined Zone alerts enabled (Min 3 OBs)
- Both alerts firing simultaneously = Highest probability entry
**3. Pre-Entry Checklist:**
- Trend Gazer BUY/SELL signal confirmed
- OB/FVG zone overlaps with price
- Filter 4 supports direction (during transition period)
- Market Structure aligns
- OB/FVG high volume confirmed (70%+ recommended)
- Higher timeframe trend doesn't conflict
- Risk:Reward ratio minimum 1:1.5
**4. Risk Management Rules:**
- Risk per trade: 0.5-1% of account balance
- Concurrent positions: Maximum 2-3 (low-correlation pairs only)
- After consecutive losses: Pause after 3 losses, review strategy
- Daily loss limit: 2-3% of account balance
**5. Situations to Avoid:**
- ❌ Entering with OB/FVG alone, without Trend Gazer signal
- ❌ Immediately before/after major economic releases (volatility spikes)
- ❌ When multiple filters contradict each other
- ❌ OB/FVG zones tested multiple times (weakened)
- ❌ Low liquidity periods (Asian early morning, etc.)
---
### Performance Enhancement Tips
**1. Timeframe Selection:**
- **Scalping**: 1m/3m OB + 5m Trend Gazer signals
- **Day Trading**: 5m/15m OB + 15m Trend Gazer signals
- **Swing Trading**: 15m/60m OB + 60m Trend Gazer signals
**2. Confluence Zone Priority:**
- **Highest**: 60min OB confluence (3+) + Trend Gazer Signal 6 or 7
- **High**: 15min OB confluence + Filter 4 transition period + Signal 1-5
- **Medium**: 5min OB + Market Structure alignment + Signal 1-4
- **Low**: Single timeframe OB + basic signal (require more confirmation)
**3. Backtesting Recommended:**
- Test each strategy on 1-3 months of historical data
- Record win rate, average R:R, maximum drawdown
- Discover optimal combinations for your trading style
**4. Continuous Improvement:**
- Keep trade journal (with screenshots)
- Weekly performance review
- Document effective combination patterns
- Adjust to changing market conditions
---
### Real-World Examples
**Example 1: Perfect Confluence BUY**
```
Situation:
- 15min chart, EUR/USD
- Price touches 60min Bullish OB confluence zone (5m+15m+60m)
- Trend Gazer Signal 6: First RSI bullish signal after 15min lower BB breakout
- Filter 4: EMA fills transitioning blue→red (BUY-only period)
- Market Structure: Turns Bullish (red border)
- OB Volume: 82% (strong buying pressure)
Entry: 1.0850 (OB zone middle)
Stop Loss: 1.0835 (OB zone lower edge - 5 pips)
Take Profit T1: 1.0875 (Next 15min Bearish OB) - Hit
Take Profit T2: 1.0895 (60min upper BB) - Hit
Take Profit T3: 1.0920 (EMA20 trailing) - Closed before opposite signal
Result: +70 pips, Risk 15 pips = 4.67:1 R:R
```
**Example 2: FVG Filling with Reversal Confirmation SELL**
```
Situation:
- 5min chart, GBP/JPY
- Unfilled Bearish FVG above (Aqua box, 15min)
- Price surges to reach FVG
- Trend Gazer Signal 7: Market Structure bearish + downward bounce from EMA50
- Reverse RSI: Bearish shift
- FVG Volume: 78% (strong selling pressure)
Entry: 191.50 (bounce confirmed at FVG upper edge)
Stop Loss: 191.75 (FVG upper edge + 25 pips)
Take Profit T1: 191.00 (FVG lower edge, gap fill) - Hit
Take Profit T2: 190.70 (Next Bullish OB) - Partially hit
Result: +50 pips (weighted average), Risk 25 pips = 2:1 R:R
```
---
### Summary: Why This Integration is Powerful
**Trend Gazer v2's Role:**
- ✅ Trend direction confirmation (VWC, EMA, Structure)
- ✅ Timing signals (7 types of entry opportunities)
- ✅ Multiple filters reduce false signals
- ✅ Dynamic stop loss management (EMA, BB)
**MTF OB & FVG Detector's Role:**
- ✅ Institutional order flow visualization
- ✅ Precise price zone identification (exact entries)
- ✅ High-probability support/resistance levels
- ✅ Volume analysis for zone strength confirmation
**Synergy from Integration:**
- 🎯 **Probability Multiplication**: Each indicator is effective alone, but alignment dramatically increases probability
- 🎯 **Risk Reduction**: More precise stop loss placement minimizes losses
- 🎯 **Reward Maximization**: Optimal entry prices expand profit potential
- 🎯 **Strategy Diversity**: Applicable to trend-following, reversals, scalping, and swing trading
**Recommended Getting Started:**
1. Test Strategy 1 (Confluence Entry) on demo account for 2 weeks
2. Keep trade journal and learn patterns
3. Practice same strategy on small real account (minimum lot)
4. Expand to Strategies 2, 3 as confidence grows
5. Continuously backtest and improve
This integrated approach enables professional-level trading strategies that combine market **supply-demand zones (OB/FVG)** with **trend momentum (Trend Gazer)**.
---
## ⚙️ Input Parameters
### Signal 8 Settings (NEW in v2)
- **Enable Signal 8: EMA Fill Color Transition:** Toggle Signal 8 on/off (Default: OFF)
- **EMA Slope Lookback:** Period for EMA slope calculation (Default: 5, Range: 2-20)
- Lower values: More sensitive, earlier signals
- Higher values: More stable, fewer false signals
### Signal Display Settings
- **Show BUY/SELL Labels:** Toggle main entry signals
- **Show RSI Trend Shift Labels:** Display Bullish/Bearish RSI shifts
- **Label Size:** Small, Normal, Large, Huge
- **Label Position:** On bar or offset by ATR
### Filter Settings
- **Enable RSI Direction Filter:** Filter signals by RSI trend (Default: ON)
- **Enable EMA Order Filter:** Require EMA alignment for SELL signals (Default: ON)
- **Enable BB Direction Filter:** Create directional bias zones after BB breakouts (Default: ON)
### Visual Settings
- **Show Structure Candles:** Color candle borders by market structure
- **Show EMAs:** Display 7 exponential moving averages
- **Show EMA Fills:** Display colored fills between key EMAs (critical for Signal 8)
- **Show 15min Bollinger Bands:** Display short-term BB
- **Show 60min Bollinger Bands:** Display longer-term BB
- **VWC Status Table:** Toggle status table display
---
## 🆕 What's New in v2
1. **Signal 8 - EMA Fill Color Transition Detection**
- Early trend reversal identification
- EMA slope flattening analysis
- EMA convergence pattern recognition
- Normalized slope calculation using ATR
2. **Enhanced Tooltip Documentation**
- All signals now clearly documented in input tooltips
- Signal 8 explanation included
3. **Improved Alert System**
- New alerts for Signal 8 BUY/SELL
- Dedicated alert for EMA fill color transitions
4. **Better Visual Clarity**
- EMA fills now critical for Signal 8 visualization
- Easy to see when all fills are transitioning colors
---
## ⚠️ Disclaimer
This indicator is provided for **educational and informational purposes only**. It is **not financial advice**.
Trading involves substantial risk of loss and is not suitable for all investors. Past performance does not guarantee future results. Users should conduct their own research and consider consulting with a qualified financial advisor before making any trading decisions.
The author is not responsible for any losses incurred using this indicator.
---
## 📝 Credits
- **Reverse RSI Signals:** Based on concepts by AlgoAlpha
- **VWC Trend Detector:** Original implementation
- **ICT Donchian Structure:** Inspired by ICT concepts and Donchian channels
- **Bollinger Bands:** Developed by John Bollinger
- **EMA Analysis:** Standard technical analysis tool
- **Signal 8 EMA Transition:** Original implementation for Trend Gazer v2
---
## 📜 License
This Pine Script™ code is subject to the terms of the **Mozilla Public License 2.0** at mozilla.org
---
## 🔔 Alerts
The indicator includes built-in alert conditions for:
- BUY signals (all 8 types)
- SELL signals (all 8 types)
- **NEW: Signal 8 EMA Fill Color Transition alerts**
- Reverse RSI Bullish/Bearish shifts
- VWC UP/DOWN signals
Configure alerts via TradingView's alert creation menu.
---
**Version:** 2.0
**Platform:** TradingView Pine Script™
**Type:** Indicator (Overlay)
---
## 🚀 Tips for Best Results
1. **Combine Signals:** Use Signal 8 with other signals for confluence
2. **Signal 8 on Higher TF:** Most reliable on 15m-1H timeframes
3. **Use EMA Fills:** Keep EMA fills visible to see Signal 8 transitions
4. **Respect Market Structure:** Don't fight the trend on larger timeframes
5. **Backtest Signal 8:** Test on historical data to understand its behavior
6. **Adjust EMA Slope Lookback:** Fine-tune for your trading style and timeframe
7. **Watch the Table:** The VWC Status Table provides quick trend assessment
8. **Signal 8 + Structure:** Best results when Signal 8 aligns with Structure change
---
**Happy Trading! 📊💹**
**v2 Upgrade: Catch trend reversals EARLIER with Signal 8!**
cd_HTF_bias_CxOverview:
No matter our trading style or model, to increase our success rate, we must move in the direction of the trend and align with the Higher Time Frame (HTF). Trading "gurus" call this the HTF bias. While we small fish tend to swim in all directions, the smart way is to flow with the big wave and the current. This indicator is designed to help us anticipate that major wave.
________________________________________
Details and Usage:
This indicator observes HTF price action across preferably seven different pairs, following specific rules. It confirms potential directional moves using CISD levels on a Medium Time Frame (MTF). In short, it forecasts the likely direction (HTF bias). The user can then search for trade opportunities aligned with this bias on a Lower Time Frame (LTF), using their preferred pair, entry model, and style.
________________________________________
Timeframe Alignment:
The commonly accepted LTF/MTF/HTF combinations include:
• 1m – 15m – H4
• 3m – H1 – Daily / 3m – 30m – Daily
• 5m – H1 – Daily
• 15m – H4 – Weekly
• H1 – Daily – Monthly
• H4 – Weekly – Quarterly
Example: If you're trading with a 3m model on a 30m/3m setup, you should seek trades in the direction of the H1/Daily bias.
________________________________________
How It Works:
The indicator first looks for sweeps on the selected HTF — when any of the last four candles are swept, the first condition is met.
The second step is confirmation with a CISD close on the MTF — once a candle closes above/below the CISD level, the second condition is fulfilled. This suggests the price has made its directional decision.
Example: If a previous HTF candle is swept and we receive a bearish CISD confirmation on H1, the HTF bias becomes bearish.
After this, you may switch to a more granular setup like HTF: 30m and MTF: 3m to look for trade entries aligned with the bias (e.g., 30m sweep + 3m CISD).
________________________________________
How Is Bias Determined?
• HTF Sweep + MTF CISD = SC (Sweep & CISD)
• Latest Bullish SC → Bias: Bullish
• Latest Bearish SC → Bias: Bearish
• Price closes above the last Bearish SC → Bias: Strong Bullish
• Price closes below the last Bullish SC → Bias: Strong Bearish
• Strong Bullish bias + Bearish CISD (without HTF sweep) → Bias: Bullish
• Strong Bearish bias + Bullish CISD (without HTF sweep) → Bias: Bearish
• Bearish price violates SC high, but Bullish SC is untouched → Bias: Bullish
• Bullish price violates SC low, but Bearish SC is untouched → Bias: Bearish
• If neither side generates SC → Bias: No Bias
The logic is built on the idea that a price overcoming resistance is stronger, and encountering resistance is weaker. This model is based on the well-known “Daily Bias” structure, but with personal refinements.
________________________________________
What’s on the Screen?
• Classic HTF zones (boxes)
• Potential MTF CISD levels
• Confirmed MTF lines
• Sweep zones when HTF sweeps occur
• Result table showing current bias status
________________________________________
Usage:
• Select HTF and MTF timeframes aligned with your trading timeframe.
• Adjust color and position settings as needed.
• Enter up to seven pairs to track via the menu.
• Use the checkbox next to each pair to enable/disable them.
• If “Ignore these assets” is checked, all pairs will be disabled, and only the currently open chart pair will be tracked.
________________________________________
Alerts:
You can choose alerts for Bullish, Bearish, Strong Bullish, or Strong Bearish conditions.
There are two types of alert sources:
1. From the indicator’s internal list
2. From TradingView’s watchlist
Visual example:
________________________________________
How I Use It:
• For spot trades, I use HTF: Weekly and MTF: H4 and look for Bullish or Strong Bullish pairs.
• For scalping, I follow bias from HTF: Daily and MTF: H1.
Example: If the indicator shows a Bearish HTF Bias, I switch to HTF: 30m and MTF: 3m and enter trades once bearish conditions are met (timeframe alignment).
________________________________________
Important Notes:
• The indicator defines CISD levels only at HTF high and low levels.
• If your chart is on a higher timeframe than your selected HTF/MTF, no data will appear.
Example: If HTF = H1 and MTF = 5m, opening a chart on H4 will result in a blank screen.
• The drawn CISD level on screen is the MTF CISD level.
• Not every alert should be traded. Always confirm with personal experience and visual validation.
• Receiving multiple Strong Bullish/Bearish alerts is intentional. (Trick 😊)
• Please share your feedback and suggestions!
________________________________________
And Most Importantly:
Don't leave street animals without water and food!
Happy trading!
EvoTrend-X Indicator — Evolutionary Trend Learner ExperimentalEvoTrend-X Indicator — Evolutionary Trend Learner
NOTE: This is an experimental Pine Script v6 port of a Python prototype. Pine wasn’t the original research language, so there may be small quirks—your feedback and bug reports are very welcome. The model is non-repainting, MTF-safe (lookahead_off + gaps_on), and features an adaptive (fitness-based) candidate selector, confidence gating, and a volatility filter.
⸻
What it is
EvoTrend-X is adaptive trend indicator that learns which moving-average length best fits the current market. It maintains a small “population” of fast EMA candidates, rewards those that align with price momentum, and continuously selects the best performer. Signals are gated by a multi-factor Confidence score (fitness, strength vs. ATR, MTF agreement) and a volatility filter (ATR%). You get a clean Fast/Slow pair (for the currently best candidate), optional HTF filter, a fitness ribbon for transparency, and a themed info panel with a one-glance STATUS readout.
Core outputs
• Selected Fast/Slow EMAs (auto-chosen from candidates via fitness learning)
• Spread cross (Fast – Slow) → visual BUY/SELL markers + alert hooks
• Confidence % (0–100): Fitness ⊕ Distance vs. ATR ⊕ MTF agreement
• Gates: Trend regime (Kaufman ER), Volatility (ATR%), MTF filter (optional)
• Candidate Fitness Ribbon: shows which lengths the learner currently prefers
• Export plot: hidden series “EvoTrend-X Export (spread)” for downstream use
⸻
Why it’s different
• Evolutionary learning (on-chart): Each candidate EMA length gets rewarded if its slope matches price change and penalized otherwise, with a gentle decay so the model forgets stale regimes. The best fitness wins the right to define the displayed Fast/Slow pair.
• Confidence gate: Signals don’t light up unless multiple conditions concur: learned fitness, spread strength vs. volatility, and (optionally) higher-timeframe trend.
• Volatility awareness: ATR% filter blocks low-energy environments that cause death-by-a-thousand-whipsaws. Your “why no signal?” answer is always visible in the STATUS.
• Preset discipline, Custom freedom: Presets set reasonable baselines for FX, equities, and crypto; Custom exposes all knobs and honors your inputs one-to-one.
• Non-repainting rigor: All MTF calls use lookahead_off + gaps_on. Decisions use confirmed bars. No forward refs. No conditional ta.* pitfalls.
⸻
Presets (and what they do)
• FX 1H (Conservative): Medium candidates, slightly higher MinConf, modest ATR% floor. Good for macro sessions and cleaner swings.
• FX 15m (Active): Shorter candidates, looser MinConf, higher ATR% floor. Designed for intraday velocity and decisive sessions.
• Equities 1D: Longer candidates, gentler volatility floor. Suits index/large-cap trend waves.
• Crypto 1H: Mid-short candidates, higher ATR% floor for 24/7 chop, stronger MinConf to avoid noise.
• Custom: Your inputs are used directly (no override). Ideal for systematic tuning or bespoke assets.
⸻
How the learning works (at a glance)
1. Candidates: A small set of fast EMA lengths (e.g., 8/12/16/20/26/34). Slow = Fast × multiplier (default ×2.0).
2. Reward/decay: If price change and the candidate’s Fast slope agree (both up or both down), its fitness increases; otherwise decreases. A decay constant slowly forgets the distant past.
3. Selection: The candidate with highest fitness defines the displayed Fast/Slow pair.
4. Signal engine: Crosses of the spread (Fast − Slow) across zero mark potential regime shifts. A Confidence score and gates decide whether to surface them.
⸻
Controls & what they mean
Learning / Regime
• Slow length = Fast ×: scales the Slow EMA relative to each Fast candidate. Larger multiplier = smoother regime detection, fewer whipsaws.
• ER length / threshold: Kaufman Efficiency Ratio; above threshold = “Trending” background.
• Learning step, Decay: Larger step reacts faster to new behavior; decay sets how quickly the past is forgotten.
Confidence / Volatility gate
• Min Confidence (%): Minimum score to show signals (and fire alerts). Raising it filters noise; lowering it increases frequency.
• ATR length: The ATR window for both the ATR% filter and strength normalization. Shorter = faster, but choppier.
• Min ATR% (percent): ATR as a percentage of price. If ATR% < Min ATR% → status shows BLOCK: low vola.
MTF Trend Filter
• Use HTF filter / Timeframe / Fast & Slow: HTF Fast>Slow for longs, Fast threshold; exit when spread flips or Confidence decays below your comfort zone.
2) FX index/majors, 15m (active intraday)
• Preset: FX 15m (Active).
• Gate: MinConf 60–70; Min ATR% 0.15–0.30.
• Flow: Focus on session opens (LDN/NY). The ribbon should heat up on shorter candidates before valid crosses appear—good early warning.
3) SPY / Index futures, 1D (positioning)
• Preset: Equities 1D.
• Gate: MinConf 55–65; Min ATR% 0.05–0.12.
• Flow: Use spread crosses as regime flags; add timing from price structure. For adds, wait for ER to remain trending across several bars.
4) BTCUSD, 1H (24/7)
• Preset: Crypto 1H.
• Gate: MinConf 70–80; Min ATR% 0.20–0.35.
• Flow: Crypto chops—volatility filter is your friend. When ribbon and HTF OK agree, favor continuation entries; otherwise stand down.
⸻
Reading the Info Panel (and fixing “no signals”)
The panel is your self-diagnostic:
• HTF OK? False means the higher-timeframe EMAs disagree with your intended side.
• Regime: If “Chop”, ER < threshold. Consider raising the threshold or waiting.
• Confidence: Heat-colored; if below MinConf, the gate blocks signals.
• ATR% vs. Min ATR%: If ATR% < Min ATR%, status shows BLOCK: low vola.
• STATUS (composite):
• BLOCK: low vola → increase Min ATR% down (i.e., allow lower vol) or wait for expansion.
• BLOCK: HTF filter → disable HTF or align with the HTF tide.
• BLOCK: confidence → lower MinConf slightly or wait for stronger alignment.
• OK → you’ll see markers on valid crosses.
⸻
Alerts
Two static alert hooks:
• BUY cross — spread crosses up and all gates (ER, Vol, MTF, Confidence) are open.
• SELL cross — mirror of the above.
Create them once from “Add Alert” → choose the condition by name.
⸻
Exporting to other scripts
In your other Pine indicators/strategies, add an input.source and select EvoTrend-X → “EvoTrend-X Export (spread)”. Common uses:
• Build a rule: only trade when exported spread > 0 (trend filter).
• Combine with your oscillator: oscillator oversold and spread > 0 → buy bias.
⸻
Best practices
• Let it learn: Keep Learning step moderate (0.4–0.6) and Decay close to 1.0 (e.g., 0.99–0.997) for smooth regime memory.
• Respect volatility: Tune Min ATR% by asset and timeframe. FX 1H ≈ 0.10–0.20; crypto 1H ≈ 0.20–0.35; equities 1D ≈ 0.05–0.12.
• MTF discipline: HTF filter removes lots of “almost” trades. If you prefer aggressive entries, turn it off and rely more on Confidence.
• Confidence as throttle:
• 40–60%: exploratory; expect more signals.
• 60–75%: balanced; good daily driver.
• 75–90%: selective; catch the clean stuff.
• 90–100%: only A-setups; patient mode.
• Watch the ribbon: When shorter candidates heat up before a cross, momentum is forming. If long candidates dominate, you’re in a slower trend cycle.
⸻
Non-repainting & safety notes
• All request.security() calls use lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_on.
• No forward references; decisions rely on confirmed bar data.
• EMA lengths are simple ints (no series-length errors).
• Confidence components are computed every bar (no conditional ta.* traps).
⸻
Limitations & tips
• Chop happens: ER helps, but sideways microstructure can still flicker—use Confidence + Vol filter as brakes.
• Presets ≠ oracle: They’re sensible baselines; always tune MinConf and Min ATR% to your venue and session.
• Theme “Auto”: Pine cannot read chart theme; “Auto” defaults to a Dark-friendly palette.
⸻
Publisher’s Screenshots Checklist
1) FX swing — EURUSD 1H
• Preset: FX 1H (Conservative)
• Params: MinConf=70, ATR Len=14, Min ATR%=0.12, MTF ON (TF=4H, 20/50)
• Show: Clear BUY cross, STATUS=OK, green regime background; Fitness Ribbon visible.
2) FX intraday — GBPUSD 15m
• Preset: FX 15m (Active)
• Params: MinConf=60, ATR Len=14, Min ATR%=0.20, MTF ON (TF=60m)
• Show: SELL cross near London session open. HTF lines enabled (translucent).
• Caption: “GBPUSD 15m • Active session sell with MTF alignment.”
3) Indices — SPY 1D
• Preset: Equities 1D
• Params: MinConf=60, ATR Len=14, Min ATR%=0.08, MTF ON (TF=1W, 20/50)
• Show: Longer trend run after BUY cross; regime shading shows persistence.
• Caption: “SPY 1D • Trend run after BUY cross; weekly filter aligned.”
4) Crypto — BINANCE:BTCUSDT 1H
• Preset: Crypto 1H
• Params: MinConf=75, ATR Len=14, Min ATR%=0.25, MTF ON (TF=4H)
• Show: BUY cross + quick follow-through; Ribbon warming (reds/yellows → greens).
• Caption: “BTCUSDT 1H • Momentum break with high confidence and ribbon turning.”
ATR%指標概要 / Overview
ATR Percentage (MTF):把 ATR 轉為百分比(ATR%)或保留為絕對值,並在該「波動序列」上套用布林帶。支援多週期(MTF)計算:例如在 5 分圖顯示 4H / D1 的 ATR%。內建白色點狀水平線作為固定門檻(預設 1%)。
ATR Percentage (MTF): Converts ATR to a percentage of price (ATR%) or keeps it as absolute ATR, then applies Bollinger Bands on this volatility series. Supports multi-timeframe (MTF) calculation (e.g., show 4H/D1 ATR% on a 5-min chart). Includes a configurable white dotted horizontal threshold line (default 1%).
⸻
設計目的 / Purpose
• 以 ATR% 衡量相對波動,利於跨品種比較。
Use ATR% for relative volatility to compare across markets.
• 以 布林帶 標示「高/低波動區」,觀察擴張與壓縮。
Use Bollinger Bands on volatility to highlight expansion/squeeze.
• 提供 固定閾值(1%) 作為策略濾網或告警門檻。
Provide a fixed threshold (1%) for filters/alerts.
• 以 MTF 方式,讓低週期策略用高週期波動做濾網。
MTF lets lower-TF strategies filter by higher-TF volatility.
⸻
參數說明 / Inputs
• Use ATR as % of Close:切換 ATR(絕對值)/ ATR%(建議)。
Toggle between absolute ATR and ATR% (recommended).
• ATR Periods:ATR 計算長度(預設 22)。
ATR lookback (default 22).
• Show Bollinger Bands / BB Periods / StdDev:布林帶開關、長度與倍數(預設 20 / 2)。
Bollinger Bands on/off, length, and deviation (default 20 / 2).
• Source Timeframe:計算用週期(如 60、240、D、W;留空/Chart = 跟隨圖表)。
Timeframe used for calculations (e.g., 60, 240, D, W; empty/“Chart” = current).
• Threshold Line (%):白色點線門檻,預設 1.0(即 1%)。
White dotted threshold line, default 1.0 (1%).
提醒:當 非 ATR% 模式時,Threshold 值代表「價格單位」而非百分比。
Note: In non-ATR% mode, the threshold is in price units, not percent.
⸻
訊號解讀 / How to Read
• ATR% > 上軌:波動顯著擴張(趨勢啟動或加速常見)。
ATR% above upper band: significant expansion; often trend ignition/acceleration.
• ATR% < 下軌:波動明顯壓縮(常見於突破前)。
ATR% below lower band: volatility squeeze; often precedes breakouts.
• ATR% 穿越 Threshold(1%):達到固定波動標準,可作策略開關或風控分水嶺。
ATR% crossing the 1% threshold: fixed volatility bar for filters/risk gates.
⸻
內建告警 / Built-in Alerts
• Volatility Breakout (MTF):ATR/ATR% 向上穿越上軌。
Triggers when ATR/ATR% crosses above the upper band.
• Volatility Squeeze (MTF):ATR/ATR% 向下穿越下軌。
Triggers when ATR/ATR% crosses below the lower band.
⸻
使用建議 / Suggested Uses
• 當沖濾網:於 1–5 分圖選擇 4H / D1 作為 Source Timeframe;僅在 ATR% > 1% 且位於中線以上時允許趨勢進場。
Intraday filter: on 1–5m charts, set 4H/D1 as source TF; allow trend entries only when ATR% > 1% and above the midline.
• 突破前偵測:ATR% 長時間貼近下軌 → 留意可能的波動擴張。
Pre-breakout scan: prolonged ATR% near lower band can foreshadow expansion.
• 跨品種比較:用 ATR% 統一指數、外匯、商品的波動刻度。
Cross-asset comparison: ATR% normalizes volatility across indices/FX/commodities.
⸻
已知限制 / Notes
• MTF 對齊:使用 request.security() 對映高週期資料到當前圖表;在歷史回補與即時邊界棒可能略有差異。
MTF alignment: request.security() maps higher-TF data; boundary bars may differ slightly between historical and realtime.
• 百分比分母:ATR% 的分母為同一週期的 close;若需更平滑可改 ATR / SMA(close, N) × 100。
Denominator: ATR% uses same-TF close; for smoother values consider ATR / SMA(close, N) × 100.
• 風險聲明:僅供研究/教育用途,非投資建議,請自行控管風險。
Disclaimer: For research/education only. Not investment advice.
⸻
版本與更新 / Version & Updates
• v1.0:ATR/ATR% + BB(MTF)、1% 白色點線、兩組告警。
v1.0: ATR/ATR% + BB (MTF), 1% white dotted line, two alert conditions.
`security()` revisited [PineCoders]NOTE
The non-repainting technique in this publication that relies on bar states is now deprecated, as we have identified inconsistencies that undermine its credibility as a universal solution. The outputs that use the technique are still available for reference in this publication. However, we do not endorse its usage. See this publication for more information about the current best practices for requesting HTF data and why they work.
█ OVERVIEW
This script presents a new function to help coders use security() in both repainting and non-repainting modes. We revisit this often misunderstood and misused function, and explain its behavior in different contexts, in the hope of dispelling some of the coder lure surrounding it. The function is incredibly powerful, yet misused, it can become a dangerous WMD and an instrument of deception, for both coders and traders.
We will discuss:
• How to use our new `f_security()` function.
• The behavior of Pine code and security() on the three very different types of bars that make up any chart.
• Why what you see on a chart is a simulation, and should be taken with a grain of salt.
• Why we are presenting a new version of a function handling security() calls.
• Other topics of interest to coders using higher timeframe (HTF) data.
█ WARNING
We have tried to deliver a function that is simple to use and will, in non-repainting mode, produce reliable results for both experienced and novice coders. If you are a novice coder, stick to our recommendations to avoid getting into trouble, and DO NOT change our `f_security()` function when using it. Use `false` as the function's last argument and refrain from using your script at smaller timeframes than the chart's. To call our function to fetch a non-repainting value of close from the 1D timeframe, use:
f_security(_sym, _res, _src, _rep) => security(_sym, _res, _src )
previousDayClose = f_security(syminfo.tickerid, "D", close, false)
If that's all you're interested in, you are done.
If you choose to ignore our recommendation and use the function in repainting mode by changing the `false` in there for `true`, we sincerely hope you read the rest of our ramblings before you do so, to understand the consequences of your choice.
Let's now have a look at what security() is showing you. There is a lot to cover, so buckle up! But before we dig in, one last thing.
What is a chart?
A chart is a graphic representation of events that occur in markets. As any representation, it is not reality, but rather a model of reality. As Scott Page eloquently states in The Model Thinker : "All models are wrong; many are useful". Having in mind that both chart bars and plots on our charts are imperfect and incomplete renderings of what actually occurred in realtime markets puts us coders in a place from where we can better understand the nature of, and the causes underlying the inevitable compromises necessary to build the data series our code uses, and print chart bars.
Traders or coders complaining that charts do not reflect reality act like someone who would complain that the word "dog" is not a real dog. Let's recognize that we are dealing with models here, and try to understand them the best we can. Sure, models can be improved; TradingView is constantly improving the quality of the information displayed on charts, but charts nevertheless remain mere translations. Plots of data fetched through security() being modelized renderings of what occurs at higher timeframes, coders will build more useful and reliable tools for both themselves and traders if they endeavor to perfect their understanding of the abstractions they are working with. We hope this publication helps you in this pursuit.
█ FEATURES
This script's "Inputs" tab has four settings:
• Repaint : Determines whether the functions will use their repainting or non-repainting mode.
Note that the setting will not affect the behavior of the yellow plot, as it always repaints.
• Source : The source fetched by the security() calls.
• Timeframe : The timeframe used for the security() calls. If it is lower than the chart's timeframe, a warning appears.
• Show timeframe reminder : Displays a reminder of the timeframe after the last bar.
█ THE CHART
The chart shows two different pieces of information and we want to discuss other topics in this section, so we will be covering:
A — The type of chart bars we are looking at, indicated by the colored band at the top.
B — The plots resulting of calling security() with the close price in different ways.
C — Points of interest on the chart.
A — Chart bars
The colored band at the top shows the three types of bars that any chart on a live market will print. It is critical for coders to understand the important distinctions between each type of bar:
1 — Gray : Historical bars, which are bars that were already closed when the script was run on them.
2 — Red : Elapsed realtime bars, i.e., realtime bars that have run their course and closed.
The state of script calculations showing on those bars is that of the last time they were made, when the realtime bar closed.
3 — Green : The realtime bar. Only the rightmost bar on the chart can be the realtime bar at any given time, and only when the chart's market is active.
Refer to the Pine User Manual's Execution model page for a more detailed explanation of these types of bars.
B — Plots
The chart shows the result of letting our 5sec chart run for a few minutes with the following settings: "Repaint" = "On" (the default is "Off"), "Source" = `close` and "Timeframe" = 1min. The five lines plotted are the following. They have progressively thinner widths:
1 — Yellow : A normal, repainting security() call.
2 — Silver : Our recommended security() function.
3 — Fuchsia : Our recommended way of achieving the same result as our security() function, for cases when the source used is a function returning a tuple.
4 — White : The method we previously recommended in our MTF Selection Framework , which uses two distinct security() calls.
5 — Black : A lame attempt at fooling traders that MUST be avoided.
All lines except the first one in yellow will vary depending on the "Repaint" setting in the script's inputs. The first plot does not change because, contrary to all other plots, it contains no conditional code to adapt to repainting/no-repainting modes; it is a simple security() call showing its default behavior.
C — Points of interest on the chart
Historical bars do not show actual repainting behavior
To appreciate what a repainting security() call will plot in realtime, one must look at the realtime bar and at elapsed realtime bars, the bars where the top line is green or red on the chart at the top of this page. There you can see how the plots go up and down, following the close value of each successive chart bar making up a single bar of the higher timeframe. You would see the same behavior in "Replay" mode. In the realtime bar, the movement of repainting plots will vary with the source you are fetching: open will not move after a new timeframe opens, low and high will change when a new low or high are found, close will follow the last feed update. If you are fetching a value calculated by a function, it may also change on each update.
Now notice how different the plots are on historical bars. There, the plot shows the close of the previously completed timeframe for the whole duration of the current timeframe, until on its last bar the price updates to the current timeframe's close when it is confirmed (if the timeframe's last bar is missing, the plot will only update on the next timeframe's first bar). That last bar is the only one showing where the plot would end if that timeframe's bars had elapsed in realtime. If one doesn't understand this, one cannot properly visualize how his script will calculate in realtime when using repainting. Additionally, as published scripts typically show charts where the script has only run on historical bars, they are, in fact, misleading traders who will naturally assume the script will behave the same way on realtime bars.
Non-repainting plots are more accurate on historical bars
Now consider this chart, where we are using the same settings as on the chart used to publish this script, except that we have turned "Repainting" off this time:
The yellow line here is our reference, repainting line, so although repainting is turned off, it is still repainting, as expected. Because repainting is now off, however, plots on historical bars show the previous timeframe's close until the first bar of a new timeframe, at which point the plot updates. This correctly reflects the behavior of the script in the realtime bar, where because we are offsetting the series by one, we are always showing the previously calculated—and thus confirmed—higher timeframe value. This means that in realtime, we will only get the previous timeframe's values one bar after the timeframe's last bar has elapsed, at the open of the first bar of a new timeframe. Historical and elapsed realtime bars will not actually show this nuance because they reflect the state of calculations made on their close , but we can see the plot update on that bar nonetheless.
► This more accurate representation on historical bars of what will happen in the realtime bar is one of the two key reasons why using non-repainting data is preferable.
The other is that in realtime, your script will be using more reliable data and behave more consistently.
Misleading plots
Valiant attempts by coders to show non-repainting, higher timeframe data updating earlier than on our chart are futile. If updates occur one bar earlier because coders use the repainting version of the function, then so be it, but they must then also accept that their historical bars are not displaying information that is as accurate. Not informing script users of this is to mislead them. Coders should also be aware that if they choose to use repainting data in realtime, they are sacrificing reliability to speed and may be running a strategy that behaves very differently from the one they backtested, thus invalidating their tests.
When, however, coders make what are supposed to be non-repainting plots plot artificially early on historical bars, as in examples "c4" and "c5" of our script, they would want us to believe they have achieved the miracle of time travel. Our understanding of the current state of science dictates that for now, this is impossible. Using such techniques in scripts is plainly misleading, and public scripts using them will be moderated. We are coding trading tools here—not video games. Elementary ethics prescribe that we should not mislead traders, even if it means not being able to show sexy plots. As the great Feynman said: You should not fool the layman when you're talking as a scientist.
You can readily appreciate the fantasy plot of "c4", the thinnest line in black, by comparing its supposedly non-repainting behavior between historical bars and realtime bars. After updating—by miracle—as early as the wide yellow line that is repainting, it suddenly moves in a more realistic place when the script is running in realtime, in synch with our non-repainting lines. The "c5" version does not plot on the chart, but it displays in the Data Window. It is even worse than "c4" in that it also updates magically early on historical bars, but goes on to evaluate like the repainting yellow line in realtime, except one bar late.
Data Window
The Data Window shows the values of the chart's plots, then the values of both the inside and outside offsets used in our calculations, so you can see them change bar by bar. Notice their differences between historical and elapsed realtime bars, and the realtime bar itself. If you do not know about the Data Window, have a look at this essential tool for Pine coders in the Pine User Manual's page on Debugging . The conditional expressions used to calculate the offsets may seem tortuous but their objective is quite simple. When repainting is on, we use this form, so with no offset on all bars:
security(ticker, i_timeframe, i_source )
// which is equivalent to:
security(ticker, i_timeframe, i_source)
When repainting is off, we use two different and inverted offsets on historical bars and the realtime bar:
// Historical bars:
security(ticker, i_timeframe, i_source )
// Realtime bar (and thus, elapsed realtime bars):
security(ticker, i_timeframe, i_source )
The offsets in the first line show how we prevent repainting on historical bars without the need for the `lookahead` parameter. We use the value of the function call on the chart's previous bar. Since values between the repainting and non-repainting versions only differ on the timeframe's last bar, we can use the previous value so that the update only occurs on the timeframe's first bar, as it will in realtime when not repainting.
In the realtime bar, we use the second call, where the offsets are inverted. This is because if we used the first call in realtime, we would be fetching the value of the repainting function on the previous bar, so the close of the last bar. What we want, instead, is the data from the previous, higher timeframe bar , which has elapsed and is confirmed, and thus will not change throughout realtime bars, except on the first constituent chart bar belonging to a new higher timeframe.
After the offsets, the Data Window shows values for the `barstate.*` variables we use in our calculations.
█ NOTES
Why are we revisiting security() ?
For four reasons:
1 — We were seeing coders misuse our `f_secureSecurity()` function presented in How to avoid repainting when using security() .
Some novice coders were modifying the offset used with the history-referencing operator in the function, making it zero instead of one,
which to our horror, caused look-ahead bias when used with `lookahead = barmerge.lookahead_on`.
We wanted to present a safer function which avoids introducing the dreaded "lookahead" in the scripts of unsuspecting coders.
2 — The popularity of security() in screener-type scripts where coders need to use the full 40 calls allowed per script made us want to propose
a solid method of allowing coders to offer a repainting/no-repainting choice to their script users with only one security() call.
3 — We wanted to explain why some alternatives we see circulating are inadequate and produce misleading behavior.
4 — Our previous publication on security() focused on how to avoid repainting, yet many other considerations worthy of attention are not related to repainting.
Handling tuples
When sending function calls that return tuples with security() , our `f_security()` function will not work because Pine does not allow us to use the history-referencing operator with tuple return values. The solution is to integrate the inside offset to your function's arguments, use it to offset the results the function is returning, and then add the outside offset in a reassignment of the tuple variables, after security() returns its values to the script, as we do in our "c2" example.
Does it repaint?
We're pretty sure Wilder was not asked very often if RSI repainted. Why? Because it wasn't in fashion—and largely unnecessary—to ask that sort of question in the 80's. Many traders back then used daily charts only, and indicator values were calculated at the day's close, so everybody knew what they were getting. Additionally, indicator values were calculated by generally reputable outfits or traders themselves, so data was pretty reliable. Today, almost anybody can write a simple indicator, and the programming languages used to write them are complex enough for some coders lacking the caution, know-how or ethics of the best professional coders, to get in over their heads and produce code that does not work the way they think it does.
As we hope to have clearly demonstrated, traders do have legitimate cause to ask if MTF scripts repaint or not when authors do not specify it in their script's description.
► We recommend that authors always use our `f_security()` with `false` as the last argument to avoid repainting when fetching data dependent on OHLCV information. This is the only way to obtain reliable HTF data. If you want to offer users a choice, make non-repainting mode the default, so that if users choose repainting, it will be their responsibility. Non-repainting security() calls are also the only way for scripts to show historical behavior that matches the script's realtime behavior, so you are not misleading traders. Additionally, non-repainting HTF data is the only way that non-repainting alerts can be configured on MTF scripts, as users of MTF scripts cannot prevent their alerts from repainting by simply configuring them to trigger on the bar's close.
Data feeds
A chart at one timeframe is made up of multiple feeds that mesh seamlessly to form one chart. Historical bars can use one feed, and the realtime bar another, which brokers/exchanges can sometimes update retroactively so that elapsed realtime bars will reappear with very slight modifications when the browser's tab is refreshed. Intraday and daily chart prices also very often originate from different feeds supplied by brokers/exchanges. That is why security() calls at higher timeframes may be using a completely different feed than the chart, and explains why the daily high value, for example, can vary between timeframes. Volume information can also vary considerably between intraday and daily feeds in markets like stocks, because more volume information becomes available at the end of day. It is thus expected behavior—and not a bug—to see data variations between timeframes.
Another point to keep in mind concerning feeds it that when you are using a repainting security() plot in realtime, you will sometimes see discrepancies between its plot and the realtime bars. An artefact revealing these inconsistencies can be seen when security() plots sometimes skip a realtime chart bar during periods of high market activity. This occurs because of races between the chart and the security() feeds, which are being monitored by independent, concurrent processes. A blue arrow on the chart indicates such an occurrence. This is another cause of repainting, where realtime bar-building logic can produce different outcomes on one closing price. It is also another argument supporting our recommendation to use non-repainting data.
Alternatives
There is an alternative to using security() in some conditions. If all you need are OHLC prices of a higher timeframe, you can use a technique like the one Duyck demonstrates in his security free MTF example - JD script. It has the great advantage of displaying actual repainting values on historical bars, which mimic the code's behavior in the realtime bar—or at least on elapsed realtime bars, contrary to a repainting security() plot. It has the disadvantage of using the current chart's TF data feed prices, whereas higher timeframe data feeds may contain different and more reliable prices when they are compiled at the end of the day. In its current state, it also does not allow for a repainting/no-repainting choice.
When `lookahead` is useful
When retrieving non-price data, or in special cases, for experiments, it can be useful to use `lookahead`. One example is our Backtesting on Non-Standard Charts: Caution! script where we are fetching prices of standard chart bars from non-standard charts.
Warning users
Normal use of security() dictates that it only be used at timeframes equal to or higher than the chart's. To prevent users from inadvertently using your script in contexts where it will not produce expected behavior, it is good practice to warn them when their chart is on a higher timeframe than the one in the script's "Timeframe" field. Our `f_tfReminderAndErrorCheck()` function in this script does that. It can also print a reminder of the higher timeframe. It uses one security() call.
Intrabar timeframes
security() is not supported by TradingView when used with timeframes lower than the chart's. While it is still possible to use security() at intrabar timeframes, it then behaves differently. If no care is taken to send a function specifically written to handle the successive intrabars, security() will return the value of the last intrabar in the chart's timeframe, so the last 1H bar in the current 1D bar, if called at "60" from a "D" chart timeframe. If you are an advanced coder, see our FAQ entry on the techniques involved in processing intrabar timeframes. Using intrabar timeframes comes with important limitations, which you must understand and explain to traders if you choose to make scripts using the technique available to others. Special care should also be taken to thoroughly test this type of script. Novice coders should refrain from getting involved in this.
█ TERMINOLOGY
Timeframe
Timeframe , interval and resolution are all being used to name the concept of timeframe. We have, in the past, used "timeframe" and "resolution" more or less interchangeably. Recently, members from the Pine and PineCoders team have decided to settle on "timeframe", so from hereon we will be sticking to that term.
Multi-timeframe (MTF)
Some coders use "multi-timeframe" or "MTF" to name what are in fact "multi-period" calculations, as when they use MAs of progressively longer periods. We consider that a misleading use of "multi-timeframe", which should be reserved for code using calculations actually made from another timeframe's context and using security() , safe for scripts like Duyck's one mentioned earlier, or TradingView's Relative Volume at Time , which use a user-selected timeframe as an anchor to reset calculations. Calculations made at the chart's timeframe by varying the period of MAs or other rolling window calculations should be called "multi-period", and "MTF-anchored" could be used for scripts that reset calculations on timeframe boundaries.
Colophon
Our script was written using the PineCoders Coding Conventions for Pine .
The description was formatted using the techniques explained in the How We Write and Format Script Descriptions PineCoders publication.
Snippets were lifted from our MTF Selection Framework , then massaged to create the `f_tfReminderAndErrorCheck()` function.
█ THANKS
Thanks to apozdnyakov for his help with the innards of security() .
Thanks to bmistiaen for proofreading our description.
Look first. Then leap.
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
Adaptive Fibonacci Pullback System -FibonacciFluxAdaptive Fibonacci Pullback System (AFPS) - FibonacciFlux
This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0). Original concepts by FibonacciFlux.
Abstract
The Adaptive Fibonacci Pullback System (AFPS) presents a sophisticated, institutional-grade algorithmic strategy engineered for high-probability trend pullback entries. Developed by FibonacciFlux, AFPS uniquely integrates a proprietary Multi-Fibonacci Supertrend engine (0.618, 1.618, 2.618 ratios) for harmonic volatility assessment, an Adaptive Moving Average (AMA) Channel providing dynamic market context, and a synergistic Multi-Timeframe (MTF) filter suite (RSI, MACD, Volume). This strategy transcends simple indicator combinations through its strict, multi-stage confluence validation logic. Historical simulations suggest that specific MTF filter configurations can yield exceptional performance metrics, potentially achieving Profit Factors exceeding 2.6 , indicative of institutional-level potential, while maintaining controlled risk under realistic trading parameters (managed equity risk, commission, slippage).
4 hourly MTF filtering
1. Introduction: Elevating Pullback Trading with Adaptive Confluence
Traditional pullback strategies often struggle with noise, false signals, and adapting to changing market dynamics. AFPS addresses these challenges by introducing a novel framework grounded in Fibonacci principles and adaptive logic. Instead of relying on static levels or single confirmations, AFPS seeks high-probability pullback entries within established trends by validating signals through a rigorous confluence of:
Harmonic Volatility Context: Understanding the trend's stability and potential turning points using the unique Multi-Fibonacci Supertrend.
Adaptive Market Structure: Assessing the prevailing trend regime via the AMA Channel.
Multi-Dimensional Confirmation: Filtering signals with lower-timeframe Momentum (RSI), Trend Alignment (MACD), and Market Conviction (Volume) using the MTF suite.
The objective is to achieve superior signal quality and adaptability, moving beyond conventional pullback methodologies.
2. Core Methodology: Synergistic Integration
AFPS's effectiveness stems from the engineered synergy between its core components:
2.1. Multi-Fibonacci Supertrend Engine: Utilizes specific Fibonacci ratios (0.618, 1.618, 2.618) applied to ATR, creating a multi-layered volatility envelope potentially resonant with market harmonics. The averaged and EMA-smoothed result (`smoothed_supertrend`) provides a robust, dynamic trend baseline and context filter.
// Key Components: Multi-Fibonacci Supertrend & Smoothing
average_supertrend = (supertrend1 + supertrend2 + supertrend3) / 3
smoothed_supertrend = ta.ema(average_supertrend, st_smooth_length)
2.2. Adaptive Moving Average (AMA) Channel: Provides dynamic market context. The `ama_midline` serves as a key filter in the entry logic, confirming the broader trend bias relative to adaptive price action. Extended Fibonacci levels derived from the channel width offer potential dynamic S/R zones.
// Key Component: AMA Midline
ama_midline = (ama_high_band + ama_low_band) / 2
2.3. Multi-Timeframe (MTF) Filter Suite: An optional but powerful validation layer (RSI, MACD, Volume) assessed on a lower timeframe. Acts as a **validation cascade** – signals must pass all enabled filters simultaneously.
2.4. High-Confluence Entry Logic: The core innovation. A pullback entry requires a specific sequence and validation:
Price interaction with `average_supertrend` and recovery above/below `smoothed_supertrend`.
Price confirmation relative to the `ama_midline`.
Simultaneous validation by all enabled MTF filters.
// Simplified Long Entry Logic Example (incorporates key elements)
long_entry_condition = enable_long_positions and
(low < average_supertrend and close > smoothed_supertrend) and // Pullback & Recovery
(close > ama_midline and close > ama_midline) and // AMA Confirmation
(rsi_filter_long_ok and macd_filter_long_ok and volume_filter_ok) // MTF Validation
This strict, multi-stage confluence significantly elevates signal quality compared to simpler pullback approaches.
1hourly filtering
3. Realistic Implementation and Performance Potential
AFPS is designed for practical application, incorporating realistic defaults and highlighting performance potential with crucial context:
3.1. Realistic Default Strategy Settings:
The script includes responsible default parameters:
strategy('Adaptive Fibonacci Pullback System - FibonacciFlux', shorttitle = "AFPS", ...,
initial_capital = 10000, // Accessible capital
default_qty_type = strategy.percent_of_equity, // Equity-based risk
default_qty_value = 4, // Default 4% equity risk per initial trade
commission_type = strategy.commission.percent,
commission_value = 0.03, // Realistic commission
slippage = 2, // Realistic slippage
pyramiding = 2 // Limited pyramiding allowed
)
Note: The default 4% risk (`default_qty_value = 4`) requires careful user assessment and adjustment based on individual risk tolerance.
3.2. Historical Performance Insights & Institutional Potential:
Backtesting provides insights into historical behavior under specific conditions (always specify Asset/Timeframe/Dates when sharing results):
Default Performance Example: With defaults, historical tests might show characteristics like Overall PF ~1.38, Max DD ~1.16%, with potential Long/Short performance variance (e.g., Long PF 1.6+, Short PF < 1).
Optimized MTF Filter Performance: Crucially, historical simulations demonstrate that meticulous configuration of the MTF filters (particularly RSI and potentially others depending on market) can significantly enhance performance. Under specific, optimized MTF filter settings combined with appropriate risk management (e.g., 7.5% risk), historical tests have indicated the potential to achieve **Profit Factors exceeding 2.6**, alongside controlled drawdowns (e.g., ~1.32%). This level of performance, if consistently achievable (which requires ongoing adaptation), aligns with metrics often sought in institutional trading environments.
Disclaimer Reminder: These results are strictly historical simulations. Past performance does not guarantee future results. Achieving high performance requires careful parameter tuning, adaptation to changing markets, and robust risk management.
3.3. Emphasizing Risk Management:
Effective use of AFPS mandates active risk management. Utilize the built-in Stop Loss, Take Profit, and Trailing Stop features. The `pyramiding = 2` setting requires particularly diligent oversight. Do not rely solely on default settings.
4. Conclusion: Advancing Trend Pullback Strategies
The Adaptive Fibonacci Pullback System (AFPS) offers a sophisticated, theoretically grounded, and highly adaptable framework for identifying and executing high-probability trend pullback trades. Its unique blend of Fibonacci resonance, adaptive context, and multi-dimensional MTF filtering represents a significant advancement over conventional methods. While requiring thoughtful implementation and risk management, AFPS provides discerning traders with a powerful tool potentially capable of achieving institutional-level performance characteristics under optimized conditions.
Acknowledgments
Developed by FibonacciFlux. Inspired by principles of Fibonacci analysis, adaptive averaging, and multi-timeframe confirmation techniques explored within the trading community.
Disclaimer
Trading involves substantial risk. AFPS is an analytical tool, not a guarantee of profit. Past performance is not indicative of future results. Market conditions change. Users are solely responsible for their decisions and risk management. Thorough testing is essential. Deploy at your own considered risk.
Opening Range Breakout with Multi-Timeframe Liquidity]═══════════════════════════════════════
OPENING RANGE BREAKOUT WITH MULTI-TIMEFRAME LIQUIDITY
═══════════════════════════════════════
A professional Opening Range Breakout (ORB) indicator enhanced with multi-timeframe liquidity detection, trading session visualization, volume analysis, and trend confirmation tools. Designed for intraday trading with comprehensive alert system.
───────────────────────────────────────
WHAT THIS INDICATOR DOES
───────────────────────────────────────
This indicator combines multiple trading concepts:
- Opening Range Breakout (ORB) - Customizable time period detection with automatic high/low identification
- Multi-Timeframe Liquidity - HTF (Higher Timeframe) and LTF (Lower Timeframe) key level detection
- Trading Sessions - Tokyo, London, New York, and Sydney session visualization
- Volume Analysis - Volume spike detection and strength measurement
- Multi-Timeframe Confirmation - Trend bias from higher timeframes
- EMA Integration - Trend filter and dynamic support/resistance
- Smart Alerts - Quality-filtered breakout notifications
───────────────────────────────────────
HOW IT WORKS
───────────────────────────────────────
OPENING RANGE BREAKOUT (ORB):
Concept:
The Opening Range is a period at the start of a trading session where price establishes an initial high and low. Breakouts beyond this range often indicate the direction of the day's trend.
Detection Method:
- Default: 15-minute opening range (configurable)
- Custom Range: Set specific session times with timezone support
- Automatically identifies ORH (Opening Range High) and ORL (Opening Range Low)
- Tracks ORB mid-point for reference
Range Establishment:
1. Session starts (or custom time begins)
2. Tracks highest high and lowest low during the period
3. Range confirmed at end of opening period
4. Levels extend throughout the session
Breakout Detection:
- Bullish Breakout: Close above ORH
- Bearish Breakout: Close below ORL
- Mid-point acts as bias indicator
Visual Display:
- Shaded box during range formation
- Horizontal lines for ORH, ORL, and mid-point
- Labels showing level values
- Color-coded fills based on selected method
Fill Color Methods:
1. Session Comparison:
- Green: Current OR mid > Previous OR mid
- Red: Current OR mid < Previous OR mid
- Gray: Equal or first session
- Shows day-over-day momentum
2. Breakout Direction (Recommended):
- Green: Price currently above ORH (bullish breakout)
- Red: Price currently below ORL (bearish breakout)
- Gray: Price inside range (no breakout)
- Real-time breakout status
MULTI-TIMEFRAME LIQUIDITY:
Two-Tier System for comprehensive level identification:
HTF (Higher Timeframe) Key Liquidity:
- Default: 4H timeframe (configurable to Daily, Weekly)
- Identifies major institutional levels
- Uses pivot detection with adjustable parameters
- Suitable for swing highs/lows where large orders rest
LTF (Lower Timeframe) Key Liquidity:
- Default: 1H timeframe (configurable)
- Provides precision entry/exit levels
- Finer granularity for intraday trading
- Captures minor swing points
Calculation Method:
- Pivot high/low detection algorithm
- Configurable left bars (lookback) and right bars (confirmation)
- Timeframe multiplier for accurate multi-timeframe detection
- Automatic level extension
Mitigation System:
- Tracks when levels are swept (broken)
- Configurable mitigation type: Wick or Close-based
- Option to remove or show mitigated levels
- Display limit prevents chart clutter
Asset-Specific Optimization:
The indicator includes quick reference settings for different assets:
- Major Forex (EUR/USD, GBP/USD): Default settings optimal
- Crypto (BTC/ETH): Left=12, Right=4, Display=7
- Gold: HTF=1D, Left=20
TRADING SESSIONS:
Four Major Sessions with Full Customization:
Tokyo Session:
- Default: 04:00-13:00 UTC+4
- Asian trading hours
- Often sets daily range
London Session:
- Default: 11:00-20:00 UTC+4
- Highest liquidity period
- Major institutional activity
New York Session:
- Default: 16:00-01:00 UTC+4
- US market hours
- High-impact news events
Sydney Session:
- Default: 01:00-10:00 UTC+4
- Earliest Asian activity
- Lower volatility
Session Features:
- Shaded background boxes
- Session name labels
- Optional open/close lines
- Session high/low tracking with colored lines
- Each session has independent color settings
- Fully customizable times and timezones
VOLUME ANALYSIS:
Volume-Based Trade Confirmation:
Volume MA:
- Configurable period (default: 20)
- Establishes average volume baseline
- Used for spike detection
Volume Spike Detection:
- Identifies when volume exceeds MA * multiplier
- Default: 1.5x average volume
- Confirms breakout strength
Volume Strength Measurement:
- Calculates current volume as percentage of average
- Shows relative volume intensity
- Used in alert quality filtering
High Volume Bars:
- Identifies bars above 50th percentile
- Additional confirmation layer
- Indicates institutional participation
MULTI-TIMEFRAME CONFIRMATION:
Trend Bias from Higher Timeframes:
HTF 1 (Trend):
- Default: 1H timeframe
- Uses EMA to determine intermediate trend
- Compares current timeframe EMA to HTF EMA
HTF 2 (Bias):
- Default: 4H timeframe
- Uses 50 EMA for longer-term bias
- Confirms overall market direction
Bias Classifications:
- Bullish Bias: HTF close > HTF 50 EMA AND Current EMA > HTF1 EMA
- Bearish Bias: HTF close < HTF 50 EMA AND Current EMA < HTF1 EMA
- Neutral Bias: Mixed signals between timeframes
EMA Stack Analysis:
- Compares EMA alignment across timeframes
- +1: Bullish stack (lower TF EMA > higher TF EMA)
- -1: Bearish stack (lower TF EMA < higher TF EMA)
- 0: Neutral/crossed
Usage:
- Filters false breakouts
- Confirms trend direction
- Improves trade quality
EMA INTEGRATION:
Dynamic EMA for Trend Reference:
Features:
- Configurable period (default: 20)
- Customizable color and width
- Acts as dynamic support/resistance
- Trend filter for ORB trades
Application:
- Above EMA: Favor long breakouts
- Below EMA: Favor short breakouts
- EMA cross: Potential trend change
- Distance from EMA: Momentum gauge
SMART ALERT SYSTEM:
Quality-Filtered Breakout Notifications:
Alert Types:
1. Standard ORB Breakout
2. High Quality ORB Breakout
Quality Criteria:
- Volume Confirmation: Volume > 1.2x average
- MTF Confirmation: Bias aligned with breakout direction
Standard Alert:
- Basic breakout detection
- Price crosses ORH or ORL
- Icon: 🚀 (bullish) or 🔻 (bearish)
High Quality Alert:
- Both volume AND MTF confirmed
- Stronger probability setup
- Icon: 🚀⭐ (bullish) or 🔻⭐ (bearish)
Alert Information Includes:
- Alert quality rating
- Breakout level and current price
- Volume strength percentage (if enabled)
- MTF bias status (if enabled)
- Recommended action
One Alert Per Bar:
- Prevents alert spam
- Uses flag system to track sent alerts
- Resets on new ORB session
───────────────────────────────────────
HOW TO USE
───────────────────────────────────────
OPENING RANGE SETUP:
Basic Configuration:
1. Select time period for opening range (default: 15 minutes)
2. Choose fill color method (Breakout Direction recommended)
3. Enable historical data display if needed
Custom Range (Advanced):
1. Enable Custom Range toggle
2. Set specific session time (e.g., 0930-0945)
3. Select appropriate timezone
4. Useful for specific market opens (NYSE, LSE, etc.)
LIQUIDITY LEVELS SETUP:
Quick Configuration by Asset:
- Forex: Use default settings (Left=15, Right=5)
- Crypto: Set Left=12, Right=4, Display=7
- Gold: Set HTF=1D, Left=20
HTF Liquidity:
- Purpose: Major support/resistance levels
- Recommended: 4H for day trading, 1D for swing trading
- Use as profit targets or reversal zones
LTF Liquidity:
- Purpose: Entry/exit refinement
- Recommended: 1H for day trading, 4H for swing trading
- Use for position management
Mitigation Settings:
- Wick-based: More sensitive (default)
- Close-based: More conservative
- Remove or Show mitigated levels based on preference
TRADING SESSIONS SETUP:
Enable/Disable Sessions:
- Master toggle for all sessions
- Individual session controls
- Show/hide session names
Session High/Low Lines:
- Enable to see session extremes
- Each session has custom colors
- Useful for range trading
Customization:
- Adjust session times for your broker
- Set timezone to match your location
- Customize colors for visibility
VOLUME ANALYSIS SETUP:
Enable Volume Analysis:
1. Toggle on Volume Analysis
2. Set MA length (20 recommended)
3. Adjust spike multiplier (1.5 typical)
Usage:
- Confirm breakouts with volume
- Identify climactic moves
- Filter false signals
MULTI-TIMEFRAME SETUP:
HTF Selection:
- HTF 1 (Trend): 1H for day trading, 4H for swing
- HTF 2 (Bias): 4H for day trading, 1D for swing
Interpretation:
- Trade only with bias alignment
- Neutral bias: Be cautious
- Bias changes: Potential reversals
EMA SETUP:
Configuration:
- Period: 20 for responsive, 50 for smoother
- Color: Choose contrasting color
- Width: 1-2 for visibility
Usage:
- Filter trades: Long above, Short below
- Dynamic support/resistance reference
- Trend confirmation
ALERT SETUP:
TradingView Alert Creation:
1. Enable alerts in indicator settings
2. Enable ORB Breakout Alerts
3. Right-click chart → Add Alert
4. Select this indicator
5. Choose "Any alert() function call"
6. Configure delivery method (mobile, email, webhook)
Alert Filtering:
- All alerts include quality rating
- High Quality alerts = Volume + MTF confirmed
- Standard alerts = Basic breakout only
───────────────────────────────────────
TRADING STRATEGIES
───────────────────────────────────────
CLASSIC ORB STRATEGY:
Setup:
1. Wait for opening range to complete
2. Price breaks and closes above ORH or below ORL
3. Volume > average (if enabled)
4. MTF bias aligned (if enabled)
Entry:
- Bullish: Buy on break above ORH
- Bearish: Sell on break below ORL
- Consider retest entries for better risk/reward
Stop Loss:
- Bullish: Below ORL or range mid-point
- Bearish: Above ORH or range mid-point
- Adjust based on volatility
Targets:
- Initial: Range width extension (ORH + range width)
- Secondary: HTF liquidity levels
- Final: Session high/low or major support/resistance
ORB + LIQUIDITY CONFLUENCE:
Enhanced Setup:
1. Opening range established
2. HTF liquidity level near or beyond ORH/ORL
3. Breakout occurs with volume
4. Price targets the liquidity level
Entry:
- Enter on ORB breakout
- Target the HTF liquidity level
- Use LTF liquidity for position management
Management:
- Partial profits at ORB + range width
- Move stop to breakeven at LTF liquidity
- Final exit at HTF liquidity sweep
ORB REJECTION STRATEGY (Counter-Trend):
Setup:
1. Price breaks above ORH or below ORL
2. Weak volume (below average)
3. MTF bias opposite to breakout
4. Price closes back inside range
Entry:
- Failed bullish break: Short below ORH
- Failed bearish break: Long above ORL
Stop Loss:
- Beyond the failed breakout level
- Or beyond session extreme
Target:
- Opposite end of opening range
- Range mid-point for partial profit
SESSION-BASED ORB TRADING:
Tokyo Session:
- Typically narrower ranges
- Good for range trading
- Wait for London open breakout
London Session:
- Highest volume and volatility
- Strong ORB setups
- Major liquidity sweeps common
New York Session:
- Strong trending moves
- News-driven volatility
- Good for momentum trades
Sydney Session:
- Quieter conditions
- Suitable for range strategies
- Sets up Tokyo session
EMA-FILTERED ORB:
Rules:
- Only take bullish breaks if price > EMA
- Only take bearish breaks if price < EMA
- Ignore counter-trend breaks
Benefits:
- Reduces false signals
- Aligns with larger trend
- Improves win rate
───────────────────────────────────────
CONFIGURATION GUIDE
───────────────────────────────────────
OPENING RANGE SETTINGS:
Time Period:
- 15 min: Standard for most markets
- 30 min: Wider range, fewer breakouts
- 60 min: For slower markets or swing trades
Custom Range:
- Use for specific market opens
- NYSE: 0930-1000 EST
- LSE: 0800-0830 GMT
- Set timezone to match exchange
Historical Display:
- Enable: See all previous session data
- Disable: Cleaner chart, current session only
LIQUIDITY SETTINGS:
Left Bars (5-30):
- Lower: More frequent, sensitive levels
- Higher: Fewer, more significant levels
- Recommended: 15 for most markets
Right Bars (1-25):
- Confirmation period
- Higher: More reliable, less frequent
- Recommended: 5 for balance
Display Limit (1-20):
- Number of active levels shown
- Higher: More context, busier chart
- Recommended: 7 for clarity
Extension Options:
- Short: Levels visible near formation
- Current: Extended to current bar (recommended)
- Max: Extended indefinitely
VOLUME SETTINGS:
MA Length (5-50):
- Shorter: More responsive to spikes
- Longer: Smoother baseline
- Recommended: 20 for balance
Spike Multiplier (1.0-3.0):
- Lower: More sensitive spike detection
- Higher: Only extreme spikes
- Recommended: 1.5 for day trading
MULTI-TIMEFRAME SETTINGS:
HTF 1 (Trend):
- 5m chart: Use 15m or 1H
- 15m chart: Use 1H or 4H
- 1H chart: Use 4H or 1D
HTF 2 (Bias):
- One level higher than HTF 1
- Provides longer-term context
- Don't use same as HTF 1
EMA SETTINGS:
Length:
- 20: Responsive, more signals
- 50: Smoother, stronger filter
- 200: Long-term trend only
Style:
- Choose contrasting color
- Width 1-2 for visibility
- Match your trading style
───────────────────────────────────────
BEST PRACTICES
───────────────────────────────────────
Chart Timeframe Selection:
- ORB Trading: Use 5m or 15m charts
- Session Review: Use 1H or 4H charts
- Swing Trading: Use 1H or 4H charts
Quality Over Quantity:
- Wait for high-quality alerts (volume + MTF)
- Avoid trading every breakout
- Focus on confluence setups
Risk Management:
- Position size based on range width
- Wider ranges = smaller positions
- Use stop losses always
- Take partial profits at targets
Market Conditions:
- Best results in trending markets
- Reduce position size in choppy conditions
- Consider session overlaps for volatility
- Avoid trading near major news if inexperienced
Continuous Improvement:
- Track win rate by session
- Note which confluence factors work best
- Adjust settings based on market volatility
- Review performance weekly
───────────────────────────────────────
PERFORMANCE OPTIMIZATION
───────────────────────────────────────
This indicator is optimized with:
- max_bars_back declarations for efficient processing
- Conditional calculations based on enabled features
- Proper memory management for drawing objects
- Minimal recalculation on each bar
Best Practices:
- Disable unused features (sessions, MTF, volume)
- Limit historical display to reduce rendering
- Use appropriate timeframe for your strategy
- Clear old drawing objects periodically
───────────────────────────────────────
EDUCATIONAL DISCLAIMER
───────────────────────────────────────
This indicator combines established trading concepts:
- Opening Range Breakout theory (price action)
- Liquidity level detection (pivot analysis)
- Session-based trading (time-of-day patterns)
- Volume analysis (confirmation technique)
- Multi-timeframe analysis (trend alignment)
All calculations use standard technical analysis methods:
- Pivot high/low detection algorithms
- Moving averages for trend and volume
- Session time filtering
- Timeframe security functions
The indicator identifies potential trading setups but does not predict future price movements. Success requires proper application within a complete trading strategy including risk management, position sizing, and market context.
───────────────────────────────────────
USAGE DISCLAIMER
───────────────────────────────────────
This tool is for educational and analytical purposes. Opening Range Breakout trading involves substantial risk. The alert system and quality filters are designed to identify potential setups but do not guarantee profitability. Always conduct independent analysis, use proper risk management, and never risk capital you cannot afford to lose. Past performance does not indicate future results. Trading intraday breakouts requires experience and discipline.
───────────────────────────────────────
CREDITS & ATTRIBUTION
───────────────────────────────────────
ORIGINAL SOURCE:
This indicator builds upon concepts from LuxAlgo's-ORB
SMC Analysis - Fair Value Gaps (Enhanced)SMC Analysis - Fair Value Gaps (Enhanced) Script Summary
Overview
The "SMC Analysis - Fair Value Gaps (Enhanced)" script, written in Pine Script (version 6), is a technical analysis indicator designed for TradingView to identify and visualize Fair Value Gaps (FVGs) on a price chart. It supports both the main timeframe and multiple higher timeframes (MTF) for comprehensive market analysis. FVGs are price gaps formed by a three-candle pattern, indicating potential areas of market inefficiency where price may return to fill the gap.
Key Features
FVG Detection:
Identifies bullish FVGs: Occur when the high of a candle two bars prior is lower than the low of the current candle, with the middle candle being bullish (close > open).
Identifies bearish FVGs: Occur when the low of a candle two bars prior is higher than the high of the current candle, with the middle candle being bearish (close < open).
Visualizes FVGs as colored boxes on the chart (green for bullish, red for bearish).
Mitigation Tracking:
Tracks when FVGs are touched (price overlaps the gap range) or mitigated (price fully closes the gap).
Strict Mode: Marks an FVG as mitigated when price touches the gap range.
Normal Mode: Requires a full breakthrough (price crossing the gap’s bottom for bullish FVGs or top for bearish FVGs) for mitigation.
Optionally converts FVG box borders to dashed lines and increases transparency when partially touched.
Multi-Timeframe (MTF) Support:
Analyzes FVGs on three user-defined higher timeframes (default: 15m, 60m, 240m).
Displays MTF FVGs with distinct labels and slightly more transparent colors.
Ensures no duplicate processing of MTF bars to maintain performance.
Customization Options:
FVG Length: Adjustable duration for how long FVGs are displayed (default: 20 bars).
Show/Hide FVGs: Toggle visibility for main timeframe and each MTF.
Color Customization: User-defined colors for bullish and bearish FVGs (default: green and red).
Display Options: Toggle for showing dashed lines after partial touches and strict mitigation mode.
Performance Optimization:
Limits the number of displayed boxes (50 for main timeframe, 20 per MTF) to prevent performance issues.
Automatically removes older boxes to maintain a clean chart.
Functionality
Visualization: Draws boxes around detected FVGs, with customizable colors and text labels ("FVG" for main timeframe, "FVG " for MTF).
Dynamic Updates: Extends or terminates FVG boxes based on mitigation status and user settings.
Efficient Storage: Uses arrays to manage FVG data (boxes, tops, bottoms, indices, mitigation status, and touch status) separately for main and MTF analyses.
Use Case
This indicator is designed for traders using Smart Money Concepts (SMC) to identify areas of market inefficiency (FVGs) for potential price reversals or continuations. The MTF support allows analysis across different timeframes, aiding in confirming trends or spotting higher-timeframe support/resistance zones.
SuperTrend Cyan — Split ST & Triple Bands (A/B/C)SuperTrend Cyan — Split ST & Triple Bands (A/B/C)
✨ Concept:
The SuperTrend Cyan indicator expands the classical SuperTrend logic into a split-line + triple-band visualization for clearer structure and volatility mapping.
Instead of a single ATR-based line, this tool separates SuperTrend direction from volatility envelopes (A/B/C), providing a layered view of both regime and range compression.
✨ The design goal:
Preserve the simplicity of SuperTrend
Add volatility context via multi-band envelopes
Provide a compact MTF (Multi-Timeframe) summary for broader trend alignment
✨ How It Works
1. SuperTrend Core (Active & Opposite Lines)
Uses ATR-based bands (Factor × ATR-Length).
Active SuperTrend is plotted according to current regime.
Opposite SuperTrend (optional) shows potential reversal threshold.
2. Triple Band System (A/B/C)
Each band (A, B, C) scales from the median price (hl2) by different ATR multipliers.
A: Outer band (wider, long-range context)
B: Inner band (mid-range activity)
C: Core band (closest to price, short-term compression)
Smoothness can be controlled with EMA.
Uptrend fills are lime-toned, downtrend fills are red-toned, with adjustable opacity (gap intensity).
3. Automatic Directional Switch
When the regime flips from up → down (or vice versa), the overlay automatically switches between lower and upper bands for a clean transition.
4. Multi-Timeframe SuperTrend Table
Displays SuperTrend direction across 5m, 15m, 1h, 4h, and 1D frames.
Green ▲ = Uptrend, Red ▼ = Downtrend.
Useful for checking cross-timeframe trend alignment.
✨ How to Read It
Green SuperTrend + Lime Bands
- Uptrend regime; volatility expanding upward
Red SuperTrend + Red Bands
- Downtrend regime; volatility expanding downward
Narrow gaps (A–C)
- Low volatility / compression (potential squeeze)
Wide gaps
- High volatility / active trend phase
Opposite ST line close to price
- Early warning for regime transition
✨ Practical Use
Identify trend direction (SuperTrend color & line position).
Assess volatility conditions (band width and gap transparency).
Watch for MTF alignment: consistent up/down signals across 1h–4h–1D = strong structural trend.
Combine with momentum indicators (e.g., RSI, DFI, PCI) for confirmation of trend maturity or exhaustion.
✨ Customization Tips
ST Factor / ATR Length
- Adjust sensitivity of SuperTrend direction changes
Band ATR Length
- Controls overall smoothness of volatility envelopes
Band Multipliers (A/B/C)
- Define how wide each volatility band extends
Gap Opacity
- Affects visual contrast between layers
MTF Table
- Enable/disable multi-timeframe display
✨ Educational Value
This script visualizes the interaction between trend direction (SuperTrend) and volatility envelopes, helping traders understand how price reacts within layered ATR zones.
It also introduces a clean MTF (multi-timeframe) perspective — ideal for discretionary and system traders alike.
✨ Disclaimer
This indicator is provided for educational and research purposes only.
It does not constitute financial advice or a trading signal.
Use at your own discretion and always confirm with additional tools.
───────────────────────────────
📘 한국어 설명 (Korean translation below)
───────────────────────────────
✨개념
SuperTrend Cyan 지표는 기존의 SuperTrend를 확장하여,
추세선 분리(Split Line) + 3중 밴드 시스템(Triple Bands) 으로
시장의 구조적 흐름과 변동성 범위를 동시에 시각화합니다.
단순한 SuperTrend의 강점을 유지하면서도,
ATR 기반의 A/B/C 밴드를 통해 변동성 압축·확장 구간을 직관적으로 파악할 수 있습니다.
✨ 작동 방식
1. SuperTrend 코어 (활성/반대 라인)
ATR×Factor를 기반으로 추세선을 계산합니다.
현재 추세 방향에 따라 활성 라인이 표시되고, “Show Opposite” 옵션을 켜면 반대편 경계선도 함께 보입니다.
2. 트리플 밴드 시스템 (A/B/C)
hl2(중간값)를 기준으로 ATR 배수에 따라 세 개의 밴드를 계산합니다.
A: 외곽 밴드 (가장 넓고 장기 구조 반영)
B: 중간 밴드 (중기적 움직임)
C: 코어 밴드 (가격에 가장 근접, 단기 변동성 반영)
EMA 스무딩으로 부드럽게 조정 가능.
업트렌드 구간은 라임색, 다운트렌드는 빨간색 음영으로 표시됩니다.
3. 자동 전환 시스템
추세가 전환될 때(Up ↔ Down), 밴드 오버레이도 자동으로 교체되어 깔끔한 시각적 구조를 유지합니다.
4. MTF SuperTrend 테이블
5m / 15m / 1h / 4h / 1D 프레임별 SuperTrend 방향을 표시합니다.
초록 ▲ = 상승, 빨강 ▼ = 하락.
복수 타임프레임 정렬 확인용으로 유용합니다.
✨ 해석 방법
초록 SuperTrend + 라임 밴드
- 상승 추세 및 확장 구간
빨강 SuperTrend + 레드 밴드
- 하락 추세 및 확장 구간
밴드 폭이 좁음
- 변동성 축소 (스퀴즈)
밴드 폭이 넓음
- 변동성 확장, 추세 강화
반대선이 근접
- 추세 전환 가능성 높음
✨ 활용 방법
SuperTrend 색상으로 추세 방향을 확인
A/B/C 밴드 폭으로 변동성 수준을 판단
MTF 테이블을 통해 복수 타임프레임 정렬 여부 확인
RSI, DFI, PCI 등 다른 지표와 함께 활용 시, 추세 피로·모멘텀 변화를 조기에 파악 가능
✨ 교육적 가치
이 스크립트는 추세 구조(SuperTrend) 와 변동성 레이어(ATR Bands) 의 상호작용을
시각적으로 학습하기 위한 교육용 지표입니다.
또한, MTF 구조를 통해 시장의 “위계적 정렬(hierarchical alignment)”을 쉽게 인식할 수 있습니다.
✨ 면책
이 지표는 교육 및 연구 목적으로만 제공됩니다.
투자 판단의 책임은 사용자 본인에게 있으며, 본 지표는 매매 신호를 보장하지 않습니다.






















