FvgCalculations█ OVERVIEW
This library provides the core calculation engine for identifying Fair Value Gaps (FVGs) across different timeframes and for processing their interaction with price. It includes functions to detect FVGs on both the current chart and higher timeframes, as well as to check for their full or partial mitigation.
█ CONCEPTS
The library's primary functions revolve around the concept of Fair Value Gaps and their lifecycle.
Fair Value Gap (FVG) Identification
An FVG, or imbalance, represents a price range where buying or selling pressure was significant enough to cause a rapid price movement, leaving an "inefficiency" in the market. This library identifies FVGs based on three-bar patterns:
Bullish FVG: Forms when the low of the current bar (bar 3) is higher than the high of the bar two periods prior (bar 1). The FVG is the space between the high of bar 1 and the low of bar 3.
Bearish FVG: Forms when the high of the current bar (bar 3) is lower than the low of the bar two periods prior (bar 1). The FVG is the space between the low of bar 1 and the high of bar 3.
The library provides distinct functions for detecting FVGs on the current (Low Timeframe - LTF) and specified higher timeframes (Medium Timeframe - MTF / High Timeframe - HTF).
FVG Mitigation
Mitigation refers to price revisiting an FVG.
Full Mitigation: An FVG is considered fully mitigated when price completely closes the gap. For a bullish FVG, this occurs if the current low price moves below or touches the FVG's bottom. For a bearish FVG, it occurs if the current high price moves above or touches the FVG's top.
Partial Mitigation (Entry/Fill): An FVG is partially mitigated when price enters the FVG's range but does not fully close it. The library tracks the extent of this fill. For a bullish FVG, if the current low price enters the FVG from above, that low becomes the new effective top of the remaining FVG. For a bearish FVG, if the current high price enters the FVG from below, that high becomes the new effective bottom of the remaining FVG.
FVG Interaction
This refers to any instance where the current bar's price range (high to low) touches or crosses into the currently unfilled portion of an active (visible and not fully mitigated) FVG.
Multi-Timeframe Data Acquisition
To detect FVGs on higher timeframes, specific historical bar data (high, low, and time of bars at indices and relative to the higher timeframe's last completed bar) is required. The requestMultiTFBarData function is designed to fetch this data efficiently.
█ CALCULATIONS AND USE
The functions in this library are typically used in a sequence to manage FVGs:
1. Data Retrieval (for MTF/HTF FVGs):
Call requestMultiTFBarData() with the desired higher timeframe string (e.g., "60", "D").
This returns a tuple of htfHigh1, htfLow1, htfTime1, htfHigh3, htfLow3, htfTime3.
2. FVG Detection:
For LTF FVGs: Call detectFvg() on each confirmed bar. It uses high , low, low , and high along with barstate.isconfirmed.
For MTF/HTF FVGs: Call detectMultiTFFvg() using the data obtained from requestMultiTFBarData().
Both detection functions return an fvgObject (defined in FvgTypes) if an FVG is found, otherwise na. They also can classify FVGs as "Large Volume" (LV) if classifyLV is true and the FVG size (top - bottom) relative to the tfAtr (Average True Range of the respective timeframe) meets the lvAtrMultiplier.
3. FVG State Updates (on each new bar for existing FVGs):
First, check for overall price interaction using fvgInteractionCheck(). This function determines if the current bar's high/low has touched or entered the FVG's currentTop or currentBottom.
If interaction occurs and the FVG is not already mitigated:
Call checkMitigation() to determine if the FVG has been fully mitigated by the current bar's currentHigh and currentLow. If true, the FVG's isMitigated status is updated.
If not fully mitigated, call checkPartialMitigation() to see if the price has further entered the FVG. This function returns the newLevel to which the FVG has been filled (e.g., currentLow for a bullish FVG, currentHigh for bearish). This newLevel is then used to update the FVG's currentTop or currentBottom.
The calling script (e.g., fvgMain.c) is responsible for storing and managing the array of fvgObject instances and passing them to these update functions.
█ NOTES
Bar State for LTF Detection: The detectFvg() function relies on barstate.isconfirmed to ensure FVG detection is based on closed bars, preventing FVGs from being detected prematurely on the currently forming bar.
Higher Timeframe Data (lookahead): The requestMultiTFBarData() function uses lookahead = barmerge.lookahead_on. This means it can access historical data from the higher timeframe that corresponds to the current bar on the chart, even if the higher timeframe bar has not officially closed. This is standard for multi-timeframe analysis aiming to plot historical HTF data accurately on a lower timeframe chart.
Parameter Typing: Functions like detectMultiTFFvg and detectFvg infer the type for boolean (classifyLV) and numeric (lvAtrMultiplier) parameters passed from the main script, while explicitly typed series parameters (like htfHigh1, currentAtr) expect series data.
fvgObject Dependency: The FVG detection functions return fvgObject instances, and fvgInteractionCheck takes an fvgObject as a parameter. This UDT is defined in the FvgTypes library, making it a dependency for using FvgCalculations.
ATR for LV Classification: The tfAtr (for MTF/HTF) and currentAtr (for LTF) parameters are expected to be the Average True Range values for the respective timeframes. These are used, if classifyLV is enabled, to determine if an FVG's size qualifies it as a "Large Volume" FVG based on the lvAtrMultiplier.
MTF/HTF FVG Appearance Timing: When displaying FVGs from a higher timeframe (MTF/HTF) on a lower timeframe (LTF) chart, users might observe that the most recent MTF/HTF FVG appears one LTF bar later compared to its appearance on a native MTF/HTF chart. This is an expected behavior due to the detection mechanism in `detectMultiTFFvg`. This function uses historical bar data from the MTF/HTF (specifically, data equivalent to `HTF_bar ` and `HTF_bar `) to identify an FVG. Therefore, all three bars forming the FVG on the MTF/HTF must be fully closed and have shifted into these historical index positions relative to the `request.security` call from the LTF chart before the FVG can be detected and displayed on the LTF. This ensures that the MTF/HTF FVG is identified based on confirmed, closed bars from the higher timeframe.
█ EXPORTED FUNCTIONS
requestMultiTFBarData(timeframe)
Requests historical bar data for specific previous bars from a specified higher timeframe.
It fetches H , L , T (for the bar before last) and H , L , T (for the bar three periods prior)
from the requested timeframe.
This is typically used to identify FVG patterns on MTF/HTF.
Parameters:
timeframe (simple string) : The higher timeframe to request data from (e.g., "60" for 1-hour, "D" for Daily).
Returns: A tuple containing: .
- htfHigh1 (series float): High of the bar at index 1 (one bar before the last completed bar on timeframe).
- htfLow1 (series float): Low of the bar at index 1.
- htfTime1 (series int) : Time of the bar at index 1.
- htfHigh3 (series float): High of the bar at index 3 (three bars before the last completed bar on timeframe).
- htfLow3 (series float): Low of the bar at index 3.
- htfTime3 (series int) : Time of the bar at index 3.
detectMultiTFFvg(htfHigh1, htfLow1, htfTime1, htfHigh3, htfLow3, htfTime3, tfAtr, classifyLV, lvAtrMultiplier, tfType)
Detects a Fair Value Gap (FVG) on a higher timeframe (MTF/HTF) using pre-fetched bar data.
Parameters:
htfHigh1 (float) : High of the first relevant bar (typically high ) from the higher timeframe.
htfLow1 (float) : Low of the first relevant bar (typically low ) from the higher timeframe.
htfTime1 (int) : Time of the first relevant bar (typically time ) from the higher timeframe.
htfHigh3 (float) : High of the third relevant bar (typically high ) from the higher timeframe.
htfLow3 (float) : Low of the third relevant bar (typically low ) from the higher timeframe.
htfTime3 (int) : Time of the third relevant bar (typically time ) from the higher timeframe.
tfAtr (float) : ATR value for the higher timeframe, used for Large Volume (LV) FVG classification.
classifyLV (bool) : If true, FVGs will be assessed to see if they qualify as Large Volume.
lvAtrMultiplier (float) : The ATR multiplier used to define if an FVG is Large Volume.
tfType (series tfType enum from no1x/FvgTypes/1) : The timeframe type (e.g., types.tfType.MTF, types.tfType.HTF) of the FVG being detected.
Returns: An fvgObject instance if an FVG is detected, otherwise na.
detectFvg(classifyLV, lvAtrMultiplier, currentAtr)
Detects a Fair Value Gap (FVG) on the current (LTF - Low Timeframe) chart.
Parameters:
classifyLV (bool) : If true, FVGs will be assessed to see if they qualify as Large Volume.
lvAtrMultiplier (float) : The ATR multiplier used to define if an FVG is Large Volume.
currentAtr (float) : ATR value for the current timeframe, used for LV FVG classification.
Returns: An fvgObject instance if an FVG is detected, otherwise na.
checkMitigation(isBullish, fvgTop, fvgBottom, currentHigh, currentLow)
Checks if an FVG has been fully mitigated by the current bar's price action.
Parameters:
isBullish (bool) : True if the FVG being checked is bullish, false if bearish.
fvgTop (float) : The top price level of the FVG.
fvgBottom (float) : The bottom price level of the FVG.
currentHigh (float) : The high price of the current bar.
currentLow (float) : The low price of the current bar.
Returns: True if the FVG is considered fully mitigated, false otherwise.
checkPartialMitigation(isBullish, currentBoxTop, currentBoxBottom, currentHigh, currentLow)
Checks for partial mitigation of an FVG by the current bar's price action.
It determines if the price has entered the FVG and returns the new fill level.
Parameters:
isBullish (bool) : True if the FVG being checked is bullish, false if bearish.
currentBoxTop (float) : The current top of the FVG box (this might have been adjusted by previous partial fills).
currentBoxBottom (float) : The current bottom of the FVG box (similarly, might be adjusted).
currentHigh (float) : The high price of the current bar.
currentLow (float) : The low price of the current bar.
Returns: The new price level to which the FVG has been filled (e.g., currentLow for a bullish FVG).
Returns na if no new partial fill occurred on this bar.
fvgInteractionCheck(fvg, highVal, lowVal)
Checks if the current bar's price interacts with the given FVG.
Interaction means the price touches or crosses into the FVG's
current (possibly partially filled) range.
Parameters:
fvg (fvgObject type from no1x/FvgTypes/1) : The FVG object to check.
Its isMitigated, isVisible, isBullish, currentTop, and currentBottom fields are used.
highVal (float) : The high price of the current bar.
lowVal (float) : The low price of the current bar.
Returns: True if price interacts with the FVG, false otherwise.
Mitigation
Price Action Volumetric Order Blocks [UAlgo]"Price Action Volumetric Order Blocks" indicator aims to identify significant price zones in the market based on a combination of price action and volume analysis. It utilizes the concept of "Order Blocks," which are areas on the chart where large orders are believed to have been placed, influencing price behavior. By analyzing price swings and volume activity, the indicator attempts to highlight potential support and resistance levels.
🔶 Key Features
Swing Length: This input allows you to adjust the timeframe used to identify price swings for order block detection. A longer swing length will focus on larger timeframes and potentially capture stronger order blocks.
Show Last X Order Blocks: This controls the number of order blocks displayed on the chart. You can choose to visualize a specific number of the most recent order blocks.
Violation Check: This setting determines how the indicator identifies potential order block violations. You can choose between "Wick" or "Close" violations. A "Wick" violation occurs when the price (wick) extends beyond the order block boundaries, while a "Close" violation signifies that the closing price breaches the order block.
Hide Overlap: This option allows you to manage the display of overlapping order blocks. If set to "True," only non-overlapping order blocks will be shown, potentially offering a clearer visualization.
Colors: You can customize the color scheme for bullish (upward) and bearish (downward) order blocks to enhance visual clarity on the chart.
🔶 Interpreting the Indicator
Order Blocks: The teal-colored boxes represent bullish order blocks, indicating areas of demand where buying pressure is likely to be strong. Red-colored boxes represent bearish order blocks, indicating areas of supply where selling pressure is likely to be dominant. These zones often signal potential reversal points or consolidation areas.
Strength Calculations: The indicator calculates the relative strength of bullish and bearish blocks based on volume. A higher bullish strength indicates stronger buying pressure, while higher bearish strength suggests more selling pressure. Traders can use this information to gauge the strength of a price level and predict future price movements.
Market Structure Lines: The indicator displays horizontal lines to depict the current market structure, labeled as "MSB" (Market Sell Balance) or "BOS" (Break of Structure). These lines can help visualize the prevailing trend direction.
Order Block Violations: When a price wick or close breaches an order block (depending on the chosen violation type), the corresponding order block visualization is removed from the chart. This can signify a potential weakening of the identified support or resistance zone.
🔶 Disclaimer
Use with Caution: This indicator is provided for educational and informational purposes only and should not be considered as financial advice. Users should exercise caution and perform their own analysis before making trading decisions based on the indicator's signals.
Not Financial Advice: The information provided by this indicator does not constitute financial advice, and the creator (UAlgo) shall not be held responsible for any trading losses incurred as a result of using this indicator.
Backtesting Recommended: Traders are encouraged to backtest the indicator thoroughly on historical data before using it in live trading to assess its performance and suitability for their trading strategies.
Risk Management: Trading involves inherent risks, and users should implement proper risk management strategies, including but not limited to stop-loss orders and position sizing, to mitigate potential losses.
No Guarantees: The accuracy and reliability of the indicator's signals cannot be guaranteed, as they are based on historical price data and past performance may not be indicative of future results.
Fair Value Gaps Setup 01 [TradingFinder] FVG Absorption + CHoCH🔵 Introduction
🟣 Market Structures
Market structures exhibit a fractal and nested nature, which leads us to classify them into internal (minor) and external (major) categories. Definitions of market structure vary, with different methodologies such as Smart Money and ICT offering distinct interpretations.
To identify market structure, the initial step involves examining key highs and lows. An uptrend is characterized by successive highs and lows that are higher than their predecessors. Conversely, a downtrend is marked by successive lows and highs that are lower than their previous counterparts.
🟣 Market Trends and Movements
Market trends consist of two primary types of movements :
Impulsive Movements : These movements align with the main trend and are characterized by high strength and momentum.
Corrective Movements : These movements counter the main trend and are marked by lower strength and momentum.
🟣 Break of Structure (BOS)
In a downtrend, a Break of Structure (BOS) occurs when the price falls below the previous low and establishes a new low (LL). In an uptrend, a BOS, also known as a Market Structure Break (MSB), happens when the price rises above the last high.
To confirm a trend, at least one BOS is necessary, which requires the price to close at least one candle beyond the previous high or low.
🟣 Change of Character (CHOCH)
Change of Character (CHOCH) is a crucial concept in market structure analysis, indicating a shift in trend. A trend concludes with a CHOCH, also referred to as a Market Structure Shift (MSS).
For example, in a downtrend, the price continues to drop with BOS, showcasing the trend's strength. However, when the price rises and exceeds the last high, a CHOCH occurs, signaling a potential transition from a downtrend to an uptrend.
It is essential to note that a CHOCH does not immediately indicate a buy trade. Instead, it is prudent to wait for a BOS in the upward direction to confirm the uptrend. Unlike BOS, a CHOCH confirmation does not require a candle to close; merely breaking the previous high or low with the candle's wick is sufficient.
🟣 Spike | Inefficiency | Imbalance
All these terms mean fast price movement in the shortest possible time.
🟣 Fair Value Gap (FVG)
To pinpoint the "Fair Value Gap" (FVG) on a chart, a detailed candle-by-candle analysis is necessary. This process involves focusing on candles with substantial bodies and evaluating them in relation to the candles immediately before and after them.
Here are the steps :
Identify the Central Candle : Look for a candle with a large body.
Examine Adjacent Candles : The candles before and after this central candle should have long shadows, and their bodies must not overlap with the body of the central candle.
Determine the FVG Range : The distance between the shadows of the first and third candles defines the FVG range.
This method helps in accurately identifying the Fair Value Gap, which is crucial for understanding market inefficiencies and potential price movements.
🟣 Setup
This setup is based on Market Structure and FVG. After a change of character and the formation of FVG in the last lag of the price movement, we are looking for trading positions in the price pullback.
Bullish Setup :
Bearish Setup :
🔵 How to Use
After forming the setup, you can enter the trade using a pending order or after receiving confirmation. To increase the probability of success, you can adjust the pivot period market structure settings or modify the market movement coefficient in the formation leg of the FVG.
Bullish Setup :
Bearish Setup :
🔵 Setting
Pivot Period of Market Structure Detector :
This parameter allows you to configure the zigzag period based on pivots. Adjusting this helps in accurately detecting order blocks.
Show major Bullish ChoCh Lines :
You can toggle the visibility of the Demand Main Zone and "ChoCh" Origin, and customize their color as needed.
Show major Bearish ChoCh Lines :
Similar to the Demand Main Zone, you can control the visibility and color of the Supply Main Zone and "ChoCh" Origin.
FVG Detector Multiplier Factor :
This feature lets you adjust the size of the moves forming the Fair Value Gaps (FVGs) using the Average True Range (ATR). The default value is 1, suitable for identifying most setups. Adjust this value based on the specific symbol and market for optimal results.
FVG Validity Period :
This parameter defines the validity period of an FVG in terms of the number of candles. By default, an FVG remains valid for up to 15 candles, but you can adjust this period as needed.
Mitigation Level FVG :
This setting establishes the basic level of an FVG. When the price reaches this level, the FVG is considered mitigated.
Level in Low-Risk Zone :
This feature aims to reduce risk by dividing the FVG into two equal areas: "Premium" (upper area) and "Discount" (lower area). For lower risk, ensure that "Demand FVG" is in the "Discount" area and "Supply FVG" in the "Premium" area. This feature is off by default.
Show or Hide :
Given the potential abundance of setups, displaying all on the chart can be overwhelming. By default, only the last setup is shown, but you can enable the option to view all setups.
Alert Settings :
On / Off : Toggle alerts on or off.
Message Frequency : Determine how often alerts are triggered.
Options include :
"All" (alerts every time the function is called)
"Once Per Bar" (alerts only on the first call within the bar)
"Once Per Bar Close" (alerts only at the last script execution of the real-time bar upon closing)
The default setting is "Once Per Bar".
Show Alert Time by Time Zone : Set the alert time based on your preferred time zone, such as "UTC-4" for New York time. The default is "UTC".
Display More Info : Optionally show additional details like the price range of the order blocks and the date, hour, and minute in the alert message. Set this to "Off" if you prefer not to receive this information.
Fair Value Gaps Mitigation Oscillator [LuxAlgo]The Fair Value Gaps Mitigation Oscillator is an oscillator based on the traditional Fair Value Gaps (FVGs) imbalances. The oscillator displays the current total un-mitigated values for the number of FVGs chosen by the user.
The indicator also displays each New FVG as a bar representing the current ratio of the New FVG in relation to the current un-mitigated total for its direction.
🔶 USAGE
When an FVG forms, it is often interpreted as strong market sentiment in the direction of the gap. For example, an upward FVG during an uptrend is typically seen as a confirmation of the strength and continuation of the trend, as it indicates that buyers are willing to purchase at higher prices without much resistance, suggesting strong demand and positive sentiment.
By analyzing the mitigation (or lack thereof), we can visualize the increase of directional strength in a trend. This is where the proposed oscillator is useful.
🔶 DETAILS
The oscillator's values are expressed as Percentages (%). Each FVG is allocated 100% of the total of its width with a max potential value of 100 and minimum potential value of 0.
Based on the "FVG Lookback" Input, the FVGs are scaled to fit within the range of +1 to -1. Using a higher "FVG Lookback" value will allow you to get indications of longer-term trends.
A higher value of the normalized bullish FVG areas suggest a stronger and cleaner uptrend, while lower values of the bearish the normalized bullish FVG areas suggest a stronger and cleaner downtrend.
+1 or -1 indicates that there is a Full Lookback of FVGs, and each one is fully un-mitigated, and the opposite direction of FVGs is entirely Mitigated.
When the price closes over/under or within an FVG it begins to get mitigated, when this happens the % of mitigation is subtracted from the total.
When a New FVG is formed, a Histogram bar is created representing the ratio of the current FVG's width to the total width off all un-mitigated FVGs.
The entire bar represents 100% of total un-mitigated FVG Width.
The filled area represents the current FVG's width relative to the whole.
A 50% hash mark is also displayed for reference.
🔶 SETTINGS
FVG Lookback - Determines the number of FVGs (Bullish and Bearish Pairs) to keep in memory for analysis.