LyroMAsLibrary "LyroMAs"
Custom Dynamic MA's that allow a dynamic calculation beginning from the first bar\ use getDynamicLength(maxLength) =>\\tmath.min(maxLength, bar_index + 1) \as length
SMA(sourceData, maxLength)
Dynamic SMA
Parameters:
sourceData (float)
maxLength (int)
EMA(src, length)
Dynamic EMA
Parameters:
src (float)
length (int)
DEMA(src, length)
Dynamic DEMA
Parameters:
src (float)
length (int)
TEMA(src, length)
Dynamic TEMA
Parameters:
src (float)
length (int)
WMA(src, length)
Dynamic WMA
Parameters:
src (float)
length (int)
HMA(src, length)
Dynamic HMA
Parameters:
src (float)
length (int)
VWMA(src, volsrc, length)
Dynamic VWMA
Parameters:
src (float)
volsrc (float)
length (int)
SMMA(src, length)
Dynamic SMMA
Parameters:
src (float)
length (int)
LSMA(src, length, offset)
Dynamic LSMA
Parameters:
src (float)
length (int)
offset (int)
RMA(src, length)
Dynamic RMA
Parameters:
src (float)
length (int)
ALMA(src, length, offset_sigma, sigma)
Dynamic ALMA
Parameters:
src (float)
length (int)
offset_sigma (float)
sigma (float)
ZLSMA(src, length)
Dynamic Zlsma
Parameters:
src (float)
length (int)
Thank you to @QuantraSystems for the dynamic codes.
Techindicator
PeekLevelLibrary "PeekLevel"
init()
run(state, zigZagPeriod, rsi, rsiMA)
Parameters:
state (ZigZagState)
zigZagPeriod (int)
rsi (float)
rsiMA (float)
method stableLevel(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method secondStableLevel(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method stableLevelTarget(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method secondStableLevelTarget(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method stableLevelRSI(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method secondStableLevelRSI(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method lastLevelRSI(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method lastLevel(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method lastLevelIndex(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method lastLevelTarget(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method lastLevelRSISignal(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
method lastPriceJump(state, direction)
Namespace types: ZigZagState
Parameters:
state (ZigZagState)
direction (int)
ZigZagState
Fields:
levelPrices (array)
levelRSI (array)
levelTarget (array)
levelTypes (array)
levelIndices (array)
levelRSISignal (array)
levelPriceJumps (array)
lastLevelPrice (series float)
lastLevelType (series int)
lastLevelIndex (series int)
lastLevelRSI (series float)
numUndirectedLevels (series int)
zigZagDirection (series int)
FvgObject█ OVERVIEW
This library provides a suite of methods designed to manage the visual representation and lifecycle of Fair Value Gap (FVG) objects on a Pine Script™ chart. It extends the `fvgObject` User-Defined Type (UDT) by attaching object-oriented functionalities for drawing, updating, and deleting FVG-related graphical elements. The primary goal is to encapsulate complex drawing logic, making the main indicator script cleaner and more focused on FVG detection and state management.
█ CONCEPTS
This library is built around the idea of treating each Fair Value Gap as an "object" with its own visual lifecycle on the chart. This is achieved by defining methods that operate directly on instances of the `fvgObject` UDT.
Object-Oriented Approach for FVGs
Pine Script™ v6 introduced the ability to define methods for User-Defined Types (UDTs). This library leverages this feature by attaching specific drawing and state management functions (methods) directly to the `fvgObject` type. This means that instead of calling global functions with an FVG object as a parameter, you call methods *on* the FVG object itself (e.g., `myFvg.updateDrawings(...)`). This approach promotes better code organization and a more intuitive way to interact with FVG data.
FVG Visual Lifecycle Management
The core purpose of this library is to manage the complete visual journey of an FVG on the chart. This lifecycle includes:
Initial Drawing: Creating the first visual representation of a newly detected FVG, including its main box and optionally its midline and labels.
State Updates & Partial Fills: Modifying the FVG's appearance as it gets partially filled by price. This involves drawing a "mitigated" portion of the box and adjusting the `currentTop` or `currentBottom` of the remaining FVG.
Full Mitigation & Tested State: Handling how an FVG is displayed once fully mitigated. Depending on user settings, it might be hidden, or its box might change color/style to indicate it has been "tested." Mitigation lines can also be managed (kept or deleted).
Midline Interaction: Visually tracking if the price has touched the FVG's 50% equilibrium level (midline).
Visibility Control: Dynamically showing or hiding FVG drawings based on various criteria, such as user settings (e.g., hide mitigated FVGs, timeframe-specific visibility) or external filters (e.g., proximity to current price).
Deletion: Cleaning up all drawing objects associated with an FVG when it's no longer needed or when settings dictate its removal.
Centralized Drawing Logic
By encapsulating all drawing-related operations within the methods of this library, the main indicator script is significantly simplified. The main script can focus on detecting FVGs and managing their state (e.g., in arrays), while delegating the complex task of rendering and updating them on the chart to the methods herein.
Interaction with `fvgObject` and `drawSettings` UDTs
All methods within this library operate on an instance of the `fvgObject` UDT. This `fvgObject` holds not only the FVG's price/time data and state (like `isMitigated`, `currentTop`) but also the IDs of its associated drawing elements (e.g., `boxId`, `midLineId`).
The appearance of these drawings (colors, styles, visibility, etc.) is dictated by a `drawSettings` UDT instance, which is passed as a parameter to most drawing-related methods. This `drawSettings` object is typically populated from user inputs in the main script, allowing for extensive customization.
Stateful Drawing Object Management
The library's methods manage Pine Script™ drawing objects (boxes, lines, labels) by storing their IDs within the `fvgObject` itself (e.g., `fvgObject.boxId`, `fvgObject.mitigatedBoxId`, etc.). Methods like `draw()` create these objects and store their IDs, while methods like `updateDrawings()` modify them, and `deleteDrawings()` removes them using these stored IDs.
Drawing Optimization
The `updateDrawings()` method, which is the most comprehensive drawing management function, incorporates optimization logic. It uses `prev_*` fields within the `fvgObject` (e.g., `prevIsMitigated`, `prevCurrentTop`) to store the FVG's state from the previous bar. By comparing the current state with the previous state, and also considering changes in visibility or relevant drawing settings, it can avoid redundant and performance-intensive drawing operations if nothing visually significant has changed for that FVG.
█ METHOD USAGE AND WORKFLOW
The methods in this library are designed to be called in a logical sequence as an FVG progresses through its lifecycle. A crucial prerequisite for all visual methods in this library is a properly populated `drawSettings` UDT instance, which dictates every aspect of an FVG's appearance, from colors and styles to visibility and labels. This `settings` object must be carefully prepared in the main indicator script, typically based on user inputs, before being passed to these methods.
Here’s a typical workflow within a main indicator script:
1. FVG Instance Creation (External to this library)
An `fvgObject` instance is typically created by functions in another library (e.g., `FvgCalculations`) when a new FVG pattern is identified. This object will have its core properties (top, bottom, startTime, isBullish, tfType) initialized.
2. Initial Drawing (`draw` method)
Once a new `fvgObject` is created and its initial visibility is determined:
Call the `myFvg.draw(settings)` method on the new FVG object.
`settings` is an instance of the `drawSettings` UDT, containing all relevant visual configurations.
This method draws the primary FVG box, its midline (if enabled in `settings`), and any initial labels. It also initializes the `currentTop` and `currentBottom` fields of the `fvgObject` if they are `na`, and stores the IDs of the created drawing objects within the `fvgObject`.
3. Per-Bar State Updates & Interaction Checks
On each subsequent bar, for every active `fvgObject`:
Interaction Check (External Logic): It's common to first use logic (e.g., from `FvgCalculations`' `fvgInteractionCheck` function) to determine if the current bar's price interacts with the FVG.
State Field Updates (External Logic): Before calling the `FvgObjectLib` methods below, ensure that your `fvgObject`'s state fields (such as `isMitigated`, `currentTop`, `currentBottom`, `isMidlineTouched`) are updated using the current bar's price data and relevant functions from other libraries (e.g., `FvgCalculations`' `checkMitigation`, `checkPartialMitigation`, etc.). This library's methods render the FVG based on these pre-updated state fields.
If interaction occurs and the FVG is not yet fully mitigated:
Full Mitigation Update (`updateMitigation` method): Call `myFvg.updateMitigation(high, low)`. This method updates `myFvg.isMitigated` and `myFvg.mitigationTime` if full mitigation occurs, based on the interaction determined by external logic.
Partial Fill Update (`updatePartialFill` method): If not fully mitigated, call `myFvg.updatePartialFill(high, low, settings)`. This method updates `myFvg.currentTop` or `myFvg.currentBottom` and adjusts drawings to show the filled portion, again based on prior interaction checks and fill level calculations.
Midline Touch Check (`checkMidlineTouch` method): Call `myFvg.checkMidlineTouch(high, low)`. This method updates `myFvg.isMidlineTouched` if the price touches the FVG's 50% level.
4. Comprehensive Visual Update (`updateDrawings` method)
After the FVG's state fields have been potentially updated by external logic and the methods in step 3:
Call `myFvg.updateDrawings(isVisibleNow, settings)` on each FVG object.
`isVisibleNow` is a boolean indicating if the FVG should currently be visible.
`settings` is the `drawSettings` UDT instance.
This method synchronizes the FVG's visual appearance with its current state and settings, managing all drawing elements (boxes, lines, labels), their styles, and visibility. It efficiently skips redundant drawing operations if the FVG's state or visibility has not changed, thanks to its internal optimization using `prev_*` fields, which are also updated by this method.
5. Deleting Drawings (`deleteDrawings` method)
When an FVG object is no longer tracked:
Call `myFvg.deleteDrawings(deleteTestedToo)`.
This method removes all drawing objects associated with that `fvgObject`.
This workflow ensures that FVG visuals are accurately maintained throughout their existence on the chart.
█ NOTES
Dependencies: This library relies on `FvgTypes` for `fvgObject` and `drawSettings` definitions, and its methods (`updateMitigation`, `updatePartialFill`) internally call functions from `FvgCalculations`.
Drawing Object Management: Be mindful of TradingView's limits on drawing objects per script. The main script should manage the number of active FVG objects.
Performance and `updateDrawings()`: The `updateDrawings()` method is comprehensive. Its internal optimization (checking `hasStateChanged` based on `prev_*` fields) is crucial for performance. Call it judiciously.
Role of `settings.currentTime`: The `currentTime` field in `drawSettings` is key for positioning time-dependent elements like labels and the right edge of non-extended drawings.
Mutability of `fvgObject` Instances: Methods in this library directly modify the `fvgObject` instance they are called upon (e.g., its state fields and drawing IDs).
Drawing ID Checks: Methods generally check if drawing IDs are `na` before acting on them, preventing runtime errors.
█ EXPORTED FUNCTIONS
method draw(this, settings)
Draws the initial visual representation of the FVG object on the chart. This includes the main FVG box, its midline (if enabled), and a label
(if enabled for the specific timeframe). This method is typically invoked
immediately after an FVG is first detected and its initial properties are set. It uses drawing settings to customize the appearance based on the FVG's timeframe type.
Namespace types: types.fvgObject
Parameters:
this (fvgObject type from no1x/FvgTypes/1) : The FVG object instance to be drawn. Core properties (top, bottom,
startTime, isBullish, tfType) should be pre-initialized. This method will
initialize boxId, midLineId, boxLabelId (if applicable), and
currentTop/currentBottom (if currently na) on this object.
settings (drawSettings type from no1x/FvgTypes/1) : A drawSettings object providing all visual parameters. Reads display settings (colors, styles, visibility for boxes, midlines, labels,
box extension) relevant to this.tfType. settings.currentTime is used for
positioning labels and the right boundary of non-extended boxes.
method updateMitigation(this, highVal, lowVal)
Checks if the FVG has been fully mitigated by the current bar's price action.
Namespace types: types.fvgObject
Parameters:
this (fvgObject type from no1x/FvgTypes/1) : The FVG object instance. Reads this.isMitigated, this.isVisible,
this.isBullish, this.top, this.bottom. Updates this.isMitigated and
this.mitigationTime if full mitigation occurs.
highVal (float) : The high price of the current bar, used for mitigation check.
lowVal (float) : The low price of the current bar, used for mitigation check.
method updatePartialFill(this, highVal, lowVal, settings)
Checks for and processes partial fills of the FVG.
Namespace types: types.fvgObject
Parameters:
this (fvgObject type from no1x/FvgTypes/1) : The FVG object instance. Reads this.isMitigated, this.isVisible,
this.isBullish, this.currentTop, this.currentBottom, original this.top/this.bottom,
this.startTime, this.tfType, this.isLV. Updates this.currentTop or
this.currentBottom, creates/updates this.mitigatedBoxId, and may update this.boxId's
top/bottom to reflect the filled portion.
highVal (float) : The high price of the current bar, used for partial fill check.
lowVal (float) : The low price of the current bar, used for partial fill check.
settings (drawSettings type from no1x/FvgTypes/1) : The drawing settings. Reads timeframe-specific colors for mitigated
boxes (e.g., settings.mitigatedBullBoxColor, settings.mitigatedLvBullColor),
box extension settings (settings.shouldExtendBoxes, settings.shouldExtendMtfBoxes, etc.),
and settings.currentTime to style and position the mitigatedBoxId and potentially adjust the main boxId.
method checkMidlineTouch(this, highVal, lowVal)
Checks if the FVG's midline (50% level or Equilibrium) has been touched.
Namespace types: types.fvgObject
Parameters:
this (fvgObject type from no1x/FvgTypes/1) : The FVG object instance. Reads this.midLineId, this.isMidlineTouched,
this.top, this.bottom. Updates this.isMidlineTouched if a touch occurs.
highVal (float) : The high price of the current bar, used for midline touch check.
lowVal (float) : The low price of the current bar, used for midline touch check.
method deleteDrawings(this, deleteTestedToo)
Deletes all visual drawing objects associated with this FVG object.
Namespace types: types.fvgObject
Parameters:
this (fvgObject type from no1x/FvgTypes/1) : The FVG object instance. Deletes drawings referenced by boxId,
mitigatedBoxId, midLineId, mitLineId, boxLabelId, mitLineLabelId,
and potentially testedBoxId, keptMitLineId. Sets these ID fields to na.
deleteTestedToo (simple bool) : If true, also deletes drawings for "tested" FVGs
(i.e., testedBoxId and keptMitLineId).
method updateDrawings(this, isVisibleNow, settings)
Manages the comprehensive update of all visual elements of an FVG object
based on its current state (e.g., active, mitigated, partially filled) and visibility. It handles the drawing, updating, or deletion of FVG boxes (main and mitigated part),
midlines, mitigation lines, and their associated labels. Visibility is determined by the isVisibleNow parameter and relevant settings
(like settings.shouldHideMitigated or timeframe-specific show flags). This method is central to the FVG's visual lifecycle and includes optimization
to avoid redundant drawing operations if the FVG's relevant state or appearance
settings have not changed since the last bar. It also updates the FVG object's internal prev_* state fields for future optimization checks.
Namespace types: types.fvgObject
Parameters:
this (fvgObject type from no1x/FvgTypes/1) : The FVG object instance to update. Reads most state fields (e.g.,
isMitigated, currentTop, tfType, etc.) and updates all drawing ID fields
(boxId, midLineId, etc.), this.isVisible, and all this.prev_* state fields.
isVisibleNow (bool) : A flag indicating whether the FVG should be currently visible. Typically determined by external logic (e.g., visual range filter). Affects
whether active FVG drawings are created/updated or deleted by this method.
settings (drawSettings type from no1x/FvgTypes/1) : A fully populated drawSettings object. This method extensively
reads its fields (colors, styles, visibility toggles, timeframe strings, etc.)
to render FVG components according to this.tfType and current state. settings.currentTime is critical for positioning elements like labels and extending drawings.
FvgCalculations█ OVERVIEW
This library provides the core calculation engine for identifying Fair Value Gaps (FVGs) across different timeframes and for processing their interaction with price. It includes functions to detect FVGs on both the current chart and higher timeframes, as well as to check for their full or partial mitigation.
█ CONCEPTS
The library's primary functions revolve around the concept of Fair Value Gaps and their lifecycle.
Fair Value Gap (FVG) Identification
An FVG, or imbalance, represents a price range where buying or selling pressure was significant enough to cause a rapid price movement, leaving an "inefficiency" in the market. This library identifies FVGs based on three-bar patterns:
Bullish FVG: Forms when the low of the current bar (bar 3) is higher than the high of the bar two periods prior (bar 1). The FVG is the space between the high of bar 1 and the low of bar 3.
Bearish FVG: Forms when the high of the current bar (bar 3) is lower than the low of the bar two periods prior (bar 1). The FVG is the space between the low of bar 1 and the high of bar 3.
The library provides distinct functions for detecting FVGs on the current (Low Timeframe - LTF) and specified higher timeframes (Medium Timeframe - MTF / High Timeframe - HTF).
FVG Mitigation
Mitigation refers to price revisiting an FVG.
Full Mitigation: An FVG is considered fully mitigated when price completely closes the gap. For a bullish FVG, this occurs if the current low price moves below or touches the FVG's bottom. For a bearish FVG, it occurs if the current high price moves above or touches the FVG's top.
Partial Mitigation (Entry/Fill): An FVG is partially mitigated when price enters the FVG's range but does not fully close it. The library tracks the extent of this fill. For a bullish FVG, if the current low price enters the FVG from above, that low becomes the new effective top of the remaining FVG. For a bearish FVG, if the current high price enters the FVG from below, that high becomes the new effective bottom of the remaining FVG.
FVG Interaction
This refers to any instance where the current bar's price range (high to low) touches or crosses into the currently unfilled portion of an active (visible and not fully mitigated) FVG.
Multi-Timeframe Data Acquisition
To detect FVGs on higher timeframes, specific historical bar data (high, low, and time of bars at indices and relative to the higher timeframe's last completed bar) is required. The requestMultiTFBarData function is designed to fetch this data efficiently.
█ CALCULATIONS AND USE
The functions in this library are typically used in a sequence to manage FVGs:
1. Data Retrieval (for MTF/HTF FVGs):
Call requestMultiTFBarData() with the desired higher timeframe string (e.g., "60", "D").
This returns a tuple of htfHigh1, htfLow1, htfTime1, htfHigh3, htfLow3, htfTime3.
2. FVG Detection:
For LTF FVGs: Call detectFvg() on each confirmed bar. It uses high , low, low , and high along with barstate.isconfirmed.
For MTF/HTF FVGs: Call detectMultiTFFvg() using the data obtained from requestMultiTFBarData().
Both detection functions return an fvgObject (defined in FvgTypes) if an FVG is found, otherwise na. They also can classify FVGs as "Large Volume" (LV) if classifyLV is true and the FVG size (top - bottom) relative to the tfAtr (Average True Range of the respective timeframe) meets the lvAtrMultiplier.
3. FVG State Updates (on each new bar for existing FVGs):
First, check for overall price interaction using fvgInteractionCheck(). This function determines if the current bar's high/low has touched or entered the FVG's currentTop or currentBottom.
If interaction occurs and the FVG is not already mitigated:
Call checkMitigation() to determine if the FVG has been fully mitigated by the current bar's currentHigh and currentLow. If true, the FVG's isMitigated status is updated.
If not fully mitigated, call checkPartialMitigation() to see if the price has further entered the FVG. This function returns the newLevel to which the FVG has been filled (e.g., currentLow for a bullish FVG, currentHigh for bearish). This newLevel is then used to update the FVG's currentTop or currentBottom.
The calling script (e.g., fvgMain.c) is responsible for storing and managing the array of fvgObject instances and passing them to these update functions.
█ NOTES
Bar State for LTF Detection: The detectFvg() function relies on barstate.isconfirmed to ensure FVG detection is based on closed bars, preventing FVGs from being detected prematurely on the currently forming bar.
Higher Timeframe Data (lookahead): The requestMultiTFBarData() function uses lookahead = barmerge.lookahead_on. This means it can access historical data from the higher timeframe that corresponds to the current bar on the chart, even if the higher timeframe bar has not officially closed. This is standard for multi-timeframe analysis aiming to plot historical HTF data accurately on a lower timeframe chart.
Parameter Typing: Functions like detectMultiTFFvg and detectFvg infer the type for boolean (classifyLV) and numeric (lvAtrMultiplier) parameters passed from the main script, while explicitly typed series parameters (like htfHigh1, currentAtr) expect series data.
fvgObject Dependency: The FVG detection functions return fvgObject instances, and fvgInteractionCheck takes an fvgObject as a parameter. This UDT is defined in the FvgTypes library, making it a dependency for using FvgCalculations.
ATR for LV Classification: The tfAtr (for MTF/HTF) and currentAtr (for LTF) parameters are expected to be the Average True Range values for the respective timeframes. These are used, if classifyLV is enabled, to determine if an FVG's size qualifies it as a "Large Volume" FVG based on the lvAtrMultiplier.
MTF/HTF FVG Appearance Timing: When displaying FVGs from a higher timeframe (MTF/HTF) on a lower timeframe (LTF) chart, users might observe that the most recent MTF/HTF FVG appears one LTF bar later compared to its appearance on a native MTF/HTF chart. This is an expected behavior due to the detection mechanism in `detectMultiTFFvg`. This function uses historical bar data from the MTF/HTF (specifically, data equivalent to `HTF_bar ` and `HTF_bar `) to identify an FVG. Therefore, all three bars forming the FVG on the MTF/HTF must be fully closed and have shifted into these historical index positions relative to the `request.security` call from the LTF chart before the FVG can be detected and displayed on the LTF. This ensures that the MTF/HTF FVG is identified based on confirmed, closed bars from the higher timeframe.
█ EXPORTED FUNCTIONS
requestMultiTFBarData(timeframe)
Requests historical bar data for specific previous bars from a specified higher timeframe.
It fetches H , L , T (for the bar before last) and H , L , T (for the bar three periods prior)
from the requested timeframe.
This is typically used to identify FVG patterns on MTF/HTF.
Parameters:
timeframe (simple string) : The higher timeframe to request data from (e.g., "60" for 1-hour, "D" for Daily).
Returns: A tuple containing: .
- htfHigh1 (series float): High of the bar at index 1 (one bar before the last completed bar on timeframe).
- htfLow1 (series float): Low of the bar at index 1.
- htfTime1 (series int) : Time of the bar at index 1.
- htfHigh3 (series float): High of the bar at index 3 (three bars before the last completed bar on timeframe).
- htfLow3 (series float): Low of the bar at index 3.
- htfTime3 (series int) : Time of the bar at index 3.
detectMultiTFFvg(htfHigh1, htfLow1, htfTime1, htfHigh3, htfLow3, htfTime3, tfAtr, classifyLV, lvAtrMultiplier, tfType)
Detects a Fair Value Gap (FVG) on a higher timeframe (MTF/HTF) using pre-fetched bar data.
Parameters:
htfHigh1 (float) : High of the first relevant bar (typically high ) from the higher timeframe.
htfLow1 (float) : Low of the first relevant bar (typically low ) from the higher timeframe.
htfTime1 (int) : Time of the first relevant bar (typically time ) from the higher timeframe.
htfHigh3 (float) : High of the third relevant bar (typically high ) from the higher timeframe.
htfLow3 (float) : Low of the third relevant bar (typically low ) from the higher timeframe.
htfTime3 (int) : Time of the third relevant bar (typically time ) from the higher timeframe.
tfAtr (float) : ATR value for the higher timeframe, used for Large Volume (LV) FVG classification.
classifyLV (bool) : If true, FVGs will be assessed to see if they qualify as Large Volume.
lvAtrMultiplier (float) : The ATR multiplier used to define if an FVG is Large Volume.
tfType (series tfType enum from no1x/FvgTypes/1) : The timeframe type (e.g., types.tfType.MTF, types.tfType.HTF) of the FVG being detected.
Returns: An fvgObject instance if an FVG is detected, otherwise na.
detectFvg(classifyLV, lvAtrMultiplier, currentAtr)
Detects a Fair Value Gap (FVG) on the current (LTF - Low Timeframe) chart.
Parameters:
classifyLV (bool) : If true, FVGs will be assessed to see if they qualify as Large Volume.
lvAtrMultiplier (float) : The ATR multiplier used to define if an FVG is Large Volume.
currentAtr (float) : ATR value for the current timeframe, used for LV FVG classification.
Returns: An fvgObject instance if an FVG is detected, otherwise na.
checkMitigation(isBullish, fvgTop, fvgBottom, currentHigh, currentLow)
Checks if an FVG has been fully mitigated by the current bar's price action.
Parameters:
isBullish (bool) : True if the FVG being checked is bullish, false if bearish.
fvgTop (float) : The top price level of the FVG.
fvgBottom (float) : The bottom price level of the FVG.
currentHigh (float) : The high price of the current bar.
currentLow (float) : The low price of the current bar.
Returns: True if the FVG is considered fully mitigated, false otherwise.
checkPartialMitigation(isBullish, currentBoxTop, currentBoxBottom, currentHigh, currentLow)
Checks for partial mitigation of an FVG by the current bar's price action.
It determines if the price has entered the FVG and returns the new fill level.
Parameters:
isBullish (bool) : True if the FVG being checked is bullish, false if bearish.
currentBoxTop (float) : The current top of the FVG box (this might have been adjusted by previous partial fills).
currentBoxBottom (float) : The current bottom of the FVG box (similarly, might be adjusted).
currentHigh (float) : The high price of the current bar.
currentLow (float) : The low price of the current bar.
Returns: The new price level to which the FVG has been filled (e.g., currentLow for a bullish FVG).
Returns na if no new partial fill occurred on this bar.
fvgInteractionCheck(fvg, highVal, lowVal)
Checks if the current bar's price interacts with the given FVG.
Interaction means the price touches or crosses into the FVG's
current (possibly partially filled) range.
Parameters:
fvg (fvgObject type from no1x/FvgTypes/1) : The FVG object to check.
Its isMitigated, isVisible, isBullish, currentTop, and currentBottom fields are used.
highVal (float) : The high price of the current bar.
lowVal (float) : The low price of the current bar.
Returns: True if price interacts with the FVG, false otherwise.
FvgTypes█ OVERVIEW
This library serves as a foundational module for Pine Script™ projects focused on Fair Value Gaps (FVGs). Its primary purpose is to define and centralize custom data structures (User-Defined Types - UDTs) and enumerations that are utilized across various components of an FVG analysis system. By providing standardized types for FVG characteristics and drawing configurations, it promotes code consistency, readability, and easier maintenance within a larger FVG indicator or strategy.
█ CONCEPTS
The library introduces several key data structures (User-Defined Types - UDTs) and an enumeration to organize Fair Value Gap (FVG) related data logically. These types are central to the functioning of FVG analysis tools built upon this library.
Timeframe Categorization (`tfType` Enum)
To manage and differentiate FVGs based on their timeframe of origin, the `tfType` enumeration is defined. It includes:
`LTF`: Low Timeframe (typically the current chart).
`MTF`: Medium Timeframe.
`HTF`: High Timeframe.
This allows for distinct logic and visual settings to be applied depending on the FVG's source timeframe.
FVG Data Encapsulation (`fvgObject` UDT)
The `fvgObject` is a comprehensive UDT designed to encapsulate all pertinent information and state for an individual Fair Value Gap throughout its lifecycle. Instead of listing every field, its conceptual structure can be understood as holding:
Core Definition: The FVG's fundamental price levels (top, bottom) and its formation time (`startTime`).
Classification Attributes: Characteristics such as its direction (`isBullish`) and whether it qualifies as a Large Volume FVG (`isLV`), along with its originating timeframe category (`tfType`).
Lifecycle State: Current status indicators including full mitigation (`isMitigated`, `mitigationTime`), partial fill levels (`currentTop`, `currentBottom`), midline interaction (`isMidlineTouched`), and overall visibility (`isVisible`).
Drawing Identifiers: References (`boxId`, `midLineId`, `mitLineLabelId`, etc.) to the actual graphical objects drawn on the chart to represent the FVG and its components.
Optimization Cache: Previous-bar state values (`prevIsMitigated`, `prevCurrentTop`, etc.) crucial for optimizing drawing updates by avoiding redundant operations.
This comprehensive structure facilitates easy access to all FVG-related information through a single object, reducing code complexity and improving manageability.
Drawing Configuration (`drawSettings` UDT)
The `drawSettings` UDT centralizes all user-configurable parameters that dictate the visual appearance of FVGs across different timeframes. It's typically populated from script inputs and conceptually groups settings for:
General Behavior: Global FVG classification toggles (e.g., `shouldClassifyLV`) and general display rules (e.g., `shouldHideMitigated`).
FVG Type Specific Colors: Colors for standard and Large Volume FVGs, both active and mitigated (e.g., `lvBullColor`, `mitigatedBearBoxColor`).
Timeframe-Specific Visuals (LTF, MTF, HTF): Detailed parameters for each timeframe category, covering FVG boxes (visibility, colors, extension, borders, labels), midlines (visibility, style, color), and mitigation lines (visibility, style, color, labels, persistence after mitigation).
Contextual Information: The current bar's time (`currentTime`) for accurate positioning of time-dependent drawing elements and timeframe display strings (`tfString`, `mtfTfString`, `htfTfString`).
This centralized approach allows for extensive customization of FVG visuals and simplifies the management of drawing parameters within the main script. Such centralization also enhances the maintainability of the visual aspects of the FVG system.
█ NOTES
User-Defined Types (UDTs): This library extensively uses UDTs (`fvgObject`, `drawSettings`) to group related data. This improves code organization and makes it easier to pass complex data between functions and libraries.
Mutability and Reference Behavior of UDTs: When UDT instances are passed to functions or methods in other libraries (like `fvgObjectLib`), those functions might modify the fields of the passed object if they are not explicitly designed to return new instances. This is because UDTs are passed by reference and are mutable in Pine Script™. Users should be aware of this standard behavior to prevent unintended side effects.
Optimization Fields: The `prev_*` fields in `fvgObject` are crucial for performance optimization in the drawing logic. They help avoid unnecessary redrawing of FVG elements if their state or relevant settings haven't changed.
No Direct Drawing Logic: `FvgTypes` itself does not contain any drawing logic. It solely defines the data structures. The actual drawing and manipulation of these objects are handled by other libraries (e.g., `fvgObjectLib`).
Centralized Definitions: By defining these types in a separate library, any changes to the structure of FVG data or settings can be made in one place, ensuring consistency across all dependent scripts and libraries.
█ EXPORTED TYPES
fvgObject
fvgObject Represents a Fair Value Gap (FVG) object.
Fields:
top (series float) : The top price level of the FVG.
bottom (series float) : The bottom price level of the FVG.
startTime (series int) : The start time (timestamp) of the bar where the FVG formed.
isBullish (series bool) : Indicates if the FVG is bullish (true) or bearish (false).
isLV (series bool) : Indicates if the FVG is a Large Volume FVG.
tfType (series tfType) : The timeframe type (LTF, MTF, HTF) to which this FVG belongs.
isMitigated (series bool) : Indicates if the FVG has been fully mitigated.
mitigationTime (series int) : The time (timestamp) when the FVG was mitigated.
isVisible (series bool) : The current visibility status of the FVG, typically managed by drawing logic based on filters.
isMidlineTouched (series bool) : Indicates if the price has touched the FVG's midline (50% level).
currentTop (series float) : The current top level of the FVG after partial fills.
currentBottom (series float) : The current bottom level of the FVG after partial fills.
boxId (series box) : The drawing ID for the main FVG box.
mitigatedBoxId (series box) : The drawing ID for the box representing the partially filled (mitigated) area.
midLineId (series line) : The drawing ID for the FVG's midline.
mitLineId (series line) : The drawing ID for the FVG's mitigation line.
boxLabelId (series label) : The drawing ID for the FVG box label.
mitLineLabelId (series label) : The drawing ID for the mitigation line label.
testedBoxId (series box) : The drawing ID for the box of a fully mitigated (tested) FVG, if kept visible.
keptMitLineId (series line) : The drawing ID for a mitigation line that is kept after full mitigation.
prevIsMitigated (series bool) : Stores the isMitigated state from the previous bar for optimization.
prevCurrentTop (series float) : Stores the currentTop value from the previous bar for optimization.
prevCurrentBottom (series float) : Stores the currentBottom value from the previous bar for optimization.
prevIsVisible (series bool) : Stores the visibility status from the previous bar for optimization (derived from isVisibleNow passed to updateDrawings).
prevIsMidlineTouched (series bool) : Stores the isMidlineTouched status from the previous bar for optimization.
drawSettings
drawSettings A structure containing settings for drawing FVGs.
Fields:
shouldClassifyLV (series bool) : Whether to classify FVGs as Large Volume (LV) based on ATR.
shouldHideMitigated (series bool) : Whether to hide FVG boxes once they are fully mitigated.
currentTime (series int) : The current bar's time, used for extending drawings.
lvBullColor (series color) : Color for Large Volume Bullish FVGs.
mitigatedLvBullColor (series color) : Color for mitigated Large Volume Bullish FVGs.
lvBearColor (series color) : Color for Large Volume Bearish FVGs.
mitigatedLvBearColor (series color) : Color for mitigated Large Volume Bearish FVGs.
shouldShowBoxes (series bool) : Whether to show FVG boxes for the LTF.
bullBoxColor (series color) : Color for LTF Bullish FVG boxes.
mitigatedBullBoxColor (series color) : Color for mitigated LTF Bullish FVG boxes.
bearBoxColor (series color) : Color for LTF Bearish FVG boxes.
mitigatedBearBoxColor (series color) : Color for mitigated LTF Bearish FVG boxes.
boxLengthBars (series int) : Length of LTF FVG boxes in bars (if not extended).
shouldExtendBoxes (series bool) : Whether to extend LTF FVG boxes to the right.
shouldShowCurrentTfBoxLabels (series bool) : Whether to show labels on LTF FVG boxes.
shouldShowBoxBorder (series bool) : Whether to show a border for LTF FVG boxes.
boxBorderWidth (series int) : Border width for LTF FVG boxes.
boxBorderStyle (series string) : Border style for LTF FVG boxes (e.g., line.style_solid).
boxBorderColor (series color) : Border color for LTF FVG boxes.
shouldShowMidpoint (series bool) : Whether to show the midline (50% level) for LTF FVGs.
midLineWidthInput (series int) : Width of the LTF FVG midline.
midpointLineStyleInput (series string) : Style of the LTF FVG midline.
midpointColorInput (series color) : Color of the LTF FVG midline.
shouldShowMitigationLine (series bool) : Whether to show the mitigation line for LTF FVGs.
(Line always extends if shown)
mitLineWidthInput (series int) : Width of the LTF FVG mitigation line.
mitigationLineStyleInput (series string) : Style of the LTF FVG mitigation line.
mitigationLineColorInput (series color) : Color of the LTF FVG mitigation line.
shouldShowCurrentTfMitLineLabels (series bool) : Whether to show labels on LTF FVG mitigation lines.
currentTfMitLineLabelOffsetX (series float) : The horizontal offset value for the LTF mitigation line's label.
shouldKeepMitigatedLines (series bool) : Whether to keep showing mitigation lines of fully mitigated LTF FVGs.
mitigatedMitLineColor (series color) : Color for kept mitigation lines of mitigated LTF FVGs.
tfString (series string) : Display string for the LTF (e.g., "Current TF").
shouldShowMtfBoxes (series bool) : Whether to show FVG boxes for the MTF.
mtfBullBoxColor (series color) : Color for MTF Bullish FVG boxes.
mtfMitigatedBullBoxColor (series color) : Color for mitigated MTF Bullish FVG boxes.
mtfBearBoxColor (series color) : Color for MTF Bearish FVG boxes.
mtfMitigatedBearBoxColor (series color) : Color for mitigated MTF Bearish FVG boxes.
mtfBoxLengthBars (series int) : Length of MTF FVG boxes in bars (if not extended).
shouldExtendMtfBoxes (series bool) : Whether to extend MTF FVG boxes to the right.
shouldShowMtfBoxLabels (series bool) : Whether to show labels on MTF FVG boxes.
shouldShowMtfBoxBorder (series bool) : Whether to show a border for MTF FVG boxes.
mtfBoxBorderWidth (series int) : Border width for MTF FVG boxes.
mtfBoxBorderStyle (series string) : Border style for MTF FVG boxes.
mtfBoxBorderColor (series color) : Border color for MTF FVG boxes.
shouldShowMtfMidpoint (series bool) : Whether to show the midline for MTF FVGs.
mtfMidLineWidthInput (series int) : Width of the MTF FVG midline.
mtfMidpointLineStyleInput (series string) : Style of the MTF FVG midline.
mtfMidpointColorInput (series color) : Color of the MTF FVG midline.
shouldShowMtfMitigationLine (series bool) : Whether to show the mitigation line for MTF FVGs.
(Line always extends if shown)
mtfMitLineWidthInput (series int) : Width of the MTF FVG mitigation line.
mtfMitigationLineStyleInput (series string) : Style of the MTF FVG mitigation line.
mtfMitigationLineColorInput (series color) : Color of the MTF FVG mitigation line.
shouldShowMtfMitLineLabels (series bool) : Whether to show labels on MTF FVG mitigation lines.
mtfMitLineLabelOffsetX (series float) : The horizontal offset value for the MTF mitigation line's label.
shouldKeepMtfMitigatedLines (series bool) : Whether to keep showing mitigation lines of fully mitigated MTF FVGs.
mtfMitigatedMitLineColor (series color) : Color for kept mitigation lines of mitigated MTF FVGs.
mtfTfString (series string) : Display string for the MTF (e.g., "MTF").
shouldShowHtfBoxes (series bool) : Whether to show FVG boxes for the HTF.
htfBullBoxColor (series color) : Color for HTF Bullish FVG boxes.
htfMitigatedBullBoxColor (series color) : Color for mitigated HTF Bullish FVG boxes.
htfBearBoxColor (series color) : Color for HTF Bearish FVG boxes.
htfMitigatedBearBoxColor (series color) : Color for mitigated HTF Bearish FVG boxes.
htfBoxLengthBars (series int) : Length of HTF FVG boxes in bars (if not extended).
shouldExtendHtfBoxes (series bool) : Whether to extend HTF FVG boxes to the right.
shouldShowHtfBoxLabels (series bool) : Whether to show labels on HTF FVG boxes.
shouldShowHtfBoxBorder (series bool) : Whether to show a border for HTF FVG boxes.
htfBoxBorderWidth (series int) : Border width for HTF FVG boxes.
htfBoxBorderStyle (series string) : Border style for HTF FVG boxes.
htfBoxBorderColor (series color) : Border color for HTF FVG boxes.
shouldShowHtfMidpoint (series bool) : Whether to show the midline for HTF FVGs.
htfMidLineWidthInput (series int) : Width of the HTF FVG midline.
htfMidpointLineStyleInput (series string) : Style of the HTF FVG midline.
htfMidpointColorInput (series color) : Color of the HTF FVG midline.
shouldShowHtfMitigationLine (series bool) : Whether to show the mitigation line for HTF FVGs.
(Line always extends if shown)
htfMitLineWidthInput (series int) : Width of the HTF FVG mitigation line.
htfMitigationLineStyleInput (series string) : Style of the HTF FVG mitigation line.
htfMitigationLineColorInput (series color) : Color of the HTF FVG mitigation line.
shouldShowHtfMitLineLabels (series bool) : Whether to show labels on HTF FVG mitigation lines.
htfMitLineLabelOffsetX (series float) : The horizontal offset value for the HTF mitigation line's label.
shouldKeepHtfMitigatedLines (series bool) : Whether to keep showing mitigation lines of fully mitigated HTF FVGs.
htfMitigatedMitLineColor (series color) : Color for kept mitigation lines of mitigated HTF FVGs.
htfTfString (series string) : Display string for the HTF (e.g., "HTF").
DisplayUtilitiesLibrary "DisplayUtilities"
Display utilities for color management and visual presentation
get_direction_color(direction, up_excessive, up_normal, neutral, down_normal, down_excessive)
Get candle color based on direction and color scheme
Parameters:
direction (int) : Direction value (-2, -1, 0, 1, 2)
up_excessive (color) : Color for +2 direction
up_normal (color) : Color for +1 direction
neutral (color) : Color for 0 direction
down_normal (color) : Color for -1 direction
down_excessive (color) : Color for -2 direction
Returns: Appropriate color for the direction
get_candle_paint_directions(paint_opt, body_dir, bar_dir, breakout_dir, combined_dir)
Get candle directions for different painting algorithms
Parameters:
paint_opt (string) : Painting option algorithm
body_dir (int) : Body direction
bar_dir (int) : Bar direction
breakout_dir (int) : Breakout direction
combined_dir (int) : Combined direction
Returns:
get_bias_paint_directions(paint_bias, unified_dir)
Get paint directions based on bias filter
Parameters:
paint_bias (string) : Paint bias option ("All", "Bull Bias", "Bear Bias")
unified_dir (int) : Unified direction
Returns: Directions for two plotcandle series
get_transparency_levels(sf_filtered, fade_option, fade_opacity)
Calculate transparency levels for strength factor filtering
Parameters:
sf_filtered (bool) : Is strength factor filtered
fade_option (string) : Fade option ("Disabled", "Fade Candle", "Do Not Fade Wick", "Do Not Fade Wick and Border")
fade_opacity (int) : Fade opacity percentage
Returns:
get_strength_factor_filter(filter_option, individual_filters)
Generate strength factor filter conditions
Parameters:
filter_option (string) : Filter option string
individual_filters (map) : Map of individual filter conditions
Returns: Boolean filter result
get_signal_bar_condition(signal_option, individual_filters)
Generate signal bar conditions (inverted filters)
Parameters:
signal_option (string) : Signal bar option string
individual_filters (map) : Map of individual filter conditions
Returns: Boolean signal bar result
get_zscore_signal_condition(z_signal_option, z_filters)
Get Z-score signal bar conditions
Parameters:
z_signal_option (string) : Z-score signal option
z_filters (map) : Map of Z-score filters
Returns: Boolean Z-score signal condition
get_standard_colors()
Create a standard color scheme for directions
Returns: Standard color set
apply_zscore_modification(original_dir, z_filtered)
Modify directions for Z-score excess display
Parameters:
original_dir (int) : Original direction
z_filtered (bool) : Is Z-score filtered (shows excess)
Returns: Modified direction (doubled if excess detected)
get_default_fade_colors()
Get default fade colors for strength factor overlay
Returns: Default colors for TV overlay
should_paint_candles(paint_algo)
Check if paint algorithm should show candles
Parameters:
paint_algo (string) : Paint algorithm option
Returns: True if algorithm should display candles
get_signal_bar_char(signal_type, is_bullish)
Get signal bar character based on signal type
Parameters:
signal_type (string) : Signal type ("strength_factor" or "zscore")
is_bullish (bool) : Direction is bullish
Returns: Character and location for plotchar
get_signal_bar_color(signal_type, is_bullish)
Get signal bar colors
Parameters:
signal_type (string) : Signal type ("strength_factor" or "zscore")
is_bullish (bool) : Direction is bullish
Returns: Signal bar color
ZScoreAnalysisLibrary "ZScoreAnalysis"
Z-score analysis for detecting statistical deviations and excess market behavior
calculate_zscore(source, lookback, threshold, switch_enabled)
Calculate Z-score and related metrics with history tracking
Parameters:
source (float) : Data source for Z-score calculation
lookback (int) : Lookback period for mean and standard deviation
threshold (float) : Z-score threshold for significance
switch_enabled (string) : Enable/disable switch ("Enabled"/"Disabled")
Returns: Z-score, historical significant values, and running average
get_zscore_threshold(opt, input_thr, avg)
Get threshold based on threshold option
Parameters:
opt (string) : Threshold option ("User Input Threshold", "Average as Threshold", or other)
input_thr (float) : User input threshold
avg (float) : Average threshold
Returns: Calculated threshold value
is_zscore_filtered(switch_enabled, zscore, threshold)
Check if a metric passes the Z-score filter
Parameters:
switch_enabled (string) : Enable/disable switch
zscore (float) : Current Z-score value
threshold (float) : Z-score threshold
Returns: True if filtered (exceeds threshold)
get_consecutive_distances(body_dir, breakout_dir, is_inside_bar)
Calculate consecutive distances for Z-score analysis
Parameters:
body_dir (int) : Body direction
breakout_dir (int) : Breakout direction
is_inside_bar (bool) : Inside bar flag
Returns:
get_trend_to_mean_distance()
Calculate distance from trend to mean for momentum analysis
Returns: Distance between trend and mean
get_all_zscores(lookback, threshold, bar_dist_switch, body_dist_switch, chl_dist_switch, cc_dist_switch, m_dist_switch, body_dir, breakout_dir, is_inside_bar)
Get all Z-score calculations for the indicator
Parameters:
lookback (int) : Z-score lookback period
threshold (float) : Z-score threshold
bar_dist_switch (string) : Enable bar distance Z-score
body_dist_switch (string) : Enable body distance Z-score
chl_dist_switch (string) : Enable consecutive highs/lows Z-score
cc_dist_switch (string) : Enable consecutive closes Z-score
m_dist_switch (string) : Enable momentum distance Z-score
body_dir (int) : Body direction
breakout_dir (int) : Breakout direction
is_inside_bar (bool) : Inside bar flag
Returns: Array of Z-score results and filters
get_combined_zscore_filters(z_filters)
Get combined Z-score filters
Parameters:
z_filters (map) : Map of individual Z-score filters
Returns: Various combinations of Z-score filters
get_basic_distances()
Calculate basic distances used in Z-score analysis
Returns: Bar range and body range
get_individual_zscore_filter(z_filters, filter_name)
Get individual Z-score filter by name
Parameters:
z_filters (map) : Map of Z-score filters
filter_name (string) : Name of the filter ("bar_dist", "body_dist", etc.)
Returns: Boolean filter result
has_any_zscore_signal(z_filters)
Check if any Z-score filter is active
Parameters:
z_filters (map) : Map of individual Z-score filters
Returns: True if any Z-score exceeds threshold
StrengthFactorsLibrary "StrengthFactors"
Strength factor calculations for various market analysis metrics
get_threshold(opt, input_val, avg_val, lineancy)
Calculate threshold based on options
Parameters:
opt (string) : Threshold option ("Disabled", "User Input Threshold", "Average as Threshold")
input_val (float) : User input threshold value
avg_val (float) : Average value for threshold
lineancy (float) : Lineancy adjustment percentage
Returns: Calculated threshold
get_percentage_of_threshold(value, threshold)
Calculate percentage of threshold
Parameters:
value (float) : Current value
threshold (float) : Threshold value
Returns: Percentage of threshold
get_distance_sf(lookback, thr_opt, thr_inp, lineancy)
Calculate Distance Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_uniformity_sf(lookback, thr_opt, thr_inp, stddev_mult, lineancy)
Calculate Uniformity Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
stddev_mult (float) : Standard deviation multiplier
lineancy (float) : Lineancy adjustment
Returns:
get_overlap_sf(lookback, thr_opt, thr_inp, lineancy)
Calculate Overlap Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_body_sf(lookback, thr_opt, thr_inp, lineancy)
Calculate Body Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_close_sf(lookback, thr_opt, thr_inp, lineancy)
Calculate Close Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_breakout_sf(lookback, thr_opt, thr_inp, lineancy, bro_dir, is_inside_bar)
Calculate Breakout Strength Factor
Parameters:
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
bro_dir (int) : Breakout direction
is_inside_bar (bool) : Is inside bar flag
Returns:
get_always_in_sf(thr_opt, thr_inp, lineancy)
Calculate Always-In Strength Factor
Parameters:
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_directional_sf(overlap_prc, distance_prc, body_prc, close_prc, breakout_prc, lookback, thr_opt, thr_inp, lineancy)
Calculate Directional Strength Factor (composite)
Parameters:
overlap_prc (float) : Overlap SF as percentage of threshold
distance_prc (float) : Distance SF as percentage of threshold
body_prc (float) : Body SF as percentage of threshold
close_prc (float) : Close SF as percentage of threshold
breakout_prc (float) : Breakout SF as percentage of threshold
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_combined_direction_sf(body_prc, close_prc, breakout_prc, lookback, thr_opt, thr_inp, lineancy)
Calculate Combined Direction Strength Factor
Parameters:
body_prc (float) : Body SF as percentage of threshold
close_prc (float) : Close SF as percentage of threshold
breakout_prc (float) : Breakout SF as percentage of threshold
lookback (int) : Lookback period for average
thr_opt (string) : Threshold option
thr_inp (float) : User threshold input
lineancy (float) : Lineancy adjustment
Returns:
get_all_strength_factors(lookback, lineancy, dist_thr_opt, dist_thr_inp, body_thr_opt, body_thr_inp, close_thr_opt, close_thr_inp, breakout_thr_opt, breakout_thr_inp, bro_dir, is_inside_bar)
Get all strength factors at once (convenience function)
Parameters:
lookback (int) : Lookback period for averages
lineancy (float) : Lineancy adjustment percentage
dist_thr_opt (string) : Distance threshold option
dist_thr_inp (float) : Distance threshold input
body_thr_opt (string) : Body threshold option
body_thr_inp (float) : Body threshold input
close_thr_opt (string) : Close threshold option
close_thr_inp (float) : Close threshold input
breakout_thr_opt (string) : Breakout threshold option
breakout_thr_inp (float) : Breakout threshold input
bro_dir (int) : Breakout direction
is_inside_bar (bool) : Is inside bar flag
Returns: Map containing all strength factor results
DirectionCalculationsLibrary "DirectionCalculations"
Direction calculation algorithms for body, bar, and breakout directions
get_body_direction()
Calculate body direction based on open vs close
Returns: Body direction: 1 (bullish), -1 (bearish), 0 (doji)
get_bar_direction()
Calculate bar direction based on close position relative to hl2
Returns: Bar direction: 1 (upper half), -1 (lower half), 0 (middle)
get_breakout_direction()
Calculate breakout direction with outside/inside bar logic
Returns:
get_combined_direction(bod_dir, bar_dir, bro_dir, bro_ob_dir)
Calculate combined direction from body and bar directions
Parameters:
bod_dir (int) : Body direction
bar_dir (int) : Bar direction
bro_dir (int) : Breakout direction
bro_ob_dir (int) : Outside bar direction
Returns: Combined direction
is_consecutive_direction(current_dir, previous_dir)
Check if directions are consecutive (no reversal)
Parameters:
current_dir (int) : Current direction
previous_dir (int) : Previous direction
Returns: True if consecutive (no reversal from +1 to -1 or -1 to +1)
get_all_directions()
Get all direction calculations at once
Returns:
get_breakout_distances()
Get distance calculations for breakout analysis
Returns: High-to-high and low-to-low distances
get_bar_patterns()
Check for specific bar patterns
Returns:
WeightedVolumeUtilsLibrary "WeightedVolumeUtils"
fun(x)
Returns the input value (placeholder function).
Parameters:
x (float) : A float value.
Returns: The same float value passed as input.
weightedBSEVolume()
Calculates the weighted volume for BSE index based on top constituent stocks.
Returns: Weighted volume value based on fixed weights for BSE SENSEX stocks.
getAdjustedVolume()
Returns the adjusted volume for SENSEX or regular volume otherwise.
Returns: Weighted BSE volume if current symbol is SENSEX, else raw volume.
Crypto_in_details_MAlibCrypto_in_details_MaLib — Advanced Moving Average Library for Pine Script
Overview:
Crypto_in_details_MaLib is a comprehensive, performance-optimized Moving Average (MA) library designed specifically for Pine Script v6 users seeking advanced technical analysis tools. Developed by Crypto_in_details, this library consolidates the most popular and sophisticated MA calculation methods — including classical, weighted, exponential, and Hull variants — into one seamless package.
Key Features:
Implements a wide range of Moving Averages: SMA, EMA, WMA, RMA, VWMA, HMA, TEMA, EHMA, THMA.
Designed for precision and flexibility — suitable for diverse trading strategies and indicator development.
Fully typed functions compatible with Pine Script v6 standards.
Simplifies your scripting workflow by providing ready-to-use MA functions via clean and easy-to-import methods.
Well-documented and maintained by an experienced Pine Script developer.
Why Use Crypto_in_details_MaLib?
Gain access to advanced MA calculations that enhance trend analysis, smoothing, and signal accuracy.
Save time on coding complex moving averages from scratch.
Easily extend or combine with your own strategies or indicators for improved performance.
Rely on a tested and community-driven solution backed by a prolific Pine Script author.
Ideal for:
Traders and developers building custom indicators or strategies requiring versatile MA techniques.
Anyone looking to improve their Pine Script efficiency and code maintainability.
Pine Script enthusiasts wanting a professional-grade MA toolkit.
VolumeFlowOscillatorLibVolume Flow Oscillator Library
Overview
The Volume Flow Oscillator library provides a comprehensive framework for analyzing directional volume flow in financial markets. It creates a multi-band oscillator system that transforms price and volume data into a spectrum of sensitivity bands, revealing the underlying buying and selling pressure.
Technical Approach
The library combines price direction with trading volume to generate an oscillator that fluctuates around a zero line, with positive values indicating buying pressure and negative values showing selling pressure. Using sophisticated ALMA (Arnaud Legoux Moving Average) smoothing techniques with asymmetric sensitivity, the library creates seven distinct bands that help identify various intensity levels of volume flow.
Key Features
Multi-band oscillator system with seven sensitivity levels
Directional volume flow analysis combining price movement and volume
Zero-line oscillation showing the balance between buying and selling pressure
Asymmetric ALMA smoothing for different sensitivity on positive/negative bands
Customizable lookback periods and multipliers for fine-tuning
Color-coded visualization for intuitive chart reading
Applications
This library offers developers a versatile foundation for creating volume-based indicators that go beyond simple volume measurement to reveal the directional force behind market movements. Ideal for confirming price trends, detecting divergences, identifying volume climaxes, and assessing overall market strength.
KTUtilsLibrary "KTUtils"
Utility functions for technical analysis indicators, trend detection, and volatility confirmation.
MGz(close, length)
MGz
@description Moving average smoother used for signal processing
Parameters:
close (float) : float Price input (typically close)
length (int) : int Length of smoothing period
Returns: float Smoothed value
atrConf(length)
atrConf
@description Calculates Average True Range (ATR) for volatility confirmation
Parameters:
length (simple int) : int Length for ATR calculation
Returns: float ATR value
f(input)
f
@description Simple Moving Average with fixed length
Parameters:
input (float) : float Input value
Returns: float Smoothed average
bcwSMA(s, l, m)
bcwSMA
@description Custom smoothing function with weight multiplier
Parameters:
s (float) : float Signal value
l (int) : int Length of smoothing
m (int) : int Weighting multiplier
Returns: float Smoothed output
MGxx(close, length)
MGxx
@description Custom Weighted Moving Average (WMA) variant
Parameters:
close (float) : float Price input
length (int) : int Period length
Returns: float MGxx smoothed output
_PerChange(lengthTime)
_PerChange
@description Measures percentage price change over a period and range deviation
Parameters:
lengthTime (int) : int Period for change measurement
Returns: tuple Measured change, high deviation, low deviation
dirmov(len)
dirmov
@description Calculates directional movement components
Parameters:
len (simple int) : int Lookback period
Returns: tuple Plus and Minus DI values
adx(dilen, adxlen)
adx
@description Calculates Average Directional Index (ADX)
Parameters:
dilen (simple int) : int Length for DI calculation
adxlen (simple int) : int Length for ADX smoothing
Returns: float ADX value
trChopAnalysis()
trChopAnalysis
@description Identifies chop and trend phases based on True Range Bollinger Bands
Returns: tuple TR SMA, chop state, trending state
wtiAnalysis(haclose, close, filterValue)
wtiAnalysis
@description Wave Trend Indicator (WTI) with signal crossover logic
Parameters:
haclose (float) : float Heikin-Ashi close
close (float) : float Standard close
filterValue (simple int) : int Smoothing length
Returns: tuple WTI lines and direction states
basicTrend(hahigh, halow, close, open, filterValue)
basicTrend
@description Determines trend direction based on HA high/low and close
Parameters:
hahigh (float) : float Heikin-Ashi high
halow (float) : float Heikin-Ashi low
close (float) : float Standard close
open (float) : float Standard open
filterValue (simple int) : int Smoothing period
Returns: tuple Uptrend, downtrend flags
metrics(close, filterValue)
metrics
@description Common market metrics
Parameters:
close (float) : float Price input
filterValue (int) : int RSI smoothing length
Returns: tuple VWMA, SMA10, RSI, smoothed RSI
piff(close, trend_change)
piff
@description Price-Informed Forward Forecasting (PIFF) model for trend strength
Parameters:
close (float) : float Price input
trend_change (float) : float Change in trend
Returns: tuple Percent change, flags for trend direction
getMACD()
getMACD
@description Returns MACD, signal line, and histogram
Returns: tuple MACD line, Signal line, Histogram
getStoch()
getStoch
@description Returns K and D lines of Stochastic Oscillator
Returns: tuple K and D lines
getKDJ()
getKDJ
@description KDJ momentum oscillator
Returns: tuple K, D, J, Average
getBBRatio()
getBBRatio
@description Bollinger Band Ratio (BBR) and signal flags
Returns: tuple Basis, Upper, Lower, BBR, BBR Up, BBR Down
getSupertrend()
getSupertrend
@description Supertrend values and direction flags
Returns: tuple Supertrend, Direction, Up, Down
remaLibrary " REMA "
Custom Regional Exponential Moving Average with enhanced sensitivity to recent price action
Description: What Makes REMA Unique?
REMA introduces a dual-region weighting system that intelligently balances short-term responsiveness with long-term trend context, solving the fundamental limitation of standard EMAs where longer periods necessarily sacrifice recent price sensitivity.
Key Differences from Standard EMA:
Adaptive Regional Weighting: Applies stronger exponential decay to recent price data while maintaining appropriate weighting for historical context.
Maintains Responsiveness at Any Length: Unlike standard EMAs where longer periods become progressively less responsive, REMA preserves significant sensitivity to recent price action even at 100+ period lengths.
Mathematically Sound Enhancement: Preserves the core mathematical integrity of exponential averaging while introducing region-specific weighting that better reflects how traders actually interpret price action.
Value to TradingView Community:
Improved Signal Timing: Detects reversals 1-3 bars earlier than traditional EMAs without increasing false signals.
Better Multi-Timeframe Analysis: Provides more consistent behavior across different period settings, reducing conflicting signals between timeframes.
Ideal for Modern Markets: Better handles today's high-volatility, algorithm-driven markets where traditional indicators often lag too much to be effective.
Optimized for Both Trend and Reversal Trading: Simultaneously provides strong trend-following capabilities while remaining sensitive to legitimate reversal signals.
Computation Efficiency: The fast implementation offers enhanced capabilities with minimal computational overhead, making it practical for real-time analysis.
REMA fills a critical gap between lagging long-period EMAs and noisy short-period EMAs, giving traders a single, versatile tool that adapts to market conditions more effectively than standard technical indicators.
Implementation:
rema(src, length, recency_bias, transition_point)
Regional Exponential Moving Average that maintains recent price sensitivity even with long lookback periods
Parameters:
src (float) : Input source series
length (int) : Overall EMA period length
recency_bias (float) : Weighting factor to increase sensitivity to recent prices (1.0-3.0 recommended)
transition_point (float) : Percentage point (0.0-1.0) in the lookback period where weighting shifts from recent to historical
Returns: Custom exponentially weighted moving average with regional bias
rema_fast(src, length, recency_bias)
Simplified Regional EMA that uses a recursive calculation method
Parameters:
src (float) : Input source series
length (int) : Overall EMA period
recency_bias (float) : Factor to increase sensitivity to recent price (1.0-3.0 recommended)
Returns: Computationally efficient regional EMA
AllCandlestickPatternsLibraryAll Candlestick Patterns Library
The Candlestick Patterns Library is a Pine Script (version 6) library extracted from the All Candlestick Patterns indicator. It provides a comprehensive set of functions to calculate candlestick properties, detect market trends, and identify various candlestick patterns (bullish, bearish, and neutral). The library is designed for reusability, enabling TradingView users to incorporate pattern detection into their own scripts, such as indicators or strategies.
The library is organized into three main sections:
Trend Detection: Functions to determine market trends (uptrend or downtrend) based on user-defined rules.
Candlestick Property Calculations: A function to compute core properties of a candlestick, such as body size, shadow lengths, and doji characteristics.
Candlestick Pattern Detection: Functions to detect specific candlestick patterns, each returning a tuple with detection status, pattern name, type, and description.
Library Structure
1. Trend Detection
This section includes the detectTrend function, which identifies whether the market is in an uptrend or downtrend based on user-specified rules, such as the relationship between the closing price and Simple Moving Averages (SMAs).
Function: detectTrend
Parameters:
downTrend (bool): Initial downtrend condition.
upTrend (bool): Initial uptrend condition.
trendRule (string): The rule for trend detection ("SMA50" or "SMA50, SMA200").
p_close (float): Current closing price.
sma50 (float): Simple Moving Average over 50 periods.
sma200 (float): Simple Moving Average over 200 periods.
Returns: A tuple indicating the detected trend.
Logic:
If trendRule is "SMA50", a downtrend is detected when p_close < sma50, and an uptrend when p_close > sma50.
If trendRule is "SMA50, SMA200", a downtrend is detected when p_close < sma50 and sma50 < sma200, and an uptrend when p_close > sma50 and sma50 > sma200.
2. Candlestick Property Calculations
This section includes the calculateCandleProperties function, which computes essential properties of a candlestick based on OHLC (Open, High, Low, Close) data and configuration parameters.
Function: calculateCandleProperties
Parameters:
p_open (float): Candlestick open price.
p_close (float): Candlestick close price.
p_high (float): Candlestick high price.
p_low (float): Candlestick low price.
bodyAvg (float): Average body size (e.g., from EMA of body sizes).
shadowPercent (float): Minimum shadow size as a percentage of body size.
shadowEqualsPercent (float): Tolerance for equal shadows in doji detection.
dojiBodyPercent (float): Maximum body size as a percentage of range for doji detection.
Returns: A tuple containing 17 properties:
C_BodyHi (float): Higher of open or close price.
C_BodyLo (float): Lower of open or close price.
C_Body (float): Body size (difference between C_BodyHi and C_BodyLo).
C_SmallBody (bool): True if body size is below bodyAvg.
C_LongBody (bool): True if body size is above bodyAvg.
C_UpShadow (float): Upper shadow length (p_high - C_BodyHi).
C_DnShadow (float): Lower shadow length (C_BodyLo - p_low).
C_HasUpShadow (bool): True if upper shadow exceeds shadowPercent of body.
C_HasDnShadow (bool): True if lower shadow exceeds shadowPercent of body.
C_WhiteBody (bool): True if candle is bullish (p_open < p_close).
C_BlackBody (bool): True if candle is bearish (p_open > p_close).
C_Range (float): Candlestick range (p_high - p_low).
C_IsInsideBar (bool): True if current candle body is inside the previous candle's body.
C_BodyMiddle (float): Midpoint of the candle body.
C_ShadowEquals (bool): True if upper and lower shadows are equal within shadowEqualsPercent.
C_IsDojiBody (bool): True if body size is small relative to range (C_Body <= C_Range * dojiBodyPercent / 100).
C_Doji (bool): True if the candle is a doji (C_IsDojiBody and C_ShadowEquals).
Purpose: These properties are used by pattern detection functions to evaluate candlestick formations.
3. Candlestick Pattern Detection
This section contains functions to detect specific candlestick patterns, each returning a tuple . The patterns are categorized as bullish, bearish, or neutral, and include detailed descriptions for use in tooltips or alerts.
Supported Patterns
The library supports the following candlestick patterns, grouped by type:
Bullish Patterns:
Rising Window: A two-candle continuation pattern in an uptrend with a price gap between the first candle's high and the second candle's low.
Rising Three Methods: A five-candle continuation pattern with a long green candle, three short red candles, and another long green candle.
Tweezer Bottom: A two-candle reversal pattern in a downtrend with nearly identical lows.
Upside Tasuki Gap: A three-candle continuation pattern in an uptrend with a gap between the first two green candles and a red candle closing partially into the gap.
Doji Star (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a doji gapping down.
Morning Doji Star: A three-candle reversal pattern with a long red candle, a doji gapping down, and a long green candle.
Piercing: A two-candle reversal pattern in a downtrend with a red candle followed by a green candle closing above the midpoint of the first.
Hammer: A single-candle reversal pattern in a downtrend with a small body and a long lower shadow.
Inverted Hammer: A single-candle reversal pattern in a downtrend with a small body and a long upper shadow.
Morning Star: A three-candle reversal pattern with a long red candle, a short candle gapping down, and a long green candle.
Marubozu White: A single-candle pattern with a long green body and minimal shadows.
Dragonfly Doji: A single-candle reversal pattern in a downtrend with a doji where open and close are at the high.
Harami Cross (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a doji inside its body.
Harami (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a small green candle inside its body.
Long Lower Shadow: A single-candle pattern with a long lower shadow indicating buyer strength.
Three White Soldiers: A three-candle reversal pattern with three long green candles in a downtrend.
Engulfing (Bullish): A two-candle reversal pattern in a downtrend with a small red candle followed by a larger green candle engulfing it.
Abandoned Baby (Bullish): A three-candle reversal pattern with a long red candle, a doji gapping down, and a green candle gapping up.
Tri-Star (Bullish): A three-candle reversal pattern with three doji candles in a downtrend, with gaps between them.
Kicking (Bullish): A two-candle reversal pattern with a bearish marubozu followed by a bullish marubozu gapping up.
Bearish Patterns:
On Neck: A two-candle continuation pattern in a downtrend with a long red candle followed by a short green candle closing near the first candle's low.
Falling Window: A two-candle continuation pattern in a downtrend with a price gap between the first candle's low and the second candle's high.
Falling Three Methods: A five-candle continuation pattern with a long red candle, three short green candles, and another long red candle.
Tweezer Top: A two-candle reversal pattern in an uptrend with nearly identical highs.
Dark Cloud Cover: A two-candle reversal pattern in an uptrend with a green candle followed by a red candle opening above the high and closing below the midpoint.
Downside Tasuki Gap: A three-candle continuation pattern in a downtrend with a gap between the first two red candles and a green candle closing partially into the gap.
Evening Doji Star: A three-candle reversal pattern with a long green candle, a doji gapping up, and a long red candle.
Doji Star (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a doji gapping up.
Hanging Man: A single-candle reversal pattern in an uptrend with a small body and a long lower shadow.
Shooting Star: A single-candle reversal pattern in an uptrend with a small body and a long upper shadow.
Evening Star: A three-candle reversal pattern with a long green candle, a short candle gapping up, and a long red candle.
Marubozu Black: A single-candle pattern with a long red body and minimal shadows.
Gravestone Doji: A single-candle reversal pattern in an uptrend with a doji where open and close are at the low.
Harami Cross (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a doji inside its body.
Harami (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a small red candle inside its body.
Long Upper Shadow: A single-candle pattern with a long upper shadow indicating seller strength.
Three Black Crows: A three-candle reversal pattern with three long red candles in an uptrend.
Engulfing (Bearish): A two-candle reversal pattern in an uptrend with a small green candle followed by a larger red candle engulfing it.
Abandoned Baby (Bearish): A three-candle reversal pattern with a long green candle, a doji gapping up, and a red candle gapping down.
Tri-Star (Bearish): A three-candle reversal pattern with three doji candles in an uptrend, with gaps between them.
Kicking (Bearish): A two-candle reversal pattern with a bullish marubozu followed by a bearish marubozu gapping down.
Neutral Patterns:
Doji: A single-candle pattern with a very small body, indicating indecision.
Spinning Top White: A single-candle pattern with a small green body and long upper and lower shadows, indicating indecision.
Spinning Top Black: A single-candle pattern with a small red body and long upper and lower shadows, indicating indecision.
Pattern Detection Functions
Each pattern detection function evaluates specific conditions based on candlestick properties (from calculateCandleProperties) and trend conditions (from detectTrend). The functions return:
detected (bool): True if the pattern is detected.
name (string): The name of the pattern (e.g., "On Neck").
type (string): The pattern type ("Bullish", "Bearish", or "Neutral").
description (string): A detailed description of the pattern for use in tooltips or alerts.
For example, the detectOnNeckBearish function checks for a bearish On Neck pattern by verifying a downtrend, a long red candle followed by a short green candle, and specific price relationships.
Usage Example
To use the library in a TradingView indicator, you can import it and call its functions as shown below:
//@version=6
indicator("Candlestick Pattern Detector", overlay=true)
import CandlestickPatternsLibrary as cp
// Calculate SMA for trend detection
sma50 = ta.sma(close, 50)
sma200 = ta.sma(close, 200)
= cp.detectTrend(true, true, "SMA50", close, sma50, sma200)
// Calculate candlestick properties
bodyAvg = ta.ema(math.max(close, open) - math.min(close, open), 14)
= cp.calculateCandleProperties(open, close, high, low, bodyAvg, 5.0, 100.0, 5.0)
// Detect a pattern (e.g., On Neck Bearish)
= cp.detectOnNeckBearish(downTrend, blackBody, longBody, whiteBody, open, close, low, bodyAvg, smallBody, candleRange)
if onNeckDetected
label.new(bar_index, low, onNeckName, style=label.style_label_up, color=color.red, textcolor=color.white, tooltip=onNeckDesc)
// Detect another pattern (e.g., Piercing Bullish)
= cp.detectPiercingBullish(downTrend, blackBody, longBody, whiteBody, open, low, close, bodyMiddle)
if piercingDetected
label.new(bar_index, low, piercingName, style=label.style_label_up, color=color.blue, textcolor=color.white, tooltip=piercingDesc)
Steps in the Example
Import the Library: Use import CandlestickPatternsLibrary as cp to access the library's functions.
Calculate Trend: Use detectTrend to determine the market trend based on SMA50 or SMA50/SMA200 rules.
Calculate Candlestick Properties: Use calculateCandleProperties to compute properties like body size, shadow lengths, and doji status.
Detect Patterns: Call specific pattern detection functions (e.g., detectOnNeckBearish, detectPiercingBullish) and use the returned values to display labels or alerts.
Visualize Patterns: Use label.new to display detected patterns on the chart with their names, types, and descriptions.
Key Features
Modularity: The library is designed as a standalone module, making it easy to integrate into other Pine Script projects.
Comprehensive Pattern Coverage: Supports over 40 candlestick patterns, covering bullish, bearish, and neutral formations.
Detailed Documentation: Each function includes comments with @param and @returns annotations for clarity.
Reusability: Can be used in indicators, strategies, or alerts by importing the library and calling its functions.
Extracted from All Candlestick Patterns: The library is derived from the All Candlestick Patterns indicator, ensuring it inherits a well-tested foundation for pattern detection.
Notes for Developers
Pine Script Version: The library uses Pine Script version 6, as specified by //@version=6.
Parameter Naming: Parameters use prefixes like p_ (e.g., p_open, p_close) to avoid conflicts with built-in variables.
Error Handling: The library has been fixed to address issues like undeclared identifiers (C_SmallBody, C_Range), unused arguments (factor), and improper comment formatting.
Testing: Developers should test the library in TradingView to ensure patterns are detected correctly under various market conditions.
Customization: Users can adjust parameters like bodyAvg, shadowPercent, shadowEqualsPercent, and dojiBodyPercent in calculateCandleProperties to fine-tune pattern detection sensitivity.
Conclusion
The Candlestick Patterns Library, extracted from the All Candlestick Patterns indicator, is a powerful tool for traders and developers looking to implement candlestick pattern detection in TradingView. Its modular design, comprehensive pattern support, and detailed documentation make it an ideal choice for building custom indicators or strategies. By leveraging the library's functions, users can analyze market trends, compute candlestick properties, and detect a wide range of patterns to inform their trading decisions.
WhispererRealtimeVolumeLibrary "WhispererRealtimeVolume"
▮ Overview
The Whisperer Realtime Volume Library is a lightweight and reusable Pine Script® library designed for real-time volume analysis.
It calculates up, down, and neutral volumes dynamically, making it an essential tool for traders who want to gain deeper insights into market activity.
This library is a simplified and modular version of the original "Realtime Volume Bars w Market Buy/Sell/Neutral split & Mkt Delta" indicator by the_MarketWhisperer , tailored for integration into custom scripts.
How bars are classified
- Up Bars
If the current bar’s closing price is higher than the previous bar’s closing price, it is classified as an up bar.
Volume handling:
The increase in volume for this bar is added to the up volume.
This represents buying pressure.
- Down Bars
If the current bar’s closing price is lower than the previous bar’s closing price, it is classified as a down bar.
Volume handling:
The increase in volume for this bar is added to the down volume.
This represents selling pressure.
- Neutral Bars
If the current bar’s closing price is the same as the previous bar’s closing price, it is classified as a neutral bar.
Volume handling:
If neutral volume is enabled, the volume is added to the neutral volume.
If neutral volume is not enabled, the volume is assigned to the same direction as the previous bar (up or down). If the previous direction is unknown, it is added to the neutral volume.
▮ What to look for
Real-Time Volume Calculation : Analyze up, down, and neutral volumes in real-time based on price movements and bar volume.
Customizable Start Line : Add a visual reference line to your chart for better context by viewing the starting point of real-time bars.
Ease of Integration : Designed as a library for seamless use in other Pine Script® indicators or strategies.
▮ How to use
Example code:
//@version=6
indicator("Volume Realtime from Whisperer")
import andre_007/WhispererRealtimeVolume/4 as MW
MW.displayStartLine(startLineColor = color.gray, startLineWidth = 1, startLineStyle = line.style_dashed,
displayStartLine = true, y1=volume, y2=volume + 10)
= MW.mw_upDownVolumeRealtime(true)
plot(volume, style=plot.style_columns, color=color.gray)
plot(volumeUp, style=plot.style_columns, color=color.green)
plot(volumeDown, style=plot.style_columns, color=color.red)
plot(volumeNeutral, style=plot.style_columns, color=color.purple)
▮ Credits
This library is inspired by the original work of the_MarketWhisperer , whose "Realtime Volume Bars" indicator served as the foundation.
Link to original indicator :
reversalchartpatternsLibrary "reversalchartpatterns"
User Defined Types and Methods for reversal chart patterns - Double Top, Double Bottom, Triple Top, Triple Bottom, Cup and Handle, Inverted Cup and Handle, Head and Shoulders, Inverse Head and Shoulders
method delete(this)
Deletes the drawing components of ReversalChartPatternDrawing object
Namespace types: ReversalChartPatternDrawing
Parameters:
this (ReversalChartPatternDrawing) : ReversalChartPatternDrawing object
Returns: current ReversalChartPatternDrawing object
method delete(this)
Deletes the drawing components of ReversalChartPattern object. In turn calls the delete of ReversalChartPatternDrawing
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: current ReversalChartPattern object
method lpush(this, obj, limit, deleteOld)
Array push with limited number of items in the array. Old items are deleted when new one comes and exceeds the limit
Namespace types: array
Parameters:
this (array) : array object
obj (ReversalChartPattern) : ReversalChartPattern object which need to be pushed to the array
limit (int) : max items on the array. Default is 10
deleteOld (bool) : If set to true, also deletes the drawing objects. If not, the drawing objects are kept but the pattern object is removed from array. Default is false.
Returns: current ReversalChartPattern object
method draw(this)
Draws the components of ReversalChartPatternDrawing
Namespace types: ReversalChartPatternDrawing
Parameters:
this (ReversalChartPatternDrawing) : ReversalChartPatternDrawing object
Returns: current ReversalChartPatternDrawing object
method draw(this)
Draws the components of ReversalChartPatternDrawing within the ReversalChartPattern object.
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: current ReversalChartPattern object
method scan(zigzag, patterns, errorPercent, shoulderStart, shoulderEnd, allowedPatterns, offset)
Scans zigzag for ReversalChartPattern occurences
Namespace types: zg.Zigzag
Parameters:
zigzag (Zigzag type from Trendoscope/Zigzag/11) : ZigzagTypes.Zigzag object having array of zigzag pivots and other information on each pivots
patterns (array) : Existing patterns array. Used for validating duplicates
errorPercent (float) : Error threshold for considering ratios. Default is 13
shoulderStart (float) : Starting range of shoulder ratio. Used for identifying shoulders, handles and necklines
shoulderEnd (float) : Ending range of shoulder ratio. Used for identifying shoulders, handles and necklines
allowedPatterns (array) : array of int containing allowed pattern types
offset (int) : Offset of zigzag to consider only confirmed pivots
Returns: int pattern type
method createPattern(zigzag, patternType, patternColor, properties, offset)
Create Pattern from ZigzagTypes.Zigzag object
Namespace types: zg.Zigzag
Parameters:
zigzag (Zigzag type from Trendoscope/Zigzag/11) : ZigzagTypes.Zigzag object having array of zigzag pivots and other information on each pivots
patternType (int) : Type of pattern being created. 1 - Double Tap, 2 - Triple Tap, 3 - Cup and Handle, 4 - Head and Shoulders
patternColor (color) : Color in which the patterns are drawn
properties (ReversalChartTradeProperties)
offset (int)
Returns: ReversalChartPattern object created
method getName(this)
get pattern name of ReversalChartPattern object
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: string name of the pattern
method getDescription(this)
get consolidated description of ReversalChartPattern object
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: string consolidated description
method init(this)
initializes the ReversalChartPattern object and creates sub object types
Namespace types: ReversalChartPattern
Parameters:
this (ReversalChartPattern) : ReversalChartPattern object
Returns: ReversalChartPattern current object
ReversalChartPatternDrawing
Type which holds the drawing objects for Reversal Chart Pattern Types
Fields:
patternLines (array type from Trendoscope/Drawing/2) : array of Line objects representing pattern
entry (Line type from Trendoscope/Drawing/2) : Entry price Line
targets (array type from Trendoscope/Drawing/2)
stop (Line type from Trendoscope/Drawing/2) : Stop price Line
patternLabel (Label type from Trendoscope/Drawing/2)
ReversalChartTradeProperties
Trade properties of ReversalChartPattern
Fields:
riskAdjustment (series float) : Risk Adjustment for calculation of stop
useFixedTarget (series bool) : Boolean flag saying use fixed target type wherever possible. If fixed target type is not possible, then risk reward/fib ratios are used for calculation of targets
variableTargetType (series int) : Integer value which defines whether to use fib based targets or risk reward based targets. 1 - Risk Reward, 2 - Fib Ratios
variableTargetRatios (array) : Risk reward or Fib Ratios to be used for calculation of targets when fixed target is not possible or not enabled
entryPivotForWm (series int) : which Pivot should be considered as entry point for WM patterns. 0 refers to the latest breakout pivot where as 5 refers to initial pivot of the pattern
ReversalChartPattern
Reversal Chart Pattern master type which holds the pattern components, drawings and trade details
Fields:
pivots (array type from Trendoscope/Zigzag/11) : Array of Zigzag Pivots forming the pattern
patternType (series int) : Defines the main type of pattern 1 - Double Tap, 1 - Triple Tap, 3 - Cup and Handle, 4 - Head and Shoulders, 5- W/M Patterns, 6 - Full Trend, 7 - Half Trend
patternColor (series color) : Color in which the pattern will be drawn on chart
properties (ReversalChartTradeProperties)
drawing (ReversalChartPatternDrawing) : ReversalChartPatternDrawing object which holds the drawing components
trade (Trade type from Trendoscope/TradeTracker/1) : TradeTracker.Trade object holding trade components
CandlestickUtilitiesThis library provides essential functions for candlestick chart analysis and pattern recognition in Pine Script®.
It includes:
• Candle structure analysis (bodies, shadows, lengths)
• Trend detection using EMAs
• Common candlestick pattern recognition
This library is under construction.
Designed to support strategy development and improve signal accuracy for traders.
Created by @xprophetx — under MPL-2.0 license.
tafirstlibGeneral Purpose: Starts by stating it's a collection of utility functions for technical analysis.
Core Functionality Areas: Mentions key categories like:
Extrema detection (isMin, isMax, etc.)
Condition checking over time (isMachedInRange, isContinuous, etc.)
Rate of change analysis (isSlowDown)
Moving average calculation (getMA)
Advanced Features: Highlights the more complex functions:
Visualization helpers (getColorNew)
Moving Regression (mr) for smoothing/trend
Cycle analysis (bpDom)
Overall Goal: Concludes by stating the library's aim – simplifying development and enabling complex analysis.
Library "tafirstlib"
TODO: add library description here
isSlowDown(data)
isSlowDown
Parameters:
data (float) : array of numbers
Returns: boolean
isMin(data, maeLength)
isMin
Parameters:
data (float) : array of numbers
maeLength (int) : number
Returns: boolean
isMax(data, maeLength)
isMax
Parameters:
data (float) : array of numbers
maeLength (int) : number
Returns: boolean
isMinStopped(data, maeLength)
isMinStopped
Parameters:
data (float) : array of numbers
maeLength (int) : number
Returns: boolean
isMaxStopped(data, maeLength)
isMaxStopped
Parameters:
data (float) : array of numbers
maeLength (int) : number
Returns: boolean
isLongMinStopped(data, maeLength, distance)
isLongMinStopped
Parameters:
data (float) : array of numbers
maeLength (int) : number
distance (int) : number
Returns: boolean
isLongMaxStopped(data, maeLength, distance)
isLongMaxStopped
Parameters:
data (float) : array of numbers
maeLength (int) : number
distance (int) : number
Returns: boolean
isMachedInRangeSkipCurrent(data, findRange, findValue)
isMachedInRangeSkipCurrent
Parameters:
data (bool) : array of numbers
findRange (int) : number
findValue (bool) : number
Returns: boolean
isMachedInRange(data, findRange, findValue)
isMachedInRange
Parameters:
data (bool) : array of numbers
findRange (int) : number
findValue (bool) : number
Returns: boolean
isMachedColorInRange(data, findRange, findValue)
isMachedColorInRange isMachedColorInRange(series color data, int findRange, color findValue)
Parameters:
data (color) : series of color
findRange (int) : int
findValue (color) : color
Returns: boolean
countMachedInRange(data, findRange, findValue)
countMachedInRange
Parameters:
data (bool) : array of numbers
findRange (int) : number
findValue (bool) : number
Returns: number
getColor(data)
getColor
Parameters:
data (float) : array of numbers
Returns: color
getColorNew(data)
getColorNew
Parameters:
data (float) : array of numbers
Returns: color
isColorBetter(color_data)
isColorBetter
Parameters:
color_data (color) : array of colors
Returns: boolean
isColorWorst(color_data)
isColorWorst
Parameters:
color_data (color) : array of colors
Returns: boolean
isColorBetter2(color_data)
isColorBetter2
Parameters:
color_data (color) : array of colors
Returns: boolean
isColorWorst2(color_data)
isColorWorst2
Parameters:
color_data (color) : array of colors
Returns: boolean
isDecreased2Bar(data)
isDecreased2Bar
Parameters:
data (float) : array of numbers
Returns: boolean
isContinuousAdvance(targetSeries, range2Find, howManyException)
isContinuousAdvance
Parameters:
targetSeries (bool) : array of booleans
range2Find (int) : number
howManyException (int) : number
Returns: boolean
isContinuous(targetSeries, range2Find, truefalse)
isContinuous
Parameters:
targetSeries (bool) : array of booleans
range2Find (int) : number
truefalse (bool) : boolean
Returns: boolean
isContinuousNotNow(targetSeries, range2Find, truefalse)
isContinuousNotNow
Parameters:
targetSeries (bool) : array of booleans
range2Find (int) : number
truefalse (bool) : boolean
Returns: boolean
isContinuousTwoFactors(targetSeries, range2Find, truefalse)
isContinuousTwoFactors
Parameters:
targetSeries (bool) : array of booleans
range2Find (int) : number
truefalse (bool) : boolean
Returns: boolean
findEventInRange(startDataBarIndex, neededDataBarIndex, currentBarIndex)
findEventInRange
Parameters:
startDataBarIndex (int) : number
neededDataBarIndex (int) : number
currentBarIndex (int) : number
Returns: boolean
findMin(firstdata, secondata, thirddata, forthdata)
findMin
Parameters:
firstdata (float) : number
secondata (float) : number
thirddata (float) : number
forthdata (float) : number
Returns: number
findMax(firstdata, secondata, thirddata, forthdata)
findMax
Parameters:
firstdata (float) : number
secondata (float) : number
thirddata (float) : number
forthdata (float) : number
Returns: number
getMA(src, length, mav)
getMA
Parameters:
src (float) : number
length (simple int) : number
mav (string) : string
Returns: number
mr(mrb_src, mrb_window, mrb_degree)
Parameters:
mrb_src (float)
mrb_window (int)
mrb_degree (int)
bpDom(maeLength, bpw, mult)
Parameters:
maeLength (int)
bpw (float)
mult (float)
CSCMultiTimeframeToolsLibrary "CSCMultiTimeframeTools"
Calculates instant higher timeframe values for higher timeframe analysis with zero lag.
getAdjustedLookback(current_tf_minutes, higher_tf_minutes, length)
Calculate adjusted lookback period for higher timeframe conversion.
Parameters:
current_tf_minutes (int) : Current chart timeframe in minutes (e.g., 5 for 5m).
higher_tf_minutes (int) : Target higher timeframe in minutes (e.g., 15 for 15m).
length (int) : Base length value (e.g., 14 for RSI/MFI).
Returns: Adjusted lookback period (length × multiplier).
Purpose and Benefits of the TimeframeTools Library
This library is designed to solve a critical pain point for traders who rely on higher timeframe (HTF) indicator values while analyzing lower timeframe (LTF) charts. Traditional methods require waiting for multiple candles to close—for example, to see a 1-hour RSI on a 5-minute chart, you’d need 12 closed candles (5m × 12 = 60m) before the value updates. This lag means missed opportunities, delayed signals, and inefficient decision-making.
Why Traders Need This
Whether you’re scalping (5M/15M) or swing trading (1H/4H), this library bridges the gap between timeframes, giving you HTF context in real time—so you can act faster, with confidence.
How This Library Eliminates the Waiting Game
By dynamically calculating the adjusted lookback period, the library allows:
Real-time HTF values on LTF charts – No waiting for candle closes.
Accurate conversions – A 14-period RSI on a 1-hour chart translates to 168 periods (14 × 12) on a 5-minute chart, ensuring mathematical precision.
Flexible application – Works with common indicators like RSI, MFI, CCI, and moving averages (though confirmations should be done before publishing under your own secondary use).
Key Advantages Over Manual Methods
Speed: Instantly reflects HTF values without waiting for candle resolutions.
Adaptability: Adjusts automatically if the user changes timeframes or lengths.
Consistency: Removes human error in manual period calculations.
Limitations to Note
Not a magic bullet – While it solves the lag issue, traders should still:
Validate signals with price action or additional confirmations.
Be mindful of extreme lookback lengths (e.g., a 200-period daily SMA on a 1-minute chart requires 28,800 periods, which may strain performance).
PineVersatilitiesBundleLibrary "PineVersatilitiesBundle"
Versatilities (aka, Versatile Utilities) Pack includes:
- Eighteen Price Variants bundled in a Map,
- Nine Smoothing Variants bundled in a Map,
- Visualisations that indicate on both - pane and chart.
price_variants(lb)
Computes Several different averages using current and previous OHLC values
Parameters:
lb (int) : - lookback distance for combining OHLC values from the past with the present
Returns: Map of Eighteen Uncommon Combinations of single and two-bar OHLC averages (rounded-to-mintick)
dynamic_MA(masrc, malen, lsmaoff, almasgm, almaoff, almaflr)
Dynamically computes Eight different MAs and returns a Map containing Nine MAs
Parameters:
masrc (float) : source series to compute MA
malen (simple int) : lookback distance for MA
lsmaoff (simple int) : optional LSMA offset - default is 0
almasgm (simple float) : optional ALMA sigma - default is 5
almaoff (simple float) : optional ALMA offset - default is 0.5
almaflr (simple bool) : optional ALMA floor flag - default is false
Returns: Map of MAs - 'ALMA', 'EMA', 'HMA', 'LSMA', 'RMA', 'SMA', 'SWMA', 'WMA', 'ALL' (rounded-to-mintick)
PivotLabelsLibrary "PivotLabels"
drawPivots(qtyLabels, leftLegs, rightLegs)
Displays a label for each of the last `qtyLabels` pivots.
Colors high pivots in green, low pivots in red, and breached pivots in gray.
Parameters:
qtyLabels (int) : (simple int) Quantity of last labels to display.
leftLegs (int) : (simple int) Left pivot legs.
rightLegs (int) : (simple int) Right pivot legs.
Returns: Nothing.
bollingerBandsV2Library "bollingerBandsV2"
Bollinger bands related functions
get_multiple_bollinger_bands(stdv1, stdv2, stdv3, stdv4, stdv5, stdv6, stdv7, length, source)
: Calculates 7 sets of bollinger bands, with 7 different standard deviations
Parameters:
stdv1 (float) : (simple int): standard deviation 1
stdv2 (float) : (simple int): standard deviation 2
stdv3 (float) : (simple int): standard deviation 3
stdv4 (float) : (simple int): standard deviation 4
stdv5 (float) : (simple int): standard deviation 5
stdv6 (float) : (simple int): standard deviation 6
stdv7 (float) : (simple int): standard deviation 7
length (simple int) : (simple int): Length for the bands
source (float) : (simple float): source for the calculation
Returns: : Returns 8 levels plus the range of all the levels.
get_bb_volatility(bb_highest, bb_lowest, ma_length, lookback)
: Provides a volatility indicator based on Bollinger Bands, and indicates wheather the volatility is increasing or decreasing.
Parameters:
bb_highest (float) : (simple float): Top Bollinger Band on which to calculate the range.
bb_lowest (float) : (simple float): Bottom Bollinger Band on which to calculate the range.
ma_length (simple int) : (simple int): Length to use in the smoothing of Bollinger Bands range.
lookback (int) : (simple int): Lookback period to identify a change in the Bollinger Bands range.
Returns: : Returns 8 levels plus the range of all the levels.
get_bbVolatility_data(source, length, stdv1, stdv2, stdv3, stdv4, stdv5, stdv6, stdv7, trend_direction)
: Generates Bollinger Bands Volatility
Parameters:
source (float) : (float): Source for Bollinger Bands
length (simple int) : (int): Length for Bollinger Bands
stdv1 (int) : (int): Standard Deviation 1
stdv2 (int) : (int): Standard Deviation 2
stdv3 (int) : (int): Standard Deviation 3
stdv4 (int) : (int): Standard Deviation 4
stdv5 (int) : (int): Standard Deviation 5
stdv6 (int) : (int): Standard Deviation 6
stdv7 (int) : (int): Standard Deviation 7
trend_direction (string) : (string): Current direction of the trend
Returns: : Returns a map with the levels, plus direction flag and the data table