z-score-calkusi-v1.14z-scores incorporate the moment of N look-back bars to allow future price projection.
z-score = (X - mean)/std.deviation ; X = close
z-scores update with each new close print and with each new bar. Each new bar augments the mean and std.deviation for the N bars considered. The old Nth bar falls away from consideration with each new historical bar.
The indicator allows two other options for X: RSI or Moving Average.
NOTE: While trading use the "price" option only.
The other two options are provided for visualisation of RSI and Moving Average as z-score curves.
Use z-scores to identify tops and bottoms in the future as well as intermediate intersections through which a z-score will pass through with each new close and each new bar.
Draw lines from peaks and troughs in the past through intermediate peaks and troughs to identify projected intersections in the future. The most likely intersections are those that are formed from a line that comes from a peak in the past and another line that comes from a trough in the past. Try getting at least two lines from historical peaks and two lines from historical troughs to pass through a future intersection.
Compute the target intersection price in the future by clicking on the z-score indicator header to see a drag-able horizontal line to drag over the intersection. The target price is the last value displayed in the indicator's status bar after the closing price.
When the indicator header is clicked, a white horizontal drag-able line will appear to allow dragging the line over an intersection that has been drawn on the indicator for a future z-score projection and the associated future closing price.
With each new bar that appears, it is necessary to repeat the procedure of clicking the z-score indicator header to be able to drag the drag-able horizontal line to see the new target price for the selected intersection. The projected price will be different from the current close price providing a price arbitrage in time.
New intermediate peaks and troughs that appear require new lines be drawn from the past through the new intermediate peak to find a new intersection in the future and a new projected price. Since z-score curves are sort of cyclical in nature, it is possible to see where one has to locate a future intersection by drawing lines from past peaks and troughs.
Do not get fixated on any one projected price as the market decides which projected price will be realised. All prospective targets should be manually updated with each new bar.
When the z-score plot moves outside a channel comprised of lines that are drawn from the past, be ready to adjust to new market conditions.
z-score plots that move above the zero line indicate price action that is either rising or ranging. Similarly, z-score plots that move below the zero line indicate price action that is either falling or ranging. Be ready to adjust to new market conditions when z-scores move back and forth across the zero line.
A bar with highest absolute z-score for a cycle screams "reversal approaching" and is followed by a bar with a lower absolute z-score where close price tops and bottoms are realised. This can occur either on the next bar or a few bars later.
The indicator also displays the required N for a Normal(0,1) distribution that can be set for finer granularity for the z-score curve.This works with the Confidence Interval (CI) z-score setting. The default z-score is 1.96 for 95% CI.
Common Confidence Interval z-scores to find N for Normal(0,1) with a Margin of Error (MOE) of 1:
70% 1.036
75% 1.150
80% 1.282
85% 1.440
90% 1.645
95% 1.960
98% 2.326
99% 2.576
99.5% 2.807
99.9% 3.291
99.99% 3.891
99.999% 4.417
9-Jun-2025
Added a feature to display price projection labels at z-score levels 3, 2, 1, 0, -1, -2, 3.
This provides a range for prices available at the current time to help decide whether it is worth entering a trade. If the range of prices from say z=|2| to z=|1| is too narrow, then a trade at the current time may not be worth the risk.
Added plot for z-score moving average.
28-Jun-2025
Added Settings option for # of Std.Deviation level Price Labels to display. The default is 3. Min is 2. Max is 6.
This feature allows likelihood assessment for Fibonacci price projections from higher time frames at lower time frames. A Fibonacci price projection that falls outside |3.x| Std.Deviations is not likely.
Added Settings option for Chart Bar Count and Target Label Offset to allow placement of price labels for the standard z-score levels to the right of the window so that these are still visible in the window.
Target Label Offset allows adjustment of placement of Target Price Label in cases when the Target Price Label is either obscured by the price labels for the standard z-score levels or is too far right to be visible in the window.
Practice makes perfect.
Use this indicator at your own risk
[i]price
Cumulative Price🎯 Cumulative Price - Usage Framework
🧭 Purpose
Cumulative Price offers a simple contextualization of price action within a daily session.
It resets to zero daily, tracking the cumulative range of price movement in ticks — a concept similar to cumulative delta, but focused purely on price activity, not volume.
🧠 Core Concept
The oscillator shows results from effort accumulate over time. Instead of measuring who is buying or selling, it reveals how far is pushing relative to zero.
🔔 Signal Types
⚖️ Zero Signal
Triggered when the oscillator crosses above or below the zero line.
📌 Interpreted as:
Price is testing fairness or market agreement.
This level is a balancing point — price may accept it (continue) or reject it (reverse).
🚩 Peak Signal
Triggered when the oscillator reaches a new extreme, defined by ATR-based thresholds.
📌 Interpreted as:
Price is undergoing strong effort — likely accumulation or distribution.
Could signal a transition, consolidation, or imminent breakout/reversal.
🧩 How to Use
Approach both signals with thoughtful market questioning:
🧐 Something significant is happening — what is it?
📈 How intense is the move? Does it align with volatility or deviate from it?
🌐 Where does this action sit in broader market context?
🧪 Analytical Tips
Zero Signals are useful for:
Identifying reversion points or fairness tests.
Monitoring price acceptance around the session midpoint.
Peak Signals help:
Spot early accumulation/distribution behavior.
Anticipate volatility expansion or fade exhaustion.
💡 Additional Thoughts
This tool does not dictate trades. Instead, it provides context.
Combine it with tools like Cumulative Delta for a layered analysis of price result and volume effort.
Use it to frame narratives, not absolutes. Ask:
"If this is happening here, what does that say about intent?"
OPR Asia-New-York [Elykia]This Pine Script indicator, called "OPR Asia-New-York ", displays time-based boxes corresponding to two specific trading periods known as OPR (Opening Price Range):
🎯 Purpose of the Indicator:
To visualize two key market time windows (morning and afternoon) as extended boxes, helping with technical analysis around opening ranges.
🕒 Two sessions displayed as boxes:
🔹 Morning OPR:
Default: from 09:00 to 09:15 (configurable)
The box extends until 10:30.
It captures the highest and lowest candle within this interval.
🔸 Afternoon OPR:
Default: from 15:30 to 15:45
The box extends until 17:30.
Follows the same logic as the morning session.
⚙️ Dashboard Options:
Enable or disable the morning or afternoon box individually
Select the timezone (e.g., GMT+2)
Customize all colors (morning/afternoon boxes, median line)
Set your own start/end/extension times for each session
📦 Each box includes:
A colored rectangle showing the price range (high/low)
A dotted median line between the high and low
The box and line extend until the end time defined
🧠 Usefulness for Traders:
Identify liquidity zones or consolidation areas
Trade setups like liquidity grabs, breakouts, or fakeouts around the OPR
Align with ICT methods or scalping strategies based on session behavior
Pristine Value Areas & MGIThe Pristine Value Areas indicator enables users to perform comprehensive technical analysis through the lens of the market profile in a fraction of the time! 🏆
A Market Profile is a charting technique devised by J. Peter Steidlmayer, a trader at the Chicago Board of Trade (CBOT), in the 1980's. He created it to gain a deeper understanding of market behavior and to analyze the auction process in financial markets. A market profile is used to analyze an auction using price, volume, and time to create a distribution-based view of trading activity. It organizes market data into a bell-curve-like structure, which reveals areas of value, balance, and imbalance.
💠 How is a Value Area Calculated?
A value area is a distribution of 68%-70% of the trading volume over a specific time interval, which represents one standard deviation above and below the point of control, which is the most highly traded level over that period.
The key reference points are as follows:
Value area low (VAL) - The lower boundary of a value area
Value area high (VAH) - The upper boundary of a value area
Point of Control (POC) - The price level at which the highest amount of a trading period's volume occurred
If we take the probability distribution of trading activity and flip it 90 degrees, the result is our Pristine Value Area!
Market Profile is our preferred method of technical analysis at Pristine Capital because it provides an objective and repeatable assessment of whether an asset is being accumulated or distributed by institutional investors. Market Profile levels work remarkably well for identifying areas of interest, because so many institutional trading algorithms have been programmed to use these levels since the 1980's!
The benefits of using Market Profile include better trade location, improved risk management, and enhanced market context. It helps traders differentiate between trending and consolidating markets, identify high-probability trade setups, and adjust their strategies based on whether the market is in balance (consolidation) or imbalance (trending). Unlike traditional indicators that rely on past price movements, Market Profile provides real-time insights into trader behavior, giving an edge to those who can interpret its nuances effectively.
Virgin Point of Control (VPOC) - A point of control from a previous time period that has not yet been revisited in subsequent periods. VPOCs are great for identifying prior supply or demand zones.
Below is a great example of price reversing lower after taking out an upside VPOC
💠 Are all POCs Created Equal?
If POCs are used to gauge supply & demand zones at key levels, then a POC with higher volume should be viewed as more significant than a POC that traded lower volume, right? We created Golden POCs as a tool to identify high volume POCs on all timeframes.
Golden POC (GPOC) - A POC that traded the highest volume compared to prior POCs (proprietary to Pristine Capital)
We calculate value areas for the following time intervals based on the user selected timeframe:
5 Minute and 15 Minute Timeframes -> Daily Value Area
The daily value area paints the distribution of the PRIOR session's trading activity. The "d" in the label references for VAHd, POCd and VALd is a visual cue that value area shown is daily.
1 Hour Timeframe -> Weekly Value Area
The weekly value area paints the distribution of the PRIOR week's trading activity. The "w" in the label references for VAHw, POCw and VALw is a visual cue that value area shown is weekly.
1 Day Timeframe -> Monthly Value Area
The monthly value area paints the distribution of the PRIOR month's trading activity. The "m" in the label references for VAHm, POCm and VALm is a visual cue that value area shown is monthly.
1 Week Timeframe -> Yearly Value Area
The yearly value area paints the distribution of the PRIOR year's trading activity. The "y" in the label references for VAHy, POCy and VALy is a visual cue that value area shown is yearly.
💠 What is a developing value area?
The developing value area provides insight into the upcoming value area while it is still forming! It appears when 80% of the way through the current value area. As the end of a trading period approaches, it can make sense to start trading off the developing value area. When the time period flips, the developing value area becomes the active value area!
💠 Value Areas Trading Setups
Two popular market profile concepts are the bullish and bearish 80% rules. The concept is that there is an 80% probability that the market will traverse the entire relevant value area.
Bullish 80% Rule - If a security opens a period below the value area low , and subsequently closes above it, the bullish 80% rule triggers, turning the value area green. One can trade for a move to the top of the value area, using a close below the value area low as a potential stop!
In the below example, HOOD triggered the bullish 80% rule after it reclaimed the monthly value area!
HOOD proceeded to rally through the monthly value area and beyond in subsequent trading sessions. Finding the first stocks to trigger the bullish 80% rule after a market correction is key for spotting the next market leaders!
Bearish 80% Rule - If a security opens a period above the value area high , and subsequently closes below it, the bearish 80% rule triggers, turning the value area red. One can trade for a move to the bottom of the value area, using a close above the value area high as a potential stop!
ES proceeded to follow through and test the value area low before trending below the weekly value area
Value Area Breakouts - When a security is inside of value, the auction is in balance. When it breaks out from a value area, it could be entering a period of price discovery. One can trade these breaks out of value with tight risk control by setting a stop inside the value area! These breakouts can be traded on all chart timeframes depending on the timeframe of the individual trader. Combining multiple timeframes can result in even more effective trading setups.
RBLX broke out from the monthly value area on 4/22/25👇
RBLX proceeded to rally +62.78% in 39 trading sessions following the monthly VAH breakout!
💠 Market Generated Information to Improve Your Situational Awareness!
In addition to the value areas, we've also included stat tables with useful market generated information. The stats displayed vary based on the timeframe the user has up on their screen. This incentivizes traders to check the chart on multiple timeframes before taking a trade!
Metrics Grouped By Use Case
Performance
▪ YTD α - YTD Alpha (α) measures the risk-adjusted, excess return of a security over its user defined benchmark, on a year-to-date basis.
▪ MTD α - MTD Alpha (α) measures the risk-adjusted, excess return of a security over its user defined benchmark, on a month-to-date basis.
▪ WTD α - WTD Alpha (α) measures the risk-adjusted, excess return of a security over its user defined benchmark, on a week-to-date basis.
▪ YTD %Δ - Year-to-date percent change in price
▪ MTD %Δ - Month-to-date percent change in price
▪ WTD %Δ - Week-to-date percent change in price
Volatility
▪ ATR % - The Average True Range (ATR) expressed as a percentage of an asset's price.
▪ Beta - Measures the price volatility of a security compared to the S&P 500 over the prior 5 years (since inception if 5 years of data is not available)
Risk Analysis
▪ LODx - Low-of-day extension - ATR % multiple from the low of day (measures how extended a stock is from its low of day)
▪ MAx - Moving average extension - ATR % multiple from the user-defined moving average (measures how extended a security is from its moving average). Default moving average = 50D SMA
Why does MAx matter?
MAx measures the number of ATR % multiples a security is trading away from a key moving average. The default moving average length is 50 days.
MAx can be used to identify mean reversion trades . When a security trends strongly in one direction and moves significantly above or below its moving average, the price often tends to revert back toward the average.
Example, if the ATR % of the security is 5%, and the stock is trading 50% higher than the 50D SMA, the MAx would be 50%/5% = 10. A user might opt to take a countertrend trade when the MAx exceeds a predetermined level.
The MAx can also be useful when trading breakouts above or below the key moving average of your choosing. The lower the MAx, the tighter stop loss one can take if trading against that level.
Identifying an extreme price extension using MAx 👇
Price mean reverted immediately following the high MAx 👇
💠 Trend Analysis
The Trend Analysis section consists of short-term and long-term stage analysis data as well as the value area timeframe and price in relation to the value area.
Stage Analysis
▪ ST ⇅ - Short-term stage analysis indicator
▪ LT ⇅ - Long-term stage analysis indicator
Short-term and long-term stage analysis data is provided in the two rightmost columns of each table. The columns are labeled ST ⇅ and LT ⇅.
Why is Stage Analysis important? Popularized by Stan Weinstein, stage analysis is a trend following system that classifies assets into four stages based on price-trend analysis.
The problem? The interpretation of stage analysis is highly subjective. Based on the methodology provided in Stan Weinstein’s books, five different traders could look at the same chart, and come to different conclusions as to which stage the security is in!
We solved for this by creating our own methodology for classifying stocks into stages using moving averages. This indicator automates that analysis, and produces short-term and long-term trend signals based on user-defined key moving averages. You won’t find this in any textbook or course, because it’s completely unique to the Pristine trading methodology.
Our indicator calculates a short-term trend signal using two moving averages; a fast moving average, and a slow moving average. We default to the 10D EMA as the fast moving average & the 20D SMA as the slow moving average. A trend signal is generated based on where price is currently trading with respect to the fast moving average and the slow moving average. We use the signal to guide shorter-term swing trades.
In general, we want to take long trades in stocks with strengthening trends, and short trades in stocks with weakening trends. The user is free to change the moving averages based on their own short-term timeframe. Every trader is unique!
The same process is applied to calculate the long-term trend signal. We default to the 50D SMA as our fast moving average, and the 200D SMA as the slow moving average for the LT ⇅ signal calculation, but users can change these to fit their own unique trading style.
What is Stage 1?
Stage 1 identifies stocks that transitioned from downtrends, into bottoming bases.
Stage 1A - Bottom Signal: Marks the first day a security shows initial signs of recovery after a downtrend, with early indications of strength emerging.👇
Stage 1B - Bottoming Process: Identifies the ongoing phase where the security continues to stabilize and strengthen, confirming the base-building process after the initial signal.👇
Stage 1R - Failed Uptrend: Detects when a security that had entered an early uptrend loses momentum and slips back into a bottoming phase, signaling a failed breakout.👇
What is Stage 2?
Stage 2 identifies stocks that transitioned from bottoming bases to uptrends.
Stage 2A - Breakout: Marks the first day a security decisively breaks out, signaling the start of a new uptrend.👇
Stage 2B - Uptrend: Identifies when the security continues to trade in an established uptrend following the initial breakout, with momentum building but not yet showing full strength.👇
Stage 2C - Strong Uptrend: Detects when the uptrend strengthens further, with the security displaying clear signs of accelerating strength and buying pressure.👇
Stage 2R - Failed Breakdown: Detects when a security that had recently entered a corrective phase reverses course and reclaims its upward trajectory, moving back into an uptrend.👇
What is Stage 3?
Stage 3 identifies stocks that transitioned from uptrends to topping bases.
Stage 3A - Top Signal: Marks the first day a security shows initial signs of weakness after an uptrend, indicating the start of a potential topping phase.👇
Stage 3B - Topping Process: Identifies the period following the initial signal when the security continues to show signs of distribution and potential trend exhaustion.👇
Stage 3R - Failed Breakdown: Detects when a security that had entered a deeper corrective phase reverses upward, recovering enough strength to re-enter the topping phase.👇
What is Stage 4?
Stage 4 identifies stocks that transitioned from topping bases to downtrends.
Stage 4A - Breakdown: Marks the first day a security decisively breaks below key support levels, signaling the start of a new downward trend.👇
Stage 4B - Downtrend: Identifies when the security continues to trend lower following the initial breakdown, with sustained bearish momentum, though not yet fully entrenched.👇
Stage 4C - Strong Downtrend: Detects when the downtrend intensifies, with the security displaying clear signs of accelerating weakness and selling pressure.👇
Stage 4R - Failed Bottom: Detects when a security that had begun to show early signs of bottoming reverses course and resumes its decline, falling back into a downtrend.👇
Stage N/A - Recent IPO: Applies to stocks that recently IPO’ed and don’t have enough data to calculate all necessary moving averages.
Value Area
In Trend Analysis, the value area information is helpful to gauge price in relation to the value area.
▪ VA(y) - Categorizes the security based on the relation of price to the yearly value area
▪ VA(m) - Categorizes the security based on the relation of price to the monthly value area
▪ VA(w) - Categorizes the security based on the relation of price to the weekly value area
Value area states:
▪ ABOVE = Price above the value area high
▪ BELOW = Price below the value area low
▪ INSIDE = Price inside the value area
▪ Bull 80% = Bullish 80% rule in effect
▪ Bear 80% rule = Bearish 80% rule in effect
For example, in the chart above, VA(m) - ABOVE indicates a monthly value area and price is above the VAH.
💠 What Makes This Indicator Unique
There are many value area indicators, however...
Value Area
▪ Golden POC (GPOC) - This is a proprietary concept.
▪ Unique Label Customization
Pristine value areas often comprehensive and unique label customizations. Styles include options to display any combination of the following on your labels:
• Price levels associated with market profile levels
• % distance of market profile levels from security price
• ATR% extension of market profile levels from security price
Multi-Timeframe Analysis
Based on the chart timeframe, unique market generated information is shown to facilitate multi-timeframe analysis.
▪ Weekly Timeframe
On the weekly timeframe the focus is the bigger picture and the metrics reflect this perspective. Performance data includes YTD Alpha and YTD percent change in price. Volatility is measured using ATR % and the industry standard beta. Trend analysis for this higher timeframe include the 52-week range, which measures where a security is trading in relation to its 52wk high and 52wk low. Also included is the where price is in relation to yearly value area.
▪ Daily Timeframe
As one drills down to the daily timeframe, the performance metrics include MTD alpha and MTD percent change in price.
Risk analysis includes the low-of-day extension (LODx), which is the ATR % multiple from the low of the day, to measures how extended a stock is from its low of day. In addition, the moving average extension (MAx) is the ATR % multiple from the user-defined moving average, measures how extended a security is from its
moving average. The default moving average is the 50D SMA, however this can be customized in Settings.
Trend Analysis on the daily timeframe includes the Pristine Capital methodology for classifying stocks into stages using moving averages. Both short-term and long-term stage analysis data is included. Finally, price in relation to monthly value area is shown.
▪ Hourly Timeframe
An the hourly timeframe, performance metrics include WTD alpha and WTD percent change in price. Trend analysis includes the daily closing range (DCR) and price in relation to weekly value area.
💠 Settings and Preferences
💠 Acknowledgements
We'd like to thank @dgtrd, a TradingView Pine Wizard, for his insight on the finer details when working with volume profiles.
9 EMA vs 21 EMA Cloud (Anchored)ema cloud 9 ema and 21 ema. whenever 9 ema is above 21 ema the trend is bulish and vice versa. when ema is below 21 ema trend bearish
QQQ NQ NDX SPY SPX ES Price Convert Overlay
_____________________________________________________________________
QQQ NQ NDX SPY SPX ES Price Convert Overlay Indicator
____________________
This 'Prices Overlay' indicator is a minimalist tool for traders who want to track and compare Nasdaq and S&P 500 instruments quickly and clearly, boosting efficiency and decision-making with minimal distraction.
How to Use It
____________________
Add the indicator onto your TradingView chart.
Adjust your Right Margin in TradingView Settings > Canvas to show as much or as little of the line as you want, based on the "Price Buffer" indicator setting.
Select which instruments to overlay (e.g., QQQ, SPX).
Adjust levels, buffer, font, transparency, and update interval.
Features and Functions
____________________
1. Automatic Ticker Detection:
The indicator identifies the ticker of your current chart (e.g., NQ, ES, SPY).
It then shows price levels for related instruments, eg:
On an NQ or MNQ chart, it can display QQQ or NDX levels.
On an ES or MES chart, it can display SPY or SPX levels.
...and vice versa
2. Adjustable Number of Levels
You can choose how many price levels to show, from 10 to 100.
This lets you decide how much detail you want based on your trading needs.
3. Visual Customization
Price Buffer: Move the lines and labels horizontally closer/further price action.
Font Size: Pick from "Tiny," "Small," or "Normal" for label text size.
Line Transparency: Adjust the opacity of the lines (0% = solid, 100% = invisible) to blend them with your chart.
4. Support for Micro Futures
Works with both regular futures (NQ, ES) and micro futures (MNQ, MES), perfect for traders using smaller contract sizes.
5. Update Frequency
Set how often the price levels refresh, from every 5 seconds to every 60 seconds.
This keeps the data current without slowing down your chart.
6. Accurate Price Conversion
Uses specific multipliers for each instrument (e.g., 100.0 for NDX and SPX, 1.0 for QQQ and SPY) to calculate and display price levels correctly.
Fetches real-time prices and converts them to match your chart’s scale.
Price conversions courtesy of PtGambler.
Benefits
____________________
Easier Analysis: See how prices from different instruments line up on one chart—no need for multiple screens or math.
Customizable: Turn on/off instruments and tweak visuals to fit your trading style.
Time-Saving: Automates price conversions, letting you focus on trading decisions.
Thanks!
____________________
Thank you for your interest in my work. This is something I use every day for my trading and wanted to share it with the public. If you have any comments, bugs, or suggestions, please leave them here, or you can find me on Twitter or Discord.
@ ContrarianIRL
Open-source developer for over 25 years
Calc win-LoserHow to Use the Calc win-Loser Indicator
The indicator calculates the profit or loss of the operation, showing how much you gained or lost on the invested amount, without adding the initial capital, displaying only the profit or loss separately.
Use a period (.) to separate decimal numbers, without thousand separators (e.g., 1000 for one thousand, 1000.50 for one thousand and fifty cents).
Price Definition for Calculation
Long Position (buy):
Low Price: entry price (lower)
High Price: exit price (higher)
Example: enter at 1 and exit at 3
Short Position (sell):
High Price: entry price (higher)
Low Price: exit price (lower)
Example: enter at 3 and exit at 1
Main Parameters
Parameter Description Example
Low Price Base price for calculation (Long: entry; Short: exit) 1
High Price Base price for calculation (Long: exit; Short: entry) 3
Leverage Operation multiplier (leverage) 2.0
Universal Amount Total amount invested 1000
Broker Fee (%) Percentage fee charged by broker 0.1
Currency Currency symbol for value display USD
Practical Example
Long: entry at 1, exit at 3, 2x leverage, $1000 investment, 0.1% fee.
Short: entry at 3, exit at 1, 2x leverage, $1000 investment, 0.1% fee.
The indicator will show the expected profit or loss based on the percentage difference adjusted by leverage and subtracting the broker fee.
Notes
Adjust prices according to the type of operation (Long or Short).
Use a period for decimals and do not use thousand separators.
This indicator is a simulation tool and does not execute automatic trades.
Original indicator by Canhoto-Medium — protected to maintain order and respect, prevent copying and plagiarism.
Bilateral Filter For Loop [BackQuant]Bilateral Filter For Loop
The Bilateral Filter For Loop is an advanced technical indicator designed to filter out market noise and smooth out price data, thus improving the identification of underlying market trends. It employs a bilateral filter, which is a sophisticated non-linear filter commonly used in image processing and price time series analysis. By considering both spatial and range differences between price points, this filter is highly effective at preserving significant trends while reducing random fluctuations, ultimately making it suitable for dynamic trend-following strategies.
Please take the time to read the following:
Key Features
1. Bilateral Filter Calculation:
The bilateral filter is the core of this indicator and works by applying a weight to each data point based on two factors: spatial distance and price range difference. This dual weighting process allows the filter to preserve important price movements while reducing the impact of less relevant fluctuations. The filter uses two primary parameters:
Spatial Sigma (σ_d): This parameter adjusts the weight applied based on the distance of each price point from the current price. A larger spatial sigma means more smoothing, as further away values will contribute more heavily to the result.
Range Sigma (σ_r): This parameter controls how much weight is applied based on the difference in price values. Larger price differences result in smaller weights, while similar price values result in larger weights, thereby preserving the trend while filtering out noise.
The output of this filter is a smoothed version of the original price series, which eliminates short-term fluctuations, helping traders focus on longer-term trends. The bilateral filter is applied over a rolling window, adjusting the level of smoothing dynamically based on both the distance between values and their relative price movements.
2. For Loop Calculation for Trend Scoring:
A for-loop is used to calculate the trend score based on the filtered price data. The loop compares the current value to previous values within the specified window, scoring the trend as follows:
+1 for upward movement (when the filtered value is greater than the previous value).
-1 for downward movement (when the filtered value is less than the previous value).
The cumulative result of this loop gives a continuous trend score, which serves as a directional indicator for the market's momentum. By summing the scores over the window period, the loop provides an aggregate value that reflects the overall trend strength. This score helps determine whether the market is experiencing a strong uptrend, downtrend, or sideways movement.
3. Long and Short Conditions:
Once the trend score has been calculated, it is compared against predefined threshold levels:
A long signal is generated when the trend score exceeds the upper threshold, indicating that the market is in a strong uptrend.
A short signal is generated when the trend score crosses below the lower threshold, signaling a potential downtrend or trend reversal.
These conditions provide clear signals for potential entry points, and the color-coding helps traders quickly identify market direction:
Long signals are displayed in green.
Short signals are displayed in red.
These signals are designed to provide high-confidence entries for trend-following strategies, helping traders capture profitable movements in the market.
4. Trend Background and Bar Coloring:
The script offers customizable visual settings to enhance the clarity of the trend signals. Traders can choose to:
Color the bars based on the trend direction: Bars are colored green for long signals and red for short signals.
Change the background color to provide additional context: The background will be shaded green for a bullish trend and red for a bearish trend. This visual feedback helps traders to stay aligned with the prevailing market sentiment.
These features offer a quick visual reference for understanding the market's direction, making it easier for traders to identify when to enter or exit positions.
5. Threshold Lines for Visual Feedback:
Threshold lines are plotted on the chart to represent the predefined long and short levels. These lines act as clear markers for when the market reaches a critical threshold, triggering a potential buy (long) or sell (short) signal. By showing these threshold lines on the chart, traders can quickly gauge the strength of the market and assess whether the trend is strong enough to warrant action.
These thresholds can be adjusted based on the trader's preferences, allowing them to fine-tune the indicator for different market conditions or asset behaviors.
6. Customizable Parameters for Flexibility:
The indicator offers several parameters that can be adjusted to suit individual trading preferences:
Window Period (Bilateral Filter): The window size determines how many past price values are used to calculate the bilateral filter. A larger window increases smoothing, while a smaller window results in more responsive, but noisier, data.
Spatial Sigma (σ_d) and Range Sigma (σ_r): These values control how sensitive the filter is to price changes and the distance between data points. Fine-tuning these parameters allows traders to adjust the degree of noise reduction applied to the price series.
Threshold Levels: The upper and lower thresholds determine when the trend score crosses into long or short territory. These levels can be customized to better match the trader's risk tolerance or asset characteristics.
Visual Settings: Traders can customize the appearance of the chart, including the line width of trend signals, bar colors, and background shading, to make the indicator more readable and aligned with their charting style.
7. Alerts for Trend Reversals:
The indicator includes alert conditions for real-time notifications when the market crosses the defined thresholds. Traders can set alerts to be notified when:
The trend score crosses the long threshold, signaling an uptrend.
The trend score crosses the short threshold, signaling a downtrend.
These alerts provide timely information, allowing traders to take immediate action when the market shows a significant change in direction.
Final Thoughts
The Bilateral Filter For Loop indicator is a robust tool for trend-following traders who wish to reduce market noise and focus on the underlying trend. By applying the bilateral filter and calculating trend scores, this indicator helps traders identify strong uptrends and downtrends, providing reliable entry signals with minimal market noise. The customizable parameters, visual feedback, and alerting system make it a versatile tool for traders seeking to improve their timing and capture profitable market movements.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
INDEX:BTCUSD
INDEX:ETHUSD
CRYPTO:SOLUSD
Wavelet Filter with Adaptive Upsampling [BackQuant]Wavelet Filter with Adaptive Upsampling
The Wavelet Filter with Adaptive Upsampling is an advanced filtering and signal reconstruction tool designed to enhance the analysis of financial time series data. It combines wavelet transforms with adaptive upsampling techniques to filter and reconstruct price data, making it ideal for capturing subtle market movements and enhancing trend detection. This system uses high-pass and low-pass filters to decompose the price series into different frequency components, applying adaptive thresholding to eliminate noise and preserve relevant signal information.
Shout out to Loxx for the Least Squares fitting of trigonometric series and Quinn and Fernandes algorithm for finding frequency
www.tradingview.com
Key Features
1. Frequency Decomposition with High-Pass and Low-Pass Filters:
The indicator decomposes the input time series using high-pass and low-pass filters to separate the high-frequency (detail) and low-frequency (trend) components of the data. This decomposition allows for a more accurate analysis of underlying trends, while mitigating the impact of noise.
2. Soft Thresholding for Noise Reduction:
A soft thresholding function is applied to the high-frequency component, allowing for the reduction of noise while retaining significant market signals. This function adjusts the coefficients of the high-frequency data, removing small fluctuations and leaving only the essential price movements.
3. Adaptive Upsampling Process:
The upsampling process in this script can be customized using different methods: sinusoidal upsampling, advanced upsampling, and simple upsampling. Each method serves a unique purpose:
Sinusoidal Upsample uses a sine wave to interpolate between data points, providing a smooth transition.
Advanced Upsample utilizes a Quinn-Fernandes algorithm to estimate frequency and apply more sophisticated interpolation techniques, adapting to the market’s cyclical behavior.
Simple Upsample linearly interpolates between data points, providing a basic upsampling technique for less complex analysis.
4. Reconstruction of Filtered Signal:
The indicator reconstructs the filtered signal by summing the high and low-frequency components after upsampling. This allows for a detailed yet smooth representation of the original time series, which can be used for analyzing underlying trends in the market.
5. Visualization of Reconstructed Data:
The reconstructed series is plotted, showing how the upsampling and filtering process enhances the clarity of the price movements. Additionally, the script provides the option to visualize the log returns of the reconstructed series as a histogram, with positive returns shown in green and negative returns in red.
6. Cumulative Series and Trend Detection:
A cumulative series is plotted to visualize the compounded effect of the filtered and reconstructed data. This feature helps traders track the overall performance of the asset over time, identifying whether the asset is following a sustained upward or downward trend.
7. Adaptive Thresholding and Noise Estimation:
The system estimates the noise level in the high-frequency component and applies an adaptive thresholding process based on the standard deviation of the downsampled data. This ensures that only significant price movements are retained, further refining the trend analysis.
8. Customizable Parameters for Flexibility:
Users can customize the following parameters to adjust the behavior of the indicator:
Frequency and Phase Shift: Control the periodicity of the wavelet transformation and the phase of the upsampling function.
Upsample Factor: Adjust the level of interpolation applied during the upsampling process.
Smoothing Period: Determine the length of time used to smooth the signal, helping to filter out short-term fluctuations.
References
Enhancing Cross-Sectional Currency Strategies with Context-Aware Learning to Rank
arxiv.org
Daubechies Wavelet - Wikipedia
en.wikipedia.org
Quinn Fernandes Fourier Transform of Filtered Price by Loxx
Note on Usage for Mean-Reversion Strategy
This indicator is primarily designed for trend-following strategies. However, by taking the inverse of the signals, it can be adapted for mean-reversion strategies. This involves buying underperforming assets and selling outperforming ones. Caution: This method may not work effectively with highly correlated assets, as the price movements between correlated assets tend to mirror each other, limiting the effectiveness of mean-reversion strategies.
Final Thoughts
The Wavelet Filter with Adaptive Upsampling is a powerful tool for traders seeking to improve their understanding of market trends and noise. By using advanced wavelet decomposition and adaptive upsampling, this system offers a clearer, more refined picture of price movements, enhancing trend-following strategies. It’s particularly useful for detecting subtle shifts in market momentum and reconstructing price data in a way that removes noise, providing more accurate insights into market conditions.
Volume Momentum [BackQuant]Volume Momentum
The Volume Momentum indicator is designed to help traders identify shifts in market momentum based on volume data. By analyzing the relative volume momentum, this indicator provides insights into whether the market is gaining strength (uptrend) or losing momentum (downtrend). The strategy uses a combination of percentile-based volume normalization, weighted moving averages (WMA), and exponential moving averages (EMA) to assess volume trends.
The system focuses on the relationship between price and volume, utilizing normalized volume data to highlight key market changes. This approach allows traders to focus on volume-driven price movements, helping them to capture momentum shifts early.
Key Features
1. Volume Normalization and Percentile Calculation:
The signed volume (positive when the close is higher than the open, negative when the close is lower) is normalized against the rolling average volume. This normalized volume is then subjected to a percentile interpolation, allowing for a robust statistical measure of how the current volume compares to historical data. The percentile level is customizable, with 50 representing the median.
2. Weighted and Smoothed Moving Averages for Trend Detection:
The normalized volume is smoothed using weighted moving averages (WMA) and exponential moving averages (EMA). These smoothing techniques help eliminate noise, providing a clearer view of the underlying momentum. The WMA filters out short-term fluctuations, while the EMA ensures that the most recent data points have a higher weight, making the system more responsive to current market conditions.
3. Trend Reversal Detection:
The indicator detects momentum shifts by evaluating whether the volume momentum crosses above or below zero. A positive volume momentum indicates a potential uptrend, while a negative momentum suggests a possible downtrend. These trend reversals are identified through crossover and crossunder conditions, triggering alerts when significant changes occur.
4. Dynamic Trend Background and Bar Coloring:
The script offers customizable background coloring based on the trend direction. When volume momentum is positive, the background is colored green, indicating a bullish trend. When volume momentum is negative, the background is colored red, signaling a bearish trend. Additionally, the bars themselves can be colored based on the trend, further helping traders quickly visualize market momentum.
5. Alerts for Momentum Shifts:
The system provides real-time alerts for traders to monitor when volume momentum crosses a critical threshold (zero), signaling a trend reversal. The alerts notify traders when the market momentum turns bullish or bearish, assisting them in making timely decisions.
6. Customizable Parameters for Flexible Usage:
Users can fine-tune the behavior of the indicator by adjusting various parameters:
Volume Rolling Mean: The period used to calculate the average volume for normalization.
Percentile Interpolation Length: Defines the range over which the percentile is calculated.
Percentile Level: Determines the percentile threshold (e.g., 50 for the median).
WMA and Smoothing Periods: Control the smoothing and response time of the indicator.
7. Trend Background Visualization and Trend-Based Bar Coloring:
The background fill is shaded according to whether the volume momentum is positive or negative, providing a visual cue to indicate market strength. Additionally, bars can be color-coded to highlight the trend, making it easier to see the trend’s direction without needing to analyze numerical data manually.
8. Note on Mean-Reversion Strategy:
If you take the inverse of the signals, this indicator can be adapted for a mean-reversion strategy. Instead of following the trend, the strategy would involve buying assets that are underperforming and selling assets that are overperforming, based on volume momentum. However, it’s important to note that this approach may not work effectively on highly correlated assets, as their price movements may be too similar, reducing the effectiveness of the mean-reversion strategy.
Final Thoughts
The Volume Momentum indicator offers a comprehensive approach to analyzing volume-based momentum shifts in the market. By using volume normalization, percentile interpolation, and smoothed moving averages, this system helps identify the strength and direction of market trends. Whether used for trend-following or adapted for mean-reversion, this tool provides traders with actionable insights into the market’s volume-driven movements, improving decision-making and portfolio management.
40 Ticker Cross-Sectional Z-Scores [BackQuant]40 Ticker Cross-Sectional Z-Scores
BackQuant’s 40 Ticker Cross-Sectional Z-Scores is a powerful portfolio management strategy that analyzes the relative performance of up to 40 different assets, comparing them on a cross-sectional basis to identify the top and bottom performers. This indicator computes Z-scores for each asset based on their log returns and evaluates them relative to the mean and standard deviation over a rolling window. The Z-scores represent how far an asset's return deviates from the average, and these values are used to rank the assets, allowing for dynamic asset allocation based on performance.
By focusing on the strongest-performing assets and avoiding the weakest, this strategy aims to enhance returns while managing risk. Additionally, by adjusting for standard deviations, the system offers a risk-adjusted method of ranking assets, making it suitable for traders who want to dynamically allocate capital based on performance metrics rather than just price movements.
Key Features
1. Cross-Sectional Z-Score Calculation:
The system calculates Z-scores for 40 different assets, evaluating their log returns against the mean and standard deviation over a rolling window. This enables users to assess the relative performance of each asset dynamically, highlighting which assets are performing better or worse compared to their historical norms. The Z-score is a useful statistical tool for identifying outliers in asset performance.
2. Asset Ranking and Allocation:
The system ranks assets based on their Z-scores and allocates capital to the top performers. It identifies the top and bottom assets, and traders can allocate capital to the top-performing assets, ensuring that their portfolio is aligned with the best performers. Conversely, the bottom assets are removed from the portfolio, reducing exposure to underperforming assets.
3. Rolling Window for Mean and Standard Deviation Calculations:
The Z-scores are calculated based on rolling means and standard deviations, making the system adaptive to changing market conditions. This rolling calculation window allows the strategy to adjust to recent performance trends and minimize the impact of outdated data.
4. Mean and Standard Deviation Visualization:
The script provides real-time visualizations of the mean (x̄) and standard deviation (σ) of asset returns, helping traders quickly identify trends and volatility in their portfolio. These visual indicators are useful for understanding the current market environment and making more informed allocation decisions.
5. Top & Bottom Performer Tables:
The system generates tables that display the top and bottom performers, ranked by their Z-scores. Traders can quickly see which assets are outperforming and underperforming. These tables provide clear and actionable insights, helping traders make informed decisions about which assets to include in their portfolio.
6. Customizable Parameters:
The strategy allows traders to customize several key parameters, including:
Rolling Calculation Window: Set the window size for the rolling mean and standard deviation calculations.
Top & Bottom Tickers: Choose how many of the top and bottom assets to display and allocate capital to.
Table Orientation: Select between vertical or horizontal table formats to suit the user’s preference.
7. Forward Test & Out-of-Sample Testing:
The system includes out-of-sample forward tests, ensuring that the strategy is evaluated based on real-time performance, not just historical data. This forward testing approach helps validate the robustness of the strategy in dynamic market conditions.
8. Visual Feedback and Alerts:
The system provides visual feedback on the current asset rankings and allocations, with dynamic labels and plots on the chart. Additionally, users receive alerts when allocations change, keeping them informed of important adjustments.
9. Risk Management via Z-Scores and Std Dev:
The system’s approach to asset selection is based on Z-scores, which normalize performance relative to the historical mean. By incorporating standard deviation, it accounts for the volatility and risk associated with each asset. This allows for more precise risk management and portfolio construction.
10. Note on Mean Reversion Strategy:
If you take the inverse of the signals provided by this indicator, the strategy can be used for mean-reversion rather than trend-following. This would involve buying the underperforming assets and selling the outperforming ones. However, it's important to note that this approach does not work well with highly correlated assets, as the relationship between the assets could result in the same directional movement, undermining the effectiveness of the mean-reversion strategy.
References
www.uts.edu.au
onlinelibrary.wiley.com
www.cmegroup.com
Final Thoughts
The 40 Ticker Cross-Sectional Z-Scores strategy offers a data-driven approach to portfolio management, dynamically allocating capital based on the relative performance of assets. By using Z-scores and standard deviations, this strategy ensures that capital is directed to the strongest performers while avoiding weaker assets, ultimately improving the risk-adjusted returns of the portfolio. Whether you’re focused on trend-following or looking to explore mean-reversion strategies, this flexible system can be tailored to suit your investment goals.
Cross-Sectional Altcoin Portfolio [BackQuant]Cross-Sectional Altcoin Portfolio
Introducing BackQuant's Cross-Sectional Altcoin Portfolio, a sophisticated trading system designed to dynamically rotate among a selection of major altcoins. This portfolio strategy compares multiple assets based on real-time performance metrics, such as momentum and trend strength, to select the strongest-performing coins. It uses a combination of adaptive scoring and regime filters to ensure the portfolio is aligned with favorable market conditions, minimizing exposure during unfavorable trends.
This system offers a comprehensive solution for crypto traders who want to optimize portfolio allocation based on cross-asset performance, while also accounting for market regimes. It allows traders to compare multiple altcoins dynamically and allocate capital to the top performers, ensuring the portfolio is always positioned in the most promising assets.
Key Features
1. Dynamic Asset Rotation:
The portfolio constantly evaluates the relative strength of 10 major altcoins: SOLUSD, RUNEUSD, ORDIUSD, DOGEUSDT, ETHUSD, ENAUSDT, RAYUSDT, PENDLEUSD, UNIUSD, and KASUSDT.
Using a ratio matrix, the system selects the strongest asset based on momentum and trend performance, dynamically adjusting the allocation as market conditions change.
2. Long-Only Portfolio with Cash Reserve:
The portfolio only takes long positions or remains in cash. The system does not enter short positions, reducing the risk of exposure during market downturns.
A powerful regime filter ensures the system is inactive during periods of market weakness, defined by the Universal Trend Performance Indicator (TPI) and other market data.
3. Equity Tracking:
The script provides real-time visualizations of portfolio equity compared to buy-and-hold strategies.
Users can compare the performance of the portfolio against holding individual assets (e.g., BTC, ETH) and see the benefits of the dynamic allocation.
4. Performance Metrics:
The system provides key performance metrics such as:
Sharpe Ratio: Measures risk-adjusted returns.
Sortino Ratio: Focuses on downside risk.
Omega Ratio: Evaluates returns relative to risk.
Maximum Drawdown: The maximum observed loss from a peak to a trough.
These metrics allow traders to assess the effectiveness of the strategy versus simply holding the assets.
5. Regime Filter:
The system incorporates a regime filter that evaluates the overall market trend using the TPI and other indicators. If the market is in a downtrend, the system exits positions and moves to cash, avoiding exposure to negative market conditions.
Users can customize the thresholds for the long and short trends to fit their risk tolerance.
6. Customizable Parameters:
Traders can adjust key parameters, such as the backtest start date, starting capital, leverage multiplier, and visualization options, including equity plot colors and line widths.
The system supports different levels of customizations for traders to optimize their strategies.
7. Equity and Buy-and-Hold Comparisons:
This script enables traders to see the side-by-side comparison of the portfolio’s equity curve and the equity curve of a buy-and-hold strategy for each asset.
The comparison allows users to evaluate the performance of the dynamic strategy versus holding the altcoins in isolation.
8. Forward Test (Out-of-Sample Testing):
The system includes a note that the portfolio provides out-of-sample forward tests, ensuring the robustness of the strategy. This is crucial for assessing the portfolio's performance beyond historical backtesting and validating its ability to adapt to future market conditions.
9. Visual Feedback:
The system offers detailed visual feedback on the current asset allocation and performance. Candles are painted according to the trend of the selected assets, and key metrics are displayed in real-time, including the momentum scores for each asset.
10. Alerts and Notifications:
Real-time alerts notify traders when the system changes asset allocations or moves to cash, ensuring they stay informed about portfolio adjustments.
Visual labels on the chart provide instant feedback on which asset is currently leading the portfolio allocation.
How the Rotation Works
The portfolio evaluates 10 different assets and calculates a momentum score for each based on their price action. This score is processed through a ratio matrix, which compares the relative performance of each asset.
Based on the rankings, the portfolio allocates capital to the top performers, ensuring it rotates between the strongest assets while minimizing exposure to underperforming assets.
If no asset shows strong performance, the system defaults to cash to preserve capital.
Final Thoughts
BackQuant’s Cross-Sectional Altcoin Portfolio provides a dynamic and systematic approach to altcoin portfolio management. By employing real-time performance metrics, adaptive scoring, and regime filters, this strategy aims to optimize returns while minimizing exposure to market downturns. The inclusion of out-of-sample forward tests ensures that the system remains robust in live market conditions, making it an ideal tool for crypto traders seeking to enhance their portfolio's performance with a data-driven, momentum-based approach.
Performance Metrics With Bracketed Rebalacing [BackQuant]Performance Metrics With Bracketed Rebalancing
The Performance Metrics With Bracketed Rebalancing script offers a robust method for assessing portfolio performance, integrating advanced portfolio metrics with different rebalancing strategies. With a focus on adaptability, the script allows traders to monitor and adjust portfolio weights, equity, and other key financial metrics dynamically. This script provides a versatile approach for evaluating different trading strategies, considering factors like risk-adjusted returns, volatility, and the impact of portfolio rebalancing.
Please take the time to read the following:
Key Features and Benefits of Portfolio Methods
Bracketed Rebalancing:
Bracketed Rebalancing is an advanced strategy designed to trigger portfolio adjustments when an asset's weight surpasses a predefined threshold. This approach minimizes overexposure to any single asset while maintaining flexibility in response to market changes. The strategy is particularly beneficial for mitigating risks that arise from significant asset weight fluctuations. The following image illustrates how this method reacts when asset weights cross the threshold:
Daily Rebalancing:
Unlike the bracketed method, Daily Rebalancing adjusts portfolio weights every trading day, ensuring consistent asset allocation. This method aims for a more even distribution of portfolio weights, making it a suitable option for traders who prefer less sensitivity to individual asset volatility. Here's an example of Daily Rebalancing in action:
No Rebalancing:
For traders who prefer a passive approach, the "No Rebalancing" option allows the portfolio to remain static, without any adjustments to asset weights. This method may appeal to long-term investors or those who believe in the inherent stability of their selected assets. Here’s how the portfolio looks when no rebalancing is applied:
Portfolio Weights Visualization:
One of the standout features of this script is the visual representation of portfolio weights. With adjustable settings, users can track the current allocation of assets in real-time, making it easier to analyze shifts and trends. The following image shows the real-time weight distribution across three assets:
Rolling Drawdown Plot:
Managing drawdown risk is a critical aspect of portfolio management. The Rolling Drawdown Plot visually tracks the drawdown over time, helping traders monitor the risk exposure and performance relative to the peak equity levels. This feature is essential for assessing the portfolio's resilience during market downturns:
Daily Portfolio Returns:
Tracking daily returns is crucial for evaluating the short-term performance of the portfolio. The script allows users to plot daily portfolio returns to gain insights into daily profit or loss, helping traders stay updated on their portfolio’s progress:
Performance Metrics
Net Profit (%):
This metric represents the total return on investment as a percentage of the initial capital. A positive net profit indicates that the portfolio has gained value over the evaluation period, while a negative value suggests a loss. It's a fundamental indicator of overall portfolio performance.
Maximum Drawdown (Max DD):
Maximum Drawdown measures the largest peak-to-trough decline in portfolio value during a specified period. It quantifies the most significant loss an investor would have experienced if they had invested at the highest point and sold at the lowest point within the timeframe. A smaller Max DD indicates better risk management and less exposure to significant losses.
Annual Mean Returns (% p/y):
This metric calculates the average annual return of the portfolio over the evaluation period. It provides insight into the portfolio's ability to generate returns on an annual basis, aiding in performance comparison with other investment opportunities.
Annual Standard Deviation of Returns (% p/y):
This measure indicates the volatility of the portfolio's returns on an annual basis. A higher standard deviation signifies greater variability in returns, implying higher risk, while a lower value suggests more stable returns.
Variance:
Variance is the square of the standard deviation and provides a measure of the dispersion of returns. It helps in understanding the degree of risk associated with the portfolio's returns.
Sortino Ratio:
The Sortino Ratio is a variation of the Sharpe Ratio that only considers downside risk, focusing on negative volatility. It is calculated as the difference between the portfolio's return and the minimum acceptable return (MAR), divided by the downside deviation. A higher Sortino Ratio indicates better risk-adjusted performance, emphasizing the importance of avoiding negative returns.
Sharpe Ratio:
The Sharpe Ratio measures the portfolio's excess return per unit of total risk, as represented by standard deviation. It is calculated by subtracting the risk-free rate from the portfolio's return and dividing by the standard deviation of the portfolio's excess return. A higher Sharpe Ratio indicates more favorable risk-adjusted returns.
Omega Ratio:
The Omega Ratio evaluates the probability of achieving returns above a certain threshold relative to the probability of experiencing returns below that threshold. It is calculated by dividing the cumulative probability of positive returns by the cumulative probability of negative returns. An Omega Ratio greater than 1 indicates a higher likelihood of achieving favorable returns.
Gain-to-Pain Ratio:
The Gain-to-Pain Ratio measures the return per unit of risk, focusing on the magnitude of gains relative to the severity of losses. It is calculated by dividing the total gains by the total losses experienced during the evaluation period. A higher ratio suggests a more favorable balance between reward and risk.
www.linkedin.com
Compound Annual Growth Rate (CAGR) (% p/y):
CAGR represents the mean annual growth rate of the portfolio over a specified period, assuming the investment has been compounding over that time. It provides a smoothed annual rate of growth, eliminating the effects of volatility and offering a clearer picture of long-term performance.
Portfolio Alpha (% p/y):
Portfolio Alpha measures the portfolio's performance relative to a benchmark index, adjusting for risk. It is calculated using the Capital Asset Pricing Model (CAPM) and represents the excess return of the portfolio over the expected return based on its beta and the benchmark's performance. A positive alpha indicates outperformance, while a negative alpha suggests underperformance.
Portfolio Beta:
Portfolio Beta assesses the portfolio's sensitivity to market movements, indicating its exposure to systematic risk. A beta greater than 1 suggests the portfolio is more volatile than the market, while a beta less than 1 indicates lower volatility. Beta is used to understand the portfolio's potential for gains or losses in relation to market fluctuations.
Skewness of Returns:
Skewness measures the asymmetry of the return distribution. A positive skew indicates a distribution with a long right tail, suggesting more frequent small losses and fewer large gains. A negative skew indicates a long left tail, implying more frequent small gains and fewer large losses. Understanding skewness helps in assessing the likelihood of extreme outcomes.
Value at Risk (VaR) 95th Percentile:
VaR at the 95th percentile estimates the maximum potential loss over a specified period, given a 95% confidence level. It provides a threshold value such that there is a 95% probability that the portfolio will not experience a loss greater than this amount.
Conditional Value at Risk (CVaR):
CVaR, also known as Expected Shortfall, measures the average loss exceeding the VaR threshold. It provides insight into the tail risk of the portfolio, indicating the expected loss in the worst-case scenarios beyond the VaR level.
These metrics collectively offer a comprehensive view of the portfolio's performance, risk exposure, and efficiency. By analyzing these indicators, investors can make informed decisions, balancing potential returns with acceptable levels of risk.
Conclusion
The Performance Metrics With Bracketed Rebalancing script provides a comprehensive framework for evaluating and optimizing portfolio performance. By integrating advanced metrics, adaptive rebalancing strategies, and visual analytics, it empowers traders to make informed decisions in managing their investment portfolios. However, it's crucial to consider the implications of rebalancing strategies, as academic research indicates that predictable rebalancing can lead to market impact costs. Therefore, adopting flexible and less predictable rebalancing approaches may enhance portfolio performance and reduce associated costs.
Enhanced Zones with Volume StrengthEnhanced Zones with Volume Strength
Your reliable visual guide to market zones — now with Multi-Timeframe (MTF) power!
What you get:
Clear visual zones on your chart — color-coded boxes that highlight important price areas.
Blue Boxes for neutral zones — easy to spot areas of indecision or balance.
Gray Boxes to show normal volume conditions, giving you context without clutter.
Green Boxes highlighting bullish zones where strength is showing.
Red Boxes marking bearish zones where weakness might be in play.
Multi-Timeframe Support:
Seamlessly visualize these zones from higher timeframes directly on your current chart for a bigger-picture view, helping you make smarter trading decisions.
How to use it:
Adjust the box width (in bars) to fit your trading style and timeframe.
Customize colors and opacity to suit your chart theme.
Toggle neutral blue and gray volume boxes on/off to focus on what matters most to you.
Set the maximum number of boxes to keep your chart clean and performant.
Why you’ll love it:
This indicator cuts through the noise by visually marking zones where volume and price action matter the most — without overwhelming your chart. The MTF feature means you’re always aligned with higher timeframe trends without switching views.
Pro tip:
Use these boxes as dynamic support/resistance areas or to confirm trade setups alongside your favorite indicators.
No complicated formulas here, just crisp, actionable visuals designed for clarity and confidence.
TCT - Envelope MatrixTCT - Envelope Matrix
A powerful multi-envelope indicator that creates a comprehensive price channel system with 4 customizable envelopes and multiple intermediate levels for precise price action analysis.
Key Features:
• 4 customizable envelopes with adjustable percentages (0.2%, 0.4%, 0.6%, 0.8% by default)
• Optional EMA or SMA basis calculation
• Color-coded bands for easy visual identification
• Automatic horizontal lines showing current band values
• Midpoint lines between adjacent bands
• Additional 25%, 50%, and 75% levels between each band pair
The indicator provides:
- Clear visual representation of price channels
- Multiple support and resistance levels
- Dynamic price boundaries that adapt to market conditions
- Enhanced precision with intermediate levels between bands
Perfect for:
• Identifying potential support and resistance zones
• Spotting overbought/oversold conditions
• Finding potential reversal points
• Analyzing price volatility and channel width
• Making informed trading decisions based on price position relative to multiple bands
Customization Options:
• Adjustable length for the basis calculation
• Choice between EMA and SMA
• Customizable colors for each envelope
• Flexible percentage settings for each band
• Optional basis line color adjustment
This indicator is particularly useful for traders who want to analyze price action within multiple dynamic channels and identify potential trading opportunities based on price interactions with various support and resistance levels.
Daily Price RangeThe indicator is designed to analyze an instrument’s volatility based on daily extremes (High-Low) and to compare the current day’s range with the typical (median) range over a selected period. This helps traders assess how much of the "usual" daily movement has already occurred and how much may still be possible during the trading day.
Volume-Price Momentum IndicatorVolume-Price Momentum Indicator (VPMI)
Overview
The Volume-Price Momentum Indicator (VPMI), developed by Kevin Svenson , is a powerful technical analysis tool designed to identify strong bullish and bearish momentum in price movements, driven by volume dynamics. By analyzing price changes and volume surges over a user-defined lookback period, VPMI highlights potential trend shifts and continuation patterns through a smoothed histogram, optional labels, and background highlights. Ideal for traders seeking to capture momentum-driven opportunities, VPMI is suitable for various markets, including stocks, forex, and cryptocurrencies.
How It Works
VPMI calculates the difference between volume-weighted buying and selling pressure based on price changes over a specified lookback period. It amplifies signals during high-volume periods, applies smoothing to reduce noise, and uses momentum checks to detect sustained trends.
Indicator display:
A histogram that oscillates above (bullish) or below (bearish) a zero line, with brighter colors indicating stronger momentum and faded colors for weaker signals.
Optional labels ("Bullish" or "Bearish") to mark significant momentum shifts.
Optional background highlights to visually emphasize strong trend conditions.
Alerts to notify users when strong bullish or bearish momentum is detected.
Key Features
Customizable Settings:
Adjust the lookback period, volume threshold, momentum length, and smoothing to suit your trading style.
Volume Sensitivity:
Emphasizes price movements during high-volume surges, enhancing signal reliability.
Momentum Detection: Uses linear regression and momentum change to confirm sustained trends, reducing false signals.
Visual Clarity:
Offers a clear histogram with color-coded signals, plus optional labels and backgrounds for enhanced chart readability.
Alerts:
Configurable alerts for strong momentum signals, enabling timely trade decisions.
Inputs and Customization
Lookback Period (Default: 9):
Sets the number of bars to analyze price changes. Higher values smooth signals but may lag.
Volume Threshold (Default: 1.4):
Defines the volume level (relative to a 20-period SMA) that qualifies as a surge, amplifying signals.
High Volume Multiplier (Default: 1.5):
Boosts histogram values during high-volume periods for stronger signals.
Histogram Smoothing Length (Default: 4):
Controls the EMA smoothing applied to the histogram, reducing noise.
Momentum Check Length (Default: 4):
Sets the period for momentum trend analysis (recommended to be less than Lookback Period).
Momentum Threshold (Default: 6):
Defines the minimum momentum change required for strong signals.
Show Labels (Default: Off):
Toggle to display "Bullish" or "Bearish" labels on significant momentum shifts.
Show Backgrounds (Default: Off):
Toggle to highlight chart backgrounds during strong momentum periods.
Bullish/Bearish Colors:
Customize colors for bullish (default: green) and bearish (default: red) signals.
Faded Transparency (Default: 40):
Adjusts the transparency of weaker signals for visual distinction.
How to Use
Interpret Signals:
Above Zero (Green):
Indicates bullish momentum. Bright green suggests strong, sustained buying pressure.
Below Zero (Red):
Indicates bearish momentum. Bright red suggests strong, sustained selling pressure.
Faded Colors:
Weaker momentum, potentially signaling consolidation or trend exhaustion.
Enable Visuals:
Turn on "Show Labels" and "Show Backgrounds" in the settings for additional context on strong momentum signals.
Set Alerts:
Use the built-in alert conditions ("Strong Bullish Momentum" or "Strong Bearish Momentum") to receive notifications when significant trends emerge.
Combine with Other Tools:
Pair VPMI with support/resistance levels, trendlines, or other indicators (e.g., RSI, MACD) for confirmation.
Best Practices
Timeframe:
VPMI works on all timeframes, but shorter timeframes (e.g., 5m, 15m) may produce more signals, while longer timeframes (e.g., 1h, 4h, 1D) offer higher reliability.
Market Conditions:
Most effective in trending markets. In choppy or sideways markets, consider increasing the smoothing length or momentum threshold to filter noise.
Risk Management:
Always use VPMI signals in conjunction with a robust trading plan, including stop-losses and position sizing.
Limitations
Lagging Nature:
As a momentum indicator, VPMI may lag in fast-moving markets due to smoothing and lookback calculations.
False Signals:
In low-volume or ranging markets, signals may be less reliable. Adjust the volume threshold or momentum settings to improve accuracy.
Customization Required:
Optimal settings vary by asset and timeframe. Experiment with inputs to align with your trading strategy.
Why Use VPMI?
VPMI offers a unique blend of volume and price momentum analysis, making it a versatile tool for traders seeking to identify high-probability trend opportunities. Its customizable inputs, clear visuals, and alert capabilities empower users to tailor the indicator to their needs, whether for day trading, swing trading, or long-term analysis.
Get Started
Apply VPMI to your chart, tweak the settings to match your trading style, and start exploring momentum-driven opportunities. For questions or feedback, consult TradingView’s community forums or documentation. Happy trading!
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.
Multi-Timeframe Price LevelsThis indicator displays key price levels from multiple timeframes on your chart, helping you identify important support and resistance zones.
## Features
- **Multiple Timeframes**: View price levels from 4H, Daily, 3-Day, Weekly, and Monthly charts simultaneously
- **Customizable Price Types**: Choose to display Open, Close, High, and Low prices
- **Color-Coded**: Each timeframe has its own color for easy identification
- **Fully Customizable**: Enable/disable specific timeframes and price types as needed
## How to Use
1. Add the indicator to your chart
2. Use the input options to select which timeframes and price types you want to display
3. Look for areas where multiple price levels converge - these often act as strong support/resistance zones
## Color Guide
- **Red**: 4-Hour timeframe
- **Blue**: Daily timeframe
- **Green**: 3-Day timeframe
- **Purple**: Weekly timeframe
- **Orange**: Monthly timeframe
For each timeframe, the transparency varies by price type:
- Open: 70% transparency
- Close: 50% transparency
- High: 30% transparency
- Low: 10% transparency (most visible)
## Trading Applications
- Identify key support and resistance levels
- Spot multi-timeframe confluences for stronger trade setups
- Plan entries and exits based on historical price reactions
- Set stop losses and take profit targets at significant levels
This indicator works best when combined with your existing trading strategy to confirm important price zones.
Grid Level Visualizer v1.0Overview
This indicator draws a customizable grid of horizontal price levels directly on your chart. It's designed to help traders visualize potential support and resistance zones, manage grid trading strategies, or simply divide a price range into equal segments. The script offers interactive controls, extensive customization options, and alert functionality.
Key Features:
Customizable Grid: Draws a grid based on user-defined Upper Price Bound and Lower Price Bound.
Interactive Bounds: Easily adjust the Upper and Lower bounds by dragging the corresponding lines directly on the chart (click the line first to select, then drag). Bounds can also be set numerically in the settings.
Adjustable Levels: Specify the total number of horizontal lines in the grid (Number of Grid Levels), including bounds.
Custom Styling: Independently configure the color, width, and style (Solid, Dashed, Dotted) for the boundary lines and the intermediate grid lines.
Price Labels: Optional display of price values for each grid level, positioned on the right side near the current bar.
Labels for boundary levels automatically inherit the boundary line colors.
Adjustable horizontal offset (Price Label Offset (X)) for labels.
Customizable text size (Text Size) and color (Price Text Color (Mid)) for mid-levels.
Grid Start Time: Define a specific date and time (Grid Start Time) from which the grid lines should start appearing on the chart (defaults to the beginning of the current month).
Line Extension: Grid lines automatically extend to the right margin of the chart.
Alert Condition: Provides a "Grid Level Cross" condition for creating custom alerts when price crosses any active grid level.
Alert Toggle: An option (Enable Alert Condition?) in the settings to enable or disable the availability of the "Grid Level Cross" condition when creating alerts.
Real-time Calculation: Uses calc_on_every_tick=true for responsive alert checking against the current price.
How to Use:
Add the "Improved Grid Level Visualizer" indicator to your chart.
Set Bounds: Adjust the Upper Price Bound and Lower Price Bound lines by clicking and dragging them on the chart, or set precise values in the indicator settings.
Set Levels: Define the Number of Grid Levels you need in the settings.
Set Start Time: Use the Grid Start Time input to control when the grid visualization begins.
Customize: Configure colors, line styles, label visibility, etc., in the settings panel.
Set Alerts (Optional): Follow the steps below.
Notes:
The grid levels are calculated purely based on the mathematical division of the specified price range. They do not automatically adapt to market structure unless you manually adjust the bounds.
When changing the Grid Start Time after the indicator has been running, you might need to refresh the chart or remove/re-add the indicator for the visual starting point to update correctly.
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.
Price Levels by Market Cap (Manual)This indicator will forecast the price by marketcap. The crypto's current circulating supply should be inputted manually.
Major Support and Resistance Price LevelsThis indicator is to be used to automatically plot Major Support and Resistance Price Levels. This is not a TREND support/resistance identifier. This is strictly for auto-plotting historically important price levels.
I would suggest adjusting the support/resistance filter before adjusting the sensistivity levels as I've testing out the setting quite a bit, but as always, do what works best for your chart.
If there is an input that you would like to have me add, let me know and I'll see what I can do.
Things to Consider:
Currently this works best on the 4H through 3D chart for Identifying major price levels; however lower timeframes do still work. Because of the large swings that can be typical when coming from Afterhours trading into Market hours, timeframes under 2H can create some false positives. This is obviously not as much of an issue on crypto or forex.
I will be working on allowing lower or higher timeframes with this indicator in order to circumvent the need to jump back to other timeframes and reference them if they are under that 2h threshold.
Future Updates:
Plotting different timeframe's results on a lower or higher timeframe.