3 Way ValuationThe 3 Way Valuation (3WV) is a composite oscillator that evaluates market conditions by combining a diverse range of metrics into a single smoothed value between 0 and 1. It draws from multiple domains, including momentum, trend strength, volatility, risk-adjusted return ratios, and volume-based analytics to offer a well-rounded view of an asset’s relative positioning.
At its core, 3WV integrates three statistical approaches: Percentile Ranking to assess how current values compare to historical distributions, Z-Score Normalization to measure deviation from the average, and Empirical CDF (ECDF) to estimate the probability of observing a value based on past behavior. These methods are applied across all selected metrics, then normalized and averaged for a comprehensive market sentiment score.
Users can tailor the smoothing level and choose whether to include volume-based components for enhanced filtering. The indicator highlights potential overbought and oversold conditions with customizable thresholds, making it a versatile tool for timing entries, exits, or confirming broader strategies.
Statistics
Leavitt Convolution ProbabilityTechnical Analysis of Markets with Leavitt Market Projections and Associated Convolution Probability
The aim of this study is to present an innovative approach to market analysis based on the research "Leavitt Market Projections." This technical tool combines one indicator and a probability function to enhance the accuracy and speed of market forecasts.
Key Features
Advanced Indicators : the script includes the Convolution line and a probability oscillator, designed to anticipate market changes. These indicators provide timely signals and offer a clear view of price dynamics.
Convolution Probability Function : The Convolution Probability (CP) is a key element of the script. A significant increase in this probability often precedes a market decline, while a decrease in probability can signal a bullish move. The Convolution Probability Function:
At each bar, i, the linear regression routine finds the two parameters for the straight line: y=mix+bi.
Standard deviations can be calculated from the sequence of slopes, {mi}, and intercepts, {bi}.
Each standard deviation has a corresponding probability.
Their adjusted product is the Convolution Probability, CP. The construction of the Convolution Probability is straightforward. The adjusted product is the probability of one times 1− the probability of the other.
Customizable Settings : Users can define oversold and overbought levels, as well as set an offset for the linear regression calculation. These options allow for tailoring the script to individual trading strategies and market conditions.
Statistical Analysis : Each analyzed bar generates regression parameters that allow for the calculation of standard deviations and associated probabilities, providing an in-depth view of market dynamics.
The results from applying this technical tool show increased accuracy and speed in market forecasts. The combination of Convolution indicator and the probability function enables the identification of turning points and the anticipation of market changes.
Additional information:
Leavitt, in his study, considers the SPY chart.
When the Convolution Probability (CP) is high, it indicates that the probability P1 (related to the slope) is high, and conversely, when CP is low, P1 is low and P2 is high.
For the calculation of probability, an approximate formula of the Cumulative Distribution Function (CDF) has been used, which is given by: CDF(x)=21(1+erf(σ2x−μ)) where μ is the mean and σ is the standard deviation.
For the calculation of probability, the formula used in this script is: 0.5 * (1 + (math.sign(zSlope) * math.sqrt(1 - math.exp(-0.5 * zSlope * zSlope))))
Conclusions
This study presents the approach to market analysis based on the research "Leavitt Market Projections." The script combines Convolution indicator and a Probability function to provide more precise trading signals. The results demonstrate greater accuracy and speed in market forecasts, making this technical tool a valuable asset for market participants.
CME Price LimitCalculates the CME Price Limit
The reference price is obtained from the previous day's closing settlement price
(data pulled from the asset's daily chart with settlement enabled)
Percentage limit can be modified in settings
Buffer can be enabled (for example, 2% buffer on a 7% limit, so a line gets drawn at 5% too)
Alert can be enabled for price crossing a certain percentage from reference on the day
You can choose to plot the historical lines on every day, or the current day only
The reference price output can be found in the data window, or in the indicator status line if enabled in the settings.
Before placing real trades with this, you should compare the indicator's reference price to what's shown on CME's website, to double check that TradingView's data matches for your contract.
www.cmegroup.com
Drawdown Visualizer v1.0Drawdown Visualizer
The Drawdown Visualizer tracks the percentage decline from all-time highs, providing valuable insights into market corrections and potential buying opportunities.
Key Features:
1) Real-Time Drawdown Tracking: The indicator continuously calculates and displays the current percentage drawdown from the all-time high price, color-coded from green (minimal drawdown) to red (severe drawdown) for instant visual feedback.
2) Maximum Drawdown Detection: Permanently tracks and displays the maximum historical drawdown encountered during the analyzed period, helping traders understand worst-case scenarios.
3) Statistical Analysis: Calculates and displays three important statistical measures:
* Average Drawdown: The mean value of all drawdowns recorded
* Median Drawdown: The middle value in the sorted list of all drawdowns, providing insight
into typical decline patterns
* Normal Drawdown Range: Visualizes the expected range of typical drawdowns based on
statistical standard deviation
Practical Applications:
1) Risk Management: Understand typical and extreme drawdowns to set appropriate stop-loss levels
2) Market Context: Gain perspective on whether current corrections are normal or exceptional
3) Entry Point Analysis: Identify potential buying opportunities when drawdowns reach statistical extremes
Daily LevelsOverview:
The Daily Levels indicator plots key price levels from the previous trading day, including the high, low, median (pivot), and projected extensions. These levels help traders identify potential support/resistance zones and anticipate breakout or reversal opportunities.
Key Features:
✅ Previous Day High & Low – Visualizes the prior day’s high and low as dynamic support/resistance levels.
✅ Median (Pivot) Line – Calculates the midpoint between the previous day’s high and low, acting as a key intraday reference.
✅ Projected Levels – Extends the high/low range symmetrically above and below the median, highlighting potential breakout zones.
✅ Customizable Display – Toggle visibility, adjust colors, and modify line styles (solid, dotted, dashed).
✅ Price Labels – Clear on-chart labels showing exact price values for quick reference.
✅ Built-in Alerts – Get notified when price crosses any of the key levels.
How to Use:
Trend Identification: If price holds above the median, the bias is bullish; below suggests bearish momentum.
Breakout Trading: Watch for moves beyond the projected levels for potential continuation.
Mean Reversion: Fade moves toward the previous day’s high/low if the median holds as support/resistance.
Ideal For:
Day Traders – Intraday support/resistance levels.
Swing Traders – Context for multi-day trends.
Breakout/Reversal Strategies – Clear levels for trade triggers.
Settings Recommendations:
High/Low Lines: Use semi-transparent colors (e.g., green/red) for clarity.
Projections: Helpful for anticipating extended moves (e.g., teal for upper, orange for lower).
Alerts: Enable notifications for key crosses (e.g., median or high/low breaks).
TS- Multitimeframe📊 The Trend Synchronizer – Multitimeframe Scalper 🔁
Indicator added at the of the chart. - Just in case anyone is confused, and one on chart as overlay is our own Delta zones indicator - as usual available to use for everyone.
🚀 Precision Aligned, Momentum Enhanced
Welcome to the Trend Synchronizer (TS) – a custom-built, multitimeframe momentum indicator developed for active traders looking to scalp lower timeframes (1–5 min) while staying in sync with broader market direction.
🔍 What Is It?
The Trend Synchronizer is an advanced momentum oscillator designed to identify entry opportunities only when multiple timeframes align.
It overlays real-time momentum signals from higher aggregations to ensure your trade is moving with the market, not against it.
✅ When short-term momentum aligns with higher timeframe direction, opportunities are clearer, stronger, and more reliable.
🧠 How to Use It (No Settings Needed)
This tool is ready to go out of the box.
It uses three internal timeframes (default: 1m, 5m, 30m) and processes their behavior to create momentum signals. Here's how to trade it:
📈 Entries
Buy Bias: When histogram bars turn bullish colors across layers and align positively.
Sell Bias: When histogram bars shift to bearish tones, confirming momentum is to the downside.
Avoid Signals when higher timeframe momentum and lower timeframe are diverging – that's when chop often occurs.
⏳ Timeframes
Default is tuned for scalping (1–5m charts), but can be adjusted.
You can change TF1, TF2, and TF3 to experiment with your preferred layers (e.g., 5m/15m/1H for intraday swing entries).
🟢 Color Cues
The color scheme helps you spot bullish and bearish dominance quickly.
Histograms are visually synced: above 0 = strength, below 0 = weakness.
⚙️ Settings
You don’t need to tweak anything unless you want to. The inputs are exposed only for fine-tuners.
TS1, TS2, TS3: Toggle momentum layers on/off.
Custom colors available for personalization.
Clean histogram-style display for clear, fast decision-making.
📌 Best Practices
Combine with price action and volume for higher conviction.
Always look for trend confirmation on your chart before executing.
It’s ideal for:
Momentum scalpers
Order flow traders
High-frequency setups
Trend pullbacks & breakouts
⚠️ Disclaimer
This indicator is for educational purposes only. It is not financial advice and does not guarantee profitability. Always do your own research and use proper risk management. You are solely responsible for your trading decisions.
✨ Final Word
The Trend Synchronizer is a tool designed to help you align with the flow of the market – not fight it. It simplifies the complexity of multiple timeframes into a visual format any trader can interpret.
If you find it useful, don’t forget to ⭐ it and drop a comment with your feedback!
Happy trading and stay in sync!
Day’s Open ForecastOverview
This Pine Script indicator combines two primary components:
1. Day’s Open Forecast:
o Tracks historical daily moves (up and down) from the day’s open.
o Calculates average up and down moves over a user-defined lookback period.
o Optionally includes standard deviation adjustments to forecast potential intraday levels.
o Plots lines on the chart for the forecasted up and down moves from the current day's open.
2. Session VWAP:
o Allows you to specify a custom trading session (by time range and UTC offset).
o Calculates and plots a Volume-Weighted Average Price (VWAP) during that session.
By combining these two features, you can gauge potential intraday moves relative to historical behavior from the open, while also tracking a session-specific VWAP that can act as a dynamic support/resistance reference.
How the Code Works
1. Collect Daily Moves
o The script detects when a new day starts using time("D").
o Once a new day is detected, it stores the previous day’s up-move (dayHigh - dayOpen) and down-move (dayOpen - dayLow) into arrays.
o These arrays keep track of the last N days (default: 126) of up/down move data.
2. Compute Statistics
o The script computes the average (f_average()) of up-moves and down-moves over the stored period.
o It also computes the standard deviation (f_stddev()) of up/down moves for optional “forecast bands.”
3. Forecast Lines
o Plots the current day’s open.
o Plots the average forecast lines above and below the open (Avg Up Move Level and Avg Down Move Level).
o If standard deviation is enabled, plots additional lines (Avg+StdDev Up and Avg+StdDev Down).
4. Session VWAP
o The script detects the start of a user-defined session (via input.session) and resets accumulation of volume and the numerator for VWAP.
o As each bar in the session updates, it accumulates volume (vwapCumulativeVolume) and a price-volume product (vwapCumulativeNumerator).
o The session VWAP is then calculated as (vwapCumulativeNumerator / vwapCumulativeVolume) and plotted.
5. Visualization Options
o Users can toggle standard deviation usage, historical up/down moves plotting, and whether to show the forecast “bands.”
o The vwapSession and vwapUtc inputs let you adjust which session (and time zone offset) the VWAP is calculated for.
________________________________________
How to Use This Indicator on TradingView
1. Create a New Script
o Open TradingView, then navigate to Pine Editor (usually found at the bottom of the chart).
o Copy and paste the entire code into the editor.
2. Save and Add to Chart
o Click Save (give it a relevant title if you wish), then click Add to chart.
o The indicator will appear on your chart with the forecast lines and VWAP.
o By default, it is overlayed on the price chart (because of overlay=true).
3. Customize Inputs
o In the indicator’s settings, you can:
Change lookback days (default: 126).
Enable or disable standard deviation (Include Standard Deviation in Forecast?).
Adjust the standard deviation multiplier.
Choose whether to plot bands (Plot Bands with Averages/StdDev?).
Plot historical moves if desired (Plot Historical Up/Down Moves for Reference?).
Set your custom session and UTC offset for the VWAP calculation.
4. Interpretation
o “Current Day Open” is simply today’s open price on your chart.
o Up/Down Move Lines: Indicate a potential forecast based on historical averages.
If standard deviation is enabled, the second set of lines acts as an extended range.
o VWAP: Helpful for determining intraday price equilibrium over the specified session.
Important Notes / Best Practices
• The script only updates the historical up/down move data once per day (when a new day starts).
• The VWAP portion resets at the start of the specified session each day.
• Standard deviation multiplies the average up/down range, giving you a sense of “volatility range” around the day’s open.
• Adjust the lookback length (dayCount) to balance how many days of data you want to average. More days = smoother but possibly slower to adapt; fewer days = more reactive but potentially less reliable historically.
Educational & Liability Disclaimers
1. Educational Disclaimer
o The information provided by this indicator is for educational and informational purposes only. It is a technical analysis tool intended to demonstrate how to use historical data and basic statistics in Pine Script.
2. No Financial Advice
o This script does not constitute financial or investment advice. All examples and explanations are solely illustrative. You should always do your own analysis before making any investment decisions.
3. No Liability
o The author of this script is not liable for any losses or damages—monetary or otherwise—that may occur from the application of this script.
o Past performance does not guarantee future results, and you should never invest money you cannot afford to lose.
By adding this indicator to your TradingView chart, you acknowledge and accept that you alone are responsible for your own trading decisions.
Enjoy using the “Day’s Open Forecast” and Session VWAP for better market insights!
Trend Targets [AlgoAlpha]OVERVIEW
This script combines a smoothed trend-following model with dynamic price rejection logic and ATR-based target projection to give traders a complete visual framework for trading trend continuations. It overlays on price and automatically detects potential trend shifts, confirms rejections near dynamic support/resistance, and displays calculated stop-loss and take-profit levels to support structured risk-reward management. Unlike traditional indicators that only show trend direction or signal entries, this tool brings together a unique mix of signal validation, volatility-aware positioning, and layered profit-taking to guide decision-making with more context.
CONCEPTS
The core trend logic is built on a custom Supertrend that uses an ATR-based band structure with long smoothing chains—first through a WMA, then an EMA—allowing the trend line to respond to major shifts while ignoring noise. A key addition is the use of rejection logic: the script looks for consolidation candles that "hug" the smoothed trend line and counts how many consecutive bars reject from it. This behavior often precedes significant moves. A user-defined threshold filters out weak tests and highlights only meaningful rejections.
FEATURES
Trend Detection : Automatically identifies trend direction using a smoothed Supertrend (WMA + EMA), with shape markers on trend shifts and color-coded bars for clarity.
Rejection Signals : Detects price rejections at the trend line after a user-defined number of consolidation bars; plots ▲/▼ icons to highlight strong continuation setups.
Target Projection : On trend confirmation, plots entry, stop-loss (ATR-based), and three dynamic take-profit levels based on customizable multiples.
Dynamic Updates : All levels (entry, SL, TP1–TP3) auto-adjust based on volatility and are labeled in real time on the chart.
Customization : Users can tweak trend parameters, rejection confirmation count, SL/TP ratios, smoothing lengths, and appearance settings.
Alerts : Built-in alerts for trend changes, rejection events, and when TP1, TP2, or TP3 are reached.
Chart Overlay : Plots directly on price chart with minimal clutter and clearly labeled levels for easy trading.
USAGE
Start by tuning the Supertrend factor and ATR period to fit your asset and timeframe—higher values will catch bigger swings, lower values catch faster moves. The confirmation count should match how tightly you want to filter rejection behavior—higher values make signals rarer but stronger. When the trend shifts, the indicator colors the bars and line accordingly, and if enabled, plots the full entry-TP-SL structure. Rejection markers appear only after enough qualifying bars confirm price pressure at the trend line. This is especially useful for continuation plays where price retests the trend but fails to break it. All calculations are based on volatility (ATR), so targets naturally adjust with market conditions. Add alerts to get notified of important signals even when away from the chart.
NR_VersatilitiesLibrary "NR_Versatilities"
Versatilities (aka, Versatile Utilities) includes:
- Seventeen Price Variants returned as a tuple,
- Eight Smoothing functions rolled into one,
- Pick any Past Value from any series with offset,
- Or just the previous value from any series.
pastVal(src, len)
Fetches past value from src that came len distance ago
Parameters:
src (float) : source series
len (int) : lookback distance - (optional) default is 1
Returns: latest src if len <= 0, else src
previous(src)
Fetches past value from src that came len distance ago
Parameters:
src (float) : source series
Returns: previous value in the series if found, else current value
price_variants()
Computes Several different averages using current and previous OHLC values
Returns: Seventeen Uncommon Average Price Combinations
dynamic_MA(matyp, masrc, malen, lsmaoff, almasgm, almaoff, almaflr)
Dynamically computes Eight different MAs on-demand individually, or an average of all taken together
Parameters:
matyp (string) : pick one of these MAs - ALMA, EMA, HMA, LSMA, RMA, SMA, SWMA, WMA, ALL
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: MA series for chosen type or, an average of all of them, if chosen so
Multi-Timeframe Anchored VWAP Valuation# Multi-Timeframe Anchored VWAP Valuation
## Overview
This indicator provides a unique perspective on potential price valuation by comparing the current price to the Volume Weighted Average Price (VWAP) anchored to the start of multiple timeframes: Weekly, Monthly, Quarterly, and Yearly. It synthesizes these comparisons into a single oscillator value, helping traders gauge if the current price is potentially extended relative to significant volume-weighted levels.
## Core Concept & Calculation
1. **Anchored VWAP:** The script calculates the VWAP separately for the current Week, Month, Quarter (3 Months), and Year (12 Months), starting the calculation from the first bar of each period.
2. **Price Deviation:** It measures how far the current `close` price is from each of these anchored VWAPs. This distance is measured in terms of standard deviations calculated *within* that specific anchor period (e.g., how many weekly standard deviations the price is away from the weekly VWAP).
3. **Deviation Score (Multiplier):** Based on this standard deviation distance, a score is assigned. The further the price is from the VWAP (in terms of standard deviations), the higher the absolute score. The indicator uses linear interpolation to determine scores between the standard deviation levels (defaulted at 1, 2, and 3 standard deviations corresponding to scores of +/-2, +/-3, +/-4, with a score of 1 at the VWAP).
4. **Timeframe Weighting:** Longer timeframes are considered more significant. The deviation scores are multiplied by fixed scalars: Weekly (x1), Monthly (x2), Quarterly (x3), Yearly (x4).
5. **Final Valuation Metric:** The weighted scores from all four timeframes are summed up to produce the final oscillator value plotted in the indicator pane.
## How to Interpret and Use
* **Histogram (Indicator Pane):**
* The main output is the histogram representing the `Final Valuation Metric`.
* **Positive Values:** Suggest the price is generally trading above its volume-weighted averages across the timeframes, potentially indicating strength or relative "overvaluation."
* **Negative Values:** Suggest the price is generally trading below its volume-weighted averages, potentially indicating weakness or relative "undervaluation."
* **Values Near Zero:** Indicate the price is relatively close to its volume-weighted averages.
* **Histogram Color:**
* The color of the histogram bars provides context based on the metric's *own recent history*.
* **Green (Positive Color):** The metric is currently *above* its recent average plus a standard deviation band (dynamic upper threshold). This highlights potentially significant "overvalued" readings relative to its normal range.
* **Red (Negative Color):** The metric is currently *below* its recent average minus a standard deviation band (dynamic lower threshold). This highlights potentially significant "undervalued" readings relative to its normal range.
* **Gray (Neutral Color):** The metric is within its typical recent range (between the dynamic upper and lower thresholds).
* **Orange Line:** Plots the moving average of the `Final Valuation Metric` itself (based on the "Threshold Lookback Period"), serving as the centerline for the dynamic thresholds.
* **On-Chart Table:**
* Provides a detailed breakdown for transparency.
* Shows the calculated VWAP, the raw deviation multiplier score, and the final weighted (adjusted) metric for each individual timeframe (W, M, Q, Y).
* Displays the current price, the final combined metric value, and a textual interpretation ("Overvalued", "Undervalued", "Neutral") based on the dynamic thresholds.
## Potential Use Cases
* Identifying potential exhaustion points when the indicator reaches statistically high (green) or low (red) levels relative to its recent history.
* Assessing whether price trends are supported by underlying volume-weighted average prices across multiple timeframes.
* Can be used alongside other technical analysis tools for confirmation.
## Settings
* **Calculation Settings:**
* `STDEV Level 1`: Adjusts the 1st standard deviation level (default 1.0).
* `STDEV Level 2`: Adjusts the 2nd standard deviation level (default 2.0).
* `STDEV Level 3`: Adjusts the 3rd standard deviation level (default 3.0).
* **Interpretation Settings:**
* `Threshold Lookback Period`: Defines the number of bars used to calculate the average and standard deviation of the final metric for dynamic thresholds (default 200).
* `Threshold StDev Multiplier`: Controls how many standard deviations above/below the metric's average are used to set the "Overvalued"/"Undervalued" thresholds (default 1.0).
* **Table Settings:** Customize the position and colors of the data table displayed on the chart.
## Important Considerations
* This indicator measures price deviation relative to *anchored* VWAPs and its *own historical range*. It is not a standalone trading system.
* The interpretation of "Overvalued" and "Undervalued" is relative to the indicator's logic and calculations; it does not guarantee future price movement.
* Like all indicators, past performance is not indicative of future results. Use this tool as part of a comprehensive analysis and risk management strategy.
* The anchored VWAP and Standard Deviation values reset at the beginning of each respective period (Week, Month, Quarter, Year).
HarmonicMapLibLibrary "HarmonicMapLib"
Harmonic Pattern Library implementation utilising maps
method tostring(this)
convert Range value to string
Namespace types: Range
Parameters:
this (Range) : Range value
Returns: converted string representation
method tostring(this)
convert array of Range value to string
Namespace types: array
Parameters:
this (array) : array object
Returns: converted string representation
method tostring(this)
convert map of string to Range value to string
Namespace types: map
Parameters:
this (map) : map object
Returns: converted string representation
method tostring(this)
convert RatioMap to string
Namespace types: RatioMap
Parameters:
this (RatioMap) : RatioMap object
Returns: converted string representation
method tostring(this)
convert array of RatioMap to string
Namespace types: array
Parameters:
this (array) : array object
Returns: converted string representation
method tostring(this)
convert map of string to RatioMap to string
Namespace types: map
Parameters:
this (map) : map object
Returns: converted string representation
method tostring(this)
convert map of string to bool to string
Namespace types: map
Parameters:
this (map) : map object
Returns: converted string representation
method tostring(this)
convert PrzRange to string
Namespace types: PrzRange
Parameters:
this (PrzRange) : PrzRange object
Returns: converted string representation
method tostring(this)
convert array of PrzRange to string
Namespace types: array
Parameters:
this (array) : array object
Returns: converted string representation
getHarmonicMap()
Creates the RatioMap for harmonic patterns
Returns: map haronic ratio rules for all patterns
method evaluate(patternsMap, pattern, ratioRange, properties, ratioValue)
evaluates harmonic ratio range
Namespace types: map
Parameters:
patternsMap (map) : parameter containing valid pattern names
pattern (string) : Pattern type to be evaluated
ratioRange (Range) : ratio range to be checked
properties (ScanProperties) : Scan Properties
ratioValue (float)
Returns: void
method evaluate(przRange, pattern, ratioRange, priceRange, properties)
Evaluate PRZ ranges
Namespace types: map
Parameters:
przRange (map)
pattern (string) : Pattern name
ratioRange (Range) : Range of ratio for the pattern
priceRange (Range) : Price range based on ratio
properties (ScanProperties) : ScanProperties object
Returns: void
method scanRatio(currentPatterns, rules, properties, ratioName, ratioValue)
Scan for particular named ratio of harmonic pattern to filter valid patterns
Namespace types: map
Parameters:
currentPatterns (map) : Current valid patterns map
rules (map) : map Harmonic ratio rules
properties (ScanProperties) : ScanProperties object
ratioName (string) : Specific ratio name
ratioValue (float) : ratio value to be checked
Returns: updated currentPatterns object
method scanPatterns(patterns, x, a, b, c, d, properties)
Scan for patterns based on X, A, B, C, D values
Namespace types: map
Parameters:
patterns (map) : List of allowed patterns
x (float) : X coordinate
a (float) : A coordinate
b (float) : B coordinate
c (float) : C coordinate
d (float) : D coordinate
properties (ScanProperties) : ScanProperties object. If na, default values are initialised
Returns: updated valid patterns map
method scanProjections(patterns, x, a, b, c, properties)
Scan for projections based on X, A, B, C values
Namespace types: map
Parameters:
patterns (map) : List of allowed patterns
x (float) : X coordinate
a (float) : A coordinate
b (float) : B coordinate
c (float) : C coordinate
properties (ScanProperties) : ScanProperties object. If na, default values are initialised
Returns: updated valid projections map
method merge(this, other)
merge two ranges into one
Namespace types: Range
Parameters:
this (Range) : first range
other (Range) : second range
Returns: combined range
method union(this, other)
union of two ranges into one
Namespace types: Range
Parameters:
this (Range) : first range
other (Range) : second range
Returns: union range
method overlaps(this, other)
checks if two ranges intersect
Namespace types: Range
Parameters:
this (Range) : first range
other (Range) : second range
Returns: true if intersects, false otherwise
method consolidate(this)
Consolidate ranges into PRZ
Namespace types: map
Parameters:
this (map) : map of Ranges
Returns: consolidated PRZ
method consolidateMany(this)
Consolidate ranges into multiple PRZ ranges
Namespace types: map
Parameters:
this (map) : map of Ranges
Returns: consolidated array of PRZ ranges
method getRange(currentPatterns, x, a, b, c, properties)
Get D range based on X, A, B, C coordinates for the current patterns
Namespace types: map
Parameters:
currentPatterns (map) : List of valid patterns
x (float) : X coordinate
a (float) : A coordinate
b (float) : B coordinate
c (float) : C coordinate
properties (ScanProperties) : ScanProperties object. If na, default values are initialised
Returns: map of D ranges
method getPrzRange(currentPatterns, x, a, b, c, properties)
Get PRZ range based on X, A, B, C coordinates for the current patterns
Namespace types: map
Parameters:
currentPatterns (map) : List of valid patterns
x (float) : X coordinate
a (float) : A coordinate
b (float) : B coordinate
c (float) : C coordinate
properties (ScanProperties) : ScanProperties object. If na, default values are initialised
Returns: PRZRange for the pattern
method getProjectionRanges(currentPatterns, x, a, b, c, properties)
Get projection range based on X, A, B, C coordinates for the current patterns
Namespace types: map
Parameters:
currentPatterns (map) : List of valid patterns
x (float) : X coordinate
a (float) : A coordinate
b (float) : B coordinate
c (float) : C coordinate
properties (ScanProperties) : ScanProperties object. If na, default values are initialised
Returns: array of projection ranges
Range
Collection of range values
Fields:
values (array) : array of float values
RatioMap
ratio map for pattern
Fields:
ratioMap (map) : map of string to Range (array of float)
ScanProperties
Pattern Scanning properties
Fields:
strictMode (series bool) : strict scanning mode will check for overflows
logScale (series bool) : scan ratios in log scale
errorMin (series float) : min error threshold
errorMax (series float)
mintick (series float) : minimum tick value of price
PrzRange
Potential reversal zone range
Fields:
patterns (array) : array of pattern names for the given XABCD combination
prz (Range) : PRZ range
Chau RSI+MA for DHChau RSI+MA for DH – Indicator Description & Usage
Overview:
The Chau RSI+MA for DH indicator is a custom RSI-based analysis tool designed to provide a deeper and more dynamic view of market momentum. It plots three configurable RSI lines along with three moving averages (MA) of the main RSI, helping traders identify overbought/oversold zones, trend strength, and potential reversal points.
🔧 Inputs & Configuration:
Three RSI Lines:
RSI 1 (default: 7)
RSI 2 (default: 14) → used as the base for MA calculations
RSI 3 (default: 21)
These allow multi-timeframe or multi-speed momentum analysis in a single panel.
Three MAs of RSI 2:
MA 1, MA 2, MA 3 – customizable lengths, defaulting to 5, 10, and 20
These help smooth out RSI 2 to detect trend direction or divergence.
Overbought/Oversold Levels:
Customizable dual thresholds (Level 1 & Level 2), offering flexible signal filtering.
🎯 Core Features & Strengths:
Multi-RSI Display:
Combines short, mid, and long RSI to give a layered view of market strength and potential turning points.
RSI MA Tracking:
Smoothing RSI 2 with three MAs helps visualize momentum trends and potential trend-following signals.
Dynamic Signal Zones:
Overbought and Oversold regions are highlighted with background colors.
Dual level alert system (e.g., 70/80 and 30/20) increases precision and adaptability for different strategies.
Highly Customizable Visualization:
Fully adjustable color schemes for all RSI and MA lines.
Easily identify confluences or divergences at a glance.
✅ Best Use Cases:
Trend Confirmation:
Use RSI 2 crossing above/below its MAs as a momentum confirmation signal.
Reversal Detection:
Identify overbought or oversold conditions combined with RSI-MA divergence.
Filtering Entries/Exits:
Combine with price action or other indicators to filter out low-probability trades.
Scalping & Swing Trading:
Adaptable to multiple timeframes and styles due to customizable RSI/MA settings.
Delta Zones🔶 Delta Zones — A Precision Tool for Time-Price Mapping 🔶
The Delta Zones indicator is a refined structure-mapping tool that dynamically tracks zones of dominant trading activity across recent sessions.
These zones are projected forward in time, offering traders a reliable visual guide to where significant interactions between buyers and sellers are likely to take place.
This tool was designed for intraday use, but its adaptability makes it powerful even on higher timeframes, giving traders insights into market behavior without the noise. You need to change session setting from indicator to higher TF that the chart. For intra, its by default on daily.
🔧 What This Indicator Does
Detects and displays the key activity zone for the current session (today).
Recalls the most active zone from the previous session, allowing you to track momentum or reversal bias.
Color codes each zone based on where price currently trades relative to it:
Neutral gradient (orange/white) for today’s zone, showing where price is consolidating or reacting.
Bullish green fade if price is trading above yesterday’s zone.
Bearish red fade if price is trading below yesterday’s zone.
Extends each zone forward (default 200 bars) so you can observe price behavior as it revisits these areas over time.
📈 How to Use Delta Zones
Trend Continuation:
If price pushes beyond today's zone and maintains momentum, it may suggest strength in that direction. Watch how price reacts on retests of this zone.
Fade or Mean Reversion:
When price strays far from a Delta Zone and struggles to gain ground, it often rotates back into that region. These situations can offer attractive risk-reward setups.
Zone Polarity from Prior Sessions:
Yesterday’s zone serves as a directional cue — if price opens and stays above it (green-filled), sentiment favors strength. If it stays below (red-filled), weakness may persist.
Support/Resistance Anchors:
Use zones as dynamic S/R levels — watch for wick tests, engulfing candles, or volume surges at zone edges for potential trade entries or exits.
🎛️ Inputs You Can Control
Session Length (Default: Daily): Defines how often a new zone is calculated.
💡 Pro Tip
These zones act like magnetic fields around price — not only can they contain price, but they also attract it. The key is to recognize when price is respecting, rejecting, or absorbing at the edges of the zone.
Pair Delta Zones with your favorite price action, momentum, or volume tools for sharper decision-making. For example, "Accumulation/Distribution Money Flow" script which I published few days ago.
⚠️ Note
This is a conceptually adaptive framework designed to simplify the visual structure of the market. While no model guarantees predictive accuracy, Delta Zones are especially useful for contextualizing price behavior and anticipating where meaningful reactions may occur.
This is an educational idea, use it at your own risk.
Past performance does not guarantee future success.
Intrinsic Event (Multi DC OS)Overview
This indicator implements an event-based approach to analyze price movements in the foreign exchange market, inspired by the intrinsic time framework introduced in Fractals and Intrinsic Time - A Challenge to Econometricians by U. A. Müller et al. (1995). It identifies significant price events using an intrinsic time perspective and supports multi-agent analysis to reflect the heterogeneous nature of financial markets. The script plots these events as lines and labels on the chart, offering a visual tool for traders to understand market dynamics at different scales.
Key Features
Intrinsic Events : The indicator detects directional change (DC) and overshoot (OS) events based on user-defined thresholds (delta), aligning with the paper’s concept of intrinsic time (Section 6). Intrinsic time redefines time based on market activity, expanding during volatile periods and contracting during inactive ones, rather than relying on a physical clock.
Multi-Agent Analysis : Supports up to five agents, each with its own threshold and color settings, reflecting the heterogeneous market hypothesis (Section 5). This allows the indicator to capture the perspectives of market participants with different time horizons, such as short-term FX dealers and long-term central banks.
How It Works
Intrinsic Events Detection : The script identifies two types of events using intrinsic time principles:
Directional Change (DC) : Triggered when the price reverses by the threshold (delta) against the current trend (e.g., a drop by delta in an uptrend signals a "Down DC").
Overshoot (OS) : Occurs when the price continues in the trend direction by the threshold (e.g., a rise by delta in an uptrend signals an "Up OS").
DC events are plotted as solid lines, and OS events as dashed lines, with labels like "Up DC" or "OS Down" for clarity. The label style adjusts based on the trend to ensure visibility.
Multi-Agent Setup : Each agent operates independently with its own threshold, mimicking market participants with varying time horizons (Section 5). Smaller thresholds detect frequent, short-term events, while larger thresholds capture broader, long-term movements.
Settings
Each agent can be configured with:
Enable Agent : Toggle the agent on or off.
Threshold (%) : The percentage threshold (delta) for detecting DC and OS events (default values: 0.1%, 0.2%, 0.5%, 1%, 2% for agents 1–5).
Up Mode Color : Color for lines and labels in up mode (DC events).
Down Mode Color : Color for lines and labels in down mode (OS events).
Usage Notes
This indicator is designed for the foreign exchange market, leveraging its high liquidity, as noted in the paper (Section 1). Adjust the threshold values based on the instrument’s volatility—higher volatility leads to more intrinsic events (Section 4). It can be adapted to other markets where event-based analysis applies.
Reference
The methodology is based on:
Fractals and Intrinsic Time - A Challenge to Econometricians by U. A. Müller, M. M. Dacorogna, R. D. Davé, O. V. Pictet, R. B. Olsen, and J. R. Ward (June 28, 1995). Olsen & Associates Preprint.
Quantify [Trading Model] | FractalystNote: In this description, "TM" refers to Trading Model (not trademark) and "EM" refers to Entry Model
What’s the indicator’s purpose and functionality?
You know how to identify market bias but always struggle with figuring out the best exit method, or even hesitating to take your trades?
I've been there. That's why I built this solution—once and for all—to help traders who know the market bias but need a systematic and quantitative approach for their entries and trade management.
A model that shows you real-time market probabilities and insights, so you can focus on execution with confidence—not doubt or FOMO.
How does this Quantify differentiate from Quantify ?
Have you managed to code or even found an indicator that identifies the market bias for you, so you don’t have to manually spend time analyzing the market and trend?
Then that’s exactly why you might need the Quantify Trading Model.
With the Trading Model (TM) version, the script automatically uses your given bias identification method to determine the trend (bull vs bear and neutral), detect the bias, and provide instant insight into the trades you could’ve taken.
To avoid complications from consecutive signals, it uses a kNN machine learning algorithm that processes market structure and probabilities to predict the best future patterns.
(You don’t have to deal with any complexity—it’s all taken care of for you.)
Quantify TM uses the k-Nearest Neighbors (kNN) machine learning algorithm to learn from historical market patterns and adapt to changing market structures. This means it can recognize similar market conditions from the past and apply those lessons to current trading decisions.
On the other hand, Quantify EM requires you to manually select your directional bias. It then focuses solely on generating entry signals based on that pre-determined bias.
While the entry model version (EM) uses your manual bias selection to determine the trend, it then provides insights into trades you could’ve taken and should be taking.
Trading Model (TM)
- Uses `input.source()` to incorporate your personal methodology for identifying market bias
- Automates everything—from bias detection to entry and exit decisions
- Adapts to market bias changes through kNN machine learning optimization
- Reduces human intervention in trading decisions, limiting emotional interference
Entry Model (EM)
- Focuses specifically on optimizing entry points within your pre-selected directional bias
- Requires manual input for determining market bias
- Provides entry signals without automating alerts or bias rules
Can the indicator be applied to any market approach/trading strategy?
Yes, if you have clear rules for identifying the market bias, then you can code your bias detection and then use the input.source() user input to retrieve the direction from your own indicator, then the Quantify uses machine-learning identify the best setups for you.
Here's an example:
//@version=6
indicator('Moving Averages Bias', overlay = true)
// Input lengths for moving averages
ma10_length = input.int(10, title = 'MA 10 Length')
ma20_length = input.int(20, title = 'MA 20 Length')
ma50_length = input.int(50, title = 'MA 50 Length')
// Calculate moving averages
ma10 = ta.sma(close, ma10_length)
ma20 = ta.sma(close, ma20_length)
ma50 = ta.sma(close, ma50_length)
// Identify bias
var bias = 0
if close > ma10 and close > ma20 and close > ma50 and ma10 > ma20 and ma20 > ma50
bias := 1 // Bullish
bias
else if close < ma10 and close < ma20 and close < ma50 and ma10 < ma20 and ma20 < ma50
bias := -1 // Bearish
bias
else
bias := 0 // Neutral
bias
// Plot the bias
plot(bias, title = 'Identified Bias', color = color.blue,display = display.none)
Once you've created your custom bias indicator, you can integrate it with Quantify :
- Add your bias indicator to your chart
- Open the Quantify settings
- Set the Bias option to "Auto"
- Select your custom indicator as the bias source
The machine learning algorithms will then analyze historical price action and identify optimal setups based on your defined bias parameters. Performance statistics are displayed in summary tables, allowing you to evaluate effectiveness across different timeframes.
Can the indicator be used for different timeframes or trading styles?
Yes, regardless of the timeframe you’d like to take your entries, the indicator adapts to your trading style.
Whether you’re a swing trader, scalper, or even a position trader, the algorithm dynamically evaluates market conditions across your chosen timeframe.
How Quantify Helps You Trade Profitably?
The Quantify Trading Model offers several powerful features that can significantly improve your trading profitability when used correctly:
Real-Time Edge Assessment
It displays real-time probability of price moving in your favor versus hitting your stoploss
This gives you immediate insight into risk/reward dynamics before entering trades
You can make more informed decisions by knowing the statistical likelihood of success
Historical Edge Validation
Instantly shows whether your trading approach has demonstrated an edge in historical data
Prevents you from trading setups that historically haven't performed well
Gives confidence when entering trades that have proven statistical advantages
Optimized Position Sizing
Analyzes each setup's success rate to determine the adjusted Kelly criterion formula
Customizes position sizing based on your selected maximum drawdown tolerance
Helps prevent account-destroying losses while maximizing growth potential
Advanced Exit Management
Utilizes market structure-based trailing stop-loss mechanisms
Maximizes the average risk-reward ratio profit per winning trade
Helps capture larger moves while protecting gains during market reversals
Emotional Discipline Enforcement
Eliminates emotional bias by adhering to your pre-defined rules for market direction
Prevents impulsive decisions by providing objective entry and exit signals
Creates psychological distance between your emotions and trading decisions
Overtrading Prevention
Highlights only setups that demonstrate positive expectancy
Reduces frequency of low-probability trades
Conserves capital for higher-quality opportunities
Systematic Approach Benefits
By combining machine learning algorithms with your personal bias identification methods, Quantify helps transform discretionary trading approaches into more systematic, probability-based strategies.
What Entry Models are used in Quantify Trading Model version?
The Quantify Trading Model utilizes two primary entry models to identify high-probability trade setups:
Breakout Entry Model
- Identifies potential trade entries when price breaks through significant swing highs and swing lows
- Captures momentum as price moves beyond established trading ranges
- Particularly effective in trending markets when combined with the appropriate bias detection
- Optimized by machine learning to filter false breakouts based on historical performance
Fractals Entry Model
- Utilizes fractal patterns to identify potential reversal or continuation points
- Also uses swing levels to determine optimal entry locations
- Based on the concept that market structure repeats across different timeframes
- Identifies local highs and lows that form natural entry points
- Enhanced by machine learning to recognize the most profitable fractal formations
- These entry models work in conjunction with your custom bias indicator to ensure trades are taken in the direction of the overall market trend. The machine learning component analyzes historical performance of these entry types across different market conditions to optimize entry timing and signal quality.
How Does This Indicator Identify Market Structure?
1. Swing Detection
• The indicator identifies key swing points on the chart. These are local highs or lows where the price reverses direction, forming the foundation of market structure.
2. Structural Break Validation
• A structural break is flagged when a candle closes above a previous swing high (bullish) or below a previous swing low (bearish).
• Break Confirmation Process:
To confirm the break, the indicator applies the following rules:
• Valid Swing Preceding the Break: There must be at least one valid swing point before the break.
3. Numeric Labeling
• Each confirmed structural break is assigned a unique numeric ID starting from 1.
• This helps traders track breaks sequentially and analyze how the market structure evolves over time.
4. Liquidity and Invalidation Zones
• For every confirmed structural break, the indicator highlights two critical zones:
1. Liquidity Zone (LIQ): Represents the structural liquidity level.
2. Invalidation Zone (INV): Acts as Invalidation point if the structure fails to hold.
How does the trailing stop-loss work? what are the underlying calculations?
A trailing stoploss is a dynamic risk management tool that moves with the price as the market trend continues in the trader’s favor. Unlike a fixed take profit, which stays at a set level, the trailing stoploss automatically adjusts itself as the market moves, locking in profits as the price advances.
In Quantify, the trailing stoploss is enhanced by incorporating market structure liquidity levels (explain above). This ensures that the stoploss adjusts intelligently based on key price levels, allowing the trader to stay in the trade as long as the trend remains intact, while also protecting profits if the market reverses.
What is the Kelly Criterion, and how does it work in Quantify?
The Kelly Criterion is a mathematical formula used to determine the optimal position size for each trade, maximizing long-term growth while minimizing the risk of large drawdowns. It calculates the percentage of your portfolio to risk on a trade based on the probability of winning and the expected payoff.
Quantify integrates this with user-defined inputs to dynamically calculate the most effective position size in percentage, aligning with the trader’s risk tolerance and desired exposure.
How does Quantify use the Kelly Criterion in practice?
Quantify uses the Kelly Criterion to optimize position sizing based on the following factors:
1. Confidence Level: The model assesses the confidence level in the trade setup based on historical data and sample size. A higher confidence level increases the suggested position size because the trade has a higher probability of success.
2. Max Allowed Drawdown (User-Defined): Traders can set their preferred maximum allowed drawdown, which dictates how much loss is acceptable before reducing position size or stopping trading. Quantify uses this input to ensure that risk exposure aligns with the trader’s risk tolerance.
3. Probabilities: Quantify calculates the probabilities of success for each trade setup. The higher the probability of a successful trade (based on historical price action and liquidity levels), the larger the position size suggested by the Kelly Criterion.
How can I get started to use the indicator?
1. Set Your Market Bias
• Choose Auto.
• Select the source you want Quantify to use as for bias identification method (explained above)
2. Choose Your Entry Timeframes
• Specify the timeframes you want to focus on for trade entries.
• The indicator will dynamically analyze these timeframes to provide optimal setups.
3. Choose Your Entry Model and BE/TP Levels
• Choose a model that suits your personality
• Choose a level where you'd like the script to take profit or move stop-loss to BE
4. Set and activate the alerts
What tables are used in the Quantify?
• Quarterly
• Monthly
• Weekly
Terms and Conditions | Disclaimer
Our charting tools are provided for informational and educational purposes only and should not be construed as financial, investment, or trading advice. They are not intended to forecast market movements or offer specific recommendations. Users should understand that past performance does not guarantee future results and should not base financial decisions solely on historical data.
Built-in components, features, and functionalities of our charting tools are the intellectual property of @Fractalyst Unauthorized use, reproduction, or distribution of these proprietary elements is prohibited.
- By continuing to use our charting tools, the user acknowledges and accepts the Terms and Conditions outlined in this legal disclaimer and agrees to respect our intellectual property rights and comply with all applicable laws and regulations.
Correlation Heatmap█ OVERVIEW
This indicator creates a correlation matrix for a user-specified list of symbols based on their time-aligned weekly or monthly price returns. It calculates the Pearson correlation coefficient for each possible symbol pair, and it displays the results in a symmetric table with heatmap-colored cells. This format provides an intuitive view of the linear relationships between various symbols' price movements over a specific time range.
█ CONCEPTS
Correlation
Correlation typically refers to an observable statistical relationship between two datasets. In a financial time series context, it usually represents the extent to which sampled values from a pair of datasets, such as two series of price returns, vary jointly over time. More specifically, in this context, correlation describes the strength and direction of the relationship between the samples from both series.
If two separate time series tend to rise and fall together proportionally, they might be highly correlated. Likewise, if the series often vary in opposite directions, they might have a strong anticorrelation . If the two series do not exhibit a clear relationship, they might be uncorrelated .
Traders frequently analyze asset correlations to help optimize portfolios, assess market behaviors, identify potential risks, and support trading decisions. For instance, correlation often plays a key role in diversification . When two instruments exhibit a strong correlation in their returns, it might indicate that buying or selling both carries elevated unsystematic risk . Therefore, traders often aim to create balanced portfolios of relatively uncorrelated or anticorrelated assets to help promote investment diversity and potentially offset some of the risks.
When using correlation analysis to support investment decisions, it is crucial to understand the following caveats:
• Correlation does not imply causation . Two assets might vary jointly over an analyzed range, resulting in high correlation or anticorrelation in their returns, but that does not indicate that either instrument directly influences the other. Joint variability between assets might occur because of shared sensitivities to external factors, such as interest rates or global sentiment, or it might be entirely coincidental. In other words, correlation does not provide sufficient information to identify cause-and-effect relationships.
• Correlation does not predict the future relationship between two assets. It only reflects the estimated strength and direction of the relationship between the current analyzed samples. Financial time series are ever-changing. A strong trend between two assets can weaken or reverse in the future.
Correlation coefficient
A correlation coefficient is a numeric measure of correlation. Several coefficients exist, each quantifying different types of relationships between two datasets. The most common and widely known measure is the Pearson product-moment correlation coefficient , also known as the Pearson correlation coefficient or Pearson's r . Usually, when the term "correlation coefficient" is used without context, it refers to this correlation measure.
The Pearson correlation coefficient quantifies the strength and direction of the linear relationship between two variables. In other words, it indicates how consistently variables' values move together or in opposite directions in a proportional, linear manner. Its formula is as follows:
𝑟(𝑥, 𝑦) = cov(𝑥, 𝑦) / (𝜎𝑥 * 𝜎𝑦)
Where:
• 𝑥 is the first variable, and 𝑦 is the second variable.
• cov(𝑥, 𝑦) is the covariance between 𝑥 and 𝑦.
• 𝜎𝑥 is the standard deviation of 𝑥.
• 𝜎𝑦 is the standard deviation of 𝑦.
In essence, the correlation coefficient measures the covariance between two variables, normalized by the product of their standard deviations. The coefficient's value ranges from -1 to 1, allowing a more straightforward interpretation of the relationship between two datasets than what covariance alone provides:
• A value of 1 indicates a perfect positive correlation over the analyzed sample. As one variable's value changes, the other variable's value changes proportionally in the same direction .
• A value of -1 indicates a perfect negative correlation (anticorrelation). As one variable's value increases, the other variable's value decreases proportionally.
• A value of 0 indicates no linear relationship between the variables over the analyzed sample.
Aligning returns across instruments
In a financial time series, each data point (i.e., bar) in a sample represents information collected in periodic intervals. For instance, on a "1D" chart, bars form at specific times as successive days elapse.
However, the times of the data points for a symbol's standard dataset depend on its active sessions , and sessions vary across instrument types. For example, the daily session for NYSE stocks is 09:30 - 16:00 UTC-4/-5 on weekdays, Forex instruments have 24-hour sessions that span from 17:00 UTC-4/-5 on one weekday to 17:00 on the next, and new daily sessions for cryptocurrencies start at 00:00 UTC every day because crypto markets are consistently open.
Therefore, comparing the standard datasets for different asset types to identify correlations presents a challenge. If two symbols' datasets have bars that form at unaligned times, their correlation coefficient does not accurately describe their relationship. When calculating correlations between the returns for two assets, both datasets must maintain consistent time alignment in their values and cover identical ranges for meaningful results.
To address the issue of time alignment across instruments, this indicator requests confirmed weekly or monthly data from spread tickers constructed from the chart's ticker and another specified ticker. The datasets for spreads are derived from lower-timeframe data to ensure the values from all symbols come from aligned points in time, allowing a fair comparison between different instrument types. Additionally, each spread ticker ID includes necessary modifiers, such as extended hours and adjustments.
In this indicator, we use the following process to retrieve time-aligned returns for correlation calculations:
1. Request the current and previous prices from a spread representing the sum of the chart symbol and another symbol ( "chartSymbol + anotherSymbol" ).
2. Request the prices from another spread representing the difference between the two symbols ( "chartSymbol - anotherSymbol" ).
3. Calculate half of the difference between the values from both spreads ( 0.5 * (requestedSum - requestedDifference) ). The results represent the symbol's prices at times aligned with the sample points on the current chart.
4. Calculate the arithmetic return of the retrieved prices: (currentPrice - previousPrice) / previousPrice
5. Repeat steps 1-4 for each symbol requiring analysis.
It's crucial to note that because this process retrieves prices for a symbol at times consistent with periodic points on the current chart, the values can represent prices from before or after the closing time of the symbol's usual session.
Additionally, note that the maximum number of weeks or months in the correlation calculations depends on the chart's range and the largest time range common to all the requested symbols. To maximize the amount of data available for the calculations, we recommend setting the chart to use a daily or higher timeframe and specifying a chart symbol that covers a sufficient time range for your needs.
█ FEATURES
This indicator analyzes the correlations between several pairs of user-specified symbols to provide a structured, intuitive view of the relationships in their returns. Below are the indicator's key features:
Requesting a list of securities
The "Symbol list" text box in the indicator's "Settings/Inputs" tab accepts a comma-separated list of symbols or ticker identifiers with optional spaces (e.g., "XOM, MSFT, BITSTAMP:BTCUSD"). The indicator dynamically requests returns for each symbol in the list, then calculates the correlation between each pair of return series for its heatmap display.
Each item in the list must represent a valid symbol or ticker ID. If the list includes an invalid symbol, the script raises a runtime error.
To specify a broker/exchange for a symbol, include its name as a prefix with a colon in the "EXCHANGE:SYMBOL" format. If a symbol in the list does not specify an exchange prefix, the indicator selects the most commonly used exchange when requesting the data.
Note that the number of symbols allowed in the list depends on the user's plan. Users with non-professional plans can compare up to 20 symbols with this indicator, and users with professional plans can compare up to 32 symbols.
Timeframe and data length selection
The "Returns timeframe" input specifies whether the indicator uses weekly or monthly returns in its calculations. By default, its value is "1M", meaning the indicator analyzes monthly returns. Note that this script requires a chart timeframe lower than or equal to "1M". If the chart uses a higher timeframe, it causes a runtime error.
To customize the length of the data used in the correlation calculations, use the "Max periods" input. When enabled, the indicator limits the calculation window to the number of periods specified in the input field. Otherwise, it uses the chart's time range as the limit. The top-left corner of the table shows the number of confirmed weeks or months used in the calculations.
It's important to note that the number of confirmed periods in the correlation calculations is limited to the largest time range common to all the requested datasets, because a meaningful correlation matrix requires analyzing each symbol's returns under the same market conditions. Therefore, the correlation matrix can show different results for the same symbol pair if another listed symbol restricts the aligned data to a shorter time range.
Heatmap display
This indicator displays the correlations for each symbol pair in a heatmap-styled table representing a symmetric correlation matrix. Each row and column corresponds to a specific symbol, and the cells at their intersections correspond to symbol pairs . For example, the cell at the "AAPL" row and "MSFT" column shows the weekly or monthly correlation between those two symbols' returns. Likewise, the cell at the "MSFT" row and "AAPL" column shows the same value.
Note that the main diagonal cells in the display, where the row and column refer to the same symbol, all show a value of 1 because any series of non-na data is always perfectly correlated with itself.
The background of each correlation cell uses a gradient color based on the correlation value. By default, the gradient uses blue hues for positive correlation, orange hues for negative correlation, and white for no correlation. The intensity of each blue or orange hue corresponds to the strength of the measured correlation or anticorrelation. Users can customize the gradient's base colors using the inputs in the "Color gradient" section of the "Settings/Inputs" tab.
█ FOR Pine Script® CODERS
• This script uses the `getArrayFromString()` function from our ValueAtTime library to process the input list of symbols. The function splits the "string" value by its commas, then constructs an array of non-empty strings without leading or trailing whitespaces. Additionally, it uses the str.upper() function to convert each symbol's characters to uppercase.
• The script's `getAlignedReturns()` function requests time-aligned prices with two request.security() calls that use spread tickers based on the chart's symbol and another symbol. Then, it calculates the arithmetic return using the `changePercent()` function from the ta library. The `collectReturns()` function uses `getAlignedReturns()` within a loop and stores the data from each call within a matrix . The script calls the `arrayCorrelation()` function on pairs of rows from the returned matrix to calculate the correlation values.
• For consistency, the `getAlignedReturns()` function includes extended hours and dividend adjustment modifiers in its data requests. Additionally, it includes other settings inherited from the chart's context, such as "settlement-as-close" preferences.
• A Pine script can execute up to 40 or 64 unique `request.*()` function calls, depending on the user's plan. The maximum number of symbols this script compares is half the plan's limit, because `getAlignedReturns()` uses two request.security() calls.
• This script can use the request.security() function within a loop because all scripts in Pine v6 enable dynamic requests by default. Refer to the Dynamic requests section of the Other timeframes and data page to learn more about this feature, and see our v6 migration guide to learn what's new in Pine v6.
• The script's table uses two distinct color.from_gradient() calls in a switch structure to determine the cell colors for positive and negative correlation values. One call calculates the color for values from -1 to 0 based on the first and second input colors, and the other calculates the colors for values from 0 to 1 based on the second and third input colors.
Look first. Then leap.
Sigma (Standard Deviation)Calculates the standard deviation (sigma) of a stock in percentages. You can edit the length as per your need.
US Recessions with SPX reversals v3 [FornaxTV]In addition to highlighting periods of official US recessions (as defined by the NBER) this script also displays vertical lines for the SPX market top and bottom associated with each recession .
This facilitates more detailed analysis of potential leading and coincident indicators for market tops and bottoms. This is particularly relevant for market tops, which typically precede the start of a recession by several months.
In addition to recessions with SPX market tops and market bottoms:
- A horizontal line can optionally be displayed for the last market top . (NOTE: this line will only be displayed for SPX tickers.)
- Labels can optionally be displayed for market tops & bottoms, plus the start and end of recessions. If the statistics are enabled (see below) these labels will also indicate the number of weeks between key market events, e.g. a market top and the start of a recession.
- A statistics table can optionally be displayed, contained statistics such as the number of weeks wince the last recession & market bottom, as well as averages for all recessions included in the analysis set.
For the recession statistics:
- "Outlier" recessions such as 1945 (WWII, where the market top occurred well after the recession itself) and 2020 (COVID pandemic, which was arguably not a "true" economic recession) can optionally be excluded.
- You can choose to exclude recessions occurring before a specific year.
Timed Reversion Markers (Custom Session Alerts)This script plots vertical histogram markers at specific intraday time points defined by the user. It is designed for traders who follow time-based reversion or breakout setups tied to predictable market behavior at key clock times, such as institutional opening moves, midday reversals, or end-of-day volatility.
Unlike traditional price-action indicators, this tool focuses purely on time-based triggers, a technique often used in time cycle analysis, market internals, and volume-timing strategies.
The indicator includes eight fully customizable time inputs, allowing users to mark any intraday minute with precision using a decimal hour format (for example, 9.55 for 9:55 AM). Each input is automatically converted into hour and minute format, and a visual histogram marker is plotted once per day at that exact time.
Example use cases:
Mark institutional session opens (e.g., 9:30, 10:00, 15:30)
Time-based mean reversion or volatility windows
Backtest recurring time-based reactions
Highlight algorithmic spike zones
The vertical plots serve as non-intrusive, high-contrast visual markers for scalping setups, session analysis, and decision-making checkpoints. All markers are displayed at the top of the chart without interfering with price candles.
Statistical OHLC Projections [neo|]█ OVERVIEW
Statistical OHLC Projections is an indicator designed to offer users a customizable deep-dive on measuring historical price levels for any timeframe. The indicator separates price into two distinct levels, "Manipulation" and "Distribution", where the idea is that for higher timeframe candles, e.g. an up-close candle, the distance from the open to the bottom of the wick would constitute the Manipulation, and the rest would be considered the Distribution. By measuring out these levels, we can gain insight on how far the market may move from higher timeframe opens to their manipulations and distributions, and apply this knowledge to our analysis.
IMPORTANT: Since levels are based on the lookback available on your chart, if the levels aren't being displayed this likely means you don't have enough lookback for your selected timeframe. To check this, enable the stat table to see how many values are available for your timeframe, and either reduce the lookback or increase your chart timeframe.
█ CONCEPTS
The core concept revolves around understanding market behavior through the lens of historical candle structure. The indicator dissects OHLC data to provide statistical boundaries of expected price movement.
- Manipulation Levels: These represent the areas typically seen as liquidity grabs or false moves where price extends in one direction before reversing.
- Distribution Levels: These highlight where the bulk of directional movement tends to occur, often following the manipulation move.
The tool aggregates this data across your selected timeframe to inform you of potential levels associated with it.
█ FEATURES
Multiple Display Types: Display statistical data through two sleek styles, areas or lines. Where areas represent the area between two customizable lookback values, and lines represent one average value.
Adjustable Timeframe Selection: Whether you want to see data based on the 1D chart, or the 1W chart, anything is possible. Simply change the timeframe on the dropdown menu and if there is sufficient lookback the indicator will adjust to your requested timeframe.
Customizable Historical Lookback: By default, the indicator will measure the average 60 values of your requested timeframe, however this may be adjusted to be higher or lower based on your preference. If you want to measure recent moves, 10-20 lookback may be better for you, or if you want more data for less volatile instruments, a value of 100 may be better.
Historical Display: Prevent historical levels from being removed by unchecking the "Remove Previous Drawings" option, this will allow you to examine how the levels previously interacted with price.
NY Midnight Anchoring: By checking the "Use NY Midnight" option, you may see the projection anchored to the New York midnight open time, which is often a significant level on indices.
Alerts: You may enable alerts for any of the indicator's provided levels to stay informed, even when off the charts.
█ How to use
To use the indicator, simply apply it to your chart and modify any of your desired inputs.
By default, the indicator will provide levels for the "1D" timeframe, with a desired lookback of 60, on most instruments and plans this can be gotten when you are on the 30 minute timeframe or above.
When price reaches or extends beyond a manipulation level, observe how it reacts and whether it rejects from that level, if it does this may be an indication that the candle for the timeframe you selected may be reversing.
█ SETTINGS AND OPTIONS
Customize the indicator’s behavior, timeframe sources, and visual appearance to fit your analysis style. Each setting has been designed with flexibility in mind, whether you're working on lower or higher timeframes.
Display Mode: Switch between different display styles for levels: - Default: Shows all statistical levels as individual lines.
- Areas: Plots filled zones between two customizable lookbacks to represent the range between them.
This is ideal for visually mapping high-probability zones of price activity.
Timeframe Settings:
- Show First/Second Timeframe: Choose to show one or both timeframe projections simultaneously.
- First Timeframe / Second Timeframe: Define the higher timeframe candle you want to base calculations on (e.g., 1D, 1W).
- Use NY Midnight: When enabled and using the daily timeframe, the levels will be anchored to the New York Midnight Open (00:00 EST), a key institutional timing reference, especially useful for indices and forex.
Calculation Settings:
- Main Lookback Period: The number of historical candles used in the statistical calculations. A lower number focuses on recent price action, while a higher number smooths results across broader history.
- First Lookback / Second Lookback: Used when “Areas” mode is selected to define the range of the shaded zone. For example, an area from 20 to 60 candles creates a band between short- and long-term price behavior averages.
Visual Settings:
- Line Style: Set your preferred visual style: Solid, Dashed, or Dotted.
- Remove Previous Drawings: When enabled, only the most recent projection is shown on the chart. Disable to retain previous levels and visually backtest their reactions over time.
Color Settings:
Customize each level independently to match your chart theme:
- Manipulation High/Low
- Distribution High/Low
- Open Level
- Label Text Color
Premium/Discount Zones:
- Enable Premium/Discount Zones: Overlay price zones above and below equilibrium to visualize potential overbought (premium) and oversold (discount) areas.
- Premium/Discount Colors: Fully customizable zone colors for clarity and emphasis.
Table Settings:
- Show Statistics Table: Adds an on-chart table summarizing key levels from your active timeframe(s).
- Table Cell Color: Set the background color of the table cells for visibility.
- Table Position: Choose from preset chart locations to position the table where it works best for your layout.
Alerts:
Stay on top of price interactions with key levels even when you're away from the charts.
- Manipulation Hits (High)
- Manipulation Hits (Low)
- Distribution Hits (High)
- Distribution Hits (Low)
TrendLibrary "Trend"
calculateSlopeTrend(source, length, thresholdMultiplier)
Parameters:
source (float)
length (int)
thresholdMultiplier (float)
Purpose:
The primary goal of this function is to determine the short-term trend direction of a given data series (like closing prices). It does this by calculating the slope of the data over a specified period and then comparing that slope against a dynamic threshold based on the data's recent volatility. It classifies the trend into one of three states: Upward, Downward, or Flat.
Parameters:
`source` (Type: `series float`): This is the input data series you want to analyze. It expects a series of floating-point numbers, typically price data like `close`, `open`, `hl2` (high+low)/2, etc.
`length` (Type: `int`): This integer defines the lookback period. The function will analyze the `source` data over the last `length` bars to calculate the slope and standard deviation.
`thresholdMultiplier` (Type: `float`, Default: `0.1`): This is a sensitivity factor. It's multiplied by the standard deviation to determine how steep the slope needs to be before it's considered a true upward or downward trend. A smaller value makes it more sensitive (detects trends earlier, potentially more false signals), while a larger value makes it less sensitive (requires a stronger move to confirm a trend).
Calculation Steps:
Linear Regression: It first calculates the value of a linear regression line fitted to the `source` data over the specified `length` (`ta.linreg(source, length, 0)`). Linear regression finds the "best fit" straight line through the data points.
Slope Calculation: It then determines the slope of this linear regression line. Since `ta.linreg` gives the *value* of the line on the current bar, the slope is calculated as the difference between the current bar's linear regression value (`linRegValue`) and the previous bar's value (`linRegValue `). A positive difference means an upward slope, negative means downward.
Volatility Measurement: It calculates the standard deviation (`ta.stdev(source, length)`) of the `source` data over the same `length`. Standard deviation is a measure of how spread out the data is, essentially quantifying its recent volatility.
Adaptive Threshold: An adaptive threshold (`threshold`) is calculated by multiplying the standard deviation (`stdDev`) by the `thresholdMultiplier`. This is crucial because it means the definition of a "flat" trend adapts to the market's volatility. In volatile times, the threshold will be wider, requiring a larger slope to signal a trend. In quiet times, the threshold will be narrower.
Trend Determination: Finally, it compares the calculated `slope` to the adaptive `threshold`:
If the `slope` is greater than the positive `threshold`, the trend is considered **Upward**, and the function returns `1`.
If the `slope` is less than the negative `threshold` (`-threshold`), the trend is considered **Downward**, and the function returns `-1`.
If the `slope` falls between `-threshold` and `+threshold` (inclusive of 0), the trend is considered **Flat**, and the function returns `0`.
Return Value:
The function returns an integer representing the determined trend direction:
`1`: Upward trend
`-1`: Downward trend
`0`: Flat trend
In essence, this library function provides a way to gauge trend direction using linear regression, but with a smart filter (the adaptive threshold) to avoid classifying minor noise or low-volatility periods as significant trends.
Statistical Price Bands with MTF Bands by QTX Algo SystemsStatistical Price Bands with MTF Bands by QTX Algo Systems
Overview
This indicator builds on the original Statistical Price Bands with Trend Filtering script by introducing Multi-Timeframe (MTF) Band Visualization. While the base version calculated adaptive price bands using statistical percentiles, trend filtering, and volatility adjustments, this enhanced version adds support/resistance bands from multiple timeframes onto the current chart.
This is not a minor cosmetic update. The MTF version includes additional request.security() logic and significantly increases context by allowing traders to reference band extremes from longer or shorter timeframes without switching charts. For this reason, the original and MTF versions are maintained separately, as this script requires a Pro+ or Premium TradingView plan to function correctly.
What’s New in This Version
Multi-Timeframe Band Support: Fetches and displays upper and lower bands from other timeframes (e.g., 30min, 1H, 4H, 1D, 1W, 1M).
Chart-Based MTF Labels: Each band is labeled with its source timeframe (e.g., “1D U” = 1-Day Upper Band) for easy visual reference.
Custom Timeframe Control: Users can toggle specific timeframes on/off depending on their preferences and strategy.
Core Calculation Method (Unchanged)
Statistical Percentile Calculation:
Determines upper and lower thresholds using a historical percentile method applied to price deviations from a VWMA anchor.
Volatility Adjustment:
Dynamically scales the percentile thresholds based on a volatility factor (standard deviation vs. moving average).
Trend Filtering:
Adds a directional bias based on whether price is above or below its VWMA, pushing the bands higher in uptrends and lower in downtrends.
MTF Band Integration
This version calculates additional statistical bands using the same logic as the chart’s timeframe, but applies it to other timeframes selected by the user. These values are fetched using request.security() and then plotted onto the current chart using lines and labels.
This functionality allows traders to:
See if current price is extended compared to higher timeframe extremes.
Spot trend continuation or exhaustion relative to intraday or macro levels.
Identify areas of confluence for trade entries, exits, or stop placement.
Inputs & Customization
Statistical Percentile (default: 95)
Controls how extreme the bands are. Higher values = wider bands.
Lookback Period (default: 350)
Number of bars used to calculate percentiles. Longer = smoother bands.
VWMA Length (default: 20)
Sets the moving average anchor for calculating relative price deviation.
Volatility Factor Multiplier (default: 1.0)
Scales the influence of market volatility on band width.
Trend Strength Multiplier (default: 10.0)
Adjusts how far bands shift in the direction of the trend.
Timeframe Toggles (MTF)
Select which timeframes (e.g., 1H, 4H, 1D, 1W) to show on the chart.
Label Offset
Controls how far right MTF labels appear on the chart.
Use Case Scenarios
Overextension Detection:
Price touching or breaching an MTF band may suggest exhaustion, especially if confirmed by confluence or divergence.
Trend Confirmation:
Bands tilting in one direction across multiple timeframes can suggest strong trend alignment.
Risk Management:
Use bands from higher timeframes as trailing stops or invalidation zones.
Why This Is a Separate Script
This version uses request.security() to retrieve values from multiple timeframes, which:
Requires an upgraded TradingView plan (Pro+ or higher).
May impact performance on lower-tier plans.
Provides a major functional difference from the original, not a minor tweak or cosmetic upgrade.
To maintain compatibility and accessibility for all users, both versions are published separately:
The original for single-timeframe users.
This version for those using a multi-timeframe workflow.
Disclaimer
This script is for educational purposes only. It is intended to support your analysis—not to predict outcomes or replace risk management. Past performance is not indicative of future results. Always perform your own analysis and trade responsibly.
Chonky ATR Levels 2.0Show ATR based high/low projections.
Choose a custom ATR calculation in the indicator's settings.
The default is a 20day RMA based ATR.
----------How projections are calculated----------
To project the ATR High, the ATR value is added to the low of the current candle that matches the ATR's timeframe.
To project the ATR Low, the ATR value is subtracted from the high of the current candle that matches the ATR's timeframe.
Example:
If a 20day RMA ATR is used:
- the ATR High will be the current day's low + the ATR value.
- the ATR Low will be the current day's high - the ATR value.
*However*, if the price action exceeds either ATR projection, the opposite ATR level will be fixed to the extreme of the period.
See the AUDUSD screenshot above for an example.
The ATR Low was exceeded, so the ATR High projection is capped at the high of day.
If the ATR High is exceeded, the ATR Low would be capped at the low of day.
Metatrader CalculatorThe “ Metatrader Calculator ” indicator calculates the position size, risk, and potential gain of a trade, taking into account the account balance, risk percentage, entry price, stop loss price, and risk/reward ratio. It supports the XAUUSD, XAGUSD, and BTCUSD pairs, automatically calculating the position size (in lots) based on these parameters. The calculation is displayed in a table on the chart, showing the lot size, loss in dollars, and potential gain based on the defined risk.